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
c0cc2e346e8e827b437dcb7ce350cf4a9f7ac97d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/auto_quote1.lean
572e48127407234d30f396ec12683fed5a5679b7
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
2,072
lean
example (a b c : nat) : a = b → b = c → c = a := by { intros, apply eq.symm, apply eq.trans, assumption, assumption } example (a b c : nat) : a = b → b = c → c = a := by intros; apply eq.symm; apply eq.trans; repeat {assumption} example (p q r : Prop) : p → q → r → p ∧ q ∧ r ∧ p ∧ q := by intros; repeat {assumption <|> constructor} example (a b c : nat) : a = b → b = c → c = a := begin intros h1 h2, -- we can optionally provide the names refine eq.symm (eq.trans h1 _), exact h2 end example (a b c : nat) : a = b → b = c → c = a := begin intro h1, intro, -- optional argument refine eq.symm (eq.trans h1 _), assumption end constant addc {a b : nat} : a + b = b + a constant addassoc {a b c : nat} : (a + b) + c = a + (b + c) constant zadd (a : nat) : 0 + a = a example (a b c : nat) : b = 0 → 0 + a + b + c = c + a := begin intro h, rewrite h, -- single rewrite rewrite [zadd, @addc a 0, zadd, addc] -- sequence of rewrites end example (a b c : nat) : 0 = b → 0 + a + b + c = c + a := begin intro h, rewrite [<- h], -- single rewrite using symmetry rw [zadd, @addc a 0, zadd, addc] -- rw is shorthand for rewrite end open nat example : ∀ n m : ℕ, n + m = m + n := begin intros n m, induction m with m' ih, { -- Remark: Used change here to make sure nat.zero is replaced with polymorphic zero. -- dsimp tactic should fix that in the future. change n + 0 = 0 + n, simp [zadd, nat.add_zero] }, { change succ (n + m') = succ m' + n, rw [succ_add, ih] } end example (a b c : nat) : 0 = b → 0 + a + b + c = c + a := by do tactic.intro `h, `[rewrite ←h, rw zadd, rw @addc a 0, rw zadd, rw addc] example : ∀ n m : ℕ, n + m = m + n := begin intros n m, induction m with m' ih, show n + 0 = 0 + n, begin change n + 0 = 0 + n, simp [zadd, nat.add_zero] end, show n + succ m' = succ m' + n, { change succ (n + m') = succ m' + n, calc succ (n + m') = succ (m' + n) : by rw ih ... = succ m' + n : by rw succ_add } end
92e8f0b8fbd911588b88806996765b9515c5750a
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/e16.lean
84a112a8155449e17e31fc8d0661066caefe415f
[ "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
543
lean
prelude inductive nat : Type | zero : nat | succ : nat → nat namespace nat end nat open nat inductive list (A : Type*) : Type* | nil {} : list | cons : A → list → list namespace list end list open list check nil check nil.{1} check @nil.{1} nat check @nil nat check cons zero nil inductive vector (A : Type*) : nat → Type* | vnil {} : vector zero | vcons : forall {n : nat}, A → vector n → vector (succ n) namespace vector end vector open vector check vcons zero vnil constant n : nat check vcons n vnil check vector.rec
03830f62b11fe5a5f89caad692c3131ec7bf751f
9cba98daa30c0804090f963f9024147a50292fa0
/old/metrology/spaces.lean
4fbfd19a7520c1b84d8f3c9c4b665f11f78f5a23
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
2,780
lean
/- The dimensions.lean file implements the concept of physical dimensions as we've understood it from, e.g., the SI system of dimensions and units. Our insight is that that approach leaves too much structure behind. What we do here, instead, it implement the concept of physical spaces. So, for example, the vector space concept of (directed) lengths is replaced by the affine space concept of a torsor of geometric points over a vector space of displacements. We will then define an algebra of *spaces* rather than an algebra of dimensions, and that, I think, it really what we need in order to implement a richly library of abstractions for doing strongly and statically typed physics. --Sullivan Oct 20/2020 We need to distinguish between physical (e.g., geomtric) spaces and labellings (coordinatizations) of points and vectors in these spaces. The reason we need to be careful is each labelling (defined by a frame) gives us a new affine coordinate space, albeit one that is isomorphic to any other such labelling. Geometric space itself has an affine space structure, and so does each labelling of this space. And we're going have to be careful here. If we have two labellings of the same physical space, then we have to undestand that.#check A coordinate-free abstraction erases all coordinatizations, and just exposes abstractions of the underying points and vectors. The DeRose library only considered coordinates when (1) instantiating a point in relation to some affine frame, (2) asking for the coordinates of a point with respect to a frame, and (3) in the hidden implementatoin when applying affine transformations to map hidden coordinations between different frames. X, Y, and Z are real affine 1-spaces X * Y * Z --- direct product of 3 one-spaces N x R^2+ -> R+ -/ inductive space : Type | geometry -- real affine 1 | time -- real affine 1 | mass -- real quasi-affine monus 1 (negative mass speculative) | temperature -- real quasi-affine monus 1 (negative mass speculative) | quantity -- nat monus 1 -- intensity -- -- current def algebraOf : space → _ -- return algebraic structure for space -- expect geometryOf geometry = affine 1 space /- Operations on these spaces -/ -- product of 1-d geometric spaces def geometry2 := directProd space.geometry space.geometry -- 2d geometry -- expect algebraOf geometry2 = 2-d affine space -- algebraOf geometry/time := affine1d X affine1d /- Operations on spaces to produce new derived spaces where the underlying albraic structures are correctly computed -/ /- Once we've got the most basic spaces down, all other spaces should be derived by applying appropriate operators to the individual spaces, for example, direct product. -/
f445390d6347f0ba552273c059f76f4ba7acb050
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/whenIO.lean
008f01b00ac5f1bff5776f49213b2112f28c24aa
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
179
lean
import system.io open io def iowhen (b : bool) (a : io unit) : io unit := if b = tt then a else return () #eval iowhen tt (put_str "hello\n") #eval iowhen ff (put_str "error\n")
8bc8891db6c1928e85b1171a04effc8b651e7929
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/probability_theory/independence.lean
1c265637afd3eea86c6bbe74b666d5c1ee7642cb
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,253
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.measure_space import measure_theory.pi_system import algebra.big_operators.intervals import data.finset.intervals /-! # Independence of sets of sets and measure spaces (σ-algebras) * A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of π-systems. * A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they define is independent. I.e., `m : ι → measurable_space α` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i)`. * Independence of sets (or events in probabilistic parlance) is defined as independence of the measurable space structures they generate: a set `s` generates the measurable space structure with measurable sets `∅, s, sᶜ, univ`. * Independence of functions (or random variables) is also defined as independence of the measurable space structures they generate: a function `f` for which we have a measurable space `m` on the codomain generates `measurable_space.comap f m`. ## Main statements * TODO: `Indep_of_Indep_sets`: if π-systems are independent as sets of sets, then the measurable space structures they generate are independent. * `indep_of_indep_sets`: variant with two π-systems. ## Implementation notes We provide one main definition of independence: * `Indep_sets`: independence of a family of sets of sets `pi : ι → set (set α)`. Three other independence notions are defined using `Indep_sets`: * `Indep`: independence of a family of measurable space structures `m : ι → measurable_space α`, * `Indep_set`: independence of a family of sets `s : ι → set α`, * `Indep_fun`: independence of a family of functions. For measurable spaces `m : Π (i : ι), measurable_space (β i)`, we consider functions `f : Π (i : ι), α → β i`. Additionally, we provide four corresponding statements for two measurable space structures (resp. sets of sets, sets, functions) instead of a family. These properties are denoted by the same names as for a family, but without a capital letter, for example `indep_fun` is the version of `Indep_fun` for two functions. The definition of independence for `Indep_sets` uses finite sets (`finset`). An alternative and equivalent way of defining independence would have been to use countable sets. TODO: prove that equivalence. Most of the definitions and lemma in this file list all variables instead of using the `variables` keyword at the beginning of a section, for example `lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α} ...` . This is intentional, to be able to control the order of the `measurable_space` variables. Indeed when defining `μ` in the example above, the measurable space used is the last one defined, here `[measurable_space α]`, and not `m₁` or `m₂`. ## References * Williams, David. Probability with martingales. Cambridge university press, 1991. Part A, Chapter 4. -/ open measure_theory measurable_space open_locale big_operators classical namespace probability_theory section definitions /-- A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of pi_systems. -/ def Indep_sets {α ι} [measurable_space α] (π : ι → set (set α)) (μ : measure α . volume_tac) : Prop := ∀ (s : finset ι) {f : ι → set α} (H : ∀ i, i ∈ s → f i ∈ π i), μ (⋂ i ∈ s, f i) = ∏ i in s, μ (f i) /-- Two sets of sets `s₁, s₂` are independent with respect to a measure `μ` if for any sets `t₁ ∈ p₁, t₂ ∈ s₂`, then `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/ def indep_sets {α} [measurable_space α] (s1 s2 : set (set α)) (μ : measure α . volume_tac) : Prop := ∀ t1 t2 : set α, t1 ∈ s1 → t2 ∈ s2 → μ (t1 ∩ t2) = μ t1 * μ t2 /-- A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they define is independent. `m : ι → measurable_space α` is independent with respect to measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. -/ def Indep {α ι} (m : ι → measurable_space α) [measurable_space α] (μ : measure α . volume_tac) : Prop := Indep_sets (λ x, (m x).measurable_set') μ /-- Two measurable space structures (or σ-algebras) `m₁, m₂` are independent with respect to a measure `μ` (defined on a third σ-algebra) if for any sets `t₁ ∈ m₁, t₂ ∈ m₂`, `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/ def indep {α} (m₁ m₂ : measurable_space α) [measurable_space α] (μ : measure α . volume_tac) : Prop := indep_sets (m₁.measurable_set') (m₂.measurable_set') μ /-- A family of sets is independent if the family of measurable space structures they generate is independent. For a set `s`, the generated measurable space has measurable sets `∅, s, sᶜ, univ`. -/ def Indep_set {α ι} [measurable_space α] (s : ι → set α) (μ : measure α . volume_tac) : Prop := Indep (λ i, generate_from {s i}) μ /-- Two sets are independent if the two measurable space structures they generate are independent. For a set `s`, the generated measurable space structure has measurable sets `∅, s, sᶜ, univ`. -/ def indep_set {α} [measurable_space α] (s t : set α) (μ : measure α . volume_tac) : Prop := indep (generate_from {s}) (generate_from {t}) μ /-- A family of functions defined on the same space `α` and taking values in possibly different spaces, each with a measurable space structure, is independent if the family of measurable space structures they generate on `α` is independent. For a function `g` with codomain having measurable space structure `m`, the generated measurable space structure is `measurable_space.comap g m`. -/ def Indep_fun {α ι} [measurable_space α] {β : ι → Type*} (m : Π (x : ι), measurable_space (β x)) (f : Π (x : ι), α → β x) (μ : measure α . volume_tac) : Prop := Indep (λ x, measurable_space.comap (f x) (m x)) μ /-- Two functions are independent if the two measurable space structures they generate are independent. For a function `f` with codomain having measurable space structure `m`, the generated measurable space structure is `measurable_space.comap f m`. -/ def indep_fun {α β γ} [measurable_space α] [mβ : measurable_space β] [mγ : measurable_space γ] (f : α → β) (g : α → γ) (μ : measure α . volume_tac) : Prop := indep (measurable_space.comap f mβ) (measurable_space.comap g mγ) μ end definitions section indep lemma indep_sets.symm {α} {s₁ s₂ : set (set α)} [measurable_space α] {μ : measure α} (h : indep_sets s₁ s₂ μ) : indep_sets s₂ s₁ μ := by { intros t1 t2 ht1 ht2, rw [set.inter_comm, mul_comm], exact h t2 t1 ht2 ht1, } lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α} (h : indep m₁ m₂ μ) : indep m₂ m₁ μ := indep_sets.symm h lemma indep_sets_of_indep_sets_of_le_left {α} {s₁ s₂ s₃: set (set α)} [measurable_space α] {μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h31 : s₃ ⊆ s₁) : indep_sets s₃ s₂ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (set.mem_of_subset_of_mem h31 ht1) ht2 lemma indep_sets_of_indep_sets_of_le_right {α} {s₁ s₂ s₃: set (set α)} [measurable_space α] {μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h32 : s₃ ⊆ s₂) : indep_sets s₁ s₃ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (set.mem_of_subset_of_mem h32 ht2) lemma indep_of_indep_of_le_left {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α] {μ : measure α} (h_indep : indep m₁ m₂ μ) (h31 : m₃ ≤ m₁) : indep m₃ m₂ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (h31 _ ht1) ht2 lemma indep_of_indep_of_le_right {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α] {μ : measure α} (h_indep : indep m₁ m₂ μ) (h32 : m₃ ≤ m₂) : indep m₁ m₃ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (h32 _ ht2) lemma indep_sets.union {α} [measurable_space α] {s₁ s₂ s' : set (set α)} {μ : measure α} (h₁ : indep_sets s₁ s' μ) (h₂ : indep_sets s₂ s' μ) : indep_sets (s₁ ∪ s₂) s' μ := begin intros t1 t2 ht1 ht2, cases (set.mem_union _ _ _).mp ht1 with ht1₁ ht1₂, { exact h₁ t1 t2 ht1₁ ht2, }, { exact h₂ t1 t2 ht1₂ ht2, }, end @[simp] lemma indep_sets.union_iff {α} [measurable_space α] {s₁ s₂ s' : set (set α)} {μ : measure α} : indep_sets (s₁ ∪ s₂) s' μ ↔ indep_sets s₁ s' μ ∧ indep_sets s₂ s' μ := ⟨λ h, ⟨indep_sets_of_indep_sets_of_le_left h (set.subset_union_left s₁ s₂), indep_sets_of_indep_sets_of_le_left h (set.subset_union_right s₁ s₂)⟩, λ h, indep_sets.union h.left h.right⟩ lemma indep_sets.Union {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)} {μ : measure α} (hyp : ∀ n, indep_sets (s n) s' μ) : indep_sets (⋃ n, s n) s' μ := begin intros t1 t2 ht1 ht2, rw set.mem_Union at ht1, cases ht1 with n ht1, exact hyp n t1 t2 ht1 ht2, end lemma indep_sets.inter {α} [measurable_space α] {s₁ s' : set (set α)} (s₂ : set (set α)) {μ : measure α} (h₁ : indep_sets s₁ s' μ) : indep_sets (s₁ ∩ s₂) s' μ := λ t1 t2 ht1 ht2, h₁ t1 t2 ((set.mem_inter_iff _ _ _).mp ht1).left ht2 lemma indep_sets.Inter {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)} {μ : measure α} (h : ∃ n, indep_sets (s n) s' μ) : indep_sets (⋂ n, s n) s' μ := by {intros t1 t2 ht1 ht2, cases h with n h, exact h t1 t2 (set.mem_Inter.mp ht1 n) ht2 } lemma indep_sets_singleton_iff {α} [measurable_space α] {s t : set α} {μ : measure α} : indep_sets {s} {t} μ ↔ μ (s ∩ t) = μ s * μ t := ⟨λ h, h s t rfl rfl, λ h s1 t1 hs1 ht1, by rwa [set.mem_singleton_iff.mp hs1, set.mem_singleton_iff.mp ht1]⟩ end indep /-! ### Deducing `indep` from `Indep` -/ section from_Indep_to_indep lemma Indep_sets.indep_sets {α ι} {s : ι → set (set α)} [measurable_space α] {μ : measure α} (h_indep : Indep_sets s μ) {i j : ι} (hij : i ≠ j) : indep_sets (s i) (s j) μ := begin intros t₁ t₂ ht₁ ht₂, have hf_m : ∀ (x : ι), x ∈ {i, j} → (ite (x=i) t₁ t₂) ∈ s x, { intros x hx, cases finset.mem_insert.mp hx with hx hx, { simp [hx, ht₁], }, { simp [finset.mem_singleton.mp hx, hij.symm, ht₂], }, }, have h1 : t₁ = ite (i = i) t₁ t₂, by simp only [if_true, eq_self_iff_true], have h2 : t₂ = ite (j = i) t₁ t₂, by simp only [hij.symm, if_false], have h_inter : (⋂ (t : ι) (H : t ∈ ({i, j} : finset ι)), ite (t = i) t₁ t₂) = (ite (i = i) t₁ t₂) ∩ (ite (j = i) t₁ t₂), by simp only [finset.set_bInter_singleton, finset.set_bInter_insert], have h_prod : (∏ (t : ι) in ({i, j} : finset ι), μ (ite (t = i) t₁ t₂)) = μ (ite (i = i) t₁ t₂) * μ (ite (j = i) t₁ t₂), by simp only [hij, finset.prod_singleton, finset.prod_insert, not_false_iff, finset.mem_singleton], rw h1, nth_rewrite 1 h2, nth_rewrite 3 h2, rw [←h_inter, ←h_prod, h_indep {i, j} hf_m], end lemma Indep.indep {α ι} {m : ι → measurable_space α} [measurable_space α] {μ : measure α} (h_indep : Indep m μ) {i j : ι} (hij : i ≠ j) : indep (m i) (m j) μ := begin change indep_sets ((λ x, (m x).measurable_set') i) ((λ x, (m x).measurable_set') j) μ, exact Indep_sets.indep_sets h_indep hij, end end from_Indep_to_indep /-! ## π-system lemma Independence of measurable spaces is equivalent to independence of generating π-systems. -/ section from_measurable_spaces_to_sets_of_sets /-! ### Independence of measurable space structures implies independence of generating π-systems -/ lemma Indep.Indep_sets {α ι} [measurable_space α] {μ : measure α} {m : ι → measurable_space α} {s : ι → set (set α)} (hms : ∀ n, m n = measurable_space.generate_from (s n)) (h_indep : Indep m μ) : Indep_sets s μ := begin refine (λ S f hfs, h_indep S (λ x hxS, _)), simp_rw hms x, exact measurable_set_generate_from (hfs x hxS), end lemma indep.indep_sets {α} [measurable_space α] {μ : measure α} {s1 s2 : set (set α)} (h_indep : indep (generate_from s1) (generate_from s2) μ) : indep_sets s1 s2 μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (measurable_set_generate_from ht1) (measurable_set_generate_from ht2) end from_measurable_spaces_to_sets_of_sets section from_pi_systems_to_measurable_spaces /-! ### Independence of generating π-systems implies independence of measurable space structures -/ private lemma indep_sets.indep_aux {α} {m2 : measurable_space α} {m : measurable_space α} {μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)} (h2 : m2 ≤ m) (hp2 : is_pi_system p2) (hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) {t1 t2 : set α} (ht1 : t1 ∈ p1) (ht2m : m2.measurable_set' t2) : μ (t1 ∩ t2) = μ t1 * μ t2 := begin let μ_inter := μ.restrict t1, let ν := (μ t1) • μ, have h_univ : μ_inter set.univ = ν set.univ, by rw [measure.restrict_apply_univ, measure.smul_apply, measure_univ, mul_one], haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t1 μ ⟨measure_lt_top μ t1⟩, rw [set.inter_comm, ←@measure.restrict_apply α _ μ t1 t2 (h2 t2 ht2m)], refine ext_on_measurable_space_of_generate_finite m p2 (λ t ht, _) h2 hpm2 hp2 h_univ ht2m, have ht2 : m.measurable_set' t, { refine h2 _ _, rw hpm2, exact measurable_set_generate_from ht, }, rw [measure.restrict_apply ht2, measure.smul_apply, set.inter_comm], exact hyp t1 t ht1 ht, end lemma indep_sets.indep {α} {m1 m2 : measurable_space α} {m : measurable_space α} {μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)} (h1 : m1 ≤ m) (h2 : m2 ≤ m) (hp1 : is_pi_system p1) (hp2 : is_pi_system p2) (hpm1 : m1 = generate_from p1) (hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) : indep m1 m2 μ := begin intros t1 t2 ht1 ht2, let μ_inter := μ.restrict t2, let ν := (μ t2) • μ, have h_univ : μ_inter set.univ = ν set.univ, by rw [measure.restrict_apply_univ, measure.smul_apply, measure_univ, mul_one], haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t2 μ ⟨measure_lt_top μ t2⟩, rw [mul_comm, ←@measure.restrict_apply α _ μ t2 t1 (h1 t1 ht1)], refine ext_on_measurable_space_of_generate_finite m p1 (λ t ht, _) h1 hpm1 hp1 h_univ ht1, have ht1 : m.measurable_set' t, { refine h1 _ _, rw hpm1, exact measurable_set_generate_from ht, }, rw [measure.restrict_apply ht1, measure.smul_apply, mul_comm], exact indep_sets.indep_aux h2 hp2 hpm2 hyp ht ht2, end end from_pi_systems_to_measurable_spaces section indep_set /-! ### Independence of measurable sets We prove the following equivalences on `indep_set`, for measurable sets `s, t`. * `indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t`, * `indep_set s t μ ↔ indep_sets {s} {t} μ`. -/ variables {α : Type*} [measurable_space α] {s t : set α} (S T : set (set α)) lemma indep_set_iff_indep_sets_singleton (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ] : indep_set s t μ ↔ indep_sets {s} {t} μ := ⟨indep.indep_sets, λ h, indep_sets.indep (generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (is_pi_system.singleton s) (is_pi_system.singleton t) rfl rfl h⟩ lemma indep_set_iff_measure_inter_eq_mul (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ] : indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t := (indep_set_iff_indep_sets_singleton hs_meas ht_meas μ).trans indep_sets_singleton_iff lemma indep_sets.indep_set_of_mem (hs : s ∈ S) (ht : t ∈ T) (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ] (h_indep : indep_sets S T μ) : indep_set s t μ := (indep_set_iff_measure_inter_eq_mul hs_meas ht_meas μ).mpr (h_indep s t hs ht) end indep_set end probability_theory
84d08e688999b4c05ca5ee65ffc6ac485ce842ba
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/rel_classes.lean
263bf5e1487cff55d215e97c18f0327a3668566f
[ "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
29,757
lean
/- Copyright (c) 2020 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Yury G. Kudryashov -/ import logic.is_empty import logic.relation import order.basic /-! # Unbundled relation classes > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove some properties of `is_*` classes defined in `init.algebra.classes`. The main difference between these classes and the usual order classes (`preorder` etc) is that usual classes extend `has_le` and/or `has_lt` while these classes take a relation as an explicit argument. -/ universes u v variables {α : Type u} {β : Type v} {r : α → α → Prop} {s : β → β → Prop} open function lemma of_eq [is_refl α r] : ∀ {a b}, a = b → r a b | _ _ ⟨h⟩ := refl _ lemma comm [is_symm α r] {a b : α} : r a b ↔ r b a := ⟨symm, symm⟩ lemma antisymm' [is_antisymm α r] {a b : α} : r a b → r b a → b = a := λ h h', antisymm h' h lemma antisymm_iff [is_refl α r] [is_antisymm α r] {a b : α} : r a b ∧ r b a ↔ a = b := ⟨λ h, antisymm h.1 h.2, by { rintro rfl, exact ⟨refl _, refl _⟩ }⟩ /-- A version of `antisymm` with `r` explicit. This lemma matches the lemmas from lean core in `init.algebra.classes`, but is missing there. -/ @[elab_simple] lemma antisymm_of (r : α → α → Prop) [is_antisymm α r] {a b : α} : r a b → r b a → a = b := antisymm /-- A version of `antisymm'` with `r` explicit. This lemma matches the lemmas from lean core in `init.algebra.classes`, but is missing there. -/ @[elab_simple] lemma antisymm_of' (r : α → α → Prop) [is_antisymm α r] {a b : α} : r a b → r b a → b = a := antisymm' /-- A version of `comm` with `r` explicit. This lemma matches the lemmas from lean core in `init.algebra.classes`, but is missing there. -/ lemma comm_of (r : α → α → Prop) [is_symm α r] {a b : α} : r a b ↔ r b a := comm theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩ theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) := ⟨λ a b h₁ h₂, antisymm h₂ h₁⟩ theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) := ⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩ theorem is_total.swap (r) [is_total α r] : is_total α (swap r) := ⟨λ a b, (total_of r a b).swap⟩ theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩ theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) := {..@is_refl.swap α r _, ..@is_trans.swap α r _} theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..@is_irrefl.swap α r _, ..@is_trans.swap α r _} theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) := {..@is_preorder.swap α r _, ..@is_antisymm.swap α r _} theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) := {..@is_preorder.swap α r _, ..@is_total.swap α r _} theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) := {..@is_partial_order.swap α r _, ..@is_total.swap α r _} protected theorem is_asymm.is_antisymm (r) [is_asymm α r] : is_antisymm α r := ⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩ protected theorem is_asymm.is_irrefl [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ protected theorem is_total.is_trichotomous (r) [is_total α r] : is_trichotomous α r := ⟨λ a b, or.left_comm.1 (or.inr $ total_of r a b)⟩ @[priority 100] -- see Note [lower instance priority] instance is_total.to_is_refl (r) [is_total α r] : is_refl α r := ⟨λ a, (or_self _).1 $ total_of r a a⟩ lemma ne_of_irrefl {r} [is_irrefl α r] : ∀ {x y : α}, r x y → x ≠ y | _ _ h rfl := irrefl _ h lemma ne_of_irrefl' {r} [is_irrefl α r] : ∀ {x y : α}, r x y → y ≠ x | _ _ h rfl := irrefl _ h lemma not_rel_of_subsingleton (r) [is_irrefl α r] [subsingleton α] (x y) : ¬ r x y := subsingleton.elim x y ▸ irrefl x lemma rel_of_subsingleton (r) [is_refl α r] [subsingleton α] (x y) : r x y := subsingleton.elim x y ▸ refl x @[simp] lemma empty_relation_apply (a b : α) : empty_relation a b ↔ false := iff.rfl lemma eq_empty_relation (r) [is_irrefl α r] [subsingleton α] : r = empty_relation := funext₂ $ by simpa using not_rel_of_subsingleton r instance : is_irrefl α empty_relation := ⟨λ a, id⟩ lemma trans_trichotomous_left [is_trans α r] [is_trichotomous α r] {a b c : α} : ¬r b a → r b c → r a c := begin intros h₁ h₂, rcases trichotomous_of r a b with h₃|h₃|h₃, exact trans h₃ h₂, rw h₃, exact h₂, exfalso, exact h₁ h₃ end lemma trans_trichotomous_right [is_trans α r] [is_trichotomous α r] {a b c : α} : r a b → ¬r c b → r a c := begin intros h₁ h₂, rcases trichotomous_of r b c with h₃|h₃|h₃, exact trans h₁ h₃, rw ←h₃, exact h₁, exfalso, exact h₂ h₃ end lemma transitive_of_trans (r : α → α → Prop) [is_trans α r] : transitive r := λ _ _ _, trans /-- In a trichotomous irreflexive order, every element is determined by the set of predecessors. -/ lemma extensional_of_trichotomous_of_irrefl (r : α → α → Prop) [is_trichotomous α r] [is_irrefl α r] {a b : α} (H : ∀ x, r x a ↔ r x b) : a = b := ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 $ irrefl a) .resolve_right $ mt (H _).1 $ irrefl b /-- Construct a partial order from a `is_strict_order` relation. See note [reducible non-instances]. -/ @[reducible] def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } /-- Construct a linear order from an `is_strict_total_order` relation. See note [reducible non-instances]. -/ @[reducible] def linear_order_of_STO (r) [is_strict_total_order α r] [Π x y, decidable (¬ r x y)] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, decidable_le := λ x y, decidable_of_iff (¬ r y x) ⟨λ h, ((trichotomous_of r y x).resolve_left h).imp eq.symm id, λ h, h.elim (λ h, h ▸ irrefl_of _ _) (asymm_of r)⟩, ..partial_order_of_SO r } theorem is_strict_total_order.swap (r) [is_strict_total_order α r] : is_strict_total_order α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} /-! ### Order connection -/ /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_asymm.is_irrefl α r _ } @[priority 100] -- see Note [lower instance priority] instance is_order_connected_of_is_strict_total_order [is_strict_total_order α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ @[priority 100] -- see Note [lower instance priority] instance is_strict_weak_order_of_is_strict_total_order [is_strict_total_order α r] : is_strict_weak_order α r := { ..is_strict_weak_order_of_is_order_connected } /-! ### Well-order -/ /-- A well-founded relation. Not to be confused with `is_well_order`. -/ @[algebra, mk_iff] class is_well_founded (α : Type u) (r : α → α → Prop) : Prop := (wf : well_founded r) instance has_well_founded.is_well_founded [h : has_well_founded α] : is_well_founded α has_well_founded.r := { ..h } namespace is_well_founded variables (r) [is_well_founded α r] /-- Induction on a well-founded relation. -/ theorem induction {C : α → Prop} : ∀ a, (∀ x, (∀ y, r y x → C y) → C x) → C a := wf.induction /-- All values are accessible under the well-founded relation. -/ theorem apply : ∀ a, acc r a := wf.apply /-- Creates data, given a way to generate a value from all that compare as less under a well-founded relation. See also `is_well_founded.fix_eq`. -/ def fix {C : α → Sort*} : (Π (x : α), (Π (y : α), r y x → C y) → C x) → Π (x : α), C x := wf.fix /-- The value from `is_well_founded.fix` is built from the previous ones as specified. -/ theorem fix_eq {C : α → Sort*} (F : Π (x : α), (Π (y : α), r y x → C y) → C x) : ∀ x, fix r F x = F x (λ y h, fix r F y) := wf.fix_eq F /-- Derive a `has_well_founded` instance from an `is_well_founded` instance. -/ def to_has_well_founded : has_well_founded α := ⟨r, is_well_founded.wf⟩ end is_well_founded theorem well_founded.asymmetric {α : Sort*} {r : α → α → Prop} (h : well_founded r) : ∀ ⦃a b⦄, r a b → ¬ r b a | a := λ b hab hba, well_founded.asymmetric hba hab using_well_founded { rel_tac := λ _ _, `[exact ⟨_, h⟩], dec_tac := tactic.assumption } @[priority 100] -- see Note [lower instance priority] instance is_well_founded.is_asymm (r : α → α → Prop) [is_well_founded α r] : is_asymm α r := ⟨is_well_founded.wf.asymmetric⟩ @[priority 100] -- see Note [lower instance priority] instance is_well_founded.is_irrefl (r : α → α → Prop) [is_well_founded α r] : is_irrefl α r := is_asymm.is_irrefl instance (r : α → α → Prop) [i : is_well_founded α r] : is_well_founded α (relation.trans_gen r) := ⟨i.wf.trans_gen⟩ /-- A class for a well founded relation `<`. -/ @[reducible] def well_founded_lt (α : Type*) [has_lt α] : Prop := is_well_founded α (<) /-- A class for a well founded relation `>`. -/ @[reducible] def well_founded_gt (α : Type*) [has_lt α] : Prop := is_well_founded α (>) @[priority 100] -- See note [lower instance priority] instance (α : Type*) [has_lt α] [h : well_founded_lt α] : well_founded_gt αᵒᵈ := h @[priority 100] -- See note [lower instance priority] instance (α : Type*) [has_lt α] [h : well_founded_gt α] : well_founded_lt αᵒᵈ := h theorem well_founded_gt_dual_iff (α : Type*) [has_lt α] : well_founded_gt αᵒᵈ ↔ well_founded_lt α := ⟨λ h, ⟨h.wf⟩, λ h, ⟨h.wf⟩⟩ theorem well_founded_lt_dual_iff (α : Type*) [has_lt α] : well_founded_lt αᵒᵈ ↔ well_founded_gt α := ⟨λ h, ⟨h.wf⟩, λ h, ⟨h.wf⟩⟩ /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_trichotomous α r, is_trans α r, is_well_founded α r : Prop @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := { } @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance namespace well_founded_lt variables [has_lt α] [well_founded_lt α] /-- Inducts on a well-founded `<` relation. -/ theorem induction {C : α → Prop} : ∀ a, (∀ x, (∀ y, y < x → C y) → C x) → C a := is_well_founded.induction _ /-- All values are accessible under the well-founded `<`. -/ theorem apply : ∀ a : α, acc (<) a := is_well_founded.apply _ /-- Creates data, given a way to generate a value from all that compare as lesser. See also `well_founded_lt.fix_eq`. -/ def fix {C : α → Sort*} : (Π (x : α), (Π (y : α), y < x → C y) → C x) → Π (x : α), C x := is_well_founded.fix (<) /-- The value from `well_founded_lt.fix` is built from the previous ones as specified. -/ theorem fix_eq {C : α → Sort*} (F : Π (x : α), (Π (y : α), y < x → C y) → C x) : ∀ x, fix F x = F x (λ y h, fix F y) := is_well_founded.fix_eq _ F /-- Derive a `has_well_founded` instance from a `well_founded_lt` instance. -/ def to_has_well_founded : has_well_founded α := is_well_founded.to_has_well_founded (<) end well_founded_lt namespace well_founded_gt variables [has_lt α] [well_founded_gt α] /-- Inducts on a well-founded `>` relation. -/ theorem induction {C : α → Prop} : ∀ a, (∀ x, (∀ y, x < y → C y) → C x) → C a := is_well_founded.induction _ /-- All values are accessible under the well-founded `>`. -/ theorem apply : ∀ a : α, acc (>) a := is_well_founded.apply _ /-- Creates data, given a way to generate a value from all that compare as greater. See also `well_founded_gt.fix_eq`. -/ def fix {C : α → Sort*} : (Π (x : α), (Π (y : α), x < y → C y) → C x) → Π (x : α), C x := is_well_founded.fix (>) /-- The value from `well_founded_gt.fix` is built from the successive ones as specified. -/ theorem fix_eq {C : α → Sort*} (F : Π (x : α), (Π (y : α), x < y → C y) → C x) : ∀ x, fix F x = F x (λ y h, fix F y) := is_well_founded.fix_eq _ F /-- Derive a `has_well_founded` instance from a `well_founded_gt` instance. -/ def to_has_well_founded : has_well_founded α := is_well_founded.to_has_well_founded (>) end well_founded_gt /-- Construct a decidable linear order from a well-founded linear order. -/ noncomputable def is_well_order.linear_order (r : α → α → Prop) [is_well_order α r] : linear_order α := by { letI := λ x y, classical.dec (¬r x y), exact linear_order_of_STO r } /-- Derive a `has_well_founded` instance from a `is_well_order` instance. -/ def is_well_order.to_has_well_founded [has_lt α] [hwo : is_well_order α (<)] : has_well_founded α := { r := (<), wf := hwo.wf } -- This isn't made into an instance as it loops with `is_irrefl α r`. theorem subsingleton.is_well_order [subsingleton α] (r : α → α → Prop) [hr : is_irrefl α r] : is_well_order α r := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim a b, trans := λ a b c h, (not_rel_of_subsingleton r a b h).elim, wf := ⟨λ a, ⟨_, λ y h, (not_rel_of_subsingleton r y a h).elim⟩⟩, ..hr } instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := subsingleton.is_well_order _ @[priority 100] instance is_empty.is_well_order [is_empty α] (r : α → α → Prop) : is_well_order α r := { trichotomous := is_empty_elim, trans := is_empty_elim, wf := well_founded_of_empty r } instance prod.lex.is_well_founded [is_well_founded α r] [is_well_founded β s] : is_well_founded (α × β) (prod.lex r s) := ⟨prod.lex_wf is_well_founded.wf is_well_founded.wf⟩ instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ (trans ab bc) }, { exact prod.lex.left _ _ ab }, { exact prod.lex.left _ _ bc }, { exact prod.lex.right _ (trans ab bc) } end, wf := prod.lex_wf is_well_founded.wf is_well_founded.wf } instance inv_image.is_well_founded (r : α → α → Prop) [is_well_founded α r] (f : β → α) : is_well_founded _ (inv_image r f) := ⟨inv_image.wf f is_well_founded.wf⟩ instance measure.is_well_founded (f : α → ℕ) : is_well_founded _ (measure f) := ⟨measure_wf f⟩ theorem subrelation.is_well_founded (r : α → α → Prop) [is_well_founded α r] {s : α → α → Prop} (h : subrelation s r) : is_well_founded α s := ⟨h.wf is_well_founded.wf⟩ namespace set /-- An unbounded or cofinal set. -/ def unbounded (r : α → α → Prop) (s : set α) : Prop := ∀ a, ∃ b ∈ s, ¬ r b a /-- A bounded or final set. Not to be confused with `metric.bounded`. -/ def bounded (r : α → α → Prop) (s : set α) : Prop := ∃ a, ∀ b ∈ s, r b a @[simp] lemma not_bounded_iff {r : α → α → Prop} (s : set α) : ¬bounded r s ↔ unbounded r s := by simp only [bounded, unbounded, not_forall, not_exists, exists_prop, not_and, not_not] @[simp] lemma not_unbounded_iff {r : α → α → Prop} (s : set α) : ¬unbounded r s ↔ bounded r s := by rw [not_iff_comm, not_bounded_iff] lemma unbounded_of_is_empty [is_empty α] {r : α → α → Prop} (s : set α) : unbounded r s := is_empty_elim end set namespace prod instance is_refl_preimage_fst {r : α → α → Prop} [h : is_refl α r] : is_refl (α × α) (prod.fst ⁻¹'o r) := ⟨λ a, refl_of r a.1⟩ instance is_refl_preimage_snd {r : α → α → Prop} [h : is_refl α r] : is_refl (α × α) (prod.snd ⁻¹'o r) := ⟨λ a, refl_of r a.2⟩ instance is_trans_preimage_fst {r : α → α → Prop} [h : is_trans α r] : is_trans (α × α) (prod.fst ⁻¹'o r) := ⟨λ _ _ _, trans_of r⟩ instance is_trans_preimage_snd {r : α → α → Prop} [h : is_trans α r] : is_trans (α × α) (prod.snd ⁻¹'o r) := ⟨λ _ _ _, trans_of r⟩ end prod /-! ### Strict-non strict relations -/ /-- An unbundled relation class stating that `r` is the nonstrict relation corresponding to the strict relation `s`. Compare `preorder.lt_iff_le_not_le`. This is mostly meant to provide dot notation on `(⊆)` and `(⊂)`. -/ class is_nonstrict_strict_order (α : Type*) (r s : α → α → Prop) := (right_iff_left_not_left (a b : α) : s a b ↔ r a b ∧ ¬ r b a) lemma right_iff_left_not_left {r s : α → α → Prop} [is_nonstrict_strict_order α r s] {a b : α} : s a b ↔ r a b ∧ ¬ r b a := is_nonstrict_strict_order.right_iff_left_not_left _ _ /-- A version of `right_iff_left_not_left` with explicit `r` and `s`. -/ lemma right_iff_left_not_left_of (r s : α → α → Prop) [is_nonstrict_strict_order α r s] {a b : α} : s a b ↔ r a b ∧ ¬ r b a := right_iff_left_not_left -- The free parameter `r` is strictly speaking not uniquely determined by `s`, but in practice it -- always has a unique instance, so this is not dangerous. @[priority 100, nolint dangerous_instance] -- see Note [lower instance priority] instance is_nonstrict_strict_order.to_is_irrefl {r : α → α → Prop} {s : α → α → Prop} [is_nonstrict_strict_order α r s] : is_irrefl α s := ⟨λ a h, ((right_iff_left_not_left_of r s).1 h).2 ((right_iff_left_not_left_of r s).1 h).1⟩ /-! #### `⊆` and `⊂` -/ section subset variables [has_subset α] {a b c : α} lemma subset_of_eq_of_subset (hab : a = b) (hbc : b ⊆ c) : a ⊆ c := by rwa hab lemma subset_of_subset_of_eq (hab : a ⊆ b) (hbc : b = c) : a ⊆ c := by rwa ←hbc @[refl] lemma subset_refl [is_refl α (⊆)] (a : α) : a ⊆ a := refl _ lemma subset_rfl [is_refl α (⊆)] : a ⊆ a := refl _ lemma subset_of_eq [is_refl α (⊆)] : a = b → a ⊆ b := λ h, h ▸ subset_rfl lemma superset_of_eq [is_refl α (⊆)] : a = b → b ⊆ a := λ h, h ▸ subset_rfl lemma ne_of_not_subset [is_refl α (⊆)] : ¬ a ⊆ b → a ≠ b := mt subset_of_eq lemma ne_of_not_superset [is_refl α (⊆)] : ¬ a ⊆ b → b ≠ a := mt superset_of_eq @[trans] lemma subset_trans [is_trans α (⊆)] {a b c : α} : a ⊆ b → b ⊆ c → a ⊆ c := trans lemma subset_antisymm [is_antisymm α (⊆)] (h : a ⊆ b) (h' : b ⊆ a) : a = b := antisymm h h' lemma superset_antisymm [is_antisymm α (⊆)] (h : a ⊆ b) (h' : b ⊆ a) : b = a := antisymm' h h' alias subset_of_eq_of_subset ← eq.trans_subset alias subset_of_subset_of_eq ← has_subset.subset.trans_eq alias subset_of_eq ← eq.subset' --TODO: Fix it and kill `eq.subset` alias superset_of_eq ← eq.superset alias subset_trans ← has_subset.subset.trans alias subset_antisymm ← has_subset.subset.antisymm alias superset_antisymm ← has_subset.subset.antisymm' lemma subset_antisymm_iff [is_refl α (⊆)] [is_antisymm α (⊆)] : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ h, ⟨h.subset', h.superset⟩, λ h, h.1.antisymm h.2⟩ lemma superset_antisymm_iff [is_refl α (⊆)] [is_antisymm α (⊆)] : a = b ↔ b ⊆ a ∧ a ⊆ b := ⟨λ h, ⟨h.superset, h.subset'⟩, λ h, h.1.antisymm' h.2⟩ end subset section ssubset variables [has_ssubset α] {a b c : α} lemma ssubset_of_eq_of_ssubset (hab : a = b) (hbc : b ⊂ c) : a ⊂ c := by rwa hab lemma ssubset_of_ssubset_of_eq (hab : a ⊂ b) (hbc : b = c) : a ⊂ c := by rwa ←hbc lemma ssubset_irrefl [is_irrefl α (⊂)] (a : α) : ¬ a ⊂ a := irrefl _ lemma ssubset_irrfl [is_irrefl α (⊂)] {a : α} : ¬ a ⊂ a := irrefl _ lemma ne_of_ssubset [is_irrefl α (⊂)] {a b : α} : a ⊂ b → a ≠ b := ne_of_irrefl lemma ne_of_ssuperset [is_irrefl α (⊂)] {a b : α} : a ⊂ b → b ≠ a := ne_of_irrefl' @[trans] lemma ssubset_trans [is_trans α (⊂)] {a b c : α} : a ⊂ b → b ⊂ c → a ⊂ c := trans lemma ssubset_asymm [is_asymm α (⊂)] {a b : α} (h : a ⊂ b) : ¬ b ⊂ a := asymm h alias ssubset_of_eq_of_ssubset ← eq.trans_ssubset alias ssubset_of_ssubset_of_eq ← has_ssubset.ssubset.trans_eq alias ssubset_irrfl ← has_ssubset.ssubset.false alias ne_of_ssubset ← has_ssubset.ssubset.ne alias ne_of_ssuperset ← has_ssubset.ssubset.ne' alias ssubset_trans ← has_ssubset.ssubset.trans alias ssubset_asymm ← has_ssubset.ssubset.asymm end ssubset section subset_ssubset variables [has_subset α] [has_ssubset α] [is_nonstrict_strict_order α (⊆) (⊂)] {a b c : α} lemma ssubset_iff_subset_not_subset : a ⊂ b ↔ a ⊆ b ∧ ¬ b ⊆ a := right_iff_left_not_left lemma subset_of_ssubset (h : a ⊂ b) : a ⊆ b := (ssubset_iff_subset_not_subset.1 h).1 lemma not_subset_of_ssubset (h : a ⊂ b) : ¬ b ⊆ a := (ssubset_iff_subset_not_subset.1 h).2 lemma not_ssubset_of_subset (h : a ⊆ b) : ¬ b ⊂ a := λ h', not_subset_of_ssubset h' h lemma ssubset_of_subset_not_subset (h₁ : a ⊆ b) (h₂ : ¬ b ⊆ a) : a ⊂ b := ssubset_iff_subset_not_subset.2 ⟨h₁, h₂⟩ alias subset_of_ssubset ← has_ssubset.ssubset.subset alias not_subset_of_ssubset ← has_ssubset.ssubset.not_subset alias not_ssubset_of_subset ← has_subset.subset.not_ssubset alias ssubset_of_subset_not_subset ← has_subset.subset.ssubset_of_not_subset lemma ssubset_of_subset_of_ssubset [is_trans α (⊆)] (h₁ : a ⊆ b) (h₂ : b ⊂ c) : a ⊂ c := (h₁.trans h₂.subset).ssubset_of_not_subset $ λ h, h₂.not_subset $ h.trans h₁ lemma ssubset_of_ssubset_of_subset [is_trans α (⊆)] (h₁ : a ⊂ b) (h₂ : b ⊆ c) : a ⊂ c := (h₁.subset.trans h₂).ssubset_of_not_subset $ λ h, h₁.not_subset $ h₂.trans h lemma ssubset_of_subset_of_ne [is_antisymm α (⊆)] (h₁ : a ⊆ b) (h₂ : a ≠ b) : a ⊂ b := h₁.ssubset_of_not_subset $ mt h₁.antisymm h₂ lemma ssubset_of_ne_of_subset [is_antisymm α (⊆)] (h₁ : a ≠ b) (h₂ : a ⊆ b) : a ⊂ b := ssubset_of_subset_of_ne h₂ h₁ lemma eq_or_ssubset_of_subset [is_antisymm α (⊆)] (h : a ⊆ b) : a = b ∨ a ⊂ b := (em (b ⊆ a)).imp h.antisymm h.ssubset_of_not_subset lemma ssubset_or_eq_of_subset [is_antisymm α (⊆)] (h : a ⊆ b) : a ⊂ b ∨ a = b := (eq_or_ssubset_of_subset h).swap alias ssubset_of_subset_of_ssubset ← has_subset.subset.trans_ssubset alias ssubset_of_ssubset_of_subset ← has_ssubset.ssubset.trans_subset alias ssubset_of_subset_of_ne ← has_subset.subset.ssubset_of_ne alias ssubset_of_ne_of_subset ← ne.ssubset_of_subset alias eq_or_ssubset_of_subset ← has_subset.subset.eq_or_ssubset alias ssubset_or_eq_of_subset ← has_subset.subset.ssubset_or_eq lemma ssubset_iff_subset_ne [is_antisymm α (⊆)] : a ⊂ b ↔ a ⊆ b ∧ a ≠ b := ⟨λ h, ⟨h.subset, h.ne⟩, λ h, h.1.ssubset_of_ne h.2⟩ lemma subset_iff_ssubset_or_eq [is_refl α (⊆)] [is_antisymm α (⊆)] : a ⊆ b ↔ a ⊂ b ∨ a = b := ⟨λ h, h.ssubset_or_eq, λ h, h.elim subset_of_ssubset subset_of_eq⟩ end subset_ssubset /-! ### Conversion of bundled order typeclasses to unbundled relation typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ instance [preorder α] : is_refl α (≥) := is_refl.swap _ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ instance [preorder α] : is_trans α (≥) := is_trans.swap _ instance [preorder α] : is_preorder α (≤) := {} instance [preorder α] : is_preorder α (≥) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ instance [preorder α] : is_trans α (>) := is_trans.swap _ instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ instance [preorder α] : is_asymm α (>) := is_asymm.swap _ instance [preorder α] : is_antisymm α (<) := is_asymm.is_antisymm _ instance [preorder α] : is_antisymm α (>) := is_asymm.is_antisymm _ instance [preorder α] : is_strict_order α (<) := {} instance [preorder α] : is_strict_order α (>) := {} instance [preorder α] : is_nonstrict_strict_order α (≤) (<) := ⟨@lt_iff_le_not_le _ _⟩ instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _ instance [partial_order α] : is_partial_order α (≤) := {} instance [partial_order α] : is_partial_order α (≥) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ instance [linear_order α] : is_total α (≥) := is_total.swap _ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance instance [linear_order α] : is_total_preorder α (≥) := {} instance [linear_order α] : is_linear_order α (≤) := {} instance [linear_order α] : is_linear_order α (≥) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _ instance [linear_order α] : is_trichotomous α (≤) := is_total.is_trichotomous _ instance [linear_order α] : is_trichotomous α (≥) := is_total.is_trichotomous _ instance [linear_order α] : is_strict_total_order α (<) := {} instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance lemma transitive_le [preorder α] : transitive (@has_le.le α _) := transitive_of_trans _ lemma transitive_lt [preorder α] : transitive (@has_lt.lt α _) := transitive_of_trans _ lemma transitive_ge [preorder α] : transitive (@ge α _) := transitive_of_trans _ lemma transitive_gt [preorder α] : transitive (@gt α _) := transitive_of_trans _ instance order_dual.is_total_le [has_le α] [is_total α (≤)] : is_total αᵒᵈ (≤) := @is_total.swap α _ _ instance : well_founded_lt ℕ := ⟨nat.lt_wf⟩ instance nat.lt.is_well_order : is_well_order ℕ (<) := { } instance [linear_order α] [h : is_well_order α (<)] : is_well_order αᵒᵈ (>) := h instance [linear_order α] [h : is_well_order α (>)] : is_well_order αᵒᵈ (<) := h
d62666885fa82f804fc64e9747f47b917f585329
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/haar/inner_product_space.lean
8d7fed18e4f47795e4294e58abe46a86a4a9c175
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,074
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.inner_product_space.orientation import measure_theory.measure.lebesgue.eq_haar /-! # Volume forms and measures on inner product spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A volume form induces a Lebesgue measure on general finite-dimensional real vector spaces. In this file, we discuss the specific situation of inner product spaces, where an orientation gives rise to a canonical volume form. We show that the measure coming from this volume form gives measure `1` to the parallelepiped spanned by any orthonormal basis, and that it coincides with the canonical `volume` from the `measure_space` instance. -/ open finite_dimensional measure_theory measure_theory.measure set variables {ι F : Type*} variables [fintype ι] [normed_add_comm_group F] [inner_product_space ℝ F] [finite_dimensional ℝ F] [measurable_space F] [borel_space F] section variables {m n : ℕ} [_i : fact (finrank ℝ F = n)] include _i /-- The volume form coming from an orientation in an inner product space gives measure `1` to the parallelepiped associated to any orthonormal basis. This is a rephrasing of `abs_volume_form_apply_of_orthonormal` in terms of measures. -/ lemma orientation.measure_orthonormal_basis (o : orientation ℝ F (fin n)) (b : orthonormal_basis ι ℝ F) : o.volume_form.measure (parallelepiped b) = 1 := begin have e : ι ≃ fin n, { refine fintype.equiv_fin_of_card_eq _, rw [← _i.out, finrank_eq_card_basis b.to_basis] }, have A : ⇑b = (b.reindex e) ∘ e, { ext x, simp only [orthonormal_basis.coe_reindex, function.comp_app, equiv.symm_apply_apply] }, rw [A, parallelepiped_comp_equiv, alternating_map.measure_parallelepiped, o.abs_volume_form_apply_of_orthonormal, ennreal.of_real_one], end /-- In an oriented inner product space, the measure coming from the canonical volume form associated to an orientation coincides with the volume. -/ lemma orientation.measure_eq_volume (o : orientation ℝ F (fin n)) : o.volume_form.measure = volume := begin have A : o.volume_form.measure ((std_orthonormal_basis ℝ F).to_basis.parallelepiped) = 1, from orientation.measure_orthonormal_basis o (std_orthonormal_basis ℝ F), rw [add_haar_measure_unique o.volume_form.measure ((std_orthonormal_basis ℝ F).to_basis.parallelepiped), A, one_smul], simp only [volume, basis.add_haar], end end /-- The volume measure in a finite-dimensional inner product space gives measure `1` to the parallelepiped spanned by any orthonormal basis. -/ lemma orthonormal_basis.volume_parallelepiped (b : orthonormal_basis ι ℝ F) : volume (parallelepiped b) = 1 := begin haveI : fact (finrank ℝ F = finrank ℝ F) := ⟨rfl⟩, let o := (std_orthonormal_basis ℝ F).to_basis.orientation, rw ← o.measure_eq_volume, exact o.measure_orthonormal_basis b, end
70b5475463228bacdbb84d880748100c585068ab
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/14.Inductive_Definitions/Data_Types/mylist.lean
f2d3d40277ee0d0677ca004deed5dd307a1b7f5c
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
4,811
lean
/- We can import definitions from another file. Here we import our definitions from the mynat.lean file. The dot (.) tells Lean to look for that file in the same directory as this file. -/ import .mynat /- Open the mynat namespace (in that file) so that we don't have to prefix names with mynat. -/ open mynat -- Create a namespace for this file namespace my_list_adt /- We now introduce a type of "lists that contain objects of some other type, T." For example, an object of type "my_list ℕ" would represent a list of value of type ℕ, while an object of type "my_list bool" would represent a list of values of type bool. Here's the "inductive" declaration. Notice that, in constrast to nat and bool, this declaration has a parameter, T. -/ inductive my_list (T: Type) : Type /- Now think about the type of my_list. Its type is Type → Type. We call my_list a type constructor or a polymorphic type. It takes a type as an argument and then returns a type, specialized for elements of the given type, as a result. Generic types in Java and template types in C++ similarly take type parameters and yield new types specialized for handling of values of the specified argument type. Now we give the constructors for our polymorphic type. The first one, my_nil, is a constant term of type (my_list T). We will interpret it as representing the "empty list of values of type T."" -/ | nil: my_list /- And here's the interesting part. We now provide my_cons as a constructor used to produce a bigger list from a given list by tacking a new value onto its front. The constructor takes a value, h (short for "head"), of type T, the value to be tacked on; and then it takes a value, t (short for tail), the smaller list onto which h will be tacked. The result is a new my_list, represented by the term, (my_cons h t), which we interpret as the list starting with h as the value at its head, wand ith the whole smaller list, t, as its tail (the rest of the list). -/ | cons: T → my_list → my_list open my_list /- EXAMPLES: * list of mynat * list of ℕ * list of bool -/ -- some lists of mynat values def empty_mynat_list : my_list mynat := (nil mynat) -- [] #reduce empty_mynat_list def zero_mynat_list := (cons zero empty_mynat_list) -- [0] #reduce zero_mynat_list def one_mynat_list := (cons one zero_mynat_list) -- [1,0] #reduce one_mynat_list def two_mynat_list := (cons two one_mynat_list) -- [2,1,0] -- A list of ℕ values! [2,1,0] def two_nat_list := (cons 2 (cons 1 (cons 0 (nil ℕ)))) #reduce two_nat_list -- A list of bool values [tt,ff,tt] def a_bool_list := (cons tt (cons ff (cons tt (nil bool)))) /- Adding functions to our algebra -/ -- If list is empty return true else false def isNil { T : Type } (l : my_list T) : bool := match l with | (nil T) := tt | _ := ff end #reduce isNil a_bool_list #reduce isNil empty_mynat_list /- Note that T is an implicit parameter here. Lean can infer T from l. -/ -- Length of l. A recursive function. def length : ∀ { T : Type }, my_list T → ℕ | _ (nil T) := 0 | _ (cons h t) := 1 + (length t) /- In the pattern matches here, Lean requires that we match on both arguments, but we do not want to give a new name to T, so we use _ as a wildcard. We can then use the T that is declared on the first line as a value in the pattern for the nil list. -/ #reduce length empty_mynat_list #reduce length a_bool_list -- Append two lists def append : ∀ { T : Type }, my_list T → my_list T → my_list T | _ (nil T) l2 := l2 | _ (cons h t) l2 := cons h (append t l2) #reduce a_bool_list #reduce append a_bool_list a_bool_list /- PROOFS! -/ -- Here's one, no induction needed theorem nil_append_left_zero : ∀ { T : Type }, ∀ l2 : my_list T, append (nil T) l2 = l2 := begin intro T, intro l2, -- simplify using rules for append simp [append], end -- But this requires induction theorem nil_append_right_zero : ∀ { T : Type }, ∀ l1 : my_list T, append l1 (nil T) = l1 := begin intro T, intro l1, induction l1, -- base case simp [append], -- inductive case simp [append], assumption, end -- A desired property of append! theorem append_length : ∀ { T : Type }, ∀ l1 l2 : my_list T, length (append l1 l2) = (length l1) + (length l2) := begin intros T l1 l2, --cases l1 with h l1' --no work! induction l1 with h l1 ih, -- need ih /- base case: simplify using definitions of length, append -/ simp [append, length], -- inductive case -- simplify goal as usual simp [append, length], -- critical: rewrite using ih!!! rw ih, /- See if Lean can figure out to figure out to apply commutativity of addition. -/ simp, -- yay, qed! end end my_list_adt
f83b0cd7d615e06b3ba76e9aa9c252b61d2f0ee5
9e90bb7eb4d1bde1805f9eb6187c333fdf09588a
/src/stump/to_epsilon.lean
b7404be32d7da4be33fe5ef0ee0d3da99062a75f
[ "Apache-2.0" ]
permissive
alexjbest/stump-learnable
6311d0c3a1a1a0e65ce83edcbb3b4b7cecabb851
f8fd812fc646d2ece312ff6ffc2a19848ac76032
refs/heads/master
1,659,486,805,691
1,590,454,024,000
1,590,454,024,000
266,173,720
0
0
Apache-2.0
1,590,169,884,000
1,590,169,883,000
null
UTF-8
Lean
false
false
14,841
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import topology.sequences import .setup_definition /-! # `extend_to_epsilon` This file proves a property of values of measures on intervals. Given a (probability) measure μ on ℝ, for every ε > 0, given a real number t such that μ(0,t] > ε we exhibit a θ such that μ(0,t) > ε and μ(θ,t] ≤ ε. This is a largely technical lemma used in other parts of the stump proof. ## Notations This file uses the local notation `f ⟶ limit` for `tendsto f at_top (nhds limit)` for better readability of some proof states. ## Implementation notes We prove this lemma for `μ` a probability measure on the non-negative real numbers `nnreal`. Note, however that we do not use that `μ` is a probability measure anywhere,and this theorem holds for an arbitrary measure on a conditionally complete, linearly ordered topological space α with an orderable topology. ## Tags measure, intervals -/ noncomputable theory local attribute [instance, priority 0] classical.prop_decidable universe u open set lattice nnreal probability_measure filter nat measure_theory topological_space local notation f `⟶` limit := tendsto f at_top (nhds limit) section stump variables (μ: probability_measure ℍ) (target: ℍ) (n: ℕ) /-- `inc_seq_of x n` takes a sequence `x` and returns the `n`th maximum member. -/ noncomputable def inc_seq_of (x : ℕ → nnreal) : ℕ → nnreal | 0 := x 0 | (nat.succ n) := max (x (nat.succ n)) (inc_seq_of n) lemma inc_seq_increasing' (x : ℕ → nnreal) : ∀ n:ℕ, inc_seq_of x n ≤ inc_seq_of x (succ n) := begin intros n, induction n with k ih, {simp [inc_seq_of], right, refl}, { by_cases (inc_seq_of x k ≤ x (succ k)), simp [inc_seq_of,h] at ih ⊢, cases ih, right, refl, simp [inc_seq_of,h] at ih ⊢, right, split, rw not_le at h, apply le_of_lt h, refl } end lemma inc_seq_mono {x : ℕ → nnreal} : ∀ n m:ℕ, (n ≤ m) → inc_seq_of x n ≤ inc_seq_of x m := begin intros n m hnm, induction hnm with k, by refl, { rw inc_seq_of, by_cases (inc_seq_of x k ≤ x (succ k)), simp [h], refine le_trans hnm_ih h, simp [h], simp at h, right, assumption, } end lemma inc_seq_le_of_seq_le {x : ℕ → nnreal} {θ : nnreal} (hx : ∀ n, x n ≤ θ) : ∀ n, inc_seq_of x n ≤ θ := begin intros n , induction n with k ih, by rw inc_seq_of;exact hx 0, { rw inc_seq_of, by_cases (inc_seq_of x k ≤ x (succ k)), simp [h], exact hx _, simp [h], exact ⟨hx _, ih⟩, } end lemma inc_seq_of_exists_index (x : ℕ → nnreal) : ∀ n : ℕ, ∃ k : ℕ, inc_seq_of x n = x k := begin intros n, induction n with n₀ ih, by rw inc_seq_of; existsi 0; refl, { rw inc_seq_of, by_cases (inc_seq_of x n₀ ≤ x (succ n₀)), simp [h], existsi (succ n₀), refl, rw max, split_ifs, exact ih, existsi (succ n₀), refl, } end lemma inc_seq_of_exists_index' (x : ℕ → nnreal) : ∀ nₖ : ℕ, ∃ n : ℕ, (inc_seq_of x nₖ = x n) ∧ (n ≤ nₖ) := begin intros n, induction n with n₀ ih, by rw inc_seq_of; existsi 0 ; exact ⟨rfl, by refl⟩, { rw inc_seq_of, by_cases (inc_seq_of x n₀ ≤ x (succ n₀)), simp[h], existsi (succ n₀), exact ⟨rfl, by refl⟩, rw max, split_ifs, choose k hk using ih, exact ⟨k, and.intro hk.left (le_succ_of_le hk.right)⟩, choose k hk using ih, existsi k, rw not_le at h_1, rw not_le at h, exfalso, have h₁ := lt_trans h h_1, have h₂ := lt_irrefl (x (succ n₀)), exact h₂ h₁, } end lemma seq_le_inc_seq (x : ℕ → nnreal) : ∀ n, x n ≤ inc_seq_of x n := begin intros n, induction n with k ih, by refl, { rw inc_seq_of, by_cases (inc_seq_of x k ≤ x (succ k)), simp [h] ; refl, simp [h],left ; refl, }, end /-- This theorem states that the sequence of maximums of a sequence (converging to a point greater than every member of the sequence) also converges to the same limit. The proof uses the sandwich theorem. -/ theorem tendsto_inc_seq_of_eq_tendsto (x : ℕ → nnreal) (θ : nnreal) (h : tendsto x at_top (nhds θ)) (hfs : ∀ n:ℕ, (x n) ≤ θ ): tendsto (inc_seq_of x) at_top (nhds θ) := begin refine tendsto_of_tendsto_of_tendsto_of_le_of_le h (tendsto_const_nhds) _ _, exact seq_le_inc_seq (λ (n : ℕ), x n), sorry, end lemma lim_le_of_seq_le {x : ℕ → ℍ} {θ y: nnreal} (lim : tendsto x at_top (nhds θ)) (hx : ∀ n, x n ≤ y) : θ ≤ y := begin refine le_of_tendsto at_top_ne_bot lim _, apply eventually_at_top.2, existsi 0, intros b _, exact hx _, apply_instance, end /-- Helper lemma for extend_to_epsilon proof. -/ lemma Ioc_eq_Union_IccB {θ target : nnreal} (h : θ < target):let y := λ n:ℕ, θ + (target - θ)/(n+1) in let B := λ n:ℕ, Icc (y n) target in Ioc (θ) target = ⋃ i:ℕ, B i := begin intros y B, have hB₁ : ∀ i, B i ⊆ B (succ i), { assume i, dsimp [B], refine Icc_subset_Icc _ (by refl), dsimp [y], simp, rw ← nnreal.coe_le_coe, rw nnreal.coe_div, rw nnreal.coe_div, rw (nnreal.coe_sub (le_of_lt h)), rw _root_.div_le_div_left, simp, exact zero_le_one, all_goals{simp}, rwa nnreal.coe_lt_coe, refine add_pos _ zero_lt_one, exact cast_add_one_pos i, exact cast_add_one_pos i, }, ext z, rw mem_Union, dsimp [B,Ioc,Icc,y], fsplit, assume H, have pos₀ : 0 < target - θ, begin rw [← nnreal.coe_pos, nnreal.coe_sub, (sub_pos :(0:ℝ) < ↑target - ↑θ ↔ ↑θ < ↑target),nnreal.coe_lt_coe], exact h, exact le_of_lt h, end, let ε₀ := z - θ, have pos₁ : (ε₀/(target - θ) : nnreal) > 0, { rw nnreal.div_def, refine mul_pos _ _, simp [ε₀], change (0 < z - θ), rw [← nnreal.coe_pos, nnreal.coe_sub, (sub_pos :(0:ℝ) < ↑z - ↑θ ↔ ↑θ < ↑z),nnreal.coe_lt_coe], exact H.1, exact le_of_lt H.1, change (0 < (target - θ)⁻¹), rwa nnreal.inv_pos, }, have := nnreal.coe_pos.mpr pos₁, replace := exists_nat_one_div_lt this, choose n hyp using this, existsi n, refine ⟨ _ , H.2 ⟩, suffices : (target - θ)/(n+1) < ε₀, refine le_of_lt _, convert (add_lt_add_left this θ), rw [add_comm, sub_add_cancel_of_le (le_of_lt H.1)], rw nnreal.coe_div at hyp, simp [-add_comm] at hyp, rw nnreal.div_def, rw ← nnreal.coe_lt_coe, rw nnreal.coe_mul, rw lt_div_iff at hyp, rw mul_comm, simpa [-add_comm], rwa nnreal.coe_pos, assume H', choose j hyp' using H', refine ⟨ _ , hyp'.2 ⟩, replace hyp' := hyp'.1, suffices : 0 < (target - θ) / (↑j + 1) , calc θ < θ + ((target - θ) / (↑j + 1)) : by rwa (lt_add_iff_pos_right _) ... ≤ z : hyp', rw [← nnreal.coe_pos, nnreal.coe_div], refine _root_.div_pos _ _, rwa [nnreal.coe_sub (le_of_lt h), _root_.sub_pos,nnreal.coe_lt_coe], simp only [nnreal.coe_nat_cast, nnreal.coe_add, nnreal.coe_one], exact add_pos_of_nonneg_of_pos (by simp) (zero_lt_one) end /-- Main theorem: given a (probability) measure μ on ℝ, for every ε > 0, given a real number t such that μ(0,t] > ε we exhibit a θ such that μ(0,t) > ε and μ(θ,t] ≤ ε. -/ theorem extend_to_epsilon_1: ∀ ε: nnreal, ε > 0 → μ (Ioc 0 target) > ε → ∃ θ: nnreal, μ (Icc θ target) ≥ ε ∧ μ (Ioc θ target) ≤ ε := begin intros ε h₁ h₂, let K := {x: ℍ | μ (Icc x target) ≥ ε}, /- We hope to prove that the supremum of the above set is the required number. -/ let θ := Sup K, existsi θ, /- The set K is non-empty since 0 ∈ K. -/ have Kne : K ≠ ∅, { assume not, have zeroK : (0:nnreal) ∈ K, replace h₂ : μ (Ioc 0 target) ≥ ε, by exact le_of_lt h₂, simp [h₂], suffices : μ (Icc 0 target) ≥ μ (Ioc 0 target), exact le_trans h₂ this, refine prob_mono _ _, rintros x ⟨hx₁,hx₂⟩, exact and.intro (le_of_lt hx₁) hx₂, finish, }, /- The set K is bounded above as `target` is an upper-bound. -/ have Kbdd : bdd_above K, { existsi target, assume y yinK, dsimp at yinK,by_contradiction, rw [Icc] at yinK, suffices : μ {x : ℍ | y ≤ x ∧ x ≤ target} = 0, rw this at yinK, change (0 < ε) at h₁, rw ←not_le at h₁, exact h₁ yinK, suffices : {x : ℍ | y ≤ x ∧ x ≤ target} = ∅, rw this, exact prob_empty μ, suffices : ∀ x : ℍ, ¬ (y ≤ x ∧ x ≤ target), simp [this], rintros _ ⟨hx₁,hx₂⟩, exact a (le_trans hx₁ hx₂) }, /- Since K is non-empty and bounded above, it's supremum is contained in it's closure. -/ have SupinClK : θ ∈ closure K, by exact cSup_mem_closure (ne_empty_iff_nonempty.mp Kne) Kbdd, /- Since the closure K is equal to the sequential closure, θ belongs to the sequential closure of K. -/ have : θ ∈ sequential_closure K, { suffices : sequential_closure K = closure K, rwa this, exact sequential_space.sequential_closure_eq_closure K, }, /- Hence, there exists a sequence x in K converging to θ. -/ have seq : ∃ x : ℕ → nnreal, (∀ n : ℕ, x n ∈ K) ∧ (tendsto x at_top (nhds θ)), by rw sequential_closure at this ; simpa [this], clear this, choose x hn using seq, rcases hn with ⟨h₁,lim⟩, /- Now, the interval [ θ , target ] is the infinite intersection of the intervals [ zₙ = max_{k ≤ n} xₖ , target]. Note that the maximums are ≤ θ since the sequence itself is ≤ θ. -/ have Iccintereq : Icc θ target = (⋂ (n : ℕ), Icc (inc_seq_of x n) target), { ext y, rw mem_Inter, fsplit, assume h i, dsimp [Icc] at h |-, rcases h with ⟨g₁,g₂⟩, refine ⟨ _, g₂⟩, simp [θ] at g₁, rw cSup_le_iff Kbdd (ne_empty_iff_nonempty.mp Kne) at g₁, refine inc_seq_le_of_seq_le _ _, assume i, exact g₁ (x i) (h₁ i), assume h, dsimp [Icc] at h |-, refine ⟨ _ , (h 0).2⟩, refine le_of_tendsto at_top_ne_bot lim _, apply eventually_at_top.2, existsi 0, intros b _, exact le_trans (seq_le_inc_seq x b) ((h b).left), apply_instance, }, /- Let s(n) denote the interval [zₙ , target]. -/ let s := λ n, Icc (inc_seq_of x n) target, /- We have lim_{n → ∞} μ [zₙ, target] = μ ([θ, target]). Crucially, we use the fact that measures are continuous from above. -/ have : tendsto (μ.to_measure ∘ s) at_top (nhds (μ.to_measure (⋂ (n : ℕ), s n))), { refine tendsto_measure_Inter _ _ _, show ∀ (n : ℕ), is_measurable (s n), from assume n, is_closed_Icc.is_measurable, show ∀ (n m : ℕ), n ≤ m → s m ⊆ s n, from assume n m hnm, Icc_subset_Icc (inc_seq_mono _ _ hnm) (by refl), existsi 0, apply to_measure_lt_top, }, /- From this the first conclusion follows, by using the fact that if aₙ⟶b and aₙ ≥ c then b ≥ c. -/ have part₁ : μ (Icc θ target) ≥ ε, { rw ←Iccintereq at this, change (ε ≤ μ (Icc θ target)), rw prob_apply, rw ←ennreal.coe_le_coe, rw ennreal.coe_to_nnreal (to_measure_ne_top _ _), refine ge_of_tendsto (at_top_ne_bot) this _, clear this, apply eventually_at_top.2, existsi 0, intros b hb, dsimp [s], have := inc_seq_of_exists_index x b, choose k₀ hk₀ using this, rw hk₀, replace h₁ := h₁ k₀, rw ← coe_eq_to_measure, rw ennreal.coe_le_coe, assumption, apply_instance, exact is_closed_Icc.is_measurable, }, /- The remaining proof proceeds by casing on target ≤ θ.-/ by_cases (target ≤ θ), /- If target ≤ θ then [θ,target] = ∅ and the conclusion follows. -/ have Iocempty : Ioc θ target = ∅, from Ioc_eq_empty h, exact ⟨part₁,by simp [Iocempty]⟩, /- If not, we define a sequence yₙ := {θ + (target - θ)/(n+1)}. -/ simp at h, let y := λ n:ℕ, θ + (target - θ)/(n+1), /- Prove that θ < yₙ ≤ target. -/ have hb : ∀ n, (θ < y n) ∧ (y n ≤ target), { assume n, split, dsimp [y], suffices : 0 < target - θ, norm_num, rw nnreal.div_def, refine mul_pos this _, apply nnreal.inv_pos.2, rw zero_lt_iff_ne_zero, simp, rw ←nnreal.coe_pos, rw nnreal.coe_sub, rw _root_.sub_pos, rwa nnreal.coe_lt_coe, exact le_of_lt h, dsimp [y], calc (θ + (target - θ) / (n + 1)) = θ + (target - θ)*(n+1)⁻¹ :by rw ←nnreal.div_def ... ≤ θ + ((target - θ)*1) : by simp; exact mul_le_of_le_one_right (le_of_lt (by rwa [← nnreal.coe_pos, nnreal.coe_sub, _root_.sub_pos,nnreal.coe_lt_coe];exact le_of_lt h)) (by rw [nnreal.inv_le,mul_one];repeat{simp}) ... = θ + (target - θ) : by rw mul_one ... = θ + target - θ : by rw [←nnreal.eq_iff,nnreal.coe_add, (nnreal.coe_sub (le_of_lt h))]; simp ... = target : by rw nnreal.add_sub_cancel', }, /- Prove that ∀ n, μ[yₙ, target] < ε. -/ have ha : ∀ n, μ (Icc (y n) target) < ε, { by_contradiction, push_neg at a, choose n ha using a, have yinK : (y n) ∈ K, from ha, have : y n ≤ θ, from le_cSup (Kbdd) yinK, exact (not_le.2 (hb n).left this), }, let B := λ n:ℕ, Icc (y n) target, /- From a helper lemma above, we get that (θ, target] = ⋃(n:ℕ),[yₙ,target]. -/ have hB₂ : Ioc (θ) target = ⋃ i:ℕ, B i, from Ioc_eq_Union_IccB h, let s' := λ n, Icc (y n) target, /- Now we prove, using the fact that measures are continuous from below, that μ [yₙ, target] → μ (θ, target]. -/ have : tendsto (μ.to_measure ∘ s') at_top (nhds (μ.to_measure (⋃ (n : ℕ), s' n))), { refine tendsto_measure_Union _ _, assume n, exact is_closed_Icc.is_measurable, unfold monotone, dsimp [s'], assume a b hab, refine Icc_subset_Icc _ (by refl), dsimp [y], rw add_le_add_iff_left, rw nnreal.div_def, rw nnreal.div_def, refine mul_le_mul_of_nonneg_left _ (le_of_lt (by rwa [← nnreal.coe_pos,nnreal.coe_sub (le_of_lt h), _root_.sub_pos,nnreal.coe_lt_coe])), rw ← nnreal.coe_le_coe, simp, rw inv_le_inv _ _, simpa, repeat{exact add_pos_of_nonneg_of_pos (by simp) (zero_lt_one)}, }, /- Show the remaining conclusion. -/ have part₂ : μ (Ioc θ target) ≤ ε, { rw ←hB₂ at this, rw [prob_apply, ←ennreal.coe_le_coe, ennreal.coe_to_nnreal (to_measure_ne_top _ _)], refine le_of_tendsto (at_top_ne_bot) this _, clear this, apply eventually_at_top.2, existsi 0, intros b hb, dsimp [s'], refine le_of_lt _ , rw ← coe_eq_to_measure, rw ennreal.coe_lt_coe, exact (ha b), apply_instance, exact ((is_open_lt continuous_const continuous_id).is_measurable).inter ((is_closed_le continuous_id continuous_const).is_measurable), }, exact ⟨part₁,part₂⟩, end end stump
401cd387192d5cedb390c93f3a42dc45f4be2684
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/nonneg.lean
e0d7c627300e7c23c757a50101c2e008cac59917
[ "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
15,948
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.order.archimedean import order.lattice_intervals import order.complete_lattice_intervals /-! # The type of nonnegative elements This file defines instances and prove some properties about the nonnegative elements `{x : α // 0 ≤ x}` of an arbitrary type `α`. Currently we only state instances and states some `simp`/`norm_cast` lemmas. When `α` is `ℝ`, this will give us some properties about `ℝ≥0`. ## Main declarations * `{x : α // 0 ≤ x}` is a `canonically_linear_ordered_add_monoid` if `α` is a `linear_ordered_ring`. * `{x : α // 0 ≤ x}` is a `linear_ordered_comm_group_with_zero` if `α` is a `linear_ordered_field`. ## Implementation Notes Instead of `{x : α // 0 ≤ x}` we could also use `set.Ici (0 : α)`, which is definitionally equal. However, using the explicit subtype has a big advantage: when writing and element explicitly with a proof of nonnegativity as `⟨x, hx⟩`, the `hx` is expected to have type `0 ≤ x`. If we would use `Ici 0`, then the type is expected to be `x ∈ Ici 0`. Although these types are definitionally equal, this often confuses the elaborator. Similar problems arise when doing cases on an element. The disadvantage is that we have to duplicate some instances about `set.Ici` to this subtype. -/ open set variables {α : Type*} namespace nonneg /-- This instance uses data fields from `subtype.partial_order` to help type-class inference. The `set.Ici` data fields are definitionally equal, but that requires unfolding semireducible definitions, so type-class inference won't see this. -/ instance order_bot [preorder α] {a : α} : order_bot {x : α // a ≤ x} := { ..set.Ici.order_bot } lemma bot_eq [preorder α] {a : α} : (⊥ : {x : α // a ≤ x}) = ⟨a, le_rfl⟩ := rfl instance no_max_order [partial_order α] [no_max_order α] {a : α} : no_max_order {x : α // a ≤ x} := set.Ici.no_max_order instance semilattice_sup [semilattice_sup α] {a : α} : semilattice_sup {x : α // a ≤ x} := set.Ici.semilattice_sup instance semilattice_inf [semilattice_inf α] {a : α} : semilattice_inf {x : α // a ≤ x} := set.Ici.semilattice_inf instance distrib_lattice [distrib_lattice α] {a : α} : distrib_lattice {x : α // a ≤ x} := set.Ici.distrib_lattice instance densely_ordered [preorder α] [densely_ordered α] {a : α} : densely_ordered {x : α // a ≤ x} := show densely_ordered (Ici a), from set.densely_ordered /-- If `Sup ∅ ≤ a` then `{x : α // a ≤ x}` is a `conditionally_complete_linear_order`. -/ @[reducible] protected noncomputable def conditionally_complete_linear_order [conditionally_complete_linear_order α] {a : α} : conditionally_complete_linear_order {x : α // a ≤ x} := { .. @ord_connected_subset_conditionally_complete_linear_order α (set.Ici a) _ ⟨⟨a, le_rfl⟩⟩ _ } /-- If `Sup ∅ ≤ a` then `{x : α // a ≤ x}` is a `conditionally_complete_linear_order_bot`. This instance uses data fields from `subtype.linear_order` to help type-class inference. The `set.Ici` data fields are definitionally equal, but that requires unfolding semireducible definitions, so type-class inference won't see this. -/ @[reducible] protected noncomputable def conditionally_complete_linear_order_bot [conditionally_complete_linear_order α] {a : α} (h : Sup ∅ ≤ a) : conditionally_complete_linear_order_bot {x : α // a ≤ x} := { cSup_empty := (function.funext_iff.1 (@subset_Sup_def α (set.Ici a) _ ⟨⟨a, le_rfl⟩⟩) ∅).trans $ subtype.eq $ by { rw bot_eq, cases h.lt_or_eq with h2 h2, { simp [h2.not_le] }, simp [h2] }, ..nonneg.order_bot, ..nonneg.conditionally_complete_linear_order } instance inhabited [preorder α] {a : α} : inhabited {x : α // a ≤ x} := ⟨⟨a, le_rfl⟩⟩ instance has_zero [has_zero α] [preorder α] : has_zero {x : α // 0 ≤ x} := ⟨⟨0, le_rfl⟩⟩ @[simp, norm_cast] protected lemma coe_zero [has_zero α] [preorder α] : ((0 : {x : α // 0 ≤ x}) : α) = 0 := rfl @[simp] lemma mk_eq_zero [has_zero α] [preorder α] {x : α} (hx : 0 ≤ x) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) = 0 ↔ x = 0 := subtype.ext_iff instance has_add [add_zero_class α] [preorder α] [covariant_class α α (+) (≤)] : has_add {x : α // 0 ≤ x} := ⟨λ x y, ⟨x + y, add_nonneg x.2 y.2⟩⟩ @[simp] lemma mk_add_mk [add_zero_class α] [preorder α] [covariant_class α α (+) (≤)] {x y : α} (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) + ⟨y, hy⟩ = ⟨x + y, add_nonneg hx hy⟩ := rfl @[simp, norm_cast] protected lemma coe_add [add_zero_class α] [preorder α] [covariant_class α α (+) (≤)] (a b : {x : α // 0 ≤ x}) : ((a + b : {x : α // 0 ≤ x}) : α) = a + b := rfl instance has_nsmul [add_monoid α] [preorder α] [covariant_class α α (+) (≤)] : has_smul ℕ {x : α // 0 ≤ x} := ⟨λ n x, ⟨n • x, nsmul_nonneg x.prop n⟩⟩ @[simp] lemma nsmul_mk [add_monoid α] [preorder α] [covariant_class α α (+) (≤)] (n : ℕ) {x : α} (hx : 0 ≤ x) : (n • ⟨x, hx⟩ : {x : α // 0 ≤ x}) = ⟨n • x, nsmul_nonneg hx n⟩ := rfl @[simp, norm_cast] protected lemma coe_nsmul [add_monoid α] [preorder α] [covariant_class α α (+) (≤)] (n : ℕ) (a : {x : α // 0 ≤ x}) : ((n • a : {x : α // 0 ≤ x}) : α) = n • a := rfl instance ordered_add_comm_monoid [ordered_add_comm_monoid α] : ordered_add_comm_monoid {x : α // 0 ≤ x} := subtype.coe_injective.ordered_add_comm_monoid _ rfl (λ x y, rfl) (λ _ _, rfl) instance linear_ordered_add_comm_monoid [linear_ordered_add_comm_monoid α] : linear_ordered_add_comm_monoid {x : α // 0 ≤ x} := subtype.coe_injective.linear_ordered_add_comm_monoid _ rfl (λ x y, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance ordered_cancel_add_comm_monoid [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid {x : α // 0 ≤ x} := subtype.coe_injective.ordered_cancel_add_comm_monoid _ rfl (λ x y, rfl) (λ _ _, rfl) instance linear_ordered_cancel_add_comm_monoid [linear_ordered_cancel_add_comm_monoid α] : linear_ordered_cancel_add_comm_monoid {x : α // 0 ≤ x} := subtype.coe_injective.linear_ordered_cancel_add_comm_monoid _ rfl (λ x y, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- Coercion `{x : α // 0 ≤ x} → α` as a `add_monoid_hom`. -/ def coe_add_monoid_hom [ordered_add_comm_monoid α] : {x : α // 0 ≤ x} →+ α := ⟨coe, nonneg.coe_zero, nonneg.coe_add⟩ @[norm_cast] lemma nsmul_coe [ordered_add_comm_monoid α] (n : ℕ) (r : {x : α // 0 ≤ x}) : ↑(n • r) = n • (r : α) := nonneg.coe_add_monoid_hom.map_nsmul _ _ instance archimedean [ordered_add_comm_monoid α] [archimedean α] : archimedean {x : α // 0 ≤ x} := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x : α) (pos_y : (0 : α) < y) in ⟨n, show (x : α) ≤ (n • y : {x : α // 0 ≤ x}), by simp [*, -nsmul_eq_mul, nsmul_coe]⟩ ⟩ instance has_one [ordered_semiring α] : has_one {x : α // 0 ≤ x} := { one := ⟨1, zero_le_one⟩ } @[simp, norm_cast] protected lemma coe_one [ordered_semiring α] : ((1 : {x : α // 0 ≤ x}) : α) = 1 := rfl @[simp] lemma mk_eq_one [ordered_semiring α] {x : α} (hx : 0 ≤ x) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) = 1 ↔ x = 1 := subtype.ext_iff instance has_mul [ordered_semiring α] : has_mul {x : α // 0 ≤ x} := { mul := λ x y, ⟨x * y, mul_nonneg x.2 y.2⟩ } @[simp, norm_cast] protected lemma coe_mul [ordered_semiring α] (a b : {x : α // 0 ≤ x}) : ((a * b : {x : α // 0 ≤ x}) : α) = a * b := rfl @[simp] lemma mk_mul_mk [ordered_semiring α] {x y : α} (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) * ⟨y, hy⟩ = ⟨x * y, mul_nonneg hx hy⟩ := rfl instance add_monoid_with_one [ordered_semiring α] : add_monoid_with_one {x : α // 0 ≤ x} := { nat_cast := λ n, ⟨n, nat.cast_nonneg n⟩, nat_cast_zero := by simp [nat.cast], nat_cast_succ := λ _, by simp [nat.cast]; refl, .. nonneg.has_one, .. nonneg.ordered_cancel_add_comm_monoid } instance has_pow [ordered_semiring α] : has_pow {x : α // 0 ≤ x} ℕ := { pow := λ x n, ⟨x ^ n, pow_nonneg x.2 n⟩ } @[simp, norm_cast] protected lemma coe_pow [ordered_semiring α] (a : {x : α // 0 ≤ x}) (n : ℕ) : ((a ^ n: {x : α // 0 ≤ x}) : α) = a ^ n := rfl @[simp] lemma mk_pow [ordered_semiring α] {x : α} (hx : 0 ≤ x) (n : ℕ) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) ^ n = ⟨x ^ n, pow_nonneg hx n⟩ := rfl instance ordered_semiring [ordered_semiring α] : ordered_semiring {x : α // 0 ≤ x} := subtype.coe_injective.ordered_semiring _ rfl rfl (λ x y, rfl) (λ x y, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) instance ordered_comm_semiring [ordered_comm_semiring α] : ordered_comm_semiring {x : α // 0 ≤ x} := subtype.coe_injective.ordered_comm_semiring _ rfl rfl (λ x y, rfl) (λ x y, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) -- These prevent noncomputable instances being found, as it does not require `linear_order` which -- is frequently non-computable. instance monoid_with_zero [ordered_semiring α] : monoid_with_zero {x : α // 0 ≤ x} := by apply_instance instance comm_monoid_with_zero [ordered_comm_semiring α] : comm_monoid_with_zero {x : α // 0 ≤ x} := by apply_instance instance semiring [ordered_semiring α] : semiring {x : α // 0 ≤ x} := infer_instance instance comm_semiring [ordered_comm_semiring α] : comm_semiring {x : α // 0 ≤ x} := infer_instance instance nontrivial [linear_ordered_semiring α] : nontrivial {x : α // 0 ≤ x} := ⟨ ⟨0, 1, λ h, zero_ne_one (congr_arg subtype.val h)⟩ ⟩ instance linear_ordered_semiring [linear_ordered_semiring α] : linear_ordered_semiring {x : α // 0 ≤ x} := subtype.coe_injective.linear_ordered_semiring _ rfl rfl (λ x y, rfl) (λ x y, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)(λ _ _, rfl) (λ _ _, rfl) instance linear_ordered_comm_monoid_with_zero [linear_ordered_comm_ring α] : linear_ordered_comm_monoid_with_zero {x : α // 0 ≤ x} := { mul_le_mul_left := λ a b h c, mul_le_mul_of_nonneg_left h c.2, ..nonneg.linear_ordered_semiring, ..nonneg.ordered_comm_semiring } /-- Coercion `{x : α // 0 ≤ x} → α` as a `ring_hom`. -/ def coe_ring_hom [ordered_semiring α] : {x : α // 0 ≤ x} →+* α := ⟨coe, nonneg.coe_one, nonneg.coe_mul, nonneg.coe_zero, nonneg.coe_add⟩ @[simp, norm_cast] protected lemma coe_nat_cast [ordered_semiring α] (n : ℕ) : ((↑n : {x : α // 0 ≤ x}) : α) = n := map_nat_cast (coe_ring_hom : {x : α // 0 ≤ x} →+* α) n instance canonically_ordered_add_monoid [ordered_ring α] : canonically_ordered_add_monoid {x : α // 0 ≤ x} := { le_self_add := λ a b, le_add_of_nonneg_right b.2, exists_add_of_le := λ a b h, ⟨⟨b - a, sub_nonneg_of_le h⟩, subtype.ext (add_sub_cancel'_right _ _).symm⟩, ..nonneg.ordered_add_comm_monoid, ..nonneg.order_bot } instance canonically_ordered_comm_semiring [ordered_comm_ring α] [no_zero_divisors α] : canonically_ordered_comm_semiring {x : α // 0 ≤ x} := { eq_zero_or_eq_zero_of_mul_eq_zero := by { rintro ⟨a, ha⟩ ⟨b, hb⟩, simp }, ..nonneg.canonically_ordered_add_monoid, ..nonneg.ordered_comm_semiring } instance canonically_linear_ordered_add_monoid [linear_ordered_ring α] : canonically_linear_ordered_add_monoid {x : α // 0 ≤ x} := { ..subtype.linear_order _, ..nonneg.canonically_ordered_add_monoid } section linear_ordered_semifield variables [linear_ordered_semifield α] {x y : α} instance has_inv : has_inv {x : α // 0 ≤ x} := ⟨λ x, ⟨x⁻¹, inv_nonneg.mpr x.2⟩⟩ @[simp, norm_cast] protected lemma coe_inv (a : {x : α // 0 ≤ x}) : ((a⁻¹ : {x : α // 0 ≤ x}) : α) = a⁻¹ := rfl @[simp] lemma inv_mk (hx : 0 ≤ x) : (⟨x, hx⟩ : {x : α // 0 ≤ x})⁻¹ = ⟨x⁻¹, inv_nonneg.mpr hx⟩ := rfl instance has_div : has_div {x : α // 0 ≤ x} := ⟨λ x y, ⟨x / y, div_nonneg x.2 y.2⟩⟩ @[simp, norm_cast] protected lemma coe_div (a b : {x : α // 0 ≤ x}) : ((a / b : {x : α // 0 ≤ x}) : α) = a / b := rfl @[simp] lemma mk_div_mk (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) / ⟨y, hy⟩ = ⟨x / y, div_nonneg hx hy⟩ := rfl instance has_zpow : has_pow {x : α // 0 ≤ x} ℤ := ⟨λ a n, ⟨a ^ n, zpow_nonneg a.2 _⟩⟩ @[simp, norm_cast] protected lemma coe_zpow (a : {x : α // 0 ≤ x}) (n : ℤ) : ((a ^ n : {x : α // 0 ≤ x}) : α) = a ^ n := rfl @[simp] lemma mk_zpow (hx : 0 ≤ x) (n : ℤ) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) ^ n = ⟨x ^ n, zpow_nonneg hx n⟩ := rfl instance linear_ordered_semifield : linear_ordered_semifield {x : α // 0 ≤ x} := subtype.coe_injective.linear_ordered_semifield _ nonneg.coe_zero nonneg.coe_one nonneg.coe_add nonneg.coe_mul nonneg.coe_inv nonneg.coe_div (λ _ _, rfl) nonneg.coe_pow nonneg.coe_zpow nonneg.coe_nat_cast (λ _ _, rfl) (λ _ _, rfl) end linear_ordered_semifield instance linear_ordered_comm_group_with_zero [linear_ordered_field α] : linear_ordered_comm_group_with_zero {x : α // 0 ≤ x} := { inv_zero := by { ext, exact inv_zero }, mul_inv_cancel := by { intros a ha, ext, refine mul_inv_cancel (mt (λ h, _) ha), ext, exact h }, ..nonneg.nontrivial, ..nonneg.has_inv, ..nonneg.linear_ordered_comm_monoid_with_zero } instance canonically_linear_ordered_semifield [linear_ordered_field α] : canonically_linear_ordered_semifield {x : α // 0 ≤ x} := { ..nonneg.linear_ordered_semifield, ..nonneg.canonically_ordered_comm_semiring } instance floor_semiring [ordered_semiring α] [floor_semiring α] : floor_semiring {r : α // 0 ≤ r} := { floor := λ a, ⌊(a : α)⌋₊, ceil := λ a, ⌈(a : α)⌉₊, floor_of_neg := λ a ha, floor_semiring.floor_of_neg ha, gc_floor := λ a n ha, begin refine (floor_semiring.gc_floor (show 0 ≤ (a : α), from ha)).trans _, rw [←subtype.coe_le_coe, nonneg.coe_nat_cast] end, gc_ceil := λ a n, begin refine (floor_semiring.gc_ceil (a : α) n).trans _, rw [←subtype.coe_le_coe, nonneg.coe_nat_cast] end} @[norm_cast] lemma nat_floor_coe [ordered_semiring α] [floor_semiring α] (a : {r : α // 0 ≤ r}) : ⌊(a : α)⌋₊ = ⌊a⌋₊ := rfl @[norm_cast] lemma nat_ceil_coe [ordered_semiring α] [floor_semiring α] (a : {r : α // 0 ≤ r}) : ⌈(a : α)⌉₊ = ⌈a⌉₊ := rfl section linear_order variables [has_zero α] [linear_order α] /-- The function `a ↦ max a 0` of type `α → {x : α // 0 ≤ x}`. -/ def to_nonneg (a : α) : {x : α // 0 ≤ x} := ⟨max a 0, le_max_right _ _⟩ @[simp] lemma coe_to_nonneg {a : α} : (to_nonneg a : α) = max a 0 := rfl @[simp] lemma to_nonneg_of_nonneg {a : α} (h : 0 ≤ a) : to_nonneg a = ⟨a, h⟩ := by simp [to_nonneg, h] @[simp] lemma to_nonneg_coe {a : {x : α // 0 ≤ x}} : to_nonneg (a : α) = a := by { cases a with a ha, exact to_nonneg_of_nonneg ha } @[simp] lemma to_nonneg_le {a : α} {b : {x : α // 0 ≤ x}} : to_nonneg a ≤ b ↔ a ≤ b := by { cases b with b hb, simp [to_nonneg, hb] } @[simp] lemma to_nonneg_lt {a : {x : α // 0 ≤ x}} {b : α} : a < to_nonneg b ↔ ↑a < b := by { cases a with a ha, simp [to_nonneg, ha.not_lt] } instance has_sub [has_sub α] : has_sub {x : α // 0 ≤ x} := ⟨λ x y, to_nonneg (x - y)⟩ @[simp] lemma mk_sub_mk [has_sub α] {x y : α} (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) - ⟨y, hy⟩ = to_nonneg (x - y) := rfl end linear_order instance has_ordered_sub [linear_ordered_ring α] : has_ordered_sub {x : α // 0 ≤ x} := ⟨by { rintro ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, simp only [sub_le_iff_le_add, subtype.mk_le_mk, mk_sub_mk, mk_add_mk, to_nonneg_le, subtype.coe_mk]}⟩ end nonneg
f185e94b8e06772c383c9fb352d381eab7c4a2e6
137c667471a40116a7afd7261f030b30180468c2
/src/analysis/calculus/tangent_cone.lean
bb44709768540b80c33d7eb8a45a78e135a9aa17
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,768
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.convex.basic import analysis.normed_space.bounded_linear_maps import analysis.specific_limits /-! # Tangent cone In this file, we define two predicates `unique_diff_within_at 𝕜 s x` and `unique_diff_on 𝕜 s` ensuring that, if a function has two derivatives, then they have to coincide. As a direct definition of this fact (quantifying on all target types and all functions) would depend on universes, we use a more intrinsic definition: if all the possible tangent directions to the set `s` at the point `x` span a dense subset of the whole subset, it is easy to check that the derivative has to be unique. Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`, and express `unique_diff_within_at` and `unique_diff_on` in terms of it. One should however think of this definition as an implementation detail: the only reason to introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness of the derivative. This is why their names reflect their uses, and not how they are defined. ## Implementation details Note that this file is imported by `fderiv.lean`. Hence, derivatives are not defined yet. The property of uniqueness of the derivative is therefore proved in `fderiv.lean`, but based on the properties of the tangent cone we prove here. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] open filter set open_locale topological_space section tangent_cone variables {E : Type*} [add_comm_monoid E] [module 𝕜 E] [topological_space E] /-- The set of all tangent directions to the set `s` at the point `x`. -/ def tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → 𝕜) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧ (tendsto (λn, ∥c n∥) at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} /-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space. The main role of this property is to ensure that the differential within `s` at `x` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `fderiv.lean`. To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which is automatic when `E` is not `0`-dimensional). -/ @[mk_iff] structure unique_diff_within_at (s : set E) (x : E) : Prop := (dense_tangent_cone : dense ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E)) (mem_closure : x ∈ closure s) /-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of the whole space. The main role of this property is to ensure that the differential along `s` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in `fderiv.lean`. -/ def unique_diff_on (s : set E) : Prop := ∀x ∈ s, unique_diff_within_at 𝕜 s x end tangent_cone variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space ℝ G] variables {𝕜} {x y : E} {s t : set E} section tangent_cone /- This section is devoted to the properties of the tangent cone. -/ open normed_field lemma tangent_cone_univ : tangent_cone_at 𝕜 univ x = univ := begin refine univ_subset_iff.1 (λy hy, _), rcases exists_one_lt_norm 𝕜 with ⟨w, hw⟩, refine ⟨λn, w^n, λn, (w^n)⁻¹ • y, univ_mem_sets' (λn, mem_univ _), _, _⟩, { simp only [norm_pow], exact tendsto_pow_at_top_at_top_of_one_lt hw }, { convert tendsto_const_nhds, ext n, have : w ^ n * (w ^ n)⁻¹ = 1, { apply mul_inv_cancel, apply pow_ne_zero, simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm }, rw [smul_smul, this, one_smul] } end lemma tangent_cone_mono (h : s ⊆ t) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, exact ⟨c, d, mem_sets_of_superset ds (λn hn, h hn), ctop, clim⟩ end /-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone, the sequence `d` tends to 0 at infinity. -/ lemma tangent_cone_at.lim_zero {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} (hc : tendsto (λn, ∥c n∥) l at_top) (hd : tendsto (λn, c n • d n) l (𝓝 y)) : tendsto d l (𝓝 0) := begin have A : tendsto (λn, ∥c n∥⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp hc, have B : tendsto (λn, ∥c n • d n∥) l (𝓝 ∥y∥) := (continuous_norm.tendsto _).comp hd, have C : tendsto (λn, ∥c n∥⁻¹ * ∥c n • d n∥) l (𝓝 (0 * ∥y∥)) := A.mul B, rw zero_mul at C, have : ∀ᶠ n in l, ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥, { apply (eventually_ne_of_tendsto_norm_at_top hc 0).mono (λn hn, _), rw [norm_smul, ← mul_assoc, inv_mul_cancel, one_mul], rwa [ne.def, norm_eq_zero] }, have D : tendsto (λ n, ∥d n∥) l (𝓝 0) := tendsto.congr' this C, rw tendsto_zero_iff_norm_tendsto_zero, exact D end lemma tangent_cone_mono_nhds (h : 𝓝[s] x ≤ 𝓝[t] x) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, refine ⟨c, d, _, ctop, clim⟩, suffices : tendsto (λ n, x + d n) at_top (𝓝[t] x), from tendsto_principal.1 (tendsto_inf.1 this).2, refine (tendsto_inf.2 ⟨_, tendsto_principal.2 ds⟩).mono_right h, simpa only [add_zero] using tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim) end /-- Tangent cone of `s` at `x` depends only on `𝓝[s] x`. -/ lemma tangent_cone_congr (h : 𝓝[s] x = 𝓝[t] x) : tangent_cone_at 𝕜 s x = tangent_cone_at 𝕜 t x := subset.antisymm (tangent_cone_mono_nhds $ le_of_eq h) (tangent_cone_mono_nhds $ le_of_eq h.symm) /-- Intersecting with a neighborhood of the point does not change the tangent cone. -/ lemma tangent_cone_inter_nhds (ht : t ∈ 𝓝 x) : tangent_cone_at 𝕜 (s ∩ t) x = tangent_cone_at 𝕜 s x := tangent_cone_congr (nhds_within_restrict' _ ht).symm /-- The tangent cone of a product contains the tangent cone of its left factor. -/ lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y ∈ closure t) : linear_map.inl 𝕜 E F '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := begin rintros _ ⟨v, ⟨c, d, hd, hc, hy⟩, rfl⟩, have : ∀n, ∃d', y + d' ∈ t ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n, { assume n, rcases mem_closure_iff_nhds.1 ht _ (eventually_nhds_norm_smul_sub_lt (c n) y (pow_pos one_half_pos n)) with ⟨z, hz, hzt⟩, exact ⟨z - y, by simpa using hzt, by simpa using hz⟩ }, choose d' hd' using this, refine ⟨c, λn, (d n, d' n), _, hc, _⟩, show ∀ᶠ n in at_top, (x, y) + (d n, d' n) ∈ set.prod s t, { filter_upwards [hd], assume n hn, simp [hn, (hd' n).1] }, { apply tendsto.prod_mk_nhds hy _, refine squeeze_zero_norm (λn, (hd' n).2.le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } end /-- The tangent cone of a product contains the tangent cone of its right factor. -/ lemma subset_tangent_cone_prod_right {t : set F} {y : F} (hs : x ∈ closure s) : linear_map.inr 𝕜 E F '' (tangent_cone_at 𝕜 t y) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := begin rintros _ ⟨w, ⟨c, d, hd, hc, hy⟩, rfl⟩, have : ∀n, ∃d', x + d' ∈ s ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n, { assume n, rcases mem_closure_iff_nhds.1 hs _ (eventually_nhds_norm_smul_sub_lt (c n) x (pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩, exact ⟨z - x, by simpa using hzs, by simpa using hz⟩ }, choose d' hd' using this, refine ⟨c, λn, (d' n, d n), _, hc, _⟩, show ∀ᶠ n in at_top, (x, y) + (d' n, d n) ∈ set.prod s t, { filter_upwards [hd], assume n hn, simp [hn, (hd' n).1] }, { apply tendsto.prod_mk_nhds _ hy, refine squeeze_zero_norm (λn, (hd' n).2.le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } end /-- The tangent cone of a product contains the tangent cone of each factor. -/ lemma maps_to_tangent_cone_pi {ι : Type*} [decidable_eq ι] {E : ι → Type*} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {s : Π i, set (E i)} {x : Π i, E i} {i : ι} (hi : ∀ j ≠ i, x j ∈ closure (s j)) : maps_to (linear_map.single i : E i →ₗ[𝕜] Π j, E j) (tangent_cone_at 𝕜 (s i) (x i)) (tangent_cone_at 𝕜 (set.pi univ s) x) := begin rintros w ⟨c, d, hd, hc, hy⟩, have : ∀ n (j ≠ i), ∃ d', x j + d' ∈ s j ∧ ∥c n • d'∥ < (1 / 2 : ℝ) ^ n, { assume n j hj, rcases mem_closure_iff_nhds.1 (hi j hj) _ (eventually_nhds_norm_smul_sub_lt (c n) (x j) (pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩, exact ⟨z - x j, by simpa using hzs, by simpa using hz⟩ }, choose! d' hd's hcd', refine ⟨c, λ n, function.update (d' n) i (d n), hd.mono (λ n hn j hj', _), hc, tendsto_pi.2 $ λ j, _⟩, { rcases em (j = i) with rfl|hj; simp * }, { rcases em (j = i) with rfl|hj, { simp [hy] }, { suffices : tendsto (λ n, c n • d' n j) at_top (𝓝 0), by simpa [hj], refine squeeze_zero_norm (λ n, (hcd' n j hj).le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } } end /-- If a subset of a real vector space contains a segment, then the direction of this segment belongs to the tangent cone at its endpoints. -/ lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment x y ⊆ s) : y - x ∈ tangent_cone_at ℝ s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩, show x + d n ∈ segment x y, { rw segment_eq_image, refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩, { rw inv_nonneg, apply pow_nonneg, norm_num }, { apply inv_le_one, apply one_le_pow_of_one_le, norm_num }, { simp only [d, sub_smul, smul_sub, one_smul], abel } }, show filter.tendsto (λ (n : ℕ), ∥c n∥) filter.at_top filter.at_top, { have : (λ (n : ℕ), ∥c n∥) = c, by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) }, rw this, exact tendsto_pow_at_top_at_top_of_one_lt (by norm_num) }, show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)), { have : (λ (n : ℕ), c n • d n) = (λn, y - x), { ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ (by norm_num) }, rw this, apply tendsto_const_nhds } end end tangent_cone section unique_diff /-! ### Properties of `unique_diff_within_at` and `unique_diff_on` This section is devoted to properties of the predicates `unique_diff_within_at` and `unique_diff_on`. -/ lemma unique_diff_on.unique_diff_within_at {s : set E} {x} (hs : unique_diff_on 𝕜 s) (h : x ∈ s) : unique_diff_within_at 𝕜 s x := hs x h lemma unique_diff_within_at_univ : unique_diff_within_at 𝕜 univ x := by { rw [unique_diff_within_at_iff, tangent_cone_univ], simp } lemma unique_diff_on_univ : unique_diff_on 𝕜 (univ : set E) := λx hx, unique_diff_within_at_univ lemma unique_diff_on_empty : unique_diff_on 𝕜 (∅ : set E) := λ x hx, hx.elim lemma unique_diff_within_at.mono_nhds (h : unique_diff_within_at 𝕜 s x) (st : 𝓝[s] x ≤ 𝓝[t] x) : unique_diff_within_at 𝕜 t x := begin simp only [unique_diff_within_at_iff] at *, rw [mem_closure_iff_nhds_within_ne_bot] at h ⊢, exact ⟨h.1.mono $ submodule.span_mono $ tangent_cone_mono_nhds st, h.2.mono st⟩ end lemma unique_diff_within_at.mono (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) : unique_diff_within_at 𝕜 t x := h.mono_nhds $ nhds_within_mono _ st lemma unique_diff_within_at_congr (st : 𝓝[s] x = 𝓝[t] x) : unique_diff_within_at 𝕜 s x ↔ unique_diff_within_at 𝕜 t x := ⟨λ h, h.mono_nhds $ le_of_eq st, λ h, h.mono_nhds $ le_of_eq st.symm⟩ lemma unique_diff_within_at_inter (ht : t ∈ 𝓝 x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x := unique_diff_within_at_congr $ (nhds_within_restrict' _ ht).symm lemma unique_diff_within_at.inter (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝 x) : unique_diff_within_at 𝕜 (s ∩ t) x := (unique_diff_within_at_inter ht).2 hs lemma unique_diff_within_at_inter' (ht : t ∈ 𝓝[s] x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x := unique_diff_within_at_congr $ (nhds_within_restrict'' _ ht).symm lemma unique_diff_within_at.inter' (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝[s] x) : unique_diff_within_at 𝕜 (s ∩ t) x := (unique_diff_within_at_inter' ht).2 hs lemma unique_diff_within_at_of_mem_nhds (h : s ∈ 𝓝 x) : unique_diff_within_at 𝕜 s x := by simpa only [univ_inter] using unique_diff_within_at_univ.inter h lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x := unique_diff_within_at_of_mem_nhds (is_open.mem_nhds hs xs) lemma unique_diff_on.inter (hs : unique_diff_on 𝕜 s) (ht : is_open t) : unique_diff_on 𝕜 (s ∩ t) := λx hx, (hs x hx.1).inter (is_open.mem_nhds ht hx.2) lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on 𝕜 s := λx hx, is_open.unique_diff_within_at hs hx /-- The product of two sets of unique differentiability at points `x` and `y` has unique differentiability at `(x, y)`. -/ lemma unique_diff_within_at.prod {t : set F} {y : F} (hs : unique_diff_within_at 𝕜 s x) (ht : unique_diff_within_at 𝕜 t y) : unique_diff_within_at 𝕜 (set.prod s t) (x, y) := begin rw [unique_diff_within_at_iff] at ⊢ hs ht, rw [closure_prod_eq], refine ⟨_, hs.2, ht.2⟩, have : _ ≤ submodule.span 𝕜 (tangent_cone_at 𝕜 (s.prod t) (x, y)) := submodule.span_mono (union_subset (subset_tangent_cone_prod_left ht.2) (subset_tangent_cone_prod_right hs.2)), rw [linear_map.span_inl_union_inr, set_like.le_def] at this, exact (hs.1.prod ht.1).mono this end lemma unique_diff_within_at.univ_pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (x : Π i, E i) (h : ∀ i, unique_diff_within_at 𝕜 (s i) (x i)) : unique_diff_within_at 𝕜 (set.pi univ s) x := begin classical, simp only [unique_diff_within_at_iff, closure_pi_set] at h ⊢, refine ⟨(dense_pi univ (λ i _, (h i).1)).mono _, λ i _, (h i).2⟩, norm_cast, simp only [← submodule.supr_map_single, supr_le_iff, linear_map.map_span, submodule.span_le, ← maps_to'], exact λ i, (maps_to_tangent_cone_pi $ λ j hj, (h j).2).mono subset.rfl submodule.subset_span end lemma unique_diff_within_at.pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (x : Π i, E i) (I : set ι) (h : ∀ i ∈ I, unique_diff_within_at 𝕜 (s i) (x i)) : unique_diff_within_at 𝕜 (set.pi I s) x := begin classical, rw [← set.univ_pi_piecewise], refine unique_diff_within_at.univ_pi _ _ _ _ (λ i, _), by_cases hi : i ∈ I; simp [*, unique_diff_within_at_univ], end /-- The product of two sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on 𝕜 s) (ht : unique_diff_on 𝕜 t) : unique_diff_on 𝕜 (set.prod s t) := λ ⟨x, y⟩ h, unique_diff_within_at.prod (hs x h.1) (ht y h.2) /-- The finite product of a family of sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (I : set ι) (h : ∀ i ∈ I, unique_diff_on 𝕜 (s i)) : unique_diff_on 𝕜 (set.pi I s) := λ x hx, unique_diff_within_at.pi _ _ _ _ _ $ λ i hi, h i hi (x i) (hx i hi) /-- The finite product of a family of sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.univ_pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (h : ∀ i, unique_diff_on 𝕜 (s i)) : unique_diff_on 𝕜 (set.pi univ s) := unique_diff_on.pi _ _ _ _ $ λ i _, h i /-- In a real vector space, a convex set with nonempty interior is a set of unique differentiability. -/ theorem unique_diff_on_convex {s : set G} (conv : convex s) (hs : (interior s).nonempty) : unique_diff_on ℝ s := begin assume x xs, rcases hs with ⟨y, hy⟩, suffices : y - x ∈ interior (tangent_cone_at ℝ s x), { refine ⟨dense.of_closure _, subset_closure xs⟩, simp [(submodule.span ℝ (tangent_cone_at ℝ s x)).eq_top_of_nonempty_interior' ⟨y - x, interior_mono submodule.subset_span this⟩] }, rw [mem_interior_iff_mem_nhds] at hy ⊢, apply mem_sets_of_superset ((is_open_map_sub_right x).image_mem_nhds hy), rintros _ ⟨z, zs, rfl⟩, exact mem_tangent_cone_of_segment_subset (conv.segment_subset xs zs) end lemma unique_diff_on_Ici (a : ℝ) : unique_diff_on ℝ (Ici a) := unique_diff_on_convex (convex_Ici a) $ by simp only [interior_Ici, nonempty_Ioi] lemma unique_diff_on_Iic (a : ℝ) : unique_diff_on ℝ (Iic a) := unique_diff_on_convex (convex_Iic a) $ by simp only [interior_Iic, nonempty_Iio] lemma unique_diff_on_Ioi (a : ℝ) : unique_diff_on ℝ (Ioi a) := is_open_Ioi.unique_diff_on lemma unique_diff_on_Iio (a : ℝ) : unique_diff_on ℝ (Iio a) := is_open_Iio.unique_diff_on lemma unique_diff_on_Icc {a b : ℝ} (hab : a < b) : unique_diff_on ℝ (Icc a b) := unique_diff_on_convex (convex_Icc a b) $ by simp only [interior_Icc, nonempty_Ioo, hab] lemma unique_diff_on_Ico (a b : ℝ) : unique_diff_on ℝ (Ico a b) := if hab : a < b then unique_diff_on_convex (convex_Ico a b) $ by simp only [interior_Ico, nonempty_Ioo, hab] else by simp only [Ico_eq_empty hab, unique_diff_on_empty] lemma unique_diff_on_Ioc (a b : ℝ) : unique_diff_on ℝ (Ioc a b) := if hab : a < b then unique_diff_on_convex (convex_Ioc a b) $ by simp only [interior_Ioc, nonempty_Ioo, hab] else by simp only [Ioc_eq_empty hab, unique_diff_on_empty] lemma unique_diff_on_Ioo (a b : ℝ) : unique_diff_on ℝ (Ioo a b) := is_open_Ioo.unique_diff_on /-- The real interval `[0, 1]` is a set of unique differentiability. -/ lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) := unique_diff_on_Icc zero_lt_one end unique_diff
90cba0a079fe82c42ea61f2eb7971ae91b8d0789
37a833c924892ee3ecb911484775a6d6ebb8984d
/src/category_theory/graphs/category.lean
6db2b0627883630f058c03f9249fb377d163ad84
[]
no_license
silky/lean-category-theory
28126e80564a1f99e9c322d86b3f7d750da0afa1
0f029a2364975f56ac727d31d867a18c95c22fd8
refs/heads/master
1,589,555,811,646
1,554,673,665,000
1,554,673,665,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,241
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan and Scott Morrison import category_theory.category import category_theory.graphs namespace category_theory open category_theory.graphs universes u v variable {C : Type u} instance category.graph [𝒞 : category.{u v} C] : graph C := { edges := 𝒞.hom } variable [small_category C] inductive morphism_path : C → C → Type (u+1) | nil : Π (h : C), morphism_path h h | cons : Π {h s t : C} (e : h ⟶ s) (l : morphism_path s t), morphism_path h t notation a :: b := morphism_path.cons a b notation `c[` l:(foldr `, ` (h t, morphism_path.cons h t) morphism_path.nil _ `]`) := l def concatenate_paths : Π {x y z : C}, morphism_path x y → morphism_path y z → morphism_path x z | ._ ._ _ (morphism_path.nil _) q := q | ._ ._ _ (@morphism_path.cons ._ _ _ _ _ e p') q := morphism_path.cons e (concatenate_paths p' q) def category.compose_path : Π {X Y : C}, morphism_path X Y → (X ⟶ Y) | X ._ (morphism_path.nil ._) := 𝟙 X | _ _ (@morphism_path.cons ._ ._ _ _ ._ e p) := e ≫ (category.compose_path p) end category_theory
ccac0f22ab4ba9fdd814370cff47d1b965f51ddd
7541ac8517945d0f903ff5397e13e2ccd7c10573
/src/category_theory/products/associator.lean
bcf034a8ccb887a3dc8d8c95e53b13a1ddd1c1d6
[]
no_license
ramonfmir/lean-category-theory
29b6bad9f62c2cdf7517a3135e5a12b340b4ed90
be516bcbc2dc21b99df2bcb8dde0d1e8de79c9ad
refs/heads/master
1,586,110,684,637
1,541,927,184,000
1,541,927,184,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,592
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.products import category_theory.equivalence open category_theory namespace category_theory.prod universes u₁ v₁ u₂ v₂ u₃ v₃ variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C] (D : Type u₂) [𝒟 : category.{u₂ v₂} D] (E : Type u₃) [ℰ : category.{u₃ v₃} E] include 𝒞 𝒟 ℰ local attribute [tidy] tactic.assumption def associator : ((C × D) × E) ⥤ (C × (D × E)) := by tidy -- { obj := λ X, (X.1.1, (X.1.2, X.2)), -- map := λ _ _ f, (f.1.1, (f.1.2, f.2)) } -- @[simp] lemma associator_obj (X) : (associator C D E) X = (X.1.1, (X.1.2, X.2)) := rfl -- @[simp] lemma associator_map {X Y} (f : X ⟶ Y) : (associator C D E).map f = (f.1.1, (f.1.2, f.2)) := rfl def inverse_associator : (C × (D × E)) ⥤ ((C × D) × E) := by tidy -- { obj := λ X, ((X.1, X.2.1), X.2.2), -- map := λ _ _ f, ((f.1, f.2.1), f.2.2) } -- @[simp] lemma inverse_associator_obj (X) : (inverse_associator C D E) X = ((X.1, X.2.1), X.2.2) := rfl -- @[simp] lemma inverse_associator_map {X Y} (f : X ⟶ Y) : (inverse_associator C D E).map f = ((f.1, f.2.1), f.2.2) := rfl local attribute [back] category.id -- def associativity : equivalence ((C × D) × E) (C × (D × E)) := --by obviously -- times out -- { functor := associator C D E, -- inverse := inverse_associator C D E, } -- TODO pentagon natural transformation? satisfying? end category_theory.prod
9c95781c0a8d6b1361420755c1ef816c1eec39aa
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/test/monotonicity.lean
e9538ac3d8105d86161706c1515a5035a7078540
[ "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
8,589
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.monotonicity import tactic.norm_num import algebra.order.ring import measure_theory.measure.lebesgue import data.list.defs open list tactic tactic.interactive set example (h : 3 + 6 ≤ 4 + 5) : 1 + 3 + 2 + 6 ≤ 4 + 2 + 1 + 5 := begin ac_mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin ac_mono, mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin transitivity (1 + 3 + 2 - 5 : ℤ), { ac_mono }, { ac_mono }, end example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, norm_num end example (x y z a b : ℤ) (h : a ≤ (b : ℤ)) (h' : z ≤ y) : (1 + a + x) - y ≤ (1 + b + x) - z := begin transitivity (1 + a + x - z), { mono, }, { mono, mono, mono }, end example (x y z : ℤ) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin transitivity (1 + 3 + x - z), { mono }, { mono, mono, norm_num }, end example (x y z : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin ac_mono, mono* end @[simp] def list.le' {α : Type*} [has_le α] : list α → list α → Prop | (x::xs) (y::ys) := x ≤ y ∧ list.le' xs ys | [] [] := true | _ _ := false @[simp] instance list_has_le {α : Type*} [has_le α] : has_le (list α) := ⟨ list.le' ⟩ lemma list.le_refl {α : Type*} [preorder α] {xs : list α} : xs ≤ xs := begin induction xs with x xs, { trivial }, { simp [has_le.le,list.le], split, apply le_refl, apply xs_ih } end -- @[trans] lemma list.le_trans {α : Type*} [preorder α] {xs zs : list α} (ys : list α) (h : xs ≤ ys) (h' : ys ≤ zs) : xs ≤ zs := begin revert ys zs, induction xs with x xs ; intros ys zs h h' ; cases ys with y ys ; cases zs with z zs ; try { cases h ; cases h' ; done }, { apply list.le_refl }, { simp [has_le.le,list.le], split, apply le_trans h.left h'.left, apply xs_ih _ h.right h'.right, } end @[mono] lemma list_le_mono_left {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : xs ++ zs ≤ ys ++ zs := begin revert ys, induction xs with x xs ; intros ys h, { cases ys, apply list.le_refl, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, revert h, apply and.imp_right, apply xs_ih } end @[mono] lemma list_le_mono_right {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : zs ++ xs ≤ zs ++ ys := begin revert ys zs, induction xs with x xs ; intros ys zs h, { cases ys, { simp, apply list.le_refl }, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, suffices : list.le' ((zs ++ [x]) ++ xs) ((zs ++ [y]) ++ ys), { refine cast _ this, simp, }, apply list.le_trans (zs ++ [y] ++ xs), { apply list_le_mono_left, induction zs with z zs, { simp [has_le.le,list.le], apply h.left }, { simp [has_le.le,list.le], split, apply le_refl, apply zs_ih, } }, { apply xs_ih h.right, } } end lemma bar_bar' (h : [] ++ [3] ++ [2] ≤ [1] ++ [5] ++ [4]) : [] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end lemma bar_bar'' (h : [3] ++ [2] ++ [2] ≤ [5] ++ [4] ++ []) : [1] ++ ([3] ++ [2]) ++ [2] ≤ [1] ++ [5] ++ ([4] ++ []) := begin ac_mono, end lemma bar_bar (h : [3] ++ [2] ≤ [5] ++ [4]) : [1] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end def P (x : ℕ) := 7 ≤ x def Q (x : ℕ) := x ≤ 7 @[mono] lemma P_mono {x y : ℕ} (h : x ≤ y) : P x → P y := by { intro h', apply le_trans h' h } @[mono] lemma Q_mono {x y : ℕ} (h : y ≤ x) : Q x → Q y := by apply le_trans h example (x y z : ℕ) (h : x ≤ y) : P (x + z) → P (z + y) := begin ac_mono, ac_mono, end example (x y z : ℕ) (h : y ≤ x) : Q (x + z) → Q (z + y) := begin ac_mono, ac_mono, end example (x y z k m n : ℤ) (h₀ : z ≤ 0) (h₁ : y ≤ x) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : n + x + m ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono* : m + x + n ≤ y + n + m, transitivity ; [ skip , apply h₁ ], apply le_of_eq, ac_refl, end example (x y z k m n : ℤ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, success_if_fail { ac_mono }, admit }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono*, change 0 ≤ z, apply nat.zero_le, }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, change (m + x + n) * z ≤ z * (y + n + m), admit }, trivial, end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono^3, cc end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : z * (x + i + n + m) + k = z * (y + j + n + m) + k := begin congr, simp [h₁], end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono*, cc, end example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 1, end example {x y z : ℕ} : true := begin have : y + x ≤ y + z, { mono, guard_target' x ≤ z, admit }, trivial end example {x y z : ℕ} : true := begin suffices : x + y ≤ z + y, trivial, mono, guard_target' x ≤ z, admit, end example {x y z w : ℕ} : true := begin have : x + y ≤ z + w, { mono, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : ℕ} : true := begin have : x * y ≤ z * w, { mono with [0 ≤ z,0 ≤ y], { guard_target 0 ≤ z, admit }, { guard_target 0 ≤ y, admit }, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∧ y → z ∧ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∨ y → z ∨ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : ℤ} : true := begin suffices : x + y < w + z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, end example {x y z w : ℤ} : true := begin suffices : x * y < w * z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, { guard_target' 0 < y, admit }, { guard_target' 0 ≤ w, admit }, end open tactic example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 3 end example {α} [linear_order α] (a b c d e : α) : max a b ≤ e → b ≤ e := by { mono, apply le_max_right } example (a b c d e : Prop) (h : d → a) (h' : c → e) : (a ∧ b → c) ∨ d → (d ∧ b → e) ∨ a := begin mono, mono, mono, end example : ∫ x in Icc 0 1, real.exp x ≤ ∫ x in Icc 0 1, real.exp (x+1) := begin mono, { exact real.continuous_exp.integrable_on_compact is_compact_Icc }, { exact (real.continuous_exp.comp $ continuous_add_right 1).integrable_on_compact is_compact_Icc }, intro x, dsimp only, mono, linarith end
33bf6be2d7b752af5b3bf6fbb3d725eb4c558a6f
28b6e1a13d35e9b450f65c001660f4ec4713aa10
/Search/Algorithm/BestFirst.lean
11d4690b97a1e8ce8daa29b54e83c58a0473b33c
[ "Apache-2.0" ]
permissive
dselsam/search
14e3af3261a7a70f8e5885db9722b186f96fe1f5
67003b859d2228d291a3873af6279c1f61430c64
refs/heads/master
1,684,700,794,306
1,614,294,810,000
1,614,294,810,000
339,578,823
1
0
null
null
null
null
UTF-8
Lean
false
false
1,944
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Search.Transform.Classic import Search.Heuristic import Search.SaveRestore namespace Search namespace Algorithm namespace BestFirst variable {m : Type → Type} {α : Type} variable [Inhabited α] [Monad m] [MonadLiftT IO m] def bestFirst (ϕ : Heuristic m (SearchT m α)) (ψ : SearchT m α) (fuel : Nat := 1000) : m (Option α) := do let mut todo : Array (SearchT m α) := #[ψ] for _ in [:fuel] do if todo.isEmpty then return none let ψ := todo.back todo := todo.pop match (← ψ.unpack) with | Status.done x => return some x | Status.choice ψs => let scores ← ϕ.score ψs println! " [scores] {repr scores}" -- TODO: insert into PQ (for now just want to collect funs) todo := todo ++ ψs.reverse return none variable {σ : Type} [Inhabited σ] [SaveRestore m σ] def bestFirstRestoring (ϕ : Heuristic m (SearchT m α)) (ψ : SearchT m α) (fuel : Nat := 1000) : m (Option (σ × α)) := do let mut todo : Array (σ × SearchT m α) := #[(← save, ψ)] for _ in [:fuel] do if todo.isEmpty then return none let (s, ψ) := todo.back todo := todo.pop match ← (restore s *> ψ.unpack) with | Status.done x => return some (← save, x) | Status.choice ψs => let s ← save -- Note: we do not inspect on the `restore` step -- We advocate explicitly summarizing the state, and relying on `inspect` only for -- the downstream computation. let scores ← ϕ.score ψs println! " [scores] {repr scores}" -- TODO: insert into PQ (for now just want to collect funs) todo := todo ++ ψs.reverse.map λ ψ => (s, ψ) return none end BestFirst end Algorithm export Algorithm.BestFirst (bestFirst bestFirstRestoring) end Search
281742544aa5723d0e4c606b774dbd624c1c4759
c777c32c8e484e195053731103c5e52af26a25d1
/src/category_theory/functor/category.lean
bf73ec5a9f3f1c6b3fd4ebc313564eb3b6f765ac
[ "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
5,396
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.natural_transformation import category_theory.isomorphism /-! # The category of functors and natural transformations between two fixed categories. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We provide the category instance on `C ⥤ D`, with morphisms the natural transformations. ## Universes If `C` and `D` are both small categories at the same universe level, this is another small category at that level. However if `C` and `D` are both large categories at the same universe level, this is a small category at the next higher level. -/ namespace category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ u₁ u₂ u₃ open nat_trans category category_theory.functor variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] local attribute [simp] vcomp_app /-- `functor.category C D` gives the category structure on functors and natural transformations between categories `C` and `D`. Notice that if `C` and `D` are both small categories at the same universe level, this is another small category at that level. However if `C` and `D` are both large categories at the same universe level, this is a small category at the next higher level. -/ instance functor.category : category.{(max u₁ v₂)} (C ⥤ D) := { hom := λ F G, nat_trans F G, id := λ F, nat_trans.id F, comp := λ _ _ _ α β, vcomp α β } variables {C D} {E : Type u₃} [category.{v₃} E] variables {F G H I : C ⥤ D} namespace nat_trans @[simp] lemma vcomp_eq_comp (α : F ⟶ G) (β : G ⟶ H) : vcomp α β = α ≫ β := rfl lemma vcomp_app' (α : F ⟶ G) (β : G ⟶ H) (X : C) : (α ≫ β).app X = (α.app X) ≫ (β.app X) := rfl lemma congr_app {α β : F ⟶ G} (h : α = β) (X : C) : α.app X = β.app X := by rw h @[simp] lemma id_app (F : C ⥤ D) (X : C) : (𝟙 F : F ⟶ F).app X = 𝟙 (F.obj X) := rfl @[simp] lemma comp_app {F G H : C ⥤ D} (α : F ⟶ G) (β : G ⟶ H) (X : C) : (α ≫ β).app X = α.app X ≫ β.app X := rfl lemma app_naturality {F G : C ⥤ (D ⥤ E)} (T : F ⟶ G) (X : C) {Y Z : D} (f : Y ⟶ Z) : ((F.obj X).map f) ≫ ((T.app X).app Z) = ((T.app X).app Y) ≫ ((G.obj X).map f) := (T.app X).naturality f lemma naturality_app {F G : C ⥤ (D ⥤ E)} (T : F ⟶ G) (Z : D) {X Y : C} (f : X ⟶ Y) : ((F.map f).app Z) ≫ ((T.app Y).app Z) = ((T.app X).app Z) ≫ ((G.map f).app Z) := congr_fun (congr_arg app (T.naturality f)) Z /-- A natural transformation is a monomorphism if each component is. -/ lemma mono_of_mono_app (α : F ⟶ G) [∀ (X : C), mono (α.app X)] : mono α := ⟨λ H g h eq, by { ext X, rw [←cancel_mono (α.app X), ←comp_app, eq, comp_app] }⟩ /-- A natural transformation is an epimorphism if each component is. -/ lemma epi_of_epi_app (α : F ⟶ G) [∀ (X : C), epi (α.app X)] : epi α := ⟨λ H g h eq, by { ext X, rw [←cancel_epi (α.app X), ←comp_app, eq, comp_app] }⟩ /-- `hcomp α β` is the horizontal composition of natural transformations. -/ @[simps] def hcomp {H I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) : (F ⋙ H) ⟶ (G ⋙ I) := { app := λ X : C, (β.app (F.obj X)) ≫ (I.map (α.app X)), naturality' := λ X Y f, begin rw [functor.comp_map, functor.comp_map, ←assoc, naturality, assoc, ←map_comp I, naturality, map_comp, assoc] end } infix ` ◫ `:80 := hcomp @[simp] lemma hcomp_id_app {H : D ⥤ E} (α : F ⟶ G) (X : C) : (α ◫ 𝟙 H).app X = H.map (α.app X) := by {dsimp, simp} -- See note [dsimp, simp]. lemma id_hcomp_app {H : E ⥤ C} (α : F ⟶ G) (X : E) : (𝟙 H ◫ α).app X = α.app _ := by simp -- Note that we don't yet prove a `hcomp_assoc` lemma here: even stating it is painful, because we -- need to use associativity of functor composition. (It's true without the explicit associator, -- because functor composition is definitionally associative, -- but relying on the definitional equality causes bad problems with elaboration later.) lemma exchange {I J K : D ⥤ E} (α : F ⟶ G) (β : G ⟶ H) (γ : I ⟶ J) (δ : J ⟶ K) : (α ≫ β) ◫ (γ ≫ δ) = (α ◫ γ) ≫ (β ◫ δ) := by ext; simp end nat_trans open nat_trans namespace functor /-- Flip the arguments of a bifunctor. See also `currying.lean`. -/ @[simps] protected def flip (F : C ⥤ (D ⥤ E)) : D ⥤ (C ⥤ E) := { obj := λ k, { obj := λ j, (F.obj j).obj k, map := λ j j' f, (F.map f).app k, map_id' := λ X, begin rw category_theory.functor.map_id, refl end, map_comp' := λ X Y Z f g, by rw [map_comp, ←comp_app] }, map := λ c c' f, { app := λ j, (F.obj j).map f } }. end functor @[simp, reassoc] lemma map_hom_inv_app (F : C ⥤ D ⥤ E) {X Y : C} (e : X ≅ Y) (Z : D) : (F.map e.hom).app Z ≫ (F.map e.inv).app Z = 𝟙 _ := by simp [← nat_trans.comp_app, ← functor.map_comp] @[simp, reassoc] lemma map_inv_hom_app (F : C ⥤ D ⥤ E) {X Y : C} (e : X ≅ Y) (Z : D) : (F.map e.inv).app Z ≫ (F.map e.hom).app Z = 𝟙 _ := by simp [← nat_trans.comp_app, ← functor.map_comp] end category_theory
b39fbf169826121ce1c41032ffd87f99d9a221ef
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/instances/kleisli.lean
3f6b6d76fc833ead1cdb156e0f21f469065fdf29
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
1,186
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon The Kleisli construction on the Type category -/ import category_theory.category universes u v namespace category_theory def Kleisli (m) [monad.{u v} m] := Type u def Kleisli.mk (m) [monad.{u v} m] (α : Type u) : Kleisli m := α instance Kleisli.category_struct {m} [monad m] : category_struct (Kleisli m) := { hom := λ α β, α → m β, id := λ α x, (pure x : m α), comp := λ X Y Z f g, f >=> g } instance Kleisli.category {m} [monad m] [is_lawful_monad m] : category (Kleisli m) := by refine { hom := λ α β, α → m β, id := λ α x, (pure x : m α), comp := λ X Y Z f g, f >=> g, id_comp' := _, comp_id' := _, assoc' := _ }; intros; ext; simp only [(>=>)] with functor_norm @[simp] lemma Kleisli.id_def {m} [monad m] [is_lawful_monad m] (α : Kleisli m) : 𝟙 α = @pure m _ α := rfl lemma Kleisli.comp_def {m} [monad m] [is_lawful_monad m] (α β γ : Kleisli m) (xs : α ⟶ β) (ys : β ⟶ γ) (a : α) : (xs ≫ ys) a = xs a >>= ys := rfl end category_theory
4d8885029c838238aa9fc0b386f27efff8a7c6e1
d642a6b1261b2cbe691e53561ac777b924751b63
/src/analysis/calculus/times_cont_diff.lean
5182bb6fcda03abd2f9565f716cbca5035928f64
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
39,741
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.fderiv /-! # Higher differentiability A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the n-th derivative of a function at the (n-1)-th derivative of the derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the field, `n` is the number of iterations, `f` is the function and `x` is the point. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `times_cont_diff 𝕜 n f` and `times_cont_diff_on 𝕜 n f s` saying that the function is `C^n`, respectively in the whole space or on the set `s`. We prove basic properties of these notions. ## Implementation notes The n-th derivative of a function belongs to the space E →L[𝕜] (E →L[𝕜] (E ... F)...))), where there are n iterations of `E →L[𝕜]`. We define this space inductively, call it `iterated_continuous_linear_map 𝕜 n E F`, and denote it by `E [×n]→L[𝕜] F`. We can define it inductively either from the left (i.e., saying that the (n+1)-th space S_{n+1} is E →L[𝕜] S_n) or from the right (i.e., saying that the (n+1)-th space associated to F, denoted by S_{n+1} (F), is equal to S_n (E →L[𝕜] F)). For proofs, it turns out to be more convenient to use the latter approach (from the right), as it means to prove things at the (n+1)-th step we only need to understand well enough the derivative in E →L[𝕜] F (contrary to the approach from the left, where one would need to know enough on the n-th derivative to deduce things on the (n+1)-th derivative). In other words, one could define the (n+1)-th derivative either as the derivative of the n-th derivative, or as the n-th derivative of the derivative. We use the latter definition. A difficulty is related to universes: the first and second spaces in the sequence, for n=0 and 1, are F and E →L[𝕜] F. If E has universe u and F has universe v, then the first one lives in v and the second one in max v u. Since they should live in the same universe (as all the other spaces in the construction), it means that at the 0-th step we should not use F, but ulift it to universe max v u. But we should also ulift its vector space structure and its normed space structure. This can certainly be done, but I decided it was not worth it for now. Therefore, the definition is only made when E and F live in the same universe. Regarding the definition of `C^n` functions, there are two equivalent definitions: * require by induction that the function is differentiable, and that its derivative is C^{n-1} * or require that, for all m ≤ n, the m-th derivative is continuous, and for all m < n the m-th derivative is differentiable. The first definition is more efficient for many proofs by induction. The second definition is more satisfactory as it gives concrete information about the n-th derivative (contrary to the first point of view), and moreover it also makes sense for n = ∞. Therefore, we give (and use) both definitions, named respectively `times_cont_diff_rec` and `times_cont_diff` (as well as relativized versions on a set). We show that they are equivalent. The first one is mainly auxiliary: in applications, one should always use `times_cont_diff` (but the proofs below use heavily the equivalence to show that `times_cont_diff` is well behaved). ## Tags derivative, differentiability, higher derivative, C^n -/ noncomputable theory local attribute [instance, priority 10] classical.decidable_inhabited classical.prop_decidable universes u v w open set variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type u} [normed_group E] [normed_space 𝕜 E] {F : Type u} [normed_group F] [normed_space 𝕜 F] {G : Type u} [normed_group G] [normed_space 𝕜 G] {s s₁ u : set E} {f f₁ : E → F} {f' f₁' : E →L[𝕜] F} {f₂ : E → G} {f₂' : E →L[𝕜] G} {g : F → G} {x : E} {c : F} {L : filter E} {t : set F} {b : E × F → G} {sb : set (E × F)} {p : E × F} {n : ℕ} include 𝕜 /-- The space `iterated_continuous_linear_map 𝕜 n E F` is the space E →L[𝕜] (E →L[𝕜] (E ... F)...))), defined inductively over `n`. This is the space to which the `n`-th derivative of a function naturally belongs. It is only defined when `E` and `F` live in the same universe. -/ def iterated_continuous_linear_map (𝕜 : Type w) [nondiscrete_normed_field 𝕜] : Π (n : ℕ) (E : Type u) [gE : normed_group E] [@normed_space 𝕜 E _ gE] (F : Type u) [gF : normed_group F] [@normed_space 𝕜 F _ gF], Type u | 0 E _ _ F _ _ := F | (n+1) E _ _ F _ _ := by { resetI, exact iterated_continuous_linear_map n E (E →L[𝕜] F) } notation E `[×`:25 n `]→L[`:25 𝕜 `] ` F := iterated_continuous_linear_map 𝕜 n E F /-- Define by induction a normed group structure on the space of iterated continuous linear maps. To avoid `resetI` in the statement, use the @ version with all parameters. As the equation compiler chokes on this one, we use the `nat.rec_on` version. -/ def iterated_continuous_linear_map.normed_group_rec (𝕜 : Type w) [h𝕜 : nondiscrete_normed_field 𝕜] (n : ℕ) (E : Type u) [gE : normed_group E] [sE : normed_space 𝕜 E] : ∀(F : Type u) [nF : normed_group F] [sF : @normed_space 𝕜 F _ nF], normed_group (@iterated_continuous_linear_map 𝕜 h𝕜 n E gE sE F nF sF) := nat.rec_on n (λF nF sF, nF) (λn aux_n F nF sF, by { resetI, apply aux_n }) /-- Define by induction a normed space structure on the space of iterated continuous linear maps. To avoid `resetI` in the statement, use the @ version with all parameters. As the equation compiler chokes on this one, we use the `nat.rec_on` version. -/ def iterated_continuous_linear_map.normed_space_rec (𝕜 : Type w) [h𝕜 : nondiscrete_normed_field 𝕜] (n : ℕ) (E : Type u) [gE : normed_group E] [sE : normed_space 𝕜 E] : ∀(F : Type u) [nF : normed_group F] [sF : @normed_space 𝕜 F _ nF], @normed_space 𝕜 (@iterated_continuous_linear_map 𝕜 h𝕜 n E gE sE F nF sF) _ (@iterated_continuous_linear_map.normed_group_rec 𝕜 h𝕜 n E gE sE F nF sF) := nat.rec_on n (λF nF sF, sF) (λn aux_n F nF sF, by { resetI, apply aux_n }) /-- Explicit normed group structure on the space of iterated continuous linear maps. -/ instance iterated_continuous_linear_map.normed_group (n : ℕ) (𝕜 : Type w) [h𝕜 : nondiscrete_normed_field 𝕜] (E : Type u) [gE : normed_group E] [sE : normed_space 𝕜 E] (F : Type u) [gF : normed_group F] [sF : normed_space 𝕜 F] : normed_group (E [×n]→L[𝕜] F) := iterated_continuous_linear_map.normed_group_rec 𝕜 n E F /-- Explicit normed space structure on the space of iterated continuous linear maps. -/ instance iterated_continuous_linear_map.normed_space (n : ℕ) (𝕜 : Type w) [h𝕜 : nondiscrete_normed_field 𝕜] (E : Type u) [gE : normed_group E] [sE : normed_space 𝕜 E] (F : Type u) [gF : normed_group F] [sF : normed_space 𝕜 F] : normed_space 𝕜 (E [×n]→L[𝕜] F) := iterated_continuous_linear_map.normed_space_rec 𝕜 n E F /-- The n-th derivative of a function, defined inductively by saying that the (n+1)-th derivative of f is the n-th derivative of the derivative of f. -/ def iterated_fderiv (𝕜 : Type w) [h𝕜 : nondiscrete_normed_field 𝕜] (n : ℕ) {E : Type u} [gE : normed_group E] [sE : normed_space 𝕜 E] : ∀{F : Type u} [gF : normed_group F] [sF : @normed_space 𝕜 F _ gF] (f : E → F), E → @iterated_continuous_linear_map 𝕜 h𝕜 n E gE sE F gF sF := nat.rec_on n (λF gF sF f, f) (λn rec F gF sF f, by { resetI, exact rec (fderiv 𝕜 f) }) @[simp] lemma iterated_fderiv_zero : iterated_fderiv 𝕜 0 f = f := rfl @[simp] lemma iterated_fderiv_succ : iterated_fderiv 𝕜 (n+1) f = (iterated_fderiv 𝕜 n (λx, fderiv 𝕜 f x) : _) := rfl /-- The n-th derivative of a function along a set, defined inductively by saying that the (n+1)-th derivative of f is the n-th derivative of the derivative of f. -/ def iterated_fderiv_within (𝕜 : Type w) [h𝕜 :nondiscrete_normed_field 𝕜] (n : ℕ) {E : Type u} [gE : normed_group E] [sE : normed_space 𝕜 E] : ∀{F : Type u} [gF : normed_group F] [sF : @normed_space 𝕜 F _ gF] (f : E → F) (s : set E), E → @iterated_continuous_linear_map 𝕜 h𝕜 n E gE sE F gF sF := nat.rec_on n (λF gF sF f s, f) (λn rec F gF sF f s, by { resetI, exact rec (fderiv_within 𝕜 f s) s}) @[simp] lemma iterated_fderiv_within_zero : iterated_fderiv_within 𝕜 0 f s = f := rfl @[simp] lemma iterated_fderiv_within_succ : iterated_fderiv_within 𝕜 (n+1) f s = (iterated_fderiv_within 𝕜 n (λx, fderiv_within 𝕜 f s x) s : _) := rfl theorem iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F, { refl }, { simp [IH] } end /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr (hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f x, { simp [hL x hx] }, { simp only [iterated_fderiv_within_succ], refine IH (λy hy, _) hx, apply fderiv_within_congr (hs y hy) hL (hL y hy) } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open (xu : x ∈ u) (hu : is_open u) (xs : x ∈ s) (hs : unique_diff_on 𝕜 (s ∩ u)) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { simp }, { simp, rw ← IH, apply iterated_fderiv_within_congr hs (λy hy, _) ⟨xs, xu⟩, apply fderiv_within_inter (mem_nhds_sets hu hy.2), have := hs y hy, rwa unique_diff_within_at_inter (mem_nhds_sets hu hy.2) at this } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter (hu : u ∈ nhds x) (xs : x ∈ s) (hs : unique_diff_on 𝕜 s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin rcases mem_nhds_sets_iff.1 hu with ⟨v, vu, v_open, xv⟩, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu yv⟩, yv⟩ }, have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter_open xv v_open xs (hs.inter v_open), rw ← this, have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open xv v_open ⟨xs, mem_of_nhds hu⟩ _, rw A, exact hs.inter v_open }, rw A at this, rw ← this end /-- Auxiliary definition defining `C^n` functions by induction over `n`. In applications, use `times_cont_diff` instead. -/ def times_cont_diff_rec (𝕜 : Type w) [nondiscrete_normed_field 𝕜] : Π (n : ℕ) {E : Type u} [gE : normed_group E] [@normed_space 𝕜 E _ gE] {F : Type u} [gF : normed_group F] [@normed_space 𝕜 F _ gF] (f : E → F), Prop | 0 E _ _ F _ _ f := by { resetI, exact continuous f } | (n+1) E _ _ F _ _ f := by { resetI, exact differentiable 𝕜 f ∧ times_cont_diff_rec n (fderiv 𝕜 f) } @[simp] lemma times_cont_diff_rec_zero : times_cont_diff_rec 𝕜 0 f ↔ continuous f := by refl @[simp] lemma times_cont_diff_rec_succ : times_cont_diff_rec 𝕜 n.succ f ↔ differentiable 𝕜 f ∧ times_cont_diff_rec 𝕜 n (λx, fderiv 𝕜 f x) := by refl lemma times_cont_diff_rec.of_succ (h : times_cont_diff_rec 𝕜 n.succ f) : times_cont_diff_rec 𝕜 n f := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F, { exact h.1.continuous }, { rw times_cont_diff_rec_succ at h ⊢, exact ⟨h.1, IH h.2⟩ } end lemma times_cont_diff_rec.continuous (h : times_cont_diff_rec 𝕜 n f) : continuous (iterated_fderiv 𝕜 n f) := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { exact h }, { rw iterated_fderiv_succ, exact IH (times_cont_diff_rec_succ.1 h).2 } end lemma times_cont_diff_rec.differentiable (h : times_cont_diff_rec 𝕜 (n+1) f) : differentiable 𝕜 (iterated_fderiv 𝕜 n f) := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { exact h.1 }, { rw iterated_fderiv_succ, apply IH h.2 } end /-- Auxiliary definition defining `C^n` functions on a set by induction over `n`. In applications, use `times_cont_diff_on` instead. -/ def times_cont_diff_on_rec (𝕜 : Type w) [nondiscrete_normed_field 𝕜] : Π (n : ℕ) {E : Type u} [gE : normed_group E] [@normed_space 𝕜 E _ gE] {F : Type u} [gF : normed_group F] [@normed_space 𝕜 F _ gF] (f : E → F) (s : set E), Prop | 0 E _ _ F _ _ f s := by { resetI, exact continuous_on f s } | (n+1) E _ _ F _ _ f s := by { resetI, exact differentiable_on 𝕜 f s ∧ times_cont_diff_on_rec n (fderiv_within 𝕜 f s) s} @[simp] lemma times_cont_diff_on_rec_zero : times_cont_diff_on_rec 𝕜 0 f s ↔ continuous_on f s := by refl @[simp] lemma times_cont_diff_on_rec_succ : times_cont_diff_on_rec 𝕜 n.succ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on_rec 𝕜 n (λx, fderiv_within 𝕜 f s x) s := by refl lemma times_cont_diff_on_rec.of_succ (h : times_cont_diff_on_rec 𝕜 n.succ f s) : times_cont_diff_on_rec 𝕜 n f s := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F, { exact h.1.continuous_on }, { rw times_cont_diff_on_rec_succ at h ⊢, exact ⟨h.1, IH h.2⟩ } end lemma times_cont_diff_on_rec.continuous_on_iterated_fderiv_within (h : times_cont_diff_on_rec 𝕜 n f s) : continuous_on (iterated_fderiv_within 𝕜 n f s) s := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { exact h }, { rw iterated_fderiv_within_succ, exact IH (times_cont_diff_on_rec_succ.1 h).2 } end lemma times_cont_diff_on_rec.differentiable_on (h : times_cont_diff_on_rec 𝕜 (n+1) f s) : differentiable_on 𝕜 (iterated_fderiv_within 𝕜 n f s) s := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { exact h.1 }, { rw iterated_fderiv_within_succ, apply IH h.2 } end lemma times_cont_diff_on_rec_univ : times_cont_diff_on_rec 𝕜 n f univ ↔ times_cont_diff_rec 𝕜 n f := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { rw [times_cont_diff_on_rec_zero, times_cont_diff_rec_zero, continuous_iff_continuous_on_univ] }, { rw [times_cont_diff_on_rec_succ, times_cont_diff_rec_succ, differentiable_on_univ, fderiv_within_univ, IH] } end /-- A function is `C^n` on a set, for `n : with_top ℕ`, if its derivatives of order at most `n` are all well defined and continuous. -/ def times_cont_diff_on (𝕜 : Type w) [nondiscrete_normed_field 𝕜] (n : with_top ℕ) {E F : Type u} [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] (f : E → F) (s : set E) := (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous_on (iterated_fderiv_within 𝕜 m f s) s) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) @[simp] lemma times_cont_diff_on_zero : times_cont_diff_on 𝕜 0 f s ↔ continuous_on f s := by simp [times_cont_diff_on] /-- The two definitions of `C^n` functions on domains, directly in terms of continuity of all derivatives, or by induction, are equivalent. -/ theorem times_cont_diff_on_iff_times_cont_diff_on_rec : times_cont_diff_on 𝕜 n f s ↔ times_cont_diff_on_rec 𝕜 n f s := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { rw [with_top.coe_zero, times_cont_diff_on_rec_zero, times_cont_diff_on_zero] }, { split, { assume H, rw times_cont_diff_on_rec_succ, refine ⟨H.2 0 (by simp only [with_top.zero_lt_coe, with_top.coe_zero, nat.succ_pos n]), _⟩, rw ← IH, split, { assume m hm, have : (m.succ : with_top nat) ≤ n.succ := with_top.coe_le_coe.2 (nat.succ_le_succ (with_top.coe_le_coe.1 hm)), exact H.1 _ this }, { assume m hm, have : (m.succ : with_top nat) < n.succ := with_top.coe_lt_coe.2 (nat.succ_le_succ (with_top.coe_lt_coe.1 hm)), exact H.2 _ this } }, { assume H, split, { assume m hm, simp only [with_top.coe_le_coe] at hm, cases nat.of_le_succ hm with h h, { have := H.of_succ, rw ← IH at this, exact this.1 _ (with_top.coe_le_coe.2 h) }, { rw h, simp at H, exact H.2.continuous_on_iterated_fderiv_within } }, { assume m hm, simp only [with_top.coe_lt_coe] at hm, cases nat.of_le_succ hm with h h, { have := H.of_succ, rw ← IH at this, exact this.2 _ (with_top.coe_lt_coe.2 h) }, { rw nat.succ_inj h, exact H.differentiable_on } } } }, end /- Next lemma is marked as a simp lemma as `C^(n+1)` functions appear mostly in inductions. -/ @[simp] lemma times_cont_diff_on_succ : times_cont_diff_on 𝕜 n.succ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λx, fderiv_within 𝕜 f s x) s := by simp [times_cont_diff_on_iff_times_cont_diff_on_rec] lemma times_cont_diff_on.of_le {m n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (le : m ≤ n) : times_cont_diff_on 𝕜 m f s := ⟨λp hp, h.1 p (le_trans hp le), λp hp, h.2 p (lt_of_lt_of_le hp le)⟩ lemma times_cont_diff_on.of_succ (h : times_cont_diff_on 𝕜 n.succ f s) : times_cont_diff_on 𝕜 n f s := h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)) lemma times_cont_diff_on.continuous_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) : continuous_on f s := h.1 0 (by simp) lemma times_cont_diff_on.continuous_on_fderiv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : continuous_on (fderiv_within 𝕜 f s) s := h.1 1 hn /-- If a function is at least C^1 on a set, it is differentiable there. -/ lemma times_cont_diff_on.differentiable_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := begin refine h.2 0 _, refine lt_of_lt_of_le _ hn, change ((0 : ℕ) : with_top ℕ) < (1 : ℕ), rw with_top.coe_lt_coe, exact zero_lt_one end set_option class.instance_max_depth 50 /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff_on.continuous_on_fderiv_within_apply {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (set.prod s univ) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (set.prod s univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact continuous_on.comp (h.continuous_on_fderiv_within hn) continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, exact A.comp_continuous_on B end lemma times_cont_diff_on_top : times_cont_diff_on 𝕜 ⊤ f s ↔ (∀n:ℕ, times_cont_diff_on 𝕜 n f s) := begin split, { assume h n, exact h.of_le lattice.le_top }, { assume h, split, { exact λm hm, (h m).1 m (le_refl _) }, { exact λ m hm, (h m.succ).2 m (with_top.coe_lt_coe.2 (lt_add_one m)) } } end lemma times_cont_diff_on_fderiv_within_nat {m n : ℕ} (hf : times_cont_diff_on 𝕜 n f s) (h : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λx, fderiv_within 𝕜 f s x) s := begin have : times_cont_diff_on 𝕜 m.succ f s := hf.of_le (with_top.coe_le_coe.2 h), exact (times_cont_diff_on_succ.1 this).2 end lemma times_cont_diff_on_fderiv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (h : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λx, fderiv_within 𝕜 f s x) s := begin cases m, { change ⊤ + 1 ≤ n at h, have : n = ⊤, by simpa using h, rw this at hf, change times_cont_diff_on 𝕜 ⊤ (λ (x : E), fderiv_within 𝕜 f s x) s, rw times_cont_diff_on_top at ⊢ hf, exact λm, times_cont_diff_on_fderiv_within_nat (hf (m + 1)) (le_refl _) }, { have : times_cont_diff_on 𝕜 (m + 1) f s := hf.of_le h, exact times_cont_diff_on_fderiv_within_nat this (le_refl _) } end lemma times_cont_diff_on.congr_mono {n : with_top ℕ} (H : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s₁) (h : ∀x ∈ s₁, f₁ x = f x) (h₁ : s₁ ⊆ s) : times_cont_diff_on 𝕜 n f₁ s₁ := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing F, { rw times_cont_diff_on_zero at H ⊢, exact continuous_on.congr_mono H h h₁ }, { rw times_cont_diff_on_succ at H ⊢, refine ⟨differentiable_on.congr_mono H.1 h h₁, IH H.2 (λx hx, _)⟩, apply differentiable_within_at.fderiv_within_congr_mono (H.1 x (h₁ hx)) h (h x hx) (hs x hx) h₁ }, { rw times_cont_diff_on_top at H ⊢, assume n, exact Itop n (H n) h } end lemma times_cont_diff_on.congr {n : with_top ℕ} {s : set E} (H : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (h : ∀x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s := times_cont_diff_on.congr_mono H hs h (subset.refl _) lemma times_cont_diff_on.congr_mono' {n m : with_top ℕ} {s : set E} (H : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s₁) (h : ∀x ∈ s₁, f₁ x = f x) (h₁ : s₁ ⊆ s) (le : m ≤ n) : times_cont_diff_on 𝕜 m f₁ s₁ := times_cont_diff_on.of_le (H.congr_mono hs h h₁) le lemma times_cont_diff_on.mono {n : with_top ℕ} {s t : set E} (h : times_cont_diff_on 𝕜 n f t) (hst : s ⊆ t) (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s := times_cont_diff_on.congr_mono h hs (λx hx, rfl) hst /-- Being `C^n` is a local property. -/ lemma times_cont_diff_on_of_locally_times_cont_diff_on {n : with_top ℕ} {s : set E} (hs : unique_diff_on 𝕜 s) (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_diff_on 𝕜 n f (s ∩ u)) : times_cont_diff_on 𝕜 n f s := begin split, { assume m hm, apply continuous_on_of_locally_continuous_on (λx hx, _), rcases h x hx with ⟨u, u_open, xu, hu⟩, refine ⟨u, u_open, xu,_⟩, apply continuous_on.congr_mono (hu.1 m hm) (λy hy, _) (subset.refl _), symmetry, exact iterated_fderiv_within_inter_open hy.2 u_open hy.1 (hs.inter u_open) }, { assume m hm, apply differentiable_on_of_locally_differentiable_on (λx hx, _), rcases h x hx with ⟨u, u_open, xu, hu⟩, refine ⟨u, u_open, xu,_⟩, apply differentiable_on.congr_mono (hu.2 m hm) (λy hy, _) (subset.refl _), symmetry, exact iterated_fderiv_within_inter_open hy.2 u_open hy.1 (hs.inter u_open) } end /-- A function is `C^n`, for `n : with_top ℕ`, if its derivatives of order at most `n` are all well defined and continuous. -/ def times_cont_diff (𝕜 : Type w) [nondiscrete_normed_field 𝕜] (n : with_top ℕ) {E F : Type u} [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] (f : E → F) := (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous (iterated_fderiv 𝕜 m f )) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) lemma times_cont_diff_on_univ {n : with_top ℕ} : times_cont_diff_on 𝕜 n f univ ↔ times_cont_diff 𝕜 n f := by simp [times_cont_diff_on, times_cont_diff, iterated_fderiv_within_univ, continuous_iff_continuous_on_univ, differentiable_on_univ] @[simp] lemma times_cont_diff_zero : times_cont_diff 𝕜 0 f ↔ continuous f := by simp [times_cont_diff] theorem times_cont_diff_iff_times_cont_diff_rec : times_cont_diff 𝕜 n f ↔ times_cont_diff_rec 𝕜 n f := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_rec_univ.symm, times_cont_diff_on_iff_times_cont_diff_on_rec] @[simp] lemma times_cont_diff_succ : times_cont_diff 𝕜 n.succ f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 n (λx, fderiv 𝕜 f x) := by simp [times_cont_diff_iff_times_cont_diff_rec] lemma times_cont_diff.of_le {m n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (le : m ≤ n) : times_cont_diff 𝕜 m f := ⟨λp hp, h.1 p (le_trans hp le), λp hp, h.2 p (lt_of_lt_of_le hp le)⟩ lemma times_cont_diff.of_succ (h : times_cont_diff 𝕜 n.succ f) : times_cont_diff 𝕜 n f := h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)) lemma times_cont_diff.continuous {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : continuous f := h.1 0 (by simp) lemma times_cont_diff.continuous_fderiv {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (fderiv 𝕜 f) := h.1 1 hn lemma times_cont_diff.continuous_fderiv_apply {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end lemma times_cont_diff_top : times_cont_diff 𝕜 ⊤ f ↔ (∀n:ℕ, times_cont_diff 𝕜 n f) := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_rec_univ.symm, times_cont_diff_on_top] lemma times_cont_diff.times_cont_diff_on {n : with_top ℕ} {s : set E} (h : times_cont_diff 𝕜 n f) (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s := by { rw ← times_cont_diff_on_univ at h, apply times_cont_diff_on.mono h (subset_univ _) hs } /-- Constants are C^∞. -/ lemma times_cont_diff_const {n : with_top ℕ} {c : F} : times_cont_diff 𝕜 n (λx : E, c) := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing F, { rw times_cont_diff_zero, apply continuous_const }, { refine times_cont_diff_succ.2 ⟨differentiable_const _, _⟩, simp [fderiv_const], exact IH }, { rw times_cont_diff_top, assume n, apply Itop } end lemma times_cont_diff_on_const {n : with_top ℕ} {c : F} {s : set E} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n (λx : E, c) s := times_cont_diff_const.times_cont_diff_on hs /-- Linear functions are C^∞. -/ lemma is_bounded_linear_map.times_cont_diff {n : with_top ℕ} (hf : is_bounded_linear_map 𝕜 f) : times_cont_diff 𝕜 n f := begin induction n using with_top.nat_induction with n IH Itop, { rw times_cont_diff_zero, exact hf.continuous }, { refine times_cont_diff_succ.2 ⟨hf.differentiable, _⟩, simp [hf.fderiv], exact times_cont_diff_const }, { rw times_cont_diff_top, apply Itop } end /-- The first projection in a product is C^∞. -/ lemma times_cont_diff_fst {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.fst : E × F → E) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.fst /-- The second projection in a product is C^∞. -/ lemma times_cont_diff_snd {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.snd : E × F → F) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.snd /-- The identity is C^∞. -/ lemma times_cont_diff_id {n : with_top ℕ} : times_cont_diff 𝕜 n (id : E → E) := is_bounded_linear_map.id.times_cont_diff /-- Bilinear functions are C^∞. -/ lemma is_bounded_bilinear_map.times_cont_diff {n : with_top ℕ} (hb : is_bounded_bilinear_map 𝕜 b) : times_cont_diff 𝕜 n b := begin induction n using with_top.nat_induction with n IH Itop, { rw times_cont_diff_zero, exact hb.continuous }, { refine times_cont_diff_succ.2 ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.times_cont_diff }, { rw times_cont_diff_top, apply Itop } end /-- Composition by bounded linear maps preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.comp_is_bounded_linear {n : with_top ℕ} {s : set E} {f : E → F} {g : F → G} (hf : times_cont_diff_on 𝕜 n f s) (hg : is_bounded_linear_map 𝕜 g) (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n (λx, g (f x)) s := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing F G, { have : continuous_on g univ := hg.continuous.continuous_on, rw times_cont_diff_on_zero at hf ⊢, apply continuous_on.comp this hf (subset_univ _) }, { rw times_cont_diff_on_succ at hf ⊢, refine ⟨differentiable_on.comp hg.differentiable_on hf.1 subset_preimage_univ, _⟩, let Φ : (E →L[𝕜] F) → (E →L[𝕜] G) := λu, continuous_linear_map.comp (hg.to_continuous_linear_map) u, have : ∀x∈s, fderiv_within 𝕜 (g ∘ f) s x = Φ (fderiv_within 𝕜 f s x), { assume x hx, rw [fderiv_within.comp x _ (hf.1 x hx) subset_preimage_univ (hs x hx), fderiv_within_univ, hg.fderiv], rw differentiable_within_at_univ, exact hg.differentiable_at }, apply times_cont_diff_on.congr_mono _ hs this (subset.refl _), simp only [times_cont_diff_on_succ] at hf, exact IH hf.2 hg.to_continuous_linear_map.is_bounded_linear_map_comp_left }, { rw times_cont_diff_on_top at hf ⊢, assume n, apply Itop n (hf n) hg } end /-- Composition by bounded linear maps preserves `C^n` functions. -/ lemma times_cont_diff.comp_is_bounded_linear {n : with_top ℕ} {f : E → F} {g : F → G} (hf : times_cont_diff 𝕜 n f) (hg : is_bounded_linear_map 𝕜 g) : times_cont_diff 𝕜 n (λx, g (f x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp_is_bounded_linear (times_cont_diff_on_univ.2 hf) hg is_open_univ.unique_diff_on /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n (λx:E, (f x, g x)) s := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing F G, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.prod hf hg }, { rw times_cont_diff_on_succ at hf hg ⊢, refine ⟨differentiable_on.prod hf.1 hg.1, _⟩, let F₁ := λx : E, (fderiv_within 𝕜 f s x, fderiv_within 𝕜 g s x), let Φ : ((E →L[𝕜] F) × (E →L[𝕜] G)) → (E →L[𝕜] (F × G)) := λp, continuous_linear_map.prod p.1 p.2, have : times_cont_diff_on 𝕜 n (Φ ∘ F₁) s := times_cont_diff_on.comp_is_bounded_linear (IH hf.2 hg.2) is_bounded_linear_map_prod_iso hs, apply times_cont_diff_on.congr_mono this hs (λx hx, _) (subset.refl _), apply differentiable_at.fderiv_within_prod (hf.1 x hx) (hg.1 x hx) (hs x hx) }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hf n) (hg n) } end /-- The cartesian product of `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx:E, (f x, g x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.prod (times_cont_diff_on_univ.2 hf) (times_cont_diff_on_univ.2 hg) is_open_univ.unique_diff_on /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing E F G, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw times_cont_diff_on_succ at hf hg ⊢, /- We have to show that the derivative of g ∘ f is C^n, given that g and f are C^(n+1). By the chain rule, this derivative is Dg(f x) ⬝ Df(x). This is the composition of x ↦ (Dg (f x), Df (x)) with the product of bounded linear maps, which is bilinear and therefore C^∞. By the induction assumption, it suffices to show that x ↦ (Dg (f x), Df (x)) is C^n. It is even enough to show that each component is C^n. This follows from the assumptions on f and g, and the inductive assumption. -/ refine ⟨differentiable_on.comp hg.1 hf.1 st, _⟩, have : ∀x∈s, fderiv_within 𝕜 (g ∘ f) s x = continuous_linear_map.comp (fderiv_within 𝕜 g t (f x)) (fderiv_within 𝕜 f s x), { assume x hx, apply fderiv_within.comp x _ (hf.1 x hx) st (hs x hx), exact hg.1 _ (st hx) }, apply times_cont_diff_on.congr _ hs this, have A : times_cont_diff_on 𝕜 n (λx, fderiv_within 𝕜 g t (f x)) s := IH hg.2 (times_cont_diff_on_succ.2 hf).of_succ hs st, have B : times_cont_diff_on 𝕜 n (λx, fderiv_within 𝕜 f s x) s := hf.2, have C : times_cont_diff_on 𝕜 n (λx:E, (fderiv_within 𝕜 f s x, fderiv_within 𝕜 g t (f x))) s := times_cont_diff_on.prod B A hs, have D : times_cont_diff_on 𝕜 n (λ(p : (E →L[𝕜] F) × (F →L[𝕜] G)), p.2.comp p.1) univ := is_bounded_bilinear_map_comp.times_cont_diff.times_cont_diff_on is_open_univ.unique_diff_on, exact IH D C hs (subset_univ _) }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hg n) (hf n) hs st } end /-- The composition of a C^n function on domain with a C^n function is C^n. -/ lemma times_cont_diff.comp_times_cont_diff_on {n : with_top ℕ} {s : set E} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n (g ∘ f) s := (times_cont_diff_on_univ.2 hg).comp hf hs subset_preimage_univ /-- The composition of `C^n` functions is `C^n`. -/ lemma times_cont_diff.comp {n : with_top ℕ} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (g ∘ f) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp (times_cont_diff_on_univ.2 hg) (times_cont_diff_on_univ.2 hf) is_open_univ.unique_diff_on (subset_univ _) /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2) (set.prod s (univ : set E)) := begin have U : unique_diff_on 𝕜 (set.prod s (univ : set E)) := hs.prod unique_diff_on_univ, have A : times_cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2), { apply is_bounded_bilinear_map.times_cont_diff, exact is_bounded_bilinear_map_apply }, have B : times_cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (set.prod s univ), { apply times_cont_diff_on.prod _ _ U, { have I : times_cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s := times_cont_diff_on_fderiv_within hf hmn, have J : times_cont_diff_on 𝕜 m (λ (x : E × E), x.1) (set.prod s univ) := times_cont_diff_fst.times_cont_diff_on U, exact times_cont_diff_on.comp I J U (prod_subset_preimage_fst _ _) }, { apply times_cont_diff.times_cont_diff_on _ U, apply is_bounded_linear_map.times_cont_diff, apply is_bounded_linear_map.snd } }, exact A.comp_times_cont_diff_on B U end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff.times_cont_diff_fderiv_apply {n m : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) : times_cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) := begin rw ← times_cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact times_cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end /-- The sum of two C^n functions on a domain is C^n. -/ lemma times_cont_diff_on.add {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n (λx, f x + g x) s := begin have : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.add is_bounded_linear_map.fst is_bounded_linear_map.snd }, exact this.comp_times_cont_diff_on (hf.prod hg hs) hs end /-- The sum of two C^n functions is C^n. -/ lemma times_cont_diff.add {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x + g x) := begin have : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.add is_bounded_linear_map.fst is_bounded_linear_map.snd }, exact this.comp (hf.prod hg) end /-- The negative of a C^n function on a domain is C^n. -/ lemma times_cont_diff_on.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n (λx, -f x) s := begin have : times_cont_diff 𝕜 n (λp : F, -p), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.neg is_bounded_linear_map.id }, exact this.comp_times_cont_diff_on hf hs end /-- The negative of a C^n function is C^n. -/ lemma times_cont_diff.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, -f x) := begin have : times_cont_diff 𝕜 n (λp : F, -p), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.neg is_bounded_linear_map.id }, exact this.comp hf end /-- The difference of two C^n functions on a domain is C^n. -/ lemma times_cont_diff_on.sub {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n (λx, f x - g x) s := hf.add (hg.neg hs) hs /-- The difference of two C^n functions is C^n. -/ lemma times_cont_diff.sub {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x - g x) := hf.add hg.neg
d2addccc9e3d621d532061bf1132b1e3ccd80e6f
c46a17c860913da8a635099f06be3a2416f6cdab
/middleschool.lean
42d09ecaa43c16ebf211cce57e73cda7566e8b3a
[]
no_license
vladfi1/vfds
4ed0b7fd810218c74eef933364b9aa6be4cc2551
664b0d1c8126c93b379115ffe5da7b943f3375d5
refs/heads/master
1,585,024,431,435
1,535,567,828,000
1,535,567,828,000
142,457,395
0
1
null
1,532,805,351,000
1,532,617,692,000
Lean
UTF-8
Lean
false
false
5,237
lean
-- inductive player : Type | a | b | c open list #print nat.no_confusion_type #print nat.no_confusion def adjacent_pred {α : Type} (p : α -> α -> Prop) : list α -> Prop | [] := true | [x] := true | (x :: y :: tail) := p x y ∧ adjacent_pred (y :: tail) def allp : list Prop -> Prop | [] := true | (x::xs) := x ∧ allp xs def is_occurrence_list {α : Type} (x : α) (xs : list α) (idxs : list ℕ) : Prop := adjacent_pred nat.lt idxs ∧ allp (list.map (λ n, nth xs n = some x) idxs) def diff_n (n : nat) := (λ x y, x + n ≤ y) def increasing_by (n : ℕ) := adjacent_pred (diff_n n) lemma allp_nth {α : Type} {xs : list α} {f : α -> Prop} : allp (list.map f xs) -> forall n (h : n < length xs), f (nth_le xs n h) := begin intro, induction xs with x xs IHxs, intros, cases h, intros, cases n with n, unfold nth_le, exact a.left, unfold nth_le, apply IHxs, apply a.right end lemma adjacent_pred_nth {α : Type} {xs : list α} {p : α -> α -> Prop} : (adjacent_pred p xs) <-> forall n {h1 : n < length xs} {h2 : nat.succ n < length xs}, p (nth_le xs n h1) (nth_le xs (nat.succ n) h2) := begin apply iff.intro, intros, revert xs, induction n, intros, cases xs, cases h1, cases xs_tl, unfold length at h2, cases h2, cases h2_a, unfold nth_le, exact a.left, intros, cases xs, cases h1, unfold nth_le, apply n_ih, cases xs_tl, cases h1, cases h1_a, exact a.right, --backwards induction xs, intros, unfold adjacent_pred, intros, cases xs_tl, unfold adjacent_pred, unfold adjacent_pred, split, apply a 0, unfold length, apply nat.zero_lt_succ, unfold length, apply nat.succ_lt_succ, apply nat.zero_lt_succ, apply xs_ih, intros, apply a (nat.succ n), apply nat.succ_lt_succ, apply h1, apply nat.succ_lt_succ, apply h2, end lemma increasing_nth {xs : list ℕ} {k : ℕ} : (increasing_by k xs) -> ∀ n (H : n < length xs), (nth_le xs n H) ≥ k * n := begin intros, induction n, unfold has_mul.mul nat.mul, apply nat.zero_le, unfold has_mul.mul nat.mul, cases xs, cases H, unfold nth_le, apply le_trans, apply add_le_add_right, apply n_ih, apply nat.lt_of_succ_lt, assumption, apply le_trans, apply adjacent_pred_nth.elim_left a, assumption, unfold nth_le, end lemma asd {n m : nat} : n ≤ m -> n = m ∨ n < m := begin intro, cases a, apply or.inl, refl, apply or.inr, apply nat.succ_le_succ, apply a_a, end lemma some_length {α : Type} {x : α} {n : nat} {xs : list α} : (nth xs n = some x) -> n < length xs := begin revert xs, induction n, intro, cases xs, intro, cases a, intro, unfold length, apply nat.zero_lt_succ, intros, cases xs, cases a, unfold length, apply nat.succ_lt_succ, apply n_ih, apply a, end set_option trace.check true lemma nth_le_nth {α : Type} {x : α} {xs : list α} {n : nat} (h : n < length xs) : nth xs n = some x -> nth_le xs n h = x := begin revert xs, induction n, intro, cases xs, intro, cases h, intros, unfold nth at a, unfold nth_le, cases a, refl, intros, cases xs, cases h, unfold nth at a, unfold nth_le, apply n_ih, assumption, end lemma diff2 {α : Type} (x : α) (xs : list α) (idxs : list ℕ) : is_occurrence_list x xs idxs ∧ adjacent_pred ne xs -> increasing_by 2 idxs := begin intro, cases a, cases a_left, apply adjacent_pred_nth.elim_right, let h_ne := adjacent_pred_nth.elim_left a_right, let h_lt := adjacent_pred_nth.elim_left a_left_left, let h_x := allp_nth a_left_right, intros, unfold diff_n, cases asd (@h_lt n h1 h2), apply absurd (h_ne (nth_le idxs n h1)), intro, apply a, simp [h], rw nth_le_nth _ (h_x n h1), rw nth_le_nth _ (h_x (nat.succ n) h2), apply some_length, apply h_x, rw h, apply some_length, apply h_x, exact h, end lemma le_pred (n : nat) (m : nat) : n ≤ nat.succ m -> nat.pred n ≤ m := begin intro, cases n, unfold nat.pred, apply nat.zero_le, unfold nat.pred, apply nat.le_of_succ_le_succ, assumption, end lemma nth_lt {α : Type} {x : α} {xs : list α} {n : nat} : list.nth xs n = option.some x -> n < length xs := begin revert xs, induction n, intro, cases xs, unfold nth, intro, cases a, unfold nth, intro, unfold length, apply nat.zero_lt_succ, intro, cases xs, unfold nth, intro, cases a, unfold nth, intro, unfold length, apply nat.succ_lt_succ, apply n_ih, assumption end theorem main {α : Type} (x : α) (xs : list α) (idxs : list ℕ) : is_occurrence_list x xs idxs -> adjacent_pred ne xs -> list.length xs ≥ 2 * list.length idxs - 1 := begin intros, cases idxs, simp, apply nat.zero_le, let idxs := idxs_hd :: idxs_tl, let i := length idxs_tl, have i_le : i < length idxs, dsimp, apply nat.lt_succ_self, let h2 := allp_nth a.right, have h1 : nth_le idxs i i_le < length xs, apply nth_lt, apply h2, clear h2, unfold length, unfold has_mul.mul nat.mul, unfold has_sub.sub nat.sub nat.pred, apply le_trans, tactic.swap, apply h1, apply nat.succ_le_succ, apply le_trans, tactic.swap, apply increasing_nth, apply diff2, split, exact a, exact a_1, apply nat.mul_le_mul_left, apply nat.le_refl, end theorem main2 {α : Type} (x : α) (xs : list α) (idxs : list ℕ) : is_occurrence_list x xs idxs -> adjacent_pred ne xs -> list.length xs = 2 * list.length idxs - 1 -> ∀ n (H : n < length idxs), (nth_le idxs n H) = 2 * n := begin intros, sorry end
1a6b64890e2636ec873e25df123f6701fab08e4d
63abd62053d479eae5abf4951554e1064a4c45b4
/src/field_theory/separable.lean
8e30edea7ffd78bfc1842834c1f7044b629f76d6
[ "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
22,430
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau. -/ import algebra.polynomial.big_operators import field_theory.minimal_polynomial import field_theory.splitting_field import field_theory.tower /-! # Separable polynomials We define a polynomial to be separable if it is coprime with its derivative. We prove basic properties about separable polynomials here. ## Main definitions * `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative. * `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`. * `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ universes u v w open_locale classical big_operators open finset namespace polynomial section comm_semiring variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] /-- A polynomial is separable iff it is coprime with its derivative. -/ def separable (f : polynomial R) : Prop := is_coprime f f.derivative lemma separable_def (f : polynomial R) : f.separable ↔ is_coprime f f.derivative := iff.rfl lemma separable_def' (f : polynomial R) : f.separable ↔ ∃ a b : polynomial R, a * f + b * f.derivative = 1 := iff.rfl lemma separable_one : (1 : polynomial R).separable := is_coprime_one_left lemma separable_X_add_C (a : R) : (X + C a).separable := by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero], exact is_coprime_one_right } lemma separable_X : (X : polynomial R).separable := by { rw [separable_def, derivative_X], exact is_coprime_one_right } lemma separable_C (r : R) : (C r).separable ↔ is_unit r := by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C] lemma separable.of_mul_left {f g : polynomial R} (h : (f * g).separable) : f.separable := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this) end lemma separable.of_mul_right {f g : polynomial R} (h : (f * g).separable) : g.separable := by { rw mul_comm at h, exact h.of_mul_left } lemma separable.of_dvd {f g : polynomial R} (hf : f.separable) (hfg : g ∣ f) : g.separable := by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf } lemma separable_gcd_left {F : Type*} [field F] {f : polynomial F} (hf : f.separable) (g : polynomial F) : (euclidean_domain.gcd f g).separable := separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g) lemma separable_gcd_right {F : Type*} [field F] {g : polynomial F} (f : polynomial F) (hg : g.separable) : (euclidean_domain.gcd f g).separable := separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g) lemma separable.is_coprime {f g : polynomial R} (h : (f * g).separable) : is_coprime f g := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this) end theorem separable.of_pow' {f : polynomial R} : ∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0 | 0 := λ h, or.inr $ or.inr rfl | 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩ | (n+2) := λ h, or.inl $ is_coprime_self.1 h.is_coprime.of_mul_right_left theorem separable.of_pow {f : polynomial R} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0) (hfs : (f ^ n).separable) : f.separable ∧ n = 1 := (hfs.of_pow'.resolve_left hf).resolve_right hn theorem separable.map {p : polynomial R} (h : p.separable) {f : R →+* S} : (p.map f).separable := let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f, by rw [derivative_map, ← map_mul, ← map_mul, ← map_add, H, map_one]⟩ variables (R) (p q : ℕ) /-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/ noncomputable def expand : polynomial R →ₐ[R] polynomial R := { commutes' := λ r, eval₂_C _ _, .. (eval₂_ring_hom C (X ^ p) : polynomial R →+* polynomial R) } lemma coe_expand : (expand R p : polynomial R → polynomial R) = eval₂ C (X ^ p) := rfl variables {R} lemma expand_eq_sum {f : polynomial R} : expand R p f = f.sum (λ e a, C a * (X ^ p) ^ e) := by { dsimp [expand, eval₂], refl, } @[simp] lemma expand_C (r : R) : expand R p (C r) = C r := eval₂_C _ _ @[simp] lemma expand_X : expand R p X = X ^ p := eval₂_X _ _ @[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r := by simp_rw [monomial_eq_smul_X, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul] theorem expand_expand (f : polynomial R) : expand R p (expand R q f) = expand R (p * q) f := polynomial.induction_on f (λ r, by simp_rw expand_C) (λ f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, alg_hom.map_pow, expand_X, pow_mul]) theorem expand_mul (f : polynomial R) : expand R (p * q) f = expand R p (expand R q f) := (expand_expand p q f).symm @[simp] theorem expand_one (f : polynomial R) : expand R 1 f = f := polynomial.induction_on f (λ r, by rw expand_C) (λ f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one]) theorem expand_pow (f : polynomial R) : expand R (p ^ q) f = (expand R p ^[q] f) := nat.rec_on q (by rw [pow_zero, expand_one, function.iterate_zero, id]) $ λ n ih, by rw [function.iterate_succ_apply', pow_succ, expand_mul, ih] theorem derivative_expand (f : polynomial R) : (expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) := by rw [coe_expand, derivative_eval₂_C, derivative_pow, derivative_X, mul_one] theorem coeff_expand {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 := begin simp only [expand_eq_sum], simp_rw [coeff_sum, ← pow_mul, C_mul_X_pow_eq_monomial, coeff_monomial, finsupp.sum], split_ifs with h, { rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl], refl, { intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] }, { intro hn, rw finsupp.not_mem_support_iff.1 hn, split_ifs; refl } }, { rw finset.sum_eq_zero, intros k hk, rw if_neg, exact λ hkn, h ⟨k, hkn.symm⟩, }, end @[simp] theorem coeff_expand_mul {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (n * p) = f.coeff n := by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp] @[simp] theorem coeff_expand_mul' {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (p * n) = f.coeff n := by rw [mul_comm, coeff_expand_mul hp] theorem expand_eq_map_domain (p : ℕ) (f : polynomial R) : expand R p f = f.map_domain (*p) := polynomial.induction_on' f (λ p q hp hq, by simp [*, finsupp.map_domain_add]) $ λ n a, by simp_rw [expand_monomial, monomial_def, finsupp.map_domain_single] theorem expand_inj {p : ℕ} (hp : 0 < p) {f g : polynomial R} : expand R p f = expand R p g ↔ f = g := ⟨λ H, ext $ λ n, by rw [← coeff_expand_mul hp, H, coeff_expand_mul hp], congr_arg _⟩ theorem expand_eq_zero {p : ℕ} (hp : 0 < p) {f : polynomial R} : expand R p f = 0 ↔ f = 0 := by rw [← (expand R p).map_zero, expand_inj hp, alg_hom.map_zero] theorem expand_eq_C {p : ℕ} (hp : 0 < p) {f : polynomial R} {r : R} : expand R p f = C r ↔ f = C r := by rw [← expand_C, expand_inj hp, expand_C] theorem nat_degree_expand (p : ℕ) (f : polynomial R) : (expand R p f).nat_degree = f.nat_degree * p := begin cases p.eq_zero_or_pos with hp hp, { rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, eval₂_hom, nat_degree_C] }, by_cases hf : f = 0, { rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] }, have hf1 : expand R p f ≠ 0 := mt (expand_eq_zero hp).1 hf, rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1], refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ λ n hn, _) _, { rw coeff_expand hp, split_ifs with hpn, { rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn, rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn }, { refl } }, { refine le_degree_of_ne_zero _, rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf } end theorem map_expand {p : ℕ} (hp : 0 < p) {f : R →+* S} {q : polynomial R} : map f (expand R p q) = expand S p (map f q) := by { ext, rw [coeff_map, coeff_expand hp, coeff_expand hp], split_ifs; simp, } end comm_semiring section comm_ring variables {R : Type u} [comm_ring R] lemma separable_X_sub_C {x : R} : separable (X - C x) := by simpa only [C_neg] using separable_X_add_C (-x) lemma separable.mul {f g : polynomial R} (hf : f.separable) (hg : g.separable) (h : is_coprime f g) : (f * g).separable := by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left ((h.symm.mul_right hg).mul_add_right_right _) } lemma separable_prod' {ι : Sort*} {f : ι → polynomial R} {s : finset ι} : (∀x∈s, ∀y∈s, x ≠ y → is_coprime (f x) (f y)) → (∀x∈s, (f x).separable) → (∏ x in s, f x).separable := finset.induction_on s (λ _ _, separable_one) $ λ a s has ih h1 h2, begin simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has, exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ λ i his, h1.1.2 i his $ ne.symm $ ne_of_mem_of_not_mem his has) end lemma separable_prod {ι : Sort*} [fintype ι] {f : ι → polynomial R} (h1 : pairwise (is_coprime on f)) (h2 : ∀ x, (f x).separable) : (∏ x, f x).separable := separable_prod' (λ x hx y hy hxy, h1 x y hxy) (λ x hx, h2 x) lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ι : Sort*} {f : ι → R} {s : finset ι} (hfs : (∏ i in s, (X - C (f i))).separable) {x y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y := begin by_contra hxy, rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy), prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← pow_two] at hfs, cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C) two_ne_zero).2 end lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ι : Sort*} [fintype ι] {f : ι → R} (hfs : (∏ i, (X - C (f i))).separable) : function.injective f := λ x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy lemma is_unit_of_self_mul_dvd_separable {p q : polynomial R} (hp : p.separable) (hq : q * q ∣ p) : is_unit q := begin obtain ⟨p, rfl⟩ := hq, apply is_coprime_self.mp, have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)), { simp only [← mul_assoc, mul_add], convert hp, rw [derivative_mul, derivative_mul], ring }, exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this) end end comm_ring section integral_domain variables (R : Type u) [integral_domain R] theorem is_local_ring_hom_expand {p : ℕ} (hp : 0 < p) : is_local_ring_hom (↑(expand R p) : polynomial R →+* polynomial R) := begin refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1, have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1), rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2, rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C] end end integral_domain section field variables {F : Type u} [field F] {K : Type v} [field K] theorem separable_iff_derivative_ne_zero {f : polynomial F} (hf : irreducible f) : f.separable ↔ f.derivative ≠ 0 := ⟨λ h1 h2, hf.1 $ is_coprime_zero_right.1 $ h2 ▸ h1, λ h, is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4, let ⟨u, hu⟩ := (hf.2 _ _ hg3).resolve_left hg1 in have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd }, not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt h⟩ theorem separable_map (f : F →+* K) {p : polynomial F} : (p.map f).separable ↔ p.separable := by simp_rw [separable_def, derivative_map, is_coprime_map] section char_p variables (p : ℕ) [hp : fact p.prime] include hp /-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ noncomputable def contract (f : polynomial F) : polynomial F := ⟨f.support.preimage (*p) $ λ _ _ _ _, (nat.mul_left_inj hp.pos).1, λ n, f.coeff (n * p), λ n, by { rw [finset.mem_preimage, finsupp.mem_support_iff], refl }⟩ theorem coeff_contract (f : polynomial F) (n : ℕ) : (contract p f).coeff n = f.coeff (n * p) := rfl theorem of_irreducible_expand {f : polynomial F} (hf : irreducible (expand F p f)) : irreducible f := @@of_irreducible_map _ _ _ (is_local_ring_hom_expand F hp.pos) hf theorem of_irreducible_expand_pow {f : polynomial F} {n : ℕ} : irreducible (expand F (p ^ n) f) → irreducible f := nat.rec_on n (λ hf, by rwa [pow_zero, expand_one] at hf) $ λ n ih hf, ih $ of_irreducible_expand p $ by rwa [expand_expand] variables [HF : char_p F p] include HF theorem expand_char (f : polynomial F) : map (frobenius F p) (expand F p f) = f ^ p := begin refine f.induction_on' (λ a b ha hb, _) (λ n a, _), { rw [alg_hom.map_add, map_add, ha, hb, add_pow_char], }, { rw [expand_monomial, map_monomial, single_eq_C_mul_X, single_eq_C_mul_X, mul_pow, ← C.map_pow, frobenius_def], ring_exp } end theorem map_expand_pow_char (f : polynomial F) (n : ℕ) : map ((frobenius F p) ^ n) (expand F (p ^ n) f) = f ^ (p ^ n) := begin induction n, {simp [ring_hom.one_def]}, symmetry, rw [pow_succ', pow_mul, ← n_ih, ← expand_char, pow_succ, ring_hom.mul_def, ← map_map, mul_comm, expand_mul, ← map_expand (nat.prime.pos hp)], end theorem expand_contract {f : polynomial F} (hf : f.derivative = 0) : expand F p (contract p f) = f := begin ext n, rw [coeff_expand hp.pos, coeff_contract], split_ifs with h, { rw nat.div_mul_cancel h }, { cases n, { exact absurd (dvd_zero p) h }, have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this }, rw [← nat.cast_succ, char_p.cast_eq_zero_iff F p] at this, exact absurd this h } end theorem separable_or {f : polynomial F} (hf : irreducible f) : f.separable ∨ ¬f.separable ∧ ∃ g : polynomial F, irreducible g ∧ expand F p g = f := if H : f.derivative = 0 then or.inr ⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H], contract p f, by haveI := is_local_ring_hom_expand F hp.pos; exact of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H at hf), expand_contract p H⟩ else or.inl $ (separable_iff_derivative_ne_zero hf).2 H theorem exists_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : ∃ (n : ℕ) (g : polynomial F), g.separable ∧ expand F (p ^ n) g = f := begin generalize hn : f.nat_degree = N, unfreezingI { revert f }, apply nat.strong_induction_on N, intros N ih f hf hf0 hn, rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩, { refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] }, { cases N with N, { rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn, rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1, rw [h1, C_0] at hn, exact absurd hn hf0 }, have hg1 : g.nat_degree * p = N.succ, { rwa [← nat_degree_expand, hgf] }, have hg2 : g.nat_degree ≠ 0, { intro this, rw [this, zero_mul] at hg1, cases hg1 }, have hg3 : g.nat_degree < N.succ, { rw [← mul_one g.nat_degree, ← hg1], exact nat.mul_lt_mul_of_pos_left hp.one_lt (nat.pos_of_ne_zero hg2) }, have hg4 : g ≠ 0, { rintro rfl, exact hg2 nat_degree_zero }, rcases ih _ hg3 hg hg4 rfl with ⟨n, g, hg5, rfl⟩, refine ⟨n+1, g, hg5, _⟩, rw [← hgf, expand_expand, pow_succ] } end theorem is_unit_or_eq_zero_of_separable_expand {f : polynomial F} (n : ℕ) (hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 := begin rw or_iff_not_imp_right, intro hn, have hf2 : (expand F (p ^ n) f).derivative = 0, { by rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero, zero_pow (nat.pos_of_ne_zero hn), zero_mul, mul_zero] }, rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩, rw [eq_comm, expand_eq_C (pow_pos hp.pos _)] at hrf, rwa [hrf, is_unit_C] end theorem unique_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) (n₁ : ℕ) (g₁ : polynomial F) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f) (n₂ : ℕ) (g₂ : polynomial F) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) : n₁ = n₂ ∧ g₁ = g₂ := begin revert g₁ g₂, wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁] tactic.skip, unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩, rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp.pos n₁)] at hgf₂, subst hgf₂, subst hgf₁, rcases is_unit_or_eq_zero_of_separable_expand p k hg₁ with h | rfl, { rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩, simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 }, { rw [add_zero, pow_zero, expand_one], split; refl } }, exact λ g₁ g₂ hg₁ hgf₁ hg₂ hgf₂, let ⟨hn, hg⟩ := this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁ in ⟨hn.symm, hg.symm⟩ end end char_p lemma separable_prod_X_sub_C_iff' {ι : Sort*} {f : ι → F} {s : finset ι} : (∏ i in s, (X - C (f i))).separable ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy, λ H, by { rw ← prod_attach, exact separable_prod' (λ x hx y hy hxy, @pairwise_coprime_X_sub _ _ { x // x ∈ s } (λ x, f x) (λ x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy) (λ _ _, separable_X_sub_C) }⟩ lemma separable_prod_X_sub_C_iff {ι : Sort*} [fintype ι] {f : ι → F} : (∏ i, (X - C (f i))).separable ↔ function.injective f := separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff] section splits open_locale big_operators variables {i : F →+* K} lemma not_unit_X_sub_C (a : F) : ¬ is_unit (X - C a) := λ h, have one_eq_zero : (1 : with_bot ℕ) = 0, by simpa using degree_eq_zero_of_is_unit h, one_ne_zero (option.some_injective _ one_eq_zero) lemma nodup_of_separable_prod {s : multiset F} (hs : separable (multiset.map (λ a, X - C a) s).prod) : s.nodup := begin rw multiset.nodup_iff_ne_cons_cons, rintros a t rfl, refine not_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _), simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _) end lemma multiplicity_le_one_of_seperable {p q : polynomial F} (hq : ¬ is_unit q) (hsep : separable p) : multiplicity q p ≤ 1 := begin contrapose! hq, apply is_unit_of_self_mul_dvd_separable hsep, rw ← pow_two, apply multiplicity.pow_dvd_of_le_multiplicity, exact_mod_cast (enat.add_one_le_of_lt hq) end lemma root_multiplicity_le_one_of_seperable {p : polynomial F} (hp : p ≠ 0) (hsep : separable p) (x : F) : root_multiplicity x p ≤ 1 := begin rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_le_coe, enat.coe_get], exact multiplicity_le_one_of_seperable (not_unit_X_sub_C _) hsep end lemma count_roots_le_one {p : polynomial F} (hsep : separable p) (x : F) : p.roots.count x ≤ 1 := begin by_cases hp : p = 0, { simp [hp] }, rw count_roots hp, exact root_multiplicity_le_one_of_seperable hp hsep x end lemma nodup_roots {p : polynomial F} (hsep : separable p) : p.roots.nodup := multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep) lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : polynomial F} (h_ne_zero : h ≠ 0) (h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h) (h_roots : ∀ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits, apply finset.mk.inj, { change _ = {i x}, rw finset.eq_singleton_iff_unique_mem, split, { apply finset.mem_mk.mpr, rw mem_roots (show h.map i ≠ 0, by exact map_ne_zero h_ne_zero), rw [is_root.def,←eval₂_eq_eval_map,eval₂_hom,h_root], exact ring_hom.map_zero i }, { exact h_roots } }, { exact nodup_roots (separable.map h_sep) }, end end splits end field end polynomial open polynomial theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : f.separable := begin rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], rintro ⟨⟩, rw [nat.pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff], refine λ hf1, hf.1 _, rw [hf1, is_unit_C, is_unit_iff_ne_zero], intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf0 end /-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff the minimal polynomial of every `x : K` is separable. -/ @[class] def is_separable (F K : Sort*) [field F] [field K] [algebra F K] : Prop := ∀ x : K, ∃ H : is_integral F x, (minimal_polynomial H).separable section is_separable_tower variables {F E : Type*} (K : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_separable_tower_top_of_is_separable (h : is_separable F E) : is_separable K E := λ x, Exists.cases_on (h x) (λ hx hs, ⟨is_integral_of_is_scalar_tower x hx, hs.map.of_dvd (minimal_polynomial.dvd_map_of_is_scalar_tower K hx)⟩) lemma is_separable_tower_bot_of_is_separable (h : is_separable F E) : is_separable F K := begin intro x, obtain ⟨hx, hs⟩ := h (algebra_map K E x), have hx' : is_integral F x := is_integral_tower_bot_of_is_integral_field hx, obtain ⟨q, hq⟩ := minimal_polynomial.dvd hx' (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero_field (minimal_polynomial.aeval hx)), use hx', apply polynomial.separable.of_mul_left, rw ← hq, exact hs, end end is_separable_tower
1f63cb01ee1cec51a00d57d0bae5073ef6faa032
98a293ccd858a15396cba300c1d91bc9d39bda52
/src/mergeSort.lean
0eac86520785df126df3eba1af2c44c5e1531709
[]
no_license
Othmanh/merge-Sort
da3a9e2ddd987b99bdd725edd6a288c1e19d3598
424433f71e5f87b0a2351ee434901d499d5fc675
refs/heads/main
1,687,662,137,031
1,627,494,456,000
1,627,494,456,000
375,764,779
0
0
null
null
null
null
UTF-8
Lean
false
false
9,179
lean
import tactic.linarith import tactic.induction import data.nat.basic import data.list.sort open nat /- This lemma applies the strong induction principle on the lenght of a list. -/ @[elab_as_eliminator] lemma list.strong_length_induction {α} {C : list α → Sort*} (rec : ∀ xs : list α, (∀ ys : list α, ys.length < xs.length → C ys) → C xs) : ∀ xs, C xs | xs := rec xs (λ ys len, list.strong_length_induction ys) using_well_founded { rel_tac := λ _ _, `[ exact ⟨_, measure_wf list.length ⟩]} /- The function split takes a list α, splits it and returns the two halves in a tuple. -/ def split {α : Type} : list α → list α × list α | xs := (list.take (xs.length/2) xs, list.drop (xs.length/2) xs) /- This lemma proves that the first split half of a list, using the function split, is smaller in length than the original list. -/ lemma split_dec_fst {α : Type} : ∀ (x x' : α) (xs : list α), (split (x :: x' :: xs)).fst.length < (x :: x' :: xs).length := begin intros x x' xs, simp [split], ring_nf, exact div_lt_self' (xs.length + 1) 0, end lemma split_dec_snd {α : Type} : ∀ (x x' : α) (xs : list α), ((split (x :: x' :: xs)).snd).length < ((x :: x' :: xs).length) := begin intros x x' xs, rw split, simp, ring_nf, apply nat.sub_lt_self, linarith, norm_num, end /- This lemma proves that concatenating the two split halves of a list produces a permutation of the original list. -/ lemma split_preserves {α : Type} : ∀ (xs : list α), (split xs).fst ++ (split xs).snd ~ xs := begin intros xs, simp [split] end /- The merge function takes two lists and recursively merges them into one ordered list. -/ def merge {α : Type} (lt : α → α → bool) : list α → list α → list α | [] a := a | (h1::t1) [] := h1::t1 | (h1::t1) (h2::t2) := if lt h1 h2 then (h1 :: (merge t1 (h2::t2))) else (h2 :: (merge (h1::t1) t2)) /- This lemma proves that merging two lists together produces a list that is a permutation of the two input lists concatenated together. -/ lemma merge_preserves {α : Type} (lt : α → α → bool) : ∀ (as bs : list α), merge lt as bs ~ as ++ bs | [] bs := begin rw merge, simp, end | (a :: as) [] := begin rw merge, simp, end | (a :: as) (b :: bs) := begin rw merge, by_cases hab: (lt a b : Prop), { rw [if_pos hab], simp, apply merge_preserves as (b :: bs), }, { rw [if_neg hab], transitivity, swap, { apply list.perm_append_comm, }, { simp, transitivity, { apply merge_preserves, }, { apply list.perm_append_comm, } } } end /- The function mergeSort -/ def mergeSort {α : Type} (lt : α -> α -> bool) : list α → list α | [] := [] | [a] := [a] | (a :: b :: xs) := let p := split (a :: b :: xs) in let as := p.fst in let bs := p.snd in let h1 : as.length < (a :: b :: xs).length := split_dec_fst _ _ _ in let h2 : bs.length < (a :: b :: xs).length := split_dec_snd _ _ _ in merge lt (mergeSort as) (mergeSort bs) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] } /- This lemma proves that sorting a list using mergeSort produces a permutation of that list. -/ lemma mergeSort_preserves {α : Type} (lt : α -> α -> bool) : ∀ (xs : list α), mergeSort lt xs ~ xs := begin intros unsorted, induction unsorted using list.strong_length_induction with xs ih, simp at ih, cases xs, case nil { rw mergeSort }, case cons: x xs { cases xs, case nil { rw mergeSort, }, case cons: x' xs { simp [mergeSort], transitivity, { apply merge_preserves, }, { transitivity, { apply list.perm.append _ _, swap 3, apply ih, apply split_dec_fst, swap, apply ih, apply split_dec_snd, }, { apply split_preserves, } } }, }, end /- This function transforms function lt to a decidable Prop. -/ def r {α : Type} (lt : α → α → bool) : α → α → Prop := λ x y, lt x y = tt /- This lemma proves that if we merge two lists using merge, all elements of the returned list belonged to either of the two original lists. -/ lemma element_of_merge {α : Type} (lt : α → α → bool): ∀ (x : α) (as bs: list α), x ∈ merge lt as bs → x ∈ as ∨ x ∈ bs | x [] as := begin intros hx, rw merge at hx, tauto, end | x (a :: as) [] := begin intros has, rw merge at has, tauto, end | x (a :: as) (b :: bs) := begin intros hab, rw merge at hab, by_cases hf : (lt a b : Prop), { rw [if_pos hf] at hab, cases hab, { left, left, exact hab, }, { have h' := element_of_merge _ _ _ hab, clear element_of_merge, cases h', { left, right, exact h', }, { right, exact h', } } }, { rw [if_neg hf] at hab, cases hab, { right, exact or.inl hab, }, { have h' := element_of_merge _ _ _ hab, clear element_of_merge, cases h', { left, exact h', }, { right, exact or.inr h', } } }, end /- This lemma proves that, given two sorted lists, the list returned by merging the two lists together using merge is sorted as well. -/ lemma merge_sorted {α : Type} (lt : α → α → bool) (tr : transitive (r lt)) (ng : ∀ x y, ¬ r lt y x → r lt x y) : ∀ (as bs: list α), list.sorted (r lt) as → list.sorted (r lt) bs → list.sorted (r lt) (merge lt as bs) | [] bs := begin intros hn hbs, rw merge, exact hbs, end | (a :: as) [] := begin intros has hn, rw merge, exact has, end | (a :: as) (b :: bs) := begin intros has hbs, have haq : ∀ q, q ∈ as → r lt a q, { intros q hq, rw list.sorted at has, rw list.pairwise_cons at has, cases has with has_l has_r, apply has_l _ hq, }, have hbq : ∀ q, q ∈ bs → r lt b q, { intros q hq, rw list.sorted at hbs, rw list.pairwise_cons at hbs, cases hbs with hbs_l hbs_r, apply hbs_l _ hq, }, rw merge, by_cases hf : (lt a b : Prop), { rw [if_pos hf], simp, split, { intros d hm, have had := element_of_merge lt d as (b :: bs) hm, cases had, { rw list.sorted at has, rw list.pairwise_cons at has, cases has with has_l has_r, apply has_l _ had, }, { simp at had, cases had, { subst had, exact hf, }, { apply tr, { exact hf, }, { simp at hbs, cases hbs with hbs_l hbs_r, apply hbs_l, exact had, } } } }, { apply merge_sorted, { rw list.sorted at has, cases has with _ _ hpas' hpas, exact hpas, }, { exact hbs, } } }, { rw [if_neg hf], simp, split, { intros k hk, have hk' := element_of_merge _ _ _ _ hk, cases hk', { cases hk', { subst hk', exact ng b k hf, }, { have fak := haq _ hk', have fba := ng _ _ hf, apply tr fba fak, } }, { apply hbq _, exact hk', } }, { apply merge_sorted, { exact has, }, { rw list.sorted at hbs, cases hbs with _ _ hpbs' hpbs, exact hpbs, } } }, end /- This lemma proves that mergeSort returns a sorted list. -/ lemma mergeSort_sorts {α : Type} (lt : α → α → bool) (tr : transitive (r lt)) (ng : ∀ x y, ¬ r lt y x → r lt x y) : ∀ (xs : list α), list.sorted (r lt) (mergeSort lt xs) := begin intros xs, induction xs using list.strong_length_induction with xs ih, simp at ih, cases xs, case nil { simp [mergeSort], }, case cons: x xs { cases xs, case nil { simp [mergeSort], }, case cons: x' xs { simp [mergeSort], apply merge_sorted lt; try { assumption }, { apply ih, apply split_dec_fst, }, { apply ih, apply split_dec_snd, } } }, end
67aa3b5959403d548df6cfdeee083d49a87c8e15
63abd62053d479eae5abf4951554e1064a4c45b4
/src/measure_theory/l1_space.lean
eaf79fabadaaf6f2df480b446a8ffc7d686d4fa0
[ "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
39,859
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.ae_eq_fun /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. In the second part, the space `L¹` of equivalence classes of integrable functions under the relation of being almost everywhere equal is defined as a subspace of the space `L⁰`. See the file `src/measure_theory/ae_eq_fun.lean` for information on `L⁰` space. ## Notation * `α →₁ β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `has_finite_integral f` means `(∫⁻ a, nnnorm (f a)) < ⊤`. * If `β` is moreover a `measurable_space` then `f` is called `integrable` if `f` is `measurable` and `has_finite_integral f` holds. * The space `L¹` is defined as a subspace of `L⁰` : An `ae_eq_fun` `[f] : α →ₘ β` is in the space `L¹` if `edist [f] 0 < ⊤`, which means `(∫⁻ a, edist (f a) 0) < ⊤` if we expand the definition of `edist` in `L⁰`. ## Main statements `L¹`, as a subspace, inherits most of the structures of `L⁰`. ## Implementation notes Maybe `integrable f` should be mean `(∫⁻ a, edist (f a) 0) < ⊤`, so that `integrable` and `ae_eq_fun.integrable` are more aligned. But in the end one can use the lemma `lintegral_nnnorm_eq_lintegral_edist : (∫⁻ a, nnnorm (f a)) = (∫⁻ a, edist (f a) 0)` to switch the two forms. To prove something for an arbitrary integrable + measurable function, a useful theorem is `integrable.induction` in the file `set_integral`. ## Tags integrable, function space, l1 -/ noncomputable theory open_locale classical topological_space big_operators open set filter topological_space ennreal emetric measure_theory variables {α β γ δ : Type*} [measurable_space α] {μ ν : measure α} variables [normed_group β] variables [normed_group γ] namespace measure_theory /-! ### Some results about the Lebesgue integral involving a normed group -/ lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) : ∫⁻ a, nnnorm (f a) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ := by simp only [edist_eq_coe_nnnorm] lemma lintegral_norm_eq_lintegral_edist (f : α → β) : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ := by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm] lemma lintegral_edist_triangle [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g h : α → β} (hf : measurable f) (hg : measurable g) (hh : measurable h) : ∫⁻ a, edist (f a) (g a) ∂μ ≤ ∫⁻ a, edist (f a) (h a) ∂μ + ∫⁻ a, edist (g a) (h a) ∂μ := begin rw ← lintegral_add (hf.edist hh) (hg.edist hh), refine lintegral_mono (λ a, _), apply edist_triangle_right end lemma lintegral_nnnorm_zero : ∫⁻ a : α, nnnorm (0 : β) ∂μ = 0 := by simp lemma lintegral_nnnorm_add [measurable_space β] [opens_measurable_space β] [measurable_space γ] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : ∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ + ∫⁻ a, nnnorm (g a) ∂μ := lintegral_add hf.ennnorm hg.ennnorm lemma lintegral_nnnorm_neg {f : α → β} : ∫⁻ a, nnnorm ((-f) a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ := by simp only [pi.neg_apply, nnnorm_neg] /-! ### The predicate `has_finite_integral` -/ /-- `has_finite_integral f μ` means that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `has_finite_integral f` means `has_finite_integral f volume`. -/ def has_finite_integral (f : α → β) (μ : measure α . volume_tac) : Prop := ∫⁻ a, nnnorm (f a) ∂μ < ⊤ lemma has_finite_integral_iff_norm (f : α → β) : has_finite_integral f μ ↔ ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ < ⊤ := by simp only [has_finite_integral, of_real_norm_eq_coe_nnnorm] lemma has_finite_integral_iff_edist (f : α → β) : has_finite_integral f μ ↔ ∫⁻ a, edist (f a) 0 ∂μ < ⊤ := by simp only [has_finite_integral_iff_norm, edist_dist, dist_zero_right] lemma has_finite_integral_iff_of_real {f : α → ℝ} (h : 0 ≤ᵐ[μ] f) : has_finite_integral f μ ↔ ∫⁻ a, ennreal.of_real (f a) ∂μ < ⊤ := have lintegral_eq : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ := begin refine lintegral_congr_ae (h.mono $ λ a h, _), rwa [real.norm_eq_abs, abs_of_nonneg] end, by rw [has_finite_integral_iff_norm, lintegral_eq] lemma has_finite_integral.mono {f : α → β} {g : α → γ} (hg : has_finite_integral g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : has_finite_integral f μ := begin simp only [has_finite_integral_iff_norm] at *, calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ (a : α), (ennreal.of_real ∥g a∥) ∂μ : lintegral_mono_ae (h.mono $ assume a h, of_real_le_of_real h) ... < ⊤ : hg end lemma has_finite_integral.mono' {f : α → β} {g : α → ℝ} (hg : has_finite_integral g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : has_finite_integral f μ := hg.mono $ h.mono $ λ x hx, le_trans hx (le_abs_self _) lemma has_finite_integral.congr' {f : α → β} {g : α → γ} (hf : has_finite_integral f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : has_finite_integral g μ := hf.mono $ eventually_eq.le $ eventually_eq.symm h lemma has_finite_integral_congr' {f : α → β} {g : α → γ} (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : has_finite_integral f μ ↔ has_finite_integral g μ := ⟨λ hf, hf.congr' h, λ hg, hg.congr' $ eventually_eq.symm h⟩ lemma has_finite_integral.congr {f g : α → β} (hf : has_finite_integral f μ) (h : f =ᵐ[μ] g) : has_finite_integral g μ := hf.congr' $ h.fun_comp norm lemma has_finite_integral_congr {f g : α → β} (h : f =ᵐ[μ] g) : has_finite_integral f μ ↔ has_finite_integral g μ := has_finite_integral_congr' $ h.fun_comp norm lemma has_finite_integral_const_iff {c : β} : has_finite_integral (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ⊤ := begin simp only [has_finite_integral, lintegral_const], by_cases hc : c = 0, { simp [hc] }, { simp only [hc, false_or], refine ⟨λ h, _, λ h, mul_lt_top coe_lt_top h⟩, replace h := mul_lt_top (@coe_lt_top $ (nnnorm c)⁻¹) h, rwa [← mul_assoc, ← coe_mul, _root_.inv_mul_cancel, coe_one, one_mul] at h, rwa [ne.def, nnnorm_eq_zero] } end lemma has_finite_integral_const [finite_measure μ] (c : β) : has_finite_integral (λ x : α, c) μ := has_finite_integral_const_iff.2 (or.inr $ measure_lt_top _ _) lemma has_finite_integral_of_bounded [finite_measure μ] {f : α → β} {C : ℝ} (hC : ∀ᵐ a ∂μ, ∥f a∥ ≤ C) : has_finite_integral f μ := (has_finite_integral_const C).mono' hC lemma has_finite_integral.mono_measure {f : α → β} (h : has_finite_integral f ν) (hμ : μ ≤ ν) : has_finite_integral f μ := lt_of_le_of_lt (lintegral_mono' hμ (le_refl _)) h lemma has_finite_integral.add_measure {f : α → β} (hμ : has_finite_integral f μ) (hν : has_finite_integral f ν) : has_finite_integral f (μ + ν) := begin simp only [has_finite_integral, lintegral_add_measure] at *, exact add_lt_top.2 ⟨hμ, hν⟩ end lemma has_finite_integral.left_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) : has_finite_integral f μ := h.mono_measure $ measure.le_add_right $ le_refl _ lemma has_finite_integral.right_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) : has_finite_integral f ν := h.mono_measure $ measure.le_add_left $ le_refl _ @[simp] lemma has_finite_integral_add_measure {f : α → β} : has_finite_integral f (μ + ν) ↔ has_finite_integral f μ ∧ has_finite_integral f ν := ⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩ lemma has_finite_integral.smul_measure {f : α → β} (h : has_finite_integral f μ) {c : ennreal} (hc : c < ⊤) : has_finite_integral f (c • μ) := begin simp only [has_finite_integral, lintegral_smul_measure] at *, exact mul_lt_top hc h end @[simp] lemma has_finite_integral_zero_measure (f : α → β) : has_finite_integral f 0 := by simp only [has_finite_integral, lintegral_zero_measure, with_top.zero_lt_top] variables (α β μ) @[simp] lemma has_finite_integral_zero : has_finite_integral (λa:α, (0:β)) μ := by simp [has_finite_integral] variables {α β μ} lemma has_finite_integral.neg {f : α → β} (hfi : has_finite_integral f μ) : has_finite_integral (-f) μ := by simpa [has_finite_integral] using hfi @[simp] lemma has_finite_integral_neg_iff {f : α → β} : has_finite_integral (-f) μ ↔ has_finite_integral f μ := ⟨λ h, neg_neg f ▸ h.neg, has_finite_integral.neg⟩ lemma has_finite_integral.norm {f : α → β} (hfi : has_finite_integral f μ) : has_finite_integral (λa, ∥f a∥) μ := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rwa [has_finite_integral, eq] } lemma has_finite_integral_norm_iff (f : α → β) : has_finite_integral (λa, ∥f a∥) μ ↔ has_finite_integral f μ := has_finite_integral_congr' $ eventually_of_forall $ λ x, norm_norm (f x) section dominated_convergence variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) := λn, (h n).mono $ λ a h, ennreal.of_real_le_of_real h lemma all_ae_tendsto_of_real_norm (h : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) : ∀ᵐ a ∂μ, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ := h.mono $ λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : ∀ᵐ a ∂μ, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) := begin have F_le_bound := all_ae_of_real_F_le_bound h_bound, rw ← ae_all_iff at F_le_bound, apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _), assume a tendsto_norm F_le_bound, exact le_of_tendsto' tendsto_norm (F_le_bound) end lemma has_finite_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_has_finite_integral : has_finite_integral bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : has_finite_integral f μ := /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ⊤` since `bound` is has_finite_integral -/ begin rw has_finite_integral_iff_norm, calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ a, ennreal.of_real (bound a) ∂μ : lintegral_mono_ae $ all_ae_of_real_f_le_bound h_bound h_lim ... < ⊤ : begin rw ← has_finite_integral_iff_of_real, { exact bound_has_finite_integral }, exact (h_bound 0).mono (λ a h, le_trans (norm_nonneg _) h) end end lemma tendsto_lintegral_norm_of_dominated_convergence [measurable_space β] [borel_space β] [second_countable_topology β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_has_finite_integral : has_finite_integral bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := let b := λa, 2 * ennreal.of_real (bound a) in /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ have hb : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a - f a∥ ≤ b a, begin assume n, filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim], assume a h₁ h₂, calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) : begin rw [← ennreal.of_real_add], apply of_real_le_of_real, { apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ } end ... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add h₁ h₂ ... = b a : by rw ← two_mul end, /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ have h : ∀ᵐ a ∂μ, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0), begin rw ← ennreal.of_real_zero, refine h_lim.mono (λ a h, (continuous_of_real.tendsto _).comp _), rwa ← tendsto_iff_norm_tendsto_zero end, /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ begin suffices h : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 (∫⁻ (a:α), 0 ∂μ)), { rwa lintegral_zero at h }, -- Using the dominated convergence theorem. refine tendsto_lintegral_of_dominated_convergence _ _ hb _ _, -- Show `λa, ∥f a - F n a∥` is measurable for all `n` { exact λn, measurable_of_real.comp ((F_measurable n).sub f_measurable).norm }, -- Show `2 * bound` is has_finite_integral { rw has_finite_integral_iff_of_real at bound_has_finite_integral, { calc ∫⁻ a, b a ∂μ = 2 * ∫⁻ a, ennreal.of_real (bound a) ∂μ : by { rw lintegral_const_mul', exact coe_ne_top } ... < ⊤ : mul_lt_top (coe_lt_top) bound_has_finite_integral }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h }, -- Show `∥f a - F n a∥ --> 0` { exact h } end end dominated_convergence section pos_part /-! Lemmas used for defining the positive part of a `L¹` function -/ lemma has_finite_integral.max_zero {f : α → ℝ} (hf : has_finite_integral f μ) : has_finite_integral (λa, max (f a) 0) μ := hf.mono $ eventually_of_forall $ λ x, by simp [real.norm_eq_abs, abs_le, abs_nonneg, le_abs_self] lemma has_finite_integral.min_zero {f : α → ℝ} (hf : has_finite_integral f μ) : has_finite_integral (λa, min (f a) 0) μ := hf.mono $ eventually_of_forall $ λ x, by simp [real.norm_eq_abs, abs_le, abs_nonneg, neg_le, neg_le_abs_self] end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma has_finite_integral.smul (c : 𝕜) {f : α → β} : has_finite_integral f μ → has_finite_integral (c • f) μ := begin simp only [has_finite_integral], assume hfi, calc ∫⁻ (a : α), nnnorm (c • f a) ∂μ = ∫⁻ (a : α), (nnnorm c) * nnnorm (f a) ∂μ : by simp only [nnnorm_smul, ennreal.coe_mul] ... < ⊤ : begin rw lintegral_const_mul', exacts [mul_lt_top coe_lt_top hfi, coe_ne_top] end end lemma has_finite_integral_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : has_finite_integral (c • f) μ ↔ has_finite_integral f μ := begin split, { assume h, simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ }, exact has_finite_integral.smul _ end lemma has_finite_integral.const_mul {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) : has_finite_integral (λ x, c * f x) μ := (has_finite_integral.smul c h : _) lemma has_finite_integral.mul_const {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) : has_finite_integral (λ x, f x * c) μ := by simp_rw [mul_comm, h.const_mul _] end normed_space /-! ### The predicate `integrable` -/ variables [measurable_space β] [measurable_space γ] [measurable_space δ] /-- `integrable f μ` means that `f` is measurable and that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `integrable f` means `integrable f volume`. -/ def integrable (f : α → β) (μ : measure α . volume_tac) : Prop := measurable f ∧ has_finite_integral f μ lemma integrable.measurable {f : α → β} (hf : integrable f μ) : measurable f := hf.1 lemma integrable.has_finite_integral {f : α → β} (hf : integrable f μ) : has_finite_integral f μ := hf.2 lemma integrable.mono {f : α → β} {g : α → γ} (hg : integrable g μ) (hf : measurable f) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : integrable f μ := ⟨hf, hg.has_finite_integral.mono h⟩ lemma integrable.mono' {f : α → β} {g : α → ℝ} (hg : integrable g μ) (hf : measurable f) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : integrable f μ := ⟨hf, hg.has_finite_integral.mono' h⟩ lemma integrable.congr' {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : measurable g) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable g μ := ⟨hg, hf.has_finite_integral.congr' h⟩ lemma integrable_congr' {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable f μ ↔ integrable g μ := ⟨λ h2f, h2f.congr' hg h, λ h2g, h2g.congr' hf $ eventually_eq.symm h⟩ lemma integrable.congr {f g : α → β} (hf : integrable f μ) (hg : measurable g) (h : f =ᵐ[μ] g) : integrable g μ := hf.congr' hg $ h.fun_comp norm lemma integrable_congr {f g : α → β} (hf : measurable f) (hg : measurable g) (h : f =ᵐ[μ] g) : integrable f μ ↔ integrable g μ := integrable_congr' hf hg $ h.fun_comp norm lemma integrable_const_iff {c : β} : integrable (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ⊤ := by rw [integrable, and_iff_right measurable_const, has_finite_integral_const_iff] lemma integrable_const [finite_measure μ] (c : β) : integrable (λ x : α, c) μ := integrable_const_iff.2 $ or.inr $ measure_lt_top _ _ lemma integrable.mono_measure {f : α → β} (h : integrable f ν) (hμ : μ ≤ ν) : integrable f μ := ⟨h.measurable, h.has_finite_integral.mono_measure hμ⟩ lemma integrable.add_measure {f : α → β} (hμ : integrable f μ) (hν : integrable f ν) : integrable f (μ + ν) := ⟨hμ.measurable, hμ.has_finite_integral.add_measure hν.has_finite_integral⟩ lemma integrable.left_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f μ := h.mono_measure $ measure.le_add_right $ le_refl _ lemma integrable.right_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f ν := h.mono_measure $ measure.le_add_left $ le_refl _ @[simp] lemma integrable_add_measure {f : α → β} : integrable f (μ + ν) ↔ integrable f μ ∧ integrable f ν := ⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩ lemma integrable.smul_measure {f : α → β} (h : integrable f μ) {c : ennreal} (hc : c < ⊤) : integrable f (c • μ) := ⟨h.measurable, h.has_finite_integral.smul_measure hc⟩ lemma integrable_map_measure [opens_measurable_space β] {f : α → δ} {g : δ → β} (hf : measurable f) (hg : measurable g) : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by { simp only [integrable, has_finite_integral, lintegral_map hg.ennnorm hf, hf, hg, hg.comp hf] } lemma lintegral_edist_lt_top [second_countable_topology β] [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : ∫⁻ a, edist (f a) (g a) ∂μ < ⊤ := lt_of_le_of_lt (lintegral_edist_triangle hf.measurable hg.measurable (measurable_const : measurable (λa, (0 : β)))) (ennreal.add_lt_top.2 $ by { simp_rw ← has_finite_integral_iff_edist, exact ⟨hf.has_finite_integral, hg.has_finite_integral⟩ }) variables (α β μ) @[simp] lemma integrable_zero : integrable (λ _, (0 : β)) μ := by simp [integrable, measurable_const] variables {α β μ} lemma integrable.add' [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f + g) μ := calc ∫⁻ a, nnnorm (f a + g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ : lintegral_mono (λ a, by exact_mod_cast nnnorm_add_le _ _) ... = _ : lintegral_nnnorm_add hf.measurable hg.measurable ... < ⊤ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.add [borel_space β] [second_countable_topology β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f + g) μ := ⟨hf.measurable.add hg.measurable, hf.add' hg⟩ lemma integrable_finset_sum {ι} [borel_space β] [second_countable_topology β] (s : finset ι) {f : ι → α → β} (hf : ∀ i, integrable (f i) μ) : integrable (λ a, ∑ i in s, f i a) μ := begin refine finset.induction_on s _ _, { simp only [finset.sum_empty, integrable_zero] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], exact (hf _).add ih } end lemma integrable.neg [borel_space β] {f : α → β} (hf : integrable f μ) : integrable (-f) μ := ⟨hf.measurable.neg, hf.has_finite_integral.neg⟩ @[simp] lemma integrable_neg_iff [borel_space β] {f : α → β} : integrable (-f) μ ↔ integrable f μ := ⟨λ h, neg_neg f ▸ h.neg, integrable.neg⟩ lemma integrable.sub' [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f - g) μ := calc ∫⁻ a, nnnorm (f a - g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (-g a) ∂μ : lintegral_mono (assume a, by exact_mod_cast nnnorm_add_le _ _ ) ... = _ : by { simp only [nnnorm_neg], exact lintegral_nnnorm_add hf.measurable hg.measurable } ... < ⊤ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.sub [borel_space β] [second_countable_topology β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f - g) μ := hf.add hg.neg lemma integrable.norm [opens_measurable_space β] {f : α → β} (hf : integrable f μ) : integrable (λa, ∥f a∥) μ := ⟨hf.measurable.norm, hf.has_finite_integral.norm⟩ lemma integrable_norm_iff [opens_measurable_space β] {f : α → β} (hf : measurable f) : integrable (λa, ∥f a∥) μ ↔ integrable f μ := by simp_rw [integrable, and_iff_right hf, and_iff_right hf.norm, has_finite_integral_norm_iff] lemma integrable.prod_mk [opens_measurable_space β] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : integrable g μ) : integrable (λ x, (f x, g x)) μ := ⟨hf.measurable.prod_mk hg.measurable, (hf.norm.add' hg.norm).mono $ eventually_of_forall $ λ x, calc max ∥f x∥ ∥g x∥ ≤ ∥f x∥ + ∥g x∥ : max_le_add_of_nonneg (norm_nonneg _) (norm_nonneg _) ... ≤ ∥(∥f x∥ + ∥g x∥)∥ : le_abs_self _⟩ section pos_part /-! ### Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.max_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, max (f a) 0) μ := ⟨hf.measurable.max measurable_const, hf.has_finite_integral.max_zero⟩ lemma integrable.min_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, min (f a) 0) μ := ⟨hf.measurable.min measurable_const, hf.has_finite_integral.min_zero⟩ end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul [borel_space β] (c : 𝕜) {f : α → β} (hf : integrable f μ) : integrable (c • f) μ := ⟨hf.measurable.const_smul c, hf.has_finite_integral.smul c⟩ lemma integrable_smul_iff [borel_space β] {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (c • f) μ ↔ integrable f μ := and_congr (measurable_const_smul_iff hc) (has_finite_integral_smul_iff hc f) lemma integrable.const_mul {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, c * f x) μ := integrable.smul c h lemma integrable.mul_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, f x * c) μ := by simp_rw [mul_comm, h.const_mul _] end normed_space section normed_space_over_complete_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma integrable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : integrable (λ x, f x • c) μ ↔ integrable f μ := begin simp_rw [integrable, measurable_smul_const hc, and.congr_right_iff, has_finite_integral, nnnorm_smul, ennreal.coe_mul], intro hf, rw [lintegral_mul_const' _ _ ennreal.coe_ne_top, ennreal.mul_lt_top_iff], have : ∀ x : ennreal, x = 0 → x < ⊤ := by simp, simp [hc, or_iff_left_of_imp (this _)] end end normed_space_over_complete_field variables [second_countable_topology β] /-! ### The predicate `integrable` on measurable functions modulo a.e.-equality -/ namespace ae_eq_fun section variable [opens_measurable_space β] /-- A class of almost everywhere equal functions is `integrable` if it has a finite distance to the origin. It means the same thing as the predicate `integrable` over functions. -/ def integrable (f : α →ₘ[μ] β) : Prop := f ∈ ball (0 : α →ₘ[μ] β) ⊤ lemma integrable_mk {f : α → β} (hf : measurable f) : (integrable (mk f hf : α →ₘ[μ] β)) ↔ measure_theory.integrable f μ := by simp [integrable, zero_def, edist_mk_mk', measure_theory.integrable, nndist_eq_nnnorm, has_finite_integral, hf] lemma integrable_coe_fn {f : α →ₘ[μ] β} : (measure_theory.integrable f μ) ↔ integrable f := by rw [← integrable_mk, mk_coe_fn] lemma integrable_zero : integrable (0 : α →ₘ[μ] β) := mem_ball_self coe_lt_top end section variable [borel_space β] lemma integrable.add {f g : α →ₘ[μ] β} : integrable f → integrable g → integrable (f + g) := begin refine induction_on₂ f g (λ f hf g hg hfi hgi, _), simp only [integrable_mk, mk_add_mk] at hfi hgi ⊢, exact hfi.add hgi end lemma integrable.neg {f : α →ₘ[μ] β} : integrable f → integrable (-f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg lemma integrable.sub {f g : α →ₘ[μ] β} (hf : integrable f) (hg : integrable g) : integrable (f - g) := hf.add hg.neg protected lemma is_add_subgroup : is_add_subgroup (ball (0 : α →ₘ[μ] β) ⊤) := { zero_mem := integrable_zero, add_mem := λ _ _, integrable.add, neg_mem := λ _, integrable.neg } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul {c : 𝕜} {f : α →ₘ[μ] β} : integrable f → integrable (c • f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 $ ((integrable_mk hfm).1 hfi).smul _ end normed_space end end ae_eq_fun /-! ### The `L¹` space of functions -/ variables (α β) /-- The space of equivalence classes of integrable (and measurable) functions, where two integrable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def l1 [opens_measurable_space β] (μ : measure α) : Type* := {f : α →ₘ[μ] β // f.integrable} notation α ` →₁[`:25 μ `] ` β := l1 α β μ variables {α β} namespace l1 open ae_eq_fun local attribute [instance] ae_eq_fun.is_add_subgroup section variable [opens_measurable_space β] instance : has_coe (α →₁[μ] β) (α →ₘ[μ] β) := coe_subtype instance : has_coe_to_fun (α →₁[μ] β) := ⟨λ f, α → β, λ f, ⇑(f : α →ₘ[μ] β)⟩ @[simp, norm_cast] lemma coe_coe (f : α →₁[μ] β) : ⇑(f : α →ₘ[μ] β) = f := rfl protected lemma eq {f g : α →₁[μ] β} : (f : α →ₘ[μ] β) = (g : α →ₘ[μ] β) → f = g := subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁[μ] β} : (f : α →ₘ[μ] β) = (g : α →ₘ[μ] β) ↔ f = g := iff.intro (l1.eq) (congr_arg coe) /- TODO : order structure of l1-/ /-- `L¹` space forms a `emetric_space`, with the emetric being inherited from almost everywhere functions, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ instance : emetric_space (α →₁[μ] β) := subtype.emetric_space /-- `L¹` space forms a `metric_space`, with the metric being inherited from almost everywhere functions, i.e., `edist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a))`. -/ instance : metric_space (α →₁[μ] β) := metric_space_emetric_ball 0 ⊤ end variable [borel_space β] instance : add_comm_group (α →₁[μ] β) := subtype.add_comm_group instance : inhabited (α →₁[μ] β) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁[μ] β) : α →ₘ[μ] β) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁[μ] β) : ((f + g : α →₁[μ] β) : α →ₘ[μ] β) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁[μ] β) : ((-f : α →₁[μ] β) : α →ₘ[μ] β) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁[μ] β) : ((f - g : α →₁[μ] β) : α →ₘ[μ] β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁[μ] β) : edist f g = edist (f : α →ₘ[μ] β) (g : α →ₘ[μ] β) := rfl lemma dist_eq (f g : α →₁[μ] β) : dist f g = ennreal.to_real (edist (f : α →ₘ[μ] β) (g : α →ₘ[μ] β)) := rfl /-- The norm on `L¹` space is defined to be `∥f∥ = ∫⁻ a, edist (f a) 0`. -/ instance : has_norm (α →₁[μ] β) := ⟨λ f, dist f 0⟩ lemma norm_eq (f : α →₁[μ] β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ[μ] β) 0) := rfl instance : normed_group (α →₁[μ] β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add], rw edist_add_right } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] instance : has_scalar 𝕜 (α →₁[μ] β) := ⟨λ x f, ⟨x • (f : α →ₘ[μ] β), ae_eq_fun.integrable.smul f.2⟩⟩ @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁[μ] β) : ((c • f : α →₁[μ] β) : α →ₘ[μ] β) = c • (f : α →ₘ[μ] β) := rfl instance : semimodule 𝕜 (α →₁[μ] β) := { one_smul := λf, l1.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, l1.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, l1.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, l1.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, l1.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, l1.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } instance : normed_space 𝕜 (α →₁[μ] β) := ⟨ begin rintros x ⟨f, hf⟩, show ennreal.to_real (edist (x • f) 0) ≤ ∥x∥ * ennreal.to_real (edist f 0), rw [edist_smul, to_real_of_real_mul], exact norm_nonneg _ end ⟩ end normed_space section of_fun /-- Construct the equivalence class `[f]` of a measurable and integrable function `f`. -/ def of_fun (f : α → β) (hf : integrable f μ) : (α →₁[μ] β) := ⟨mk f hf.measurable, by { rw integrable_mk, exact hf }⟩ @[simp] lemma of_fun_eq_mk (f : α → β) (hf : integrable f μ) : (of_fun f hf : α →ₘ[μ] β) = mk f hf.measurable := rfl lemma of_fun_eq_of_fun (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : of_fun f hf = of_fun g hg ↔ f =ᵐ[μ] g := by { rw ← l1.eq_iff, simp only [of_fun_eq_mk, mk_eq_mk] } lemma of_fun_zero : of_fun (λ _, (0 : β)) (integrable_zero α β μ) = 0 := rfl lemma of_fun_add (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : of_fun (f + g) (hf.add hg) = of_fun f hf + of_fun g hg := rfl lemma of_fun_neg (f : α → β) (hf : integrable f μ) : of_fun (- f) (integrable.neg hf) = - of_fun f hf := rfl lemma of_fun_sub (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : of_fun (f - g) (hf.sub hg) = of_fun f hf - of_fun g hg := rfl lemma norm_of_fun (f : α → β) (hf : integrable f μ) : ∥ of_fun f hf ∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) := rfl lemma norm_of_fun_eq_lintegral_norm (f : α → β) (hf : integrable f μ) : ∥ of_fun f hf ∥ = ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := by { rw [norm_of_fun, lintegral_norm_eq_lintegral_edist] } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_fun_smul (f : α → β) (hf : integrable f μ) (k : 𝕜) : of_fun (λa, k • f a) (hf.smul k) = k • of_fun f hf := rfl end of_fun section to_fun protected lemma measurable (f : α →₁[μ] β) : measurable f := f.1.measurable lemma measurable_norm (f : α →₁[μ] β) : measurable (λ a, ∥f a∥) := f.measurable.norm protected lemma integrable (f : α →₁[μ] β) : integrable ⇑f μ := integrable_coe_fn.2 f.2 protected lemma has_finite_integral (f : α →₁[μ] β) : has_finite_integral ⇑f μ := f.integrable.has_finite_integral lemma integrable_norm (f : α →₁[μ] β) : integrable (λ a, ∥f a∥) μ := (integrable_norm_iff f.measurable).mpr f.integrable lemma of_fun_to_fun (f : α →₁[μ] β) : of_fun f f.integrable = f := subtype.ext (f : α →ₘ[μ] β).mk_coe_fn lemma mk_to_fun (f : α →₁[μ] β) : (mk f f.measurable : α →ₘ[μ] β) = f := by { rw ← of_fun_eq_mk, rw l1.eq_iff, exact of_fun_to_fun f } lemma to_fun_of_fun (f : α → β) (hf : integrable f μ) : ⇑(of_fun f hf : α →₁[μ] β) =ᵐ[μ] f := coe_fn_mk f hf.measurable variables (α β) lemma zero_to_fun : ⇑(0 : α →₁[μ] β) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero variables {α β} lemma add_to_fun (f g : α →₁[μ] β) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _ lemma neg_to_fun (f : α →₁[μ] β) : ⇑(-f) =ᵐ[μ] -⇑f := ae_eq_fun.coe_fn_neg _ lemma sub_to_fun (f g : α →₁[μ] β) : ⇑(f - g) =ᵐ[μ] ⇑f - ⇑g := ae_eq_fun.coe_fn_sub _ _ lemma dist_to_fun (f g : α →₁[μ] β) : dist f g = ennreal.to_real (∫⁻ x, edist (f x) (g x) ∂μ) := by { simp only [← coe_coe, dist_eq, edist_eq_coe] } lemma norm_eq_nnnorm_to_fun (f : α →₁[μ] β) : ∥f∥ = ennreal.to_real (∫⁻ a, nnnorm (f a) ∂μ) := by { rw [← coe_coe, lintegral_nnnorm_eq_lintegral_edist, ← edist_zero_eq_coe], refl } lemma norm_eq_norm_to_fun (f : α →₁[μ] β) : ∥f∥ = ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := by { rw norm_eq_nnnorm_to_fun, congr, funext, rw of_real_norm_eq_coe_nnnorm } lemma lintegral_edist_to_fun_lt_top (f g : α →₁[μ] β) : (∫⁻ a, edist (f a) (g a) ∂μ) < ⊤ := lintegral_edist_lt_top f.integrable g.integrable variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_fun (c : 𝕜) (f : α →₁[μ] β) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _ lemma norm_eq_lintegral (f : α →₁[μ] β) : ∥f∥ = (∫⁻ x, (nnnorm (f x) : ennreal) ∂μ).to_real := by simp [l1.norm_eq, ae_eq_fun.edist_zero_eq_coe, ← edist_eq_coe_nnnorm] /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ lemma norm_sub_eq_lintegral (f g : α →₁[μ] β) : ∥f - g∥ = (∫⁻ x, (nnnorm (f x - g x) : ennreal) ∂μ).to_real := begin simp_rw [l1.norm_eq, ae_eq_fun.edist_zero_eq_coe, ← edist_eq_coe_nnnorm], rw lintegral_congr_ae, refine (ae_eq_fun.coe_fn_sub (f : α →ₘ[μ] β) g).mp _, apply eventually_of_forall, intros x hx, simp [hx] end lemma of_real_norm_eq_lintegral (f : α →₁[μ] β) : ennreal.of_real ∥f∥ = ∫⁻ x, (nnnorm (f x) : ennreal) ∂μ := by { rw [norm_eq_lintegral, ennreal.of_real_to_real], rw [← ennreal.lt_top_iff_ne_top], exact f.has_finite_integral } /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `of_real_norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ lemma of_real_norm_sub_eq_lintegral (f g : α →₁[μ] β) : ennreal.of_real ∥f - g∥ = ∫⁻ x, (nnnorm (f x - g x) : ennreal) ∂μ := begin simp_rw [of_real_norm_eq_lintegral, ← edist_eq_coe_nnnorm], apply lintegral_congr_ae, refine (ae_eq_fun.coe_fn_sub (f : α →ₘ[μ] β) g).mp _, apply eventually_of_forall, intros x hx, simp only [l1.coe_coe, pi.sub_apply] at hx, simp_rw [← hx, ← l1.coe_sub, l1.coe_coe] end end to_fun section pos_part /-- Positive part of a function in `L¹` space. -/ def pos_part (f : α →₁[μ] ℝ) : α →₁[μ] ℝ := ⟨ae_eq_fun.pos_part f, begin rw [← ae_eq_fun.integrable_coe_fn, integrable_congr (ae_eq_fun.measurable _) (f.measurable.max measurable_const) (coe_fn_pos_part _)], exact f.integrable.max_zero end ⟩ /-- Negative part of a function in `L¹` space. -/ def neg_part (f : α →₁[μ] ℝ) : α →₁[μ] ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁[μ] ℝ) : (f.pos_part : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl lemma pos_part_to_fun (f : α →₁[μ] ℝ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 := ae_eq_fun.coe_fn_pos_part _ lemma neg_part_to_fun_eq_max (f : α →₁[μ] ℝ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 := begin rw neg_part, filter_upwards [pos_part_to_fun (-f), neg_to_fun f], assume a h₁ h₂, rw [h₁, h₂, pi.neg_apply] end lemma neg_part_to_fun_eq_min (f : α →₁[μ] ℝ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 := (neg_part_to_fun_eq_max f).mono $ assume a h, by rw [h, ← max_neg_neg, neg_zero] lemma norm_le_norm_of_ae_le {f g : α →₁[μ] β} (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : ∥f∥ ≤ ∥g∥ := begin simp only [l1.norm_eq_norm_to_fun], rw to_real_le_to_real, { apply lintegral_mono_ae, exact h.mono (λ a h, of_real_le_of_real h) }, { rw [← lt_top_iff_ne_top, ← has_finite_integral_iff_norm], exact f.has_finite_integral }, { rw [← lt_top_iff_ne_top, ← has_finite_integral_iff_norm], exact g.has_finite_integral } end lemma continuous_pos_part : continuous $ λf : α →₁[μ] ℝ, pos_part f := begin simp only [metric.continuous_iff], assume g ε hε, use ε, use hε, simp only [dist_eq_norm], assume f hfg, refine lt_of_le_of_lt (norm_le_norm_of_ae_le _) hfg, filter_upwards [l1.sub_to_fun f g, l1.sub_to_fun (pos_part f) (pos_part g), pos_part_to_fun f, pos_part_to_fun g], assume a h₁ h₂ h₃ h₄, simp only [real.norm_eq_abs, h₁, h₂, h₃, h₄, pi.sub_apply], exact abs_max_sub_max_le_abs _ _ _ end lemma continuous_neg_part : continuous $ λf : α →₁[μ] ℝ, neg_part f := have eq : (λf : α →₁[μ] ℝ, neg_part f) = (λf : α →₁[μ] ℝ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part /- TODO: l1 is a complete space -/ end l1 end measure_theory open measure_theory lemma measurable.integrable_zero [measurable_space β] {f : α → β} (hf : measurable f) : integrable f 0 := ⟨hf, has_finite_integral_zero_measure f⟩
3c8f54dae3be1dbee7e2f0483a96067c77d33cb8
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/Tactic/Config.lean
b2f30d517c82fee938f8a4fdf4e26b7f72c1ebf6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
1,237
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Eval import Lean.Elab.Tactic.Basic import Lean.Elab.SyntheticMVars import Lean.Linter.MissingDocs namespace Lean.Elab.Tactic open Meta macro (name := configElab) doc?:(docComment)? "declare_config_elab" elabName:ident type:ident : command => `(unsafe def evalUnsafe (e : Expr) : TermElabM $type := Meta.evalExpr' (safety := .unsafe) $type ``$type e @[implementedBy evalUnsafe] opaque eval (e : Expr) : TermElabM $type $[$doc?:docComment]? def $elabName (optConfig : Syntax) : TermElabM $type := do if optConfig.isNone then return { : $type } else let c ← withoutModifyingStateWithInfoAndMessages <| withLCtx {} {} <| withSaveInfoContext <| Term.withSynthesize do let c ← Term.elabTermEnsuringType optConfig[0][3] (Lean.mkConst ``$type) Term.synthesizeSyntheticMVarsNoPostponing instantiateMVars c eval c ) open Linter.MissingDocs in @[builtinMissingDocsHandler Elab.Tactic.configElab] def checkConfigElab : SimpleHandler := mkSimpleHandler "config elab" end Lean.Elab.Tactic
9ef7b45311040ddafb5e438141ab05f06dec5115
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/algebra/bundled.hlean
cb6942964e4928dbab989be2ad091fca5ba2fb1c
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
5,629
hlean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Bundled structures -/ import algebra.group open algebra pointed is_trunc namespace algebra structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] structure Group := (carrier : Type) (struct : group carrier) attribute Group.carrier [coercion] attribute Group.struct [instance] section local attribute Group.struct [instance] definition pSet_of_Group [constructor] [reducible] [coercion] (G : Group) : Set* := ptrunctype.mk G !semigroup.is_set_carrier 1 end attribute algebra._trans_of_pSet_of_Group [unfold 1] attribute algebra._trans_of_pSet_of_Group_1 algebra._trans_of_pSet_of_Group_2 [constructor] definition pType_of_Group [reducible] [constructor] : Group → Type* := algebra._trans_of_pSet_of_Group_1 definition Set_of_Group [reducible] [constructor] : Group → Set := algebra._trans_of_pSet_of_Group_2 definition AddGroup : Type := Group definition AddGroup.mk [constructor] [reducible] (G : Type) (H : add_group G) : AddGroup := Group.mk G H definition AddGroup.struct [reducible] (G : AddGroup) : add_group G := Group.struct G attribute AddGroup.struct Group.struct [instance] [priority 2000] structure AbGroup := (carrier : Type) (struct : ab_group carrier) attribute AbGroup.carrier [coercion] definition AddAbGroup : Type := AbGroup definition AddAbGroup.mk [constructor] [reducible] (G : Type) (H : add_ab_group G) : AddAbGroup := AbGroup.mk G H definition AddAbGroup.struct [reducible] (G : AddAbGroup) : add_ab_group G := AbGroup.struct G attribute AddAbGroup.struct AbGroup.struct [instance] [priority 2000] definition Group_of_AbGroup [coercion] [constructor] (G : AbGroup) : Group := Group.mk G _ attribute algebra._trans_of_Group_of_AbGroup_1 algebra._trans_of_Group_of_AbGroup algebra._trans_of_Group_of_AbGroup_3 [constructor] attribute algebra._trans_of_Group_of_AbGroup_2 [unfold 1] definition ab_group_AbGroup [instance] (G : AbGroup) : ab_group G := AbGroup.struct G definition add_ab_group_AddAbGroup [instance] (G : AddAbGroup) : add_ab_group G := AbGroup.struct G -- structure AddSemigroup := -- (carrier : Type) (struct : add_semigroup carrier) -- attribute AddSemigroup.carrier [coercion] -- attribute AddSemigroup.struct [instance] -- structure AddCommSemigroup := -- (carrier : Type) (struct : add_comm_semigroup carrier) -- attribute AddCommSemigroup.carrier [coercion] -- attribute AddCommSemigroup.struct [instance] -- structure AddMonoid := -- (carrier : Type) (struct : add_monoid carrier) -- attribute AddMonoid.carrier [coercion] -- attribute AddMonoid.struct [instance] -- structure AddCommMonoid := -- (carrier : Type) (struct : add_comm_monoid carrier) -- attribute AddCommMonoid.carrier [coercion] -- attribute AddCommMonoid.struct [instance] -- structure AddGroup := -- (carrier : Type) (struct : add_group carrier) -- attribute AddGroup.carrier [coercion] -- attribute AddGroup.struct [instance] -- structure AddAbGroup := -- (carrier : Type) (struct : add_ab_group carrier) -- attribute AddAbGroup.carrier [coercion] -- attribute AddAbGroup.struct [instance] -- some bundled infinity-structures structure InfGroup := (carrier : Type) (struct : inf_group carrier) attribute InfGroup.carrier [coercion] attribute InfGroup.struct [instance] section local attribute InfGroup.struct [instance] definition pType_of_InfGroup [constructor] [reducible] [coercion] (G : InfGroup) : Type* := pType.mk G 1 end attribute algebra._trans_of_pType_of_InfGroup [unfold 1] definition AddInfGroup : Type := InfGroup definition AddInfGroup.mk [constructor] [reducible] (G : Type) (H : add_inf_group G) : AddInfGroup := InfGroup.mk G H definition AddInfGroup.struct [reducible] (G : AddInfGroup) : add_inf_group G := InfGroup.struct G attribute AddInfGroup.struct InfGroup.struct [instance] [priority 2000] structure AbInfGroup := (carrier : Type) (struct : ab_inf_group carrier) attribute AbInfGroup.carrier [coercion] definition AddAbInfGroup : Type := AbInfGroup definition AddAbInfGroup.mk [constructor] [reducible] (G : Type) (H : add_ab_inf_group G) : AddAbInfGroup := AbInfGroup.mk G H definition AddAbInfGroup.struct [reducible] (G : AddAbInfGroup) : add_ab_inf_group G := AbInfGroup.struct G attribute AddAbInfGroup.struct AbInfGroup.struct [instance] [priority 2000] definition InfGroup_of_AbInfGroup [coercion] [constructor] (G : AbInfGroup) : InfGroup := InfGroup.mk G _ attribute algebra._trans_of_InfGroup_of_AbInfGroup_1 [constructor] attribute algebra._trans_of_InfGroup_of_AbInfGroup [unfold 1] definition InfGroup_of_Group [constructor] (G : Group) : InfGroup := InfGroup.mk G _ definition AddInfGroup_of_AddGroup [constructor] (G : AddGroup) : AddInfGroup := AddInfGroup.mk G _ definition AbInfGroup_of_AbGroup [constructor] (G : AbGroup) : AbInfGroup := AbInfGroup.mk G _ definition AddAbInfGroup_of_AddAbGroup [constructor] (G : AddAbGroup) : AddAbInfGroup := AddAbInfGroup.mk G _ end algebra
dd18100229ac2cd6cc5d5dd097f0532aa4e9a071
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/Simp/SimpM.lean
59ae4baa69ccd99bb3b2d1d3727d86dc7b5b3c30
[ "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
9,104
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.ImplementedByAttr import Lean.Compiler.LCNF.Renaming import Lean.Compiler.LCNF.ElimDead import Lean.Compiler.LCNF.AlphaEqv import Lean.Compiler.LCNF.PrettyPrinter import Lean.Compiler.LCNF.Bind import Lean.Compiler.LCNF.Internalize import Lean.Compiler.LCNF.Simp.JpCases import Lean.Compiler.LCNF.Simp.DiscrM import Lean.Compiler.LCNF.Simp.FunDeclInfo import Lean.Compiler.LCNF.Simp.Config namespace Lean.Compiler.LCNF namespace Simp structure Context where /-- Name of the declaration being simplified. We currently use this information because we are generating phase1 declarations on demand, and it may trigger non-termination when trying to access the phase1 declaration. -/ declName : Name config : Config := {} /-- Stack of global declarations being recursively inlined. -/ inlineStack : List Name := [] /-- Mapping from declaration names to number of occurrences at `inlineStack` -/ inlineStackOccs : PHashMap Name Nat := {} structure State where /-- Free variable substitution. We use it to implement inlining and removing redundant variables `let _x.i := _x.j` -/ subst : FVarSubst := {} /-- Track used local declarations to be able to eliminate dead variables. -/ used : UsedLocalDecls := {} /-- Mapping containing free variables ids that need to be renamed (i.e., the `binderName`). We use this map to preserve user provide names. -/ binderRenaming : Renaming := {} /-- Mapping used to decide whether a local function declaration must be inlined or not. -/ funDeclInfoMap : FunDeclInfoMap := {} /-- `true` if some simplification was performed in the current simplification pass. -/ simplified : Bool := false /-- Number of visited `let-declarations` and terminal values. This is a performance counter, and currently has no impact on code generation. -/ visited : Nat := 0 /-- Number of definitions inlined. This is a performance counter. -/ inline : Nat := 0 /-- Number of local functions inlined. This is a performance counter. -/ inlineLocal : Nat := 0 abbrev SimpM := ReaderT Context $ StateRefT State DiscrM @[always_inline] instance : Monad SimpM := let i := inferInstanceAs (Monad SimpM); { pure := i.pure, bind := i.bind } instance : MonadFVarSubst SimpM false where getSubst := return (← get).subst instance : MonadFVarSubstState SimpM where modifySubst f := modify fun s => { s with subst := f s.subst } /-- Set the `simplified` flag to `true`. -/ def markSimplified : SimpM Unit := modify fun s => { s with simplified := true } /-- Increment `visited` performance counter. -/ def incVisited : SimpM Unit := modify fun s => { s with visited := s.visited + 1 } /-- Increment `inline` performance counter. It is the number of inlined global declarations. -/ def incInline : SimpM Unit := modify fun s => { s with inline := s.inline + 1 } /-- Increment `inlineLocal` performance counter. It is the number of inlined local function and join point declarations. -/ def incInlineLocal : SimpM Unit := modify fun s => { s with inlineLocal := s.inlineLocal + 1 } /-- Mark the local function declaration or join point with the given id as a "must inline". -/ def addMustInline (fvarId : FVarId) : SimpM Unit := modify fun s => { s with funDeclInfoMap := s.funDeclInfoMap.addMustInline fvarId } /-- Add a new occurrence of local function `fvarId`. -/ def addFunOcc (fvarId : FVarId) : SimpM Unit := modify fun s => { s with funDeclInfoMap := s.funDeclInfoMap.add fvarId } /-- Add a new occurrence of local function `fvarId` in argument position . -/ def addFunHoOcc (fvarId : FVarId) : SimpM Unit := modify fun s => { s with funDeclInfoMap := s.funDeclInfoMap.addHo fvarId } @[inherit_doc FunDeclInfoMap.update] partial def updateFunDeclInfo (code : Code) (mustInline := false) : SimpM Unit := do let map ← modifyGet fun s => (s.funDeclInfoMap, { s with funDeclInfoMap := {} }) let map ← map.update code mustInline modify fun s => { s with funDeclInfoMap := map } /-- Execute `x` with an updated `inlineStack`. If `value` is of the form `const ...`, add `const` to the stack. Otherwise, do not change the `inlineStack`. -/ @[inline] def withInlining (value : LetValue) (recursive : Bool) (x : SimpM α) : SimpM α := do if let .const declName _ _ := value then let numOccs ← check declName withReader (fun ctx => { ctx with inlineStack := declName :: ctx.inlineStack, inlineStackOccs := ctx.inlineStackOccs.insert declName numOccs }) x else x where check (declName : Name) : SimpM Nat := do trace[Compiler.simp.inline] "{declName}" let numOccs := (← read).inlineStackOccs.find? declName |>.getD 0 let numOccs := numOccs + 1 let inlineIfReduce ← if let some decl ← getDecl? declName then pure decl.inlineIfReduceAttr else pure false if recursive && inlineIfReduce && numOccs > (← getConfig).maxRecInlineIfReduce then throwError "function `{declName}` has been recursively inlined more than #{(← getConfig).maxRecInlineIfReduce}, consider removing the attribute `[inline_if_reduce]` from this declaration or increasing the limit using `set_option compiler.maxRecInlineIfReduce <num>`" return numOccs /-- Similar to the default `Lean.withIncRecDepth`, but include the `inlineStack` in the error messsage. -/ @[inline] def withIncRecDepth (x : SimpM α) : SimpM α := do let curr ← MonadRecDepth.getRecDepth let max ← MonadRecDepth.getMaxRecDepth if curr == max then throwMaxRecDepth else MonadRecDepth.withRecDepth (curr+1) x where throwMaxRecDepth : SimpM α := do match (← read).inlineStack with | [] => throwError maxRecDepthErrorMessage | declName :: stack => let mut fmt := f!"{declName}\n" let mut prev := declName let mut ellipsis := false for declName in stack do if prev == declName then unless ellipsis do ellipsis := true fmt := fmt ++ "...\n" else fmt := fmt ++ f!"{declName}\n" prev := declName ellipsis := false throwError "maximum recursion depth reached in the code generator\nfunction inline stack:\n{fmt}" /-- Execute `x` with `fvarId` set as `mustInline`. After execution the original setting is restored. -/ def withAddMustInline (fvarId : FVarId) (x : SimpM α) : SimpM α := do let saved? := (← get).funDeclInfoMap.map.find? fvarId try addMustInline fvarId x finally modify fun s => { s with funDeclInfoMap := s.funDeclInfoMap.restore fvarId saved? } /-- Return true if the given local function declaration or join point id is marked as `once` or `mustInline`. We use this information to decide whether to inline them. -/ def isOnceOrMustInline (fvarId : FVarId) : SimpM Bool := do match (← get).funDeclInfoMap.map.find? fvarId with | some .once | some .mustInline => return true | _ => return false /-- Return `true` if the given code is considered "small". -/ def isSmall (code : Code) : SimpM Bool := return code.sizeLe (← getConfig).smallThreshold /-- Return `true` if the given local function declaration should be inlined. -/ def shouldInlineLocal (decl : FunDecl) : SimpM Bool := do if (← isOnceOrMustInline decl.fvarId) then return true else isSmall decl.value /-- LCNF "Beta-reduce". The equivalent of `(fun params => code) args`. If `mustInline` is true, the local function declarations in the resulting code are marked as `.mustInline`. See comment at `updateFunDeclInfo`. -/ def betaReduce (params : Array Param) (code : Code) (args : Array Arg) (mustInline := false) : SimpM Code := do let mut subst := {} for param in params, arg in args do subst := subst.insert param.fvarId arg.toExpr let code ← code.internalize subst updateFunDeclInfo code mustInline return code /-- Erase the given let-declaration from the local context, and set the `simplified` flag to true. -/ def eraseLetDecl (decl : LetDecl) : SimpM Unit := do LCNF.eraseLetDecl decl markSimplified /-- Erase the given local function declaration from the local context, and set the `simplified` flag to true. -/ def eraseFunDecl (decl : FunDecl) : SimpM Unit := do LCNF.eraseFunDecl decl markSimplified /-- Similar to `LCNF.addFVarSubst`. That is, add the entry `fvarId ↦ fvarId'` to the free variable substitution. If `fvarId` has a non-internal binder name `n`, but `fvarId'` does not, this method also adds the entry `fvarId' ↦ n` to the `binderRenaming` map. The goal is to preserve user provided names. -/ def addFVarSubst (fvarId : FVarId) (fvarId' : FVarId) : SimpM Unit := do LCNF.addFVarSubst fvarId fvarId' let binderName ← getBinderName fvarId unless binderName.isInternal do let binderName' ← getBinderName fvarId' if binderName'.isInternal then modify fun s => { s with binderRenaming := s.binderRenaming.insert fvarId' binderName }
531e39e80d1b658fc17d957e078c757bea7a8e44
54c9ed381c63410c9b6af3b0a1722c41152f037f
/Lib4/PostPort.lean
15dcecba130f4be86a7a722f815ef7924a5a9ac7
[ "Apache-2.0" ]
permissive
dselsam/binport
0233f1aa961a77c4fc96f0dccc780d958c5efc6c
aef374df0e169e2c3f1dc911de240c076315805c
refs/heads/master
1,687,453,448,108
1,627,483,296,000
1,627,483,296,000
333,825,622
0
0
null
null
null
null
UTF-8
Lean
false
false
200
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import PostPort.Coe import PostPort.Pow
1d5cc410266d38f06155834e9504da29f5bfdfe3
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/rewriter15.lean
a437423d50fbe76bc02cddb4b042069e7a9fe664
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
156
lean
import data.nat open nat set_option rewriter.syntactic true example (x : nat) (H1 : x = 0) : x + 0 + 0 = 0 := begin rewrite *add_zero, rewrite H1 end
0fde3f64322c83f92e3fd9964e68a976da715d9c
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/data/option/instances.lean
da7b33cb010074521d415644eea5d8d103a39f96
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,200
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.data.option.basic import init.meta.tactic universes u v @[inline] def option_bind {α : Type u} {β : Type v} : option α → (α → option β) → option β | none b := none | (some a) b := b a instance : monad option := {pure := @some, bind := @option_bind, id_map := λ α x, option.rec rfl (λ x, rfl) x, pure_bind := λ α β x f, rfl, bind_assoc := λ α β γ x f g, option.rec rfl (λ x, rfl) x} def option_orelse {α : Type u} : option α → option α → option α | (some a) o := some a | none (some a) := some a | none none := none instance : alternative option := { option.monad with failure := @none, orelse := @option_orelse } lemma option.eq_of_eq_some {α : Type u} : Π {x y : option α}, (∀z, x = some z ↔ y = some z) → x = y | none none h := rfl | none (some z) h := option.no_confusion ((h z).2 rfl) | (some z) none h := option.no_confusion ((h z).1 rfl) | (some z) (some w) h := option.no_confusion ((h w).2 rfl) (congr_arg some)
529e0557606ccfa6b10b05335c9bd70c046c1034
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Lean/PrettyPrinter/Delaborator/Builtins.lean
13d253bcc6e97ea42d2dfd251d67bb7a521b6394
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,199
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.Basic import Lean.Parser namespace Lean.PrettyPrinter.Delaborator open Lean.Meta open Lean.Parser.Term @[builtinDelab fvar] def delabFVar : Delab := do let Expr.fvar id _ ← getExpr | unreachable! try let l ← getLocalDecl id pure $ mkIdent l.userName catch _ => -- loose free variable, use internal name pure $ mkIdent id -- loose bound variable, use pseudo syntax @[builtinDelab bvar] def delabBVar : Delab := do let Expr.bvar idx _ ← getExpr | unreachable! pure $ mkIdent $ Name.mkSimple $ "#" ++ toString idx @[builtinDelab mvar] def delabMVar : Delab := do let Expr.mvar n _ ← getExpr | unreachable! let n := n.replacePrefix `_uniq `m `(?$(mkIdent n)) @[builtinDelab sort] def delabSort : Delab := do let Expr.sort l _ ← getExpr | unreachable! match l with | Level.zero _ => `(Prop) | Level.succ (Level.zero _) _ => `(Type) | _ => match l.dec with | some l' => `(Type $(Level.quote l' maxPrec!)) | none => `(Sort $(Level.quote l maxPrec!)) -- find shorter names for constants, in reverse to Lean.Elab.ResolveName private def unresolveQualifiedName (ns : Name) (c : Name) : DelabM Name := do let c' := c.replacePrefix ns Name.anonymous; let env ← getEnv guard $ c' != c && !c'.isAnonymous && (!c'.isAtomic || !isProtected env c) pure c' private def unresolveUsingNamespace (c : Name) : Name → DelabM Name | ns@(Name.str p _ _) => unresolveQualifiedName ns c <|> unresolveUsingNamespace c p | _ => failure private def unresolveOpenDecls (c : Name) : List OpenDecl → DelabM Name | [] => failure | OpenDecl.simple ns exs :: openDecls => let c' := c.replacePrefix ns Name.anonymous if c' != c && exs.elem c' then unresolveOpenDecls c openDecls else unresolveQualifiedName ns c <|> unresolveOpenDecls c openDecls | OpenDecl.explicit openedId resolvedId :: openDecls => guard (c == resolvedId) *> pure openedId <|> unresolveOpenDecls c openDecls -- NOTE: not a registered delaborator, as `const` is never called (see [delab] description) def delabConst : Delab := do let Expr.const c ls _ ← getExpr | unreachable! let c ← if (← getPPOption getPPFullNames) then pure c else let ctx ← read let env ← getEnv let as := getRevAliases env c -- might want to use a more clever heuristic such as selecting the shortest alias... let c := as.headD c unresolveUsingNamespace c ctx.currNamespace <|> unresolveOpenDecls c ctx.openDecls <|> pure c let c ← if (← getPPOption getPPPrivateNames) then pure c else pure $ (privateToUserName? c).getD c let ppUnivs ← getPPOption getPPUniverses if ls.isEmpty || !ppUnivs then pure $ mkIdent c else `($(mkIdent c).{$[$(ls.toArray.map quote)],*}) inductive ParamKind where | explicit -- combines implicit params, optParams, and autoParams | implicit (defVal : Option Expr) /-- Return array with n-th element set to kind of n-th parameter of `e`. -/ def getParamKinds (e : Expr) : MetaM (Array ParamKind) := do let t ← inferType e forallTelescopeReducing t fun params _ => params.mapM fun param => do let l ← getLocalDecl param.fvarId! match l.type.getOptParamDefault? with | some val => pure $ ParamKind.implicit val | _ => if l.type.isAutoParam || !l.binderInfo.isExplicit then pure $ ParamKind.implicit none else pure ParamKind.explicit @[builtinDelab app] def delabAppExplicit : Delab := do let (fnStx, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab let paramKinds ← liftM <| getParamKinds fn <|> pure #[] let stx ← if paramKinds.any (fun k => match k with | ParamKind.explicit => false | _ => true) = true then `(@$stx) else pure stx pure (stx, #[])) (fun ⟨fnStx, argStxs⟩ => do let argStx ← delab pure (fnStx, argStxs.push argStx)) Syntax.mkApp fnStx argStxs @[builtinDelab app] def delabAppImplicit : Delab := whenNotPPOption getPPExplicit do let (fnStx, _, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab let paramKinds ← liftM (getParamKinds fn <|> pure #[]) pure (stx, paramKinds.toList, #[])) (fun (fnStx, paramKinds, argStxs) => do let arg ← getExpr; let implicit : Bool := match paramKinds with -- TODO: check why we need `: Bool` here | [ParamKind.implicit (some v)] => !v.hasLooseBVars && v == arg | ParamKind.implicit none :: _ => true | _ => false if implicit then pure (fnStx, paramKinds.tailD [], argStxs) else do let argStx ← delab pure (fnStx, paramKinds.tailD [], argStxs.push argStx)) Syntax.mkApp fnStx argStxs @[builtinDelab app] def delabAppWithUnexpander : Delab := whenPPOption getPPNotation do let Expr.const c _ _ ← pure (← getExpr).getAppFn | failure let stx ← delabAppImplicit match stx with | `($cPP:ident $args*) => do let some (f::_) ← pure <| (appUnexpanderAttribute.ext.getState (← getEnv)).table.find? c | pure stx let EStateM.Result.ok stx _ ← f stx |>.run () | pure stx pure stx | _ => pure stx /-- State for `delabAppMatch` and helpers. -/ structure AppMatchState where info : MatcherInfo matcherTy : Expr params : Array Expr := #[] hasMotive : Bool := false discrs : Array Syntax := #[] rhss : Array Syntax := #[] -- additional arguments applied to the result of the `match` expression moreArgs : Array Syntax := #[] /-- Skip `numParams` binders. -/ private def skippingBinders {α} : (numParams : Nat) → (x : DelabM α) → DelabM α | 0, x => x | numParams+1, x => withBindingBodyUnusedName fun _ => skippingBinders numParams x /-- Extract arguments of motive applications from the matcher type. For the example below: `#[#[`([])], #[`(a::as)]]` -/ private def delabPatterns (st : AppMatchState) : DelabM (Array (Array Syntax)) := do let ty ← instantiateForall st.matcherTy st.params forallTelescope ty fun params _ => do -- skip motive and discriminators let alts := Array.ofSubarray $ params[1 + st.discrs.size:] alts.mapIdxM fun idx alt => do let ty ← inferType alt withReader ({ · with expr := ty }) $ skippingBinders st.info.altNumParams[idx] do withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (← delab)) /-- Delaborate applications of "matchers" such as ``` List.map.match_1 : {α : Type _} → (motive : List α → Sort _) → (x : List α) → (Unit → motive List.nil) → ((a : α) → (as : List α) → motive (a :: as)) → motive x ``` -/ @[builtinDelab app] def delabAppMatch : Delab := whenPPOption getPPNotation do -- incrementally fill `AppMatchState` from arguments let st ← withAppFnArgs (do let (Expr.const c us _) ← getExpr | failure let (some info) ← getMatcherInfo? c | failure { matcherTy := (← getConstInfo c).instantiateTypeLevelParams us, info := info, : AppMatchState }) (fun st => do if st.params.size < st.info.numParams then pure { st with params := st.params.push (← getExpr) } else if !st.hasMotive then -- discard motive argument pure { st with hasMotive := true } else if st.discrs.size < st.info.numDiscrs then pure { st with discrs := st.discrs.push (← delab) } else if st.rhss.size < st.info.altNumParams.size then pure { st with rhss := st.rhss.push (← skippingBinders st.info.altNumParams[st.rhss.size] delab) } else pure { st with moreArgs := st.moreArgs.push (← delab) }) if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then -- underapplied failure match st.discrs, st.rhss with | #[discr], #[] => let stx ← `(nomatch $discr) Syntax.mkApp stx st.moreArgs | _, #[] => failure | _, _ => let pats ← delabPatterns st let stx ← `(match $[$st.discrs:term],* with $[| $pats,* => $st.rhss]*) Syntax.mkApp stx st.moreArgs @[builtinDelab mdata] def delabMData : Delab := do -- only interpret `pp.` values by default let Expr.mdata m _ _ ← getExpr | unreachable! let mut posOpts := (← read).optionsPerPos let mut inaccessible := false let pos := (← read).pos for (k, v) in m do if (`pp).isPrefixOf k then let opts := posOpts.find? pos |>.getD {} posOpts := posOpts.insert pos (opts.insert k v) if k == `inaccessible then inaccessible := true withReader ({ · with optionsPerPos := posOpts }) do let s ← withMDataExpr delab if inaccessible then `(.($s)) else pure s /-- Check for a `Syntax.ident` of the given name anywhere in the tree. This is usually a bad idea since it does not check for shadowing bindings, but in the delaborator we assume that bindings are never shadowed. -/ partial def hasIdent (id : Name) : Syntax → Bool | Syntax.ident _ _ id' _ => id == id' | Syntax.node _ args => args.any (hasIdent id) | _ => false /-- Return `true` iff current binder should be merged with the nested binder, if any, into a single binder group: * both binders must have same binder info and domain * they cannot be inst-implicit (`[a b : A]` is not valid syntax) * `pp.binder_types` must be the same value for both terms * prefer `fun a b` over `fun (a b)` -/ private def shouldGroupWithNext : DelabM Bool := do let e ← getExpr let ppEType ← getPPOption getPPBinderTypes; let go (e' : Expr) := do let ppE'Type ← withBindingBody `_ $ getPPOption getPPBinderTypes pure $ e.binderInfo == e'.binderInfo && e.bindingDomain! == e'.bindingDomain! && e'.binderInfo != BinderInfo.instImplicit && ppEType == ppE'Type && (e'.binderInfo != BinderInfo.default || ppE'Type) match e with | Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e' | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e' | _ => pure false private partial def delabBinders (delabGroup : Array Syntax → Syntax → Delab) : optParam (Array Syntax) #[] → Delab -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types. | curNames => do if (← shouldGroupWithNext) then -- group with nested binder => recurse immediately withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN) else -- don't group => delab body and prepend current binder group let (stx, stxN) ← withBindingBodyUnusedName fun stxN => do (← delab, stxN) delabGroup (curNames.push stxN) stx @[builtinDelab lam] def delabLam : Delab := delabBinders fun curNames stxBody => do let e ← getExpr let stxT ← withBindingDomain delab let ppTypes ← getPPOption getPPBinderTypes let expl ← getPPOption getPPExplicit -- leave lambda implicit if possible let blockImplicitLambda := expl || e.binderInfo == BinderInfo.default || Elab.Term.blockImplicitLambda stxBody || curNames.any (fun n => hasIdent n.getId stxBody); if !blockImplicitLambda then pure stxBody else let group ← match e.binderInfo, ppTypes with | BinderInfo.default, true => -- "default" binder group is the only one that expects binder names -- as a term, i.e. a single `Syntax.ident` or an application thereof let stxCurNames ← if curNames.size > 1 then `($(curNames.get! 0) $(curNames.eraseIdx 0)*) else pure $ curNames.get! 0; `(funBinder| ($stxCurNames : $stxT)) | BinderInfo.default, false => pure curNames.back -- here `curNames.size == 1` | BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT}) | BinderInfo.implicit, false => `(funBinder| {$curNames*}) | BinderInfo.instImplicit, _ => `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1` | _ , _ => unreachable!; match stxBody with | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody) | _ => `(fun $group => $stxBody) @[builtinDelab forallE] def delabForall : Delab := delabBinders fun curNames stxBody => do let e ← getExpr let stxT ← withBindingDomain delab match e.binderInfo with | BinderInfo.default => -- heuristic: use non-dependent arrows only if possible for whole group to avoid -- noisy mix like `(α : Type) → Type → (γ : Type) → ...`. let dependent := curNames.any $ fun n => hasIdent n.getId stxBody -- NOTE: non-dependent arrows are available only for the default binder info if dependent then do `(($curNames* : $stxT) → $stxBody) else curNames.foldrM (fun _ stxBody => `($stxT → $stxBody)) stxBody | BinderInfo.implicit => `({$curNames* : $stxT} → $stxBody) -- here `curNames.size == 1` | BinderInfo.instImplicit => `([$curNames.back : $stxT] → $stxBody) | _ => unreachable! @[builtinDelab letE] def delabLetE : Delab := do let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n let stxT ← descend t 0 delab let stxV ← descend v 1 delab let stxB ← withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 delab `(let $(mkIdent n) : $stxT := $stxV; $stxB) @[builtinDelab lit] def delabLit : Delab := do let Expr.lit l _ ← getExpr | unreachable! match l with | Literal.natVal n => pure $ quote n | Literal.strVal s => pure $ quote s -- `@OfNat.ofNat _ n _` ~> `n` @[builtinDelab app.OfNat.ofNat] def delabOfNat : Delab := whenPPOption getPPCoercions do let (Expr.app (Expr.app _ (Expr.lit (Literal.natVal n) _) _) _ _) ← getExpr | failure return quote n -- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true` @[builtinDelab app.OfScientific.ofScientific] def delabOfScientific : Delab := whenPPOption getPPCoercions do let expr ← getExpr guard <| expr.getAppNumArgs == 5 let Expr.lit (Literal.natVal m) _ ← pure (expr.getArg! 2) | failure let Expr.lit (Literal.natVal e) _ ← pure (expr.getArg! 4) | failure let s ← match expr.getArg! 3 with | Expr.const `Bool.true _ _ => pure true | Expr.const `Bool.false _ _ => pure false | _ => failure let str := toString m if s && e == str.length then return Syntax.mkScientificLit ("0." ++ str) else if s && e < str.length then let mStr := str.extract 0 (str.length - e) let eStr := str.extract (str.length - e) str.length return Syntax.mkScientificLit (mStr ++ "." ++ eStr) else return Syntax.mkScientificLit (str ++ "e" ++ (if s then "-" else "") ++ toString e) /-- Delaborate a projection primitive. These do not usually occur in user code, but are pretty-printed when e.g. `#print`ing a projection function. -/ @[builtinDelab proj] def delabProj : Delab := do let Expr.proj _ idx _ _ ← getExpr | unreachable! let e ← withProj delab -- not perfectly authentic: elaborates to the `idx`-th named projection -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual -- `proj`. let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1)); `($(e).$idx:fieldIdx) /-- Delaborate a call to a projection function such as `Prod.fst`. -/ @[builtinDelab app] def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do let e@(Expr.app fn _ _) ← getExpr | failure let Expr.const c@(Name.str _ f _) _ _ ← pure fn.getAppFn | failure let env ← getEnv let some info ← pure $ env.getProjectionFnInfo? c | failure -- can't use with classes since the instance parameter is implicit guard $ !info.fromClass -- projection function should be fully applied (#struct params + 1 instance parameter) -- TODO: support over-application guard $ e.getAppNumArgs == info.nparams + 1 -- If pp.explicit is true, and the structure has parameters, we should not -- use field notation because we will not be able to see the parameters. let expl ← getPPOption getPPExplicit guard $ !expl || info.nparams == 0 let appStx ← withAppArg delab `($(appStx).$(mkIdent f):ident) @[builtinDelab app] def delabStructureInstance : Delab := whenPPOption getPPStructureInstances do let env ← getEnv let e ← getExpr let some s ← pure $ e.isConstructorApp? env | failure guard $ isStructure env s.induct; /- If implicit arguments should be shown, and the structure has parameters, we should not pretty print using { ... }, because we will not be able to see the parameters. -/ let explicit ← getPPOption getPPExplicit guard !(explicit && s.nparams > 0) let fieldNames := getStructureFields env s.induct let (_, fields) ← withAppFnArgs (pure (0, #[])) fun ⟨idx, fields⟩ => do if idx < s.nparams then pure (idx + 1, fields) else let val ← delab let field ← `(structInstField|$(mkIdent <| fieldNames.get! (idx - s.nparams)):ident := $val) pure (idx + 1, fields.push field) let lastField := fields[fields.size - 1] let fields := fields.pop let ty ← if (← getPPOption getPPStructureInstanceType) then let ty ← inferType e -- `ty` is not actually part of `e`, but since `e` must be an application or constant, we know that -- index 2 is unused. pure <| some (← descend ty 2 delab) else pure <| none `({ $[$fields, ]* $lastField $[: $ty]? }) @[builtinDelab app.Prod.mk] def delabTuple : Delab := whenPPOption getPPNotation do let e ← getExpr guard $ e.getAppNumArgs == 4 let a ← withAppFn $ withAppArg delab let b ← withAppArg delab match b with | `(($b, $bs,*)) => `(($a, $b, $bs,*)) | _ => `(($a, $b)) -- abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β @[builtinDelab app.coe] def delabCoe : Delab := whenPPOption getPPCoercions do let e ← getExpr guard $ e.getAppNumArgs >= 4 -- delab as application, then discard function let stx ← delabAppImplicit match stx with | `($fn $arg) => arg | `($fn $args*) => `($(args.get! 0) $(args.eraseIdx 0)*) | _ => failure -- abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a @[builtinDelab app.coeFun] def delabCoeFun : Delab := delabCoe @[builtinDelab app.List.nil] def delabNil : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 1 `([]) @[builtinDelab app.List.cons] def delabConsList : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 3 let x ← withAppFn (withAppArg delab) match (← withAppArg delab) with | `([]) => `([$x]) | `([$xs,*]) => `([$x, $xs,*]) | _ => failure @[builtinDelab app.List.toArray] def delabListToArray : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 2 match (← withAppArg delab) with | `([$xs,*]) => `(#[$xs,*]) | _ => failure @[builtinDelab app.ite] def delabIte : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 5 let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab let t ← withAppFn $ withAppArg delab let e ← withAppArg delab `(if $c then $t else $e) @[builtinDelab app.dite] def delabDIte : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 5 let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab let (t, h) ← withAppFn $ withAppArg $ delabBranch none let (e, _) ← withAppArg $ delabBranch h `(if $(mkIdent h):ident : $c then $t else $e) where delabBranch (h? : Option Name) : DelabM (Syntax × Name) := do let e ← getExpr guard e.isLambda let h ← match h? with | some h => return (← withBindingBody h delab, h) | none => withBindingBodyUnusedName fun h => do return (← delab, h.getId) @[builtinDelab app.namedPattern] def delabNamedPattern : Delab := do guard $ (← getExpr).getAppNumArgs == 3 let x ← withAppFn $ withAppArg delab let p ← withAppArg delab guard x.isIdent `($x:ident@$p:term) partial def delabDoElems : DelabM (List Syntax) := do let e ← getExpr if e.isAppOfArity `Bind.bind 6 then -- Bind.bind.{u, v} : {m : Type u → Type v} → [self : Bind m] → {α β : Type u} → m α → (α → m β) → m β let ma ← withAppFn $ withAppArg delab withAppArg do match (← getExpr) with | Expr.lam _ _ body _ => withBindingBodyUnusedName fun n => do if body.hasLooseBVars then prependAndRec `(doElem|let $n:term ← $ma) else prependAndRec `(doElem|$ma:term) | _ => delabAndRet else if e.isLet then let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n let stxT ← descend t 0 delab let stxV ← descend v 1 delab withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 $ prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV) else delabAndRet where prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems delabAndRet : DelabM _ := do let stx ← delab; [←`(doElem|$stx:term)] @[builtinDelab app.Bind.bind] def delabDo : Delab := whenPPOption getPPNotation do unless (← getExpr).isAppOfArity `Bind.bind 6 do failure let elems ← delabDoElems let items ← elems.toArray.mapM (`(doSeqItem|$(·):doElem)) `(do $items:doSeqItem*) end Lean.PrettyPrinter.Delaborator
b9e974fcdcc5d7f85cf511d2762cfdbd7c145a12
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/shrinking_lemma.lean
31c7f0514b6d4694ea089371ccd04a66ee9cc096
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,196
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Reid Barton -/ import topology.separation /-! # The shrinking lemma In this file we prove a few versions of the shrinking lemma. The lemma says that in a normal topological space a point finite open covering can be “shrunk”: for a point finite open covering `u : ι → set X` there exists a refinement `v : ι → set X` such that `closure (v i) ⊆ u i`. For finite or countable coverings this lemma can be proved without the axiom of choice, see [ncatlab](https://ncatlab.org/nlab/show/shrinking+lemma) for details. We only formalize the most general result that works for any covering but needs the axiom of choice. We prove two versions of the lemma: * `exists_subset_Union_closure_subset` deals with a covering of a closed set in a normal space; * `exists_Union_eq_closure_subset` deals with a covering of the whole space. ## Tags normal space, shrinking lemma -/ open set function open_locale classical noncomputable theory variables {ι X : Type*} [topological_space X] [normal_space X] namespace shrinking_lemma /-- Auxiliary definition for the proof of `shrinking_lemma`. A partial refinement of a covering `⋃ i, u i` of a set `s` is a map `v : ι → set X` and a set `carrier : set ι` such that * `s ⊆ ⋃ i, v i`; * all `v i` are open; * if `i ∈ carrier v`, then `closure (v i) ⊆ u i`; * if `i ∉ carrier`, then `v i = u i`. This type is equipped with the folowing partial order: `v ≤ v'` if `v.carrier ⊆ v'.carrier` and `v i = v' i` for `i ∈ v.carrier`. We will use Zorn's lemma to prove that this type has a maximal element, then show that the maximal element must have `carrier = univ`. -/ @[nolint has_inhabited_instance] -- the trivial refinement needs `u` to be a covering structure partial_refinement (u : ι → set X) (s : set X) := (to_fun : ι → set X) (carrier : set ι) (is_open' : ∀ i, is_open (to_fun i)) (subset_Union' : s ⊆ ⋃ i, to_fun i) (closure_subset' : ∀ i ∈ carrier, closure (to_fun i) ⊆ (u i)) (apply_eq' : ∀ i ∉ carrier, to_fun i = u i) namespace partial_refinement variables {u : ι → set X} {s : set X} instance : has_coe_to_fun (partial_refinement u s) (λ _, ι → set X) := ⟨to_fun⟩ lemma subset_Union (v : partial_refinement u s) : s ⊆ ⋃ i, v i := v.subset_Union' lemma closure_subset (v : partial_refinement u s) {i : ι} (hi : i ∈ v.carrier) : closure (v i) ⊆ (u i) := v.closure_subset' i hi lemma apply_eq (v : partial_refinement u s) {i : ι} (hi : i ∉ v.carrier) : v i = u i := v.apply_eq' i hi protected lemma is_open (v : partial_refinement u s) (i : ι) : is_open (v i) := v.is_open' i protected lemma subset (v : partial_refinement u s) (i : ι) : v i ⊆ u i := if h : i ∈ v.carrier then subset.trans subset_closure (v.closure_subset h) else (v.apply_eq h).le attribute [ext] partial_refinement instance : partial_order (partial_refinement u s) := { le := λ v₁ v₂, v₁.carrier ⊆ v₂.carrier ∧ ∀ i ∈ v₁.carrier, v₁ i = v₂ i, le_refl := λ v, ⟨subset.refl _, λ _ _, rfl⟩, le_trans := λ v₁ v₂ v₃ h₁₂ h₂₃, ⟨subset.trans h₁₂.1 h₂₃.1, λ i hi, (h₁₂.2 i hi).trans (h₂₃.2 i $ h₁₂.1 hi)⟩, le_antisymm := λ v₁ v₂ h₁₂ h₂₁, have hc : v₁.carrier = v₂.carrier, from subset.antisymm h₁₂.1 h₂₁.1, ext _ _ (funext $ λ x, if hx : x ∈ v₁.carrier then h₁₂.2 _ hx else (v₁.apply_eq hx).trans (eq.symm $ v₂.apply_eq $ hc ▸ hx)) hc } /-- If two partial refinements `v₁`, `v₂` belong to a chain (hence, they are comparable) and `i` belongs to the carriers of both partial refinements, then `v₁ i = v₂ i`. -/ lemma apply_eq_of_chain {c : set (partial_refinement u s)} (hc : is_chain (≤) c) {v₁ v₂} (h₁ : v₁ ∈ c) (h₂ : v₂ ∈ c) {i} (hi₁ : i ∈ v₁.carrier) (hi₂ : i ∈ v₂.carrier) : v₁ i = v₂ i := begin wlog hle : v₁ ≤ v₂ := hc.total h₁ h₂ using [v₁ v₂, v₂ v₁], exact hle.2 _ hi₁, end /-- The carrier of the least upper bound of a non-empty chain of partial refinements is the union of their carriers. -/ def chain_Sup_carrier (c : set (partial_refinement u s)) : set ι := ⋃ v ∈ c, carrier v /-- Choice of an element of a nonempty chain of partial refinements. If `i` belongs to one of `carrier v`, `v ∈ c`, then `find c ne i` is one of these partial refinements. -/ def find (c : set (partial_refinement u s)) (ne : c.nonempty) (i : ι) : partial_refinement u s := if hi : ∃ v ∈ c, i ∈ carrier v then hi.some else ne.some lemma find_mem {c : set (partial_refinement u s)} (i : ι) (ne : c.nonempty) : find c ne i ∈ c := by { rw find, split_ifs, exacts [h.some_spec.fst, ne.some_spec] } lemma mem_find_carrier_iff {c : set (partial_refinement u s)} {i : ι} (ne : c.nonempty) : i ∈ (find c ne i).carrier ↔ i ∈ chain_Sup_carrier c := begin rw find, split_ifs, { have : i ∈ h.some.carrier ∧ i ∈ chain_Sup_carrier c, from ⟨h.some_spec.snd, mem_Union₂.2 h⟩, simp only [this] }, { have : i ∉ ne.some.carrier ∧ i ∉ chain_Sup_carrier c, from ⟨λ hi, h ⟨_, ne.some_spec, hi⟩, mt mem_Union₂.1 h⟩, simp only [this] } end lemma find_apply_of_mem {c : set (partial_refinement u s)} (hc : is_chain (≤) c) (ne : c.nonempty) {i v} (hv : v ∈ c) (hi : i ∈ carrier v) : find c ne i i = v i := apply_eq_of_chain hc (find_mem _ _) hv ((mem_find_carrier_iff _).2 $ mem_Union₂.2 ⟨v, hv, hi⟩) hi /-- Least upper bound of a nonempty chain of partial refinements. -/ def chain_Sup (c : set (partial_refinement u s)) (hc : is_chain (≤) c) (ne : c.nonempty) (hfin : ∀ x ∈ s, finite {i | x ∈ u i}) (hU : s ⊆ ⋃ i, u i) : partial_refinement u s := begin refine ⟨λ i, find c ne i i, chain_Sup_carrier c, λ i, (find _ _ _).is_open i, λ x hxs, mem_Union.2 _, λ i hi, (find c ne i).closure_subset ((mem_find_carrier_iff _).2 hi), λ i hi, (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi)⟩, rcases em (∃ i ∉ chain_Sup_carrier c, x ∈ u i) with ⟨i, hi, hxi⟩|hx, { use i, rwa (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi) }, { simp_rw [not_exists, not_imp_not, chain_Sup_carrier, mem_Union₂] at hx, haveI : nonempty (partial_refinement u s) := ⟨ne.some⟩, choose! v hvc hiv using hx, rcases (hfin x hxs).exists_maximal_wrt v _ (mem_Union.1 (hU hxs)) with ⟨i, hxi : x ∈ u i, hmax : ∀ j, x ∈ u j → v i ≤ v j → v i = v j⟩, rcases mem_Union.1 ((v i).subset_Union hxs) with ⟨j, hj⟩, use j, have hj' : x ∈ u j := (v i).subset _ hj, have : v j ≤ v i, from (hc.total (hvc _ hxi) (hvc _ hj')).elim (λ h, (hmax j hj' h).ge) id, rwa find_apply_of_mem hc ne (hvc _ hxi) (this.1 $ hiv _ hj') } end /-- `chain_Sup hu c hc ne hfin hU` is an upper bound of the chain `c`. -/ lemma le_chain_Sup {c : set (partial_refinement u s)} (hc : is_chain (≤) c) (ne : c.nonempty) (hfin : ∀ x ∈ s, finite {i | x ∈ u i}) (hU : s ⊆ ⋃ i, u i) {v} (hv : v ∈ c) : v ≤ chain_Sup c hc ne hfin hU := ⟨λ i hi, mem_bUnion hv hi, λ i hi, (find_apply_of_mem hc _ hv hi).symm⟩ /-- If `s` is a closed set, `v` is a partial refinement, and `i` is an index such that `i ∉ v.carrier`, then there exists a partial refinement that is strictly greater than `v`. -/ lemma exists_gt (v : partial_refinement u s) (hs : is_closed s) (i : ι) (hi : i ∉ v.carrier) : ∃ v' : partial_refinement u s, v < v' := begin have I : s ∩ (⋂ j ≠ i, (v j)ᶜ) ⊆ v i, { simp only [subset_def, mem_inter_eq, mem_Inter, and_imp], intros x hxs H, rcases mem_Union.1 (v.subset_Union hxs) with ⟨j, hj⟩, exact (em (j = i)).elim (λ h, h ▸ hj) (λ h, (H j h hj).elim) }, have C : is_closed (s ∩ (⋂ j ≠ i, (v j)ᶜ)), from is_closed.inter hs (is_closed_bInter $ λ _ _, is_closed_compl_iff.2 $ v.is_open _), rcases normal_exists_closure_subset C (v.is_open i) I with ⟨vi, ovi, hvi, cvi⟩, refine ⟨⟨update v i vi, insert i v.carrier, _, _, _, _⟩, _, _⟩, { intro j, by_cases h : j = i; simp [h, ovi, v.is_open] }, { refine λ x hx, mem_Union.2 _, rcases em (∃ j ≠ i, x ∈ v j) with ⟨j, hji, hj⟩|h, { use j, rwa update_noteq hji }, { push_neg at h, use i, rw update_same, exact hvi ⟨hx, mem_bInter h⟩ } }, { rintro j (rfl|hj), { rwa [update_same, ← v.apply_eq hi] }, { rw update_noteq (ne_of_mem_of_not_mem hj hi), exact v.closure_subset hj } }, { intros j hj, rw [mem_insert_iff, not_or_distrib] at hj, rw [update_noteq hj.1, v.apply_eq hj.2] }, { refine ⟨subset_insert _ _, λ j hj, _⟩, exact (update_noteq (ne_of_mem_of_not_mem hj hi) _ _).symm }, { exact λ hle, hi (hle.1 $ mem_insert _ _) } end end partial_refinement end shrinking_lemma open shrinking_lemma variables {u : ι → set X} {s : set X} /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ lemma exists_subset_Union_closure_subset (hs : is_closed s) (uo : ∀ i, is_open (u i)) (uf : ∀ x ∈ s, finite {i | x ∈ u i}) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i := begin classical, haveI : nonempty (partial_refinement u s) := ⟨⟨u, ∅, uo, us, λ _, false.elim, λ _ _, rfl⟩⟩, have : ∀ c : set (partial_refinement u s), is_chain (≤) c → c.nonempty → ∃ ub, ∀ v ∈ c, v ≤ ub, from λ c hc ne, ⟨partial_refinement.chain_Sup c hc ne uf us, λ v hv, partial_refinement.le_chain_Sup _ _ _ _ hv⟩, rcases zorn_nonempty_partial_order this with ⟨v, hv⟩, suffices : ∀ i, i ∈ v.carrier, from ⟨v, v.subset_Union, λ i, v.is_open _, λ i, v.closure_subset (this i)⟩, contrapose! hv, rcases hv with ⟨i, hi⟩, rcases v.exists_gt hs i hi with ⟨v', hlt⟩, exact ⟨v', hlt.le, hlt.ne'⟩ end /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each new closed set is contained in the corresponding original open set. See also `exists_subset_Union_closure_subset` for a stronger statement. -/ lemma exists_subset_Union_closed_subset (hs : is_closed s) (uo : ∀ i, is_open (u i)) (uf : ∀ x ∈ s, finite {i | x ∈ u i}) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, hsv, hvo, hv⟩ := exists_subset_Union_closure_subset hs uo uf us in ⟨λ i, closure (v i), subset.trans hsv (Union_mono $ λ i, subset_closure), λ i, is_closed_closure, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ lemma exists_Union_eq_closure_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, finite {i | x ∈ u i}) (uU : (⋃ i, u i) = univ) : ∃ v : ι → set X, Union v = univ ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_Union_closure_subset is_closed_univ uo (λ x _, uf x) uU.ge in ⟨v, univ_subset_iff.1 vU, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each of the new closed sets is contained in the corresponding original open set. See also `exists_Union_eq_closure_subset` for a stronger statement. -/ lemma exists_Union_eq_closed_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, finite {i | x ∈ u i}) (uU : (⋃ i, u i) = univ) : ∃ v : ι → set X, Union v = univ ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_Union_closed_subset is_closed_univ uo (λ x _, uf x) uU.ge in ⟨v, univ_subset_iff.1 vU, hv⟩
fa1fe2fc4149708a549cddf8c4d286a3f8e52e6b
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Compiler/IR/Basic.lean
d6a586be6fb5ce4f01286623665022baa82496fa
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,770
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Data.Name import Lean.Data.Format import Lean.Compiler.ExternAttr /- Implements (extended) λPure and λRc proposed in the article "Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura. The Lean to IR transformation produces λPure code, and this part is implemented in C++. The procedures described in the paper above are implemented in Lean. -/ namespace Lean.IR /- Function identifier -/ abbrev FunId := Name abbrev Index := Nat /- Variable identifier -/ structure VarId := (idx : Index) /- Join point identifier -/ structure JoinPointId := (idx : Index) abbrev Index.lt (a b : Index) : Bool := a < b instance : BEq VarId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩ instance : ToFormat VarId := ⟨fun a => toString a⟩ instance : Hashable VarId := ⟨fun a => hash a.idx⟩ instance : BEq JoinPointId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩ instance : ToFormat JoinPointId := ⟨fun a => toString a⟩ instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩ abbrev MData := KVMap abbrev MData.empty : MData := {} /- Low Level IR types. Most are self explanatory. - `usize` represents the C++ `size_t` Type. We have it here because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines, and we want the C++ backend for our Compiler to generate platform independent code. - `irrelevant` for Lean types, propositions and proofs. - `object` a pointer to a value in the heap. - `tobject` a pointer to a value in the heap or tagged pointer (i.e., the least significant bit is 1) storing a scalar value. - `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`) on the stack. Remark: the RC operations for `tobject` are slightly more expensive because we first need to test whether the `tobject` is really a pointer or not. Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT). Lean cannot be compiled on old platforms where this is not True. Since values of type `struct` and `union` are only used to return values, We assume they must be used/consumed "linearly". We use the term "linear" here to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct, then one of the following must hold in each (execution) branch. 1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned. 2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`. 3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union fields that do not contain object fields. -/ inductive IRType := | float | uint8 | uint16 | uint32 | uint64 | usize | irrelevant | object | tobject | struct (leanTypeName : Option Name) (types : Array IRType) : IRType | union (leanTypeName : Name) (types : Array IRType) : IRType namespace IRType partial def beq : IRType → IRType → Bool | float, float => true | uint8, uint8 => true | uint16, uint16 => true | uint32, uint32 => true | uint64, uint64 => true | usize, usize => true | irrelevant, irrelevant => true | object, object => true | tobject, tobject => true | struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | _, _ => false instance : BEq IRType := ⟨beq⟩ def isScalar : IRType → Bool | float => true | uint8 => true | uint16 => true | uint32 => true | uint64 => true | usize => true | _ => false def isObj : IRType → Bool | object => true | tobject => true | _ => false def isIrrelevant : IRType → Bool | irrelevant => true | _ => false def isStruct : IRType → Bool | struct _ _ => true | _ => false def isUnion : IRType → Bool | union _ _ => true | _ => false end IRType /- Arguments to applications, constructors, etc. We use `irrelevant` for Lean types, propositions and proofs that have been erased. Recall that for a Function `f`, we also generate `f._rarg` which does not take `irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/ inductive Arg := | var (id : VarId) | irrelevant protected def Arg.beq : Arg → Arg → Bool | var x, var y => x == y | irrelevant, irrelevant => true | _, _ => false instance : BEq Arg := ⟨Arg.beq⟩ instance : Inhabited Arg := ⟨Arg.irrelevant⟩ @[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id inductive LitVal := | num (v : Nat) | str (v : String) def LitVal.beq : LitVal → LitVal → Bool | num v₁, num v₂ => v₁ == v₂ | str v₁, str v₂ => v₁ == v₂ | _, _ => false instance : BEq LitVal := ⟨LitVal.beq⟩ /- Constructor information. - `name` is the Name of the Constructor in Lean. - `cidx` is the Constructor index (aka tag). - `size` is the number of arguments of type `object/tobject`. - `usize` is the number of arguments of type `usize`. - `ssize` is the number of bytes used to store scalar values. Recall that a Constructor object contains a header, then a sequence of pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`) scalar values, and a sequence of other scalar values. -/ structure CtorInfo := (name : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) def CtorInfo.beq : CtorInfo → CtorInfo → Bool | ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ => n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂ instance : BEq CtorInfo := ⟨CtorInfo.beq⟩ def CtorInfo.isRef (info : CtorInfo) : Bool := info.size > 0 || info.usize > 0 || info.ssize > 0 def CtorInfo.isScalar (info : CtorInfo) : Bool := !info.isRef inductive Expr := /- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime. This instruction is also used to creat `struct` and `union` return values. For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/ | ctor (i : CtorInfo) (ys : Array Arg) | reset (n : Nat) (x : VarId) /- `reuse x in ctor_i ys` instruction in the paper. -/ | reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg) /- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`. We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/ | proj (i : Nat) (x : VarId) /- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/ | uproj (i : Nat) (x : VarId) /- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/ | sproj (n : Nat) (offset : Nat) (x : VarId) /- Full application. -/ | fap (c : FunId) (ys : Array Arg) /- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/ | pap (c : FunId) (ys : Array Arg) /- Application. `x` must be a `pap` value. -/ | ap (x : VarId) (ys : Array Arg) /- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`. For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/ | box (ty : IRType) (x : VarId) /- Given `x : [t]object`, obtain the scalar value. -/ | unbox (x : VarId) | lit (v : LitVal) /- Return `1 : uint8` Iff `RC(x) > 1` -/ | isShared (x : VarId) /- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/ | isTaggedPtr (x : VarId) @[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr := Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys @[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x @[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x @[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x @[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys @[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys @[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys @[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v) @[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v) structure Param := (x : VarId) (borrow : Bool) (ty : IRType) instance : Inhabited Param := ⟨{ x := { idx := 0 }, borrow := false, ty := IRType.object }⟩ @[export lean_ir_mk_param] def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩ inductive AltCore (FnBody : Type) : Type := | ctor (info : CtorInfo) (b : FnBody) : AltCore FnBody | default (b : FnBody) : AltCore FnBody inductive FnBody := /- `let x : ty := e; b` -/ | vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) /- Join point Declaration `block_j (xs) := e; b` -/ | jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) /- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. This operation is not part of λPure is only used during optimization. -/ | set (x : VarId) (i : Nat) (y : Arg) (b : FnBody) | setTag (x : VarId) (cidx : Nat) (b : FnBody) /- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/ | uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody) /- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. `ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/ | sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) /- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) /- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) | del (x : VarId) (b : FnBody) | mdata (d : MData) (b : FnBody) | case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody)) | ret (x : Arg) /- Jump to join point `j` -/ | jmp (j : JoinPointId) (ys : Array Arg) | unreachable instance : Inhabited FnBody := ⟨FnBody.unreachable⟩ abbrev FnBody.nil := FnBody.unreachable @[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b @[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b @[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b @[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b @[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody := -- Tyhe field `xType` is set by `explicitBoxing` compiler pass. FnBody.case tid x IRType.object cs @[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x @[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys @[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable abbrev Alt := AltCore FnBody @[matchPattern] abbrev Alt.ctor := @AltCore.ctor FnBody @[matchPattern] abbrev Alt.default := @AltCore.default FnBody instance : Inhabited Alt := ⟨Alt.default arbitrary⟩ def FnBody.isTerminal : FnBody → Bool | FnBody.case _ _ _ _ => true | FnBody.ret _ => true | FnBody.jmp _ _ => true | FnBody.unreachable => true | _ => false def FnBody.body : FnBody → FnBody | FnBody.vdecl _ _ _ b => b | FnBody.jdecl _ _ _ b => b | FnBody.set _ _ _ b => b | FnBody.uset _ _ _ b => b | FnBody.sset _ _ _ _ _ b => b | FnBody.setTag _ _ b => b | FnBody.inc _ _ _ _ b => b | FnBody.dec _ _ _ _ b => b | FnBody.del _ b => b | FnBody.mdata _ b => b | other => other def FnBody.setBody : FnBody → FnBody → FnBody | FnBody.vdecl x t v _, b => FnBody.vdecl x t v b | FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b | FnBody.set x i y _, b => FnBody.set x i y b | FnBody.uset x i y _, b => FnBody.uset x i y b | FnBody.sset x i o y t _, b => FnBody.sset x i o y t b | FnBody.setTag x i _, b => FnBody.setTag x i b | FnBody.inc x n c p _, b => FnBody.inc x n c p b | FnBody.dec x n c p _, b => FnBody.dec x n c p b | FnBody.del x _, b => FnBody.del x b | FnBody.mdata d _, b => FnBody.mdata d b | other, b => other @[inline] def FnBody.resetBody (b : FnBody) : FnBody := b.setBody FnBody.nil /- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`, and c.body == FnBody.nil -/ @[inline] def FnBody.split (b : FnBody) : FnBody × FnBody := let b' := b.body let c := b.resetBody (c, b') def AltCore.body : Alt → FnBody | Alt.ctor _ b => b | Alt.default b => b def AltCore.setBody : Alt → FnBody → Alt | Alt.ctor c _, b => Alt.ctor c b | Alt.default _, b => Alt.default b @[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt | Alt.ctor c b => Alt.ctor c (f b) | Alt.default b => Alt.default (f b) @[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt | Alt.ctor c b => Alt.ctor c <$> f b | Alt.default b => Alt.default <$> f b def Alt.isDefault : Alt → Bool | Alt.ctor _ _ => false | Alt.default _ => true def push (bs : Array FnBody) (b : FnBody) : Array FnBody := let b := b.resetBody bs.push b partial def flattenAux (b : FnBody) (r : Array FnBody) : (Array FnBody) × FnBody := if b.isTerminal then (r, b) else flattenAux b.body (push r b) def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody := flattenAux b #[] partial def reshapeAux (a : Array FnBody) (i : Nat) (b : FnBody) : FnBody := if i == 0 then b else let i := i - 1 let (curr, a) := a.swapAt! i arbitrary let b := curr.setBody b reshapeAux a i b def reshape (bs : Array FnBody) (term : FnBody) : FnBody := reshapeAux bs bs.size term @[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody := bs.map fun b => match b with | FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k | other => other @[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) := bs.mapM fun b => match b with | FnBody.jdecl j xs v k => do let v ← f v; pure $ FnBody.jdecl j xs v k | other => pure other @[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt := Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b inductive Decl := | fdecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) | extern (f : FunId) (xs : Array Param) (ty : IRType) (ext : ExternAttrData) namespace Decl instance : Inhabited Decl := ⟨fdecl arbitrary arbitrary IRType.irrelevant arbitrary⟩ def name : Decl → FunId | Decl.fdecl f _ _ _ => f | Decl.extern f _ _ _ => f def params : Decl → Array Param | Decl.fdecl _ xs _ _ => xs | Decl.extern _ xs _ _ => xs def resultType : Decl → IRType | Decl.fdecl _ _ t _ => t | Decl.extern _ _ t _ => t def isExtern : Decl → Bool | Decl.extern _ _ _ _ => true | _ => false end Decl @[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl := Decl.fdecl f xs ty b @[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl := Decl.extern f xs ty e open Std (RBTree RBTree.empty RBMap) /-- Set of variable and join point names -/ abbrev IndexSet := RBTree Index Index.lt instance : Inhabited IndexSet := ⟨{}⟩ def mkIndexSet (idx : Index) : IndexSet := RBTree.empty.insert idx inductive LocalContextEntry := | param : IRType → LocalContextEntry | localVar : IRType → Expr → LocalContextEntry | joinPoint : Array Param → FnBody → LocalContextEntry abbrev LocalContext := RBMap Index LocalContextEntry Index.lt def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext := ctx.insert x.idx (LocalContextEntry.localVar t v) def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext := ctx.insert j.idx (LocalContextEntry.joinPoint xs b) def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext := ctx.insert p.x.idx (LocalContextEntry.param p.ty) def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext := ps.foldl LocalContext.addParam ctx def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.joinPoint _ _) => true | other => false def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint _ b) => some b | other => none def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint ys _) => some ys | other => none def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.param _) => true | other => false def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.localVar _ _) => true | other => false def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool := Std.RBMap.contains ctx idx def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext := ctx.erase j.idx def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType := match ctx.find? x.idx with | some (LocalContextEntry.param t) => some t | some (LocalContextEntry.localVar t _) => some t | other => none def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr := match ctx.find? x.idx with | some (LocalContextEntry.localVar _ v) => some v | other => none abbrev IndexRenaming := RBMap Index Index Index.lt class AlphaEqv (α : Type) := (aeqv : IndexRenaming → α → α → Bool) export AlphaEqv (aeqv) def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool := match ρ.find? v₁.idx with | some v => v == v₂.idx | none => v₁ == v₂ instance : AlphaEqv VarId := ⟨VarId.alphaEqv⟩ def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool | Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂ | Arg.irrelevant, Arg.irrelevant => true | _, _ => false instance : AlphaEqv Arg := ⟨Arg.alphaEqv⟩ def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool := Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b) instance: AlphaEqv (Array Arg) := ⟨args.alphaEqv⟩ def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool | Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂ | Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂ | Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂ | Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂ | Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂ | Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂ | Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂ | Expr.lit v₁, Expr.lit v₂ => v₁ == v₂ | Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂ | Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂ | _, _ => false instance : AlphaEqv Expr:= ⟨Expr.alphaEqv⟩ def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) := if x₁ == x₂ then ρ else ρ.insert x₁ x₂ def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming := if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then some (addVarRename ρ p₁.x.idx p₂.x.idx) else none def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := do if ps₁.size != ps₂.size then none else let mut ρ := ρ for i in [:ps₁.size] do ρ ← addParamRename ρ ps₁[i] ps₂[i] pure ρ partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool | ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂ | ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with | some ρ' => alphaEqv ρ' v₁ v₂ && alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂ | none => false | ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ => aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ => match alt₁, alt₂ with | Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && alphaEqv ρ b₁ b₂ | Alt.default b₁, Alt.default b₂ => alphaEqv ρ b₁ b₂ | _, _ => false) | ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂ | ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂ | _, FnBody.unreachable, FnBody.unreachable => true | _, _, _ => false def FnBody.beq (b₁ b₂ : FnBody) : Bool := FnBody.alphaEqv ∅ b₁ b₂ instance : BEq FnBody := ⟨FnBody.beq⟩ abbrev VarIdSet := RBTree VarId (fun x y => x.idx < y.idx) instance : Inhabited VarIdSet := ⟨{}⟩ def mkIf (x : VarId) (t e : FnBody) : FnBody := FnBody.case `Bool x IRType.uint8 #[ Alt.ctor {name := `Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e, Alt.ctor {name := `Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t ] end Lean.IR
ce3809da7ea6c1d45b15717321084a5437a7c737
64874bd1010548c7f5a6e3e8902efa63baaff785
/library/data/sum.lean
3296b87ac90be311981e0ef46923ffb7223efa9f
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,017
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 namespace sum notation A ⊎ B := sum A B 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, no_confusion H definition inr_ne_inl (b : B) (a : A) : inr b ≠ inl a := assume H, no_confusion H definition inl_inj {a₁ a₂ : A} : intro_left B a₁ = intro_left B a₂ → a₁ = a₂ := assume H, no_confusion H (λe, e) definition inr_inj {b₁ b₂ : B} : intro_right A b₁ = intro_right A b₂ → b₁ = b₂ := assume H, no_confusion H (λe, e) protected definition is_inhabited_left [instance] : inhabited A → inhabited (A + B) := assume H : inhabited A, inhabited.mk (inl (default A)) protected definition is_inhabited_right [instance] : inhabited B → inhabited (A + B) := assume H : inhabited B, inhabited.mk (inr (default B)) protected definition has_eq_decidable [instance] (h₁ : decidable_eq A) (h₂ : decidable_eq B) : ∀ s₁ s₂ : A + B, decidable (s₁ = s₂), has_eq_decidable (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_eq_decidable (inl a₁) (inr b₂) := decidable.inr (λ e, sum.no_confusion e), has_eq_decidable (inr b₁) (inl a₂) := decidable.inr (λ e, sum.no_confusion e), has_eq_decidable (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
f5d4daee76ee14574a6e0d3e1e523bf7158b6189
a46270e2f76a375564f3b3e9c1bf7b635edc1f2c
/5.8.1-4.6.7.lean
63d4863f0afa94b5fb87dcd477aaec58168c077d
[ "CC0-1.0" ]
permissive
wudcscheme/lean-exercise
88ea2506714eac343de2a294d1132ee8ee6d3a20
5b23b9be3d361fff5e981d5be3a0a1175504b9f6
refs/heads/master
1,678,958,930,293
1,583,197,205,000
1,583,197,205,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51
lean
example (x : ℤ) : x * 0 = 0 := begin simp end
729696c4bce746635707b7333858de04c715fedd
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Meta/Tactic/Rewrite.lean
0be0607ad4a855fb4e5c6609b4835e4d3bc65895
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
2,729
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.KAbstract import Lean.Meta.Check import Lean.Meta.Tactic.Apply namespace Lean.Meta structure RewriteResult where eNew : Expr eqProof : Expr mvarIds : List MVarId -- new goals def rewrite (mvarId : MVarId) (e : Expr) (heq : Expr) (symm : Bool := false) (occs : Occurrences := Occurrences.all) (mode := TransparencyMode.reducible) : MetaM RewriteResult := withMVarContext mvarId do checkNotAssigned mvarId `rewrite let heqType ← inferType heq let (newMVars, binderInfos, heqType) ← forallMetaTelescopeReducing heqType let heq := mkAppN heq newMVars let cont (heq heqType : Expr) : MetaM RewriteResult := do match (← matchEq? heqType) with | none => throwTacticEx `rewrite mvarId m!"equality or iff proof expected{indentExpr heqType}" | some (α, lhs, rhs) => let cont (heq heqType lhs rhs : Expr) : MetaM RewriteResult := do if lhs.getAppFn.isMVar then throwTacticEx `rewrite mvarId m!"pattern is a metavariable{indentExpr lhs}\nfrom equation{indentExpr heqType}" let e ← instantiateMVars e let eAbst ← withTransparency mode <| kabstract e lhs occs unless eAbst.hasLooseBVars do throwTacticEx `rewrite mvarId m!"did not find instance of the pattern in the target expression{indentExpr lhs}" -- construct rewrite proof let eNew := eAbst.instantiate1 rhs let eNew ← instantiateMVars eNew let eEqE ← mkEq e e let eEqEAbst := mkApp eEqE.appFn! eAbst let motive := Lean.mkLambda `_a BinderInfo.default α eEqEAbst unless (← isTypeCorrect motive) do throwTacticEx `rewrite mvarId "motive is not type correct" let eqRefl ← mkEqRefl e let eqPrf ← mkEqNDRec motive eqRefl heq postprocessAppMVars `rewrite mvarId newMVars binderInfos let newMVars ← newMVars.filterM fun mvar => not <$> isExprMVarAssigned mvar.mvarId! pure { eNew := eNew, eqProof := eqPrf, mvarIds := newMVars.toList.map Expr.mvarId! } match symm with | false => cont heq heqType lhs rhs | true => do let heq ← mkEqSymm heq let heqType ← mkEq rhs lhs cont heq heqType rhs lhs match heqType.iff? with | some (lhs, rhs) => let heqType ← mkEq lhs rhs let heq := mkApp3 (mkConst `propext) lhs rhs heq cont heq heqType | none => cont heq heqType end Lean.Meta
882d9d1be740be458755a868347225b00d2c1154
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/t6.lean
ee7ff2b9d5069b5ef178c2cdd9663c10b0edf044
[ "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
370
lean
prelude precedence `+` : 65 precedence `++` : 100 constant N : Type.{1} constant f : N → N → N constant a : N #check let g x y := f x y, infix + := g, b : N := a+a, c := b+a, h (x : N) := x+x, postfix ++ := h, d := c++, r (x : N) : N := x++++ in f b (r c)
30f881a73c09b9cc30f8ef6b484125c06a98e5c0
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/measure_theory/measure/lebesgue.lean
0249bbb9a3c6c0f096ad6fa92c5bc6babdd55bb2
[ "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
24,978
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, Sébastien Gouëzel, Yury Kudryashov -/ import dynamics.ergodic.measure_preserving import linear_algebra.determinant import linear_algebra.matrix.diagonal import linear_algebra.matrix.transvection import measure_theory.constructions.pi import measure_theory.measure.stieltjes /-! # Lebesgue measure on the real line and on `ℝⁿ` We construct Lebesgue measure on the real line, as a particular case of Stieltjes measure associated to the function `x ↦ x`. We obtain as a consequence Lebesgue measure on `ℝⁿ`. We prove that they are translation invariant. We show that, on `ℝⁿ`, a linear map acts on Lebesgue measure by rescaling it through the absolute value of its determinant, in `real.map_linear_map_volume_pi_eq_smul_volume_pi`. More properties of the Lebesgue measure are deduced from this in `haar_lebesgue.lean`, where they are proved more generally for any additive Haar measure on a finite-dimensional real vector space. -/ noncomputable theory open classical set filter measure_theory measure_theory.measure open ennreal (of_real) open_locale big_operators ennreal nnreal topological_space /-! ### Definition of the Lebesgue measure and lengths of intervals -/ /-- Lebesgue measure on the Borel sigma algebra, giving measure `b - a` to the interval `[a, b]`. -/ instance real.measure_space : measure_space ℝ := ⟨stieltjes_function.id.measure⟩ namespace real variables {ι : Type*} [fintype ι] open_locale topological_space theorem volume_val (s) : volume s = stieltjes_function.id.measure s := rfl @[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := by simp [volume_val] @[simp] lemma volume_univ : volume (univ : set ℝ) = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, calc (r : ℝ≥0∞) = volume (Icc (0 : ℝ) r) : by simp ... ≤ volume univ : measure_mono (subset_univ _) @[simp] lemma volume_ball (a r : ℝ) : volume (metric.ball a r) = of_real (2 * r) := by rw [ball_eq_Ioo, volume_Ioo, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_closed_ball (a r : ℝ) : volume (metric.closed_ball a r) = of_real (2 * r) := by rw [closed_ball_eq_Icc, volume_Icc, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_emetric_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [metric.emetric_ball_top, volume_univ, two_mul, ennreal.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_ball_nnreal, volume_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end @[simp] lemma volume_emetric_closed_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.closed_ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [emetric.closed_ball_top, volume_univ, two_mul, ennreal.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_closed_ball_nnreal, volume_closed_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) := ⟨λ x, volume_singleton⟩ @[simp] lemma volume_interval {a b : ℝ} : volume (interval a b) = of_real (|b - a|) := by rw [interval, volume_Icc, max_sub_min_eq_abs] @[simp] lemma volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo a (a + n)) : by simp ... ≤ volume (Ioi a) : measure_mono Ioo_subset_Ioi_self @[simp] lemma volume_Ici {a : ℝ} : volume (Ici a) = ∞ := by simp [← measure_congr Ioi_ae_eq_Ici] @[simp] lemma volume_Iio {a : ℝ} : volume (Iio a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo (a - n) a) : by simp ... ≤ volume (Iio a) : measure_mono Ioo_subset_Iio_self @[simp] lemma volume_Iic {a : ℝ} : volume (Iic a) = ∞ := by simp [← measure_congr Iio_ae_eq_Iic] instance locally_finite_volume : is_locally_finite_measure (volume : measure ℝ) := ⟨λ x, ⟨Ioo (x - 1) (x + 1), is_open.mem_nhds is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩, by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩ instance is_finite_measure_restrict_Icc (x y : ℝ) : is_finite_measure (volume.restrict (Icc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ico (x y : ℝ) : is_finite_measure (volume.restrict (Ico x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioc (x y : ℝ) : is_finite_measure (volume.restrict (Ioc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioo (x y : ℝ) : is_finite_measure (volume.restrict (Ioo x y)) := ⟨by simp⟩ /-! ### Volume of a box in `ℝⁿ` -/ lemma volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ennreal.of_real (b i - a i) := begin rw [← pi_univ_Icc, volume_pi_pi], simp only [real.volume_Icc] end @[simp] lemma volume_Icc_pi_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (Icc a b)).to_real = ∏ i, (b i - a i) := by simp only [volume_Icc_pi, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioo {a b : ι → ℝ} : volume (pi univ (λ i, Ioo (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioo_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioo (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioo, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioc {a b : ι → ℝ} : volume (pi univ (λ i, Ioc (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioc_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioc (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioc, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ico {a b : ι → ℝ} : volume (pi univ (λ i, Ico (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ico_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ico (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ico, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] @[simp] lemma volume_pi_ball (a : ι → ℝ) {r : ℝ} (hr : 0 < r) : volume (metric.ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_ball a hr, volume_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr.le) _).symm end @[simp] lemma volume_pi_closed_ball (a : ι → ℝ) {r : ℝ} (hr : 0 ≤ r) : volume (metric.closed_ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_closed_ball a hr, volume_closed_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr) _).symm end lemma volume_le_diam (s : set ℝ) : volume s ≤ emetric.diam s := begin by_cases hs : metric.bounded s, { rw [real.ediam_eq hs, ← volume_Icc], exact volume.mono (real.subset_Icc_Inf_Sup_of_bounded hs) }, { rw metric.ediam_of_unbounded hs, exact le_top } end lemma volume_pi_le_prod_diam (s : set (ι → ℝ)) : volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) := calc volume s ≤ volume (pi univ (λ i, closure (function.eval i '' s))) : volume.mono $ subset.trans (subset_pi_eval_image univ s) $ pi_mono $ λ i hi, subset_closure ... = ∏ i, volume (closure $ function.eval i '' s) : volume_pi_pi _ ... ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : finset.prod_le_prod' $ λ i hi, (volume_le_diam _).trans_eq (emetric.diam_closure _) lemma volume_pi_le_diam_pow (s : set (ι → ℝ)) : volume s ≤ emetric.diam s ^ fintype.card ι := calc volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : volume_pi_le_prod_diam s ... ≤ ∏ i : ι, (1 : ℝ≥0) * emetric.diam s : finset.prod_le_prod' $ λ i hi, (lipschitz_with.eval i).ediam_image_le s ... = emetric.diam s ^ fintype.card ι : by simp only [ennreal.coe_one, one_mul, finset.prod_const, fintype.card] /-! ### Images of the Lebesgue measure under translation/multiplication in ℝ -/ instance is_add_left_invariant_real_volume : is_add_left_invariant (volume : measure ℝ) := ⟨λ a, eq.symm $ real.measure_ext_Ioo_rat $ λ p q, by simp [measure.map_apply (measurable_const_add a) measurable_set_Ioo, sub_sub_sub_cancel_right]⟩ lemma smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map ((*) a) volume = volume := begin refine (real.measure_ext_Ioo_rat $ λ p q, _).symm, cases lt_or_gt_of_ne h with h h, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, neg_sub_neg, neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub, smul_eq_mul, mul_div_cancel' _ (ne_of_lt h)] }, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, preimage_const_mul_Ioo _ _ h, abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h), smul_eq_mul] } end lemma map_volume_mul_left {a : ℝ} (h : a ≠ 0) : measure.map ((*) a) volume = ennreal.of_real (|a⁻¹|) • volume := by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one, one_smul] } @[simp] lemma volume_preimage_mul_left {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume (((*) a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume (((*) a) ⁻¹' s) = measure.map ((*) a) volume s : ((homeomorph.mul_left₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_left h, refl } lemma smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map (* a) volume = volume := by simpa only [mul_comm] using real.smul_map_volume_mul_left h lemma map_volume_mul_right {a : ℝ} (h : a ≠ 0) : measure.map (* a) volume = ennreal.of_real (|a⁻¹|) • volume := by simpa only [mul_comm] using real.map_volume_mul_left h @[simp] lemma volume_preimage_mul_right {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume ((* a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume ((* a) ⁻¹' s) = measure.map (* a) volume s : ((homeomorph.mul_right₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_right h, refl } instance : is_neg_invariant (volume : measure ℝ) := ⟨eq.symm $ real.measure_ext_Ioo_rat $ λ p q, by simp [show volume.neg (Ioo (p : ℝ) q) = _, from measure.map_apply measurable_neg measurable_set_Ioo]⟩ /-! ### Images of the Lebesgue measure under translation/linear maps in ℝⁿ -/ open matrix /-- A diagonal matrix rescales Lebesgue according to its determinant. This is a special case of `real.map_matrix_volume_pi_eq_smul_volume_pi`, that one should use instead (and whose proof uses this particular case). -/ lemma smul_map_diagonal_volume_pi [decidable_eq ι] {D : ι → ℝ} (h : det (diagonal D) ≠ 0) : ennreal.of_real (abs (det (diagonal D))) • measure.map ((diagonal D).to_lin') volume = volume := begin refine (measure.pi_eq (λ s hs, _)).symm, simp only [det_diagonal, measure.coe_smul, algebra.id.smul_eq_mul, pi.smul_apply], rw [measure.map_apply _ (measurable_set.univ_pi_fintype hs)], swap, { exact continuous.measurable (linear_map.continuous_on_pi _) }, have : (matrix.to_lin' (diagonal D)) ⁻¹' (set.pi set.univ (λ (i : ι), s i)) = set.pi set.univ (λ (i : ι), ((*) (D i)) ⁻¹' (s i)), { ext f, simp only [linear_map.coe_proj, algebra.id.smul_eq_mul, linear_map.smul_apply, mem_univ_pi, mem_preimage, linear_map.pi_apply, diagonal_to_lin'] }, have B : ∀ i, of_real (abs (D i)) * volume (has_mul.mul (D i) ⁻¹' s i) = volume (s i), { assume i, have A : D i ≠ 0, { simp only [det_diagonal, ne.def] at h, exact finset.prod_ne_zero_iff.1 h i (finset.mem_univ i) }, rw [volume_preimage_mul_left A, ← mul_assoc, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_inv_cancel A, abs_one, ennreal.of_real_one, one_mul] }, rw [this, volume_pi_pi, finset.abs_prod, ennreal.of_real_prod_of_nonneg (λ i hi, abs_nonneg (D i)), ← finset.prod_mul_distrib], simp only [B] end /-- A transvection preserves Lebesgue measure. -/ lemma volume_preserving_transvection_struct [decidable_eq ι] (t : transvection_struct ι ℝ) : measure_preserving (t.to_matrix.to_lin') := begin /- We separate the coordinate along which there is a shearing from the other ones, and apply Fubini. Along this coordinate (and when all the other coordinates are fixed), it acts like a translation, and therefore preserves Lebesgue. -/ let p : ι → Prop := λ i, i ≠ t.i, let α : Type* := {x // p x}, let β : Type* := {x // ¬ (p x)}, let g : (α → ℝ) → (β → ℝ) → (β → ℝ) := λ a b, (λ x, t.c * a ⟨t.j, t.hij.symm⟩) + b, let F : (α → ℝ) × (β → ℝ) → (α → ℝ) × (β → ℝ) := λ p, (id p.1, g p.1 p.2), let e : (ι → ℝ) ≃ᵐ (α → ℝ) × (β → ℝ) := measurable_equiv.pi_equiv_pi_subtype_prod (λ i : ι, ℝ) p, have : (t.to_matrix.to_lin' : (ι → ℝ) → (ι → ℝ)) = e.symm ∘ F ∘ e, { cases t, ext f k, simp only [linear_equiv.map_smul, dite_eq_ite, linear_map.id_coe, p, ite_not, algebra.id.smul_eq_mul, one_mul, dot_product, std_basis_matrix, measurable_equiv.pi_equiv_pi_subtype_prod_symm_apply, id.def, transvection, pi.add_apply, zero_mul, linear_map.smul_apply, function.comp_app, measurable_equiv.pi_equiv_pi_subtype_prod_apply, matrix.transvection_struct.to_matrix_mk, matrix.mul_vec, linear_equiv.map_add, ite_mul, e, matrix.to_lin'_apply, pi.smul_apply, subtype.coe_mk, g, linear_map.add_apply, finset.sum_congr, matrix.to_lin'_one], by_cases h : t_i = k, { simp only [h, true_and, finset.mem_univ, if_true, eq_self_iff_true, finset.sum_ite_eq, one_apply, boole_mul, add_comm], }, { simp only [h, ne.symm h, add_zero, if_false, finset.sum_const_zero, false_and, mul_zero] } }, rw this, have A : measure_preserving e, { convert volume_preserving_pi_equiv_pi_subtype_prod (λ i : ι, ℝ) p }, have B : measure_preserving F, { have g_meas : measurable (function.uncurry g), { have : measurable (λ (c : (α → ℝ)), c ⟨t.j, t.hij.symm⟩) := measurable_pi_apply ⟨t.j, t.hij.symm⟩, refine (measurable_pi_lambda _ (λ i, measurable.const_mul _ _)).add measurable_snd, exact this.comp measurable_fst }, exact (measure_preserving.id _).skew_product g_meas (eventually_of_forall (λ a, map_add_left_eq_self _ _)) }, exact ((A.symm e).comp B).comp A, end /-- Any invertible matrix rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_matrix_volume_pi_eq_smul_volume_pi [decidable_eq ι] {M : matrix ι ι ℝ} (hM : det M ≠ 0) : measure.map M.to_lin' volume = ennreal.of_real (abs (det M)⁻¹) • volume := begin -- This follows from the cases we have already proved, of diagonal matrices and transvections, -- as these matrices generate all invertible matrices. apply diagonal_transvection_induction_of_det_ne_zero _ M hM (λ D hD, _) (λ t, _) (λ A B hA hB IHA IHB, _), { conv_rhs { rw [← smul_map_diagonal_volume_pi hD] }, rw [smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel hD, abs_one, ennreal.of_real_one, one_smul] }, { simp only [matrix.transvection_struct.det, ennreal.of_real_one, (volume_preserving_transvection_struct _).map_eq, one_smul, _root_.inv_one, abs_one] }, { rw [to_lin'_mul, det_mul, linear_map.coe_comp, ← measure.map_map, IHB, measure.map_smul, IHA, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_comm, mul_inv], { apply continuous.measurable, apply linear_map.continuous_on_pi }, { apply continuous.measurable, apply linear_map.continuous_on_pi } } end /-- Any invertible linear map rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_linear_map_volume_pi_eq_smul_volume_pi {f : (ι → ℝ) →ₗ[ℝ] (ι → ℝ)} (hf : f.det ≠ 0) : measure.map f volume = ennreal.of_real (abs (f.det)⁻¹) • volume := begin -- this is deduced from the matrix case classical, let M := f.to_matrix', have A : f.det = det M, by simp only [linear_map.det_to_matrix'], have B : f = M.to_lin', by simp only [to_lin'_to_matrix'], rw [A, B], apply map_matrix_volume_pi_eq_smul_volume_pi, rwa A at hf end end real open_locale topological_space lemma filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : ∀ᶠ x in 𝓝 a, p x) : (0 : ℝ≥0∞) < volume {x | p x} := begin rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩, refine lt_of_lt_of_le _ (measure_mono hs), simpa [-mem_Ioo] using hx.1.trans hx.2 end section region_between open_locale classical variable {α : Type*} /-- The region between two real-valued functions on an arbitrary set. -/ def region_between (f g : α → ℝ) (s : set α) : set (α × ℝ) := {p : α × ℝ | p.1 ∈ s ∧ p.2 ∈ Ioo (f p.1) (g p.1)} lemma region_between_subset (f g : α → ℝ) (s : set α) : region_between f g s ⊆ s ×ˢ univ := by simpa only [prod_univ, region_between, set.preimage, set_of_subset_set_of] using λ a, and.left variables [measurable_space α] {μ : measure α} {f g : α → ℝ} {s : set α} /-- The region between two measurable functions on a measurable set is measurable. -/ lemma measurable_set_region_between (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set (region_between f g s) := begin dsimp only [region_between, Ioo, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter (measurable_set_lt measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graph of the upper function. -/ lemma measurable_set_region_between_oc (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Ioc (f p.fst) (g p.fst)} := begin dsimp only [region_between, Ioc, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter (measurable_set_le measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graph of the lower function. -/ lemma measurable_set_region_between_co (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Ico (f p.fst) (g p.fst)} := begin dsimp only [region_between, Ico, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_le (hf.comp measurable_fst) measurable_snd).inter (measurable_set_lt measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graphs of both functions. -/ lemma measurable_set_region_between_cc (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Icc (f p.fst) (g p.fst)} := begin dsimp only [region_between, Icc, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_le (hf.comp measurable_fst) measurable_snd).inter (measurable_set_le measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The graph of a measurable function is a measurable set. -/ lemma measurable_set_graph (hf : measurable f) : measurable_set {p : α × ℝ | p.snd = f p.fst} := by simpa using measurable_set_region_between_cc hf hf measurable_set.univ theorem volume_region_between_eq_lintegral' (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin rw measure.prod_apply, { have h : (λ x, volume {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)}) = s.indicator (λ x, ennreal.of_real (g x - f x)), { funext x, rw indicator_apply, split_ifs, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = Ioo (f x) (g x) := by simp [h, Ioo], simp only [hx, real.volume_Ioo, sub_zero] }, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = ∅ := by simp [h], simp only [hx, measure_empty] } }, dsimp only [region_between, preimage_set_of_eq], rw [h, lintegral_indicator]; simp only [hs, pi.sub_apply] }, { exact measurable_set_region_between hf hg hs }, end /-- The volume of the region between two almost everywhere measurable functions on a measurable set can be represented as a Lebesgue integral. -/ theorem volume_region_between_eq_lintegral [sigma_finite μ] (hf : ae_measurable f (μ.restrict s)) (hg : ae_measurable g (μ.restrict s)) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin have h₁ : (λ y, ennreal.of_real ((g - f) y)) =ᵐ[μ.restrict s] λ y, ennreal.of_real ((ae_measurable.mk g hg - ae_measurable.mk f hf) y) := (hg.ae_eq_mk.sub hf.ae_eq_mk).fun_comp _, have h₂ : (μ.restrict s).prod volume (region_between f g s) = (μ.restrict s).prod volume (region_between (ae_measurable.mk f hf) (ae_measurable.mk g hg) s), { apply measure_congr, apply eventually_eq.rfl.inter, exact ((ae_eq_comp' measurable_fst.ae_measurable hf.ae_eq_mk measure.prod_fst_absolutely_continuous).comp₂ _ eventually_eq.rfl).inter (eventually_eq.rfl.comp₂ _ (ae_eq_comp' measurable_fst.ae_measurable hg.ae_eq_mk measure.prod_fst_absolutely_continuous)) }, rw [lintegral_congr_ae h₁, ← volume_region_between_eq_lintegral' hf.measurable_mk hg.measurable_mk hs], convert h₂ using 1, { rw measure.restrict_prod_eq_prod_univ, exact (measure.restrict_eq_self _ (region_between_subset f g s)).symm, }, { rw measure.restrict_prod_eq_prod_univ, exact (measure.restrict_eq_self _ (region_between_subset (ae_measurable.mk f hf) (ae_measurable.mk g hg) s)).symm }, end theorem volume_region_between_eq_integral' [sigma_finite μ] (f_int : integrable_on f s μ) (g_int : integrable_on g s μ) (hs : measurable_set s) (hfg : f ≤ᵐ[μ.restrict s] g ) : μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) := begin have h : g - f =ᵐ[μ.restrict s] (λ x, real.to_nnreal (g x - f x)), from hfg.mono (λ x hx, (real.coe_to_nnreal _ $ sub_nonneg.2 hx).symm), rw [volume_region_between_eq_lintegral f_int.ae_measurable g_int.ae_measurable hs, integral_congr_ae h, lintegral_congr_ae, lintegral_coe_eq_integral _ ((integrable_congr h).mp (g_int.sub f_int))], simpa only, end /-- If two functions are integrable on a measurable set, and one function is less than or equal to the other on that set, then the volume of the region between the two functions can be represented as an integral. -/ theorem volume_region_between_eq_integral [sigma_finite μ] (f_int : integrable_on f s μ) (g_int : integrable_on g s μ) (hs : measurable_set s) (hfg : ∀ x ∈ s, f x ≤ g x) : μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) := volume_region_between_eq_integral' f_int g_int hs ((ae_restrict_iff' hs).mpr (eventually_of_forall hfg)) end region_between
c1c377109b453d8d34dfc89065b343b1a6a38edf
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/run/reserve.lean
7ee6a52e16a04d4021a83d33b025717d24f8ca5f
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
178
lean
reserve infix `=?=`:50 reserve infixr `&&&`:25 notation a `=?=` b := eq a b notation a `&&&` b := and a b set_option pp.notation false #check λ a b : num, a =?= b &&& b =?= a
ffa04e367cbda22995a3aa8e521997f98bc70178
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/converter/conv.lean
622ec654b71ca5015ac6edac40093280f513aede
[]
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
774
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Converter monad for building simplifiers. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.meta.simp_tactic import Mathlib.Lean3Lib.init.meta.interactive import Mathlib.Lean3Lib.init.meta.congr_lemma import Mathlib.Lean3Lib.init.meta.match_tactic namespace Mathlib /-- `conv α` is a tactic for discharging goals of the form `lhs ~ rhs` for some relation `~` (usually equality) and fixed lhs, rhs. Known in the literature as a __conversion__ tactic. So for example, if one had the lemma `p : x = y`, then the conversion for `p` would be one that solves `p`. -/
94d2446dfb213218de931e9389d25b0055a4b9bf
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Leanpkg/Proc.lean
f62c07c2c86f0fe5535e68c3e461830a4ffe1d0e
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
730
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich -/ namespace Leanpkg def execCmd (args : IO.Process.SpawnArgs) : IO Unit := do let envstr := String.join <| args.env.toList.map fun (k, v) => s!"{k}={v.getD ""} " let cmdstr := " ".intercalate (args.cmd :: args.args.toList) IO.println <| "> " ++ envstr ++ match args.cwd with | some cwd => cmdstr ++ " # in directory " ++ cwd | none => cmdstr let child ← IO.Process.spawn args let exitCode ← child.wait if exitCode != 0 then throw <| IO.userError <| s!"external command exited with status {exitCode}" end Leanpkg
8004dcde0357140c95432177e0f0388175b10820
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/whiskering.lean
13dbbf7a8ef2b2f1539ebb77af84dab8e24e74f4
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
5,580
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.isomorphism import category_theory.functor_category namespace category_theory universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄ section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] (E : Type u₃) [ℰ : category.{v₃} E] include 𝒞 𝒟 ℰ def whiskering_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) := { obj := λ F, { obj := λ G, F ⋙ G, map := λ G H α, { app := λ c, α.app (F.obj c), naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, α.naturality] } }, map := λ F G τ, { app := λ H, { app := λ c, H.map (τ.app c), naturality' := λ X Y f, begin dsimp at *, rw [←H.map_comp, ←H.map_comp, ←τ.naturality] end }, naturality' := λ X Y f, begin ext1, dsimp at *, rw [←nat_trans.naturality] end } } def whiskering_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) := { obj := λ H, { obj := λ F, F ⋙ H, map := λ _ _ α, { app := λ c, H.map (α.app c), naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, ←H.map_comp, ←H.map_comp, α.naturality] } }, map := λ G H τ, { app := λ F, { app := λ c, τ.app (F.obj c), naturality' := λ X Y f, begin dsimp at *, rw [τ.naturality] end }, naturality' := λ X Y f, begin ext1, dsimp at *, rw [←nat_trans.naturality] end } } variables {C} {D} {E} def whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟹ H) : (F ⋙ G) ⟹ (F ⋙ H) := ((whiskering_left C D E).obj F).map α @[simp] lemma whisker_left.app (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟹ H) (X : C) : (whisker_left F α).app X = α.app (F.obj X) := rfl def whisker_right {G H : C ⥤ D} (α : G ⟹ H) (F : D ⥤ E) : (G ⋙ F) ⟹ (H ⋙ F) := ((whiskering_right C D E).obj F).map α @[simp] lemma whisker_right.app {G H : C ⥤ D} (α : G ⟹ H) (F : D ⥤ E) (X : C) : (whisker_right α F).app X = F.map (α.app X) := rfl @[simp] lemma whisker_left_id (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (nat_trans.id G) = nat_trans.id (F.comp G) := rfl @[simp] lemma whisker_right_id {G : C ⥤ D} (F : D ⥤ E) : whisker_right (nat_trans.id G) F = nat_trans.id (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_left_vcomp (F : C ⥤ D) {G H K : D ⥤ E} (α : G ⟹ H) (β : H ⟹ K) : whisker_left F (α ⊟ β) = (whisker_left F α) ⊟ (whisker_left F β) := rfl @[simp] lemma whisker_right_vcomp {G H K : C ⥤ D} (α : G ⟹ H) (β : H ⟹ K) (F : D ⥤ E) : whisker_right (α ⊟ β) F = (whisker_right α F) ⊟ (whisker_right β F) := ((whiskering_right C D E).obj F).map_comp α β variables {B : Type u₄} [ℬ : category.{v₄} B] include ℬ local attribute [elab_simple] whisker_left whisker_right @[simp] lemma whisker_left_twice (F : B ⥤ C) (G : C ⥤ D) {H K : D ⥤ E} (α : H ⟹ K) : whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α := rfl @[simp] lemma whisker_right_twice {H K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟹ K) : whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) := rfl lemma whisker_right_left (F : B ⥤ C) {G H : C ⥤ D} (α : G ⟹ H) (K : D ⥤ E) : whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) := rfl end namespace functor universes u₅ v₅ variables {A : Type u₁} [𝒜 : category.{v₁} A] variables {B : Type u₂} [ℬ : category.{v₂} B] include 𝒜 ℬ def left_unitor (F : A ⥤ B) : ((functor.id _) ⋙ F) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] lemma left_unitor_hom_app {F : A ⥤ B} {X} : F.left_unitor.hom.app X = 𝟙 _ := rfl @[simp] lemma left_unitor_inv_app {F : A ⥤ B} {X} : F.left_unitor.inv.app X = 𝟙 _ := rfl def right_unitor (F : A ⥤ B) : (F ⋙ (functor.id _)) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] lemma right_unitor_hom_app {F : A ⥤ B} {X} : F.right_unitor.hom.app X = 𝟙 _ := rfl @[simp] lemma right_unitor_inv_app {F : A ⥤ B} {X} : F.right_unitor.inv.app X = 𝟙 _ := rfl variables {C : Type u₃} [𝒞 : category.{v₃} C] variables {D : Type u₄} [𝒟 : category.{v₄} D] include 𝒞 𝒟 def associator (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) : ((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H)) := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } } @[simp] lemma associator_hom_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} : (associator F G H).hom.app X = 𝟙 _ := rfl @[simp] lemma associator_inv_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} : (associator F G H).inv.app X = 𝟙 _ := rfl omit 𝒟 lemma triangle (F : A ⥤ B) (G : B ⥤ C) : (associator F (functor.id B) G).hom ⊟ (whisker_left F (left_unitor G).hom) = (whisker_right (right_unitor F).hom G) := begin ext1, dsimp [associator, left_unitor, right_unitor], simp end variables {E : Type u₅} [ℰ : category.{v₅} E] include 𝒟 ℰ variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E) lemma pentagon : (whisker_right (associator F G H).hom K) ⊟ (associator F (G ⋙ H) K).hom ⊟ (whisker_left F (associator G H K).hom) = ((associator (F ⋙ G) H K).hom ⊟ (associator F G (H ⋙ K)).hom) := begin ext1, dsimp [associator], simp, end end functor end category_theory
fd7d57b792b141fc88c5086ea528f76e45518c62
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/option/defs.lean
36ebc54d059bf18f687e4eb9c1b6cea58524efa9
[ "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
3,583
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Extra definitions on option. -/ namespace option variables {α : Type*} {β : Type*} instance has_mem : has_mem α (option α) := ⟨λ a b, b = some a⟩ @[simp] theorem mem_def {a : α} {b : option α} : a ∈ b ↔ b = some a := iff.rfl theorem is_none_iff_eq_none {o : option α} : o.is_none = tt ↔ o = none := ⟨option.eq_none_of_is_none, λ e, e.symm ▸ rfl⟩ theorem some_inj {a b : α} : some a = some b ↔ a = b := by simp instance decidable_eq_none {o : option α} : decidable (o = none) := decidable_of_decidable_of_iff (bool.decidable_eq _ _) is_none_iff_eq_none instance decidable_forall_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∀ a ∈ o, p a) | none := is_true (by simp) | (some a) := if h : p a then is_true $ λ o e, some_inj.1 e ▸ h else is_false $ mt (λ H, H _ rfl) h instance decidable_exists_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∃ a ∈ o, p a) | none := is_false (λ ⟨a, ⟨h, _⟩⟩, by cases h) | (some a) := if h : p a then is_true $ ⟨_, rfl, h⟩ else is_false $ λ ⟨_, ⟨rfl, hn⟩⟩, h hn /-- inhabited `get` function. Returns `a` if the input is `some a`, otherwise returns `default`. -/ @[reducible] def iget [inhabited α] : option α → α | (some x) := x | none := default α @[simp] theorem iget_some [inhabited α] {a : α} : (some a).iget = a := rfl /-- `guard p a` returns `some a` if `p a` holds, otherwise `none`. -/ def guard (p : α → Prop) [decidable_pred p] (a : α) : option α := if p a then some a else none /-- `filter p o` returns `some a` if `o` is `some a` and `p a` holds, otherwise `none`. -/ def filter (p : α → Prop) [decidable_pred p] (o : option α) : option α := o.bind (guard p) def to_list : option α → list α | none := [] | (some a) := [a] @[simp] theorem mem_to_list {a : α} {o : option α} : a ∈ to_list o ↔ a ∈ o := by cases o; simp [to_list, eq_comm] def lift_or_get (f : α → α → α) : option α → option α → option α | none none := none | (some a) none := some a -- get a | none (some b) := some b -- get b | (some a) (some b) := some (f a b) -- lift f instance lift_or_get_comm (f : α → α → α) [h : is_commutative α f] : is_commutative (option α) (lift_or_get f) := ⟨λ a b, by cases a; cases b; simp [lift_or_get, h.comm]⟩ instance lift_or_get_assoc (f : α → α → α) [h : is_associative α f] : is_associative (option α) (lift_or_get f) := ⟨λ a b c, by cases a; cases b; cases c; simp [lift_or_get, h.assoc]⟩ instance lift_or_get_idem (f : α → α → α) [h : is_idempotent α f] : is_idempotent (option α) (lift_or_get f) := ⟨λ a, by cases a; simp [lift_or_get, h.idempotent]⟩ instance lift_or_get_is_left_id (f : α → α → α) : is_left_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ instance lift_or_get_is_right_id (f : α → α → α) : is_right_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ inductive rel (r : α → β → Prop) : option α → option β → Prop | some {a b} : r a b → rel (some a) (some b) | none {} : rel none none protected def {u v} traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : option α → F (option β) | none := pure none | (some x) := some <$> f x end option
7454ec3a7d3bf807d9cec9e3a979d2caa39462ad
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/bool/count.lean
a1d3d07f72dddca8ac93dbadb71041f8d0da96ff
[ "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
4,360
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.nat.parity /-! # List of booleans In this file we prove lemmas about the number of `ff`s and `tt`s in a list of booleans. First we prove that the number of `ff`s plus the number of `tt` equals the length of the list. Then we prove that in a list with alternating `tt`s and `ff`s, the number of `tt`s differs from the number of `ff`s by at most one. We provide several versions of these statements. -/ namespace list @[simp] theorem count_bnot_add_count (l : list bool) (b : bool) : count (!b) l + count b l = length l := by simp only [length_eq_countp_add_countp (eq (!b)), bool.bnot_not_eq, count] @[simp] theorem count_add_count_bnot (l : list bool) (b : bool) : count b l + count (!b) l = length l := by rw [add_comm, count_bnot_add_count] @[simp] theorem count_ff_add_count_tt (l : list bool) : count ff l + count tt l = length l := count_bnot_add_count l tt @[simp] theorem count_tt_add_count_ff (l : list bool) : count tt l + count ff l = length l := count_bnot_add_count l ff lemma chain.count_bnot : ∀ {b : bool} {l : list bool}, chain (≠) b l → count (!b) l = count b l + length l % 2 | b [] h := rfl | b (x :: l) h := begin obtain rfl : b = !x := bool.eq_bnot_iff.2 (rel_of_chain_cons h), rw [bnot_bnot, count_cons_self, count_cons_of_ne x.bnot_ne_self, chain.count_bnot (chain_of_chain_cons h), length, add_assoc, nat.mod_two_add_succ_mod_two] end namespace chain' variables {l : list bool} theorem count_bnot_eq_count (hl : chain' (≠) l) (h2 : even (length l)) (b : bool) : count (!b) l = count b l := begin cases l with x l, { refl }, rw [length_cons, nat.even_add_one, nat.not_even_iff] at h2, suffices : count (!x) (x :: l) = count x (x :: l), { cases b; cases x; try { exact this }; exact this.symm }, rw [count_cons_of_ne x.bnot_ne_self, hl.count_bnot, h2, count_cons_self] end theorem count_ff_eq_count_tt (hl : chain' (≠) l) (h2 : even (length l)) : count ff l = count tt l := hl.count_bnot_eq_count h2 tt lemma count_bnot_le_count_add_one (hl : chain' (≠) l) (b : bool) : count (!b) l ≤ count b l + 1 := begin cases l with x l, { exact zero_le _ }, obtain rfl | rfl : b = x ∨ b = !x, by simp only [bool.eq_bnot_iff, em], { rw [count_cons_of_ne b.bnot_ne_self, count_cons_self, hl.count_bnot, add_assoc], exact add_le_add_left (nat.mod_lt _ two_pos).le _ }, { rw [bnot_bnot, count_cons_self, count_cons_of_ne x.bnot_ne_self, hl.count_bnot], exact add_le_add_right (le_add_right le_rfl) _ } end lemma count_ff_le_count_tt_add_one (hl : chain' (≠) l) : count ff l ≤ count tt l + 1 := hl.count_bnot_le_count_add_one tt lemma count_tt_le_count_ff_add_one (hl : chain' (≠) l) : count tt l ≤ count ff l + 1 := hl.count_bnot_le_count_add_one ff theorem two_mul_count_bool_of_even (hl : chain' (≠) l) (h2 : even (length l)) (b : bool) : 2 * count b l = length l := by rw [← count_bnot_add_count l b, hl.count_bnot_eq_count h2, two_mul] theorem two_mul_count_bool_eq_ite (hl : chain' (≠) l) (b : bool) : 2 * count b l = if even (length l) then length l else if b ∈ l.head' then length l + 1 else length l - 1 := begin by_cases h2 : even (length l), { rw [if_pos h2, hl.two_mul_count_bool_of_even h2] }, { cases l with x l, { exact (h2 even_zero).elim }, simp only [if_neg h2, count_cons', mul_add, head', option.mem_some_iff, @eq_comm _ x], rw [length_cons, nat.even_add_one, not_not] at h2, replace hl : l.chain' (≠) := hl.tail, rw [hl.two_mul_count_bool_of_even h2], split_ifs; simp } end theorem length_sub_one_le_two_mul_count_bool (hl : chain' (≠) l) (b : bool) : length l - 1 ≤ 2 * count b l := by { rw [hl.two_mul_count_bool_eq_ite], split_ifs; simp [le_tsub_add, nat.le_succ_of_le] } theorem length_div_two_le_count_bool (hl : chain' (≠) l) (b : bool) : length l / 2 ≤ count b l := begin rw [nat.div_le_iff_le_mul_add_pred two_pos, ← tsub_le_iff_right], exact length_sub_one_le_two_mul_count_bool hl b end lemma two_mul_count_bool_le_length_add_one (hl : chain' (≠) l) (b : bool) : 2 * count b l ≤ length l + 1 := by { rw [hl.two_mul_count_bool_eq_ite], split_ifs; simp [nat.le_succ_of_le] } end chain' end list
c4eeb58a69d222cfca19ff100b292db7b1dbe6f8
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/rw_set2.lean
71377a296594c44af8eb2292dfe355b6eaa2a76c
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
35
lean
import data.nat print [simp] nat
4c3f952006672dbdba41cf1ec30d535cbd4ca2b2
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/type_library/list.lean
48c565748db3837c72a5ef9d0f976a667b548f3f
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
610
lean
namespace hidden universe u inductive list (α : Type u) : Type u | nil {} : list | cons (h : α) (t : list) : list #check list #check list nat #check list string #check list bool def l : list nat := list.nil def t : list nat := list.cons (3) (list.cons (4) (list.cons 5 list.nil) ) #check (list.cons 5 list.nil) -- [3,4,5] /- inductive list (α : Type u) : Type u | nil {} : list | cons (h : α) (t : list) : list -/ def list_len {α : Type u} : list α → nat | list.nil := 0 | (list.cons h t) := (list_len t) + 1 #eval list_len t #print list end hidden
1419b1c2586d0fbe7bebd0cd0dea1b0bf48cdb09
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/discrete_category.lean
3f2cfa4fcb498c1a28b9af72e2616a9ee73e7b45
[ "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
6,217
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, Floris van Doorn -/ import category_theory.eq_to_hom import data.ulift /-! # Discrete categories We define `discrete α := α` for any type `α`, and use this type alias to provide a `small_category` instance whose only morphisms are the identities. There is an annoying technical difficulty that it has turned out to be inconvenient to allow categories with morphisms living in `Prop`, so instead of defining `X ⟶ Y` in `discrete α` as `X = Y`, one might define it as `plift (X = Y)`. In fact, to allow `discrete α` to be a `small_category` (i.e. with morphisms in the same universe as the objects), we actually define the hom type `X ⟶ Y` as `ulift (plift (X = Y))`. `discrete.functor` promotes a function `f : I → C` (for any category `C`) to a functor `discrete.functor f : discrete I ⥤ C`. Similarly, `discrete.nat_trans` and `discrete.nat_iso` promote `I`-indexed families of morphisms, or `I`-indexed families of isomorphisms to natural transformations or natural isomorphism. We show equivalences of types are the same as (categorical) equivalences of the corresponding discrete categories. -/ namespace category_theory universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. /-- A type synonym for promoting any type to a category, with the only morphisms being equalities. -/ def discrete (α : Type u₁) := α /-- The "discrete" category on a type, whose morphisms are equalities. Because we do not allow morphisms in `Prop` (only in `Type`), somewhat annoyingly we have to define `X ⟶ Y` as `ulift (plift (X = Y))`. See https://stacks.math.columbia.edu/tag/001A -/ instance discrete_category (α : Type u₁) : small_category (discrete α) := { hom := λ X Y, ulift (plift (X = Y)), id := λ X, ulift.up (plift.up rfl), comp := λ X Y Z g f, by { rcases f with ⟨⟨rfl⟩⟩, exact g } } namespace discrete variables {α : Type u₁} instance [inhabited α] : inhabited (discrete α) := by { dsimp [discrete], apply_instance } instance [subsingleton α] : subsingleton (discrete α) := by { dsimp [discrete], apply_instance } /-- Extract the equation from a morphism in a discrete category. -/ lemma eq_of_hom {X Y : discrete α} (i : X ⟶ Y) : X = Y := i.down.down @[simp] lemma id_def (X : discrete α) : ulift.up (plift.up (eq.refl X)) = 𝟙 X := rfl variables {C : Type u₂} [category.{v₂} C] instance {I : Type u₁} {i j : discrete I} (f : i ⟶ j) : is_iso f := ⟨⟨eq_to_hom (eq_of_hom f).symm, by tidy⟩⟩ /-- Any function `I → C` gives a functor `discrete I ⥤ C`. -/ def functor {I : Type u₁} (F : I → C) : discrete I ⥤ C := { obj := F, map := λ X Y f, begin cases f, cases f, cases f, exact 𝟙 (F X) end } @[simp] lemma functor_obj {I : Type u₁} (F : I → C) (i : I) : (discrete.functor F).obj i = F i := rfl lemma functor_map {I : Type u₁} (F : I → C) {i : discrete I} (f : i ⟶ i) : (discrete.functor F).map f = 𝟙 (F i) := by { cases f, cases f, cases f, refl } /-- For functors out of a discrete category, a natural transformation is just a collection of maps, as the naturality squares are trivial. -/ def nat_trans {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) : F ⟶ G := { app := f } @[simp] lemma nat_trans_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) (i) : (discrete.nat_trans f).app i = f i := rfl /-- For functors out of a discrete category, a natural isomorphism is just a collection of isomorphisms, as the naturality squares are trivial. -/ def nat_iso {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) : F ≅ G := nat_iso.of_components f (by tidy) @[simp] lemma nat_iso_hom_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).hom.app i = (f i).hom := rfl @[simp] lemma nat_iso_inv_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).inv.app i = (f i).inv := rfl @[simp] lemma nat_iso_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).app i = f i := by tidy /-- Every functor `F` from a discrete category is naturally isomorphic (actually, equal) to `discrete.functor (F.obj)`. -/ def nat_iso_functor {I : Type u₁} {F : discrete I ⥤ C} : F ≅ discrete.functor (F.obj) := nat_iso $ λ i, iso.refl _ /-- We can promote a type-level `equiv` to an equivalence between the corresponding `discrete` categories. -/ @[simps] def equivalence {I J : Type u₁} (e : I ≃ J) : discrete I ≌ discrete J := { functor := discrete.functor (e : I → J), inverse := discrete.functor (e.symm : J → I), unit_iso := discrete.nat_iso (λ i, eq_to_iso (by simp)), counit_iso := discrete.nat_iso (λ j, eq_to_iso (by simp)), } /-- We can convert an equivalence of `discrete` categories to a type-level `equiv`. -/ @[simps] def equiv_of_equivalence {α β : Type u₁} (h : discrete α ≌ discrete β) : α ≃ β := { to_fun := h.functor.obj, inv_fun := h.inverse.obj, left_inv := λ a, eq_of_hom (h.unit_iso.app a).2, right_inv := λ a, eq_of_hom (h.counit_iso.app a).1 } end discrete namespace discrete variables {J : Type v₁} open opposite /-- A discrete category is equivalent to its opposite category. -/ protected def opposite (α : Type u₁) : (discrete α)ᵒᵖ ≌ discrete α := let F : discrete α ⥤ (discrete α)ᵒᵖ := discrete.functor (λ x, op x) in begin refine equivalence.mk (functor.left_op F) F _ (discrete.nat_iso $ λ X, by simp [F]), refine nat_iso.of_components (λ X, by simp [F]) _, tidy end variables {C : Type u₂} [category.{v₂} C] @[simp] lemma functor_map_id (F : discrete J ⥤ C) {j : discrete J} (f : j ⟶ j) : F.map f = 𝟙 (F.obj j) := begin have h : f = 𝟙 j, { cases f, cases f, ext, }, rw h, simp, end end discrete end category_theory
953b407d85058a97126c0c87fb7be0937235f415
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Parser/Basic.lean
edd32307a3c203f48e899f7966cd58ff1fcae45e
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
75,445
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 `leading_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 import Lean.ResolveName namespace Lean namespace Parser def isLitKind (k : SyntaxNodeKind) : Bool := k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind 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 := eval_prec max def argPrec : Nat := eval_prec arg def leadPrec : Nat := eval_prec lead def minPrec : Nat := eval_prec min abbrev Token := String structure TokenCacheEntry where startPos : String.Pos := 0 stopPos : String.Pos := 0 token : Syntax := Syntax.missing structure ParserCache where 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 := Std.PersistentHashMap.insert s 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 where input : String fileName : String fileMap : FileMap deriving Inhabited /-- Input context derived from elaboration of previous commands. -/ structure ParserModuleContext where env : Environment options : Options -- for name lookup currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] structure ParserContext extends InputContext, ParserModuleContext where prec : Nat tokens : TokenTable insideQuot : Bool := false suppressInsideQuot : Bool := false savedPos? : Option String.Pos := none forbiddenTk? : Option Token := none def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) := ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id structure Error where unexpected : String := "" expected : List String := [] deriving Inhabited, BEq namespace 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 : ToString Error := ⟨Error.toString⟩ 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 where stxStack : Array Syntax := #[] /-- Set to the precedence of the preceding (not surrounding) parser by `runLongestMatchParser` for the use of `checkLhsPrec` in trailing parsers. Note that with chaining, the preceding parser can be another trailing parser: in `1 * 2 + 3`, the preceding parser is '*' when '+' is executed. -/ lhsPrec : Nat := 0 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 (toString msg) def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => if err != none && stack.size == iniStackSz then -- If there is an error but there are no new nodes on the stack, use `missing` instead. -- Thus we ensure the property that an syntax tree contains (at least) one `missing` node -- if (and only if) there was a parse error. -- We should not create an actual node of kind `k` in this case because it would mean we -- choose an "arbitrary" node (in practice the last one) in an alternative of the form -- `node k1 p1 <|> ... <|> node kn pn` when all parsers fail. With the code below we -- instead return a less misleading single `missing` node without randomly selecting any `ki`. let stack := stack.push Syntax.missing ⟨stack, lhsPrec, pos, cache, err⟩ else let newNode := Syntax.node k (stack.extract iniStackSz stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size) let stack := stack.shrink (iniStackSz - 1) let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def mkError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkUnexpectedError (s : ParserState) (msg : String) (expected : List String := []) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { unexpected := msg, expected := expected }⟩ def mkEOIError (s : ParserState) (expected : List String := []) : ParserState := s.mkUnexpectedError "unexpected end of input" expected def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack, lhsPrec, pos, cache, some { expected := ex }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz, lhsPrec, pos, cache, some { expected := ex }⟩ def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { unexpected := msg }⟩ end ParserState def ParserFn := ParserContext → ParserState → ParserState instance : Inhabited ParserFn where default := fun ctx s => s inductive FirstTokens where | epsilon : FirstTokens | unknown : FirstTokens | tokens : List Token → FirstTokens | optTokens : List Token → FirstTokens deriving Inhabited 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 : ToString FirstTokens := ⟨toStr⟩ end FirstTokens structure ParserInfo where collectTokens : List Token → List Token := id collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id firstTokens : FirstTokens := FirstTokens.unknown deriving Inhabited structure Parser where info : ParserInfo := {} fn : ParserFn deriving Inhabited abbrev TrailingParser := Parser def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn := fun c s => let sz := s.stxStack.size let s' := p c s dbg_trace "{label} pos: {s'.pos} err: {s'.errorMsg} out: {s'.stxStack.extract sz s'.stxStack.size}" s' def dbgTraceState (label : String) (p : Parser) : Parser where fn := dbgTraceStateFn label p.fn info := p.info @[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 : AndThen Parser := ⟨andthen⟩ @[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkNode n iniSz @[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun 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 } def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s => match c.savedPos? with | none => s | some pos => let pos := if delta then c.input.next pos else pos match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { unexpected := msg }⟩ /- Generate an error at the position saved with the `withPosition` combinator. If `delta == true`, then it reports at saved position+1. This useful to make sure a parser consumed at least one character. -/ @[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := { fn := errorAtSavedPosFn msg delta } /- 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 } /- Succeeds if `c.lhsPrec >= prec` -/ def checkLhsPrecFn (prec : Nat) : ParserFn := fun c s => if s.lhsPrec >= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkLhsPrecFn prec } def setLhsPrecFn (prec : Nat) : ParserFn := fun c s => if s.hasError then s else { s with lhsPrec := prec } @[inline] def setLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := setLhsPrecFn 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 => if c.suppressInsideQuot then p c s else p { c with insideQuot := !c.insideQuot } s @[inline] def toggleInsideQuot (p : Parser) : Parser := { info := p.info, fn := toggleInsideQuotFn p.fn } def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s => p { c with suppressInsideQuot := true } s @[inline] def suppressInsideQuot (p : Parser) : Parser := { info := p.info, fn := suppressInsideQuotFn p.fn } @[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser := checkPrec prec >> node n p >> setLhsPrec prec @[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := { info := nodeInfo n p.info, fn := trailingNodeFn n p.fn } @[inline] def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser := checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some error2⟩ => if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩ else s | other => other def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn := fun 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 } /-- Run `p`, falling back to `q` if `p` failed without consuming any input. NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...` is fine as well. -/ @[inline] def orelse (p q : Parser) : Parser := { info := orelseInfo p.info q.info, fn := orelseFn p.fn q.fn } instance : OrElse Parser := ⟨orelse⟩ @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { collectTokens := info.collectTokens, collectKinds := info.collectKinds } def atomicFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos match p c s with | ⟨stack, lhsPrec, _, cache, some msg⟩ => ⟨stack.shrink iniSz, lhsPrec, iniPos, cache, some msg⟩ | other => other @[inline] def atomic (p : Parser) : Parser := { info := p.info, fn := atomicFn p.fn } 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 optionalNoAntiquot (p : Parser) : Parser := { info := optionaInfo p.info, fn := optionalFn p.fn } 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 } def notFollowedByFn (p : ParserFn) (msg : String) : 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.mkUnexpectedError s!"unexpected {msg}" @[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := { fn := notFollowedByFn p.fn msg } partial def manyAux (p : ParserFn) : ParserFn := fun c s => do let iniSz := s.stackSize let iniPos := s.pos let mut s := p c s if s.hasError then return if iniPos == s.pos then s.restore iniSz iniPos else s if iniPos == s.pos then return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything" if s.stackSize > iniSz + 1 then s := s.mkNode nullKind iniSz manyAux p 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 manyNoAntiquot (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 many1NoAntiquot (p : Parser) : Parser := { info := p.info, fn := many1Fn p.fn } private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn := let rec parse (pOpt : Bool) (c s) := do let sz := s.stackSize let pos := s.pos let mut s := p c s if s.hasError then if s.pos > pos then return s.mkNode nullKind iniSz else if pOpt then let s := s.restore sz pos return s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete let s := s.pushSyntax Syntax.missing return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz let sz := s.stackSize let pos := s.pos let s := sep c s if s.hasError then let s := s.restore sz pos return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz parse allowTrailingSep c s parse pOpt def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz true c s def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun 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 sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepByInfo p.info sep.info, fn := sepByFn allowTrailingSep p.fn sep.fn } @[inline] def sepBy1NoAntiquot (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` -/ 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 (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun 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 partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else if p (c.input.get i) then s else takeUntilFn p c (s.next c.input i) 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) variable (startPos : String.Pos) in partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then eoi s else let curr := input.get i let i := input.next i if curr == '-' then if input.atEnd i then eoi s 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 eoi s 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) where eoi s := s.mkUnexpectedErrorAt "unterminated comment" startPos /- Consume whitespace and comments -/ partial def whitespace : ParserFn := fun 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 startPos := i 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 startPos 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 := fun 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 (SourceInfo.original leading startPos trailing) val s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos let atom := mkAtom (SourceInfo.original leading startPos 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 := fun 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 := fun 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" def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun 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 := SourceInfo.original leading startPos trailing s.pushSyntax (Syntax.mkLit n val info) def charLitFnAux (startPos : Nat) : ParserFn := fun 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 := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos 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 startPos) c s else strLitFnAux startPos c s def decimalNumberFn (startPos : Nat) (c : ParserContext) : ParserState → ParserState := fun s => let s := takeWhileFn (fun c => c.isDigit) c s let input := c.input let i := s.pos let curr := input.get i if curr == '.' || curr == 'e' || curr == 'E' then let s := parseOptDot s let s := parseOptExp s mkNodeToken scientificLitKind startPos c s else mkNodeToken numLitKind startPos c s where parseOptDot s := let input := c.input let i := s.pos let curr := input.get i 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.setPos i else s parseOptExp s := let input := c.input let i := s.pos let curr := input.get i if curr == 'e' || curr == 'E' then let i := input.next i let i := if input.get i == '-' then input.next i else i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else 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 := fun 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 => if c.forbiddenTk? == some tk then s.mkErrorAt "forbidden token" startPos else 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 (SourceInfo.original leading startPos 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 := SourceInfo.original leading startPos trailing let atom := mkIdent info rawVal val s.pushSyntax atom partial def identFnAux (startPos : Nat) (tk : Option Token) (r : Name) : ParserFn := let rec parse (r : Name) (c s) := do let input := c.input let i := s.pos if input.atEnd i then return s.mkEOIError let curr := input.get i if isIdBeginEscape curr then let startPart := input.next i let s := takeUntilFn isIdEndEscape c (s.setPos startPart) if input.atEnd s.pos then return s.mkUnexpectedErrorAt "unterminated identifier escape" startPart let stopPart := s.pos let s := s.next c.input s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse 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 := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else mkTokenAndFixPos startPos tk c s parse r private def isIdFirstOrBeginEscape (c : Char) : Bool := isIdFirst c || isIdBeginEscape c private def nameLitAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let s := identFnAux startPos none Name.anonymous c (s.next input startPos) if s.hasError then s 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 := fun 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 := -- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache` match s with | ⟨stack, lhsPrec, pos, cache, none⟩ => if stack.size == 0 then s else let tk := stack.back ⟨stack, lhsPrec, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩ | other => other def tokenFn (expected : List String := []) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError expected 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 × Except ParserState Syntax := let iniSz := s.stackSize let iniPos := s.pos let s := tokenFn [] c s if let some e := s.errorMsg then (s.restore iniSz iniPos, Except.error s) else let stx := s.stxStack.back (s.restore iniSz iniPos, Except.ok stx) def peekToken (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let tkc := s.cache.tokenCache if tkc.startPos == s.pos then (s, Except.ok 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 initStackSz := s.stackSize let startPos := s.pos let s := tokenFn expected c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz | _ => s.mkErrorsAt expected startPos initStackSz 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 symbolNoAntiquot (sym : String) : Parser := let sym := sym.trim { info := symbolInfo sym, fn := symbolFn sym } def checkTailNoWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing => trailing.stopPos == trailing.startPos | _ => false /-- 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 initStackSz := s.stackSize let startPos := s.pos let s := tokenFn [errorMsg] c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym' => if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz | Syntax.ident info rawVal _ _ => if sym == rawVal.toString then let s := s.popSyntax s.pushSyntax (Syntax.atom info sym) else s.mkErrorAt errorMsg startPos initStackSz | _ => s.mkErrorAt errorMsg startPos initStackSz @[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 nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser := let sym := sym.trim { info := nonReservedSymbolInfo sym includeIdent, fn := nonReservedSymbolFn sym } partial def strAux (sym : String) (errorMsg : String) (j : Nat) :ParserFn := let rec parse (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 parse (sym.next j) c (s.next input i) parse j def checkTailWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ 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 := "space before") : Parser := { info := epsilonInfo, fn := checkWsBeforeFn errorMsg } def checkTailLinebreak (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing => trailing.contains '\n' | _ => false def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailLinebreak prev then s else s.mkError errorMsg def checkLinebreakBefore (errorMsg : String := "line break") : Parser := { info := epsilonInfo fn := checkLinebreakBeforeFn errorMsg } 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 := "no space before") : Parser := { info := epsilonInfo, fn := checkNoWsBeforeFn errorMsg } 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 unicodeSymbolNoAntiquot (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 initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["numeral"] c s if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s @[inline] def numLitNoAntiquot : Parser := { fn := numLitFn, info := mkAtomicInfo "numLit" } def scientificLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["scientific number"] c s if !s.hasError && !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos initStackSz else s @[inline] def scientificLitNoAntiquot : Parser := { fn := scientificLitFn, info := mkAtomicInfo "scientificLit" } def strLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["string literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos initStackSz else s @[inline] def strLitNoAntiquot : Parser := { fn := strLitFn, info := mkAtomicInfo "strLit" } def charLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["char literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos initStackSz else s @[inline] def charLitNoAntiquot : Parser := { fn := charLitFn, info := mkAtomicInfo "charLit" } def nameLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["Name literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos initStackSz else s @[inline] def nameLitNoAntiquot : Parser := { fn := nameLitFn, info := mkAtomicInfo "nameLit" } def identFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if !s.hasError && !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos initStackSz 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 initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if s.hasError then s else match s.stxStack.back with | Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos initStackSz else s | _ => s.mkErrorAt "identifier" iniPos initStackSz @[inline] def identEq (id : Name) : Parser := { fn := identEqFn id, info := mkAtomicInfo "ident" } namespace ParserState def keepTop (s : Array Syntax) (startStackSize : Nat) : Array Syntax := let node := s.back s.shrink startStackSize |>.push node def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => ⟨keepTop stack oldStackSize, lhsPrec, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.shrink oldStackSize, lhsPrec, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some err⟩ => if oldError == err then s else ⟨stack.shrink oldStackSize, lhsPrec, pos, cache, some (oldError.merge err)⟩ | other => other def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨keepTop stack startStackSize, lhsPrec, 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`. Remark: `p` must produce exactly one syntax node. Remark: the `left?` is not none when we are processing trailing parsers. -/ def runLongestMatchParser (left? : Option Syntax) (startLhsPrec : Nat) (p : ParserFn) : ParserFn := fun c s => do /- We assume any registered parser `p` has one of two forms: * a direct call to `leadingParser` or `trailingParser` * a direct call to a (leading) token parser In the first case, we can extract the precedence of the parser by having `leadingParser/trailingParser` set `ParserState.lhsPrec` to it in the very end so that no nested parser can interfere. In the second case, the precedence is effectively `max` (there is a `checkPrec` merely for the convenience of the pretty printer) and there are no nested `leadingParser/trailingParser` calls, so the value of `lhsPrec` will not be changed by the parser (nor will it be read by any leading parser). Thus we initialize the field to `maxPrec` in the leading case. -/ let mut s := { s with lhsPrec := if left?.isSome then startLhsPrec else maxPrec } let startSize := s.stackSize if let some left := left? then s := s.pushSyntax left s := p c s -- stack contains `[..., result ]` if s.stackSize == startSize + 1 then s -- success or error with the expected number of nodes else if s.hasError then -- error with an unexpected number of nodes. s.shrinkStack startSize |>.pushSyntax Syntax.missing else -- parser succeded with incorrect number of nodes invalidLongestMatchParser s def longestMatchStep (left? : Option Syntax) (startSize startLhsPrec : 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 prevLhsPrec := s.lhsPrec let s := s.restore prevSize startPos let s := runLongestMatchParser left? startLhsPrec 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 with lhsPrec := prevLhsPrec }, prevPrio) -- keep prev -- it is not clear what the precedence of a choice node should be, so we conservatively take the minimum else ({s with lhsPrec := s.lhsPrec.min prevLhsPrec }, prio) | none, some _ => -- prev succeeded, current failed ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) | some oldError, some _ => -- both failed if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError startSize, 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 startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn := let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) := match ps with | [] => fun _ s => longestMatchMkResult startSize s | p::ps => fun c s => let (s, prevPrio) := longestMatchStep left? startSize startLhsPrec startPos prevPrio p.2 p.1.fn c s parse prevPrio ps c s parse prevPrio ps def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn | [] => fun _ s => s.mkError "longestMatch: empty list" | [p] => fun c s => runLongestMatchParser left? s.lhsPrec p.1.fn c s | p::ps => fun c s => let startSize := s.stackSize let startLhsPrec := s.lhsPrec let startPos := s.pos let s := runLongestMatchParser left? s.lhsPrec p.1.fn c s longestMatchFnAux left? startSize startLhsPrec 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 savedPos := c.fileMap.toPosition 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 savedPos := c.fileMap.toPosition 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 checkLineEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.line == savedPos.line then s else s.mkError errorMsg @[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser := { fn := checkLineEqFn errorMsg } @[inline] def withPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with savedPos? := s.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 } @[inline] def withForbidden (tk : Token) (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := tk } s } @[inline] def withoutForbidden (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := 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 } 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 (map : TokenMap α) (k : Name) (v : α) : TokenMap α := match map.find? k with | none => Std.RBMap.insert map k [v] | some vs => Std.RBMap.insert map k (v::vs) instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩ instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩ end TokenMap structure PrattParsingTables where 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 : Inhabited PrattParsingTables := ⟨{}⟩ /- The type `leadingIdentBehavior` specifies how the parsing table lookup function behaves for identifiers. The function `prattParser` uses two tables `leadingTable` and `trailingTable`. They map tokens to parsers. - `LeadingIdentBehavior.default`: if the leading token is an identifier, then `prattParser` just executes the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.symbol`: if the leading token is an identifier `<foo>`, and there are parsers `P` associated with the toek `<foo>`, then it executes `P`. Otherwise, it executes only the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.both`: if the leading token an identifier `<foo>`, the it executes the parsers associated with token `<foo>` and parsers associated with the auxiliary token "ident". We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both` and `nonReservedSymbol` parser to implement the `tactic` parsers. The idea is 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). -/ inductive LeadingIdentBehavior where | default | symbol | both deriving Inhabited, BEq /-- 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 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 where tables : PrattParsingTables behavior : LeadingIdentBehavior deriving Inhabited abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : 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 | Except.ok (Syntax.atom _ sym) => find (Name.mkSimple sym) | Except.ok (Syntax.ident _ _ val _) => match behavior with | LeadingIdentBehavior.default => find identKind | LeadingIdentBehavior.symbol => match map.find? val with | some as => (s, as) | none => find identKind | LeadingIdentBehavior.both => match map.find? val with | some as => match map.find? identKind with | some as' => (s, as ++ as') | _ => (s, as) | none => find identKind | Except.ok (Syntax.node k _) => find k | Except.ok _ => (s, []) | Except.error s' => (s', []) abbrev CategoryParserFn := Name → ParserFn builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun _ => whitespace builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get 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 -/ /- ============== -/ /-- 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 (symbolNoAntiquot "(" >> toggleInsideQuot termParser >> symbolNoAntiquot ")") def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr @[inline] def tokenWithAntiquotFn (p : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError then return s let iniSz := s.stackSize let iniPos := s.pos let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s if s.hasError then return s.restore iniSz iniPos s.mkNode (`token_antiquot) (iniSz - 1) @[inline] def tokenWithAntiquot (p : Parser) : Parser where fn := tokenWithAntiquotFn p.fn info := p.info @[inline] def symbol (sym : String) : Parser := tokenWithAntiquot (symbolNoAntiquot sym) instance : Coe String Parser := ⟨fun s => symbol s ⟩ @[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser := tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent) @[inline] def unicodeSymbol (sym asciiSym : String) : Parser := tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym) /-- 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 leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> antiquotExpr >> nameP def tryAnti (c : ParserContext) (s : ParserState) : Bool := let (s, stx) := peekToken c s match stx with | Except.ok 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 } def withoutInfo (p : Parser) : Parser := { fn := p.fn } /-- Parse `$[p]suffix`, e.g. `$[p],*`. -/ def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := let kind := kind ++ `antiquot_scope leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >> suffix @[inline] def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (p suffix : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || !s.stxStack.back.isAntiquot then return s let iniSz := s.stackSize let iniPos := s.pos let s := suffix c s if s.hasError then return s.restore iniSz iniPos s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2) /-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/ @[inline] def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := { info := andthenInfo p.info suffix.info, fn := withAntiquotSuffixSpliceFn kind p.fn suffix.fn } def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) := -- prevent `p`'s info from being collected twice withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix) def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser := withAntiquot (mkAntiquot name kind anonymous) $ node kind p /- ===================== -/ /- End of Antiquotations -/ /- ===================== -/ def sepByElemParser (p : Parser) (sep : String) : Parser := withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*")) def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep 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 } unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => match ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.Parser declName <|> ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.TrailingParser declName with | Except.ok p => p.fn ctx s | Except.error e => s.mkUnexpectedError s!"error running parser {declName}: {e}" @[implementedBy evalParserConstUnsafe] constant evalParserConst (declName : Name) : ParserFn unsafe def parserOfStackFnUnsafe (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident (val := parserName) .. => match ctx.resolveName parserName with | [(parserName, [])] => let iniSz := s.stackSize let s := evalParserConst parserName ctx s if !s.hasError && s.stackSize != iniSz + 1 then s.mkUnexpectedError "expected parser to return exactly one syntax object" else s | _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}" | _ => s.mkUnexpectedError s!"unknown parser {parserName}" | _ => s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier") @[implementedBy parserOfStackFnUnsafe] constant parserOfStackFn (offset : Nat) : ParserFn def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => parserOfStackFn offset { c with prec := prec } s } /-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/ def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with fn := fun c s => if c.insideQuot && c.env.contains declName then evalParserConst declName c s else p.fn c 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) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => do let iniSz := s.stackSize let (s, ps) := indexed tables.leadingTable c s behavior if s.hasError then return s let ps := tables.leadingParsers ++ ps if ps.isEmpty then return s.mkError (toString kind) let s := longestMatchFn none ps c s mkResult s iniSz @[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := withAntiquotFn antiquotParser (leadingParserAux kind tables behavior) def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := do let iniSz := s.stackSize let iniPos := s.pos let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default if s.hasError then -- Discard token parse errors and break the trailing loop instead. -- The error will be flagged when the next leading position is parsed, unless the token -- is in fact valid there (e.g. EOI at command level, no-longer forbidden token) return s.restore iniSz iniPos if ps.isEmpty && tables.trailingParsers.isEmpty then return s -- no available trailing parser let left := s.stxStack.back let s := s.popSyntax let s := trailingLoopStep tables left ps c s if s.hasError then -- Discard non-consuming parse errors and break the trailing loop instead, restoring `left`. -- This is necessary for fallback parsers like `app` that pretend to be always applicable. return if s.pos == iniPos then s.restore (iniSz - 1) iniPos |>.pushSyntax left else s trailingLoop tables c 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) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := leadingParser kind tables behavior antiquotParser c s if s.hasError then s else trailingLoop tables c s def fieldIdxFn : ParserFn := fun c s => let initStackSz := s.stackSize 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 initStackSz @[inline] def fieldIdx : Parser := withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) { fn := fieldIdxFn, info := mkAtomicInfo "fieldIdx" } @[inline] def skip : Parser := { fn := fun c s => s, info := epsilonInfo } end Parser namespace Syntax section variable {β : 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) () end end Syntax end Lean
52c25b8051b6b7881d8d2f5e46d5bcce1c37b6bb
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/sheaves/functors.lean
0ca023927481e8a8202ee581677d073f72eadc8e
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,429
lean
/- Copyright (c) 2021 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import topology.sheaves.sheaf_condition.pairwise_intersections /-! # functors between categories of sheaves Show that the pushforward of a sheaf is a sheaf, and define the pushforward functor from the category of C-valued sheaves on X to that of sheaves on Y, given a continuous map between topological spaces X and Y. TODO: pullback for presheaves and sheaves -/ noncomputable theory universes v u u₁ open category_theory open category_theory.limits open topological_space variables {C : Type u₁} [category.{v} C] variables {X Y : Top.{v}} (f : X ⟶ Y) variables ⦃ι : Type v⦄ {U : ι → opens Y} namespace Top namespace presheaf.sheaf_condition_pairwise_intersections lemma map_diagram : pairwise.diagram U ⋙ opens.map f = pairwise.diagram ((opens.map f).obj ∘ U) := begin apply functor.hext, abstract obj_eq {intro i, cases i; refl}, intros i j g, apply subsingleton.helim, iterate 2 {rw map_diagram.obj_eq}, end lemma map_cocone : (opens.map f).map_cocone (pairwise.cocone U) == pairwise.cocone ((opens.map f).obj ∘ U) := begin unfold functor.map_cocone cocones.functoriality, dsimp, congr, iterate 2 {rw map_diagram, rw opens.map_supr}, apply subsingleton.helim, rw [map_diagram, opens.map_supr], apply proof_irrel_heq, end theorem pushforward_sheaf_of_sheaf {F : presheaf C X} (h : F.is_sheaf_pairwise_intersections) : (f _* F).is_sheaf_pairwise_intersections := λ ι U, begin convert h ((opens.map f).obj ∘ U) using 2, rw ← map_diagram, refl, change F.map_cone ((opens.map f).map_cocone _).op == _, congr, iterate 2 {rw map_diagram}, apply map_cocone, end end presheaf.sheaf_condition_pairwise_intersections namespace sheaf open presheaf variables [has_products C] /-- The pushforward of a sheaf (by a continuous map) is a sheaf. -/ theorem pushforward_sheaf_of_sheaf {F : presheaf C X} (h : F.is_sheaf) : (f _* F).is_sheaf := by rw is_sheaf_iff_is_sheaf_pairwise_intersections at h ⊢; exact sheaf_condition_pairwise_intersections.pushforward_sheaf_of_sheaf f h /-- The pushforward functor. -/ def pushforward (f : X ⟶ Y) : X.sheaf C ⥤ Y.sheaf C := { obj := λ ℱ, ⟨f _* ℱ.1, pushforward_sheaf_of_sheaf f ℱ.2⟩, map := λ _ _, pushforward_map f } end sheaf end Top
4864d6a9b888a83c584db39d694377e797abbdaf
a51edd9a1700339fa6dc7dc428eb5dfa3994b8bc
/src/misc/vm_check.lean
de144ea4f7d51b41ffb21a34a15636331273a515
[]
no_license
avigad/formal_logic
83f5c0534b3e9e7da53eff01bb82289daad65555
59d7fe7cb7a7927fb72d89d4fd40965bcd769349
refs/heads/master
1,585,302,642,116
1,541,000,469,000
1,541,000,469,000
146,376,915
1
1
null
null
null
null
UTF-8
Lean
false
false
907
lean
axiom vm_checked {P : Prop} : P open tactic /-- Uses the vm to cerify a goal of the form t = tt, where t is a closed boolean term -/ meta def vm_check_tt : tactic unit := do tgt ← target, match tgt with | `(%%t = tt) := do et ← eval_expr bool t, match et with | tt := applyc ``vm_checked | ff := fail "goal is false" end | _ := fail "goal must be of the form t = tt" end def of_to_bool_eq_tt {P : Prop} [h₁ : decidable P] (h₂ : to_bool P = tt) : P := match h₁, h₂ with | (decidable.is_true h_P), h₂ := h_P | (decidable.is_false h_nP), h₂ := by contradiction end /- meta def vm_check : tactic unit := do tgt ← target, apply `(@of_to_bool_eq_tt %%tgt) <|> fail "could not infer decidability", vm_check_tt -/ -- in analogy to dec_trivial notation `vm_check` := of_to_bool_eq_tt (by vm_check_tt)
c971421d2b2b8b6e2d3bd8e53f8b5da0905b6f66
026eca3e4f104406f03192524c0ebed8b40e468b
/library/init/data/nat/lemmas.lean
fef406cde1b067e4c7d2861efd016404383c7977
[ "Apache-2.0" ]
permissive
jpablo/lean
99bebe8f1c3e3df37e19fc4af27d4261efa40bc6
bec8f0688552bc64f9c08fe0459f3fb20f93cb33
refs/heads/master
1,679,677,848,004
1,615,913,211,000
1,615,913,211,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
47,278
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad -/ prelude import init.data.nat.basic init.data.nat.div init.meta init.algebra.functions universes u namespace nat attribute [pre_smt] nat_zero_eq_zero protected lemma add_comm : ∀ n m : ℕ, n + m = m + n | n 0 := eq.symm (nat.zero_add n) | n (m+1) := suffices succ (n + m) = succ (m + n), from eq.symm (succ_add m n) ▸ this, congr_arg succ (add_comm n m) protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k) | n m 0 := rfl | n m (succ k) := by rw [add_succ, add_succ, add_assoc] protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) := left_comm nat.add nat.add_comm nat.add_assoc protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k | 0 m k := by simp [nat.zero_add] {contextual := tt} | (succ n) m k := λ h, have n+m = n+k, by { simp [succ_add] at h, assumption }, add_left_cancel this protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k := have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h, nat.add_left_cancel this lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 := assume h, nat.no_confusion h lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n | 0 h := absurd h (nat.succ_ne_zero 0) | (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h)) protected lemma one_ne_zero : 1 ≠ (0 : ℕ) := assume h, nat.no_confusion h protected lemma zero_ne_one : 0 ≠ (1 : ℕ) := assume h, nat.no_confusion h lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0 | 0 m := by simp [nat.zero_add] | (n+1) m := λ h, begin exfalso, rw [add_one, succ_add] at h, apply succ_ne_zero _ h end lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 := @eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h) @[simp] lemma pred_zero : pred 0 = 0 := rfl @[simp] lemma pred_succ (n : ℕ) : pred (succ n) = n := rfl protected lemma mul_zero (n : ℕ) : n * 0 = 0 := rfl lemma mul_succ (n m : ℕ) : n * succ m = n * m + n := rfl protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0 | 0 := rfl | (succ n) := by rw [mul_succ, zero_mul] private meta def sort_add := `[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]] lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m | n 0 := rfl | n (succ m) := begin simp [mul_succ, add_succ, succ_mul n m], sort_add end protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k | n m 0 := rfl | n m (succ k) := begin simp [mul_succ, right_distrib n m k], sort_add end protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k | 0 m k := by simp [nat.zero_mul] | (succ n) m k := begin simp [succ_mul, left_distrib n m k], sort_add end protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n | n 0 := by rw [nat.zero_mul, nat.mul_zero] | n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m] protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k) | n m 0 := rfl | n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k] protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add protected lemma one_mul (n : ℕ) : 1 * n = n := by rw [nat.mul_comm, nat.mul_one] /- properties of inequality -/ protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ less_than_or_equal.refl lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m := nat.le_trans h (le_succ m) lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m := nat.le_trans (le_succ n) h protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m := le_of_succ_le h lemma lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ 0 < n := by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)} protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → 0 < n := or.resolve_left (eq_zero_or_pos n) protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k := nat.le_trans (less_than_or_equal.step h₁) protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ h₁) lemma lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n) lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m := less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n)) protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ b ≤ a | a 0 := or.inr (zero_le a) | a (b+1) := match lt_or_ge a b with | or.inl h := or.inl (le_succ_of_le h) | or.inr h := match nat.eq_or_lt_of_le h with | or.inl h1 := or.inl (h1 ▸ lt_succ_self b) | or.inr h1 := or.inr h1 end end protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m := or.imp_left nat.le_of_lt (nat.lt_or_ge m n) protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n := or.resolve_right (or.swap (nat.eq_or_lt_of_le h1)) protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) := ⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩, λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩ instance : linear_order ℕ := { le := nat.less_than_or_equal, le_refl := @nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, lt := nat.lt, lt_iff_le_not_le := @nat.lt_iff_le_not_le, decidable_lt := nat.decidable_lt, decidable_le := nat.decidable_le, decidable_eq := nat.decidable_eq } lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 := le_antisymm h (zero_le _) lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m | 0 _ h₁ h := absurd rfl h₁ | _ 0 h₁ h := absurd h (not_lt_zero _) | (succ n) (succ m) _ h := lt_of_succ_lt_succ h lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k | n 0 := nat.le_refl n | n (k+1) := le_succ_of_le (le_add_right n k) lemma le_add_left (n m : ℕ): n ≤ m + n := nat.add_comm n m ▸ le_add_right n m lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m | n _ less_than_or_equal.refl := ⟨0, rfl⟩ | n _ (less_than_or_equal.step h) := match le.dest h with | ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩ end lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := h ▸ le_add_right n k protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end end protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k := begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc] at hw, apply nat.add_left_cancel hw end end protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m := begin rw [nat.add_comm _ k, nat.add_comm _ k], apply nat.le_of_add_le_add_left end protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m := ⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩ protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m := let h' := nat.le_of_lt h in nat.lt_of_le_and_ne (nat.le_of_add_le_add_left h') (λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end) protected lemma lt_of_add_lt_add_right {a b c : ℕ} (h : a + b < c + b) : a < c := nat.lt_of_add_lt_add_left $ show b + a < b + c, by rwa [nat.add_comm b a, nat.add_comm b c] protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m := lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k) protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k := nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k protected lemma lt_add_of_pos_right {n k : ℕ} (h : 0 < k) : n < n + k := nat.add_lt_add_left h n protected lemma lt_add_of_pos_left {n k : ℕ} (h : 0 < k) : n < k + n := by rw nat.add_comm; exact nat.lt_add_of_pos_right h protected lemma add_lt_add {a b c d : ℕ} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (nat.add_lt_add_right h₁ c) (nat.add_lt_add_left h₂ b) protected lemma add_le_add {a b c d : ℕ} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (nat.add_le_add_right h₁ c) (nat.add_le_add_left h₂ b) protected lemma zero_lt_one : 0 < (1:nat) := zero_lt_succ 0 lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ := have k * n + k * l = k * m, by rw [← nat.left_distrib, hl], le.intro this end lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k := nat.mul_comm k m ▸ nat.mul_comm k n ▸ mul_le_mul_left k h protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : 0 < k) : k * n < k * m := nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h)) protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : 0 < k) : n * k < m * k := nat.mul_comm k m ▸ nat.mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk protected lemma le_of_mul_le_mul_left {a b c : ℕ} (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := decidable.not_lt.1 (assume h1 : b < a, have h2 : c * b < c * a, from nat.mul_lt_mul_of_pos_left h1 hc, not_le_of_gt h2 h) lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n := le_of_succ_le_succ theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : 0 < n) (H : n * m = n * k) : m = k := le_antisymm (nat.le_of_mul_le_mul_left (le_of_eq H) Hn) (nat.le_of_mul_le_mul_left (le_of_eq H.symm) Hn) /- sub properties -/ @[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0 | 0 := rfl | (a+1) := congr_arg pred (zero_sub a) lemma sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le (sub_le a b) protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k | 0 := h | (succ z) := pred_le_pred (sub_le_sub_right z) /- bit0/bit1 properties -/ protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) := rfl protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) := eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n)) protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1 | 0 h h1 := absurd rfl h | (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _)) protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1 | 0 h := absurd h (ne.symm nat.one_ne_zero) | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero (n + n))) protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1 | 0 h := nat.no_confusion h | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n))) protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m | 0 m h := absurd h (ne.symm (nat.add_self_ne_one m)) | (n+1) 0 h := have h1 : succ (bit0 (succ n)) = 0, from h, absurd h1 (nat.succ_ne_zero _) | (n+1) (m+1) h := have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h, have h2 : bit1 n = bit0 m, from nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')), absurd h2 (bit1_ne_bit0 n m) protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m := λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n) protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m | 0 0 h := rfl | 0 (m+1) h := by contradiction | (n+1) 0 h := by contradiction | (n+1) (m+1) h := have succ (succ (n + n)) = succ (succ (m + m)), by { unfold bit0 at h, simp [add_one, add_succ, succ_add] at h, have aux : n + n = m + m := h, rw aux }, have n + n = m + m, by iterate { injection this with this }, have n = m, from bit0_inj this, by rw this protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m := λ n m h, have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, rw h end, have bit0 n = bit0 m, by injection this, nat.bit0_inj this protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m := λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁ protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m := λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁ protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n := λ h, ne.symm (nat.bit0_ne_zero h) protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n := ne.symm (nat.bit1_ne_zero n) protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n := ne.symm (nat.bit0_ne_one n) protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n := λ h, ne.symm (nat.bit1_ne_one h) protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit1_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit0_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m := nat.add_lt_add h h protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m := succ_lt_succ (nat.add_lt_add h h) protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m := lt_succ_of_le (nat.add_le_add h h) protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m | n 0 h := absurd h (not_lt_zero _) | n (succ m) h := have n ≤ m, from le_of_lt_succ h, have succ (n + n) ≤ succ (m + m), from succ_le_succ (nat.add_le_add this this), have succ (n + n) ≤ succ m + m, {rw succ_add, assumption}, show succ (n + n) < succ (succ m + m), from lt_succ_of_le this protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n := show 1 ≤ succ (bit0 n), from succ_le_succ (zero_le (bit0 n)) protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n | 0 h := absurd rfl h | (n+1) h := suffices 1 ≤ succ (succ (bit0 n)), from eq.symm (nat.bit0_succ_eq n) ▸ this, succ_le_succ (zero_le (succ (bit0 n))) /- subtraction -/ @[simp] protected theorem sub_zero (n : ℕ) : n - 0 = n := rfl theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : ℕ), n - n = 0 | 0 := by rw nat.sub_zero | (succ n) := by rw [succ_sub_succ, sub_self n] /- TODO(Leo): remove the following ematch annotations as soon as we have arithmetic theory in the smt_stactic -/ @[ematch_lhs] protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m | n 0 m := by rw [nat.add_zero, nat.add_zero] | n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m] @[ematch_lhs] protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := by rw [nat.add_comm k n, nat.add_comm k m, nat.add_sub_add_right] @[ematch_lhs] protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n := suffices n + m - (0 + m) = n, from by rwa [nat.zero_add] at this, by rw [nat.add_sub_add_right, nat.sub_zero] @[ematch_lhs] protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m := show n + m - (n + 0) = m, from by rw [nat.add_sub_add_left, nat.sub_zero] protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k) | n m 0 := by rw [nat.add_zero, nat.sub_zero] | n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k] theorem le_of_le_of_sub_le_sub_right {n m k : ℕ} (h₀ : k ≤ m) (h₁ : n - k ≤ m - k) : n ≤ m := begin revert k m, induction n with n ; intros k m h₀ h₁, { apply zero_le }, { cases k with k, { apply h₁ }, cases m with m, { cases not_succ_le_zero _ h₀ }, { simp [succ_sub_succ] at h₁, apply succ_le_succ, apply n_ih _ h₁, apply le_of_succ_le_succ h₀ }, } end protected theorem sub_le_sub_right_iff (n m k : ℕ) (h : k ≤ m) : n - k ≤ m - k ↔ n ≤ m := ⟨ le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩ theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 := show (n + 0) - (n + m) = 0, from by rw [nat.add_sub_add_left, nat.zero_sub] theorem add_le_to_le_sub (x : ℕ) {y k : ℕ} (h : k ≤ y) : x + k ≤ y ↔ x ≤ y - k := by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel] lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b) : b - a < b := begin apply sub_lt _ h₀, apply lt_of_lt_of_le h₀ h₁ end theorem sub_one (n : ℕ) : n - 1 = pred n := rfl theorem succ_sub_one (n : ℕ) : succ n - 1 = n := rfl theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, 0 < n → succ (pred n) = n | 0 h := absurd h (lt_irrefl 0) | (succ k) h := rfl theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, sub_self_add]) protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m | n 0 H := begin rw [nat.sub_zero] at H, simp [H] end | 0 (m+1) H := zero_le _ | (n+1) (m+1) H := nat.add_le_add_right (le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _ protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m := ⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩ theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left]) protected theorem sub_add_cancel {n m : ℕ} (h : m ≤ n) : n - m + m = n := by rw [nat.add_comm, add_sub_of_le h] protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := exists.elim (nat.le.dest h) (assume l, assume hl : k + l = m, by rw [← hl, nat.add_sub_cancel_left, nat.add_comm k, ← nat.add_assoc, nat.add_sub_cancel]) protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b := ⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end, assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩ protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m := not_le.1 (assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end) lemma zero_min (a : ℕ) : min 0 a = 0 := min_eq_left (zero_le a) lemma min_zero (a : ℕ) : min a 0 = 0 := min_eq_right (zero_le a) -- Distribute succ over min theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) := have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ x : if_pos (succ_le_succ p) ... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)), have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ y : if_neg (λeq, p (pred_le_pred eq)) ... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)), decidable.by_cases f g theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m := if h : n ≥ m then by rewrite [min_eq_right h] else by rewrite [sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self] @[simp] theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n := by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)] /- TODO(Leo): sub + inequalities -/ protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _), begin intros n, induction n with n ih, {intros m h₁, exact absurd h₁ (not_lt_zero _)}, {intros m h₁, apply or.by_cases (decidable.lt_or_eq_of_le (le_of_lt_succ h₁)), {intros, apply ih, assumption}, {intros, subst m, apply h _ ih}} end protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := nat.strong_rec_on n h protected lemma case_strong_induction_on {p : nat → Prop} (a : nat) (hz : p 0) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a := nat.strong_induction_on a $ λ n, match n with | 0 := λ _, hz | (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂)) end /- mod -/ lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := by have h := mod_def_aux x y; rwa [dif_eq_if] at h @[simp] lemma mod_zero (a : nat) : a % 0 = a := begin rw mod_def, have h : ¬ (0 < 0 ∧ 0 ≤ a), simp [lt_irrefl], simp [if_neg, h] end lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a := begin rw mod_def, have h' : ¬(0 < b ∧ b ≤ a), simp [not_le_of_gt h], simp [if_neg, h'] end @[simp] lemma zero_mod (b : nat) : 0 % b = 0 := begin rw mod_def, have h : ¬(0 < b ∧ b ≤ 0), {intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)}, simp [if_neg, h] end lemma mod_eq_sub_mod {a b : nat} (h : b ≤ a) : a % b = (a - b) % b := or.elim (eq_zero_or_pos b) (λb0, by rw [b0, nat.sub_zero]) (λh₂, by rw [mod_def, if_pos (and.intro h₂ h)]) lemma mod_lt (x : nat) {y : nat} (h : 0 < y) : x % y < y := begin induction x using nat.case_strong_induction_on with x ih, { rw zero_mod, assumption }, { by_cases h₁ : succ x < y, { rwa [mod_eq_of_lt h₁] }, { have h₁ : succ x % y = (succ x - y) % y := mod_eq_sub_mod (decidable.not_lt.1 h₁), have : succ x - y ≤ x := le_of_lt_succ (sub_lt (succ_pos x) h), have h₂ : (succ x - y) % y < y := ih _ this, rwa [← h₁] at h₂ } } end @[simp] theorem mod_self (n : nat) : n % n = 0 := by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod] @[simp] lemma mod_one (n : ℕ) : n % 1 = 0 := have n % 1 < 1, from (mod_lt n) (succ_pos 0), eq_zero_of_le_zero (le_of_lt_succ this) lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 := match n % 2, @nat.mod_lt n 2 dec_trivial with | 0, _ := or.inl rfl | 1, _ := or.inr rfl | k+2, h := absurd h dec_trivial end /- div & mod -/ lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := by have h := div_def_aux x y; rwa dif_eq_if at h lemma mod_add_div (m k : ℕ) : m % k + k * (m / k) = m := begin apply nat.strong_induction_on m, clear m, intros m IH, cases decidable.em (0 < k ∧ k ≤ m) with h h', -- 0 < k ∧ k ≤ m { have h' : m - k < m, { apply nat.sub_lt _ h.left, apply lt_of_lt_of_le h.left h.right }, rw [div_def, mod_def, if_pos h, if_pos h], simp [nat.left_distrib, IH _ h', nat.add_comm, nat.add_left_comm], rw [nat.add_comm, ← nat.add_sub_assoc h.right, nat.mul_one, nat.add_sub_cancel_left] }, -- ¬ (0 < k ∧ k ≤ m) { rw [div_def, mod_def, if_neg h', if_neg h', nat.mul_zero, nat.add_zero] }, end /- div -/ @[simp] protected lemma div_one (n : ℕ) : n / 1 = n := have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _, by { rwa [mod_one, nat.zero_add, nat.one_mul] at this } @[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 := begin rw [div_def], simp [lt_irrefl] end @[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 := eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt) protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n | 0 h := by simp [nat.div_zero]; apply zero_le | (succ k) h := suffices succ k * (m / succ k) ≤ succ k * n, from nat.le_of_mul_le_mul_left this (zero_lt_succ _), calc succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : le_add_left _ _ ... = m : by rw mod_add_div ... ≤ succ k * n : h protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m | m 0 := by simp [nat.div_zero]; apply zero_le | m (succ n) := have m ≤ succ n * m, from calc m = 1 * m : by rw nat.one_mul ... ≤ succ n * m : mul_le_mul_right _ (succ_le_succ (zero_le _)), nat.div_le_of_le_mul this lemma div_eq_sub_div {a b : nat} (h₁ : 0 < b) (h₂ : b ≤ a) : a / b = (a - b) / b + 1 := begin rw [div_def a, if_pos], split ; assumption end lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 := begin rw [div_def a, if_neg], intro h₁, apply not_le_of_gt h₀ h₁.right end -- this is a Galois connection -- f x ≤ y ↔ x ≤ g y -- with -- f x = x * k -- g y = y / k theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ} (Hk : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin -- Hk is needed because, despite div being made total, y / 0 := 0 -- x * 0 ≤ y ↔ x ≤ y / 0 -- ↔ 0 ≤ y ↔ x ≤ 0 -- ↔ true ↔ x = 0 -- ↔ x = 0 revert x, apply nat.strong_induction_on y _, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, -- base case: y < k { rw [div_eq_of_lt h], cases x with x, { simp [nat.zero_mul, zero_le] }, { simp [succ_mul, not_succ_le_zero, nat.add_comm], apply lt_of_lt_of_le h, apply le_add_right } }, -- step: k ≤ y { rw [div_eq_sub_div Hk h], cases x with x, { simp [nat.zero_mul, zero_le] }, { have Hlt : y - k < y, { apply sub_lt_of_pos_le ; assumption }, rw [ ← add_one , nat.add_le_add_iff_le_right , IH (y - k) Hlt x , add_one , succ_mul, add_le_to_le_sub _ h ] } } end theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ} (Hk : 0 < k) : x / k < y ↔ x < y * k := begin simp [← not_le], apply not_iff_not_of_iff, apply le_div_iff_mul_le _ _ Hk end def iterate {α : Sort u} (op : α → α) : ℕ → α → α | 0 a := a | (succ k) a := iterate k (op a) notation f`^[`n`]` := iterate f n /- successor and predecessor -/ theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _ theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) := by cases n; simp theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k := ⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩ def discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B := by induction h : n; [exact H1 h, exact H2 _ h] theorem one_succ_zero : 1 = succ 0 := rfl def two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a | 0 := H1 | 1 := H2 | (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _) def sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m | 0 m := H1 _ | (succ n) 0 := H2 _ | (succ n) (succ m) := H3 _ _ (sub_induction n m) /- addition -/ theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := by simp [succ_add, add_succ] -- theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m := right_comm nat.add nat.add_comm nat.add_assoc theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 := ⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩ theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0 | 0 m := λ h, or.inl rfl | (succ n) m := begin rw succ_mul, intro h, exact or.inr (eq_zero_of_add_eq_zero_left h) end /- properties of inequality -/ theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ) theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false := nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂) theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false := le_lt_antisymm h₂ h₁ protected theorem lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt h₁) protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : b ≤ a → C) : C := decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a))) protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C) (h₃ : b < a → C) : C := nat.lt_ge_by_cases h₁ (λ h₁, nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a := nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h)) protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a := (nat.lt_trichotomy a b).resolve_left hnlt theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h lemma one_pos : 0 < 1 := nat.zero_lt_one /- subtraction -/ protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n := by induction h; [refl, exact le_trans (pred_le _) h_ih] theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k := by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ] protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n := by rw [nat.sub_sub, nat.sub_sub, nat.add_comm] theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m | 0 m := by simp [nat.zero_sub, pred_zero, nat.zero_mul] | (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel] theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := by rw [nat.mul_comm, mul_pred_left, nat.mul_comm] protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k | n 0 k := by simp [nat.sub_zero, nat.zero_mul] | n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub] protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k := by rw [nat.mul_comm, nat.mul_sub_right_distrib, nat.mul_comm m n, nat.mul_comm n k] protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) := by rw [nat.mul_sub_left_distrib, nat.right_distrib, nat.right_distrib, nat.mul_comm b a, nat.add_comm (a*a) (a*b), nat.add_sub_add_left] theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a*b + a + b + 1 := begin rw [← add_one, ← add_one], simp [nat.right_distrib, nat.left_distrib, nat.add_left_comm, nat.mul_one, nat.one_mul, nat.add_assoc], end theorem succ_sub {m n : ℕ} (h : n ≤ m) : succ m - n = succ (m - n) := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left]) protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : 0 < n - m := have 0 + m < n - m + m, begin rw [nat.zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end, nat.lt_of_add_lt_add_right this protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m := (nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (eq.symm (add_sub_of_le h)) protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m := (nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2 (by rwa [nat.add_right_comm, nat.sub_add_cancel]) theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin rw nat.sub_sub, apply nat.sub_lt, apply lt_of_lt_of_le (nat.zero_lt_succ _) h, rw nat.add_comm, apply nat.zero_lt_succ end theorem pred_inj : ∀ {a b : nat}, 0 < a → 0 < b → nat.pred a = nat.pred b → a = b | (succ a) (succ b) ha hb h := have a = b, from h, by rw this | (succ a) 0 ha hb h := absurd hb (lt_irrefl _) | 0 (succ b) ha hb h := absurd ha (lt_irrefl _) | 0 0 ha hb h := rfl /- find -/ section find parameter {p : ℕ → Prop} private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k parameters [decidable_pred p] (H : ∃n, p n) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _), λm, nat.rec_on m (λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩) (λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩ protected def find_x : {n // p n ∧ ∀m < n, ¬p m} := @well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp (λm IH al, if pm : p m then ⟨m, pm, al⟩ else have ∀ n ≤ m, ¬p n, from λn h, or.elim (decidable.lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm), IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h)) 0 (λn h, absurd h (nat.not_lt_zero _)) protected def find : ℕ := nat.find_x.1 protected theorem find_spec : p nat.find := nat.find_x.2.left protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m := decidable.le_of_not_lt (λ l, find_min l h) end find /- mod -/ theorem mod_le (x y : ℕ) : x % y ≤ x := or.elim (decidable.lt_or_le x y) (λxlty, by rw mod_eq_of_lt xlty; refl) (λylex, or.elim (eq_zero_or_pos y) (λy0, by rw [y0, mod_zero]; refl) (λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex)) @[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z := by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x := by rw [nat.add_comm, add_mod_right] @[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := by {induction z with z ih, rw [nat.mul_zero, nat.add_zero], rw [mul_succ, ← nat.add_assoc, add_mod_right, ih]} @[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z := by rw [nat.mul_comm, add_mul_mod_self_left] @[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 := by rw [← nat.zero_add (m*n), add_mul_mod_self_left, zero_mod] @[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 := by rw [nat.mul_comm, mul_mod_right] theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) := if y0 : y = 0 then by rw [y0, nat.mul_zero, mod_zero, mod_zero] else if z0 : z = 0 then by rw [z0, nat.zero_mul, nat.zero_mul, nat.zero_mul, mod_zero] else x.strong_induction_on $ λn IH, have y0 : y > 0, from nat.pos_of_ne_zero y0, have z0 : z > 0, from nat.pos_of_ne_zero z0, or.elim (decidable.le_or_lt y n) (λyn, by rw [ mod_eq_sub_mod yn, mod_eq_sub_mod (mul_le_mul_left z yn), ← nat.mul_sub_left_distrib]; exact IH _ (sub_lt (lt_of_lt_of_le y0 yn) y0)) (λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (nat.mul_lt_mul_of_pos_left yn z0)]) theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z := by rw [nat.mul_comm x z, nat.mul_comm y z, nat.mul_comm (x % y) z]; apply mul_mod_mul_left theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)] : cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 := begin by_cases h : x % 2 = 1, { simp! [*] }, { cases mod_two_eq_zero_or_one x; simp! [*, nat.zero_ne_one] } end theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n := begin induction k with k, { rw [nat.mul_zero, nat.sub_zero] }, { have h₂ : n * k ≤ x, { rw [mul_succ] at h₁, apply nat.le_trans _ h₁, apply le_add_right _ n }, have h₄ : x - n * k ≥ n, { apply @nat.le_of_add_le_add_right (n*k), rw [nat.sub_add_cancel h₂], simp [mul_succ, nat.add_comm] at h₁, simp [h₁] }, rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, k_ih h₂] } end /- div -/ theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p := begin cases eq_zero_or_pos n with h₀ h₀, { rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] }, { induction p with p, { rw [nat.mul_zero, nat.sub_zero, nat.sub_zero] }, { have h₂ : n*p ≤ x, { transitivity, { apply nat.mul_le_mul_left, apply le_succ }, { apply h₁ } }, have h₃ : x - n * p ≥ n, { apply nat.le_of_add_le_add_right, rw [nat.sub_add_cancel h₂, nat.add_comm], rw [mul_succ] at h₁, apply h₁ }, rw [sub_succ, ← p_ih h₂], rw [@div_eq_sub_div (x - n*p) _ h₀ h₃], simp [add_one, pred_succ, mul_succ, nat.sub_sub] } } end theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m | m 0 := by simp; apply zero_le | m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _) @[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : 0 < z) : (x + z) / z = succ (x / z) := by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : 0 < z) : (z + x) / z = succ (x / z) := by rw [nat.add_comm, add_div_right x H] @[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : 0 < m) : m * n / m = n := by {induction n; simp [*, mul_succ, nat.mul_zero] } @[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m := by rw [nat.mul_comm, mul_div_right _ H] protected theorem div_self {n : ℕ} (H : 0 < n) : n / n = 1 := let t := add_div_right 0 H in by rwa [nat.zero_add, nat.zero_div] at t theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : 0 < y) : (x + y * z) / y = x / y + z := begin induction z with z ih, { rw [nat.mul_zero, nat.add_zero, nat.add_zero] }, { rw [mul_succ, ← nat.add_assoc, add_div_right _ H, ih] } end theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : 0 < z) : (x + y * z) / z = x / z + y := by rw [nat.mul_comm, add_mul_div_left _ _ H] protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m := let t := add_mul_div_right 0 m H in by rwa [nat.zero_add, nat.zero_div, nat.zero_add] at t protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : 0 < n) : n * m / n = m := by rw [nat.mul_comm, nat.mul_div_cancel _ H] protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : 0 < n) (H2 : m = k * n) : m / n = k := by rw [H2, nat.mul_div_cancel _ H1] protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : 0 < n) (H2 : m = n * k) : m / n = k := by rw [H2, nat.mul_div_cancel_left _ H1] protected theorem div_eq_of_lt_le {m n k : ℕ} (lo : k * n ≤ m) (hi : m < succ k * n) : m / n = k := have npos : 0 < n, from (eq_zero_or_pos _).resolve_left $ λ hn, by rw [hn, nat.mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi), le_antisymm (le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi)) ((nat.le_div_iff_mul_le _ _ npos).2 lo) theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) := begin have npos : 0 < n := (eq_zero_or_pos _).resolve_left (λ n0, by rw [n0, nat.zero_mul] at h₁; exact not_lt_zero _ h₁), apply nat.div_eq_of_lt_le, { rw [nat.mul_sub_right_distrib, nat.mul_comm], apply nat.sub_le_sub_left, exact (div_lt_iff_lt_mul _ _ npos).1 (lt_succ_self _) }, { change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁), succ_pred_eq_of_pos (nat.sub_pos_of_lt _)], { rw [nat.mul_sub_right_distrib, nat.mul_comm], apply nat.sub_le_sub_left, apply div_mul_le_self }, { apply (div_lt_iff_lt_mul _ _ npos).2, rwa nat.mul_comm } } end protected lemma mul_pos {a b : ℕ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from nat.mul_lt_mul_of_pos_right ha hb, by rwa nat.zero_mul at h protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) := begin cases eq_zero_or_pos k with k0 kpos, {rw [k0, nat.mul_zero, nat.div_zero, nat.div_zero]}, cases eq_zero_or_pos n with n0 npos, {rw [n0, nat.zero_mul, nat.div_zero, nat.zero_div]}, apply le_antisymm, { apply (le_div_iff_mul_le _ _ (nat.mul_pos npos kpos)).2, rw [nat.mul_comm n k, ← nat.mul_assoc], apply (le_div_iff_mul_le _ _ npos).1, apply (le_div_iff_mul_le _ _ kpos).1, refl }, { apply (le_div_iff_mul_le _ _ kpos).2, apply (le_div_iff_mul_le _ _ npos).2, rw [nat.mul_assoc, nat.mul_comm n k], apply (le_div_iff_mul_le _ _ (nat.mul_pos kpos npos)).1, refl } end protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : 0 < m) : m * n / (m * k) = n / k := by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H] /- dvd -/ protected theorem dvd_mul_right (a b : ℕ) : a ∣ a * b := ⟨b, rfl⟩ protected theorem dvd_trans {a b c : ℕ} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := match h₁, h₂ with | ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ := ⟨d * e, show c = a * (d * e), by simp [h₃, h₄, nat.mul_assoc]⟩ end protected theorem eq_zero_of_zero_dvd {a : ℕ} (h : 0 ∣ a) : a = 0 := exists.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (nat.zero_mul c)) protected theorem dvd_add {a b c : ℕ} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := exists.elim h₁ (λ d hd, exists.elim h₂ (λ e he, ⟨d + e, by simp [nat.left_distrib, hd, he]⟩)) protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n := ⟨nat.dvd_add h, exists.elim h $ λd hd, match m, hd with | ._, rfl := λh₂, exists.elim h₂ $ λe he, ⟨e - d, by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩ end⟩ protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n := by rw nat.add_comm; exact nat.dvd_add_iff_right h theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := (nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁ theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m := let t := @nat.dvd_add_iff_left _ (m % n) _ (nat.dvd_trans h (nat.dvd_mul_right n (m / n))) in by rwa mod_add_div at t theorem le_of_dvd {m n : ℕ} (h : 0 < n) : m ∣ n → m ≤ n := λ⟨k, e⟩, by { revert h, rw e, refine k.cases_on _ _, exact λhn, absurd hn (lt_irrefl _), exact λk _, let t := mul_le_mul_left m (succ_pos k) in by rwa nat.mul_one at t } theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n | m 0 h₁ h₂ := nat.eq_zero_of_zero_dvd h₂ | 0 n h₁ h₂ := (nat.eq_zero_of_zero_dvd h₁).symm | (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂) theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : 0 < n) : 0 < m := nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw nat.eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2 theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial) theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n := ⟨n / m, by { have t := (mod_add_div n m).symm, rwa [H, nat.zero_add] at t }⟩ theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 := exists.elim H (λ z H1, by rw [H1, mul_mod_right]) theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ instance decidable_dvd : @decidable_rel ℕ (∣) := λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m := let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, nat.zero_add] at t protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m := by rw [nat.mul_comm, nat.mul_div_cancel' H] protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) := or.elim (eq_zero_or_pos k) (λh, by rw [h, nat.div_zero, nat.div_zero, nat.mul_zero]) (λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H, by rw[this, ← nat.mul_assoc, nat.mul_div_cancel _ h]) theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : 0 < k) (H : k * m ∣ k * n) : m ∣ n := exists.elim H (λl H1, by rw nat.mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left kpos H1⟩) theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : 0 < k) (H : m * k ∣ n * k) : m ∣ n := by rw [nat.mul_comm m k, nat.mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H /- --- -/ protected lemma mul_le_mul_of_nonneg_left {a b c : ℕ} (h₁ : a ≤ b) : c * a ≤ c * b := begin by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] }, by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 (zero_le c), nat.zero_mul] }, exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_left (lt_of_le_not_le h₁ hba) (lt_of_le_not_le (zero_le c) hc0))).left, end protected lemma mul_le_mul_of_nonneg_right {a b c : ℕ} (h₁ : a ≤ b) : a * c ≤ b * c := begin by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] }, by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 (zero_le c), nat.mul_zero] }, exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_right (lt_of_le_not_le h₁ hba) (lt_of_le_not_le (zero_le c) hc0))).left, end protected lemma mul_lt_mul {a b c d : ℕ} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) : a * b < c * d := calc a * b < c * b : nat.mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd protected lemma mul_lt_mul' {a b c d : ℕ} (h1 : a ≤ c) (h2 : b < d) (h3 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right h1 ... < c * d : nat.mul_lt_mul_of_pos_left h2 h3 -- TODO: there are four variations, depending on which variables we assume to be nonneg protected lemma mul_le_mul {a b c d : ℕ} (hac : a ≤ c) (hbd : b ≤ d) : a * b ≤ c * d := calc a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right hac ... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd lemma div_lt_self {n m : nat} : 0 < n → 1 < m → n / m < n := begin intros h₁ h₂, have m_pos : 0 < m, { apply lt_trans _ h₂, comp_val }, suffices : 1 * n < m * n, { rw [nat.one_mul, nat.mul_comm] at this, exact iff.mpr (nat.div_lt_iff_lt_mul n n m_pos) this }, exact nat.mul_lt_mul h₂ (le_refl _) h₁ end end nat
636e4a9aeb1d7baae3ab00b1b4d0ec4e6ff0e138
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/logic/connectives.lean
820c86030fd3e8fe2881c9c56d25b189499eb03e
[ "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
5,051
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Haitao Zhang The propositional connectives. See also init.datatypes and init.logic. -/ open eq.ops variables {a b c d : Prop} /- implies -/ definition imp (a b : Prop) : Prop := a → b theorem imp.id (H : a) : a := H theorem imp.intro (H : a) (H₂ : b) : a := H theorem imp.mp (H : a) (H₂ : a → b) : b := H₂ H theorem imp.syl (H : a → b) (H₂ : c → a) (Hc : c) : b := H (H₂ Hc) theorem imp.left (H : a → b) (H₂ : b → c) (Ha : a) : c := H₂ (H Ha) theorem imp_true (a : Prop) : (a → true) ↔ true := iff_true_intro (imp.intro trivial) theorem true_imp (a : Prop) : (true → a) ↔ a := iff.intro (assume H, H trivial) imp.intro theorem imp_false (a : Prop) : (a → false) ↔ ¬ a := iff.rfl theorem false_imp (a : Prop) : (false → a) ↔ true := iff_true_intro false.elim /- not -/ theorem not.elim {A : Type} (H1 : ¬a) (H2 : a) : A := absurd H2 H1 theorem not.mto {a b : Prop} : (a → b) → ¬b → ¬a := imp.left theorem not_imp_not_of_imp {a b : Prop} : (a → b) → ¬b → ¬a := not.mto theorem not_not_of_not_implies : ¬(a → b) → ¬¬a := not.mto not.elim theorem not_of_not_implies : ¬(a → b) → ¬b := not.mto imp.intro theorem not_not_em : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), not_em (or.inr (not.mto or.inl not_em)) theorem not_iff_not (H : a ↔ b) : ¬a ↔ ¬b := iff.intro (not.mto (iff.mpr H)) (not.mto (iff.mp H)) /- and -/ definition not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := not.mto and.left definition not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := not.mto and.right theorem and.imp_left (H : a → b) : a ∧ c → b ∧ c := and.imp H imp.id theorem and.imp_right (H : a → b) : c ∧ a → c ∧ b := and.imp imp.id H theorem and_of_and_of_imp_of_imp (H₁ : a ∧ b) (H₂ : a → c) (H₃ : b → d) : c ∧ d := and.imp H₂ H₃ H₁ theorem and_of_and_of_imp_left (H₁ : a ∧ c) (H : a → b) : b ∧ c := and.imp_left H H₁ theorem and_of_and_of_imp_right (H₁ : c ∧ a) (H : a → b) : c ∧ b := and.imp_right H H₁ theorem and_imp_iff (a b c : Prop) : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λH a b, H (and.intro a b)) and.rec theorem and_imp_eq (a b c : Prop) : (a ∧ b → c) = (a → b → c) := propext !and_imp_iff /- or -/ definition not_or : ¬a → ¬b → ¬(a ∨ b) := or.rec theorem or_of_or_of_imp_of_imp (H₁ : a ∨ b) (H₂ : a → c) (H₃ : b → d) : c ∨ d := or.imp H₂ H₃ H₁ theorem or_of_or_of_imp_left (H₁ : a ∨ c) (H : a → b) : b ∨ c := or.imp_left H H₁ theorem or_of_or_of_imp_right (H₁ : c ∨ a) (H : a → b) : c ∨ b := or.imp_right H H₁ theorem or.elim3 (H : a ∨ b ∨ c) (Ha : a → d) (Hb : b → d) (Hc : c → d) : d := or.elim H Ha (assume H₂, or.elim H₂ Hb Hc) theorem or_resolve_right (H₁ : a ∨ b) (H₂ : ¬a) : b := or.elim H₁ (not.elim H₂) imp.id theorem or_resolve_left (H₁ : a ∨ b) : ¬b → a := or_resolve_right (or.swap H₁) theorem or.imp_distrib : ((a ∨ b) → c) ↔ ((a → c) ∧ (b → c)) := iff.intro (λH, and.intro (imp.syl H or.inl) (imp.syl H or.inr)) (and.rec or.rec) theorem or_iff_right_of_imp {a b : Prop} (Ha : a → b) : (a ∨ b) ↔ b := iff.intro (or.rec Ha imp.id) or.inr theorem or_iff_left_of_imp {a b : Prop} (Hb : b → a) : (a ∨ b) ↔ a := iff.intro (or.rec imp.id Hb) or.inl theorem or_iff_or (H1 : a ↔ c) (H2 : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp H1) (iff.mp H2)) (or.imp (iff.mpr H1) (iff.mpr H2)) /- distributivity -/ theorem and.left_distrib (a b c : Prop) : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := iff.intro (and.rec (λH, or.imp (and.intro H) (and.intro H))) (or.rec (and.imp_right or.inl) (and.imp_right or.inr)) theorem and.right_distrib (a b c : Prop) : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := iff.trans (iff.trans !and.comm !and.left_distrib) (or_iff_or !and.comm !and.comm) theorem or.left_distrib (a b c : Prop) : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := iff.intro (or.rec (λH, and.intro (or.inl H) (or.inl H)) (and.imp or.inr or.inr)) (and.rec (or.rec (imp.syl imp.intro or.inl) (imp.syl or.imp_right and.intro))) theorem or.right_distrib (a b c : Prop) : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := iff.trans (iff.trans !or.comm !or.left_distrib) (and_congr !or.comm !or.comm) /- iff -/ definition iff.def : (a ↔ b) = ((a → b) ∧ (b → a)) := rfl theorem forall_imp_forall {A : Type} {P Q : A → Prop} (H : ∀a, (P a → Q a)) (p : ∀a, P a) (a : A) : Q a := (H a) (p a) theorem forall_iff_forall {A : Type} {P Q : A → Prop} (H : ∀a, (P a ↔ Q a)) : (∀a, P a) ↔ (∀a, Q a) := iff.intro (λp a, iff.elim_left (H a) (p a)) (λq a, iff.elim_right (H a) (q a)) theorem imp_iff {P : Prop} (Q : Prop) (p : P) : (P → Q) ↔ Q := iff.intro (λf, f p) imp.intro
467c6c5b29523516f8682d7f76eb9155dcc00cad
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/meta_tac7.lean
c6ff543b1da15f346ad85af88cd7d4390c785f2b
[ "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
196
lean
open nat tactic example (a b c : Prop) (Ha : a) (Hb : b) (Hc : c) : b := by do trace_state, assumption definition ex1 (a b c : Prop) : a → b → c → b := by do intros, assumption print ex1
eb6580e83f9dbed75e4e5695ef77e0eadb69479c
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/PreDefinition/WF/PackMutual.lean
d748b70fbbc935c1a20865570aa408a0d1a566df
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
8,585
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Basic namespace Lean.Elab.WF open Meta /-- Combine different function domains `ds` using `PSum`s -/ private def mkNewDomain (ds : Array Expr) : MetaM Expr := do let mut r := ds.back for d in ds.pop.reverse do r ← mkAppM ``PSum #[d, r] return r private def getCodomainLevel (preDefType : Expr) : MetaM Level := forallBoundedTelescope preDefType (some 1) fun _ body => getLevel body /-- Return the universe level for the codomain of the given definitions. This method produces an error if the codomains are in different universe levels. -/ private def getCodomainsLevel (preDefsOriginal : Array PreDefinition) (preDefTypes : Array Expr) : MetaM Level := do let r ← getCodomainLevel preDefTypes[0]! for i in [1:preDefTypes.size] do let preDef := preDefTypes[i]! unless (← isLevelDefEq r (← getCodomainLevel preDef)) do let arity₀ ← lambdaTelescope preDefsOriginal[0]!.value fun xs _ => return xs.size let arityᵢ ← lambdaTelescope preDefsOriginal[i]!.value fun xs _ => return xs.size forallBoundedTelescope preDefsOriginal[0]!.type arity₀ fun _ type₀ => forallBoundedTelescope preDefsOriginal[i]!.type arityᵢ fun _ typeᵢ => withOptions (fun o => pp.sanitizeNames.set o false) do throwError "invalid mutual definition, result types must be in the same universe level, resulting type for `{preDefsOriginal[0]!.declName}` is{indentExpr type₀} : {← inferType type₀}\nand for `{preDefsOriginal[i]!.declName}` is{indentExpr typeᵢ} : {← inferType typeᵢ}" return r /-- Create the codomain for the new function that "combines" different `preDef` types See: `packMutual` -/ private partial def mkNewCoDomain (preDefsOriginal : Array PreDefinition) (preDefTypes : Array Expr) (x : Expr) : MetaM Expr := do let u ← getCodomainsLevel preDefsOriginal preDefTypes let rec go (x : Expr) (i : Nat) : MetaM Expr := do if i < preDefTypes.size - 1 then let xType ← whnfD (← inferType x) assert! xType.isAppOfArity ``PSum 2 let xTypeArgs := xType.getAppArgs let casesOn := mkConst (mkCasesOnName ``PSum) (mkLevelSucc u :: xType.getAppFn.constLevels!) let casesOn := mkAppN casesOn xTypeArgs -- parameters let casesOn := mkApp casesOn (← mkLambdaFVars #[x] (mkSort u)) -- motive let casesOn := mkApp casesOn x -- major let minor1 ← withLocalDeclD (← mkFreshUserName `_x) xTypeArgs[0]! fun x => mkLambdaFVars #[x] (preDefTypes[i]!.bindingBody!.instantiate1 x) let minor2 ← withLocalDeclD (← mkFreshUserName `_x) xTypeArgs[1]! fun x => do mkLambdaFVars #[x] (← go x (i+1)) return mkApp2 casesOn minor1 minor2 else return preDefTypes[i]!.bindingBody!.instantiate1 x go x 0 /-- Combine/pack the values of the different definitions in a single value `x` is `PSum`, and we use `PSum.casesOn` to select the appropriate `preDefs.value`. See: `packMutual`. Remark: this method does not replace the nested recursive `preDefValues` applications. This step is performed by `transform` with the following `post` method. -/ private partial def packValues (x : Expr) (codomain : Expr) (preDefValues : Array Expr) : MetaM Expr := do let varNames := preDefValues.map fun val => assert! val.isLambda val.bindingName! let mvar ← mkFreshExprSyntheticOpaqueMVar codomain let rec go (mvarId : MVarId) (x : FVarId) (i : Nat) : MetaM Unit := do if i < preDefValues.size - 1 then /- Names for the `cases` tactics. The names are important to preserve the user provided names (unary functions). -/ let givenNames : Array AltVarNames := if i == preDefValues.size - 2 then #[{ varNames := [varNames[i]!] }, { varNames := [varNames[i+1]!] }] else #[{ varNames := [varNames[i]!] }] let #[s₁, s₂] ← mvarId.cases x (givenNames := givenNames) | unreachable! s₁.mvarId.assign (mkApp preDefValues[i]! s₁.fields[0]!).headBeta go s₂.mvarId s₂.fields[0]!.fvarId! (i+1) else mvarId.assign (mkApp preDefValues[i]! (mkFVar x)).headBeta go mvar.mvarId! x.fvarId! 0 instantiateMVars mvar /-- Auxiliary function for replacing nested `preDefs` recursive calls in `e` with the new function `newFn`. See: `packMutual` -/ private partial def post (fixedPrefix : Nat) (preDefs : Array PreDefinition) (domain : Expr) (newFn : Name) (e : Expr) : MetaM TransformStep := do if e.getAppNumArgs != fixedPrefix + 1 then return TransformStep.done e let f := e.getAppFn if !f.isConst then return TransformStep.done e let declName := f.constName! let us := f.constLevels! if let some fidx := preDefs.findIdx? (·.declName == declName) then let args := e.getAppArgs let fixedArgs := args[:fixedPrefix] let arg := args.back let rec mkNewArg (i : Nat) (type : Expr) : MetaM Expr := do if i == preDefs.size - 1 then return arg else (← whnfD type).withApp fun f args => do assert! args.size == 2 if i == fidx then return mkApp3 (mkConst ``PSum.inl f.constLevels!) args[0]! args[1]! arg else let r ← mkNewArg (i+1) args[1]! return mkApp3 (mkConst ``PSum.inr f.constLevels!) args[0]! args[1]! r return TransformStep.done <| mkApp (mkAppN (mkConst newFn us) fixedArgs) (← mkNewArg 0 domain) return TransformStep.done e partial def withFixedPrefix (fixedPrefix : Nat) (preDefs : Array PreDefinition) (k : Array Expr → Array Expr → Array Expr → MetaM α) : MetaM α := go fixedPrefix #[] (preDefs.map (·.value)) where go (i : Nat) (fvars : Array Expr) (vals : Array Expr) : MetaM α := do match i with | 0 => k fvars (← preDefs.mapM fun preDef => instantiateForall preDef.type fvars) vals | i+1 => withLocalDecl vals[0]!.bindingName! vals[0]!.binderInfo vals[0]!.bindingDomain! fun x => go i (fvars.push x) (vals.map fun val => val.bindingBody!.instantiate1 x) /-- If `preDefs.size > 1`, combine different functions in a single one using `PSum`. This method assumes all `preDefs` have arity 1, and have already been processed using `packDomain`. Here is a small example. Suppose the input is ``` f x := match x.2.1, x.2.2.1, x.2.2.2 with | 0, a, b => a | Nat.succ n, a, b => (g ⟨x.1, n, a, b⟩).fst g x := match x.2.1, x.2.2.1, x.2.2.2 with | 0, a, b => (a, b) | Nat.succ n, a, b => (h ⟨x.1, n, a, b⟩, a) h x => match x.2.1, x.2.2.1, x.2.2.2 with | 0, a, b => b | Nat.succ n, a, b => f ⟨x.1, n, a, b⟩ ``` this method produces the following pre definition ``` f._mutual x := PSum.casesOn x (fun val => match val.2.1, val.2.2.1, val.2.2.2 with | 0, a, b => a | Nat.succ n, a, b => (f._mutual (PSum.inr (PSum.inl ⟨val.1, n, a, b⟩))).fst fun val => PSum.casesOn val (fun val => match val.2.1, val.2.2.1, val.2.2.2 with | 0, a, b => (a, b) | Nat.succ n, a, b => (f._mutual (PSum.inr (PSum.inr ⟨val.1, n, a, b⟩)), a) fun val => match val.2.1, val.2.2.1, val.2.2.2 with | 0, a, b => b | Nat.succ n, a, b => f._mutual (PSum.inl ⟨val.1, n, a, b⟩) ``` Remark: `preDefsOriginal` is used for error reporting, it contains the definitions before applying `packDomain`. -/ def packMutual (fixedPrefix : Nat) (preDefsOriginal : Array PreDefinition) (preDefs : Array PreDefinition) : MetaM PreDefinition := do if preDefs.size == 1 then return preDefs[0]! withFixedPrefix fixedPrefix preDefs fun ys types vals => do let domains := types.map fun type => type.bindingDomain! let domain ← mkNewDomain domains withLocalDeclD (← mkFreshUserName `_x) domain fun x => do let codomain ← mkNewCoDomain preDefsOriginal types x let type ← mkForallFVars (ys.push x) codomain let value ← packValues x codomain vals let newFn := preDefs[0]!.declName ++ `_mutual let preDefNew := { preDefs[0]! with declName := newFn, type, value } addAsAxiom preDefNew let value ← transform value (post := post fixedPrefix preDefs domain newFn) let value ← mkLambdaFVars (ys.push x) value return { preDefNew with value } end Lean.Elab.WF
2dac0122a16622f3ef6f7d96e84b5a373188d753
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/category/Preorder.lean
75cb06958c7419d87c98321e418e1d1eb3fdf863
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,546
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import category_theory.category.Cat import category_theory.category.preorder import category_theory.concrete_category.bundled_hom import order.hom.basic /-! # Category of preorders This defines `Preorder`, the category of preorders with monotone maps. -/ universe u open category_theory /-- The category of preorders. -/ def Preorder := bundled preorder namespace Preorder instance : bundled_hom @order_hom := { to_fun := @order_hom.to_fun, id := @order_hom.id, comp := @order_hom.comp, hom_ext := @order_hom.ext } attribute [derive [large_category, concrete_category]] Preorder instance : has_coe_to_sort Preorder Type* := bundled.has_coe_to_sort /-- Construct a bundled Preorder from the underlying type and typeclass. -/ def of (α : Type*) [preorder α] : Preorder := bundled.of α @[simp] lemma coe_of (α : Type*) [preorder α] : ↥(of α) = α := rfl instance : inhabited Preorder := ⟨of punit⟩ instance (α : Preorder) : preorder α := α.str /-- Constructs an equivalence between preorders from an order isomorphism between them. -/ @[simps] def iso.mk {α β : Preorder.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply x }, inv_hom_id' := by { ext, exact e.apply_symm_apply x } } /-- `order_dual` as a functor. -/ @[simps] def dual : Preorder ⥤ Preorder := { obj := λ X, of Xᵒᵈ, map := λ X Y, order_hom.dual } /-- The equivalence between `Preorder` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : Preorder ≌ Preorder := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end Preorder /-- The embedding of `Preorder` into `Cat`. -/ @[simps] def Preorder_to_Cat : Preorder.{u} ⥤ Cat := { obj := λ X, Cat.of X.1, map := λ X Y f, f.monotone.functor, map_id' := λ X, begin apply category_theory.functor.ext, tidy end, map_comp' := λ X Y Z f g, begin apply category_theory.functor.ext, tidy end } instance : faithful Preorder_to_Cat.{u} := { map_injective' := λ X Y f g h, begin ext x, exact functor.congr_obj h x end } instance : full Preorder_to_Cat.{u} := { preimage := λ X Y f, ⟨f.obj, f.monotone⟩, witness' := λ X Y f, begin apply category_theory.functor.ext, tidy end }
328a7fb20516a417f86eaf7fb7da3e8746961734
690889011852559ee5ac4dfea77092de8c832e7e
/src/topology/uniform_space/completion.lean
644ded44bc9eb641768f59937c05a3ca5da71753
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
24,891
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Hausdorff completions of uniform spaces. The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism (ie. uniformly continuous map) `completion : α → completion α` which solves the universal mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`. It means any uniformly continuous `f : α → β` gives rise to a unique morphism `completion.extension f : completion α → β` such that `f = completion.extension f ∘ completion α`. Actually `completion.extension f` is defined for all maps from `α` to `β` but it has the desired properties only if `f` is uniformly continuous. Beware that `completion α` is not injective if `α` is not Hausdorff. But its image is always dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense. For every uniform spaces `α` and `β`, it turns `f : α → β` into a morphism `completion.map f : completion α → completion β` such that `coe ∘ f = (completion.map f) ∘ coe` provided `f` is uniformly continuous. This construction is compatible with composition. In this file we introduce the following concepts: * `Cauchy α` the uniform completion of the uniform space `α` (using Cauchy filters). These are not minimal filters. * `completion α := quotient (separation_setoid (Cauchy α))` the Hausdorff completion. This formalization is mostly based on N. Bourbaki: General Topology I. M. James: Topologies and Uniformities From a slightly different perspective in order to reuse material in topology.uniform_space.basic. -/ import data.set.basic import topology.uniform_space.abstract_completion topology.uniform_space.separation noncomputable theory open filter set universes u v w x open_locale uniformity classical /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] variables {β : Type v} {γ : Type w} variables [uniform_space β] [uniform_space γ] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ filter.prod (p.1.val) (p.2.val) } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap ((𝓤 α).lift' gen) ≤ (𝓤 α).lift' gen := calc map prod.swap ((𝓤 α).lift' gen) = (𝓤 α).lift' (λs:set (α×α), {p | s ∈ filter.prod (p.2.val) (p.1.val) }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ (𝓤 α).lift' gen : uniformity_lift_le_swap (monotone_principal.comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val))))) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val), t₂, (ht₂ : t₂ ∈ h.val), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val), t₄, (ht₄ : t₄ ∈ g.val), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) ≤ (𝓤 α).lift' gen := calc ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) = (𝓤 α).lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ (𝓤 α).lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = ((𝓤 α).lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ (𝓤 α).lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := (𝓤 α).lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, ∀ f g : Cauchy α, t ∈ filter.prod f.1 g.1 → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_inducing_pure_cauchy : uniform_inducing (pure_cauchy : α → Cauchy α) := ⟨have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ((𝓤 α).lift' gen) = (𝓤 α).lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = 𝓤 α : by simp [this]⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := { inj := assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, ..uniform_inducing_pure_cauchy } lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀ s ∈ 𝓤 (Cauchy α), ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ filter.prod (f.val) (f.val), from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ filter.prod f.val (pure x), from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end lemma dense_inducing_pure_cauchy : dense_inducing pure_cauchy := uniform_inducing_pure_cauchy.dense_inducing pure_cauchy_dense lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy := uniform_embedding_pure_cauchy.dense_embedding pure_cauchy_dense lemma nonempty_Cauchy_iff : nonempty (Cauchy α) ↔ nonempty α := begin split ; rintro ⟨c⟩, { have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.to_dense_inducing.closure_range c, have := mem_closure_iff.1 this _ is_open_univ trivial, rcases exists_mem_of_ne_empty this with ⟨_, ⟨_, a, _⟩⟩, exact ⟨a⟩ }, { exact ⟨pure_cauchy c⟩ } end section set_option eqn_compiler.zeta true instance : complete_space (Cauchy α) := complete_space_extension uniform_inducing_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ (𝓤 $ Cauchy α).lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).sets_of_superset (prod_mem_prod ht' $ mem_pure hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end instance [inhabited α] : inhabited (Cauchy α) := ⟨pure_cauchy $ default α⟩ instance [h : nonempty α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a section extend def extend (f : α → β) : (Cauchy α → β) := if uniform_continuous f then dense_inducing_pure_cauchy.extend f else λ x, f (classical.inhabited_of_nonempty $ nonempty_Cauchy_iff.1 ⟨x⟩).default variables [separated β] lemma extend_pure_cauchy {f : α → β} (hf : uniform_continuous f) (a : α) : extend f (pure_cauchy a) = f a := begin rw [extend, if_pos hf], exact uniformly_extend_of_ind uniform_inducing_pure_cauchy pure_cauchy_dense hf _ end variables [_root_.complete_space β] lemma uniform_continuous_extend {f : α → β} : uniform_continuous (extend f) := begin by_cases hf : uniform_continuous f, { rw [extend, if_pos hf], exact uniform_continuous_uniformly_extend uniform_inducing_pure_cauchy pure_cauchy_dense hf }, { rw [extend, if_neg hf], exact uniform_continuous_of_const (assume a b, by congr) } end end extend end theorem Cauchy_eq {α : Type*} [inhabited α] [uniform_space α] [complete_space α] [separated α] {f g : Cauchy α} : lim f.1 = lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy α) := begin split, { intros e s hs, rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩, apply ts, rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩, refine mem_prod_iff.2 ⟨_, le_nhds_lim_of_cauchy f.2 (mem_nhds_right (lim f.1) du), _, le_nhds_lim_of_cauchy g.2 (mem_nhds_left (lim g.1) du), λ x h, _⟩, cases x with a b, cases h with h₁ h₂, rw ← e at h₂, exact dt ⟨_, h₁, h₂⟩ }, { intros H, refine separated_def.1 (by apply_instance) _ _ (λ t tu, _), rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩, refine H {p | (lim p.1.1, lim p.2.1) ∈ t} (Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩), rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩, have limc : ∀ (f : Cauchy α) (x ∈ f.1), lim f.1 ∈ closure x, { intros f x xf, rw closure_eq_nhds, exact lattice.neq_bot_of_le_neq_bot f.2.1 (lattice.le_inf (le_nhds_lim_of_cauchy f.2) (le_principal_iff.2 xf)) }, have := (closure_subset_iff_subset_of_is_closed dc).2 h, rw closure_prod_eq at this, refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption } end section local attribute [instance] uniform_space.separation_setoid lemma injective_separated_pure_cauchy {α : Type*} [uniform_space α] [s : separated α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).comap_uniformity, filter.mem_comap_sets] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end end Cauchy local attribute [instance] uniform_space.separation_setoid open Cauchy set namespace uniform_space variables (α : Type*) [uniform_space α] variables {β : Type*} [uniform_space β] variables {γ : Type*} [uniform_space γ] instance complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (f.comap (λx, ⟦x⟧)), from cauchy_comap comap_quotient_le_uniformity hf $ comap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : f.comap (λx, ⟦x⟧) ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f = map (λx, ⟦x⟧) (f.comap (λx, ⟦x⟧)) : (map_comap $ univ_mem_sets' $ assume b, quotient.exists_rep _).symm ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_continuous_at.mp uniform_continuous_quotient_mk.continuous _⟩⟩ /-- Hausdorff completion of `α` -/ def completion := quotient (separation_setoid $ Cauchy α) namespace completion @[priority 50] instance : uniform_space (completion α) := by dunfold completion ; apply_instance instance : complete_space (completion α) := by dunfold completion ; apply_instance instance : separated (completion α) := by dunfold completion ; apply_instance instance : t2_space (completion α) := separated_t2 instance : regular_space (completion α) := separated_regular /-- Automatic coercion from `α` to its completion. Not always injective. -/ instance : has_coe α (completion α) := ⟨quotient.mk ∘ pure_cauchy⟩ protected lemma coe_eq : (coe : α → completion α) = quotient.mk ∘ pure_cauchy := rfl lemma comap_coe_eq_uniformity : (𝓤 _).comap (λ(p:α×α), ((p.1 : completion α), (p.2 : completion α))) = 𝓤 α := begin have : (λx:α×α, ((x.1 : completion α), (x.2 : completion α))) = (λx:(Cauchy α)×(Cauchy α), (⟦x.1⟧, ⟦x.2⟧)) ∘ (λx:α×α, (pure_cauchy x.1, pure_cauchy x.2)), { ext ⟨a, b⟩; simp; refl }, rw [this, ← filter.comap_comap_comp], change filter.comap _ (filter.comap _ (𝓤 $ quotient $ separation_setoid $ Cauchy α)) = 𝓤 α, rw [comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.comap_uniformity] end lemma uniform_inducing_coe : uniform_inducing (coe : α → completion α) := ⟨comap_coe_eq_uniformity α⟩ variables {α} lemma dense : closure (range (coe : α → completion α)) = univ := by rw [completion.coe_eq, range_comp]; exact quotient_dense_of_dense pure_cauchy_dense variables (α) def cpkg {α : Type*} [uniform_space α] : abstract_completion α := { space := completion α, coe := coe, uniform_struct := by apply_instance, complete := by apply_instance, separation := by apply_instance, uniform_inducing := completion.uniform_inducing_coe α, dense := (dense_range_iff_closure_eq _).2 completion.dense } local attribute [instance] abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation lemma nonempty_completion_iff : nonempty (completion α) ↔ nonempty α := (dense_range.nonempty (cpkg.dense)).symm lemma uniform_continuous_coe : uniform_continuous (coe : α → completion α) := cpkg.uniform_continuous_coe lemma continuous_coe : continuous (coe : α → completion α) := cpkg.continuous_coe lemma uniform_embedding_coe [separated α] : uniform_embedding (coe : α → completion α) := { comap_uniformity := comap_coe_eq_uniformity α, inj := injective_separated_pure_cauchy } variable {α} lemma dense_inducing_coe : dense_inducing (coe : α → completion α) := { dense := (dense_range_iff_closure_eq _).2 dense, ..(uniform_inducing_coe α).inducing } lemma dense_embedding_coe [separated α]: dense_embedding (coe : α → completion α) := { inj := injective_separated_pure_cauchy, ..dense_inducing_coe } lemma dense₂ : closure (range (λx:α × β, ((x.1 : completion α), (x.2 : completion β)))) = univ := by rw [← set.prod_range_range_eq, closure_prod_eq, dense, dense, univ_prod_univ] lemma dense₃ : closure (range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ))))) = univ := let a : α → completion α := coe, bc := λp:β × γ, ((p.1 : completion β), (p.2 : completion γ)) in show closure (range (λx:α × (β × γ), (a x.1, bc x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range a) (range bc), ← univ_prod_univ], congr, exact dense, exact dense₂ end @[elab_as_eliminator] lemma induction_on {p : completion α → Prop} (a : completion α) (hp : is_closed {a | p a}) (ih : ∀a:α, p a) : p a := is_closed_property dense hp ih a @[elab_as_eliminator] lemma induction_on₂ {p : completion α → completion β → Prop} (a : completion α) (b : completion β) (hp : is_closed {x : completion α × completion β | p x.1 x.2}) (ih : ∀(a:α) (b:β), p a b) : p a b := have ∀x : completion α × completion β, p x.1 x.2, from is_closed_property dense₂ hp $ assume ⟨a, b⟩, ih a b, this (a, b) @[elab_as_eliminator] lemma induction_on₃ {p : completion α → completion β → completion γ → Prop} (a : completion α) (b : completion β) (c : completion γ) (hp : is_closed {x : completion α × completion β × completion γ | p x.1 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ), p a b c) : p a b c := have ∀x : completion α × completion β × completion γ, p x.1 x.2.1 x.2.2, from is_closed_property dense₃ hp $ assume ⟨a, b, c⟩, ih a b c, this (a, b, c) @[elab_as_eliminator] lemma induction_on₄ {δ : Type*} [uniform_space δ] {p : completion α → completion β → completion γ → completion δ → Prop} (a : completion α) (b : completion β) (c : completion γ) (d : completion δ) (hp : is_closed {x : (completion α × completion β) × (completion γ × completion δ) | p x.1.1 x.1.2 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ) (d : δ), p ↑a ↑b ↑c ↑d) : p a b c d := let ab := λp:α × β, ((p.1 : completion α), (p.2 : completion β)), cd := λp:γ × δ, ((p.1 : completion γ), (p.2 : completion δ)) in have dense₄ : closure (range (λx:(α × β) × (γ × δ), (ab x.1, cd x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range ab) (range cd), ← univ_prod_univ], congr, exact dense₂, exact dense₂ end, have ∀x:(completion α × completion β) × (completion γ × completion δ), p x.1.1 x.1.2 x.2.1 x.2.2, from is_closed_property dense₄ hp (assume p:(α×β)×(γ×δ), ih p.1.1 p.1.2 p.2.1 p.2.2), this ((a, b), (c, d)) lemma ext [t2_space β] {f g : completion α → β} (hf : continuous f) (hg : continuous g) (h : ∀a:α, f a = g a) : f = g := cpkg.funext hf hg h section extension variables {f : α → β} /-- "Extension" to the completion. It is defined for any map `f` but returns an arbitrary constant value if `f` is not uniformly continuous -/ protected def extension (f : α → β) : completion α → β := cpkg.extend f variables [separated β] @[simp] lemma extension_coe (hf : uniform_continuous f) (a : α) : (completion.extension f) a = f a := cpkg.extend_coe hf a variables [complete_space β] lemma uniform_continuous_extension : uniform_continuous (completion.extension f) := cpkg.uniform_continuous_extend lemma continuous_extension : continuous (completion.extension f) := cpkg.continuous_extend lemma extension_unique (hf : uniform_continuous f) {g : completion α → β} (hg : uniform_continuous g) (h : ∀ a : α, f a = g (a : completion α)) : completion.extension f = g := cpkg.extend_unique hf hg h @[simp] lemma extension_comp_coe {f : completion α → β} (hf : uniform_continuous f) : completion.extension (f ∘ coe) = f := cpkg.extend_comp_coe hf end extension section map variables {f : α → β} /-- Completion functor acting on morphisms -/ protected def map (f : α → β) : completion α → completion β := cpkg.map cpkg f lemma uniform_continuous_map : uniform_continuous (completion.map f) := cpkg.uniform_continuous_map cpkg f lemma continuous_map : continuous (completion.map f) := cpkg.continuous_map cpkg f @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : (completion.map f) a = f a := cpkg.map_coe cpkg hf a lemma map_unique {f : α → β} {g : completion α → completion β} (hg : uniform_continuous g) (h : ∀a:α, ↑(f a) = g a) : completion.map f = g := cpkg.map_unique cpkg hg h @[simp] lemma map_id : completion.map (@id α) = id := cpkg.map_id lemma extension_map [complete_space γ] [separated γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : completion.extension f ∘ completion.map g = completion.extension (f ∘ g) := completion.ext (continuous_extension.comp continuous_map) continuous_extension $ by intro a; simp only [hg, hf, hf.comp hg, (∘), map_coe, extension_coe] lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : completion.map g ∘ completion.map f = completion.map (g ∘ f) := extension_map ((uniform_continuous_coe _).comp hg) hf end map /- In this section we construct isomorphisms between the completion of a uniform space and the completion of its separation quotient -/ section separation_quotient_completion def completion_separation_quotient_equiv (α : Type u) [uniform_space α] : completion (separation_quotient α) ≃ completion α := begin refine ⟨completion.extension (separation_quotient.lift (coe : α → completion α)), completion.map quotient.mk, _, _⟩, { assume a, refine completion.induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _, rintros ⟨a⟩, show completion.map quotient.mk (completion.extension (separation_quotient.lift coe) ↑⟦a⟧) = ↑⟦a⟧, rw [extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α), completion.map_coe uniform_continuous_quotient_mk] ; apply_instance }, { assume a, refine completion.induction_on a (is_closed_eq (continuous_extension.comp continuous_map) continuous_id) _, assume a, rw [map_coe uniform_continuous_quotient_mk, extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α) _] ; apply_instance } end lemma uniform_continuous_completion_separation_quotient_equiv : uniform_continuous ⇑(completion_separation_quotient_equiv α) := uniform_continuous_extension lemma uniform_continuous_completion_separation_quotient_equiv_symm : uniform_continuous ⇑(completion_separation_quotient_equiv α).symm := uniform_continuous_map end separation_quotient_completion section extension₂ variables (f : α → β → γ) open function protected def extension₂ (f : α → β → γ) : completion α → completion β → γ := cpkg.extend₂ cpkg f variables [separated γ] {f} @[simp] lemma extension₂_coe_coe (hf : uniform_continuous $ uncurry' f) (a : α) (b : β) : completion.extension₂ f a b = f a b := cpkg.extension₂_coe_coe cpkg hf a b variables [complete_space γ] (f) lemma uniform_continuous_extension₂ : uniform_continuous₂ (completion.extension₂ f) := cpkg.uniform_continuous_extension₂ cpkg f end extension₂ section map₂ open function protected def map₂ (f : α → β → γ) : completion α → completion β → completion γ := cpkg.map₂ cpkg cpkg f lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous (uncurry' $ completion.map₂ f) := cpkg.uniform_continuous_map₂ cpkg cpkg f lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → completion α} {b : δ → completion β} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, completion.map₂ f (a d) (b d)) := cpkg.continuous_map₂ cpkg cpkg ha hb lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous $ uncurry' f) : completion.map₂ f (a : completion α) (b : completion β) = f a b := cpkg.map₂_coe_coe cpkg cpkg a b f hf end map₂ end completion end uniform_space
6dc845bc3dccd63f7f88b692f6061ac493292098
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/anonymous_param.lean
1873ab3a1d790147a7160c1e7c416a08366c66cb
[ "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
128
lean
#check λ _, nat #check λ (_ _ : nat), nat #check λ _ _ : nat, nat #check (λ _, 0 : nat → nat) def f (_ : nat) : nat := 0
05215ed649d39e8bf21b182b4f1c562319458beb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/Lsp/TextSync.lean
96b796d8b7f690990e9cce1441225e196fc9aef5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,837
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic /-! Section "Text Document Synchronization" of the LSP spec. -/ namespace Lean namespace Lsp open Json inductive TextDocumentSyncKind where | none | full | incremental instance : FromJson TextDocumentSyncKind := ⟨fun j => match j.getNat? with | Except.ok 0 => return TextDocumentSyncKind.none | Except.ok 1 => return TextDocumentSyncKind.full | Except.ok 2 => return TextDocumentSyncKind.incremental | _ => throw "unknown TextDocumentSyncKind"⟩ instance : ToJson TextDocumentSyncKind := ⟨fun | TextDocumentSyncKind.none => 0 | TextDocumentSyncKind.full => 1 | TextDocumentSyncKind.incremental => 2⟩ structure DidOpenTextDocumentParams where textDocument : TextDocumentItem deriving ToJson, FromJson structure TextDocumentChangeRegistrationOptions where documentSelector? : Option DocumentSelector := none syncKind : TextDocumentSyncKind deriving FromJson inductive TextDocumentContentChangeEvent where -- omitted: deprecated rangeLength | rangeChange (range : Range) (text : String) | fullChange (text : String) instance : FromJson TextDocumentContentChangeEvent where fromJson? j := (do let range ← j.getObjValAs? Range "range" let text ← j.getObjValAs? String "text" return TextDocumentContentChangeEvent.rangeChange range text) <|> (TextDocumentContentChangeEvent.fullChange <$> j.getObjValAs? String "text") instance TextDocumentContentChangeEvent.hasToJson : ToJson TextDocumentContentChangeEvent := ⟨fun o => mkObj $ match o with | TextDocumentContentChangeEvent.rangeChange range text => [⟨"range", toJson range⟩, ⟨"text", toJson text⟩] | TextDocumentContentChangeEvent.fullChange text => [⟨"text", toJson text⟩]⟩ structure DidChangeTextDocumentParams where textDocument : VersionedTextDocumentIdentifier contentChanges : Array TextDocumentContentChangeEvent deriving ToJson, FromJson -- TODO: missing: -- WillSaveTextDocumentParams, TextDocumentSaveReason, -- TextDocumentSaveRegistrationOptions, DidSaveTextDocumentParams structure SaveOptions where includeText : Bool deriving ToJson, FromJson structure DidCloseTextDocumentParams where textDocument : TextDocumentIdentifier deriving ToJson, FromJson -- TODO: TextDocumentSyncClientCapabilities /-- NOTE: This is defined twice in the spec. The latter version has more fields. -/ structure TextDocumentSyncOptions where openClose : Bool change : TextDocumentSyncKind willSave : Bool willSaveWaitUntil : Bool save? : Option SaveOptions := none deriving ToJson, FromJson end Lsp end Lean
3bb1db2a42610614548d96a024b2b5d99346c5c6
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/triv_sq_zero_ext.lean
29181f505e0752fd6240ecd68b13bda3dc78669c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
16,678
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.basic import linear_algebra.prod /-! # Trivial Square-Zero Extension Given a module `M` over a ring `R`, the trivial square-zero extension of `M` over `R` is defined to be the `R`-algebra `R ⊕ M` with multiplication given by `(r₁ + m₁) * (r₂ + m₂) = r₁ r₂ + r₁ m₂ + r₂ m₁`. It is a square-zero extension because `M^2 = 0`. ## Main definitions * `triv_sq_zero_ext.inl`, `triv_sq_zero_ext.inr`: the canonical inclusions into `triv_sq_zero_ext R M`. * `triv_sq_zero_ext.fst`, `triv_sq_zero_ext.snd`: the canonical projections from `triv_sq_zero_ext R M`. * `triv_sq_zero_ext.algebra`: the associated `R`-algebra structure. * `triv_sq_zero_ext.lift`: the universal property of the trivial square-zero extension; algebra morphisms `triv_sq_zero_ext R M →ₐ[R] A` are uniquely defined by linear maps `M →ₗ[R] A` for which the product of any two elements in the range is zero. -/ universes u v w /-- "Trivial Square-Zero Extension". Given a module `M` over a ring `R`, the trivial square-zero extension of `M` over `R` is defined to be the `R`-algebra `R × M` with multiplication given by `(r₁ + m₁) * (r₂ + m₂) = r₁ r₂ + r₁ m₂ + r₂ m₁`. It is a square-zero extension because `M^2 = 0`. -/ def triv_sq_zero_ext (R : Type u) (M : Type v) := R × M local notation `tsze` := triv_sq_zero_ext namespace triv_sq_zero_ext section basic variables {R : Type u} {M : Type v} /-- The canonical inclusion `R → triv_sq_zero_ext R M`. -/ def inl [has_zero M] (r : R) : tsze R M := (r, 0) /-- The canonical inclusion `M → triv_sq_zero_ext R M`. -/ def inr [has_zero R] (m : M) : tsze R M := (0, m) /-- The canonical projection `triv_sq_zero_ext R M → R`. -/ def fst (x : tsze R M) : R := x.1 /-- The canonical projection `triv_sq_zero_ext R M → M`. -/ def snd (x : tsze R M) : M := x.2 @[ext] lemma ext {x y : tsze R M} (h1 : x.fst = y.fst) (h2 : x.snd = y.snd) : x = y := prod.ext h1 h2 section variables (M) @[simp] lemma fst_inl [has_zero M] (r : R) : (inl r : tsze R M).fst = r := rfl @[simp] lemma snd_inl [has_zero M] (r : R) : (inl r : tsze R M).snd = 0 := rfl end section variables (R) @[simp] lemma fst_inr [has_zero R] (m : M) : (inr m : tsze R M).fst = 0 := rfl @[simp] lemma snd_inr [has_zero R] (m : M) : (inr m : tsze R M).snd = m := rfl end lemma inl_injective [has_zero M] : function.injective (inl : R → tsze R M) := function.left_inverse.injective $ fst_inl _ lemma inr_injective [has_zero R] : function.injective (inr : M → tsze R M) := function.left_inverse.injective $ snd_inr _ end basic /-! ### Structures inherited from `prod` Additive operators and scalar multiplication operate elementwise. -/ section additive variables {T : Type*} {S : Type*} {R : Type u} {M : Type v} instance [inhabited R] [inhabited M] : inhabited (tsze R M) := prod.inhabited instance [has_zero R] [has_zero M] : has_zero (tsze R M) := prod.has_zero instance [has_add R] [has_add M] : has_add (tsze R M) := prod.has_add instance [has_neg R] [has_neg M] : has_neg (tsze R M) := prod.has_neg instance [add_semigroup R] [add_semigroup M] : add_semigroup (tsze R M) := prod.add_semigroup instance [add_zero_class R] [add_zero_class M] : add_zero_class (tsze R M) := prod.add_zero_class instance [add_monoid R] [add_monoid M] : add_monoid (tsze R M) := prod.add_monoid instance [add_group R] [add_group M] : add_group (tsze R M) := prod.add_group instance [add_comm_semigroup R] [add_comm_semigroup M] : add_comm_semigroup (tsze R M) := prod.add_comm_semigroup instance [add_comm_monoid R] [add_comm_monoid M] : add_comm_monoid (tsze R M) := prod.add_comm_monoid instance [add_comm_group R] [add_comm_group M] : add_comm_group (tsze R M) := prod.add_comm_group instance [has_scalar S R] [has_scalar S M] : has_scalar S (tsze R M) := prod.has_scalar instance [has_scalar T R] [has_scalar T M] [has_scalar S R] [has_scalar S M] [has_scalar T S] [is_scalar_tower T S R] [is_scalar_tower T S M] : is_scalar_tower T S (tsze R M) := prod.is_scalar_tower instance [has_scalar T R] [has_scalar T M] [has_scalar S R] [has_scalar S M] [smul_comm_class T S R] [smul_comm_class T S M] : smul_comm_class T S (tsze R M) := prod.smul_comm_class instance [has_scalar S R] [has_scalar S M] [has_scalar Sᵐᵒᵖ R] [has_scalar Sᵐᵒᵖ M] [is_central_scalar S R] [is_central_scalar S M] : is_central_scalar S (tsze R M) := prod.is_central_scalar instance [monoid S] [mul_action S R] [mul_action S M] : mul_action S (tsze R M) := prod.mul_action instance [monoid S] [add_monoid R] [add_monoid M] [distrib_mul_action S R] [distrib_mul_action S M] : distrib_mul_action S (tsze R M) := prod.distrib_mul_action instance [semiring S] [add_comm_monoid R] [add_comm_monoid M] [module S R] [module S M] : module S (tsze R M) := prod.module @[simp] lemma fst_zero [has_zero R] [has_zero M] : (0 : tsze R M).fst = 0 := rfl @[simp] lemma snd_zero [has_zero R] [has_zero M] : (0 : tsze R M).snd = 0 := rfl @[simp] lemma fst_add [has_add R] [has_add M] (x₁ x₂ : tsze R M) : (x₁ + x₂).fst = x₁.fst + x₂.fst := rfl @[simp] lemma snd_add [has_add R] [has_add M] (x₁ x₂ : tsze R M) : (x₁ + x₂).snd = x₁.snd + x₂.snd := rfl @[simp] lemma fst_neg [has_neg R] [has_neg M] (x : tsze R M) : (-x).fst = -x.fst := rfl @[simp] lemma snd_neg [has_neg R] [has_neg M] (x : tsze R M) : (-x).snd = -x.snd := rfl @[simp] lemma fst_smul [has_scalar S R] [has_scalar S M] (s : S) (x : tsze R M) : (s • x).fst = s • x.fst := rfl @[simp] lemma snd_smul [has_scalar S R] [has_scalar S M] (s : S) (x : tsze R M) : (s • x).snd = s • x.snd := rfl section variables (M) @[simp] lemma inl_zero [has_zero R] [has_zero M] : (inl 0 : tsze R M) = 0 := rfl @[simp] lemma inl_add [has_add R] [add_zero_class M] (r₁ r₂ : R) : (inl (r₁ + r₂) : tsze R M) = inl r₁ + inl r₂ := ext rfl (add_zero 0).symm @[simp] lemma inl_neg [has_neg R] [add_group M] (r : R) : (inl (-r) : tsze R M) = -inl r := ext rfl neg_zero.symm @[simp] lemma inl_smul [monoid S] [add_monoid M] [has_scalar S R] [distrib_mul_action S M] (s : S) (r : R) : (inl (s • r) : tsze R M) = s • inl r := ext rfl (smul_zero s).symm end section variables (R) @[simp] lemma inr_zero [has_zero R] [has_zero M] : (inr 0 : tsze R M) = 0 := rfl @[simp] lemma inr_add [add_zero_class R] [add_zero_class M] (m₁ m₂ : M) : (inr (m₁ + m₂) : tsze R M) = inr m₁ + inr m₂ := ext (add_zero 0).symm rfl @[simp] lemma inr_neg [add_group R] [has_neg M] (m : M) : (inr (-m) : tsze R M) = -inr m := ext neg_zero.symm rfl @[simp] lemma inr_smul [has_zero R] [has_zero S] [smul_with_zero S R] [has_scalar S M] (r : S) (m : M) : (inr (r • m) : tsze R M) = r • inr m := ext (smul_zero' _ _).symm rfl end lemma inl_fst_add_inr_snd_eq [add_zero_class R] [add_zero_class M] (x : tsze R M) : inl x.fst + inr x.snd = x := ext (add_zero x.1) (zero_add x.2) /-- To show a property hold on all `triv_sq_zero_ext R M` it suffices to show it holds on terms of the form `inl r + inr m`. This can be used as `induction x using triv_sq_zero_ext.ind`. -/ lemma ind {R M} [add_zero_class R] [add_zero_class M] {P : triv_sq_zero_ext R M → Prop} (h : ∀ r m, P (inl r + inr m)) (x) : P x := inl_fst_add_inr_snd_eq x ▸ h x.1 x.2 /-- This cannot be marked `@[ext]` as it ends up being used instead of `linear_map.prod_ext` when working with `R × M`. -/ lemma linear_map_ext {N} [semiring S] [add_comm_monoid R] [add_comm_monoid M] [add_comm_monoid N] [module S R] [module S M] [module S N] ⦃f g : tsze R M →ₗ[S] N⦄ (hl : ∀ r, f (inl r) = g (inl r)) (hr : ∀ m, f (inr m) = g (inr m)) : f = g := linear_map.prod_ext (linear_map.ext hl) (linear_map.ext hr) variables (R M) /-- The canonical `R`-linear inclusion `M → triv_sq_zero_ext R M`. -/ @[simps apply] def inr_hom [semiring R] [add_comm_monoid M] [module R M] : M →ₗ[R] tsze R M := { to_fun := inr, ..linear_map.inr R R M } /-- The canonical `R`-linear projection `triv_sq_zero_ext R M → M`. -/ @[simps apply] def snd_hom [semiring R] [add_comm_monoid M] [module R M] : tsze R M →ₗ[R] M := { to_fun := snd, ..linear_map.snd _ _ _ } end additive /-! ### Multiplicative structure -/ section mul variables {R : Type u} {M : Type v} instance [has_one R] [has_zero M] : has_one (tsze R M) := ⟨(1, 0)⟩ instance [has_mul R] [has_add M] [has_scalar R M] : has_mul (tsze R M) := ⟨λ x y, (x.1 * y.1, x.1 • y.2 + y.1 • x.2)⟩ @[simp] lemma fst_one [has_one R] [has_zero M] : (1 : tsze R M).fst = 1 := rfl @[simp] lemma snd_one [has_one R] [has_zero M] : (1 : tsze R M).snd = 0 := rfl @[simp] lemma fst_mul [has_mul R] [has_add M] [has_scalar R M] (x₁ x₂ : tsze R M) : (x₁ * x₂).fst = x₁.fst * x₂.fst := rfl @[simp] lemma snd_mul [has_mul R] [has_add M] [has_scalar R M] (x₁ x₂ : tsze R M) : (x₁ * x₂).snd = x₁.fst • x₂.snd + x₂.fst • x₁.snd := rfl section variables (M) @[simp] lemma inl_one [has_one R] [has_zero M] : (inl 1 : tsze R M) = 1 := rfl @[simp] lemma inl_mul [monoid R] [add_monoid M] [distrib_mul_action R M] (r₁ r₂ : R) : (inl (r₁ * r₂) : tsze R M) = inl r₁ * inl r₂ := ext rfl $ show (0 : M) = r₁ • 0 + r₂ • 0, by rw [smul_zero, zero_add, smul_zero] lemma inl_mul_inl [monoid R] [add_monoid M] [distrib_mul_action R M] (r₁ r₂ : R) : (inl r₁ * inl r₂ : tsze R M) = inl (r₁ * r₂) := (inl_mul M r₁ r₂).symm end section variables (R) @[simp] lemma inr_mul_inr [semiring R] [add_comm_monoid M] [module R M] (m₁ m₂ : M) : (inr m₁ * inr m₂ : tsze R M) = 0 := ext (mul_zero _) $ show (0 : R) • m₂ + (0 : R) • m₁ = 0, by rw [zero_smul, zero_add, zero_smul] end lemma inl_mul_inr [semiring R] [add_comm_monoid M] [module R M] (r : R) (m : M) : (inl r * inr m : tsze R M) = inr (r • m) := ext (mul_zero r) $ show r • m + (0 : R) • 0 = r • m, by rw [smul_zero, add_zero] lemma inr_mul_inl [semiring R] [add_comm_monoid M] [module R M] (r : R) (m : M) : (inr m * inl r : tsze R M) = inr (r • m) := ext (zero_mul r) $ show (0 : R) • 0 + r • m = r • m, by rw [smul_zero, zero_add] instance [monoid R] [add_monoid M] [distrib_mul_action R M] : mul_one_class (tsze R M) := { one_mul := λ x, ext (one_mul x.1) $ show (1 : R) • x.2 + x.1 • 0 = x.2, by rw [one_smul, smul_zero, add_zero], mul_one := λ x, ext (mul_one x.1) $ show (x.1 • 0 : M) + (1 : R) • x.2 = x.2, by rw [smul_zero, zero_add, one_smul], .. triv_sq_zero_ext.has_one, .. triv_sq_zero_ext.has_mul } instance [semiring R] [add_comm_monoid M] [module R M] : non_assoc_semiring (tsze R M) := { zero_mul := λ x, ext (zero_mul x.1) $ show (0 : R) • x.2 + x.1 • 0 = 0, by rw [zero_smul, zero_add, smul_zero], mul_zero := λ x, ext (mul_zero x.1) $ show (x.1 • 0 : M) + (0 : R) • x.2 = 0, by rw [smul_zero, zero_add, zero_smul], left_distrib := λ x₁ x₂ x₃, ext (mul_add x₁.1 x₂.1 x₃.1) $ show x₁.1 • (x₂.2 + x₃.2) + (x₂.1 + x₃.1) • x₁.2 = x₁.1 • x₂.2 + x₂.1 • x₁.2 + (x₁.1 • x₃.2 + x₃.1 • x₁.2), by simp_rw [smul_add, add_smul, add_add_add_comm], right_distrib := λ x₁ x₂ x₃, ext (add_mul x₁.1 x₂.1 x₃.1) $ show (x₁.1 + x₂.1) • x₃.2 + x₃.1 • (x₁.2 + x₂.2) = x₁.1 • x₃.2 + x₃.1 • x₁.2 + (x₂.1 • x₃.2 + x₃.1 • x₂.2), by simp_rw [add_smul, smul_add, add_add_add_comm], .. triv_sq_zero_ext.mul_one_class, .. triv_sq_zero_ext.add_comm_monoid } instance [comm_monoid R] [add_monoid M] [distrib_mul_action R M] : monoid (tsze R M) := { mul_assoc := λ x y z, ext (mul_assoc x.1 y.1 z.1) $ show (x.1 * y.1) • z.2 + z.1 • (x.1 • y.2 + y.1 • x.2) = x.1 • (y.1 • z.2 + z.1 • y.2) + (y.1 * z.1) • x.2, by simp_rw [smul_add, ← mul_smul, add_assoc, mul_comm], .. triv_sq_zero_ext.mul_one_class } instance [comm_monoid R] [add_comm_monoid M] [distrib_mul_action R M] : comm_monoid (tsze R M) := { mul_comm := λ x₁ x₂, ext (mul_comm x₁.1 x₂.1) $ show x₁.1 • x₂.2 + x₂.1 • x₁.2 = x₂.1 • x₁.2 + x₁.1 • x₂.2, from add_comm _ _, .. triv_sq_zero_ext.monoid } instance [comm_semiring R] [add_comm_monoid M] [module R M] : comm_semiring (tsze R M) := { .. triv_sq_zero_ext.comm_monoid, .. triv_sq_zero_ext.non_assoc_semiring } variables (R M) /-- The canonical inclusion of rings `R → triv_sq_zero_ext R M`. -/ @[simps apply] def inl_hom [semiring R] [add_comm_monoid M] [module R M] : R →+* tsze R M := { to_fun := inl, map_one' := inl_one M, map_mul' := inl_mul M, map_zero' := inl_zero M, map_add' := inl_add M } end mul section algebra variables (S : Type*) (R : Type u) (M : Type v) variables [comm_semiring S] [comm_semiring R] [add_comm_monoid M] variables [algebra S R] [module S M] [module R M] [is_scalar_tower S R M] instance algebra' : algebra S (tsze R M) := { commutes' := λ r x, mul_comm _ _, smul_def' := λ r x, ext (algebra.smul_def _ _) $ show r • x.2 = algebra_map S R r • x.2 + x.1 • 0, by rw [smul_zero, add_zero, algebra_map_smul], .. (triv_sq_zero_ext.inl_hom R M).comp (algebra_map S R) } -- shortcut instance for the common case instance : algebra R (tsze R M) := triv_sq_zero_ext.algebra' _ _ _ lemma algebra_map_eq_inl : ⇑(algebra_map R (tsze R M)) = inl := rfl lemma algebra_map_eq_inl_hom : algebra_map R (tsze R M) = inl_hom R M := rfl lemma algebra_map_eq_inl' (s : S) : algebra_map S (tsze R M) s = inl (algebra_map S R s) := rfl /-- The canonical `R`-algebra projection `triv_sq_zero_ext R M → R`. -/ @[simps] def fst_hom : tsze R M →ₐ[R] R := { to_fun := fst, map_one' := fst_one, map_mul' := fst_mul, map_zero' := fst_zero, map_add' := fst_add, commutes' := fst_inl M } variables {R S M} lemma alg_hom_ext {A} [semiring A] [algebra R A] ⦃f g : tsze R M →ₐ[R] A⦄ (h : ∀ m, f (inr m) = g (inr m)) : f = g := alg_hom.to_linear_map_injective $ linear_map_ext (λ r, (f.commutes _).trans (g.commutes _).symm) h @[ext] lemma alg_hom_ext' {A} [semiring A] [algebra R A] ⦃f g : tsze R M →ₐ[R] A⦄ (h : f.to_linear_map.comp (inr_hom R M) = g.to_linear_map.comp (inr_hom R M)) : f = g := alg_hom_ext $ linear_map.congr_fun h variables {A : Type*} [semiring A] [algebra R A] /-- There is an alg_hom from the trivial square zero extension to any `R`-algebra with a submodule whose products are all zero. See `triv_sq_zero_ext.lift` for this as an equiv. -/ def lift_aux (f : M →ₗ[R] A) (hf : ∀ x y, f x * f y = 0) : tsze R M →ₐ[R] A := alg_hom.of_linear_map ((algebra.linear_map _ _).comp (fst_hom R M).to_linear_map + f.comp (snd_hom R M)) (show algebra_map R _ 1 + f (0 : M) = 1, by rw [map_zero, map_one, add_zero]) (triv_sq_zero_ext.ind $ λ r₁ m₁, triv_sq_zero_ext.ind $ λ r₂ m₂, begin dsimp, simp only [add_zero, zero_add, add_mul, mul_add, smul_mul_smul, hf, smul_zero], rw [←ring_hom.map_mul, linear_map.map_add, ←algebra.commutes _ (f _), ←algebra.smul_def, ←algebra.smul_def, add_right_comm, add_assoc, linear_map.map_smul, linear_map.map_smul], end) @[simp] lemma lift_aux_apply_inr (f : M →ₗ[R] A) (hf : ∀ x y, f x * f y = 0) (m : M) : lift_aux f hf (inr m) = f m := show algebra_map R A 0 + f m = f m, by rw [ring_hom.map_zero, zero_add] @[simp] lemma lift_aux_comp_inr_hom (f : M →ₗ[R] A) (hf : ∀ x y, f x * f y = 0) : (lift_aux f hf).to_linear_map.comp (inr_hom R M) = f := linear_map.ext $ lift_aux_apply_inr f hf /- When applied to `inr` itself, `lift_aux` is the identity. -/ @[simp] lemma lift_aux_inr_hom : lift_aux (inr_hom R M) (inr_mul_inr R) = alg_hom.id R (tsze R M) := alg_hom_ext' $ lift_aux_comp_inr_hom _ _ /-- A universal property of the trivial square-zero extension, providing a unique `triv_sq_zero_ext R M →ₐ[R] A` for every linear map `M →ₗ[R] A` whose range has no non-zero products. This isomorphism is named to match the very similar `complex.lift`. -/ @[simps] def lift : {f : M →ₗ[R] A // ∀ x y, f x * f y = 0} ≃ (tsze R M →ₐ[R] A) := { to_fun := λ f, lift_aux f f.prop, inv_fun := λ F, ⟨F.to_linear_map.comp (inr_hom R M), λ x y, (F.map_mul _ _).symm.trans $ (F.congr_arg $ inr_mul_inr _ _ _).trans F.map_zero⟩, left_inv := λ f, subtype.ext $ lift_aux_comp_inr_hom _ _, right_inv := λ F, alg_hom_ext' $ lift_aux_comp_inr_hom _ _, } end algebra end triv_sq_zero_ext
df6cd6f586854b0cb4fea03d5657744c07b54cb3
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/notation5.lean
59646ea799578c89a0e1c1a0bb74a194766a4c61
[ "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
118
lean
import data.num notation `((` := 1 precedence `(` : 30 notation `))` := 1 notation `,,` := 1 precedence `,` : 10
3ccfec2064e3b3ebb7c001d0b420404106bf6e6b
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/tests/lean/axioms_of.lean
2ff97f5227895d1477b4721e5c869ce763e8c3d1
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
243
lean
import data.finset data.rat print axioms nat.add print "-----" print axioms int.add print "-----" print axioms rat.add print "-----" print axioms finset.union print "-----" print axioms finset.mem print "-----" print axioms finset.union.comm
39b0e45e63c56b9a5e3e3a82e26d25470aa2ae0b
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/tree3.lean
cc2f84bcc889c8ed4509c9a064c61f3fbf420023
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,512
lean
import logic data.prod open eq.ops prod tactic inductive tree (A : Type) := | leaf : A → tree A | node : tree A → tree A → tree A inductive one.{l} : Type.{max 1 l} := star : one set_option pp.universes true namespace tree namespace manual section universe variables l₁ l₂ variable {A : Type.{l₁}} variable (C : tree A → Type.{l₂}) definition below (t : tree A) : Type := tree.rec_on t (λ a, one.{l₂}) (λ t₁ t₂ r₁ r₂, C t₁ × C t₂ × r₁ × r₂) end section universe variables l₁ l₂ variable {A : Type.{l₁}} variable {C : tree A → Type.{l₂}} definition below_rec_on (t : tree A) (H : Π (n : tree A), below C n → C n) : C t := have general : C t × below C t, from tree.rec_on t (λa, (H (leaf a) one.star, one.star)) (λ (l r : tree A) (Hl : C l × below C l) (Hr : C r × below C r), have b : below C (node l r), from (pr₁ Hl, pr₁ Hr, pr₂ Hl, pr₂ Hr), have c : C (node l r), from H (node l r) b, (c, b)), pr₁ general end end manual local abbreviation no_confusion := @tree.no_confusion check no_confusion theorem leaf_ne_tree {A : Type} (a : A) (l r : tree A) : leaf a ≠ node l r := assume h : leaf a = node l r, no_confusion h constant A : Type₁ constants l₁ l₂ r₁ r₂ : tree A axiom node_eq : node l₁ r₁ = node l₂ r₂ check no_confusion node_eq definition tst : (l₁ = l₂ → r₁ = r₂ → l₁ = l₂) → l₁ = l₂ := no_confusion node_eq check tst (λ e₁ e₂, e₁) theorem node.inj1 {A : Type} (l₁ l₂ r₁ r₂ : tree A) : node l₁ r₁ = node l₂ r₂ → l₁ = l₂ := assume h, have trivial : (l₁ = l₂ → r₁ = r₂ → l₁ = l₂) → l₁ = l₂, from no_confusion h, trivial (λ e₁ e₂, e₁) theorem node.inj2 {A : Type} (l₁ l₂ r₁ r₂ : tree A) : node l₁ r₁ = node l₂ r₂ → l₁ = l₂ := begin intro h, apply (no_confusion h), intros, assumption end theorem node.inj3 {A : Type} {l₁ l₂ r₁ r₂ : tree A} (h : node l₁ r₁ = node l₂ r₂) : l₁ = l₂ := begin apply (no_confusion h), assume (e₁ : l₁ = l₂) (e₂ : r₁ = r₂), e₁ end theorem node.inj4 {A : Type} {l₁ l₂ r₁ r₂ : tree A} (h : node l₁ r₁ = node l₂ r₂) : l₁ = l₂ := begin apply (no_confusion h), assume e₁ e₂, e₁ end end tree
12ee6bf8846fab9f9b075319efba0e6433a76850
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/commutator.lean
8ad98a85d3bc5c169b2d5c86af26cd29a4a60a48
[ "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,983
lean
/- Copyright (c) 2021 Jordan Brown, Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jordan Brown, Thomas Browning, Patrick Lutz -/ import data.bracket import group_theory.subgroup.basic import tactic.group /-! # Commutators of Subgroups If `G` is a group and `H₁ H₂ : subgroup G` then the commutator `⁅H₁, H₂⁆ : subgroup G` is the subgroup of `G` generated by the commutators `h₁ * h₂ * h₁⁻¹ * h₂⁻¹`. ## Main definitions * `⁅g₁, g₂⁆` : the commutator of the elements `g₁` and `g₂` (defined by `commutator_element` elsewhere). * `⁅H₁, H₂⁆` : the commutator of the subgroups `H₁` and `H₂`. -/ variables {G G' F : Type*} [group G] [group G'] [monoid_hom_class F G G'] (f : F) {g₁ g₂ g₃ g : G} lemma commutator_element_eq_one_iff_mul_comm : ⁅g₁, g₂⁆ = 1 ↔ g₁ * g₂ = g₂ * g₁ := by rw [commutator_element_def, mul_inv_eq_one, mul_inv_eq_iff_eq_mul] lemma commutator_element_eq_one_iff_commute : ⁅g₁, g₂⁆ = 1 ↔ commute g₁ g₂ := commutator_element_eq_one_iff_mul_comm lemma commute.commutator_eq (h : commute g₁ g₂) : ⁅g₁, g₂⁆ = 1 := commutator_element_eq_one_iff_commute.mpr h variables (g₁ g₂ g₃ g) @[simp] lemma commutator_element_one_right : ⁅g, (1 : G)⁆ = 1 := (commute.one_right g).commutator_eq @[simp] lemma commutator_element_one_left : ⁅(1 : G), g⁆ = 1 := (commute.one_left g).commutator_eq @[simp] lemma commutator_element_self : ⁅g, g⁆ = 1 := (commute.refl g).commutator_eq @[simp] lemma commutator_element_inv : ⁅g₁, g₂⁆⁻¹ = ⁅g₂, g₁⁆ := by simp_rw [commutator_element_def, mul_inv_rev, inv_inv, mul_assoc] lemma map_commutator_element : (f ⁅g₁, g₂⁆ : G') = ⁅f g₁, f g₂⁆ := by simp_rw [commutator_element_def, map_mul f, map_inv f] lemma conjugate_commutator_element : g₃ * ⁅g₁, g₂⁆ * g₃⁻¹ = ⁅g₃ * g₁ * g₃⁻¹, g₃ * g₂ * g₃⁻¹⁆ := map_commutator_element (mul_aut.conj g₃).to_monoid_hom g₁ g₂ namespace subgroup /-- The commutator of two subgroups `H₁` and `H₂`. -/ instance commutator : has_bracket (subgroup G) (subgroup G) := ⟨λ H₁ H₂, closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g}⟩ lemma commutator_def (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g} := rfl variables {g₁ g₂ g₃} {H₁ H₂ H₃ K₁ K₂ : subgroup G} lemma commutator_mem_commutator (h₁ : g₁ ∈ H₁) (h₂ : g₂ ∈ H₂) : ⁅g₁, g₂⁆ ∈ ⁅H₁, H₂⁆ := subset_closure ⟨g₁, h₁, g₂, h₂, rfl⟩ lemma commutator_le : ⁅H₁, H₂⁆ ≤ H₃ ↔ ∀ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ ∈ H₃ := H₃.closure_le.trans ⟨λ h a b c d, h ⟨a, b, c, d, rfl⟩, λ h g ⟨a, b, c, d, h_eq⟩, h_eq ▸ h a b c d⟩ lemma commutator_mono (h₁ : H₁ ≤ K₁) (h₂ : H₂ ≤ K₂) : ⁅H₁, H₂⁆ ≤ ⁅K₁, K₂⁆ := commutator_le.mpr (λ g₁ hg₁ g₂ hg₂, commutator_mem_commutator (h₁ hg₁) (h₂ hg₂)) lemma commutator_eq_bot_iff_le_centralizer : ⁅H₁, H₂⁆ = ⊥ ↔ H₁ ≤ H₂.centralizer := begin rw [eq_bot_iff, commutator_le], refine forall_congr (λ p, forall_congr (λ hp, forall_congr (λ q, forall_congr (λ hq, _)))), rw [mem_bot, commutator_element_eq_one_iff_mul_comm, eq_comm], end /-- **The Three Subgroups Lemma** (via the Hall-Witt identity) -/ lemma commutator_commutator_eq_bot_of_rotate (h1 : ⁅⁅H₂, H₃⁆, H₁⁆ = ⊥) (h2 : ⁅⁅H₃, H₁⁆, H₂⁆ = ⊥) : ⁅⁅H₁, H₂⁆, H₃⁆ = ⊥ := begin simp_rw [commutator_eq_bot_iff_le_centralizer, commutator_le, mem_centralizer_iff_commutator_eq_one, ←commutator_element_def] at h1 h2 ⊢, intros x hx y hy z hz, transitivity x * z * ⁅y, ⁅z⁻¹, x⁻¹⁆⁆⁻¹ * z⁻¹ * y * ⁅x⁻¹, ⁅y⁻¹, z⁆⁆⁻¹ * y⁻¹ * x⁻¹, { group }, { rw [h1 _ (H₂.inv_mem hy) _ hz _ (H₁.inv_mem hx), h2 _ (H₃.inv_mem hz) _ (H₁.inv_mem hx) _ hy], group }, end variables (H₁ H₂) lemma commutator_comm_le : ⁅H₁, H₂⁆ ≤ ⁅H₂, H₁⁆ := commutator_le.mpr (λ g₁ h₁ g₂ h₂, commutator_element_inv g₂ g₁ ▸ ⁅H₂, H₁⁆.inv_mem_iff.mpr (commutator_mem_commutator h₂ h₁)) lemma commutator_comm : ⁅H₁, H₂⁆ = ⁅H₂, H₁⁆ := le_antisymm (commutator_comm_le H₁ H₂) (commutator_comm_le H₂ H₁) section normal instance commutator_normal [h₁ : H₁.normal] [h₂ : H₂.normal] : normal ⁅H₁, H₂⁆ := begin let base : set G := {x | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = x}, change (closure base).normal, suffices h_base : base = group.conjugates_of_set base, { rw h_base, exact subgroup.normal_closure_normal }, refine set.subset.antisymm group.subset_conjugates_of_set (λ a h, _), simp_rw [group.mem_conjugates_of_set_iff, is_conj_iff] at h, rcases h with ⟨b, ⟨c, hc, e, he, rfl⟩, d, rfl⟩, exact ⟨_, h₁.conj_mem c hc d, _, h₂.conj_mem e he d, (conjugate_commutator_element c e d).symm⟩, end lemma commutator_def' [H₁.normal] [H₂.normal] : ⁅H₁, H₂⁆ = normal_closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g} := le_antisymm closure_le_normal_closure (normal_closure_le_normal subset_closure) lemma commutator_le_right [h : H₂.normal] : ⁅H₁, H₂⁆ ≤ H₂ := commutator_le.mpr (λ g₁ h₁ g₂ h₂, H₂.mul_mem (h.conj_mem g₂ h₂ g₁) (H₂.inv_mem h₂)) lemma commutator_le_left [H₁.normal] : ⁅H₁, H₂⁆ ≤ H₁ := commutator_comm H₂ H₁ ▸ commutator_le_right H₂ H₁ @[simp] lemma commutator_bot_left : ⁅(⊥ : subgroup G), H₁⁆ = ⊥ := le_bot_iff.mp (commutator_le_left ⊥ H₁) @[simp] lemma commutator_bot_right : ⁅H₁, ⊥⁆ = (⊥ : subgroup G) := le_bot_iff.mp (commutator_le_right H₁ ⊥) lemma commutator_le_inf [normal H₁] [normal H₂] : ⁅H₁, H₂⁆ ≤ H₁ ⊓ H₂ := le_inf (commutator_le_left H₁ H₂) (commutator_le_right H₁ H₂) end normal lemma map_commutator (f : G →* G') : map f ⁅H₁, H₂⁆ = ⁅map f H₁, map f H₂⁆ := begin simp_rw [le_antisymm_iff, map_le_iff_le_comap, commutator_le, mem_comap, map_commutator_element], split, { intros p hp q hq, exact commutator_mem_commutator (mem_map_of_mem _ hp) (mem_map_of_mem _ hq), }, { rintros _ ⟨p, hp, rfl⟩ _ ⟨q, hq, rfl⟩, rw ← map_commutator_element, exact mem_map_of_mem _ (commutator_mem_commutator hp hq) } end variables {H₁ H₂} lemma commutator_le_map_commutator {f : G →* G'} {K₁ K₂ : subgroup G'} (h₁ : K₁ ≤ H₁.map f) (h₂ : K₂ ≤ H₂.map f) : ⁅K₁, K₂⁆ ≤ ⁅H₁, H₂⁆.map f := (commutator_mono h₁ h₂).trans (ge_of_eq (map_commutator H₁ H₂ f)) variables (H₁ H₂) instance commutator_characteristic [h₁ : characteristic H₁] [h₂ : characteristic H₂] : characteristic ⁅H₁, H₂⁆ := characteristic_iff_le_map.mpr (λ ϕ, commutator_le_map_commutator (characteristic_iff_le_map.mp h₁ ϕ) (characteristic_iff_le_map.mp h₂ ϕ)) lemma commutator_prod_prod (K₁ K₂ : subgroup G') : ⁅H₁.prod K₁, H₂.prod K₂⁆ = ⁅H₁, H₂⁆.prod ⁅K₁, K₂⁆ := begin apply le_antisymm, { rw commutator_le, rintros ⟨p₁, p₂⟩ ⟨hp₁, hp₂⟩ ⟨q₁, q₂⟩ ⟨hq₁, hq₂⟩, exact ⟨commutator_mem_commutator hp₁ hq₁, commutator_mem_commutator hp₂ hq₂⟩ }, { rw prod_le_iff, split; { rw map_commutator, apply commutator_mono; simp [le_prod_iff, map_map, monoid_hom.fst_comp_inl, monoid_hom.snd_comp_inl, monoid_hom.fst_comp_inr, monoid_hom.snd_comp_inr ], }, } end /-- The commutator of direct product is contained in the direct product of the commutators. See `commutator_pi_pi_of_finite` for equality given `fintype η`. -/ lemma commutator_pi_pi_le {η : Type*} {Gs : η → Type*} [∀ i, group (Gs i)] (H K : Π i, subgroup (Gs i)) : ⁅subgroup.pi set.univ H, subgroup.pi set.univ K⁆ ≤ subgroup.pi set.univ (λ i, ⁅H i, K i⁆) := commutator_le.mpr $ λ p hp q hq i hi, commutator_mem_commutator (hp i hi) (hq i hi) /-- The commutator of a finite direct product is contained in the direct product of the commutators. -/ lemma commutator_pi_pi_of_finite {η : Type*} [finite η] {Gs : η → Type*} [∀ i, group (Gs i)] (H K : Π i, subgroup (Gs i)) : ⁅subgroup.pi set.univ H, subgroup.pi set.univ K⁆ = subgroup.pi set.univ (λ i, ⁅H i, K i⁆) := begin classical, apply le_antisymm (commutator_pi_pi_le H K), { rw pi_le_iff, intros i hi, rw map_commutator, apply commutator_mono; { rw le_pi_iff, intros j hj, rintros _ ⟨_, ⟨x, hx, rfl⟩, rfl⟩, by_cases h : j = i, { subst h, simpa using hx, }, { simp [h, one_mem] }, }, }, end end subgroup
1f190bd9d38793aeed36e68fc962a0387a2c28fc
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/hints/category_theory/exercise1/hint1.lean
518f7dfe6161007dc382d0da6f698744c30e7eca
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
718
lean
import category_theory.isomorphism import category_theory.yoneda open category_theory open opposite variables {C : Type*} [category C] def iso_of_hom_iso_attempt_1 (X Y : C) (h : yoneda.obj X ≅ yoneda.obj Y) : X ≅ Y := -- We're trying to construct an isomorphism, so our first task is to write a stub for the structure: -- { } sorry /- This says: ``` invalid structure value { ... }, field 'hom' was not provided invalid structure value { ... }, field 'inv' was not provided ``` so let's try again: -/ def iso_of_hom_iso_attempt_2 (X Y : C) (h : yoneda.obj X ≅ yoneda.obj Y) : X ≅ Y := { hom := sorry, inv := sorry, } /- It's time to think about the maths, but lets do that in the next hint file. -/
88f0b7908d5708446192cd819333bad0c1fe77a1
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/asymptotics/theta.lean
f5cca8f17b8c1b12a76961335a9b126840f54a36
[ "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,957
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.asymptotics.asymptotics /-! # Asymptotic equivalence up to a constant In this file we define `asymptotics.is_Theta l f g` (notation: `f =Θ[l] g`) as `f =O[l] g ∧ g =O[l] f`, then prove basic properties of this equivalence relation. -/ open filter open_locale topological_space namespace asymptotics variables {α : Type*} {β : Type*} {E : Type*} {F : Type*} {G : Type*} {E' : Type*} {F' : Type*} {G' : Type*} {E'' : Type*} {F'' : Type*} {G'' : Type*} {R : Type*} {R' : Type*} {𝕜 : Type*} {𝕜' : Type*} variables [has_norm E] [has_norm F] [has_norm G] variables [semi_normed_group E'] [semi_normed_group F'] [semi_normed_group G'] variables [normed_group E''] [normed_group F''] [normed_group G''] variables [semi_normed_ring R] [semi_normed_ring R'] variables [normed_field 𝕜] [normed_field 𝕜'] variables {c c' c₁ c₂ : ℝ} {f : α → E} {g : α → F} {k : α → G} variables {f' : α → E'} {g' : α → F'} {k' : α → G'} variables {f'' : α → E''} {g'' : α → F''} variables {l l' : filter α} /-- We say that `f` is `Θ(g)` along a filter `l` (notation: `f =Θ[l] g`) if `f =O[l] g` and `g =O[l] f`. -/ def is_Theta (l : filter α) (f : α → E) (g : α → F) : Prop := is_O l f g ∧ is_O l g f notation f ` =Θ[`:100 l `] ` g:100 := is_Theta l f g lemma is_O.antisymm (h₁ : f =O[l] g) (h₂ : g =O[l] f) : f =Θ[l] g := ⟨h₁, h₂⟩ @[refl] lemma is_Theta_refl (f : α → E) (l : filter α) : f =Θ[l] f := ⟨is_O_refl _ _, is_O_refl _ _⟩ lemma is_Theta_rfl : f =Θ[l] f := is_Theta_refl _ _ @[symm] lemma is_Theta.symm (h : f =Θ[l] g) : g =Θ[l] f := h.symm lemma is_Theta_comm : f =Θ[l] g ↔ g =Θ[l] f := ⟨λ h, h.symm, λ h, h.symm⟩ @[trans] lemma is_Theta.trans {f : α → E} {g : α → F'} {k : α → G} (h₁ : f =Θ[l] g) (h₂ : g =Θ[l] k) : f =Θ[l] k := ⟨h₁.1.trans h₂.1, h₂.2.trans h₁.2⟩ @[trans] lemma is_O.trans_is_Theta {f : α → E} {g : α → F'} {k : α → G} (h₁ : f =O[l] g) (h₂ : g =Θ[l] k) : f =O[l] k := h₁.trans h₂.1 @[trans] lemma is_Theta.trans_is_O {f : α → E} {g : α → F'} {k : α → G} (h₁ : f =Θ[l] g) (h₂ : g =O[l] k) : f =O[l] k := h₁.1.trans h₂ @[trans] lemma is_o.trans_is_Theta {f : α → E} {g : α → F} {k : α → G'} (h₁ : f =o[l] g) (h₂ : g =Θ[l] k) : f =o[l] k := h₁.trans_is_O h₂.1 @[trans] lemma is_Theta.trans_is_o {f : α → E} {g : α → F'} {k : α → G} (h₁ : f =Θ[l] g) (h₂ : g =o[l] k) : f =o[l] k := h₁.1.trans_is_o h₂ @[trans] lemma is_Theta.trans_eventually_eq {f : α → E} {g₁ g₂ : α → F} (h : f =Θ[l] g₁) (hg : g₁ =ᶠ[l] g₂) : f =Θ[l] g₂ := ⟨h.1.trans_eventually_eq hg, hg.symm.trans_is_O h.2⟩ @[trans] lemma _root_.filter.eventually_eq.trans_is_Theta {f₁ f₂ : α → E} {g : α → F} (hf : f₁ =ᶠ[l] f₂) (h : f₂ =Θ[l] g) : f₁ =Θ[l] g := ⟨hf.trans_is_O h.1, h.2.trans_eventually_eq hf.symm⟩ @[simp] lemma is_Theta_norm_left : (λ x, ∥f' x∥) =Θ[l] g ↔ f' =Θ[l] g := by simp [is_Theta] @[simp] lemma is_Theta_norm_right : f =Θ[l] (λ x, ∥g' x∥) ↔ f =Θ[l] g' := by simp [is_Theta] alias is_Theta_norm_left ↔ is_Theta.of_norm_left is_Theta.norm_left alias is_Theta_norm_right ↔ is_Theta.of_norm_right is_Theta.norm_right lemma is_Theta_of_norm_eventually_eq (h : (λ x, ∥f x∥) =ᶠ[l] (λ x, ∥g x∥)) : f =Θ[l] g := ⟨is_O.of_bound 1 $ by simpa only [one_mul] using h.le, is_O.of_bound 1 $ by simpa only [one_mul] using h.symm.le⟩ lemma is_Theta_of_norm_eventually_eq' {g : α → ℝ} (h : (λ x, ∥f' x∥) =ᶠ[l] g) : f' =Θ[l] g := is_Theta_of_norm_eventually_eq $ h.mono $ λ x hx, by simp only [← hx, norm_norm] lemma is_Theta.is_o_congr_left (h : f' =Θ[l] g') : f' =o[l] k ↔ g' =o[l] k := ⟨h.symm.trans_is_o, h.trans_is_o⟩ lemma is_Theta.is_o_congr_right (h : g' =Θ[l] k') : f =o[l] g' ↔ f =o[l] k' := ⟨λ H, H.trans_is_Theta h, λ H, H.trans_is_Theta h.symm⟩ lemma is_Theta.is_O_congr_left (h : f' =Θ[l] g') : f' =O[l] k ↔ g' =O[l] k := ⟨h.symm.trans_is_O, h.trans_is_O⟩ lemma is_Theta.is_O_congr_right (h : g' =Θ[l] k') : f =O[l] g' ↔ f =O[l] k' := ⟨λ H, H.trans_is_Theta h, λ H, H.trans_is_Theta h.symm⟩ lemma is_Theta.mono (h : f =Θ[l] g) (hl : l' ≤ l) : f =Θ[l'] g := ⟨h.1.mono hl, h.2.mono hl⟩ lemma is_Theta.sup (h : f' =Θ[l] g') (h' : f' =Θ[l'] g') : f' =Θ[l ⊔ l'] g' := ⟨h.1.sup h'.1, h.2.sup h'.2⟩ @[simp] lemma is_Theta_sup : f' =Θ[l ⊔ l'] g' ↔ f' =Θ[l] g' ∧ f' =Θ[l'] g' := ⟨λ h, ⟨h.mono le_sup_left, h.mono le_sup_right⟩, λ h, h.1.sup h.2⟩ lemma is_Theta.eq_zero_iff (h : f'' =Θ[l] g'') : ∀ᶠ x in l, f'' x = 0 ↔ g'' x = 0 := h.1.eq_zero_imp.mp $ h.2.eq_zero_imp.mono $ λ x, iff.intro lemma is_Theta.tendsto_zero_iff (h : f'' =Θ[l] g'') : tendsto f'' l (𝓝 0) ↔ tendsto g'' l (𝓝 0) := by simp only [← is_o_one_iff ℝ, h.is_o_congr_left] lemma is_Theta.tendsto_norm_at_top_iff (h : f' =Θ[l] g') : tendsto (norm ∘ f') l at_top ↔ tendsto (norm ∘ g') l at_top := by simp only [← is_o_const_left_of_ne (@one_ne_zero ℝ _ _), h.is_o_congr_right] lemma is_Theta.is_bounded_under_le_iff (h : f' =Θ[l] g') : is_bounded_under (≤) l (norm ∘ f') ↔ is_bounded_under (≤) l (norm ∘ g') := by simp only [← is_O_const_of_ne (@one_ne_zero ℝ _ _), h.is_O_congr_left] lemma is_Theta.smul [normed_space 𝕜 E'] [normed_space 𝕜' F'] {f₁ : α → 𝕜} {f₂ : α → 𝕜'} {g₁ : α → E'} {g₂ : α → F'} (hf : f₁ =Θ[l] f₂) (hg : g₁ =Θ[l] g₂) : (λ x, f₁ x • g₁ x) =Θ[l] (λ x, f₂ x • g₂ x) := ⟨hf.1.smul hg.1, hf.2.smul hg.2⟩ lemma is_Theta.mul {f₁ f₂ : α → 𝕜} {g₁ g₂ : α → 𝕜'} (h₁ : f₁ =Θ[l] g₁) (h₂ : f₂ =Θ[l] g₂) : (λ x, f₁ x * f₂ x) =Θ[l] (λ x, g₁ x * g₂ x) := h₁.smul h₂ lemma is_Theta.inv {f : α → 𝕜} {g : α → 𝕜'} (h : f =Θ[l] g) : (λ x, (f x)⁻¹) =Θ[l] (λ x, (g x)⁻¹) := ⟨h.2.inv_rev h.1.eq_zero_imp, h.1.inv_rev h.2.eq_zero_imp⟩ @[simp] lemma is_Theta_inv {f : α → 𝕜} {g : α → 𝕜'} : (λ x, (f x)⁻¹) =Θ[l] (λ x, (g x)⁻¹) ↔ f =Θ[l] g := ⟨λ h, by simpa only [inv_inv] using h.inv, is_Theta.inv⟩ lemma is_Theta.div {f₁ f₂ : α → 𝕜} {g₁ g₂ : α → 𝕜'} (h₁ : f₁ =Θ[l] g₁) (h₂ : f₂ =Θ[l] g₂) : (λ x, f₁ x / f₂ x) =Θ[l] (λ x, g₁ x / g₂ x) := by simpa only [div_eq_mul_inv] using h₁.mul h₂.inv lemma is_Theta.pow {f : α → 𝕜} {g : α → 𝕜'} (h : f =Θ[l] g) (n : ℕ) : (λ x, (f x) ^ n) =Θ[l] (λ x, (g x) ^ n) := ⟨h.1.pow n, h.2.pow n⟩ lemma is_Theta.zpow {f : α → 𝕜} {g : α → 𝕜'} (h : f =Θ[l] g) (n : ℤ) : (λ x, (f x) ^ n) =Θ[l] (λ x, (g x) ^ n) := begin cases n, { simpa only [zpow_of_nat] using h.pow _ }, { simpa only [zpow_neg_succ_of_nat] using (h.pow _).inv } end lemma is_Theta_const_const {c₁ : E''} {c₂ : F''} (h₁ : c₁ ≠ 0) (h₂ : c₂ ≠ 0) : (λ x : α, c₁) =Θ[l] (λ x, c₂) := ⟨is_O_const_const _ h₂ _, is_O_const_const _ h₁ _⟩ @[simp] lemma is_Theta_const_const_iff [ne_bot l] {c₁ : E''} {c₂ : F''} : (λ x : α, c₁) =Θ[l] (λ x, c₂) ↔ (c₁ = 0 ↔ c₂ = 0) := by simpa only [is_Theta, is_O_const_const_iff, ← iff_def] using iff.comm @[simp] lemma is_Theta_zero_left : (λ x, (0 : E')) =Θ[l] g'' ↔ g'' =ᶠ[l] 0 := by simp only [is_Theta, is_O_zero, is_O_zero_right_iff, true_and] @[simp] lemma is_Theta_zero_right : f'' =Θ[l] (λ x, (0 : F')) ↔ f'' =ᶠ[l] 0 := is_Theta_comm.trans is_Theta_zero_left lemma is_Theta_const_smul_left [normed_space 𝕜 E'] {c : 𝕜} (hc : c ≠ 0) : (λ x, c • f' x) =Θ[l] g ↔ f' =Θ[l] g := and_congr (is_O_const_smul_left hc) (is_O_const_smul_right hc) alias is_Theta_const_smul_left ↔ is_Theta.of_const_smul_left is_Theta.const_smul_left lemma is_Theta_const_smul_right [normed_space 𝕜 F'] {c : 𝕜} (hc : c ≠ 0) : f =Θ[l] (λ x, c • g' x) ↔ f =Θ[l] g' := and_congr (is_O_const_smul_right hc) (is_O_const_smul_left hc) alias is_Theta_const_smul_right ↔ is_Theta.of_const_smul_right is_Theta.const_smul_right lemma is_Theta_const_mul_left {c : 𝕜} {f : α → 𝕜} (hc : c ≠ 0) : (λ x, c * f x) =Θ[l] g ↔ f =Θ[l] g := by simpa only [← smul_eq_mul] using is_Theta_const_smul_left hc alias is_Theta_const_mul_left ↔ is_Theta.of_const_mul_left is_Theta.const_mul_left lemma is_Theta_const_mul_right {c : 𝕜} {g : α → 𝕜} (hc : c ≠ 0) : f =Θ[l] (λ x, c * g x) ↔ f =Θ[l] g := by simpa only [← smul_eq_mul] using is_Theta_const_smul_right hc alias is_Theta_const_mul_right ↔ is_Theta.of_const_mul_right is_Theta.const_mul_right end asymptotics
d7f8ec1e01c5dbe0be9c28f03fed469d3ece45f1
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/equivalence.lean
008fecb5bc77443cf4f4463e615987a747515498
[ "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
14,346
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.fully_faithful import category_theory.whiskering import category_theory.natural_isomorphism import tactic.slice import tactic.converter.interactive namespace category_theory open category_theory.functor nat_iso category universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other words the composite `F ⟶ FGF ⟶ F` is the identity. The triangle equation is written as a family of equalities between morphisms, it is more complicated if we write it as an equality of natural transformations, because then we would have to insert natural transformations like `F ⟶ F1`. -/ structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] := mk' :: (functor : C ⥤ D) (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ functor ⋙ inverse) (counit_iso : inverse ⋙ functor ≅ 𝟭 D) (functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫ counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously) restate_axiom equivalence.functor_unit_iso_comp' infixr ` ≌ `:10 := equivalence variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 namespace equivalence @[simp] def unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom @[simp] def counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom @[simp] def unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv @[simp] def counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv lemma unit_def (e : C ≌ D) : e.unit_iso.hom = e.unit := rfl lemma counit_def (e : C ≌ D) : e.counit_iso.hom = e.counit := rfl lemma unit_inv_def (e : C ≌ D) : e.unit_iso.inv = e.unit_inv := rfl lemma counit_inv_def (e : C ≌ D) : e.counit_iso.inv = e.counit_inv := rfl @[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) := e.functor_unit_iso_comp X @[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) : e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) := begin erw [iso.inv_eq_inv (e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)], exact e.functor_unit_comp X end lemma functor_unit (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) = e.counit_inv.app (e.functor.obj X) := by { erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl } lemma counit_functor (e : C ≌ D) (X : C) : e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) := by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl } /-- The other triangle equality. The proof follows the following proof in Globular: http://globular.science/1905.001 -/ @[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) := begin rw [←id_comp _ (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp, ←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)), app_hom, app_inv, unit_def, unit_inv_def], slice_lhs 2 3 { erw [e.unit.naturality] }, slice_lhs 1 2 { erw [e.unit.naturality] }, slice_lhs 4 4 { rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] }, slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality], erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] }, slice_lhs 3 4 { erw [e.unit_inv.naturality] }, slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 3 4 { erw [←e.unit_inv.naturality] }, slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality, (e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl end @[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) : e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) := begin erw [iso.inv_eq_inv (e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)], exact e.unit_inverse_comp Y end lemma unit_inverse (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) := by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl } lemma inverse_counit (e : C ≌ D) (Y : D) : e.inverse.map (e.counit.app Y) = e.unit_inv.app (e.inverse.obj Y) := by { erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl } @[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y := (nat_iso.naturality_2 (e.counit_iso) f).symm @[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y := (nat_iso.naturality_1 (e.unit_iso) f).symm section -- In this section we convert an arbitrary equivalence to a half-adjoint equivalence. variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) def adjointify_η : 𝟭 C ≅ F ⋙ G := calc 𝟭 C ≅ F ⋙ G : η ... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm ... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G) ... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G) ... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm ... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G) ... ≅ F ⋙ G : left_unitor (F ⋙ G) lemma adjointify_η_ε (X : C) : F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) := begin dsimp [adjointify_η], simp, have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this, rw [←assoc _ _ _ (F.map _)], have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this, have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this, rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this] end end protected definition mk (F : C ⥤ D) (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D := ⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ omit 𝒟 @[refl] def refl : C ≌ C := equivalence.mk (𝟭 C) (𝟭 C) (iso.refl _) (iso.refl _) include 𝒟 @[symm] def symm (e : C ≌ D) : D ≌ C := ⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩ variables {E : Type u₃} [ℰ : category.{v₃} E] include ℰ @[trans] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E := begin apply equivalence.mk (e.functor ⋙ f.functor) (f.inverse ⋙ e.inverse), { refine iso.trans e.unit_iso _, exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) }, { refine iso.trans _ f.counit_iso, exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor) } end def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor @[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) := by { dsimp [fun_inv_id_assoc], tidy } @[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) := by { dsimp [fun_inv_id_assoc], tidy } def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor @[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) := by { dsimp [inv_fun_id_assoc], tidy } @[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) := by { dsimp [inv_fun_id_assoc], tidy } end equivalence /-- A functor that is part of a (half) adjoint equivalence -/ class is_equivalence (F : C ⥤ D) := mk' :: (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ F ⋙ inverse) (counit_iso : inverse ⋙ F ≅ 𝟭 D) (functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫ counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously) restate_axiom is_equivalence.functor_unit_iso_comp' namespace is_equivalence instance of_equivalence (F : C ≌ D) : is_equivalence F.functor := { ..F } instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse := is_equivalence.of_equivalence F.symm open equivalence protected definition mk {F : C ⥤ D} (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F := ⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ end is_equivalence namespace functor def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D := ⟨F, is_equivalence.inverse F, is_equivalence.unit_iso F, is_equivalence.counit_iso F, is_equivalence.functor_unit_iso_comp F⟩ omit 𝒟 instance is_equivalence_refl : is_equivalence (𝟭 C) := is_equivalence.of_equivalence equivalence.refl include 𝒟 def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C := is_equivalence.inverse F instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv := is_equivalence.of_equivalence F.as_equivalence.symm def fun_inv_id (F : C ⥤ D) [is_equivalence F] : F ⋙ F.inv ≅ 𝟭 C := (is_equivalence.unit_iso F).symm def inv_fun_id (F : C ⥤ D) [is_equivalence F] : F.inv ⋙ F ≅ 𝟭 D := is_equivalence.counit_iso F variables {E : Type u₃} [ℰ : category.{v₃} E] include ℰ instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] : is_equivalence (F ⋙ G) := is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G)) end functor namespace is_equivalence @[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) : F.map (F.inv.map f) = (F.inv_fun_id.hom.app X) ≫ f ≫ (F.inv_fun_id.inv.app Y) := begin erw [nat_iso.naturality_2], refl end @[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) : F.inv.map (F.map f) = (F.fun_inv_id.hom.app X) ≫ f ≫ (F.fun_inv_id.inv.app Y) := begin erw [nat_iso.naturality_2], refl end -- We should probably restate many of the lemmas about `equivalence` for `is_equivalence`, -- but these are the only ones I need for now. @[simp] lemma functor_unit_comp (E : C ⥤ D) [is_equivalence E] (Y) : E.map (((is_equivalence.unit_iso E).hom).app Y) ≫ ((is_equivalence.counit_iso E).hom).app (E.obj Y) = 𝟙 _ := equivalence.functor_unit_comp (E.as_equivalence) Y @[simp] lemma counit_inv_functor_comp (E : C ⥤ D) [is_equivalence E] (Y) : ((is_equivalence.counit_iso E).inv).app (E.obj Y) ≫ E.map (((is_equivalence.unit_iso E).inv).app Y) = 𝟙 _ := eq_of_inv_eq_inv (functor_unit_comp _ _) end is_equivalence class ess_surj (F : C ⥤ D) := (obj_preimage (d : D) : C) (iso' (d : D) : F.obj (obj_preimage d) ≅ d . obviously) restate_axiom ess_surj.iso' namespace functor def obj_preimage (F : C ⥤ D) [ess_surj F] (d : D) : C := ess_surj.obj_preimage.{v₁ v₂} F d def fun_obj_preimage_iso (F : C ⥤ D) [ess_surj F] (d : D) : F.obj (F.obj_preimage d) ≅ d := ess_surj.iso F d end functor namespace equivalence def ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F := ⟨ λ Y : D, F.inv.obj Y, λ Y : D, (F.inv_fun_id.app Y) ⟩ @[priority 100] -- see Note [lower instance priority] instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F := { injectivity' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w, simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p end }. @[priority 100] -- see Note [lower instance priority] instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F := { preimage := λ X Y f, (F.fun_inv_id.app X).inv ≫ (F.inv.map f) ≫ (F.fun_inv_id.app Y).hom, witness' := λ X Y f, begin apply F.inv.injectivity, /- obviously can finish from here... -/ dsimp, simp, dsimp, slice_lhs 4 6 { rw [←functor.map_comp, ←functor.map_comp], rw [←is_equivalence.fun_inv_map], }, slice_lhs 1 2 { simp }, dsimp, simp, slice_lhs 2 4 { rw [←functor.map_comp, ←functor.map_comp], erw [nat_iso.naturality_2], }, erw [nat_iso.naturality_1], refl end }. @[simp] private def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C := { obj := λ X, F.obj_preimage X, map := λ X Y f, F.preimage ((F.fun_obj_preimage_iso X).hom ≫ f ≫ (F.fun_obj_preimage_iso Y).inv), map_id' := λ X, begin apply F.injectivity, tidy end, map_comp' := λ X Y Z f g, by apply F.injectivity; simp }. def equivalence_of_fully_faithfully_ess_surj (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F := is_equivalence.mk (equivalence_inverse F) (nat_iso.of_components (λ X, (preimage_iso $ F.fun_obj_preimage_iso $ F.obj X).symm) (λ X Y f, by { apply F.injectivity, obviously })) (nat_iso.of_components (λ Y, F.fun_obj_preimage_iso Y) (by obviously)) end equivalence end category_theory
2a7724ed354aaa0db3d0298a197e1f2325221fbe
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/lcnfTypes.lean
ef514d113a6bc8b6cea0305984f2350b0fc581df
[ "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
3,767
lean
import Lean notation "◾" => lcErased notation "⊤" => lcAny open Lean Compiler Meta def test (declName : Name) : MetaM Unit := do IO.println s!"{declName} : {← ppExpr (← getDeclLCNFType declName)}" inductive Vec (α : Type u) : Nat → Type u | nil : Vec α 0 | cons : α → Vec α n → Vec α (n+1) def Vec.zip : Vec α n → Vec β n → Vec (α × β) n | .cons a as, .cons b bs => .cons (a, b) (zip as bs) | .nil, .nil => .nil def Tuple (α : Type u) : Nat → Type u | 0 => PUnit | 1 => α | n+2 => α × Tuple α n def mkConstTuple (a : α) : (n : Nat) → Tuple α n | 0 => ⟨⟩ | 1 => a | n+2 => (a, mkConstTuple a n) #eval test ``Vec.zip #eval test ``mkConstTuple #eval test ``Fin.add #eval test ``Vec.cons #eval test ``Eq.rec #eval test ``GetElem.getElem inductive HList {α : Type v} (β : α → Type u) : List α → Type (max u v) | nil : HList β [] | cons : β i → HList β is → HList β (i::is) infix:67 " :: " => HList.cons inductive Member : α → List α → Type _ | head : Member a (a::as) | tail : Member a bs → Member a (b::bs) def HList.get : HList β is → Member i is → β i | a::as, .head => a | _::as, .tail h => as.get h inductive Ty where | nat | fn : Ty → Ty → Ty abbrev Ty.denote : Ty → Type | nat => Nat | fn a b => a.denote → b.denote inductive Term : List Ty → Ty → Type | var : Member ty ctx → Term ctx ty | const : Nat → Term ctx .nat | plus : Term ctx .nat → Term ctx .nat → Term ctx .nat | app : Term ctx (.fn dom ran) → Term ctx dom → Term ctx ran | lam : Term (dom :: ctx) ran → Term ctx (.fn dom ran) | «let» : Term ctx ty₁ → Term (ty₁ :: ctx) ty₂ → Term ctx ty₂ def Term.denote : Term ctx ty → HList Ty.denote ctx → ty.denote | var h, env => env.get h | const n, _ => n | plus a b, env => a.denote env + b.denote env | app f a, env => f.denote env (a.denote env) | lam b, env => fun x => b.denote (x :: env) | «let» a b, env => b.denote (a.denote env :: env) def Term.constFold : Term ctx ty → Term ctx ty | const n => const n | var h => var h | app f a => app f.constFold a.constFold | lam b => lam b.constFold | «let» a b => «let» a.constFold b.constFold | plus a b => match a.constFold, b.constFold with | const n, const m => const (n+m) | a', b' => plus a' b' #eval test ``Term.constFold #eval test ``Term.denote #eval test ``HList.get #eval test ``Member.head #eval test ``Ty.denote #eval test ``MonadControl.liftWith #eval test ``MonadControl.restoreM #eval test ``Decidable.casesOn #eval test ``getConstInfo #eval test ``instMonadMetaM #eval test ``Lean.Meta.inferType #eval test ``Elab.Term.elabTerm #eval test ``Nat.add structure Magma where carrier : Type mul : carrier → carrier → carrier #eval test ``Magma.mul def weird1 (c : Bool) : (cond c List Array) Nat := match c with | true => [] | false => #[] #eval test ``weird1 def compatible (declName₁ declName₂ : Name) : MetaM Unit := do let type₁ ← getDeclLCNFType declName₁ let type₂ ← getDeclLCNFType declName₂ unless compatibleTypes type₁ type₂ do throwError "{declName₁} : {← ppExpr type₁}\ntype is not compatible with\n{declName₂} : {← ppExpr type₂}" axiom monadList₁.{u} : Monad List.{u} axiom monadList₂.{u} : Monad (fun α : Type u => List α) set_option pp.all true #eval compatible ``monadList₁ ``monadList₂ axiom lamAny₁ (c : Bool) : Monad (fun α : Type => cond c (List α) (Array α)) axiom lamAny₂ (c : Bool) : Monad (cond c List.{0} Array.{0}) #eval test ``lamAny₁ #eval test ``lamAny₂ #eval compatible ``lamAny₁ ``lamAny₂
6fe496890089c54b98af62e2e3c7cb7b74e75e97
6e41ee3ac9b96e8980a16295cc21f131e731884f
/hott/algebra/group.hlean
b5a869c55764078830771c4b0b894b68b52b44a9
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,215
hlean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.group Authors: Jeremy Avigad, Leonardo de Moura Various multiplicative and additive structures. Partially modeled on Isabelle's library. -/ import algebra.binary open eq truncation binary -- note: ⁻¹ will be overloaded namespace path_algebra variable {A : Type} /- overloaded symbols -/ structure has_mul [class] (A : Type) := (mul : A → A → A) structure has_add [class] (A : Type) := (add : A → A → A) structure has_one [class] (A : Type) := (one : A) structure has_zero [class] (A : Type) := (zero : A) structure has_inv [class] (A : Type) := (inv : A → A) structure has_neg [class] (A : Type) := (neg : A → A) infixl `*` := has_mul.mul infixl `+` := has_add.add postfix `⁻¹` := has_inv.inv prefix `-` := has_neg.neg notation 1 := !has_one.one notation 0 := !has_zero.zero /- semigroup -/ structure semigroup [class] (A : Type) extends has_mul A := (carrier_hset : is_hset A) (mul_assoc : ∀a b c, mul (mul a b) c = mul a (mul b c)) theorem mul_assoc [s : semigroup A] (a b c : A) : a * b * c = a * (b * c) := !semigroup.mul_assoc structure comm_semigroup [class] (A : Type) extends semigroup A := (mul_comm : ∀a b, mul a b = mul b a) theorem mul_comm [s : comm_semigroup A] (a b : A) : a * b = b * a := !comm_semigroup.mul_comm theorem mul_left_comm [s : comm_semigroup A] (a b c : A) : a * (b * c) = b * (a * c) := binary.left_comm (@mul_comm A s) (@mul_assoc A s) a b c theorem mul_right_comm [s : comm_semigroup A] (a b c : A) : (a * b) * c = (a * c) * b := binary.right_comm (@mul_comm A s) (@mul_assoc A s) a b c structure left_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_left_cancel : ∀a b c, mul a b = mul a c → b = c) theorem mul_left_cancel [s : left_cancel_semigroup A] {a b c : A} : a * b = a * c → b = c := !left_cancel_semigroup.mul_left_cancel structure right_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_right_cancel : ∀a b c, mul a b = mul c b → a = c) theorem mul_right_cancel [s : right_cancel_semigroup A] {a b c : A} : a * b = c * b → a = c := !right_cancel_semigroup.mul_right_cancel /- additive semigroup -/ structure add_semigroup [class] (A : Type) extends has_add A := (add_assoc : ∀a b c, add (add a b) c = add a (add b c)) theorem add_assoc [s : add_semigroup A] (a b c : A) : a + b + c = a + (b + c) := !add_semigroup.add_assoc structure add_comm_semigroup [class] (A : Type) extends add_semigroup A := (add_comm : ∀a b, add a b = add b a) theorem add_comm [s : add_comm_semigroup A] (a b : A) : a + b = b + a := !add_comm_semigroup.add_comm theorem add_left_comm [s : add_comm_semigroup A] (a b c : A) : a + (b + c) = b + (a + c) := binary.left_comm (@add_comm A s) (@add_assoc A s) a b c theorem add_right_comm [s : add_comm_semigroup A] (a b c : A) : (a + b) + c = (a + c) + b := binary.right_comm (@add_comm A s) (@add_assoc A s) a b c structure add_left_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_left_cancel : ∀a b c, add a b = add a c → b = c) theorem add_left_cancel [s : add_left_cancel_semigroup A] {a b c : A} : a + b = a + c → b = c := !add_left_cancel_semigroup.add_left_cancel structure add_right_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_right_cancel : ∀a b c, add a b = add c b → a = c) theorem add_right_cancel [s : add_right_cancel_semigroup A] {a b c : A} : a + b = c + b → a = c := !add_right_cancel_semigroup.add_right_cancel /- monoid -/ structure monoid [class] (A : Type) extends semigroup A, has_one A := (mul_left_id : ∀a, mul one a = a) (mul_right_id : ∀a, mul a one = a) theorem mul_left_id [s : monoid A] (a : A) : 1 * a = a := !monoid.mul_left_id theorem mul_right_id [s : monoid A] (a : A) : a * 1 = a := !monoid.mul_right_id structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A /- additive monoid -/ structure add_monoid [class] (A : Type) extends add_semigroup A, has_zero A := (add_left_id : ∀a, add zero a = a) (add_right_id : ∀a, add a zero = a) theorem add_left_id [s : add_monoid A] (a : A) : 0 + a = a := !add_monoid.add_left_id theorem add_right_id [s : add_monoid A] (a : A) : a + 0 = a := !add_monoid.add_right_id structure add_comm_monoid [class] (A : Type) extends add_monoid A, add_comm_semigroup A /- group -/ structure group [class] (A : Type) extends monoid A, has_inv A := (mul_left_inv : ∀a, mul (inv a) a = one) -- Note: with more work, we could derive the axiom mul_left_id section group variable [s : group A] include s theorem mul_left_inv (a : A) : a⁻¹ * a = 1 := !group.mul_left_inv theorem inv_mul_cancel_left (a b : A) : a⁻¹ * (a * b) = b := calc a⁻¹ * (a * b) = a⁻¹ * a * b : mul_assoc ... = 1 * b : mul_left_inv ... = b : mul_left_id theorem inv_mul_cancel_right (a b : A) : a * b⁻¹ * b = a := calc a * b⁻¹ * b = a * (b⁻¹ * b) : mul_assoc ... = a * 1 : mul_left_inv ... = a : mul_right_id theorem inv_unique {a b : A} (H : a * b = 1) : a⁻¹ = b := calc a⁻¹ = a⁻¹ * 1 : mul_right_id ... = a⁻¹ * (a * b) : H ... = b : inv_mul_cancel_left theorem inv_one : 1⁻¹ = 1 := inv_unique (mul_left_id 1) theorem inv_inv (a : A) : (a⁻¹)⁻¹ = a := inv_unique (mul_left_inv a) theorem inv_inj {a b : A} (H : a⁻¹ = b⁻¹) : a = b := calc a = (a⁻¹)⁻¹ : inv_inv ... = b : inv_unique (H⁻¹ ▹ (mul_left_inv _)) --theorem inv_eq_inv_iff_eq (a b : A) : a⁻¹ = b⁻¹ ↔ a = b := --iff.intro (assume H, inv_inj H) (assume H, congr_arg _ H) --theorem inv_eq_one_iff_eq_one (a b : A) : a⁻¹ = 1 ↔ a = 1 := --inv_one ▹ !inv_eq_inv_iff_eq theorem eq_inv_imp_eq_inv {a b : A} (H : a = b⁻¹) : b = a⁻¹ := H⁻¹ ▹ (inv_inv b)⁻¹ --theorem eq_inv_iff_eq_inv (a b : A) : a = b⁻¹ ↔ b = a⁻¹ := --iff.intro !eq_inv_imp_eq_inv !eq_inv_imp_eq_inv theorem mul_right_inv (a : A) : a * a⁻¹ = 1 := calc a * a⁻¹ = (a⁻¹)⁻¹ * a⁻¹ : inv_inv ... = 1 : mul_left_inv theorem mul_inv_cancel_left (a b : A) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = a * a⁻¹ * b : mul_assoc ... = 1 * b : mul_right_inv ... = b : mul_left_id theorem mul_inv_cancel_right (a b : A) : a * b * b⁻¹ = a := calc a * b * b⁻¹ = a * (b * b⁻¹) : mul_assoc ... = a * 1 : mul_right_inv ... = a : mul_right_id theorem inv_mul (a b : A) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := inv_unique (calc a * b * (b⁻¹ * a⁻¹) = a * (b * (b⁻¹ * a⁻¹)) : mul_assoc ... = a * a⁻¹ : mul_inv_cancel_left ... = 1 : mul_right_inv) theorem mul_inv_eq_one_imp_eq {a b : A} (H : a * b⁻¹ = 1) : a = b := calc a = a * b⁻¹ * b : inv_mul_cancel_right ... = 1 * b : H ... = b : mul_left_id -- TODO: better names for the next eight theorems? (Also for additive ones.) theorem mul_eq_imp_eq_mul_inv {a b c : A} (H : a * b = c) : a = c * b⁻¹ := H ▹ !mul_inv_cancel_right⁻¹ theorem mul_eq_imp_eq_inv_mul {a b c : A} (H : a * b = c) : b = a⁻¹ * c := H ▹ !inv_mul_cancel_left⁻¹ theorem eq_mul_imp_inv_mul_eq {a b c : A} (H : a = b * c) : b⁻¹ * a = c := H⁻¹ ▹ !inv_mul_cancel_left theorem eq_mul_imp_mul_inv_eq {a b c : A} (H : a = b * c) : a * c⁻¹ = b := H⁻¹ ▹ !mul_inv_cancel_right theorem mul_inv_eq_imp_eq_mul {a b c : A} (H : a * b⁻¹ = c) : a = c * b := !inv_inv ▹ (mul_eq_imp_eq_mul_inv H) theorem inv_mul_eq_imp_eq_mul {a b c : A} (H : a⁻¹ * b = c) : b = a * c := !inv_inv ▹ (mul_eq_imp_eq_inv_mul H) theorem eq_inv_mul_imp_mul_eq {a b c : A} (H : a = b⁻¹ * c) : b * a = c := !inv_inv ▹ (eq_mul_imp_inv_mul_eq H) theorem eq_mul_inv_imp_mul_eq {a b c : A} (H : a = b * c⁻¹) : a * c = b := !inv_inv ▹ (eq_mul_imp_mul_inv_eq H) --theorem mul_eq_iff_eq_inv_mul (a b c : A) : a * b = c ↔ b = a⁻¹ * c := --iff.intro mul_eq_imp_eq_inv_mul eq_inv_mul_imp_mul_eq --theorem mul_eq_iff_eq_mul_inv (a b c : A) : a * b = c ↔ a = c * b⁻¹ := --iff.intro mul_eq_imp_eq_mul_inv eq_mul_inv_imp_mul_eq definition group.to_left_cancel_semigroup [instance] : left_cancel_semigroup A := left_cancel_semigroup.mk (@group.mul A s) (@group.carrier_hset A s) (@group.mul_assoc A s) (take a b c, assume H : a * b = a * c, calc b = a⁻¹ * (a * b) : inv_mul_cancel_left ... = a⁻¹ * (a * c) : H ... = c : inv_mul_cancel_left) definition group.to_right_cancel_semigroup [instance] : right_cancel_semigroup A := right_cancel_semigroup.mk (@group.mul A s) (@group.carrier_hset A s) (@group.mul_assoc A s) (take a b c, assume H : a * b = c * b, calc a = (a * b) * b⁻¹ : mul_inv_cancel_right ... = (c * b) * b⁻¹ : H ... = c : mul_inv_cancel_right) end group structure comm_group [class] (A : Type) extends group A, comm_monoid A /- additive group -/ structure add_group [class] (A : Type) extends add_monoid A, has_neg A := (add_left_inv : ∀a, add (neg a) a = zero) section add_group variables [s : add_group A] include s theorem add_left_inv (a : A) : -a + a = 0 := !add_group.add_left_inv theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := calc -a + (a + b) = -a + a + b : add_assoc ... = 0 + b : add_left_inv ... = b : add_left_id theorem neg_add_cancel_right (a b : A) : a + -b + b = a := calc a + -b + b = a + (-b + b) : add_assoc ... = a + 0 : add_left_inv ... = a : add_right_id theorem neg_unique {a b : A} (H : a + b = 0) : -a = b := calc -a = -a + 0 : add_right_id ... = -a + (a + b) : H ... = b : neg_add_cancel_left theorem neg_zero : -0 = 0 := neg_unique (add_left_id 0) theorem neg_neg (a : A) : -(-a) = a := neg_unique (add_left_inv a) theorem neg_inj {a b : A} (H : -a = -b) : a = b := calc a = -(-a) : neg_neg ... = b : neg_unique (H⁻¹ ▹ (add_left_inv _)) --theorem neg_eq_neg_iff_eq (a b : A) : -a = -b ↔ a = b := --iff.intro (assume H, neg_inj H) (assume H, congr_arg _ H) --theorem neg_eq_zero_iff_eq_zero (a b : A) : -a = 0 ↔ a = 0 := --neg_zero ▹ !neg_eq_neg_iff_eq theorem eq_neg_imp_eq_neg {a b : A} (H : a = -b) : b = -a := H⁻¹ ▹ (neg_neg b)⁻¹ --theorem eq_neg_iff_eq_neg (a b : A) : a = -b ↔ b = -a := --iff.intro !eq_neg_imp_eq_neg !eq_neg_imp_eq_neg theorem add_right_inv (a : A) : a + -a = 0 := calc a + -a = -(-a) + -a : neg_neg ... = 0 : add_left_inv theorem add_neg_cancel_left (a b : A) : a + (-a + b) = b := calc a + (-a + b) = a + -a + b : add_assoc ... = 0 + b : add_right_inv ... = b : add_left_id theorem add_neg_cancel_right (a b : A) : a + b + -b = a := calc a + b + -b = a + (b + -b) : add_assoc ... = a + 0 : add_right_inv ... = a : add_right_id theorem neg_add (a b : A) : -(a + b) = -b + -a := neg_unique (calc a + b + (-b + -a) = a + (b + (-b + -a)) : add_assoc ... = a + -a : add_neg_cancel_left ... = 0 : add_right_inv) theorem add_eq_imp_eq_add_neg {a b c : A} (H : a + b = c) : a = c + -b := H ▹ !add_neg_cancel_right⁻¹ theorem add_eq_imp_eq_neg_add {a b c : A} (H : a + b = c) : b = -a + c := H ▹ !neg_add_cancel_left⁻¹ theorem eq_add_imp_neg_add_eq {a b c : A} (H : a = b + c) : -b + a = c := H⁻¹ ▹ !neg_add_cancel_left theorem eq_add_imp_add_neg_eq {a b c : A} (H : a = b + c) : a + -c = b := H⁻¹ ▹ !add_neg_cancel_right theorem add_neg_eq_imp_eq_add {a b c : A} (H : a + -b = c) : a = c + b := !neg_neg ▹ (add_eq_imp_eq_add_neg H) theorem neg_add_eq_imp_eq_add {a b c : A} (H : -a + b = c) : b = a + c := !neg_neg ▹ (add_eq_imp_eq_neg_add H) theorem eq_neg_add_imp_add_eq {a b c : A} (H : a = -b + c) : b + a = c := !neg_neg ▹ (eq_add_imp_neg_add_eq H) theorem eq_add_neg_imp_add_eq {a b c : A} (H : a = b + -c) : a + c = b := !neg_neg ▹ (eq_add_imp_add_neg_eq H) --theorem add_eq_iff_eq_neg_add (a b c : A) : a + b = c ↔ b = -a + c := --iff.intro add_eq_imp_eq_neg_add eq_neg_add_imp_add_eq --theorem add_eq_iff_eq_add_neg (a b c : A) : a + b = c ↔ a = c + -b := --iff.intro add_eq_imp_eq_add_neg eq_add_neg_imp_add_eq definition add_group.to_left_cancel_semigroup [instance] : add_left_cancel_semigroup A := add_left_cancel_semigroup.mk (@add_group.add A s) (@add_group.add_assoc A s) (take a b c, assume H : a + b = a + c, calc b = -a + (a + b) : neg_add_cancel_left ... = -a + (a + c) : H ... = c : neg_add_cancel_left) definition add_group.to_add_right_cancel_semigroup [instance] : add_right_cancel_semigroup A := add_right_cancel_semigroup.mk (@add_group.add A s) (@add_group.add_assoc A s) (take a b c, assume H : a + b = c + b, calc a = (a + b) + -b : add_neg_cancel_right ... = (c + b) + -b : H ... = c : add_neg_cancel_right) /- minus -/ -- TODO: derive corresponding facts for div in a field definition minus [reducible] (a b : A) : A := a + -b infix `-` := minus theorem minus_self (a : A) : a - a = 0 := !add_right_inv theorem minus_add_cancel (a b : A) : a - b + b = a := !neg_add_cancel_right theorem add_minus_cancel (a b : A) : a + b - b = a := !add_neg_cancel_right theorem minus_eq_zero_imp_eq {a b : A} (H : a - b = 0) : a = b := calc a = (a - b) + b : minus_add_cancel ... = 0 + b : H ... = b : add_left_id --theorem eq_iff_minus_eq_zero (a b : A) : a = b ↔ a - b = 0 := --iff.intro (assume H, H ▹ !minus_self) (assume H, minus_eq_zero_imp_eq H) theorem zero_minus (a : A) : 0 - a = -a := !add_left_id theorem minus_zero (a : A) : a - 0 = a := (neg_zero⁻¹) ▹ !add_right_id theorem minus_neg_eq_add (a b : A) : a - (-b) = a + b := !neg_neg ▹ idp theorem neg_minus_eq (a b : A) : -(a - b) = b - a := neg_unique (calc a - b + (b - a) = a - b + b - a : add_assoc ... = a - a : minus_add_cancel ... = 0 : minus_self) theorem add_minus_eq (a b c : A) : a + (b - c) = a + b - c := !add_assoc⁻¹ theorem minus_add_eq_minus_swap (a b c : A) : a - (b + c) = a - c - b := calc a - (b + c) = a + (-c - b) : neg_add ... = a - c - b : add_assoc --theorem minus_eq_iff_eq_add (a b c : A) : a - b = c ↔ a = c + b := --iff.intro (assume H, add_neg_eq_imp_eq_add H) (assume H, eq_add_imp_add_neg_eq H) --theorem eq_minus_iff_add_eq (a b c : A) : a = b - c ↔ a + c = b := --iff.intro (assume H, eq_add_neg_imp_add_eq H) (assume H, add_eq_imp_eq_add_neg H) --theorem minus_eq_minus_iff {a b c d : A} (H : a - b = c - d) : a = b ↔ c = d := --calc -- a = b ↔ a - b = 0 : eq_iff_minus_eq_zero -- ... ↔ c - d = 0 : H ▹ !iff.refl -- ... ↔ c = d : iff.symm (eq_iff_minus_eq_zero c d) end add_group structure add_comm_group [class] (A : Type) extends add_group A, add_comm_monoid A section add_comm_group variable [s : add_comm_group A] include s theorem minus_add_eq (a b c : A) : a - (b + c) = a - b - c := !add_comm ▹ !minus_add_eq_minus_swap theorem neg_add_eq_minus (a b : A) : -a + b = b - a := !add_comm theorem neg_add_distrib (a b : A) : -(a + b) = -a + -b := !add_comm ▹ !neg_add theorem minus_add_right_comm (a b c : A) : a - b + c = a + c - b := !add_right_comm theorem minus_minus_eq (a b c : A) : a - b - c = a - (b + c) := calc a - b - c = a + (-b + -c) : add_assoc ... = a + -(b + c) : neg_add_distrib ... = a - (b + c) : idp theorem add_minus_cancel_left (a b c : A) : (c + a) - (c + b) = a - b := calc (c + a) - (c + b) = c + a - c - b : minus_add_eq ... = a + c - c - b : add_comm a c ... = a - b : add_minus_cancel end add_comm_group /- bundled structures -/ structure Semigroup := (carrier : Type) (struct : semigroup carrier) persistent attribute Semigroup.carrier [coercion] persistent attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) persistent attribute CommSemigroup.carrier [coercion] persistent attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) persistent attribute Monoid.carrier [coercion] persistent attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) persistent attribute CommMonoid.carrier [coercion] persistent attribute CommMonoid.struct [instance] structure Group := (carrier : Type) (struct : group carrier) persistent attribute Group.carrier [coercion] persistent attribute Group.struct [instance] structure CommGroup := (carrier : Type) (struct : comm_group carrier) persistent attribute CommGroup.carrier [coercion] persistent attribute CommGroup.struct [instance] structure AddSemigroup := (carrier : Type) (struct : add_semigroup carrier) persistent attribute AddSemigroup.carrier [coercion] persistent attribute AddSemigroup.struct [instance] structure AddCommSemigroup := (carrier : Type) (struct : add_comm_semigroup carrier) persistent attribute AddCommSemigroup.carrier [coercion] persistent attribute AddCommSemigroup.struct [instance] structure AddMonoid := (carrier : Type) (struct : add_monoid carrier) persistent attribute AddMonoid.carrier [coercion] persistent attribute AddMonoid.struct [instance] structure AddCommMonoid := (carrier : Type) (struct : add_comm_monoid carrier) persistent attribute AddCommMonoid.carrier [coercion] persistent attribute AddCommMonoid.struct [instance] structure AddGroup := (carrier : Type) (struct : add_group carrier) persistent attribute AddGroup.carrier [coercion] persistent attribute AddGroup.struct [instance] structure AddCommGroup := (carrier : Type) (struct : add_comm_group carrier) persistent attribute AddCommGroup.carrier [coercion] persistent attribute AddCommGroup.struct [instance] end path_algebra
90873f187b08c564bef0e6712c1af5bbe0342977
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/lie/of_associative.lean
99e834dfe38d8f53f35b2f834de10b814cd7930c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
9,960
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.basic import algebra.lie.subalgebra import algebra.lie.submodule import algebra.algebra.subalgebra.basic /-! # Lie algebras of associative algebras This file defines the Lie algebra structure that arises on an associative algebra via the ring commutator. Since the linear endomorphisms of a Lie algebra form an associative algebra, one can define the adjoint action as a morphism of Lie algebras from a Lie algebra to its linear endomorphisms. We make such a definition in this file. ## Main definitions * `lie_algebra.of_associative_algebra` * `lie_algebra.of_associative_algebra_hom` * `lie_module.to_endomorphism` * `lie_algebra.ad` * `linear_equiv.lie_conj` * `alg_equiv.to_lie_equiv` ## Tags lie algebra, ring commutator, adjoint action -/ universes u v w w₁ w₂ section of_associative variables {A : Type v} [ring A] namespace ring /-- The bracket operation for rings is the ring commutator, which captures the extent to which a ring is commutative. It is identically zero exactly when the ring is commutative. -/ @[priority 100] instance : has_bracket A A := ⟨λ x y, x*y - y*x⟩ lemma lie_def (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl end ring namespace lie_ring /-- An associative ring gives rise to a Lie ring by taking the bracket to be the ring commutator. -/ @[priority 100] instance of_associative_ring : lie_ring A := { add_lie := by simp only [ring.lie_def, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev], lie_add := by simp only [ring.lie_def, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev], lie_self := by simp only [ring.lie_def, forall_const, sub_self], leibniz_lie := λ x y z, by { repeat { rw ring.lie_def, }, noncomm_ring, } } lemma of_associative_ring_bracket (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl @[simp] lemma lie_apply {α : Type*} (f g : α → A) (a : α) : ⁅f, g⁆ a = ⁅f a, g a⁆ := rfl end lie_ring section associative_module variables {M : Type w} [add_comm_group M] [module A M] /-- We can regard a module over an associative ring `A` as a Lie ring module over `A` with Lie bracket equal to its ring commutator. Note that this cannot be a global instance because it would create a diamond when `M = A`, specifically we can build two mathematically-different `has_bracket A A`s: 1. `@ring.has_bracket A _` which says `⁅a, b⁆ = a * b - b * a` 2. `(@lie_ring_module.of_associative_module A _ A _ _).to_has_bracket` which says `⁅a, b⁆ = a • b` (and thus `⁅a, b⁆ = a * b`) See note [reducible non-instances] -/ @[reducible] def lie_ring_module.of_associative_module : lie_ring_module A M := { bracket := (•), add_lie := add_smul, lie_add := smul_add, leibniz_lie := by simp [lie_ring.of_associative_ring_bracket, sub_smul, mul_smul, sub_add_cancel], } local attribute [instance] lie_ring_module.of_associative_module lemma lie_eq_smul (a : A) (m : M) : ⁅a, m⁆ = a • m := rfl end associative_module section lie_algebra variables {R : Type u} [comm_ring R] [algebra R A] /-- An associative algebra gives rise to a Lie algebra by taking the bracket to be the ring commutator. -/ @[priority 100] instance lie_algebra.of_associative_algebra : lie_algebra R A := { lie_smul := λ t x y, by rw [lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_sub], } local attribute [instance] lie_ring_module.of_associative_module section associative_representation variables {M : Type w} [add_comm_group M] [module R M] [module A M] [is_scalar_tower R A M] /-- A representation of an associative algebra `A` is also a representation of `A`, regarded as a Lie algebra via the ring commutator. See the comment at `lie_ring_module.of_associative_module` for why the possibility `M = A` means this cannot be a global instance. -/ def lie_module.of_associative_module : lie_module R A M := { smul_lie := smul_assoc, lie_smul := smul_algebra_smul_comm } instance module.End.lie_ring_module : lie_ring_module (module.End R M) M := lie_ring_module.of_associative_module instance module.End.lie_module : lie_module R (module.End R M) M := lie_module.of_associative_module end associative_representation namespace alg_hom variables {B : Type w} {C : Type w₁} [ring B] [ring C] [algebra R B] [algebra R C] variables (f : A →ₐ[R] B) (g : B →ₐ[R] C) /-- The map `of_associative_algebra` associating a Lie algebra to an associative algebra is functorial. -/ def to_lie_hom : A →ₗ⁅R⁆ B := { map_lie' := λ x y, show f ⁅x,y⁆ = ⁅f x,f y⁆, by simp only [lie_ring.of_associative_ring_bracket, alg_hom.map_sub, alg_hom.map_mul], ..f.to_linear_map, } instance : has_coe (A →ₐ[R] B) (A →ₗ⁅R⁆ B) := ⟨to_lie_hom⟩ @[simp] lemma to_lie_hom_coe : f.to_lie_hom = ↑f := rfl @[simp] lemma coe_to_lie_hom : ((f : A →ₗ⁅R⁆ B) : A → B) = f := rfl lemma to_lie_hom_apply (x : A) : f.to_lie_hom x = f x := rfl @[simp] lemma to_lie_hom_id : (alg_hom.id R A : A →ₗ⁅R⁆ A) = lie_hom.id := rfl @[simp] lemma to_lie_hom_comp : (g.comp f : A →ₗ⁅R⁆ C) = (g : B →ₗ⁅R⁆ C).comp (f : A →ₗ⁅R⁆ B) := rfl lemma to_lie_hom_injective {f g : A →ₐ[R] B} (h : (f : A →ₗ⁅R⁆ B) = (g : A →ₗ⁅R⁆ B)) : f = g := by { ext a, exact lie_hom.congr_fun h a, } end alg_hom end lie_algebra end of_associative section adjoint_action 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] /-- A Lie module yields a Lie algebra morphism into the linear endomorphisms of the module. See also `lie_module.to_module_hom`. -/ @[simps] def lie_module.to_endomorphism : L →ₗ⁅R⁆ module.End R M := { to_fun := λ x, { to_fun := λ m, ⁅x, m⁆, map_add' := lie_add x, map_smul' := λ t, lie_smul t x, }, map_add' := λ x y, by { ext m, apply add_lie, }, map_smul' := λ t x, by { ext m, apply smul_lie, }, map_lie' := λ x y, by { ext m, apply lie_lie, }, } /-- The adjoint action of a Lie algebra on itself. -/ def lie_algebra.ad : L →ₗ⁅R⁆ module.End R L := lie_module.to_endomorphism R L L @[simp] lemma lie_algebra.ad_apply (x y : L) : lie_algebra.ad R L x y = ⁅x, y⁆ := rfl @[simp] lemma lie_module.to_endomorphism_module_End : lie_module.to_endomorphism R (module.End R M) M = lie_hom.id := by { ext g m, simp [lie_eq_smul], } lemma lie_subalgebra.to_endomorphism_eq (K : lie_subalgebra R L) {x : K} : lie_module.to_endomorphism R K M x = lie_module.to_endomorphism R L M x := rfl @[simp] lemma lie_subalgebra.to_endomorphism_mk (K : lie_subalgebra R L) {x : L} (hx : x ∈ K) : lie_module.to_endomorphism R K M ⟨x, hx⟩ = lie_module.to_endomorphism R L M x := rfl variables {R L M} lemma lie_submodule.coe_map_to_endomorphism_le {N : lie_submodule R L M} {x : L} : (N : submodule R M).map (lie_module.to_endomorphism R L M x) ≤ N := begin rintros n ⟨m, hm, rfl⟩, exact N.lie_mem hm, end open lie_algebra lemma lie_algebra.ad_eq_lmul_left_sub_lmul_right (A : Type v) [ring A] [algebra R A] : (ad R A : A → module.End R A) = algebra.lmul_left R - algebra.lmul_right R := by { ext a b, simp [lie_ring.of_associative_ring_bracket], } lemma lie_subalgebra.ad_comp_incl_eq (K : lie_subalgebra R L) (x : K) : (ad R L ↑x).comp (K.incl : K →ₗ[R] L) = (K.incl : K →ₗ[R] L).comp (ad R K x) := begin ext y, simp only [ad_apply, lie_hom.coe_to_linear_map, lie_subalgebra.coe_incl, linear_map.coe_comp, lie_subalgebra.coe_bracket, function.comp_app], end end adjoint_action /-- A subalgebra of an associative algebra is a Lie subalgebra of the associated Lie algebra. -/ def lie_subalgebra_of_subalgebra (R : Type u) [comm_ring R] (A : Type v) [ring A] [algebra R A] (A' : subalgebra R A) : lie_subalgebra R A := { lie_mem' := λ x y hx hy, by { change ⁅x, y⁆ ∈ A', change x ∈ A' at hx, change y ∈ A' at hy, rw lie_ring.of_associative_ring_bracket, have hxy := A'.mul_mem hx hy, have hyx := A'.mul_mem hy hx, exact submodule.sub_mem A'.to_submodule hxy hyx, }, ..A'.to_submodule } namespace linear_equiv variables {R : Type u} {M₁ : Type v} {M₂ : Type w} variables [comm_ring R] [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] variables (e : M₁ ≃ₗ[R] M₂) /-- A linear equivalence of two modules induces a Lie algebra equivalence of their endomorphisms. -/ def lie_conj : module.End R M₁ ≃ₗ⁅R⁆ module.End R M₂ := { map_lie' := λ f g, show e.conj ⁅f, g⁆ = ⁅e.conj f, e.conj g⁆, by simp only [lie_ring.of_associative_ring_bracket, linear_map.mul_eq_comp, e.conj_comp, linear_equiv.map_sub], ..e.conj } @[simp] lemma lie_conj_apply (f : module.End R M₁) : e.lie_conj f = e.conj f := rfl @[simp] lemma lie_conj_symm : e.lie_conj.symm = e.symm.lie_conj := rfl end linear_equiv namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} variables [comm_ring R] [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] variables (e : A₁ ≃ₐ[R] A₂) /-- An equivalence of associative algebras is an equivalence of associated Lie algebras. -/ def to_lie_equiv : A₁ ≃ₗ⁅R⁆ A₂ := { to_fun := e.to_fun, map_lie' := λ x y, by simp [lie_ring.of_associative_ring_bracket], ..e.to_linear_equiv } @[simp] lemma to_lie_equiv_apply (x : A₁) : e.to_lie_equiv x = e x := rfl @[simp] lemma to_lie_equiv_symm_apply (x : A₂) : e.to_lie_equiv.symm x = e.symm x := rfl end alg_equiv
a567d5028ef5d81575d0b98292d76292b9360483
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/metric_space/gluing.lean
15e54523b73a8eced67aede077ca121cd96448c8
[ "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
32,225
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.isometry /-! # Metric space gluing Gluing two metric spaces along a common subset. Formally, we are given ``` Φ Z ---> X | |Ψ v Y ``` where `hΦ : isometry Φ` and `hΨ : isometry Ψ`. We want to complete the square by a space `glue_space hΦ hΨ` and two isometries `to_glue_l hΦ hΨ` and `to_glue_r hΦ hΨ` that make the square commute. We start by defining a predistance on the disjoint union `X ⊕ Y`, for which points `Φ p` and `Ψ p` are at distance 0. The (quotient) metric space associated to this predistance is the desired space. This is an instance of a more general construction, where `Φ` and `Ψ` do not have to be isometries, but the distances in the image almost coincide, up to `2ε` say. Then one can almost glue the two spaces so that the images of a point under `Φ` and `Ψ` are `ε`-close. If `ε > 0`, this yields a metric space structure on `X ⊕ Y`, without the need to take a quotient. In particular, this gives a natural metric space structure on `X ⊕ Y`, where the basepoints are at distance 1, say, and the distances between other points are obtained by going through the two basepoints. (We also register the same metric space structure on a general disjoint union `Σ i, E i`). We also define the inductive limit of metric spaces. Given ``` f 0 f 1 f 2 f 3 X 0 -----> X 1 -----> X 2 -----> X 3 -----> ... ``` where the `X n` are metric spaces and `f n` isometric embeddings, we define the inductive limit of the `X n`, also known as the increasing union of the `X n` in this context, if we identify `X n` and `X (n+1)` through `f n`. This is a metric space in which all `X n` embed isometrically and in a way compatible with `f n`. -/ noncomputable theory universes u v w open function set open_locale uniformity namespace metric section approx_gluing variables {X : Type u} {Y : Type v} {Z : Type w} variables [metric_space X] [metric_space Y] {Φ : Z → X} {Ψ : Z → Y} {ε : ℝ} open _root_.sum (inl inr) /-- Define a predistance on `X ⊕ Y`, for which `Φ p` and `Ψ p` are at distance `ε` -/ def glue_dist (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : X ⊕ Y → X ⊕ Y → ℝ | (inl x) (inl y) := dist x y | (inr x) (inr y) := dist x y | (inl x) (inr y) := (⨅ p, dist x (Φ p) + dist y (Ψ p)) + ε | (inr x) (inl y) := (⨅ p, dist y (Φ p) + dist x (Ψ p)) + ε private lemma glue_dist_self (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : ∀ x, glue_dist Φ Ψ ε x x = 0 | (inl x) := dist_self _ | (inr x) := dist_self _ lemma glue_dist_glued_points [nonempty Z] (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (p : Z) : glue_dist Φ Ψ ε (inl (Φ p)) (inr (Ψ p)) = ε := begin have : (⨅ q, dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q)) = 0, { have A : ∀ q, 0 ≤ dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q) := λq, by rw ← add_zero (0 : ℝ); exact add_le_add dist_nonneg dist_nonneg, refine le_antisymm _ (le_cinfi A), have : 0 = dist (Φ p) (Φ p) + dist (Ψ p) (Ψ p), by simp, rw this, exact cinfi_le ⟨0, forall_range_iff.2 A⟩ p }, rw [glue_dist, this, zero_add] end private lemma glue_dist_comm (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : ∀ x y, glue_dist Φ Ψ ε x y = glue_dist Φ Ψ ε y x | (inl x) (inl y) := dist_comm _ _ | (inr x) (inr y) := dist_comm _ _ | (inl x) (inr y) := rfl | (inr x) (inl y) := rfl variable [nonempty Z] private lemma glue_dist_triangle (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (H : ∀ p q, |dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)| ≤ 2 * ε) : ∀ x y z, glue_dist Φ Ψ ε x z ≤ glue_dist Φ Ψ ε x y + glue_dist Φ Ψ ε y z | (inl x) (inl y) (inl z) := dist_triangle _ _ _ | (inr x) (inr y) (inr z) := dist_triangle _ _ _ | (inr x) (inl y) (inl z) := begin have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : (⨅ p, dist z (Φ p) + dist x (Ψ p)) ≤ (⨅ p, dist y (Φ p) + dist x (Ψ p)) + dist y z, { have : (⨅ p, dist y (Φ p) + dist x (Ψ p)) + dist y z = infi ((λt, t + dist y z) ∘ (λp, dist y (Φ p) + dist x (Ψ p))), { refine monotone.map_cinfi_of_continuous_at (continuous_at_id.add continuous_at_const) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_mono (B _ _) (λp, _), calc dist z (Φ p) + dist x (Ψ p) ≤ (dist y z + dist y (Φ p)) + dist x (Ψ p) : add_le_add (dist_triangle_left _ _ _) le_rfl ... = dist y (Φ p) + dist x (Ψ p) + dist y z : by ring }, linarith end | (inr x) (inr y) (inl z) := begin have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : (⨅ p, dist z (Φ p) + dist x (Ψ p)) ≤ dist x y + ⨅ p, dist z (Φ p) + dist y (Ψ p), { have : dist x y + (⨅ p, dist z (Φ p) + dist y (Ψ p)) = infi ((λt, dist x y + t) ∘ (λp, dist z (Φ p) + dist y (Ψ p))), { refine monotone.map_cinfi_of_continuous_at (continuous_at_const.add continuous_at_id) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_mono (B _ _) (λp, _), calc dist z (Φ p) + dist x (Ψ p) ≤ dist z (Φ p) + (dist x y + dist y (Ψ p)) : add_le_add le_rfl (dist_triangle _ _ _) ... = dist x y + (dist z (Φ p) + dist y (Ψ p)) : by ring }, linarith end | (inl x) (inl y) (inr z) := begin have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : (⨅ p, dist x (Φ p) + dist z (Ψ p)) ≤ dist x y + ⨅ p, dist y (Φ p) + dist z (Ψ p), { have : dist x y + (⨅ p, dist y (Φ p) + dist z (Ψ p)) = infi ((λt, dist x y + t) ∘ (λp, dist y (Φ p) + dist z (Ψ p))), { refine monotone.map_cinfi_of_continuous_at (continuous_at_const.add continuous_at_id) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_mono (B _ _) (λp, _), calc dist x (Φ p) + dist z (Ψ p) ≤ (dist x y + dist y (Φ p)) + dist z (Ψ p) : add_le_add (dist_triangle _ _ _) le_rfl ... = dist x y + (dist y (Φ p) + dist z (Ψ p)) : by ring }, linarith end | (inl x) (inr y) (inr z) := begin have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : (⨅ p, dist x (Φ p) + dist z (Ψ p)) ≤ (⨅ p, dist x (Φ p) + dist y (Ψ p)) + dist y z, { have : (⨅ p, dist x (Φ p) + dist y (Ψ p)) + dist y z = infi ((λt, t + dist y z) ∘ (λp, dist x (Φ p) + dist y (Ψ p))), { refine monotone.map_cinfi_of_continuous_at (continuous_at_id.add continuous_at_const) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_mono (B _ _) (λp, _), calc dist x (Φ p) + dist z (Ψ p) ≤ dist x (Φ p) + (dist y z + dist y (Ψ p)) : add_le_add le_rfl (dist_triangle_left _ _ _) ... = dist x (Φ p) + dist y (Ψ p) + dist y z : by ring }, linarith end | (inl x) (inr y) (inl z) := le_of_forall_pos_le_add $ λδ δpos, begin obtain ⟨p, hp⟩ : ∃ p, dist x (Φ p) + dist y (Ψ p) < (⨅ p, dist x (Φ p) + dist y (Ψ p)) + δ / 2, from exists_lt_of_cinfi_lt (by linarith), obtain ⟨q, hq⟩ : ∃ q, dist z (Φ q) + dist y (Ψ q) < (⨅ p, dist z (Φ p) + dist y (Ψ p)) + δ / 2, from exists_lt_of_cinfi_lt (by linarith), have : dist (Φ p) (Φ q) ≤ dist (Ψ p) (Ψ q) + 2 * ε, { have := le_trans (le_abs_self _) (H p q), by linarith }, calc dist x z ≤ dist x (Φ p) + dist (Φ p) (Φ q) + dist (Φ q) z : dist_triangle4 _ _ _ _ ... ≤ dist x (Φ p) + dist (Ψ p) (Ψ q) + dist z (Φ q) + 2 * ε : by rw [dist_comm z]; linarith ... ≤ dist x (Φ p) + (dist y (Ψ p) + dist y (Ψ q)) + dist z (Φ q) + 2 * ε : add_le_add (add_le_add (add_le_add le_rfl (dist_triangle_left _ _ _)) le_rfl) le_rfl ... ≤ ((⨅ p, dist x (Φ p) + dist y (Ψ p)) + ε) + ((⨅ p, dist z (Φ p) + dist y (Ψ p)) + ε) + δ : by linarith end | (inr x) (inl y) (inr z) := le_of_forall_pos_le_add $ λδ δpos, begin obtain ⟨p, hp⟩ : ∃ p, dist y (Φ p) + dist x (Ψ p) < (⨅ p, dist y (Φ p) + dist x (Ψ p)) + δ / 2, from exists_lt_of_cinfi_lt (by linarith), obtain ⟨q, hq⟩ : ∃ q, dist y (Φ q) + dist z (Ψ q) < (⨅ p, dist y (Φ p) + dist z (Ψ p)) + δ / 2, from exists_lt_of_cinfi_lt (by linarith), have : dist (Ψ p) (Ψ q) ≤ dist (Φ p) (Φ q) + 2 * ε, { have := le_trans (neg_le_abs_self _) (H p q), by linarith }, calc dist x z ≤ dist x (Ψ p) + dist (Ψ p) (Ψ q) + dist (Ψ q) z : dist_triangle4 _ _ _ _ ... ≤ dist x (Ψ p) + dist (Φ p) (Φ q) + dist z (Ψ q) + 2 * ε : by rw [dist_comm z]; linarith ... ≤ dist x (Ψ p) + (dist y (Φ p) + dist y (Φ q)) + dist z (Ψ q) + 2 * ε : add_le_add (add_le_add (add_le_add le_rfl (dist_triangle_left _ _ _)) le_rfl) le_rfl ... ≤ ((⨅ p, dist y (Φ p) + dist x (Ψ p)) + ε) + ((⨅ p, dist y (Φ p) + dist z (Ψ p)) + ε) + δ : by linarith end private lemma glue_eq_of_dist_eq_zero (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (ε0 : 0 < ε) : ∀ p q : X ⊕ Y, glue_dist Φ Ψ ε p q = 0 → p = q | (inl x) (inl y) h := by rw eq_of_dist_eq_zero h | (inl x) (inr y) h := begin have : 0 ≤ (⨅ p, dist x (Φ p) + dist y (Ψ p)) := le_cinfi (λp, by simpa using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)), have : 0 + ε ≤ glue_dist Φ Ψ ε (inl x) (inr y) := add_le_add this (le_refl ε), exfalso, linarith end | (inr x) (inl y) h := begin have : 0 ≤ ⨅ p, dist y (Φ p) + dist x (Ψ p) := le_cinfi (λp, by simpa [add_comm] using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)), have : 0 + ε ≤ glue_dist Φ Ψ ε (inr x) (inl y) := add_le_add this (le_refl ε), exfalso, linarith end | (inr x) (inr y) h := by rw eq_of_dist_eq_zero h /-- Given two maps `Φ` and `Ψ` intro metric spaces `X` and `Y` such that the distances between `Φ p` and `Φ q`, and between `Ψ p` and `Ψ q`, coincide up to `2 ε` where `ε > 0`, one can almost glue the two spaces `X` and `Y` along the images of `Φ` and `Ψ`, so that `Φ p` and `Ψ p` are at distance `ε`. -/ def glue_metric_approx (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (ε0 : 0 < ε) (H : ∀ p q, |dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)| ≤ 2 * ε) : metric_space (X ⊕ Y) := { dist := glue_dist Φ Ψ ε, dist_self := glue_dist_self Φ Ψ ε, dist_comm := glue_dist_comm Φ Ψ ε, dist_triangle := glue_dist_triangle Φ Ψ ε H, eq_of_dist_eq_zero := glue_eq_of_dist_eq_zero Φ Ψ ε ε0 } end approx_gluing section sum /- A particular case of the previous construction is when one uses basepoints in `X` and `Y` and one glues only along the basepoints, putting them at distance 1. We give a direct definition of the distance, without infi, as it is easier to use in applications, and show that it is equal to the gluing distance defined above to take advantage of the lemmas we have already proved. -/ variables {X : Type u} {Y : Type v} {Z : Type w} variables [metric_space X] [metric_space Y] open sum (inl inr) /-- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible with each factor. If the two spaces are bounded, one can say for instance that each point in the first is at distance `diam X + diam Y + 1` of each point in the second. Instead, we choose a construction that works for unbounded spaces, but requires basepoints, chosen arbitrarily. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ def sum.dist : X ⊕ Y → X ⊕ Y → ℝ | (inl a) (inl a') := dist a a' | (inr b) (inr b') := dist b b' | (inl a) (inr b) := dist a (nonempty.some ⟨a⟩) + 1 + dist (nonempty.some ⟨b⟩) b | (inr b) (inl a) := dist b (nonempty.some ⟨b⟩) + 1 + dist (nonempty.some ⟨a⟩) a lemma sum.dist_eq_glue_dist {p q : X ⊕ Y} (x : X) (y : Y) : sum.dist p q = glue_dist (λ _ : unit, nonempty.some ⟨x⟩) (λ _ : unit, nonempty.some ⟨y⟩) 1 p q := by cases p; cases q; refl <|> simp [sum.dist, glue_dist, dist_comm, add_comm, add_left_comm] private lemma sum.dist_comm (x y : X ⊕ Y) : sum.dist x y = sum.dist y x := by cases x; cases y; simp only [sum.dist, dist_comm, add_comm, add_left_comm] lemma sum.one_dist_le {x : X} {y : Y} : 1 ≤ sum.dist (inl x) (inr y) := le_trans (le_add_of_nonneg_right dist_nonneg) $ add_le_add_right (le_add_of_nonneg_left dist_nonneg) _ lemma sum.one_dist_le' {x : X} {y : Y} : 1 ≤ sum.dist (inr y) (inl x) := by rw sum.dist_comm; exact sum.one_dist_le private lemma sum.mem_uniformity (s : set ((X ⊕ Y) × (X ⊕ Y))) : s ∈ 𝓤 (X ⊕ Y) ↔ ∃ ε > 0, ∀ a b, sum.dist a b < ε → (a, b) ∈ s := begin split, { rintro ⟨hsX, hsY⟩, rcases mem_uniformity_dist.1 hsX with ⟨εX, εX0, hX⟩, rcases mem_uniformity_dist.1 hsY with ⟨εY, εY0, hY⟩, refine ⟨min (min εX εY) 1, lt_min (lt_min εX0 εY0) zero_lt_one, _⟩, rintro (a|a) (b|b) h, { exact hX (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_left _ _))) }, { cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le }, { cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le' }, { exact hY (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_right _ _))) } }, { rintro ⟨ε, ε0, H⟩, split; rw [filter.mem_sets, filter.mem_map, mem_uniformity_dist]; exact ⟨ε, ε0, λ x y h, H _ _ (by exact h)⟩ } end /-- The distance on the disjoint union indeed defines a metric space. All the distance properties follow from our choice of the distance. The harder work is to show that the uniform structure defined by the distance coincides with the disjoint union uniform structure. -/ def metric_space_sum : metric_space (X ⊕ Y) := { dist := sum.dist, dist_self := λx, by cases x; simp only [sum.dist, dist_self], dist_comm := sum.dist_comm, dist_triangle := λ p q r, begin cases p; cases q; cases r, { exact dist_triangle _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist p r], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist p q], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist p q], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist q p], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist q p], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist r p], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { exact dist_triangle _ _ _ }, end, eq_of_dist_eq_zero := λ p q, begin cases p; cases q, { simp only [sum.dist, dist_eq_zero, imp_self] }, { assume h, simp only [dist, sum.dist_eq_glue_dist p q] at h, exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _ h }, { assume h, simp only [dist, sum.dist_eq_glue_dist q p] at h, exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _ h }, { simp only [sum.dist, dist_eq_zero, imp_self] }, end, to_uniform_space := sum.uniform_space, uniformity_dist := uniformity_dist_of_mem_uniformity _ _ sum.mem_uniformity } local attribute [instance] metric_space_sum lemma sum.dist_eq {x y : X ⊕ Y} : dist x y = sum.dist x y := rfl /-- The left injection of a space in a disjoint union is an isometry -/ lemma isometry_inl : isometry (sum.inl : X → (X ⊕ Y)) := isometry.of_dist_eq $ λ x y, rfl /-- The right injection of a space in a disjoint union is an isometry -/ lemma isometry_inr : isometry (sum.inr : Y → (X ⊕ Y)) := isometry.of_dist_eq $ λ x y, rfl end sum namespace sigma /- Copy of the previous paragraph, but for arbitrary disjoint unions instead of the disjoint union of two spaces. I.e., work with sigma types instead of sum types. -/ variables {ι : Type*} {E : ι → Type*} [∀ i, metric_space (E i)] open_locale classical /-- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible with each factor. We choose a construction that works for unbounded spaces, but requires basepoints, chosen arbitrarily. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ protected def dist : (Σ i, E i) → (Σ i, E i) → ℝ | ⟨i, x⟩ ⟨j, y⟩ := if h : i = j then by { have : E j = E i, by rw h, exact has_dist.dist x (cast this y) } else has_dist.dist x (nonempty.some ⟨x⟩) + 1 + has_dist.dist (nonempty.some ⟨y⟩) y /-- A `has_dist` instance on the disjoint union `Σ i, E i`. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ def has_dist : has_dist (Σ i, E i) := ⟨sigma.dist⟩ local attribute [instance] sigma.has_dist @[simp] lemma dist_same (i : ι) (x : E i) (y : E i) : dist (⟨i, x⟩ : Σ j, E j) ⟨i, y⟩ = dist x y := by simp [has_dist.dist, sigma.dist] @[simp] lemma dist_ne {i j : ι} (h : i ≠ j) (x : E i) (y : E j) : dist (⟨i, x⟩ : Σ k, E k) ⟨j, y⟩ = dist x (nonempty.some ⟨x⟩) + 1 + dist (nonempty.some ⟨y⟩) y := by simp [has_dist.dist, sigma.dist, h] lemma one_le_dist_of_ne {i j : ι} (h : i ≠ j) (x : E i) (y : E j) : 1 ≤ dist (⟨i, x⟩ : Σ k, E k) ⟨j, y⟩ := begin rw sigma.dist_ne h x y, linarith [@dist_nonneg _ _ x (nonempty.some ⟨x⟩), @dist_nonneg _ _ (nonempty.some ⟨y⟩) y] end lemma fst_eq_of_dist_lt_one (x y : Σ i, E i) (h : dist x y < 1) : x.1 = y.1 := begin cases x, cases y, contrapose! h, apply one_le_dist_of_ne h, end protected lemma dist_triangle (x y z : Σ i, E i) : dist x z ≤ dist x y + dist y z := begin rcases x with ⟨i, x⟩, rcases y with ⟨j, y⟩, rcases z with ⟨k, z⟩, rcases eq_or_ne i k with rfl|hik, { rcases eq_or_ne i j with rfl|hij, { simpa using dist_triangle x y z }, { simp only [hij, hij.symm, sigma.dist_same, sigma.dist_ne, ne.def, not_false_iff], calc dist x z ≤ dist x (nonempty.some ⟨x⟩) + 0 + 0 + (0 + 0 + dist (nonempty.some ⟨z⟩) z) : by simpa only [zero_add, add_zero] using dist_triangle _ _ _ ... ≤ _ : by apply_rules [add_le_add, le_rfl, dist_nonneg, zero_le_one] } }, { rcases eq_or_ne i j with rfl|hij, { simp only [hik, sigma.dist_ne, ne.def, not_false_iff, sigma.dist_same], calc dist x (nonempty.some ⟨x⟩) + 1 + dist (nonempty.some ⟨z⟩) z ≤ (dist x y + dist y (nonempty.some ⟨y⟩) + 1 + dist (nonempty.some ⟨z⟩) z) : by apply_rules [add_le_add, le_rfl, dist_triangle] ... = _ : by abel }, { rcases eq_or_ne j k with rfl|hjk, { simp only [hij, sigma.dist_ne, ne.def, not_false_iff, sigma.dist_same], calc dist x (nonempty.some ⟨x⟩) + 1 + dist (nonempty.some ⟨z⟩) z ≤ dist x (nonempty.some ⟨x⟩) + 1 + (dist (nonempty.some ⟨z⟩) y + dist y z) : by apply_rules [add_le_add, le_rfl, dist_triangle] ... = _ : by abel }, { simp only [hik, hij, hjk, sigma.dist_ne, ne.def, not_false_iff], calc dist x (nonempty.some ⟨x⟩) + 1 + dist (nonempty.some ⟨z⟩) z = dist x (nonempty.some ⟨x⟩) + 1 + 0 + (0 + 0 + dist (nonempty.some ⟨z⟩) z) : by simp only [add_zero, zero_add] ... ≤ _ : by apply_rules [add_le_add, zero_le_one, dist_nonneg, le_rfl] } } } end protected lemma is_open_iff (s : set (Σ i, E i)) : is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s := begin split, { rintros hs ⟨i, x⟩ hx, obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ball x ε ⊆ sigma.mk i ⁻¹' s := metric.is_open_iff.1 (is_open_sigma_iff.1 hs i) x hx, refine ⟨min ε 1, lt_min εpos zero_lt_one, _⟩, rintros ⟨j, y⟩ hy, rcases eq_or_ne i j with rfl|hij, { simp only [sigma.dist_same, lt_min_iff] at hy, exact hε (mem_ball'.2 hy.1) }, { apply (lt_irrefl (1 : ℝ) _).elim, calc 1 ≤ sigma.dist ⟨i, x⟩ ⟨j, y⟩ : sigma.one_le_dist_of_ne hij _ _ ... < 1 : hy.trans_le (min_le_right _ _) } }, { assume H, apply is_open_sigma_iff.2 (λ i, _), apply metric.is_open_iff.2 (λ x hx, _), obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ y, dist (⟨i, x⟩ : Σ j, E j) y < ε → y ∈ s := H ⟨i, x⟩ hx, refine ⟨ε, εpos, λ y hy, _⟩, apply hε ⟨i, y⟩, rw sigma.dist_same, exact mem_ball'.1 hy } end /-- A metric space structure on the disjoint union `Σ i, E i`. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ protected def metric_space : metric_space (Σ i, E i) := begin refine metric_space.of_metrizable sigma.dist _ _ sigma.dist_triangle sigma.is_open_iff _, { rintros ⟨i, x⟩, simp [sigma.dist] }, { rintros ⟨i, x⟩ ⟨j, y⟩, rcases eq_or_ne i j with rfl|h, { simp [sigma.dist, dist_comm] }, { simp only [sigma.dist, dist_comm, h, h.symm, not_false_iff, dif_neg], abel } }, { rintros ⟨i, x⟩ ⟨j, y⟩, rcases eq_or_ne i j with rfl|hij, { simp [sigma.dist] }, { assume h, apply (lt_irrefl (1 : ℝ) _).elim, calc 1 ≤ sigma.dist (⟨i, x⟩ : Σ k, E k) ⟨j, y⟩ : sigma.one_le_dist_of_ne hij _ _ ... < 1 : by { rw h, exact zero_lt_one } } } end local attribute [instance] sigma.metric_space open_locale topological_space open filter /-- The injection of a space in a disjoint union is an isometry -/ lemma isometry_mk (i : ι) : isometry (sigma.mk i : E i → Σ k, E k) := isometry.of_dist_eq (λ x y, by simp) /-- A disjoint union of complete metric spaces is complete. -/ protected lemma complete_space [∀ i, complete_space (E i)] : complete_space (Σ i, E i) := begin set s : ι → set (Σ i, E i) := λ i, (sigma.fst ⁻¹' {i}), set U := {p : (Σ k, E k) × (Σ k, E k) | dist p.1 p.2 < 1}, have hc : ∀ i, is_complete (s i), { intro i, simp only [s, ← range_sigma_mk], exact (isometry_mk i).uniform_inducing.is_complete_range }, have hd : ∀ i j (x ∈ s i) (y ∈ s j), (x, y) ∈ U → i = j, from λ i j x hx y hy hxy, (eq.symm hx).trans ((fst_eq_of_dist_lt_one _ _ hxy).trans hy), refine complete_space_of_is_complete_univ _, convert is_complete_Union_separated hc (dist_mem_uniformity zero_lt_one) hd, simp [s, ← preimage_Union] end end sigma section gluing /- Exact gluing of two metric spaces along isometric subsets. -/ variables {X : Type u} {Y : Type v} {Z : Type w} variables [nonempty Z] [metric_space Z] [metric_space X] [metric_space Y] {Φ : Z → X} {Ψ : Z → Y} {ε : ℝ} open _root_.sum (inl inr) local attribute [instance] pseudo_metric.dist_setoid /-- Given two isometric embeddings `Φ : Z → X` and `Ψ : Z → Y`, we define a pseudo metric space structure on `X ⊕ Y` by declaring that `Φ x` and `Ψ x` are at distance `0`. -/ def glue_premetric (hΦ : isometry Φ) (hΨ : isometry Ψ) : pseudo_metric_space (X ⊕ Y) := { dist := glue_dist Φ Ψ 0, dist_self := glue_dist_self Φ Ψ 0, dist_comm := glue_dist_comm Φ Ψ 0, dist_triangle := glue_dist_triangle Φ Ψ 0 $ λp q, by rw [hΦ.dist_eq, hΨ.dist_eq]; simp } /-- Given two isometric embeddings `Φ : Z → X` and `Ψ : Z → Y`, we define a space `glue_space hΦ hΨ` by identifying in `X ⊕ Y` the points `Φ x` and `Ψ x`. -/ def glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : Type* := @pseudo_metric_quot _ (glue_premetric hΦ hΨ) instance metric_space_glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : metric_space (glue_space hΦ hΨ) := @metric_space_quot _ (glue_premetric hΦ hΨ) /-- The canonical map from `X` to the space obtained by gluing isometric subsets in `X` and `Y`. -/ def to_glue_l (hΦ : isometry Φ) (hΨ : isometry Ψ) (x : X) : glue_space hΦ hΨ := by letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ; exact ⟦inl x⟧ /-- The canonical map from `Y` to the space obtained by gluing isometric subsets in `X` and `Y`. -/ def to_glue_r (hΦ : isometry Φ) (hΨ : isometry Ψ) (y : Y) : glue_space hΦ hΨ := by letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ; exact ⟦inr y⟧ instance inhabited_left (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited X] : inhabited (glue_space hΦ hΨ) := ⟨to_glue_l _ _ default⟩ instance inhabited_right (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited Y] : inhabited (glue_space hΦ hΨ) := ⟨to_glue_r _ _ default⟩ lemma to_glue_commute (hΦ : isometry Φ) (hΨ : isometry Ψ) : (to_glue_l hΦ hΨ) ∘ Φ = (to_glue_r hΦ hΨ) ∘ Ψ := begin letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ, funext, simp only [comp, to_glue_l, to_glue_r, quotient.eq], exact glue_dist_glued_points Φ Ψ 0 x end lemma to_glue_l_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_l hΦ hΨ) := isometry.of_dist_eq $ λ_ _, rfl lemma to_glue_r_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_r hΦ hΨ) := isometry.of_dist_eq $ λ_ _, rfl end gluing --section section inductive_limit /- In this section, we define the inductive limit of f 0 f 1 f 2 f 3 X 0 -----> X 1 -----> X 2 -----> X 3 -----> ... where the X n are metric spaces and f n isometric embeddings. We do it by defining a premetric space structure on Σ n, X n, where the predistance dist x y is obtained by pushing x and y in a common X k using composition by the f n, and taking the distance there. This does not depend on the choice of k as the f n are isometries. The metric space associated to this premetric space is the desired inductive limit.-/ open nat variables {X : ℕ → Type u} [∀ n, metric_space (X n)] {f : Π n, X n → X (n+1)} /-- Predistance on the disjoint union `Σ n, X n`. -/ def inductive_limit_dist (f : Π n, X n → X (n+1)) (x y : Σ n, X n) : ℝ := dist (le_rec_on (le_max_left x.1 y.1) f x.2 : X (max x.1 y.1)) (le_rec_on (le_max_right x.1 y.1) f y.2 : X (max x.1 y.1)) /-- The predistance on the disjoint union `Σ n, X n` can be computed in any `X k` for large enough `k`. -/ lemma inductive_limit_dist_eq_dist (I : ∀ n, isometry (f n)) (x y : Σ n, X n) (m : ℕ) : ∀ hx : x.1 ≤ m, ∀ hy : y.1 ≤ m, inductive_limit_dist f x y = dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) := begin induction m with m hm, { assume hx hy, have A : max x.1 y.1 = 0, { rw [nonpos_iff_eq_zero.1 hx, nonpos_iff_eq_zero.1 hy], simp }, unfold inductive_limit_dist, congr; simp only [A] }, { assume hx hy, by_cases h : max x.1 y.1 = m.succ, { unfold inductive_limit_dist, congr; simp only [h] }, { have : max x.1 y.1 ≤ succ m := by simp [hx, hy], have : max x.1 y.1 ≤ m := by simpa [h] using of_le_succ this, have xm : x.1 ≤ m := le_trans (le_max_left _ _) this, have ym : y.1 ≤ m := le_trans (le_max_right _ _) this, rw [le_rec_on_succ xm, le_rec_on_succ ym, (I m).dist_eq], exact hm xm ym }} end /-- Premetric space structure on `Σ n, X n`.-/ def inductive_premetric (I : ∀ n, isometry (f n)) : pseudo_metric_space (Σ n, X n) := { dist := inductive_limit_dist f, dist_self := λx, by simp [dist, inductive_limit_dist], dist_comm := λx y, begin let m := max x.1 y.1, have hx : x.1 ≤ m := le_max_left _ _, have hy : y.1 ≤ m := le_max_right _ _, unfold dist, rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y x m hy hx, dist_comm] end, dist_triangle := λx y z, begin let m := max (max x.1 y.1) z.1, have hx : x.1 ≤ m := le_trans (le_max_left _ _) (le_max_left _ _), have hy : y.1 ≤ m := le_trans (le_max_right _ _) (le_max_left _ _), have hz : z.1 ≤ m := le_max_right _ _, calc inductive_limit_dist f x z = dist (le_rec_on hx f x.2 : X m) (le_rec_on hz f z.2 : X m) : inductive_limit_dist_eq_dist I x z m hx hz ... ≤ dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) + dist (le_rec_on hy f y.2 : X m) (le_rec_on hz f z.2 : X m) : dist_triangle _ _ _ ... = inductive_limit_dist f x y + inductive_limit_dist f y z : by rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y z m hy hz] end } local attribute [instance] inductive_premetric pseudo_metric.dist_setoid /-- The type giving the inductive limit in a metric space context. -/ def inductive_limit (I : ∀ n, isometry (f n)) : Type* := @pseudo_metric_quot _ (inductive_premetric I) /-- Metric space structure on the inductive limit. -/ instance metric_space_inductive_limit (I : ∀ n, isometry (f n)) : metric_space (inductive_limit I) := @metric_space_quot _ (inductive_premetric I) /-- Mapping each `X n` to the inductive limit. -/ def to_inductive_limit (I : ∀ n, isometry (f n)) (n : ℕ) (x : X n) : metric.inductive_limit I := by letI : pseudo_metric_space (Σ n, X n) := inductive_premetric I; exact ⟦sigma.mk n x⟧ instance (I : ∀ n, isometry (f n)) [inhabited (X 0)] : inhabited (inductive_limit I) := ⟨to_inductive_limit _ 0 default⟩ /-- The map `to_inductive_limit n` mapping `X n` to the inductive limit is an isometry. -/ lemma to_inductive_limit_isometry (I : ∀ n, isometry (f n)) (n : ℕ) : isometry (to_inductive_limit I n) := isometry.of_dist_eq $ λ x y, begin change inductive_limit_dist f ⟨n, x⟩ ⟨n, y⟩ = dist x y, rw [inductive_limit_dist_eq_dist I ⟨n, x⟩ ⟨n, y⟩ n (le_refl n) (le_refl n), le_rec_on_self, le_rec_on_self] end /-- The maps `to_inductive_limit n` are compatible with the maps `f n`. -/ lemma to_inductive_limit_commute (I : ∀ n, isometry (f n)) (n : ℕ) : (to_inductive_limit I n.succ) ∘ (f n) = to_inductive_limit I n := begin funext, simp only [comp, to_inductive_limit, quotient.eq], show inductive_limit_dist f ⟨n.succ, f n x⟩ ⟨n, x⟩ = 0, { rw [inductive_limit_dist_eq_dist I ⟨n.succ, f n x⟩ ⟨n, x⟩ n.succ, le_rec_on_self, le_rec_on_succ, le_rec_on_self, dist_self], exact le_rfl, exact le_rfl, exact le_succ _ } end end inductive_limit --section end metric --namespace
aa70765c3ee8647061f6a36638623432637038d3
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/constructions.lean
02707ef244e0571744929ff9bb43ebf7494723c0
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
30,185
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter lattice open_locale classical topological_space universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced subtype.val t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ := eq_univ_of_forall $ λ x, begin rw mem_closure_iff, intros U U_op x_in_U, let V := quotient.mk ⁻¹' U, cases quotient.exists_rep x with y y_x, have y_in_V : y ∈ V, by simp only [mem_preimage, y_x, x_in_U], have V_op : is_open V := U_op, obtain ⟨w, w_in_V, w_in_range⟩ : (V ∩ s).nonempty := mem_closure_iff.1 (H y) V V_op y_in_V, exact ⟨_, w_in_V, mem_image_of_mem quotient.mk w_in_range⟩ end instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨subtype.val '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.val_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 a.val, (@subtype.val α s) ⁻¹' u ⊆ t := mem_nhds_induced subtype.val a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap subtype.val (𝓝 a.val) := nhds_induced subtype.val a end topα end constructions section prod open topological_space variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = filter.prod (𝓝 a) (𝓝 b) := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := by rw [nhds_prod_eq]; exact prod_mem_prod ha hb lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma prod_generate_from_generate_from_eq {α : Type*} {β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open_prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := begin assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₁, refine ⟨o₁, _, o₁_open, yo₁⟩, assume z zs, rw mem_image_eq, exact ⟨(z, y₂), ho (by simp [zs, yo₂]), rfl⟩ end /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := begin /- This lemma could be proved by composing the fact that the first projection is open, and exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/ assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₂, refine ⟨o₂, _, o₂_open, yo₂⟩, assume z zs, rw mem_image_eq, exact ⟨(y₁, z), ho (by simp [zs, yo₁]), rfl⟩ end /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (set.prod s t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp [st.1.ne_empty, st.2.ne_empty] at H, exact is_open_prod H.1 H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have filter.prod (𝓝 a) (𝓝 b) ⊓ principal (set.prod s t) = filter.prod (𝓝 a ⊓ principal s) (𝓝 b ⊓ principal t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_ne_bot lemma mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed_prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed] lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_inl : continuous (@sum.inl α β) := continuous_sup_rng_left continuous_coinduced_rng lemma continuous_inr : continuous (@sum.inr α β) := continuous_sup_rng_right continuous_coinduced_rng lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_sup_dom hf hg lemma embedding_inl : embedding (@sum.inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_left }, { intros u hu, existsi (sum.inl '' u), change (is_open (sum.inl ⁻¹' (@sum.inl α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inl α β '' u))) ∧ sum.inl ⁻¹' (sum.inl '' u) = u, have : sum.inl ⁻¹' (@sum.inl α β '' u) = u := preimage_image_eq u (λ _ _, sum.inl.inj_iff.mp), rw this, have : sum.inr ⁻¹' (@sum.inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, sum.inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, sum.inl.inj_iff.mp } lemma embedding_inr : embedding (@sum.inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_right }, { intros u hu, existsi (sum.inr '' u), change (is_open (sum.inl ⁻¹' (@sum.inr α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inr α β '' u))) ∧ sum.inr ⁻¹' (sum.inr '' u) = u, have : sum.inl ⁻¹' (@sum.inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, sum.inr_ne_inl h), rw this, have : sum.inr ⁻¹' (@sum.inr α β '' u) = u := preimage_image_eq u (λ _ _, sum.inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, sum.inr.inj_iff.mp } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_val : embedding (@subtype.val α p) := ⟨⟨rfl⟩, subtype.val_injective⟩ lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma is_open.open_embedding_subtype_val {s : set α} (hs : is_open s) : open_embedding (subtype.val : s → α) := { induced := rfl, inj := subtype.val_injective, open_range := (subtype.val_range : range subtype.val = s).symm ▸ hs } lemma is_open.is_open_map_subtype_val {s : set α} (hs : is_open s) : is_open_map (subtype.val : s → α) := hs.open_embedding_subtype_val.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (function.restrict f s) := hf.comp hs.is_open_map_subtype_val lemma is_closed.closed_embedding_subtype_val {s : set α} (hs : is_closed s) : closed_embedding (subtype.val : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.val_injective, closed_range := (subtype.val_range : range subtype.val = s).symm ▸ hs } lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_val lemma continuous_at_subtype_val {p : α → Prop} {a : subtype p} : continuous_at subtype.val a := continuous_iff_continuous_at.mp continuous_subtype_val _ lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (@subtype.val α p) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_eq (by simp [subtype.val_image, h]) lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap subtype.val (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, subtype.val (f x)) b (𝓝 a.val) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map subtype.val (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x.val) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_val (by simp [subtype.val_range]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simp [and.comm, and.left_comm], simpa [(∘)], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) := closure_induced $ assume x y, subtype.eq end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} open topological_space lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom /-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is continuous. -/ lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} : continuous (λ x : π i, function.update f i x) := begin refine continuous_pi (λj, _), by_cases h : j = i, { rw h, simpa using continuous_id }, { simpa [h] using continuous_const } end lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha) lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] open lattice lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := is_open_sigma_iff lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk injective_sigma_mk is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk injective_sigma_mk is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, injective_sigma_map function.injective_id (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext p, rcases p with ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h ... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
acff1801aeb8579f0ee72c9f51230a9e887e0282
4e3bf8e2b29061457a887ac8889e88fa5aa0e34c
/lean/love12_basic_mathematical_structures_demo.lean
06bc0bf4781a341cbadaacc0a5ea16a455229211
[]
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
6,197
lean
/- LoVe Demo 12: Basic Mathematical Structures -/ import .love05_inductive_predicates_demo namespace LoVe /- Type Classes -/ -- The `inhabited` typeclass for types that contain at least one element #check inhabited -- `nonempty` lives in `Prop`, whereas `inhabited` lives in `Type` #check nonempty -- Recall: `head` returns `option α` #check head -- Variant of `head` for inhabited types def ihead {α : Type} [inhabited α] (xs : list α) : α := match xs with | [] := inhabited.default α | x :: _ := x end lemma ihead_ihead {α : Type} [inhabited α] (xs : list α) : ihead [ihead xs] = ihead xs := begin cases xs, { refl }, { refl } end -- The natural numbers can be made an instance as follows: instance : inhabited ℕ := { default := 0 } #reduce inhabited.default ℕ #reduce ihead ([] : list ℕ) #check ihead_ihead ([1, 2, 3] : list ℕ) -- Syntactic type classes #check has_zero #check has_neg #check has_add #check has_one #check has_inv #check has_mul #check (1 : ℕ) #check (1 : ℤ) #check (1 : ℝ) #check (1 : linear_map _ _ _) /- Groups -/ #print group #print add_group inductive ℤ₂ : Type | zero | one def ℤ₂.add : ℤ₂ → ℤ₂ → ℤ₂ | ℤ₂.zero x := x | x ℤ₂.zero := x | ℤ₂.one ℤ₂.one := ℤ₂.zero instance ℤ₂.add_group : add_group ℤ₂ := { add := ℤ₂.add, add_assoc := begin intros a b c, simp [(+)], cases a; cases b; cases c; refl end, zero := ℤ₂.zero, zero_add := begin intro a, cases a; refl end, add_zero := begin intro a, cases a; refl end, neg := (λ x, x), add_left_neg := begin intro a, cases a; refl end } #reduce ℤ₂.one + 0 - 0 - ℤ₂.one example : ∀a : ℤ₂, a + - a = 0 := add_right_neg -- Another example: lists as `add_monoid`: instance {α : Type} : add_monoid (list α) := { zero := [], add := (++), add_assoc := list.append_assoc, zero_add := list.nil_append, add_zero := list.append_nil } /- Fields -/ #print field def ℤ₂.mul : ℤ₂ → ℤ₂ → ℤ₂ | ℤ₂.one x := x | x ℤ₂.one := x | ℤ₂.zero ℤ₂.zero := ℤ₂.zero instance : field ℤ₂ := { one := ℤ₂.one, mul := ℤ₂.mul, inv := λx, x, add_comm := begin intros a b, cases a; cases b; refl end, zero_ne_one := begin intro h, cases h end, one_mul := begin intros a, cases a; refl end, mul_one := begin intros a, cases a; refl end, mul_inv_cancel := begin intros a h, cases a, apply false.elim, apply h, refl, refl end, inv_mul_cancel := begin intros a h, cases a, apply false.elim, apply h, refl, refl end, mul_assoc := begin intros a b c, cases a; cases b; cases c; refl end, mul_comm := begin intros a b, cases a; cases b; refl end, left_distrib := begin intros a b c, cases a; cases b; cases c; refl end, right_distrib := begin intros a b c, cases a; cases b; cases c; refl end, ..ℤ₂.add_group } #reduce (1 : ℤ₂) * 0 / (0 - 1) -- result: ℤ₂.zero #reduce (3 : ℤ₂) -- result: ℤ₂.one example (a b : ℤ₂) : (a + b) ^ 3 = a ^ 3 + 3 * a^2 * b + 3 * a * b ^ 2 + b ^ 3 := by ring -- normalizes terms of rings example (a b : ℤ) : (a + b + 0) - ((b + a) + a) = -a := by abel -- normalizes terms of commutative monoids /- Coercions -/ lemma neg_mul_neg_nat (n : ℕ) (z : ℤ) : (- z) * (- n) = z * n := neg_mul_neg z n -- This works, althogh negation `- n` is not defined on natural numbers. #print neg_mul_neg_nat -- Lean introduced a coercion `↑` automatically. lemma neg_mul_neg_nat₂ (n : ℕ) (z : ℤ) : (- n : ℤ) * (- z) = n * z := neg_mul_neg n z #print neg_mul_neg_nat₂ example (m n : ℕ) (h : (m : ℤ) = (n : ℤ)) : m = n := begin norm_cast at h, exact h end example (m n : ℕ) : (m : ℤ) + (n : ℤ) = ((m + n : ℕ) : ℤ) := begin norm_cast end -- norm_cast internally uses lemmas such as: #check nat.cast_add #check int.cast_add #check rat.cast_add /- Lists, Multisets and Finite Sets -/ -- lists: number of occurrences and order matter example : [1, 2, 2, 3] ≠ [1, 2, 3] := dec_trivial example : [3, 2, 1] ≠ [1, 2, 3] := dec_trivial -- multisets: number of occurrences matters, order doesn't example : ({1, 2, 2, 3} : multiset ℕ) ≠ {1, 2, 3} := dec_trivial example : ({1, 2, 3} : multiset ℕ) = {3, 2, 1} := dec_trivial -- finsets: number of occurrences and order don't matter example : ({1, 2, 2, 3} : finset ℕ) = {1, 2, 3} := dec_trivial example : ({1, 2, 3} : finset ℕ) = {3, 2, 1} := dec_trivial -- `dec_trivial` can solve goals for which Lean can infer an algorithm -- to compute their truth value, i.e., trivially decidable goals -- list of nodes (depth first) def nodes_list : btree ℕ → list ℕ | empty := [] | (node a t₁ t₂) := a :: nodes_list t₁ ++ nodes_list t₂ -- multiset of nodes def nodes_multiset : btree ℕ → multiset ℕ | empty := ∅ | (node a t₁ t₂) := insert a (nodes_multiset t₁ ∪ nodes_multiset t₂) -- finset of nodes def nodes_finset : btree ℕ → finset ℕ | empty := ∅ | (node a t₁ t₂) := insert a (nodes_finset t₁ ∪ nodes_finset t₂) #eval list.sum [1, 2, 3, 4] -- result: 10 #eval multiset.sum ({1, 2, 3, 4} : multiset ℕ) -- result: 10 #eval finset.sum ({1, 2, 3, 4} : finset ℕ) (λx, x) -- result: 10 #eval list.prod [1, 2, 3, 4] -- result: 24 #eval multiset.prod ({1, 2, 3, 4} : multiset ℕ) -- result: 24 #eval finset.prod ({1, 2, 3, 4} : finset ℕ) (λx, x) -- result: 24 end LoVe
679c9b6852254079b283ef11910fe8411b79328c
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/with_cases1.lean
88da6116689b5e2b230d71a07e83076581caca8d
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,402
lean
example (n : nat) (m : nat) : n > m → m < n := begin with_cases { revert m, induction n }, case nat.zero : m' { show 0 > m' → m' < 0, admit }, case nat.succ : n' ih m' { show nat.succ n' > m' → m' < nat.succ n', admit } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { revert m, induction n }, case nat.zero { show ∀ m, 0 > m → m < 0, admit }, case nat.succ { show ∀ m, nat.succ n_n > m → m < nat.succ n_n, admit } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { induction n generalizing m }, case nat.zero { show 0 > m → m < 0, admit }, case nat.succ { show nat.succ n_n > m → m < nat.succ n_n, admit } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { induction n generalizing m }, case nat.zero : m' { show 0 > m' → m' < 0, admit }, case nat.succ : n' ih m' { show nat.succ n' > m' → m' < nat.succ n', admit } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { induction n generalizing m }, case nat.zero : m' { show 0 > m' → m' < 0, admit }, case nat.succ : n' ih { show nat.succ n' > m → m < nat.succ n', admit } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { induction n generalizing m }, case nat.zero { show 0 > m → m < 0, admit }, case nat.succ : n' ih { show nat.succ n' > m → m < nat.succ n', admit } end
cae83f519ab510d866c52073d0c2c353f1ccbb52
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/ring_theory/algebraic.lean
48abe2914247975cff1057c07089c7fdfb3c7cb1
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
4,654
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import linear_algebra.finite_dimensional import ring_theory.integral_closure /-! # Algebraic elements and algebraic extensions An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. An R-algebra is algebraic over R if and only if all its elements are algebraic over R. The main result in this file proves transitivity of algebraicity: a tower of algebraic field extensions is algebraic. -/ universe variables u v open_locale classical open polynomial section variables (R : Type u) {A : Type v} [comm_ring R] [comm_ring A] [algebra R A] /-- An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. -/ def is_algebraic (x : A) : Prop := ∃ p : polynomial R, p ≠ 0 ∧ aeval R A x p = 0 variables {R} /-- A subalgebra is algebraic if all its elements are algebraic. -/ def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x variables (R A) /-- An algebra is algebraic if all its elements are algebraic. -/ def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x variables {R A} /-- A subalgebra is algebraic if and only if it is algebraic an algebra. -/ lemma subalgebra.is_algebraic_iff (S : subalgebra R A) : S.is_algebraic ↔ @algebra.is_algebraic R S _ _ (S.algebra) := begin delta algebra.is_algebraic subalgebra.is_algebraic, rw [subtype.forall'], apply forall_congr, rintro ⟨x, hx⟩, apply exists_congr, intro p, apply and_congr iff.rfl, have h : function.injective (S.val) := subtype.val_injective, conv_rhs { rw [← h.eq_iff, alg_hom.map_zero], }, rw [← aeval_alg_hom_apply, S.val_apply, subtype.val_eq_coe], end /-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/ lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic := begin delta algebra.is_algebraic subalgebra.is_algebraic, simp only [algebra.mem_top, forall_prop_of_true, iff_self], end end section zero_ne_one variables (R : Type u) {A : Type v} [comm_ring R] [nontrivial R] [comm_ring A] [algebra R A] /-- An integral element of an algebra is algebraic.-/ lemma is_integral.is_algebraic {x : A} (h : is_integral R x) : is_algebraic R x := by { rcases h with ⟨p, hp, hpx⟩, exact ⟨p, hp.ne_zero, hpx⟩ } end zero_ne_one section field variables (K : Type u) {A : Type v} [field K] [comm_ring A] [algebra K A] /-- An element of an algebra over a field is algebraic if and only if it is integral.-/ lemma is_algebraic_iff_is_integral {x : A} : is_algebraic K x ↔ is_integral K x := begin refine ⟨_, is_integral.is_algebraic K⟩, rintro ⟨p, hp, hpx⟩, refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩, rw [alg_hom.map_mul, hpx, zero_mul], end end field namespace algebra variables {K : Type*} {L : Type*} {A : Type*} variables [field K] [field L] [comm_ring A] variables [algebra K L] [algebra L A] [algebra K A] [is_algebra_tower K L A] /-- If L is an algebraic field extension of K and A is an algebraic algebra over L, then A is algebraic over K. -/ lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) : is_algebraic K A := begin simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢, exact is_integral_trans L_alg A_alg, end /-- A field extension is algebraic if it is finite. -/ lemma is_algebraic_of_finite [finite : finite_dimensional K L] : is_algebraic K L := λ x, (is_algebraic_iff_is_integral _).mpr (is_integral_of_noetherian ⊤ (is_noetherian_of_submodule_of_noetherian _ _ _ finite) x algebra.mem_top) end algebra variables {R S : Type*} [integral_domain R] [comm_ring S] lemma exists_integral_multiple [algebra R S] {z : S} (hz : is_algebraic R z) (inj : ∀ x, algebra_map R S x = 0 → x = 0) : ∃ (x : integral_closure R S) (y ≠ (0 : integral_closure R S)), z * y = x := begin rcases hz with ⟨p, p_ne_zero, px⟩, set n := p.nat_degree with n_def, set a := p.leading_coeff with a_def, have a_ne_zero : a ≠ 0 := mt polynomial.leading_coeff_eq_zero.mp p_ne_zero, have y_integral : is_integral R (algebra_map R S a) := is_integral_algebra_map, have x_integral : is_integral R (z * algebra_map R S a) := ⟨ p.integral_normalization, monic_integral_normalization p_ne_zero, integral_normalization_aeval_eq_zero p_ne_zero px inj ⟩, refine ⟨⟨_, x_integral⟩, ⟨_, y_integral⟩, _, rfl⟩, exact λ h, a_ne_zero (inj _ (subtype.ext_iff_val.mp h)) end
c78a10cdfe7fd32309c14b7666a793b4d88ae9e5
3ed5a65c1ab3ce5d1a094edce8fa3287980f197b
/src/herstein/ex2_3/Q_03.lean
062ca8675de239e631088e37cd3aad74964d81a8
[]
no_license
group-study-group/herstein
35d32e77158efa2cc303c84e1ee5e3bc80831137
f5a1a72eb56fa19c19ece0cb3ab6cf7ffd161f66
refs/heads/master
1,586,202,191,519
1,548,969,759,000
1,548,969,759,000
157,746,953
0
0
null
1,542,412,901,000
1,542,302,366,000
Lean
UTF-8
Lean
false
false
844
lean
import algebra.group algebra.group_power variables {G: Type*} theorem Q_03 [hG: group G]: (∀ a b: G, (a * b) ^ 2 = a ^ 2 * b ^ 2) → comm_group G := λ h, begin have lem: ∀ a b: G, a * (a * b) * b = a * (b * a) * b, from λ a b, calc a * (a * b) * b = a * a * (b * b) : by rw [←mul_assoc, mul_assoc] ... = a * a ^ 1 * (b * b ^ 1) : by rw [pow_one, pow_one] ... = a ^ 2 * b ^ 2 : by rw [←pow_succ, ←pow_succ] ... = (a * b) ^ 2 : (h a b).symm ... = a * b * (a * b) : by rw [pow_succ, pow_one] ... = a * (b * a) * b : by rw [←mul_assoc, ←mul_assoc], have comm: ∀ a b: G, a * b = b * a, from λ a b, mul_left_cancel (mul_right_cancel (lem a b)), -- G is a group, together with comm, show that -- G is an abelian group: exact { mul_comm := comm, .. hG }, end
05da6531ebabcca88f109e5a9e1c10fe88f9686c
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/bases.lean
c0049e831da344cbd6197c2710796a13950f55a5
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
10,502
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 Bases of topologies. Countability axioms. -/ import topology.order data.set.countable open set filter lattice classical namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b, by simpa only [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _, by rw sInter_empty; exact nonempty_iff_univ_ne_empty.1 ⟨a⟩⟩, sInter_empty⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (generate_from_le $ assume s hs, by_cases (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s ≠ ∅, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs, by rwa [sInter_singleton]⟩, sInter_singleton s⟩)) (generate_from_le $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, _root_.is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in ⟨u, h₁, h₂⟩, le_antisymm (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu)) (generate_from_le h_open)⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ nhds a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin change s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s, rw [hb.2.2, nhds_generate_from, infi_sets_eq'], { simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au lemma sUnion_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩ lemma Union_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in ⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩ variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t)) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b}, countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, countable_image _ hb, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [topological_space α] [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in ⟨b', countable_image _ $ countable_subset (by simp only [(and_assoc _ _).symm]; exact inter_subset_left _ _) (countable_set_of_finite_subset hb₁), assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp, is_topological_basis_of_subbasis hb₂⟩ instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val), by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl, have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs, have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this, let ⟨f, hf⟩ := this in ⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}), countable_bUnion hb₁ (λ _ _, countable_Union_Prop $ λ _, countable_singleton _), set.ext $ assume a, have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial, let ⟨t, ht₁, ht₂⟩ := this in have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩, suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥, by simpa only [closure_eq_nhds, nhds_eq, infi_inf w, inf_principal, mem_set_of_eq, mem_univ, iff_true], infi_neq_bot_of_directed ⟨a⟩ (assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩, let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in ⟨⟨s₃, has₃, hs₃⟩, begin simp only [le_principal_iff, mem_principal_sets, (≥)], simp only [subset_inter_iff] at hs, split; apply inter_subset_inter_left; simp only [hs] end⟩) (assume ⟨s, has, hs⟩, have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅, from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩, mt principal_eq_bot_iff.1 this) ⟩⟩ variables {α} lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, _root_.is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in begin let B' := {b ∈ B | ∃ i, b ⊆ s i}, choose f hf using λ b:B', b.2.2, haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable, refine ⟨_, countable_range f, subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, countable_image _ cT, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ end topological_space
64484a04779bd65eea2b77e5e68f1b5f19c33573
bb31430994044506fa42fd667e2d556327e18dfe
/src/number_theory/cyclotomic/discriminant.lean
f268b04516fcd5969f8ad7cbe0de31f8c57c2fca
[ "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
11,500
lean
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import number_theory.cyclotomic.primitive_roots import ring_theory.discriminant /-! # Discriminant of cyclotomic fields We compute the discriminant of a `p ^ n`-th cyclotomic extension. ## Main results * `is_cyclotomic_extension.discr_odd_prime` : if `p` is an odd prime such that `is_cyclotomic_extension {p} K L` and `irreducible (cyclotomic p K)`, then `discr K (hζ.power_basis K).basis = (-1) ^ ((p - 1) / 2) * p ^ (p - 2)` for any `hζ : is_primitive_root ζ p`. -/ universes u v open algebra polynomial nat is_primitive_root power_basis open_locale polynomial cyclotomic namespace is_primitive_root variables {n : ℕ+} {K : Type u} [field K] [char_zero K] {ζ : K} variables [is_cyclotomic_extension {n} ℚ K] /-- The discriminant of the power basis given by a primitive root of unity `ζ` is the same as the discriminant of the power basis given by `ζ - 1`. -/ lemma discr_zeta_eq_discr_zeta_sub_one (hζ : is_primitive_root ζ n) : discr ℚ (hζ.power_basis ℚ).basis = discr ℚ (hζ.sub_one_power_basis ℚ).basis := begin haveI : number_field K := number_field.mk, have H₁ : (aeval (hζ.power_basis ℚ).gen) (X - 1 : ℤ[X]) = (hζ.sub_one_power_basis ℚ).gen := by simp, have H₂ : (aeval (hζ.sub_one_power_basis ℚ).gen) (X + 1 : ℤ[X]) = (hζ.power_basis ℚ).gen := by simp, refine discr_eq_discr_of_to_matrix_coeff_is_integral _ (λ i j, to_matrix_is_integral H₁ _ _ _ _) (λ i j, to_matrix_is_integral H₂ _ _ _ _), { exact hζ.is_integral n.pos }, { refine minpoly.gcd_domain_eq_field_fractions' _ (hζ.is_integral n.pos) }, { exact is_integral_sub (hζ.is_integral n.pos) is_integral_one }, { refine minpoly.gcd_domain_eq_field_fractions' _ _, exact is_integral_sub (hζ.is_integral n.pos) is_integral_one } end end is_primitive_root namespace is_cyclotomic_extension variables {p : ℕ+} {k : ℕ} {K : Type u} {L : Type v} {ζ : L} [field K] [field L] variables [algebra K L] /-- If `p` is a prime and `is_cyclotomic_extension {p ^ (k + 1)} K L`, then the discriminant of `hζ.power_basis K` is `(-1) ^ ((p ^ (k + 1).totient) / 2) * p ^ (p ^ k * ((p - 1) * (k + 1) - 1))` if `irreducible (cyclotomic (p ^ (k + 1)) K))`, and `p ^ (k + 1) ≠ 2`. -/ lemma discr_prime_pow_ne_two [is_cyclotomic_extension {p ^ (k + 1)} K L] [hp : fact (p : ℕ).prime] (hζ : is_primitive_root ζ ↑(p ^ (k + 1))) (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (hk : p ^ (k + 1) ≠ 2) : discr K (hζ.power_basis K).basis = (-1) ^ (((p ^ (k + 1) : ℕ).totient) / 2) * p ^ ((p : ℕ) ^ k * ((p - 1) * (k + 1) - 1)) := begin haveI hne := is_cyclotomic_extension.ne_zero' (p ^ (k + 1)) K L, have hp2 : p = 2 → 1 ≤ k, { intro hp, refine one_le_iff_ne_zero.2 (λ h, _), rw [h, hp, zero_add, pow_one] at hk, exact hk rfl }, rw [discr_power_basis_eq_norm, finrank _ hirr, hζ.power_basis_gen _, ← hζ.minpoly_eq_cyclotomic_of_irreducible hirr, pnat.pow_coe, totient_prime_pow hp.out (succ_pos k)], congr' 1, { by_cases hptwo : p = 2, { obtain ⟨k₁, hk₁⟩ := nat.exists_eq_succ_of_ne_zero (one_le_iff_ne_zero.1 (hp2 hptwo)), rw [hk₁, succ_sub_one, hptwo, pnat.coe_bit0, pnat.one_coe, succ_sub_succ_eq_sub, tsub_zero, mul_one, pow_succ, mul_assoc, nat.mul_div_cancel_left _ zero_lt_two, nat.mul_div_cancel_left _ zero_lt_two], by_cases hk₁zero : k₁ = 0, { simp [hk₁zero] }, obtain ⟨k₂, rfl⟩ := nat.exists_eq_succ_of_ne_zero hk₁zero, rw [pow_succ, mul_assoc, pow_mul (-1 : K), pow_mul (-1 : K), neg_one_sq, one_pow, one_pow] }, { simp only [succ_sub_succ_eq_sub, tsub_zero], replace hptwo : ↑p ≠ 2, { intro h, rw [← pnat.one_coe, ← pnat.coe_bit0, pnat.coe_inj] at h, exact hptwo h }, obtain ⟨a, ha⟩ := even_sub_one_of_prime_ne_two hp.out hptwo, rw [mul_comm ((p : ℕ) ^ k), mul_assoc, ha], nth_rewrite 0 [← mul_one a], nth_rewrite 4 [← mul_one a], rw [← nat.mul_succ, mul_comm a, mul_assoc, mul_assoc 2, nat.mul_div_cancel_left _ zero_lt_two, nat.mul_div_cancel_left _ zero_lt_two, ← mul_assoc, mul_comm (a * (p : ℕ) ^ k), pow_mul, ← ha], congr' 1, refine odd.neg_one_pow (nat.even.sub_odd (nat.succ_le_iff.2 (mul_pos (tsub_pos_iff_lt.2 hp.out.one_lt) (pow_pos hp.out.pos _))) (even.mul_right (nat.even_sub_one_of_prime_ne_two hp.out hptwo) _) odd_one) } }, { have H := congr_arg derivative (cyclotomic_prime_pow_mul_X_pow_sub_one K p k), rw [derivative_mul, derivative_sub, derivative_one, sub_zero, derivative_X_pow, C_eq_nat_cast, derivative_sub, derivative_one, sub_zero, derivative_X_pow, C_eq_nat_cast, ← pnat.pow_coe, hζ.minpoly_eq_cyclotomic_of_irreducible hirr] at H, replace H := congr_arg (λ P, aeval ζ P) H, simp only [aeval_add, aeval_mul, minpoly.aeval, zero_mul, add_zero, aeval_nat_cast, _root_.map_sub, aeval_one, aeval_X_pow] at H, replace H := congr_arg (algebra.norm K) H, have hnorm : (norm K) (ζ ^ (p : ℕ) ^ k - 1) = p ^ ((p : ℕ) ^ k), { by_cases hp : p = 2, { exact hζ.pow_sub_one_norm_prime_pow_of_one_le hirr rfl.le (hp2 hp) }, { exact hζ.pow_sub_one_norm_prime_ne_two hirr rfl.le hp } }, rw [monoid_hom.map_mul, hnorm, monoid_hom.map_mul, ← map_nat_cast (algebra_map K L), algebra.norm_algebra_map, finrank _ hirr, pnat.pow_coe, totient_prime_pow hp.out (succ_pos k), nat.sub_one, nat.pred_succ, ← hζ.minpoly_eq_cyclotomic_of_irreducible hirr, map_pow, hζ.norm_eq_one hk hirr, one_pow, mul_one, cast_pow, ← coe_coe, ← pow_mul, ← mul_assoc, mul_comm (k + 1), mul_assoc] at H, { have := mul_pos (succ_pos k) (tsub_pos_iff_lt.2 hp.out.one_lt), rw [← succ_pred_eq_of_pos this, mul_succ, pow_add _ _ ((p : ℕ) ^ k)] at H, replace H := (mul_left_inj' (λ h, _)).1 H, { simpa only [← pnat.pow_coe, H, mul_comm _ (k + 1)] }, { replace h := pow_eq_zero h, rw [coe_coe] at h, simpa using hne.1 } }, all_goals { apply_instance } }, all_goals { apply_instance } end /-- If `p` is a prime and `is_cyclotomic_extension {p ^ (k + 1)} K L`, then the discriminant of `hζ.power_basis K` is `(-1) ^ (p ^ k * (p - 1) / 2) * p ^ (p ^ k * ((p - 1) * (k + 1) - 1))` if `irreducible (cyclotomic (p ^ (k + 1)) K))`, and `p ^ (k + 1) ≠ 2`. -/ lemma discr_prime_pow_ne_two' [is_cyclotomic_extension {p ^ (k + 1)} K L] [hp : fact (p : ℕ).prime] (hζ : is_primitive_root ζ ↑(p ^ (k + 1))) (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K)) (hk : p ^ (k + 1) ≠ 2) : discr K (hζ.power_basis K).basis = (-1) ^ (((p : ℕ) ^ k * (p - 1)) / 2) * p ^ ((p : ℕ) ^ k * ((p - 1) * (k + 1) - 1)) := by simpa [totient_prime_pow hp.out (succ_pos k)] using discr_prime_pow_ne_two hζ hirr hk /-- If `p` is a prime and `is_cyclotomic_extension {p ^ k} K L`, then the discriminant of `hζ.power_basis K` is `(-1) ^ ((p ^ k).totient / 2) * p ^ (p ^ (k - 1) * ((p - 1) * k - 1))` if `irreducible (cyclotomic (p ^ k) K))`. Beware that in the cases `p ^ k = 1` and `p ^ k = 2` the formula uses `1 / 2 = 0` and `0 - 1 = 0`. It is useful only to have a uniform result. See also `is_cyclotomic_extension.discr_prime_pow_eq_unit_mul_pow`. -/ lemma discr_prime_pow [hcycl : is_cyclotomic_extension {p ^ k} K L] [hp : fact (p : ℕ).prime] (hζ : is_primitive_root ζ ↑(p ^ k)) (hirr : irreducible (cyclotomic (↑(p ^ k) : ℕ) K)) : discr K (hζ.power_basis K).basis = (-1) ^ (((p ^ k : ℕ).totient) / 2) * p ^ ((p : ℕ) ^ (k - 1) * ((p - 1) * k - 1)) := begin unfreezingI { cases k }, { simp only [coe_basis, pow_zero, power_basis_gen, totient_one, mul_zero, mul_one, show 1 / 2 = 0, by refl, discr, trace_matrix], have hζone : ζ = 1 := by simpa using hζ, rw [hζ.power_basis_dim _, hζone, ← (algebra_map K L).map_one, minpoly.eq_X_sub_C_of_algebra_map_inj _ (algebra_map K L).injective, nat_degree_X_sub_C], simp only [trace_matrix, map_one, one_pow, matrix.det_unique, trace_form_apply, mul_one], rw [← (algebra_map K L).map_one, trace_algebra_map, finrank _ hirr], { simp }, { apply_instance }, { exact hcycl } }, { by_cases hk : p ^ (k + 1) = 2, { have hp : p = 2, { rw [← pnat.coe_inj, pnat.coe_bit0, pnat.one_coe, pnat.pow_coe, ← pow_one 2] at hk, replace hk := eq_of_prime_pow_eq (prime_iff.1 hp.out) (prime_iff.1 nat.prime_two) (succ_pos _) hk, rwa [show 2 = ((2 : ℕ+) : ℕ), by simp, pnat.coe_inj] at hk }, rw [hp, ← pnat.coe_inj, pnat.pow_coe, pnat.coe_bit0, pnat.one_coe] at hk, nth_rewrite 1 [← pow_one 2] at hk, replace hk := nat.pow_right_injective rfl.le hk, rw [add_left_eq_self] at hk, simp only [hp, hk, pow_one, pnat.coe_bit0, pnat.one_coe] at hζ, simp only [hp, hk, show 1 / 2 = 0, by refl, coe_basis, pow_one, power_basis_gen, pnat.coe_bit0, pnat.one_coe, totient_two, pow_zero, mul_one, mul_zero], rw [power_basis_dim, hζ.eq_neg_one_of_two_right, show (-1 : L) = algebra_map K L (-1), by simp, minpoly.eq_X_sub_C_of_algebra_map_inj _ (algebra_map K L).injective, nat_degree_X_sub_C], simp only [discr, trace_matrix, matrix.det_unique, fin.default_eq_zero, fin.coe_zero, pow_zero, trace_form_apply, mul_one], rw [← (algebra_map K L).map_one, trace_algebra_map, finrank _ hirr, hp, hk], { simp }, { apply_instance }, { exact hcycl } }, { exact discr_prime_pow_ne_two hζ hirr hk } } end /-- If `p` is a prime and `is_cyclotomic_extension {p ^ k} K L`, then there are `u : ℤˣ` and `n : ℕ` such that the discriminant of `hζ.power_basis K` is `u * p ^ n`. Often this is enough and less cumbersome to use than `is_cyclotomic_extension.discr_prime_pow`. -/ lemma discr_prime_pow_eq_unit_mul_pow [is_cyclotomic_extension {p ^ k} K L] [hp : fact (p : ℕ).prime] (hζ : is_primitive_root ζ ↑(p ^ k)) (hirr : irreducible (cyclotomic (↑(p ^ k) : ℕ) K)) : ∃ (u : ℤˣ) (n : ℕ), discr K (hζ.power_basis K).basis = u * p ^ n := begin rw [discr_prime_pow hζ hirr], by_cases heven : even (((p ^ k : ℕ).totient) / 2), { refine ⟨1, (p : ℕ) ^ (k - 1) * ((p - 1) * k - 1), by simp [heven.neg_one_pow]⟩ }, { exact ⟨-1, (p : ℕ) ^ (k - 1) * ((p - 1) * k - 1), by simp [(odd_iff_not_even.2 heven).neg_one_pow]⟩ }, end /-- If `p` is an odd prime and `is_cyclotomic_extension {p} K L`, then `discr K (hζ.power_basis K).basis = (-1) ^ ((p - 1) / 2) * p ^ (p - 2)` if `irreducible (cyclotomic p K)`. -/ lemma discr_odd_prime [is_cyclotomic_extension {p} K L] [hp : fact (p : ℕ).prime] (hζ : is_primitive_root ζ p) (hirr : irreducible (cyclotomic p K)) (hodd : p ≠ 2) : discr K (hζ.power_basis K).basis = (-1) ^ (((p : ℕ) - 1) / 2) * p ^ ((p : ℕ) - 2) := begin haveI : is_cyclotomic_extension {p ^ (0 + 1)} K L, { rw [zero_add, pow_one], apply_instance }, have hζ' : is_primitive_root ζ ↑(p ^ (0 + 1)) := by simpa using hζ, convert discr_prime_pow_ne_two hζ' (by simpa [hirr]) (by simp [hodd]), { rw [zero_add, pow_one, totient_prime hp.out] }, { rw [pow_zero, one_mul, zero_add, mul_one, nat.sub_sub] } end end is_cyclotomic_extension
80b27f6d77f105b42170111e899cb34e428af901
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/normed_space/hahn_banach.lean
799ee2f8b85d3e1243cf1a43271fcd6b74cc2825
[ "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
6,501
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 import analysis.normed_space.is_R_or_C import analysis.normed_space.extend /-! # Hahn-Banach theorem In this file we prove a version of Hahn-Banach theorem for continuous linear functions on normed spaces over `ℝ` and `ℂ`. In order to state and prove its 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*} [semi_normed_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*} [semi_normed_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_eq_neg_mul_symm, 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_eq_neg_mul_symm, 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.extend_to_𝕜.op_norm_le_bound g.op_norm_nonneg (norm_bound _) ... = ∥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_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
58e55cf3460be496c38622b3a16ae78d5048c9ec
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/preserves/functor_category.lean
a267cd407e0df511cb70ef67046371e13f39334f
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,489
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 category_theory.limits.functor_category import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.yoneda import category_theory.limits.presheaf /-! # Preservation of (co)limits in the functor category * Show that if `X ⨯ -` preserves colimits in `D` for any `X : D`, then the product functor `F ⨯ -` for `F : C ⥤ D` preserves colimits. The idea of the proof is simply that products and colimits in the functor category are computed pointwise, so pointwise preservation implies general preservation. * Show that `F ⋙ -` preserves limits if the target category has limits. * Show that `F : C ⥤ D` preserves limits of a certain shape if `Lan F.op : Cᵒᵖ ⥤ Type*` preserves such limits. # References https://ncatlab.org/nlab/show/commutativity+of+limits+and+colimits#preservation_by_functor_categories_and_localizations -/ universes v₁ v₂ u u₂ noncomputable theory namespace category_theory open category limits variables {C : Type u} [category.{v₁} C] variables {D : Type u₂} [category.{u} D] variables {E : Type u} [category.{v₂} E] /-- If `X × -` preserves colimits in `D` for any `X : D`, then the product functor `F ⨯ -` for `F : C ⥤ D` also preserves colimits. Note this is (mathematically) a special case of the statement that "if limits commute with colimits in `D`, then they do as well in `C ⥤ D`" but the story in Lean is a bit more complex, and this statement isn't directly a special case. That is, even with a formalised proof of the general statement, there would still need to be some work to convert to this version: namely, the natural isomorphism `(evaluation C D).obj k ⋙ prod.functor.obj (F.obj k) ≅ prod.functor.obj F ⋙ (evaluation C D).obj k` -/ def functor_category.prod_preserves_colimits [has_binary_products D] [has_colimits D] [∀ (X : D), preserves_colimits (prod.functor.obj X)] (F : C ⥤ D) : preserves_colimits (prod.functor.obj F) := { preserves_colimits_of_shape := λ J 𝒥, by exactI { preserves_colimit := λ K, { preserves := λ c t, begin apply evaluation_jointly_reflects_colimits _ (λ k, _), change is_colimit ((prod.functor.obj F ⋙ (evaluation _ _).obj k).map_cocone c), let := is_colimit_of_preserves ((evaluation C D).obj k ⋙ prod.functor.obj (F.obj k)) t, apply is_colimit.map_cocone_equiv _ this, apply (nat_iso.of_components _ _).symm, { intro G, apply as_iso (prod_comparison ((evaluation C D).obj k) F G) }, { intros G G', apply prod_comparison_natural ((evaluation C D).obj k) (𝟙 F) }, end } } } instance whiskering_left_preserves_limits [has_limits D] (F : C ⥤ E) : preserves_limits ((whiskering_left C E D).obj F) := ⟨λ J hJ, by exactI ⟨λ K, ⟨λ c hc, begin apply evaluation_jointly_reflects_limits, intro Y, change is_limit (((evaluation E D).obj (F.obj Y)).map_cone c), exact preserves_limit.preserves hc, end ⟩⟩⟩ instance whiskering_right_preserves_limits_of_shape {C : Type u} [category C] {D : Type*} [category.{u} D] {E : Type*} [category.{u} E] {J : Type u} [small_category J] [has_limits_of_shape J D] (F : D ⥤ E) [preserves_limits_of_shape J F] : preserves_limits_of_shape J ((whiskering_right C D E).obj F) := ⟨λ K, ⟨λ c hc, begin apply evaluation_jointly_reflects_limits, intro k, change is_limit (((evaluation _ _).obj k ⋙ F).map_cone c), exact preserves_limit.preserves hc, end ⟩⟩ instance whiskering_right_preserves_limits {C : Type u} [category C] {D : Type*} [category.{u} D] {E : Type*} [category.{u} E] (F : D ⥤ E) [has_limits D] [preserves_limits F] : preserves_limits ((whiskering_right C D E).obj F) := ⟨⟩ /-- If `Lan F.op : (Cᵒᵖ ⥤ Type*) ⥤ (Dᵒᵖ ⥤ Type*)` preserves limits of shape `J`, so will `F`. -/ noncomputable def preserves_limit_of_Lan_presesrves_limit {C D : Type u} [small_category C] [small_category D] (F : C ⥤ D) (J : Type u) [small_category J] [preserves_limits_of_shape J (Lan F.op : _ ⥤ (Dᵒᵖ ⥤ Type u))] : preserves_limits_of_shape J F := begin apply preserves_limits_of_shape_of_reflects_of_preserves F yoneda, exact preserves_limits_of_shape_of_nat_iso (comp_yoneda_iso_yoneda_comp_Lan F).symm, apply_instance end end category_theory
04972b25704451d74ac4b8594bf2e44a7bd4613f
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/set/basic.lean
173d157289d0c2990174cdb935e4e8ee3a8bb820
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
52,575
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import tactic.finish data.subtype tactic.interactive open function /- set coercion to a type -/ namespace set instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ end set section set_coe universe u variables {α : Type u} theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.property namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[extensionality] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {α : Type u} {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /- mem and set_of -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {α} {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl @[simp] lemma set_of_mem {α} {s : set α} : {a | a ∈ s} = s := rfl /- subset -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {α : Type u} {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alterantive name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a, a ∈ s ∧ a ∉ t := by simp [subset_def, classical.not_forall] /- strict subset -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ s ≠ t instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ s ≠ t) := rfl lemma exists_of_ssubset {α : Type u} {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := classical.by_contradiction $ assume hn, have t ⊆ s, from assume a hat, classical.by_contradiction $ assume has, hn ⟨a, hat, has⟩, h.2 $ subset.antisymm h.1 this lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : ¬ (a ∉ s) ↔ a ∈ s := not_not /- empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] theorem ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := by { intro hs, rw hs at h, apply not_mem_empty _ h } @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem] theorem exists_mem_of_ne_empty {s : set α} : s ≠ ∅ → ∃ x, x ∈ s := ne_empty_iff_exists_mem.1 theorem coe_nonempty_iff_ne_empty {s : set α} : nonempty s ↔ s ≠ ∅ := nonempty_subtype.trans ne_empty_iff_exists_mem.symm -- TODO: remove when simplifier stops rewriting `a ≠ b` to `¬ a = b` theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem subset_ne_empty {s t : set α} (h : t ⊆ s) : t ≠ ∅ → s ≠ ∅ := mt (subset_eq_empty h) theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /- universal set -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : inhabited α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 @[simp] lemma univ_eq_empty_iff {α : Type*} : (univ : set α) = ∅ ↔ ¬ nonempty α := eq_empty_iff_forall_not_mem.trans ⟨λ H ⟨x⟩, H x trivial, λ H x _, H ⟨x⟩⟩ lemma nonempty_iff_univ_ne_empty {α : Type*} : nonempty α ↔ (univ : set α) ≠ ∅ := by classical; exact iff_not_comm.1 univ_eq_empty_iff lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ @[simp] lemma univ_ne_empty {α} [h : nonempty α] : (univ : set α) ≠ ∅ := λ e, univ_eq_empty_iff.1 e h instance univ_decidable : decidable_pred (@set.univ α) := λ x, is_true trivial /- union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /- intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set α} (h : s ∩ t ≠ ∅) : t ≠ ∅ := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set α} (h : s ∩ t ≠ ∅) : s ≠ ∅ := by finish [ext_iff, iff_def] /- distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /- insert -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_def, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] -- TODO(Jeremy): make this automatic theorem insert_ne_empty (a : α) (s : set α) : insert a s ≠ ∅ := by safe [ext_iff, iff_def]; have h' := a_1 a; finish -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /- singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := set.ext $ λ n, (set.mem_singleton_iff).symm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := insert_ne_empty _ _ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := ext $ by simp @[simp] theorem union_singleton : s ∪ {a} = insert a s := by simp [singleton_def] @[simp] theorem singleton_union : {a} ∪ s = insert a s := by rw [union_comm, union_singleton] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ nonempty s := by simp [coe_nonempty_iff_ne_empty] /- separation -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := set.ext $ by simp /- complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h lemma compl_set_of {α} (p : α → Prop) : - {a | p a} = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] lemma compl_empty_iff {s : set α} : -s = ∅ ↔ s = univ := by { split, intro h, rw [←compl_compl s, h, compl_empty], intro h, rw [h, compl_univ] } lemma compl_univ_iff {s : set α} : -s = univ ↔ s = ∅ := by rw [←compl_empty_iff, compl_compl] lemma nonempty_compl {s : set α} : nonempty (-s : set α) ↔ s ≠ univ := by { symmetry, rw [coe_nonempty_iff_ne_empty], apply not_congr, split, intro h, rw [h, compl_univ], intro h, rw [←compl_compl s, h, compl_empty] } theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ -b ∪ c := begin haveI := classical.prop_decidable, split, { intros h x xa, by_cases h' : x ∈ b, simp [h ⟨xa, h'⟩], simp [h'] }, intros h x, rintro ⟨xa, xb⟩, cases h xa, contradiction, assumption end /- set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] @[simp] lemma empty_diff {α : Type*} (s : set α) : (∅ \ s : set α) = ∅ := eq_empty_of_subset_empty $ assume x ⟨hx, _⟩, hx theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma subset_insert_diff (s t : set α) : s ⊆ (s \ t) ∪ t := by rw [union_comm, ←diff_subset_iff] @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := ext $ by simp lemma mem_diff_singleton {s s' : set α} {t : set (set α)} : s ∈ t \ {s'} ↔ (s ∈ t ∧ s ≠ s') := by simp lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} : s ∈ t \ {∅} ↔ (s ∈ t ∧ nonempty s) := by simp [coe_nonempty_iff_ne_empty] /- powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /- inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage_eq {s : set β} {a : α} : (a ∈ f ⁻¹' s) = (f a ∈ s) := rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : α → β) (a : set α) : Prop := ∀ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem mono_image {f : α → β} {s t : set α} (h : s ⊆ t) : f '' s ⊆ f '' t := assume x ⟨y, hy, y_eq⟩, y_eq ▸ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /- A common special case of `image_congr` -/ lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s := image_congr (λx _, h x) theorem image_eq_image_of_eq_on {f₁ f₂ : α → β} {s : set α} (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s := (image_comp g f s).symm theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := ext $ λ x, by simp [image]; rw eq_comm @[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ := by simp only [eq_empty_iff_forall_not_mem]; exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ lemma inter_singleton_ne_empty {α : Type*} {s : set α} {a : α} : s ∩ {a} ≠ ∅ ↔ a ∈ s := by finish [set.inter_singleton_eq_empty] theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set α) : id '' s = s := ext $ by simp /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := image_id s theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) lemma nonempty_image (f : α → β) {s : set α} : nonempty s → nonempty (f '' s) | ⟨⟨x, hx⟩⟩ := ⟨⟨f x, mem_image_of_mem f hx⟩⟩ /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq]) (assume eq, eq ▸ rfl) lemma surjective_preimage {f : β → α} (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma injective_image {f : α → β} (hf : injective f) : injective (('') f) := assume s t, (image_eq_image hf).1 lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) def image_factorization (f : α → β) (s : set α) : s → f '' s := λ p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : α → β} {s : set α} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ λ p, rfl lemma surjective_onto_image {f : α → β} {s : set α} : surjective (image_factorization f s) := λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := ⟨assume ⟨a, ⟨i, eq⟩, h⟩, ⟨i, eq.symm ▸ h⟩, assume ⟨i, h⟩, ⟨f i, mem_range_self _, h⟩⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := ext $ by simp [image, range] theorem image_subset_range {ι : Type*} (f : ι → β) (s : set ι) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {ι : Type*} {f : ι → β} {s : set β} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma nonempty_of_nonempty_range {α : Type*} {β : Type*} {f : α → β} (H : ¬range f = ∅) : nonempty α := begin cases exists_mem_of_ne_empty H with x h, cases mem_range.1 h with y _, exact ⟨y⟩ end @[simp] lemma range_eq_empty {α : Type u} {β : Type v} {f : α → β} : range f = ∅ ↔ ¬ nonempty α := by rw ← set.image_univ; simp [-set.image_univ] theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma range_const_subset {c : β} : range (λx:α, c) ⊆ {c} := range_subset_iff.2 $ λ x, or.inl rfl @[simp] lemma range_const [h : nonempty α] {c : β} : range (λx:α, c) = {c} := begin refine subset.antisymm range_const_subset (λy hy, _), rw set.mem_singleton_iff.1 hy, rcases exists_mem_of_nonempty α with ⟨x, _⟩, exact mem_range_self x end def range_factorization (f : ι → β) : ι → range f := λ i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ι → β} : subtype.val ∘ range_factorization f = f := funext $ λ i, rfl lemma surjective_onto_range : surjective (range_factorization f) := λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x.1) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y theorem pairwise_on.mono {s t : set α} {r} (h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r := λ x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop} (H : ∀ a b, r a b → r' a b) (hp : pairwise_on s r) : pairwise_on s r' := λ x xs y ys h, H _ _ (hp x xs y ys h) end set open set /- image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ @[simp] lemma val_range {p : α → Prop} : set.range (@subtype.val _ p) = {x | p x} := by rw ← set.image_univ; simp [-set.image_univ, val_image] @[simp] lemma range_val (s : set α) : range (subtype.val : s → α) = s := val_range theorem val_image_subset (s : set α) (t : set (subtype s)) : t.image val ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem val_image_univ (s : set α) : @val _ s '' set.univ = s := set.eq_of_subset_of_subset (val_image_subset _ _) (λ x xs, ⟨⟨x, xs⟩, ⟨set.mem_univ _, rfl⟩⟩) theorem image_preimage_val (s t : set α) : (@subtype.val _ s) '' ((@subtype.val _ s) ⁻¹' t) = t ∩ s := begin ext x, simp, split, { rintros ⟨y, ys, yt, yx⟩, rw ←yx, exact ⟨yt, ys⟩ }, rintros ⟨xt, xs⟩, exact ⟨x, xs, xt, rfl⟩ end theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((@subtype.val _ s) ⁻¹' t = (@subtype.val _ s) ⁻¹' u) ↔ (t ∩ s = u ∩ s) := begin rw [←image_preimage_val, ←image_preimage_val], split, { intro h, rw h }, intro h, exact set.injective_image (val_injective) h end lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (subtype.val '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨subtype.val '' s, _, hs⟩, convert image_subset_range _ _, rw [range_val] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨subtype.val ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_val], exact hs₁ end end subtype namespace set section range variable {α : Type*} @[simp] lemma subtype.val_range {p : α → Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype.val_image] @[simp] lemma range_coe_subtype (s : set α): range (coe : s → α) = s := subtype.val_range end range section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma prod_eq (s : set α) (t : set β) : set.prod s t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ @[simp] theorem prod_empty {s : set α} : set.prod s ∅ = (∅ : set (α × β)) := ext $ by simp [set.prod] @[simp] theorem empty_prod {t : set β} : set.prod ∅ t = (∅ : set (α × β)) := ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := ext $ by simp [set.prod] theorem prod_neq_empty_iff {s : set α} {t : set β} : set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := by simp [not_eq_empty_iff_exists] theorem prod_eq_empty_iff {s : set α} {t : set β} : set.prod s t = ∅ ↔ (s = ∅ ∨ t = ∅) := suffices (¬ set.prod s t ≠ ∅) ↔ (¬ s ≠ ∅ ∨ ¬ t ≠ ∅), by simpa only [(≠), classical.not_not], by classical; rw [prod_neq_empty_iff, not_and_distrib] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] end prod section pi variables {α : Type*} {π : α → Type*} def pi (i : set α) (s : Πa, set (π a)) : set (Πa, π a) := { f | ∀a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Πa, set (π a)) : pi ∅ s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : α) (i : set α) (s : Πa, set (π a)) : pi (insert a i) s = ((λf, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : α) (s : Πa, set (π a)) : pi {a} s = ((λf:(Πa, π a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : α → Prop} [h : decidable_pred p] (i : set α) (s t : Πa, set (π a)) : pi i (λa, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | ¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi section inclusion variable {α : Type*} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion {s t : set α} (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self {s : set α} (x : s) : inclusion (set.subset.refl _) x = x := by cases x; refl @[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x := by cases x; refl lemma inclusion_injective {s t : set α} (h : s ⊆ t) : function.injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext.2 ∘ subtype.ext.1 end inclusion end set
38f1f56ebee51ea94d807c113bc044b1f00291f4
618003631150032a5676f229d13a079ac875ff77
/src/topology/dense_embedding.lean
a76820dc1893b2dfd0f90a56b18e57d8bf7edb5f
[ "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
14,559
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.separation /-! # Dense embeddings This file defines three properties of functions: * `dense_range f` means `f` has dense image; * `dense_inducing i` means `i` is also `inducing`; * `dense_embedding e` means `e` is also an `embedding`. The main theorem `continuous_extend` gives a criterion for a function `f : X → Z` to a regular (T₃) space Z to extend along a dense embedding `i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only has to be `dense_inducing` (not necessarily injective). -/ noncomputable theory open set filter open_locale classical topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section dense_range variables [topological_space β] [topological_space γ] (f : α → β) (g : β → γ) /-- `f : α → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := ∀ x, x ∈ closure (range f) variables {f} lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := eq_univ_iff_forall.symm lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := eq_univ_iff_forall.mpr h lemma dense_range.comp (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := begin have : g '' (closure $ range f) ⊆ closure (g '' range f), from image_closure_subset_closure_image cg, have : closure (g '' closure (range f)) ⊆ closure (g '' range f), by simpa [closure_closure] using (closure_mono this), intro c, rw range_comp, apply this, rw [hf.closure_range, image_univ], exact hg c end /-- If `f : α → β` has dense range and `β` contains some element, then `α` must too. -/ def dense_range.inhabited (df : dense_range f) (b : β) : inhabited α := ⟨classical.choice $ by simpa only [univ_inter, range_nonempty_iff_nonempty] using mem_closure_iff.1 (df b) _ is_open_univ trivial⟩ lemma dense_range.nonempty (hf : dense_range f) : nonempty α ↔ nonempty β := ⟨nonempty.map f, λ ⟨b⟩, @nonempty_of_inhabited _ (hf.inhabited b)⟩ lemma dense_range.prod {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (λ p : ι × κ, (f p.1, g p.2)) := have closure (range $ λ p : ι×κ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩ end dense_range /-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α` is the one induced by `i` from the topology on `β`. -/ structure dense_inducing [topological_space α] [topological_space β] (i : α → β) extends inducing i : Prop := (dense : dense_range i) namespace dense_inducing variables [topological_space α] [topological_space β] variables {i : α → β} (di : dense_inducing i) lemma nhds_eq_comap (di : dense_inducing i) : ∀ a : α, 𝓝 a = comap i (𝓝 $ i a) := di.to_inducing.nhds_eq_comap protected lemma continuous (di : dense_inducing i) : continuous i := di.to_inducing.continuous lemma closure_range : closure (range i) = univ := di.dense.closure_range lemma self_sub_closure_image_preimage_of_open {s : set β} (di : dense_inducing i) : is_open s → s ⊆ closure (i '' (i ⁻¹' s)) := begin intros s_op b b_in_s, rw [image_preimage_eq_inter_range, mem_closure_iff], intros U U_op b_in, rw ←inter_assoc, exact (dense_iff_inter_open.1 di.closure_range) _ (is_open_inter U_op s_op) ⟨b, b_in, b_in_s⟩ end lemma closure_image_nhds_of_nhds {s : set α} {a : α} (di : dense_inducing i) : s ∈ 𝓝 a → closure (i '' s) ∈ 𝓝 (i a) := begin rw [di.nhds_eq_comap a, mem_comap_sets], intro h, rcases h with ⟨t, t_nhd, sub⟩, rw mem_nhds_sets_iff at t_nhd, rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩, have := calc i ⁻¹' U ⊆ i⁻¹' t : preimage_mono U_sub ... ⊆ s : sub, have := calc U ⊆ closure (i '' (i ⁻¹' U)) : self_sub_closure_image_preimage_of_open di U_op ... ⊆ closure (i '' s) : closure_mono (image_subset i this), have U_nhd : U ∈ 𝓝 (i a) := mem_nhds_sets U_op e_a_in_U, exact (𝓝 (i a)).sets_of_superset U_nhd this end /-- The product of two dense inducings is a dense inducing -/ protected lemma prod [topological_space γ] [topological_space δ] {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) : dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced, dense := de₁.dense.prod de₂.dense } variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- γ -f→ α g↓ ↓e δ -h→ β -/ lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i) (H : tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) := begin have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le, replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1, rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1, have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H, rw ← di.nhds_eq_comap at lim2, exact le_trans lim1 lim2, end protected lemma nhds_inf_ne_bot (di : dense_inducing i) {b : β} : 𝓝 b ⊓ principal (range i) ≠ ⊥ := begin convert di.dense b, simp [closure_eq_nhds] end lemma comap_nhds_ne_bot (di : dense_inducing i) {b : β} : comap i (𝓝 b) ≠ ⊥ := comap_ne_bot $ λ s hs, let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩ variables [topological_space γ] /-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends" to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a continuous extension, then `g` is the unique such extension. In general, `g` might not be continuous or even extend `f`. -/ def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ := @lim _ _ ⟨f (dense_range.inhabited di.dense b).default⟩ (map f (comap i (𝓝 b))) lemma extend_eq [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : map f (comap i (𝓝 b)) ≤ 𝓝 c) : di.extend f b = c := @lim_eq _ _ (id _) _ _ _ (by simp; exact comap_nhds_ne_bot di) hf lemma extend_e_eq [t2_space γ] {f : α → γ} (a : α) (hf : continuous_at f a) : di.extend f (i a) = f a := extend_eq _ $ di.nhds_eq_comap a ▸ hf lemma extend_eq_of_cont [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) : di.extend f (i a) = f a := di.extend_e_eq a (continuous_iff_continuous_at.1 hf a) lemma tendsto_extend [regular_space γ] {b : β} {f : α → γ} (di : dense_inducing i) (hf : {b | ∃c, tendsto f (comap i $ 𝓝 b) (𝓝 c)} ∈ 𝓝 b) : tendsto (di.extend f) (𝓝 b) (𝓝 (di.extend f b)) := let φ := {b | tendsto f (comap i $ 𝓝 b) (𝓝 $ di.extend f b)} in have hφ : φ ∈ 𝓝 b, from (𝓝 b).sets_of_superset hf $ assume b ⟨c, hc⟩, show tendsto f (comap i (𝓝 b)) (𝓝 (di.extend f b)), from (di.extend_eq hc).symm ▸ hc, assume s hs, let ⟨s'', hs''₁, hs''₂, hs''₃⟩ := nhds_is_closed hs in let ⟨s', hs'₁, (hs'₂ : i ⁻¹' s' ⊆ f ⁻¹' s'')⟩ := mem_of_nhds hφ hs''₁ in let ⟨t, (ht₁ : t ⊆ φ ∩ s'), ht₂, ht₃⟩ := mem_nhds_sets_iff.mp $ inter_mem_sets hφ hs'₁ in have h₁ : closure (f '' (i ⁻¹' s')) ⊆ s'', by rw [closure_subset_iff_subset_of_is_closed hs''₃, image_subset_iff]; exact hs'₂, have h₂ : t ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' t)), from assume b' hb', have 𝓝 b' ≤ principal t, by simp; exact mem_nhds_sets ht₂ hb', have map f (comap i (𝓝 b')) ≤ 𝓝 (di.extend f b') ⊓ principal (f '' (i ⁻¹' t)), from calc _ ≤ map f (comap i (𝓝 b' ⊓ principal t)) : map_mono $ comap_mono $ le_inf (le_refl _) this ... ≤ map f (comap i (𝓝 b')) ⊓ map f (comap i (principal t)) : le_inf (map_mono $ comap_mono $ inf_le_left) (map_mono $ comap_mono $ inf_le_right) ... ≤ map f (comap i (𝓝 b')) ⊓ principal (f '' (i ⁻¹' t)) : by simp [le_refl] ... ≤ _ : inf_le_inf_right _ (ht₁ hb').left, show di.extend f b' ∈ closure (f '' (i ⁻¹' t)), begin rw [closure_eq_nhds], apply ne_bot_of_le_ne_bot _ this, simp, exact di.comap_nhds_ne_bot end, (𝓝 b).sets_of_superset (show t ∈ 𝓝 b, from mem_nhds_sets ht₂ ht₃) (calc t ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' t)) : h₂ ... ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' s')) : preimage_mono $ closure_mono $ image_subset f $ preimage_mono $ subset.trans ht₁ $ inter_subset_right _ _ ... ⊆ di.extend f ⁻¹' s'' : preimage_mono h₁ ... ⊆ di.extend f ⁻¹' s : preimage_mono hs''₂) lemma continuous_extend [regular_space γ] {f : α → γ} (di : dense_inducing i) (hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) := continuous_iff_continuous_at.mpr $ assume b, di.tendsto_extend $ univ_mem_sets' hf lemma mk' (i : α → β) (c : continuous i) (dense : ∀x, x ∈ closure (range i)) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) : dense_inducing i := { induced := (induced_iff_nhds_eq i).2 $ λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [le_def] using H a), dense := dense } end dense_inducing /-- A dense embedding is an embedding with dense image. -/ structure dense_embedding [topological_space α] [topological_space β] (e : α → β) extends dense_inducing e : Prop := (inj : function.injective e) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := { inj := inj, ..dense_inducing.mk' e c dense H} namespace dense_embedding variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] variables {e : α → β} (de : dense_embedding e) lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma to_embedding : embedding e := { induced := de.induced, inj := de.inj } /-- The product of two dense embeddings is a dense embedding -/ protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, ..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing } /-- The dense embedding of a subtype inside its closure. -/ def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩ protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) := { dense_embedding . dense := assume ⟨x, hx⟩, closure_subtype.mpr $ have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl, begin rw ← image_univ, simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ], rw [this, image_comp, subtype.val_image], simp, assumption end, inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h, induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap_comp, (∘)]) } end dense_embedding lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop} (he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.closure_range.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : closure_eq_of_is_closed hp, assume b, this trivial lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod he) hp $ λ _, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod $ he.prod he) hp $ λ _, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ @[elab_as_eliminator] lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop} (b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ := is_closed_property he hp ih b₀ @[elab_as_eliminator] lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) (b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _ @[elab_as_eliminator] lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) (b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _ section variables [topological_space β] [topological_space γ] [t2_space γ] variables {f : α → β} /-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/ lemma dense_range.equalizer (hfd : dense_range f) {g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) : g = h := funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H end
5b11911767697772ae3cbf07943095031bfc94f9
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/hott/algebra/groupoid.hlean
591c9b7b411406eaa0e948c1ed97e99e68bf5fd1
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,054
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.groupoid Author: Jakob von Raumer Ported from Coq HoTT -/ import .precategory.iso .group open eq is_trunc iso category path_algebra nat unit namespace category structure groupoid [class] (ob : Type) extends parent : precategory ob := (all_iso : Π ⦃a b : ob⦄ (f : hom a b), @is_iso ob parent a b f) abbreviation all_iso := @groupoid.all_iso attribute groupoid.all_iso [instance] [priority 100000] definition groupoid.mk' [reducible] (ob : Type) (C : precategory ob) (H : Π (a b : ob) (f : a ⟶ b), is_iso f) : groupoid ob := precategory.rec_on C groupoid.mk H definition groupoid_of_1_type.{l} (A : Type.{l}) [H : is_trunc 1 A] : groupoid.{l l} A := groupoid.mk (λ (a b : A), a = b) (λ (a b : A), have ish : is_hset (a = b), from is_trunc_eq nat.zero a b, ish) (λ (a b c : A) (p : b = c) (q : a = b), q ⬝ p) (λ (a : A), refl a) (λ (a b c d : A) (p : c = d) (q : b = c) (r : a = b), con.assoc r q p) (λ (a b : A) (p : a = b), con_idp p) (λ (a b : A) (p : a = b), idp_con p) (λ (a b : A) (p : a = b), @is_iso.mk A _ a b p p⁻¹ !con.right_inv !con.left_inv) -- A groupoid with a contractible carrier is a group definition group_of_is_contr_groupoid {ob : Type} [H : is_contr ob] [G : groupoid ob] : group (hom (center ob) (center ob)) := begin fapply group.mk, intros (f, g), apply (comp f g), apply homH, intros (f, g, h), apply (assoc f g h)⁻¹, apply (ID (center ob)), intro f, apply id_left, intro f, apply id_right, intro f, exact (iso.inverse f), intro f, exact (iso.left_inverse f), end definition group_of_groupoid_unit [G : groupoid unit] : group (hom ⋆ ⋆) := begin fapply group.mk, intros (f, g), apply (comp f g), apply homH, intros (f, g, h), apply (assoc f g h)⁻¹, apply (ID ⋆), intro f, apply id_left, intro f, apply id_right, intro f, exact (iso.inverse f), intro f, exact (iso.left_inverse f), end -- Conversely we can turn each group into a groupoid on the unit type definition groupoid_of_group.{l} (A : Type.{l}) [G : group A] : groupoid.{l l} unit := begin fapply groupoid.mk, intros, exact A, intros, apply (@group.carrier_hset A G), intros (a, b, c, g, h), exact (@group.mul A G g h), intro a, exact (@group.one A G), intros, exact (@group.mul_assoc A G h g f)⁻¹, intros, exact (@group.one_mul A G f), intros, exact (@group.mul_one A G f), intros, apply is_iso.mk, apply mul_left_inv, apply mul_right_inv, end protected definition hom_group {A : Type} [G : groupoid A] (a : A) : group (hom a a) := begin fapply group.mk, intros (f, g), apply (comp f g), apply homH, intros (f, g, h), apply (assoc f g h)⁻¹, apply (ID a), intro f, apply id_left, intro f, apply id_right, intro f, exact (iso.inverse f), intro f, exact (iso.left_inverse f), end -- Bundled version of categories -- we don't use Groupoid.carrier explicitly, but rather use Groupoid.carrier (to_Precategory C) structure Groupoid : Type := (carrier : Type) (struct : groupoid carrier) attribute Groupoid.struct [instance] [coercion] -- definition objects [reducible] := Category.objects -- definition category_instance [instance] [coercion] [reducible] := Category.category_instance definition Groupoid.to_Precategory [coercion] [reducible] (C : Groupoid) : Precategory := Precategory.mk (Groupoid.carrier C) C definition groupoid.Mk [reducible] := Groupoid.mk definition groupoid.MK [reducible] (C : Precategory) (H : Π (a b : C) (f : a ⟶ b), is_iso f) : Groupoid := Groupoid.mk C (groupoid.mk' C C H) definition Groupoid.eta (C : Groupoid) : Groupoid.mk C C = C := Groupoid.rec (λob c, idp) C end category
a4c9e4e072e378a24e9501120525f40b441a9ec1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/goalIssue.lean
76554d1ad133332a31e6ba505a56b444117e31b1
[ "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
261
lean
theorem foo1 (x : Nat) : 0 + x = x := by first | skip; have : x + x = x + x := rfl; done --^ $/lean/plainGoal | simp theorem foo2 (x : Nat) : 0 + x = x := by induction x with | zero => done --^ $/lean/plainGoal | succ => done
67f04fae7e2a1a66d7edb5ff89ab4f8b2008f75d
80b18137872dad7c3df334b9069d70935b4224f3
/src/analysis/calculus/fderiv.lean
5ddc72d845f5490c673fe5b99d37ba90f14cafa0
[ "Apache-2.0" ]
permissive
Jack-Pumpkinhead/mathlib
1bcf5692d355dc397847791c137158f01b407535
da8b23f907f750528539bffa604875b98717fb93
refs/heads/master
1,621,299,949,262
1,585,480,767,000
1,585,480,767,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
84,309
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.asymptotics analysis.calculus.tangent_cone /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set open_locale topological_space classical noncomputable theory set_option class.instance_max_depth 90 section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = nhds_within x s` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (nhds_within x s) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (nhds_within x s), { conv in (nhds_within x s) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (nhds_within x s) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := begin have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y, { rintros y ⟨c, d, dtop, clim, cdlim⟩, exact tendsto_nhds_unique (by simp) (h.lim at_top dtop clim cdlim) (h₁.lim at_top dtop clim cdlim) }, have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y, { assume y hy, apply submodule.span_induction hy, { exact λy hy, A y hy }, { simp only [continuous_linear_map.map_zero] }, { simp {contextual := tt} }, { simp {contextual := tt} } }, have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B, have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K := closure_mono this, have : y ∈ closure K := this hy, rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this }, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := unique_diff_within_at.eq (H x hx) h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin split, { assume H, have : tendsto (λ (z : E), z + x) (𝓝 0) (𝓝 (0 + x)), from tendsto_id.add tendsto_const_nhds, rw [zero_add] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel', add_comm z] }, { assume H, have : tendsto (λ (z : E), z - x) (𝓝 x) (𝓝 (x - x)), from tendsto_id.sub tendsto_const_nhds, rw [sub_self] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel'_right] } end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (hf hc) lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only [], rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ nhds_within x s) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp [mem_closure_iff_nhds_within_ne_bot] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ nhds_within x s) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at end continuous section congr /-! ### congr properties of the derivative -/ theorem has_strict_fderiv_at_congr_of_mem_sets (h : ∀ᶠ y in 𝓝 x, f₀ y = f₁ y) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall _ $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_fderiv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall _ $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_mem_sets (h : has_fderiv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (has_fderiv_at_filter_congr_of_mem_sets hx hL $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_mem_sets (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_mem_nhds_within (h : has_fderiv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_mem_sets h h₁ hx lemma has_fderiv_at.congr_of_mem_nhds (h : has_fderiv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_mem_nhds_within (h : differentiable_within_at 𝕜 f s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_mem_nhds_within h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_mem_nhds (h : differentiable_at 𝕜 f x) (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma fderiv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_mem_sets hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_mem_nhds_within (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply fderiv_within_congr_of_mem_nhds_within hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma fderiv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := (mem_of_nhds hL : _), rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact fderiv_within_congr_of_mem_nhds_within unique_diff_within_at_univ hL A end end congr section id /-! ### Derivative of the identity -/ theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id : E →L[𝕜] E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id : E →L[𝕜] E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id : E →L[𝕜] E) x := has_fderiv_at_filter_id _ _ lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {f₂ : E → G} {f₂' : E →L[𝕜] G} lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 f₂ x) := has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at) lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end cartesian_product section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (nhds_within x s) ≤ nhds_within (f x) (f '' s) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (f x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf end composition section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.add_const c).fderiv_within hxs lemma fderiv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.add_const c).fderiv theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_add c).fderiv_within hxs lemma fderiv_const_add (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := (hf.has_fderiv_at.const_add c).fderiv end add section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at 𝕜 f x) : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := h.has_fderiv_at.neg.fderiv end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.sub_const c).fderiv_within hxs lemma fderiv_sub_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.sub_const c).fderiv theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_sub c).fderiv_within hxs lemma fderiv_const_sub (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := (hf.has_fderiv_at.const_sub c).fderiv end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext q, rcases q with ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ set_option class.instance_max_depth 120 variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : closure (range f') = univ) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E), f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F), { assume v hv, apply submodule.span_induction hv, { exact λ w hw, submodule.subset_span (h.maps_to_tangent_cone hw) }, { simp }, { assume w₁ w₂ hw₁ hw₂, rw continuous_linear_map.map_add, exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ }, { assume a w hw, rw continuous_linear_map.map_smul, exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } }, rw [unique_diff_within_at, ← univ_subset_iff], split, show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2, show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc univ ⊆ closure (range f') : univ_subset_iff.2 h' ... = closure (f' '' univ) : by rw image_univ ... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1 ... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : closure_mono (image_closure_subset_closure_image f'.cont) ... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure ... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) : closure_mono (image_subset_iff.mpr B) end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin apply h.unique_diff_within_at hs, have : range (e' : E →L[𝕜] F) = univ := e'.to_linear_equiv.to_equiv.range_eq_univ, rw [this, closure_univ] end lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} local attribute [instance] normed_space.restrict_scalars lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
780addb28257f0586df10d690ced801225b430ba
626e312b5c1cb2d88fca108f5933076012633192
/src/analysis/convex/specific_functions.lean
27d5e4f76cfc70b42746bdbfd5de4871086d03fb
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,261
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel -/ import analysis.calculus.mean_value import analysis.special_functions.pow /-! # Collection of convex functions In this file we prove that the following functions are convex: * `convex_on_exp` : the exponential function is convex on $(-∞, +∞)$; * `convex_on_pow_of_even` : given an even natural number $n$, the function $f(x)=x^n$ is convex on $(-∞, +∞)$; * `convex_on_pow` : for a natural $n$, the function $f(x)=x^n$ is convex on $[0, +∞)$; * `convex_on_fpow` : for an integer $m$, the function $f(x)=x^m$ is convex on $(0, +∞)$. * `convex_on_rpow : ∀ p : ℝ, 1 ≤ p → convex_on (Ici 0) (λ x, x ^ p)` * `concave_on_log_Ioi` and `concave_on_log_Iio`: log is concave on `Ioi 0` and `Iio 0` respectively. -/ open real set open_locale big_operators /-- `exp` is convex on the whole real line -/ lemma convex_on_exp : convex_on univ exp := convex_on_univ_of_deriv2_nonneg differentiable_exp (by simp) (assume x, (iter_deriv_exp 2).symm ▸ le_of_lt (exp_pos x)) /-- `x^n`, `n : ℕ` is convex on the whole real line whenever `n` is even -/ lemma convex_on_pow_of_even {n : ℕ} (hn : even n) : convex_on set.univ (λ x : ℝ, x^n) := begin apply convex_on_univ_of_deriv2_nonneg differentiable_pow, { simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] }, { intro x, rcases nat.even.sub_even hn (nat.even_bit0 1) with ⟨k, hk⟩, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub, hk, pow_mul'], exact mul_nonneg (nat.cast_nonneg _) (pow_two_nonneg _) } end /-- `x^n`, `n : ℕ` is convex on `[0, +∞)` for all `n` -/ lemma convex_on_pow (n : ℕ) : convex_on (Ici 0) (λ x : ℝ, x^n) := begin apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on differentiable_on_pow, { simp only [deriv_pow'], exact differentiable_on_pow.const_mul _ }, { intros x hx, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub], exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (interior_subset hx) _) } end lemma finset.prod_nonneg_of_card_nonpos_even {α β : Type*} [linear_ordered_comm_ring β] {f : α → β} [decidable_pred (λ x, f x ≤ 0)] {s : finset α} (h0 : even (s.filter (λ x, f x ≤ 0)).card) : 0 ≤ ∏ x in s, f x := calc 0 ≤ (∏ x in s, ((if f x ≤ 0 then (-1:β) else 1) * f x)) : finset.prod_nonneg (λ x _, by { split_ifs with hx hx, by simp [hx], simp at hx ⊢, exact le_of_lt hx }) ... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one, mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul] lemma int_prod_range_nonneg (m : ℤ) (n : ℕ) (hn : even n) : 0 ≤ ∏ k in finset.range n, (m - k) := begin rcases hn with ⟨n, rfl⟩, induction n with n ihn, { simp }, rw [nat.succ_eq_add_one, mul_add, mul_one, bit0, ← add_assoc, finset.prod_range_succ, finset.prod_range_succ, mul_assoc], refine mul_nonneg ihn _, generalize : (1 + 1) * n = k, cases le_or_lt m k with hmk hmk, { have : m ≤ k + 1, from hmk.trans (lt_add_one ↑k).le, exact mul_nonneg_of_nonpos_of_nonpos (sub_nonpos.2 hmk) (sub_nonpos.2 this) }, { exact mul_nonneg (sub_nonneg.2 hmk.le) (sub_nonneg.2 hmk) } end /-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` -/ lemma convex_on_fpow (m : ℤ) : convex_on (Ioi 0) (λ x : ℝ, x^m) := begin have : ∀ n : ℤ, differentiable_on ℝ (λ x, x ^ n) (Ioi (0 : ℝ)), from λ n, differentiable_on_fpow _ _ (or.inl $ lt_irrefl _), apply convex_on_of_deriv2_nonneg (convex_Ioi 0); try { simp only [interior_Ioi, deriv_fpow'] }, { exact (this _).continuous_on }, { exact this _ }, { exact (this _).const_mul _ }, { intros x hx, simp only [iter_deriv_fpow, ← int.cast_coe_nat, ← int.cast_sub, ← int.cast_prod], refine mul_nonneg (int.cast_nonneg.2 _) (fpow_nonneg (le_of_lt hx) _), exact int_prod_range_nonneg _ _ (nat.even_bit0 1) } end lemma convex_on_rpow {p : ℝ} (hp : 1 ≤ p) : convex_on (Ici 0) (λ x : ℝ, x^p) := begin have A : deriv (λ (x : ℝ), x ^ p) = λ x, p * x^(p-1), by { ext x, simp [hp] }, apply convex_on_of_deriv2_nonneg (convex_Ici 0), { exact continuous_on_id.rpow_const (λ x _, or.inr (zero_le_one.trans hp)) }, { exact (differentiable_rpow_const hp).differentiable_on }, { rw A, assume x hx, replace hx : x ≠ 0, by { simp at hx, exact ne_of_gt hx }, simp [differentiable_at.differentiable_within_at, hx] }, { assume x hx, replace hx : 0 < x, by simpa using hx, suffices : 0 ≤ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], apply mul_nonneg (le_trans zero_le_one hp), exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg (le_of_lt hx) _) } end lemma concave_on_log_Ioi : concave_on (Ioi 0) log := begin have h₁ : Ioi 0 ⊆ ({0} : set ℝ)ᶜ, { intros x hx hx', rw [mem_singleton_iff] at hx', rw [hx'] at hx, exact lt_irrefl 0 hx }, refine concave_on_open_of_deriv2_nonpos (convex_Ioi 0) is_open_Ioi _ _ _, { exact differentiable_on_log.mono h₁ }, { refine ((times_cont_diff_on_log.deriv_of_open _ le_top).differentiable_on le_top).mono h₁, exact is_open_compl_singleton }, { intros x hx, rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x ≤ 0, rw [deriv_log', deriv_inv], exact neg_nonpos.mpr (inv_nonneg.mpr (sq_nonneg x)) } end lemma concave_on_log_Iio : concave_on (Iio 0) log := begin have h₁ : Iio 0 ⊆ ({0} : set ℝ)ᶜ, { intros x hx hx', rw [mem_singleton_iff] at hx', rw [hx'] at hx, exact lt_irrefl 0 hx }, refine concave_on_open_of_deriv2_nonpos (convex_Iio 0) is_open_Iio _ _ _, { exact differentiable_on_log.mono h₁ }, { refine ((times_cont_diff_on_log.deriv_of_open _ le_top).differentiable_on le_top).mono h₁, exact is_open_compl_singleton }, { intros x hx, rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x ≤ 0, rw [deriv_log', deriv_inv], exact neg_nonpos.mpr (inv_nonneg.mpr (sq_nonneg x)) } end
9db26c4c0c0a46d063e1c204503c72d80f053db6
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/meta/format.lean
d45ecaf2042ea0343ab33d67954764b08a81364a
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,570
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.options universes u v inductive format.color | red | green | orange | blue | pink | cyan | grey meta constant format : Type meta constant format.line : format meta constant format.space : format meta constant format.nil : format meta constant format.compose : format → format → format meta constant format.nest : nat → format → format meta constant format.highlight : format → color → format meta constant format.group : format → format meta constant format.of_string : string → format meta constant format.of_nat : nat → format meta constant format.flatten : format → format meta constant format.to_string : format → options → string meta constant format.of_options : options → format meta constant format.is_nil : format → bool meta constant trace_fmt {α : Type u} : format → (unit → α) → α meta instance : inhabited format := ⟨format.space⟩ meta instance : has_append format := ⟨format.compose⟩ meta instance : has_to_string format := ⟨λ f, format.to_string f options.mk⟩ meta class has_to_format (α : Type u) := (to_format : α → format) meta instance : has_to_format format := ⟨id⟩ meta def to_fmt {α : Type u} [has_to_format α] : α → format := has_to_format.to_format meta instance nat_to_format : has_coe nat format := ⟨format.of_nat⟩ meta instance string_to_format : has_coe string format := ⟨format.of_string⟩ open format list meta def format.indent (f : format) (n : nat) : format := nest n (line ++ f) meta def format.when {α : Type u} [has_to_format α] : bool → α → format | tt a := to_fmt a | ff a := nil meta def format.join (xs : list format) : format := foldl compose (of_string "") xs meta instance : has_to_format options := ⟨λ o, format.of_options o⟩ meta instance : has_to_format bool := ⟨λ b, if b then of_string "tt" else of_string "ff"⟩ meta instance {p : Prop} : has_to_format (decidable p) := ⟨λ b : decidable p, @ite p b _ (of_string "tt") (of_string "ff")⟩ meta instance : has_to_format string := ⟨λ s, format.of_string s⟩ meta instance : has_to_format nat := ⟨λ n, format.of_nat n⟩ meta instance : has_to_format char := ⟨λ c : char, format.of_string [c]⟩ meta def list.to_format {α : Type u} [has_to_format α] : list α → format | [] := to_fmt "[]" | xs := to_fmt "[" ++ group (nest 1 $ format.join $ list.intersperse ("," ++ line) $ xs^.for to_fmt) ++ to_fmt "]" meta instance {α : Type u} [has_to_format α] : has_to_format (list α) := ⟨list.to_format⟩ attribute [instance] string.has_to_format meta instance : has_to_format name := ⟨λ n, to_fmt (to_string n)⟩ meta instance : has_to_format unit := ⟨λ u, to_fmt "()"⟩ meta instance {α : Type u} [has_to_format α] : has_to_format (option α) := ⟨λ o, option.cases_on o (to_fmt "none") (λ a, to_fmt "(some " ++ nest 6 (to_fmt a) ++ to_fmt ")")⟩ meta instance sum_has_to_format {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (sum α β) := ⟨λ s, sum.cases_on s (λ a, to_fmt "(inl " ++ nest 5 (to_fmt a) ++ to_fmt ")") (λ b, to_fmt "(inr " ++ nest 5 (to_fmt b) ++ to_fmt ")")⟩ open prod meta instance {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (prod α β) := ⟨λ p, group (nest 1 (to_fmt "(" ++ to_fmt p.1 ++ to_fmt "," ++ line ++ to_fmt p.2 ++ to_fmt ")"))⟩ open sigma meta instance {α : Type u} {β : α → Type v} [has_to_format α] [s : ∀ x, has_to_format (β x)] : has_to_format (sigma β) := ⟨λ p, group (nest 1 (to_fmt "⟨" ++ to_fmt p.1 ++ to_fmt "," ++ line ++ to_fmt p.2 ++ to_fmt "⟩"))⟩ open subtype meta instance {α : Type u} {p : α → Prop} [has_to_format α] : has_to_format (subtype p) := ⟨λ s, to_fmt (elt_of s)⟩ meta def format.bracket : string → string → format → format | o c f := to_fmt o ++ nest (utf8_length o) f ++ to_fmt c meta def format.paren (f : format) : format := format.bracket "(" ")" f meta def format.cbrace (f : format) : format := format.bracket "{" "}" f meta def format.sbracket (f : format) : format := format.bracket "[" "]" f meta def format.dcbrace (f : format) : format := to_fmt "⦃" ++ nest 1 f ++ to_fmt "⦄"
c0cb0b7e447caf6fbf59406d186978e1b06d30b5
bb31430994044506fa42fd667e2d556327e18dfe
/src/field_theory/fixed.lean
f8192a036843837c9c31ac053475f02dd4715bb4
[ "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
14,408
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.group_ring_action.invariant import algebra.polynomial.group_ring_action import field_theory.normal import field_theory.separable import field_theory.tower /-! # Fixed field under a group action. This is the basis of the Fundamental Theorem of Galois Theory. Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`. This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F` then `finrank (fixed_points G F) F = fintype.card G`. ## Main Definitions - `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where `G` is a group that acts on `F`. -/ noncomputable theory open_locale classical big_operators open mul_action finset finite_dimensional universes u v w variables {M : Type u} [monoid M] variables (G : Type u) [group G] variables (F : Type v) [field F] [mul_semiring_action M F] [mul_semiring_action G F] (m : M) /-- The subfield of F fixed by the field endomorphism `m`. -/ def fixed_by.subfield : subfield F := { carrier := fixed_by M F m, zero_mem' := smul_zero m, add_mem' := λ x y hx hy, (smul_add m x y).trans $ congr_arg2 _ hx hy, neg_mem' := λ x hx, (smul_neg m x).trans $ congr_arg _ hx, one_mem' := smul_one m, mul_mem' := λ x y hx hy, (smul_mul' m x y).trans $ congr_arg2 _ hx hy, inv_mem' := λ x hx, (smul_inv'' m x).trans $ congr_arg _ hx } section invariant_subfields variables (M) {F} /-- A typeclass for subrings invariant under a `mul_semiring_action`. -/ class is_invariant_subfield (S : subfield F) : Prop := (smul_mem : ∀ (m : M) {x : F}, x ∈ S → m • x ∈ S) variable (S : subfield F) instance is_invariant_subfield.to_mul_semiring_action [is_invariant_subfield M S] : mul_semiring_action M S := { smul := λ m x, ⟨m • x, is_invariant_subfield.smul_mem m x.2⟩, one_smul := λ s, subtype.eq $ one_smul M s, mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s, smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂, smul_zero := λ m, subtype.eq $ smul_zero m, smul_one := λ m, subtype.eq $ smul_one m, smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ } instance [is_invariant_subfield M S] : is_invariant_subring M (S.to_subring) := { smul_mem := is_invariant_subfield.smul_mem } end invariant_subfields namespace fixed_points variable (M) -- we use `subfield.copy` so that the underlying set is `fixed_points M F` /-- The subfield of fixed points by a monoid action. -/ def subfield : subfield F := subfield.copy (⨅ (m : M), fixed_by.subfield F m) (fixed_points M F) (by { ext z, simp [fixed_points, fixed_by.subfield, infi, subfield.mem_Inf] }) instance : is_invariant_subfield M (fixed_points.subfield M F) := { smul_mem := λ g x hx g', by rw [hx, hx] } instance : smul_comm_class M (fixed_points.subfield M F) F := { smul_comm := λ m f f', show m • (↑f * f') = f * (m • f'), by rw [smul_mul', f.prop m] } instance smul_comm_class' : smul_comm_class (fixed_points.subfield M F) M F := smul_comm_class.symm _ _ _ @[simp] theorem smul (m : M) (x : fixed_points.subfield M F) : m • x = x := subtype.eq $ x.2 m -- Why is this so slow? @[simp] theorem smul_polynomial (m : M) (p : polynomial (fixed_points.subfield M F)) : m • p = p := polynomial.induction_on p (λ x, by rw [polynomial.smul_C, smul]) (λ p q ihp ihq, by rw [smul_add, ihp, ihq]) (λ n x ih, by rw [smul_mul', polynomial.smul_C, smul, smul_pow', polynomial.smul_X]) instance : algebra (fixed_points.subfield M F) F := by apply_instance theorem coe_algebra_map : algebra_map (fixed_points.subfield M F) F = subfield.subtype (fixed_points.subfield M F) := rfl lemma linear_independent_smul_of_linear_independent {s : finset F} : linear_independent (fixed_points.subfield G F) (λ i : (s : set F), (i : F)) → linear_independent F (λ i : (s : set F), mul_action.to_fun G F i) := begin haveI : is_empty ((∅ : finset F) : set F) := ⟨subtype.prop⟩, refine finset.induction_on s (λ _, linear_independent_empty_type) (λ a s has ih hs, _), rw coe_insert at hs ⊢, rw linear_independent_insert (mt mem_coe.1 has) at hs, rw linear_independent_insert' (mt mem_coe.1 has), refine ⟨ih hs.1, λ ha, _⟩, rw finsupp.mem_span_image_iff_total at ha, rcases ha with ⟨l, hl, hla⟩, rw [finsupp.total_apply_of_mem_supported F hl] at hla, suffices : ∀ i ∈ s, l i ∈ fixed_points.subfield G F, { replace hla := (sum_apply _ _ (λ i, l i • to_fun G F i)).symm.trans (congr_fun hla 1), simp_rw [pi.smul_apply, to_fun_apply, one_smul] at hla, refine hs.2 (hla ▸ submodule.sum_mem _ (λ c hcs, _)), change (⟨l c, this c hcs⟩ : fixed_points.subfield G F) • c ∈ _, exact submodule.smul_mem _ _ (submodule.subset_span $ mem_coe.2 hcs) }, intros i his g, refine eq_of_sub_eq_zero (linear_independent_iff'.1 (ih hs.1) s.attach (λ i, g • l i - l i) _ ⟨i, his⟩ (mem_attach _ _) : _), refine (@sum_attach _ _ s _ (λ i, (g • l i - l i) • mul_action.to_fun G F i)).trans _, ext g', dsimp only, conv_lhs { rw sum_apply, congr, skip, funext, rw [pi.smul_apply, sub_smul, smul_eq_mul] }, rw [sum_sub_distrib, pi.zero_apply, sub_eq_zero], conv_lhs { congr, skip, funext, rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x] }, show ∑ x in s, g • (λ y, l y • mul_action.to_fun G F y) x (g⁻¹ * g') = ∑ x in s, (λ y, l y • mul_action.to_fun G F y) x g', rw [← smul_sum, ← sum_apply _ _ (λ y, l y • to_fun G F y), ← sum_apply _ _ (λ y, l y • to_fun G F y)], dsimp only, rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left] end section fintype variables [fintype G] (x : F) /-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/ def minpoly : polynomial (fixed_points.subfield G F) := (prod_X_sub_smul G F x).to_subring (fixed_points.subfield G F).to_subring $ λ c hc g, let ⟨n, hc0, hn⟩ := polynomial.mem_frange_iff.1 hc in hn.symm ▸ prod_X_sub_smul.coeff G F x g n namespace minpoly theorem monic : (minpoly G F x).monic := by { simp only [minpoly, polynomial.monic_to_subring], exact prod_X_sub_smul.monic G F x } theorem eval₂ : polynomial.eval₂ (subring.subtype $ (fixed_points.subfield G F).to_subring) x (minpoly G F x) = 0 := begin rw [← prod_X_sub_smul.eval G F x, polynomial.eval₂_eq_eval_map], simp only [minpoly, polynomial.map_to_subring], end theorem eval₂' : polynomial.eval₂ (subfield.subtype $ (fixed_points.subfield G F)) x (minpoly G F x) = 0 := eval₂ G F x theorem ne_one : minpoly G F x ≠ (1 : polynomial (fixed_points.subfield G F)) := λ H, have _ := eval₂ G F x, (one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this theorem of_eval₂ (f : polynomial (fixed_points.subfield G F)) (hf : polynomial.eval₂ (subfield.subtype $ fixed_points.subfield G F) x f = 0) : minpoly G F x ∣ f := begin erw [← polynomial.map_dvd_map' (subfield.subtype $ fixed_points.subfield G F), minpoly, polynomial.map_to_subring _ (subfield G F).to_subring, prod_X_sub_smul], refine fintype.prod_dvd_of_coprime (polynomial.pairwise_coprime_X_sub_C $ mul_action.injective_of_quotient_stabilizer G x) (λ y, quotient_group.induction_on y $ λ g, _), rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk, polynomial.eval_smul', ← subfield.to_subring.subtype_eq_subtype, ← is_invariant_subring.coe_subtype_hom' G (fixed_points.subfield G F).to_subring, ← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul, smul_polynomial, mul_semiring_action_hom.coe_polynomial, is_invariant_subring.coe_subtype_hom', polynomial.eval_map, subfield.to_subring.subtype_eq_subtype, hf, smul_zero] end /- Why is this so slow? -/ theorem irreducible_aux (f g : polynomial (fixed_points.subfield G F)) (hf : f.monic) (hg : g.monic) (hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 := begin have hf2 : f ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_right _ _ }, have hg2 : g ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_left _ _ }, have := eval₂ G F x, rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this, cases this, { right, have hf3 : f = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hf (monic G F x) (associated_of_dvd_dvd hf2 $ @of_eval₂ G _ F _ _ _ x f this) }, rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).ne_zero] at hfg }, { left, have hg3 : g = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hg (monic G F x) (associated_of_dvd_dvd hg2 $ @of_eval₂ G _ F _ _ _ x g this) }, rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).ne_zero] at hfg } end theorem irreducible : irreducible (minpoly G F x) := (polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x) end minpoly end fintype theorem is_integral [finite G] (x : F) : is_integral (fixed_points.subfield G F) x := by { casesI nonempty_fintype G, exact ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩ } section fintype variables [fintype G] (x : F) theorem minpoly_eq_minpoly : minpoly G F x = _root_.minpoly (fixed_points.subfield G F) x := minpoly.eq_of_irreducible_of_monic (minpoly.irreducible G F x) (minpoly.eval₂ G F x) (minpoly.monic G F x) lemma dim_le_card : module.rank (fixed_points.subfield G F) F ≤ fintype.card G := dim_le $ λ s hs, by simpa only [dim_fun', cardinal.mk_coe_finset, finset.coe_sort_coe, cardinal.lift_nat_cast, cardinal.nat_cast_le] using cardinal_lift_le_dim_of_linear_independent' (linear_independent_smul_of_linear_independent G F hs) end fintype section finite variables [finite G] instance normal : normal (fixed_points.subfield G F) F := ⟨λ x, (is_integral G F x).is_algebraic _, λ x, (polynomial.splits_id_iff_splits _).1 $ begin casesI nonempty_fintype G, rw [←minpoly_eq_minpoly, minpoly, coe_algebra_map, ←subfield.to_subring.subtype_eq_subtype, polynomial.map_to_subring _ (subfield G F).to_subring, prod_X_sub_smul], exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _), end⟩ instance separable : is_separable (fixed_points.subfield G F) F := ⟨is_integral G F, λ x, by { casesI nonempty_fintype G, -- this was a plain rw when we were using unbundled subrings erw [← minpoly_eq_minpoly, ← polynomial.separable_map (fixed_points.subfield G F).subtype, minpoly, polynomial.map_to_subring _ ((subfield G F).to_subring) ], exact polynomial.separable_prod_X_sub_C_iff.2 (injective_of_quotient_stabilizer G x) }⟩ instance : finite_dimensional (subfield G F) F := by { casesI nonempty_fintype G, exact is_noetherian.iff_fg.1 (is_noetherian.iff_dim_lt_aleph_0.2 $ (dim_le_card G F).trans_lt $ cardinal.nat_lt_aleph_0 _) } end finite lemma finrank_le_card [fintype G] : finrank (subfield G F) F ≤ fintype.card G := begin rw [← cardinal.nat_cast_le, finrank_eq_dim], apply dim_le_card, end end fixed_points lemma linear_independent_to_linear_map (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [ring A] [algebra R A] [comm_ring B] [is_domain B] [algebra R B] : linear_independent B (alg_hom.to_linear_map : (A →ₐ[R] B) → (A →ₗ[R] B)) := have linear_independent B (linear_map.lto_fun R A B ∘ alg_hom.to_linear_map), from ((linear_independent_monoid_hom A B).comp (coe : (A →ₐ[R] B) → (A →* B)) (λ f g hfg, alg_hom.ext $ monoid_hom.ext_iff.1 hfg) : _), this.of_comp _ lemma cardinal_mk_alg_hom (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : cardinal.mk (V →ₐ[K] W) ≤ finrank W (V →ₗ[K] W) := cardinal_mk_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V W noncomputable instance alg_equiv.fintype (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype (V ≃ₐ[K] V) := fintype.of_equiv (V →ₐ[K] V) (alg_equiv_equiv_alg_hom K V).symm lemma finrank_alg_hom (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype.card (V →ₐ[K] V) ≤ finrank V (V →ₗ[K] V) := fintype_card_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V V namespace fixed_points theorem finrank_eq_card (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_smul G F] : finrank (fixed_points.subfield G F) F = fintype.card G := le_antisymm (fixed_points.finrank_le_card G F) $ calc fintype.card G ≤ fintype.card (F →ₐ[fixed_points.subfield G F] F) : fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) ... ≤ finrank F (F →ₗ[fixed_points.subfield G F] F) : finrank_alg_hom (fixed_points G F) F ... = finrank (fixed_points.subfield G F) F : finrank_linear_map' _ _ _ /-- `mul_semiring_action.to_alg_hom` is bijective. -/ theorem to_alg_hom_bijective (G : Type u) (F : Type v) [group G] [field F] [finite G] [mul_semiring_action G F] [has_faithful_smul G F] : function.bijective (mul_semiring_action.to_alg_hom _ _ : G → F →ₐ[subfield G F] F) := begin casesI nonempty_fintype G, rw fintype.bijective_iff_injective_and_card, split, { exact mul_semiring_action.to_alg_hom_injective _ F }, { apply le_antisymm, { exact fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) }, { rw ← finrank_eq_card G F, exact has_le.le.trans_eq (finrank_alg_hom _ F) (finrank_linear_map' _ _ _) } }, end /-- Bijection between G and algebra homomorphisms that fix the fixed points -/ def to_alg_hom_equiv (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_smul G F] : G ≃ (F →ₐ[fixed_points.subfield G F] F) := equiv.of_bijective _ (to_alg_hom_bijective G F) end fixed_points
3123ad51b5dd355b437322bcf981f301a6ba9f8b
d1bbf1801b3dcb214451d48214589f511061da63
/src/linear_algebra/basic.lean
2b62d813b23a4d217167250c524d8882faf12408
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
107,669
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import algebra.big_operators.pi import algebra.module.pi import algebra.module.prod import algebra.module.submodule import algebra.group.prod import data.finsupp.basic import algebra.pointwise /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module`. ## Main definitions * Many constructors for linear maps, including `prod` and `coprod` * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `quotient_inf_equiv_sup_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. * We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is `\.`, not the same as the scalar multiplication `•`/`\bub`. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`prod`, `coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [semiring R] [add_comm_monoid M] [semimodule R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (f g : M →ₗ[R] M₂) include R @[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 : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (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 R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := (f.dom_restrict p).cod_restrict p $ submodule.forall.2 hf lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl @[simp] lemma default_def : default (M →ₗ[R] M₂) = 0 := rfl instance unique_of_left [subsingleton M] : unique (M →ₗ[R] M₂) := { uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero], .. linear_map.inhabited } instance unique_of_right [subsingleton M₂] : unique (M →ₗ[R] M₂) := coe_injective.unique /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp [add_comm, add_left_comm], by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map_apply_is_add_monoid_hom (a : M) : is_add_monoid_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a, map_zero := rfl } lemma add_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (h + g).comp f = h.comp f + g.comp f := rfl lemma comp_add (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (f + g) = h.comp f + h.comp g := by { ext, simp } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm /-- `λb, f b • x` is a linear map. -/ def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M := ⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩. @[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_right f x : M₂ → M) c = f c • x := rfl instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ lemma mul_eq_comp (f g : M →ₗ[R] M) : f * g = f.comp g := rfl @[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..}; { intros, apply linear_map.ext, simp {proj := ff} } section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩ /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩ end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The prod of two linear maps is a linear map. -/ def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ := { to_fun := λ x, (f x, g x), map_add' := λ x y, by simp only [prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem prod_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) : prod f g x = (f x, g x) := rfl @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := by refine ⟨add_monoid_hom.inl _ _, _, _⟩; intros; simp /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨add_monoid_hom.inr _ _, _, _⟩; intros; simp end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := { to_fun := λ x, f x.1 + g x.2, map_add' := λ x y, by simp only [map_add, prod.snd_add, prod.fst_add]; cc, map_smul' := λ x y, by simp only [smul_add, prod.smul_snd, prod.smul_fst, map_smul] } @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) : coprod f g (x, y) = f x + g y := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext ⟨x, y⟩; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext ⟨x, y⟩; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext ⟨x, y⟩; simp theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] (f g : M →ₗ[R] M₂) /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp [add_comm], by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl @[simp] lemma comp_neg (g : M₂ →ₗ[R] M₃) : g.comp (- f) = - g.comp f := by { ext, simp } /-- The negation of a linear map is linear. -/ instance : has_sub (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b - g b, by { simp only [map_add, sub_eq_add_neg, neg_add], cc }, by { intros, simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl lemma sub_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (g - f) = h.comp g - h.comp f := by { ext, simp } /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, ..}; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg] instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } end add_comm_group section has_scalar variables {S : Type*} [semiring R] [monoid S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [distrib_mul_action S M₂] [smul_comm_class R S M₂] (f : M →ₗ[R] M₂) instance : has_scalar S (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, λ x y, by rw [f.map_add, smul_add], λ c x, by simp only [f.map_smul, smul_comm c]⟩⟩ @[simp] lemma smul_apply (a : S) (x : M) : (a • f) x = a • f x := rfl instance : distrib_mul_action S (M →ₗ[R] M₂) := { one_smul := λ f, ext $ λ _, one_smul _ _, mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _, smul_add := λ c f g, ext $ λ x, smul_add _ _ _, smul_zero := λ c, ext $ λ x, smul_zero _ } theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) := rfl end has_scalar section semimodule variables {S : Type*} [semiring R] [semiring S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule S M₂] [semimodule S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] (f : M →ₗ[R] M₂) instance : semimodule S (M →ₗ[R] M₂) := { add_smul := λ a b f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variable (S) /-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`. See `applyₗ` for a version where `S = R` -/ def applyₗ' (v : M) : (M →ₗ[R] M₂) →ₗ[S] M₂ := { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v } end semimodule section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (f g : M →ₗ[R] M₂) include R theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨f.comp, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. See also `linear_map.applyₗ'` for a version that works with two different semirings. -/ def applyₗ (v : M) : (M →ₗ[R] M₂) →ₗ[R] M₂ := applyₗ' R v end comm_semiring section semiring variables [semiring R] [add_comm_monoid M] [semimodule R M] instance endomorphism_semiring : semiring (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..linear_map.add_comm_monoid, ..}; { intros, apply linear_map.ext, simp {proj := ff} } lemma mul_apply (f g : M →ₗ[R] M) (x : M) : (f * g) x = f (g x) := rfl end semiring section ring variables [ring R] [add_comm_group M] [semimodule R M] instance endomorphism_ring : ring (M →ₗ[R] M) := { ..linear_map.endomorphism_semiring, ..linear_map.add_comm_group } end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set instance : partial_order (submodule R M) := { le := λ p p', ∀ ⦃x⦄, x ∈ p → x ∈ p', ..partial_order.lift (coe : submodule R M → set M) coe_injective } variables {p p'} lemma le_def : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl lemma le_def' : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl lemma lt_def : p < p' ↔ (p : set M) ⊂ p' := iff.rfl lemma not_le_iff_exists : ¬ (p ≤ p') ↔ ∃ x ∈ p, x ∉ p' := not_subset lemma exists_of_lt {p p' : submodule R M} : p < p' → ∃ x ∈ p', x ∉ p := exists_of_ssubset lemma lt_iff_le_and_exists : p < p' ↔ p ≤ p' ∧ ∃ x ∈ p', x ∉ p := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨{ carrier := {0}, smul_mem' := by simp { contextual := tt }, .. (⊥ : add_submonoid M)}⟩ instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl section variables (R) @[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff end lemma nonzero_mem_of_bot_lt {I : submodule R M} (bot_lt : ⊥ < I) : ∃ a : I, a ≠ 0 := begin have h := (submodule.lt_iff_le_and_exists.1 bot_lt).2, tidy, end instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..submodule.partial_order } protected lemma eq_bot_iff (p : submodule R M) : p = ⊥ ↔ ∀ x ∈ p, x = (0 : M) := ⟨ λ h, h.symm ▸ λ x hx, (mem_bot R).mp hx, λ h, eq_bot_iff.mpr (λ x hx, (mem_bot R).mpr (h x hx)) ⟩ protected lemma ne_bot_iff (p : submodule R M) : p ≠ ⊥ ↔ ∃ x ∈ p, x ≠ (0 : M) := by { haveI := classical.prop_decidable, simp_rw [ne.def, p.eq_bot_iff, not_forall] } /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨{ carrier := univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ := by ext x; simp [semimodule.eq_zero_of_zero_eq_one x zero_eq_one] instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, (s : set M), zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule R M) := ⟨λ p p', { carrier := p ∩ p', zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, 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.order_top, ..submodule.order_bot } instance add_comm_monoid_submodule : add_comm_monoid (submodule R 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 (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ lemma bot_ne_top [nontrivial M] : (⊥ : submodule R M) ≠ ⊤ := λ h, let ⟨a, ha⟩ := exists_ne (0 : M) in ha $ (mem_bot R).1 $ (eq_top_iff.1 h) trivial @[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule R M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] lemma mem_Inf {S : set (submodule R M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[simp] theorem mem_infi {ι} (p : ι → submodule R M) : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h @[simp] lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := submodule.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : 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 : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : 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 R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span lemma map_span (f : M →ₗ[R] M₂) (s : set M) : (span R s).map f = span R (f '' s) := eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩ /- See also `span_preimage_eq` below. -/ lemma span_preimage_le (f : M →ₗ[R] M₂) (s : set M₂) : span R (f ⁻¹' s) ≤ (span R s).comap f := by { rw [span_le, comap_coe], exact preimage_mono (subset_span), } /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma mem_sup_left {S T : submodule R M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : submodule R M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Sort*} {b : M} {p : ι → submodule R M} (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h lemma mem_Sup_of_mem {S : set (submodule R M)} {s : submodule R M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] 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 [add_assoc]; cc⟩ }, { 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)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [submodule.exists, coe_mk] end notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x) lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, 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 le_span_singleton_iff {s : submodule R M} {v₀ : M} : s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v := by simp_rw [le_def', mem_span_singleton] @[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ := by { ext, simp [mem_span_singleton, eq_comm] } lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x := begin rw [span_le, set.singleton_subset_iff, mem_coe], exact smul_mem _ _ (mem_span_singleton_self _) end lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x := begin refine le_antisymm (span_singleton_smul_le r x) _, convert span_singleton_smul_le r⁻¹ (r • x), exact (inv_smul_smul' hr _).symm end lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {p : submodule K E} {x : E} (x0 : x ≠ 0) : disjoint p (K ∙ x) ↔ x ∉ p := disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩ lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R 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 supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, mem_coe] lemma lt_add_iff_not_mem {I : submodule R M} {a : M} : I < I + (R ∙ a) ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I + (R ∙ a) ≤ I, { simp only [add_eq_sup, sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply lt_iff_le_and_exists.mpr, split, simp only [add_eq_sup, le_sup_left], use a, split, swap, { assumption, }, { have : (R ∙ a) ≤ I + (R ∙ a) := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : 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') := coe_injective 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 end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set @[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff @[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p := ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩, λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩ @[simp] lemma span_neg (s : set M) : span R (-s) = span R s := calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp ... = map (-linear_map.id) (span R s) : (map_span _ _).symm ... = span R s : by simp lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨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 [sub_eq_add_neg, add_left_comm, add_comm] 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 : has_sub (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 [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ (neg_mem p h₂)⟩ @[simp] theorem mk_sub : (mk (x - y) : quotient p) = mk x - mk y := rfl instance : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, ← mk_zero p, -mk_add, ← mk_add p, -mk_neg, ← mk_neg p, -mk_sub, ← mk_sub p, sub_eq_add_neg]; cc instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : semimodule R (quotient p) := semimodule.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] lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) := by { rintros ⟨x⟩, exact ⟨x, rfl⟩ } lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) := begin obtain ⟨x, _, not_mem_s⟩ := exists_of_lt h, refine ⟨⟨mk x, 0, _⟩⟩, simpa using not_mem_s end end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (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 : V →ₗ[K] V₂) (p : submodule K V) (a : K) (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 lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/ lemma eq_on_span {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`. See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/ lemma eq_on_span' {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) : set.eq_on f g (span R s : set M) := eq_on_span H /-- If `s` generates the whole semimodule and linear maps `f`, `g` are equal on `s`, then they are equal. -/ lemma ext_on {s : set M} {f g : M →ₗ[R] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) : f = g := linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _)) /-- If the range of `v : ι → M` generates the whole semimodule and linear maps `f`, `g` are equal at each `v i`, then they are equal. -/ lemma ext_on_range {v : ι → M} {f g : M →ₗ[R] M₂} (hv : span R (set.range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := ext_on hv (set.forall_range_iff.2 h) @[simp] lemma finsupp_sum {γ} [has_zero γ] (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (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⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤ theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ @[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := set.ext_iff.1 (range_coe f) theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _ theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := map_mono le_top lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma is_compl_range_inl_inr : is_compl (inl R M M₂).range (inr R M M₂).range := begin split, { rintros ⟨_, _⟩ ⟨⟨x, -, hx⟩, ⟨y, -, hy⟩⟩, simp only [prod.ext_iff, inl_apply, inr_apply, mem_bot] at hx hy ⊢, exact ⟨hy.1.symm, hx.2.symm⟩ }, { rintros ⟨x, y⟩ -, simp only [mem_sup, mem_range, exists_prop], refine ⟨(x, 0), ⟨x, rfl⟩, (0, y), ⟨y, rfl⟩, _⟩, simp } end lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := is_compl_range_inl_inr.sup_eq_top /-- Restrict the codomain of a linear map `f` to `f.range`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₗ[R] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : 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 : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem range_eq_bot {f : M →ₗ[R] M₂} : range f = ⊥ ↔ f = 0 := by rw [← range_le_bot_iff, le_bot_iff] lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ mem_map_of_mem trivial, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y ⟨_, hy⟩, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (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 : M →ₗ[R] M₂} (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_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod 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_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [le_def', prod_apply, mem_range, mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : 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 : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (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 map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range, map_le_map_iff] end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables {f : M →ₗ[R] M₂} include R open submodule theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {p : submodule R M} : 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 {p : submodule R M} {s : set M} (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) theorem ker_eq_bot : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ lemma ker_le_iff {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p := begin split, { intros h, use 0, rw [← mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, }, { rintros ⟨y, h₁, h₂⟩, rw le_def, intros z hz, simp only [mem_ker, mem_coe] at hz, rw [← mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁, have hx' : x ∈ p, { exact h₂ hx, }, have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], }, suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], }, exact p.sub_mem hxz hx', }, end /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [le_def', prod_apply, mem_range, mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end ring section field variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a end field end linear_map lemma submodule.sup_eq_range [semiring R] [add_comm_monoid M] [semimodule R M] (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, submodule.exists] namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [semimodule R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [semimodule R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (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] @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_snd] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { 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.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, map_le_map_iff' (ker_subtype p) } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ 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 : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (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 R 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] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (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 : M →ₗ[R] M₂) (h) (q : submodule R (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 : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.rel_iso : submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} := { 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.ext_val $ by simpa [comap_map_mkq p], map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.order_embedding : submodule R p.quotient ↪o submodule R M := (rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.order_embedding p p' = comap p.mkq p' := rfl lemma span_preimage_eq {f : M →ₗ[R] M₂} {s : set M₂} (h₀ : s.nonempty) (h₁ : s ⊆ range f) : span R (f ⁻¹' s) = (span R s).comap f := begin suffices : (span R s).comap f ≤ span R (f ⁻¹' s), { exact le_antisymm (span_preimage_le f s) this, }, have hk : ker f ≤ span R (f ⁻¹' s), { let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, }, rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy, exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), }, rw ← left_eq_sup at hk, rw f.range_coe at h₁, rw [hk, ← map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁], exact inf_le_right, end end ring end submodule namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] lemma range_mkq_comp (f : M →ₗ[R] M₂) : f.range.mkq.comp f = 0 := linear_map.ext $ λ x, by simp lemma ker_le_range_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 := by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end /-- An epimorphism is surjective. -/ lemma range_eq_top_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : M₂ →ₗ[R] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R] f.range.quotient).comp f = 0 := zero_comp _, rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)], exact ker_zero end end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := submodule.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule of the domain onto the image of the submodule. -/ def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) := { inv_fun := λ y, ⟨e.symm y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) } @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl end section prod variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_add' := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), map_smul' := λ c x, prod.ext (e₁.map_smul c _) (e₂.map_smul c _), .. equiv.prod_congr e₁.to_equiv e₂.to_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end prod section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def uncurry : (V → V₂ → R) ≃ₗ[R] (V × V₂ → R) := { map_add' := λ _ _, by { ext ⟨⟩, refl }, map_smul' := λ _ _, by { ext ⟨⟩, refl }, .. equiv.arrow_arrow_equiv_prod_arrow _ _ _} @[simp] lemma coe_uncurry : ⇑(linear_equiv.uncurry R V V₂) = uncurry := rfl @[simp] lemma coe_uncurry_symm : ⇑(linear_equiv.uncurry R V V₂).symm = curry := rfl end uncurry section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { 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 {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [semimodule R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective end end add_comm_monoid section add_comm_group variables [semiring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end add_comm_group section neg variables (R) [semiring R] [add_comm_group M] [semimodule R M] /-- `x ↦ -x` as a `linear_equiv` -/ def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) } variable {R} @[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl lemma neg_apply (x : M) : neg R x = -x := by simp @[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl end neg section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (e : M ≃ₗ[R] M₂) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. -/ noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range := { .. (equiv.set.range f $ linear_map.ker_eq_bot.1 h).trans (equiv.set.of_eq f.range_coe.symm), .. f.cod_restrict f.range (λ x, f.mem_range_self x) } @[simp] theorem of_injective_apply {h : f.ker = ⊥} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (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) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp }, right_inv := λ f, by { ext x, simp }, map_add' := λ f g, by { ext x, simp }, map_smul' := λ c f, by { ext x, simp } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl @[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) : (arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_group N] [add_comm_group N₂] [add_comm_group N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁] [add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ := begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) := linear_equiv.trans (linear_equiv.of_injective (to_span_singleton K M x) (ker_to_span_singleton K M h)) (of_eq (to_span_singleton K M x).range (K ∙ x) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) := begin apply submodule.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section semimodule variables [semiring R] [add_comm_monoid M] [semimodule R M] /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, submodule.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, submodule.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end semimodule variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl variables (q : submodule R M) /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = q) : p.quotient ≃ₗ[R] q.quotient := { map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl }, ..@quotient.congr _ _ (quotient_rel p) (quotient_rel q) (equiv.refl _) $ λ a b, by { subst h, refl } } end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) @[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw le_def', intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw le_def', intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\\{f ∈ Hom(M, M₂) | f(p) ⊆ q \\}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\\{f ∈ Hom(M, M₂) | f(p) ⊆ q \\} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, map_smul' := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace add_equiv variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl end add_equiv namespace linear_map open submodule section isomorphism_laws variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (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_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [quotient_inf_to_sup_quotient, 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 @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws section prod lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_group M₃] [semimodule R M] [semimodule R M₂] [semimodule R M₃] : is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) := ⟨λu v, rfl, λc u, rfl⟩ end prod section pi universe i variables [semiring R] [add_comm_monoid M₂] [semimodule R M₂] [add_comm_monoid M₃] [semimodule R M₃] {φ : ι → Type i} [∀i, add_comm_monoid (φ i)] [∀i, semimodule R (φ 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, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) := ⟨λc i, f i c, λ c d, funext $ λ i, (f i).map_add _ _, λ c d, funext $ λ i, (f i).map_smul _ _⟩ @[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ 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, M₂ →ₗ[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of modules are linear maps. -/ def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i := ⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Π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 (R φ) /-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ 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 R (Πi, φ i)) ≃ₗ[R] (Π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.coe_prop], ext b ⟨j, hj⟩, refl }, { ext1 ⟨b, hb⟩, apply subtype.ext, 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, { refl }, { 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 →ₗ[R] φ j := @function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ 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 (R φ) /-- The standard basis of the product of `φ`. -/ def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i) lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ 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 R φ i b i = b := by rw [std_basis_apply, update_same] lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := by rw [std_basis_apply, update_noteq h]; refl lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot_of_injective $ assume f g hfg, have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl, by simpa only [std_basis_same] lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := by ext b; simp lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := by ext b; simp [std_basis_ne R φ _ _ h] lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ 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 R φ 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 R φ i)) := submodule.le_def'.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show ∑ i in I, std_basis R φ i (b i) = b, { ext i, rw [finset.sum_apply, ← std_basis_same R φ 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 $ (std_basis R φ i).mem_range_self (b i)) 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 R φ 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 [hI.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _), rw [set.finite.mem_to_finset], exact le_refl _ end lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ 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 R φ this), exact infi_emptyset.symm, exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ 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 R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint.mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right) _, 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 lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := begin ext i j, rw [std_basis_apply, finsupp.single_apply], split_ifs, { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h)], refl }, end end end pi section fun_left variables (R M) [semiring R] [add_comm_monoid M] [semimodule R M] variables {m n p : Type*} /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := mk (∘f) (λ _ _, rfl) (λ _ _, rfl) @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end fun_left universe i variables [semiring R] [add_comm_monoid M] [semimodule R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, 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 : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { 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 } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map
7239b4b5f1c35ed7f8873cb2c6f8e8197c2b353e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/char_p/two.lean
c69cce8d5f6c3ba99befed9797e32dfd83518f6b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,337
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.char_p.basic /-! # Lemmas about rings of characteristic two > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains results about `char_p R 2`, in the `char_two` namespace. The lemmas in this file with a `_sq` suffix are just special cases of the `_pow_char` lemmas elsewhere, with a shorter name for ease of discovery, and no need for a `[fact (prime 2)]` argument. -/ variables {R ι : Type*} namespace char_two section semiring variables [semiring R] [char_p R 2] lemma two_eq_zero : (2 : R) = 0 := by rw [← nat.cast_two, char_p.cast_eq_zero] @[simp] lemma add_self_eq_zero (x : R) : x + x = 0 := by rw [←two_smul R x, two_eq_zero, zero_smul] @[simp] lemma bit0_eq_zero : (bit0 : R → R) = 0 := by { funext, exact add_self_eq_zero _ } lemma bit0_apply_eq_zero (x : R) : (bit0 x : R) = 0 := by simp @[simp] lemma bit1_eq_one : (bit1 : R → R) = 1 := by { funext, simp [bit1] } lemma bit1_apply_eq_one (x : R) : (bit1 x : R) = 1 := by simp end semiring section ring variables [ring R] [char_p R 2] @[simp] lemma neg_eq (x : R) : -x = x := by rw [neg_eq_iff_add_eq_zero, ←two_smul R x, two_eq_zero, zero_smul] lemma neg_eq' : has_neg.neg = (id : R → R) := funext neg_eq @[simp] lemma sub_eq_add (x y : R) : x - y = x + y := by rw [sub_eq_add_neg, neg_eq] lemma sub_eq_add' : has_sub.sub = ((+) : R → R → R) := funext $ λ x, funext $ λ y, sub_eq_add x y end ring section comm_semiring variables [comm_semiring R] [char_p R 2] lemma add_sq (x y : R) : (x + y) ^ 2 = x ^ 2 + y ^ 2 := add_pow_char _ _ _ lemma add_mul_self (x y : R) : (x + y) * (x + y) = x * x + y * y := by rw [←pow_two, ←pow_two, ←pow_two, add_sq] open_locale big_operators lemma list_sum_sq (l : list R) : l.sum ^ 2 = (l.map (^ 2)).sum := list_sum_pow_char _ _ lemma list_sum_mul_self (l : list R) : l.sum * l.sum = (list.map (λ x, x * x) l).sum := by simp_rw [←pow_two, list_sum_sq] lemma multiset_sum_sq (l : multiset R) : l.sum ^ 2 = (l.map (^ 2)).sum := multiset_sum_pow_char _ _ lemma multiset_sum_mul_self (l : multiset R) : l.sum * l.sum = (multiset.map (λ x, x * x) l).sum := by simp_rw [←pow_two, multiset_sum_sq] lemma sum_sq (s : finset ι) (f : ι → R) : (∑ i in s, f i) ^ 2 = ∑ i in s, f i ^ 2 := sum_pow_char _ _ _ lemma sum_mul_self (s : finset ι) (f : ι → R) : (∑ i in s, f i) * (∑ i in s, f i) = ∑ i in s, f i * f i := by simp_rw [←pow_two, sum_sq] end comm_semiring end char_two section ring_char variables [ring R] lemma neg_one_eq_one_iff [nontrivial R]: (-1 : R) = 1 ↔ ring_char R = 2 := begin refine ⟨λ h, _, λ h, @@char_two.neg_eq _ (ring_char.of_eq h) 1⟩, rw [eq_comm, ←sub_eq_zero, sub_neg_eq_add, ← nat.cast_one, ← nat.cast_add] at h, exact ((nat.dvd_prime nat.prime_two).mp (ring_char.dvd h)).resolve_left char_p.ring_char_ne_one end @[simp] lemma order_of_neg_one [nontrivial R] : order_of (-1 : R) = if ring_char R = 2 then 1 else 2 := begin split_ifs, { rw [neg_one_eq_one_iff.2 h, order_of_one] }, apply order_of_eq_prime, { simp }, simpa [neg_one_eq_one_iff] using h end end ring_char
9e237075668cdfc63b46b4d643645250ce446e19
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/calculus/specific_functions.lean
43480bbf2259a894865803e9591d3b0f2b5fa6ee
[ "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
18,942
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.iterated_deriv import analysis.inner_product_space.euclidean_dist /-! # Infinitely smooth bump function In this file we construct several infinitely smooth functions with properties that an analytic function cannot have: * `exp_neg_inv_glue` is equal to zero for `x ≤ 0` and is strictly positive otherwise; it is given by `x ↦ exp (-1/x)` for `x > 0`; * `real.smooth_transition` is equal to zero for `x ≤ 0` and is equal to one for `x ≥ 1`; it is given by `exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x))`; * `f : times_cont_diff_bump_of_inner c`, where `c` is a point in an inner product space, is a bundled smooth function such that - `f` is equal to `1` in `metric.closed_ball c f.r`; - `support f = metric.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `times_cont_diff_bump_of_inner` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`. * `f : times_cont_diff_bump c`, where `c` is a point in a finite dimensional real vector space, is a bundled smooth function such that - `f` is equal to `1` in `euclidean.closed_ball c f.r`; - `support f = euclidean.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `times_cont_diff_bump` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`. -/ noncomputable theory open_locale classical topological_space open polynomial real filter set function /-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0` for `x ≤ 0`. It 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, { assume k, rw tsub_eq_iff_eq_add_of_le, { ring }, { simpa [mul_add] using add_le_add (zero_le (2 * k)) one_le_two } }, 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], -- `ring_exp` can't solve `p ∨ q` goal generated by `mul_eq_mul_right_iff` cases n; simp [nat.succ_eq_add_one, A, -mul_eq_mul_right_iff]; 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, filter_upwards [lt_mem_nhds hx], assume y hy, simp [f_aux, hy.not_le] 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_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_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, filter_upwards [gt_mem_nhds hx], assume y hy, simp [f_aux, hy.le] }, { 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. -/ protected theorem times_cont_diff {n} : times_cont_diff ℝ n 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 /-- An infinitely smooth function `f : ℝ → ℝ` such that `f x = 0` for `x ≤ 0`, `f x = 1` for `1 ≤ x`, and `0 < f x < 1` for `0 < x < 1`. -/ def real.smooth_transition (x : ℝ) : ℝ := exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x)) namespace real namespace smooth_transition variables {x : ℝ} open exp_neg_inv_glue lemma pos_denom (x) : 0 < exp_neg_inv_glue x + exp_neg_inv_glue (1 - x) := ((@zero_lt_one ℝ _ _).lt_or_lt x).elim (λ hx, add_pos_of_pos_of_nonneg (pos_of_pos hx) (nonneg _)) (λ hx, add_pos_of_nonneg_of_pos (nonneg _) (pos_of_pos $ sub_pos.2 hx)) lemma one_of_one_le (h : 1 ≤ x) : smooth_transition x = 1 := (div_eq_one_iff_eq $ (pos_denom x).ne').2 $ by rw [zero_of_nonpos (sub_nonpos.2 h), add_zero] lemma zero_of_nonpos (h : x ≤ 0) : smooth_transition x = 0 := by rw [smooth_transition, zero_of_nonpos h, zero_div] lemma le_one (x : ℝ) : smooth_transition x ≤ 1 := (div_le_one (pos_denom x)).2 $ le_add_of_nonneg_right (nonneg _) lemma nonneg (x : ℝ) : 0 ≤ smooth_transition x := div_nonneg (exp_neg_inv_glue.nonneg _) (pos_denom x).le lemma lt_one_of_lt_one (h : x < 1) : smooth_transition x < 1 := (div_lt_one $ pos_denom x).2 $ lt_add_of_pos_right _ $ pos_of_pos $ sub_pos.2 h lemma pos_of_pos (h : 0 < x) : 0 < smooth_transition x := div_pos (exp_neg_inv_glue.pos_of_pos h) (pos_denom x) protected lemma times_cont_diff {n} : times_cont_diff ℝ n smooth_transition := exp_neg_inv_glue.times_cont_diff.div (exp_neg_inv_glue.times_cont_diff.add $ exp_neg_inv_glue.times_cont_diff.comp $ times_cont_diff_const.sub times_cont_diff_id) $ λ x, (pos_denom x).ne' protected lemma times_cont_diff_at {x n} : times_cont_diff_at ℝ n smooth_transition x := smooth_transition.times_cont_diff.times_cont_diff_at end smooth_transition end real variable {E : Type*} /-- `f : times_cont_diff_bump_of_inner c`, where `c` is a point in an inner product space, is a bundled smooth function such that - `f` is equal to `1` in `metric.closed_ball c f.r`; - `support f = metric.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `times_cont_diff_bump_of_inner` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`. -/ structure times_cont_diff_bump_of_inner (c : E) := (r R : ℝ) (r_pos : 0 < r) (r_lt_R : r < R) namespace times_cont_diff_bump_of_inner lemma R_pos {c : E} (f : times_cont_diff_bump_of_inner c) : 0 < f.R := f.r_pos.trans f.r_lt_R instance (c : E) : inhabited (times_cont_diff_bump_of_inner c) := ⟨⟨1, 2, zero_lt_one, one_lt_two⟩⟩ variables [inner_product_space ℝ E] {c : E} (f : times_cont_diff_bump_of_inner c) {x : E} /-- The function defined by `f : times_cont_diff_bump_of_inner c`. Use automatic coercion to function instead. -/ def to_fun (f : times_cont_diff_bump_of_inner c) : E → ℝ := λ x, real.smooth_transition ((f.R - dist x c) / (f.R - f.r)) instance : has_coe_to_fun (times_cont_diff_bump_of_inner c) (λ _, E → ℝ) := ⟨to_fun⟩ open real (smooth_transition) real.smooth_transition metric lemma one_of_mem_closed_ball (hx : x ∈ closed_ball c f.r) : f x = 1 := one_of_one_le $ (one_le_div (sub_pos.2 f.r_lt_R)).2 $ sub_le_sub_left hx _ lemma nonneg : 0 ≤ f x := nonneg _ lemma le_one : f x ≤ 1 := le_one _ lemma pos_of_mem_ball (hx : x ∈ ball c f.R) : 0 < f x := pos_of_pos $ div_pos (sub_pos.2 hx) (sub_pos.2 f.r_lt_R) lemma lt_one_of_lt_dist (h : f.r < dist x c) : f x < 1 := lt_one_of_lt_one $ (div_lt_one (sub_pos.2 f.r_lt_R)).2 $ sub_lt_sub_left h _ lemma zero_of_le_dist (hx : f.R ≤ dist x c) : f x = 0 := zero_of_nonpos $ div_nonpos_of_nonpos_of_nonneg (sub_nonpos.2 hx) (sub_nonneg.2 f.r_lt_R.le) lemma support_eq : support (f : E → ℝ) = metric.ball c f.R := begin ext x, suffices : f x ≠ 0 ↔ dist x c < f.R, by simpa [mem_support], cases lt_or_le (dist x c) f.R with hx hx, { simp [hx, (f.pos_of_mem_ball hx).ne'] }, { simp [hx.not_lt, f.zero_of_le_dist hx] } end lemma eventually_eq_one_of_mem_ball (h : x ∈ ball c f.r) : f =ᶠ[𝓝 x] 1 := ((is_open_lt (continuous_id.dist continuous_const) continuous_const).eventually_mem h).mono $ λ z hz, f.one_of_mem_closed_ball (le_of_lt hz) lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 := f.eventually_eq_one_of_mem_ball (mem_ball_self f.r_pos) protected lemma times_cont_diff_at {n} : times_cont_diff_at ℝ n f x := begin rcases em (x = c) with rfl|hx, { refine times_cont_diff_at.congr_of_eventually_eq _ f.eventually_eq_one, rw pi.one_def, exact times_cont_diff_at_const }, { exact real.smooth_transition.times_cont_diff_at.comp x (times_cont_diff_at.div_const $ times_cont_diff_at_const.sub $ times_cont_diff_at_id.dist times_cont_diff_at_const hx) } end protected lemma times_cont_diff {n} : times_cont_diff ℝ n f := times_cont_diff_iff_times_cont_diff_at.2 $ λ y, f.times_cont_diff_at protected lemma times_cont_diff_within_at {s n} : times_cont_diff_within_at ℝ n f s x := f.times_cont_diff_at.times_cont_diff_within_at end times_cont_diff_bump_of_inner /-- `f : times_cont_diff_bump c`, where `c` is a point in a finite dimensional real vector space, is a bundled smooth function such that - `f` is equal to `1` in `euclidean.closed_ball c f.r`; - `support f = euclidean.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `times_cont_diff_bump` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`.-/ structure times_cont_diff_bump [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] (c : E) extends times_cont_diff_bump_of_inner (to_euclidean c) namespace times_cont_diff_bump variables [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {c x : E} (f : times_cont_diff_bump c) /-- The function defined by `f : times_cont_diff_bump c`. Use automatic coercion to function instead. -/ def to_fun (f : times_cont_diff_bump c) : E → ℝ := f.to_times_cont_diff_bump_of_inner ∘ to_euclidean instance : has_coe_to_fun (times_cont_diff_bump c) (λ _, E → ℝ) := ⟨to_fun⟩ instance (c : E) : inhabited (times_cont_diff_bump c) := ⟨⟨default _⟩⟩ lemma R_pos : 0 < f.R := f.to_times_cont_diff_bump_of_inner.R_pos lemma coe_eq_comp : ⇑f = f.to_times_cont_diff_bump_of_inner ∘ to_euclidean := rfl lemma one_of_mem_closed_ball (hx : x ∈ euclidean.closed_ball c f.r) : f x = 1 := f.to_times_cont_diff_bump_of_inner.one_of_mem_closed_ball hx lemma nonneg : 0 ≤ f x := f.to_times_cont_diff_bump_of_inner.nonneg lemma le_one : f x ≤ 1 := f.to_times_cont_diff_bump_of_inner.le_one lemma pos_of_mem_ball (hx : x ∈ euclidean.ball c f.R) : 0 < f x := f.to_times_cont_diff_bump_of_inner.pos_of_mem_ball hx lemma lt_one_of_lt_dist (h : f.r < euclidean.dist x c) : f x < 1 := f.to_times_cont_diff_bump_of_inner.lt_one_of_lt_dist h lemma zero_of_le_dist (hx : f.R ≤ euclidean.dist x c) : f x = 0 := f.to_times_cont_diff_bump_of_inner.zero_of_le_dist hx lemma support_eq : support (f : E → ℝ) = euclidean.ball c f.R := by rw [euclidean.ball_eq_preimage, ← f.to_times_cont_diff_bump_of_inner.support_eq, ← support_comp_eq_preimage, coe_eq_comp] lemma closure_support_eq : closure (support f) = euclidean.closed_ball c f.R := by rw [f.support_eq, euclidean.closure_ball _ f.R_pos] lemma compact_closure_support : is_compact (closure (support f)) := by { rw f.closure_support_eq, exact euclidean.is_compact_closed_ball } lemma eventually_eq_one_of_mem_ball (h : x ∈ euclidean.ball c f.r) : f =ᶠ[𝓝 x] 1 := to_euclidean.continuous_at (f.to_times_cont_diff_bump_of_inner.eventually_eq_one_of_mem_ball h) lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 := f.eventually_eq_one_of_mem_ball $ euclidean.mem_ball_self f.r_pos protected lemma times_cont_diff {n} : times_cont_diff ℝ n f := f.to_times_cont_diff_bump_of_inner.times_cont_diff.comp (to_euclidean : E ≃L[ℝ] _).times_cont_diff protected lemma times_cont_diff_at {n} : times_cont_diff_at ℝ n f x := f.times_cont_diff.times_cont_diff_at protected lemma times_cont_diff_within_at {s n} : times_cont_diff_within_at ℝ n f s x := f.times_cont_diff_at.times_cont_diff_within_at lemma exists_closure_support_subset {s : set E} (hs : s ∈ 𝓝 c) : ∃ f : times_cont_diff_bump c, closure (support f) ⊆ s := let ⟨R, h0, hR⟩ := euclidean.nhds_basis_closed_ball.mem_iff.1 hs in ⟨⟨⟨R / 2, R, half_pos h0, half_lt_self h0⟩⟩, by rwa closure_support_eq⟩ lemma exists_closure_subset {R : ℝ} (hR : 0 < R) {s : set E} (hs : is_closed s) (hsR : s ⊆ euclidean.ball c R) : ∃ f : times_cont_diff_bump c, f.R = R ∧ s ⊆ euclidean.ball c f.r := begin rcases euclidean.exists_pos_lt_subset_ball hR hs hsR with ⟨r, hr, hsr⟩, exact ⟨⟨⟨r, R, hr.1, hr.2⟩⟩, rfl, hsr⟩ end end times_cont_diff_bump open finite_dimensional metric /-- If `E` is a finite dimensional normed space over `ℝ`, then for any point `x : E` and its neighborhood `s` there exists an infinitely smooth function with the following properties: * `f y = 1` in a neighborhood of `x`; * `f y = 0` outside of `s`; * moreover, `closure (support f) ⊆ s` and `closure (support f)` is a compact set; * `f y ∈ [0, 1]` for all `y`. This lemma is a simple wrapper around lemmas about bundled smooth bump functions, see `times_cont_diff_bump`. -/ lemma exists_times_cont_diff_bump_function_of_mem_nhds [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {x : E} {s : set E} (hs : s ∈ 𝓝 x) : ∃ f : E → ℝ, f =ᶠ[𝓝 x] 1 ∧ (∀ y, f y ∈ Icc (0 : ℝ) 1) ∧ times_cont_diff ℝ ⊤ f ∧ is_compact (closure $ support f) ∧ closure (support f) ⊆ s := let ⟨f, hf⟩ := times_cont_diff_bump.exists_closure_support_subset hs in ⟨f, f.eventually_eq_one, λ y, ⟨f.nonneg, f.le_one⟩, f.times_cont_diff, f.compact_closure_support, hf⟩
e3a902bcbc8c6bc35f8d58a98d5d06c8b87542c6
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/sheaves/sheaf.lean
d97c773eeecf1ee9cdf3ffaab57b16c526e3e459
[ "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
3,686
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 topology.sheaves.sheaf_condition.equalizer_products import category_theory.full_subcategory /-! # Sheaves We define sheaves on a topological space, with values in an arbitrary category with products. The sheaf condition for a `F : presheaf C X` requires that the morphism `F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ F.obj (U i) ⟶ ∏ F.obj (U i ⊓ U j)`. We provide the instance `category (sheaf C X)` as the full subcategory of presheaves, and the fully faithful functor `sheaf.forget : sheaf C X ⥤ presheaf C X`. ## Equivalent conditions While the "official" definition is in terms of an equalizer diagram, in `src/topology/sheaves/sheaf_condition/pairwise_intersections.lean` and in `src/topology/sheaves/sheaf_condition/open_le_cover.lean` we provide two equivalent conditions (and prove they are equivalent). The first is that `F.obj U` is the limit point of the diagram consisting of all the `F.obj (U i)` and `F.obj (U i ⊓ U j)`. (That is, we explode the equalizer of two products out into its component pieces.) The second is that `F.obj U` is the limit point of the diagram constisting of all the `F.obj V`, for those `V : opens X` such that `V ≤ U i` for some `i`. (This condition is particularly easy to state, and perhaps should become the "official" definition.) -/ universes v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] [has_products C] variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) namespace presheaf open sheaf_condition_equalizer_products /-- The sheaf condition for a `F : presheaf C X` requires that the morphism `F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ F.obj (U i) ⟶ ∏ F.obj (U i) ⊓ (U j)`. -/ def is_sheaf (F : presheaf C X) : Prop := ∀ ⦃ι : Type v⦄ (U : ι → opens X), nonempty (is_limit (sheaf_condition_equalizer_products.fork F U)) /-- The presheaf valued in `punit` over any topological space is a sheaf. -/ lemma is_sheaf_punit (F : presheaf (category_theory.discrete punit) X) : F.is_sheaf := λ ι U, ⟨punit_cone_is_limit⟩ /-- Transfer the sheaf condition across an isomorphism of presheaves. -/ lemma is_sheaf_of_iso {F G : presheaf C X} (α : F ≅ G) (h : F.is_sheaf) : G.is_sheaf := λ ι U, ⟨is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv _ _).symm (h U).some) (sheaf_condition_equalizer_products.fork.iso_of_iso U α.symm).symm⟩ lemma is_sheaf_iso_iff {F G : presheaf C X} (α : F ≅ G) : F.is_sheaf ↔ G.is_sheaf := ⟨(λ h, is_sheaf_of_iso α h), (λ h, is_sheaf_of_iso α.symm h)⟩ end presheaf variables (C X) /-- A `sheaf C X` is a presheaf of objects from `C` over a (bundled) topological space `X`, satisfying the sheaf condition. -/ @[derive category] def sheaf : Type (max u v) := { F : presheaf C X // F.is_sheaf } -- Let's construct a trivial example, to keep the inhabited linter happy. instance sheaf_inhabited : inhabited (sheaf (category_theory.discrete punit) X) := ⟨⟨functor.star _, presheaf.is_sheaf_punit _⟩⟩ namespace sheaf /-- The forgetful functor from sheaves to presheaves. -/ @[derive [full, faithful]] def forget : Top.sheaf C X ⥤ Top.presheaf C X := full_subcategory_inclusion presheaf.is_sheaf end sheaf end Top
88c5da3e0d8b4a06d7996c50ebd7fdd2a7f4f37b
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/structuralIssue2.lean
797da1daa235d96bbfaf5cc7d36a07db4d1667a7
[ "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
744
lean
namespace List @[simp] theorem filter_nil {p : α → Bool} : filter p [] = [] := by simp [filter, filterAux, reverse, reverseAux] theorem cons_eq_append (a : α) (as : List α) : a :: as = [a] ++ as := rfl theorem filter_cons (a : α) (as : List α) : filter p (a :: as) = if p a then a :: filter p as else filter p as := sorry @[simp] theorem filter_append {as bs : List α} {p : α → Bool} : filter p (as ++ bs) = filter p as ++ filter p bs := match as with | [] => by simp | a :: as => by rw [filter_cons, cons_append, filter_cons] cases p a simp [filter_append] simp [filter_append] -- the previous contains a more complicated version of def f : Nat → Nat | 0 => 1 | i+1 => (fun x => f x) i
547f0f735cbb56f4b5468daf8f9dd6823a335464
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/primorial.lean
99f8a7ae25b6fff273fde028befdcd2666978a3d
[ "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
6,733
lean
/- Copyright (c) 2020 Patrick Stevens. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Stevens -/ import tactic.ring_exp import data.nat.parity import data.nat.choose.sum /-! # Primorial This file defines the primorial function (the product of primes less than or equal to some bound), and proves that `primorial n ≤ 4 ^ n`. ## Notations We use the local notation `n#` for the primorial of `n`: that is, the product of the primes less than or equal to `n`. -/ open finset open nat open_locale big_operators nat /-- The primorial `n#` of `n` is the product of the primes less than or equal to `n`. -/ def primorial (n : ℕ) : ℕ := ∏ p in (filter nat.prime (range (n + 1))), p local notation x`#` := primorial x lemma primorial_succ {n : ℕ} (n_big : 1 < n) (r : n % 2 = 1) : (n + 1)# = n# := begin have not_prime : ¬nat.prime (n + 1), { intros is_prime, cases (prime.eq_two_or_odd is_prime) with _ n_even, { linarith, }, { apply nat.zero_ne_one, rwa [add_mod, r, nat.one_mod, ←two_mul, mul_one, nat.mod_self] at n_even, }, }, apply finset.prod_congr, { rw [@range_succ (n + 1), filter_insert, if_neg not_prime], }, { exact λ _ _, rfl, }, end lemma dvd_choose_of_middling_prime (p : ℕ) (is_prime : nat.prime p) (m : ℕ) (p_big : m + 1 < p) (p_small : p ≤ 2 * m + 1) : p ∣ choose (2 * m + 1) (m + 1) := begin have m_size : m + 1 ≤ 2 * m + 1 := le_of_lt (lt_of_lt_of_le p_big p_small), have s : ¬(p ∣ (m + 1)!), { intros p_div_fact, have p_le_succ_m : p ≤ m + 1 := (prime.dvd_factorial is_prime).mp p_div_fact, linarith, }, have t : ¬(p ∣ (2 * m + 1 - (m + 1))!), { intros p_div_fact, have p_small : p ≤ 2 * m + 1 - (m + 1) := (prime.dvd_factorial is_prime).mp p_div_fact, linarith, }, have expanded : choose (2 * m + 1) (m + 1) * (m + 1)! * (2 * m + 1 - (m + 1))! = (2 * m + 1)! := @choose_mul_factorial_mul_factorial (2 * m + 1) (m + 1) m_size, have p_div_big_fact : p ∣ (2 * m + 1)! := (prime.dvd_factorial is_prime).mpr p_small, rw [←expanded, mul_assoc] at p_div_big_fact, obtain p_div_choose | p_div_facts : p ∣ choose (2 * m + 1) (m + 1) ∨ p ∣ _! * _! := (prime.dvd_mul is_prime).1 p_div_big_fact, { exact p_div_choose, }, cases (prime.dvd_mul is_prime).1 p_div_facts, cc, cc, end lemma prod_primes_dvd {s : finset ℕ} : ∀ (n : ℕ) (h : ∀ a ∈ s, nat.prime a) (div : ∀ a ∈ s, a ∣ n), (∏ p in s, p) ∣ n := begin apply finset.induction_on s, { simp, }, { intros a s a_not_in_s induct n primes divs, rw finset.prod_insert a_not_in_s, obtain ⟨k, rfl⟩ : a ∣ n := divs a (finset.mem_insert_self a s), apply mul_dvd_mul_left a, apply induct k, { intros b b_in_s, exact primes b (finset.mem_insert_of_mem b_in_s), }, { intros b b_in_s, have b_div_n := divs b (finset.mem_insert_of_mem b_in_s), have a_prime := primes a (finset.mem_insert_self a s), have b_prime := primes b (finset.mem_insert_of_mem b_in_s), refine ((prime.dvd_mul b_prime).mp b_div_n).resolve_left (λ b_div_a, _), obtain rfl : b = a := ((nat.dvd_prime a_prime).1 b_div_a).resolve_left b_prime.ne_one, exact a_not_in_s b_in_s, } }, end lemma primorial_le_4_pow : ∀ (n : ℕ), n# ≤ 4 ^ n | 0 := le_rfl | 1 := le_of_inf_eq rfl | (n + 2) := match nat.mod_two_eq_zero_or_one (n + 1) with | or.inl n_odd := match nat.even_iff.2 n_odd with | ⟨m, twice_m⟩ := let recurse : m + 1 < n + 2 := by linarith in begin calc (n + 2)# = ∏ i in filter nat.prime (range (2 * m + 2)), i : by simpa [←twice_m] ... = ∏ i in filter nat.prime (finset.Ico (m + 2) (2 * m + 2) ∪ range (m + 2)), i : begin rw [range_eq_Ico, finset.union_comm, finset.Ico_union_Ico_eq_Ico], exact bot_le, simp only [add_le_add_iff_right], linarith, end ... = ∏ i in (filter nat.prime (finset.Ico (m + 2) (2 * m + 2)) ∪ (filter nat.prime (range (m + 2)))), i : by rw filter_union ... = (∏ i in filter nat.prime (finset.Ico (m + 2) (2 * m + 2)), i) * (∏ i in filter nat.prime (range (m + 2)), i) : begin apply finset.prod_union, have disj : disjoint (finset.Ico (m + 2) (2 * m + 2)) (range (m + 2)), { simp only [finset.disjoint_left, and_imp, finset.mem_Ico, not_lt, finset.mem_range], intros _ pr _, exact pr, }, exact finset.disjoint_filter_filter disj, end ... ≤ (∏ i in filter nat.prime (finset.Ico (m + 2) (2 * m + 2)), i) * 4 ^ (m + 1) : nat.mul_le_mul_left _ (primorial_le_4_pow (m + 1)) ... ≤ (choose (2 * m + 1) (m + 1)) * 4 ^ (m + 1) : begin have s : ∏ i in filter nat.prime (finset.Ico (m + 2) (2 * m + 2)), i ∣ choose (2 * m + 1) (m + 1), { refine prod_primes_dvd (choose (2 * m + 1) (m + 1)) _ _, { intros a, rw finset.mem_filter, cc, }, { intros a, rw finset.mem_filter, intros pr, rcases pr with ⟨ size, is_prime ⟩, simp only [finset.mem_Ico] at size, rcases size with ⟨ a_big , a_small ⟩, exact dvd_choose_of_middling_prime a is_prime m a_big (nat.lt_succ_iff.mp a_small), }, }, have r : ∏ i in filter nat.prime (finset.Ico (m + 2) (2 * m + 2)), i ≤ choose (2 * m + 1) (m + 1), { refine @nat.le_of_dvd _ _ _ s, exact @choose_pos (2 * m + 1) (m + 1) (by linarith), }, exact nat.mul_le_mul_right _ r, end ... = (choose (2 * m + 1) m) * 4 ^ (m + 1) : by rw choose_symm_half m ... ≤ 4 ^ m * 4 ^ (m + 1) : nat.mul_le_mul_right _ (choose_middle_le_pow m) ... = 4 ^ (2 * m + 1) : by ring_exp ... = 4 ^ (n + 2) : by rw ←twice_m, end end | or.inr n_even := begin obtain one_lt_n | n_le_one : 1 < n + 1 ∨ n + 1 ≤ 1 := lt_or_le 1 (n + 1), { rw primorial_succ (by linarith) n_even, calc (n + 1)# ≤ 4 ^ n.succ : primorial_le_4_pow (n + 1) ... ≤ 4 ^ (n + 2) : pow_le_pow (by norm_num) (nat.le_succ _), }, { have n_zero : n = 0 := eq_bot_iff.2 (succ_le_succ_iff.1 n_le_one), norm_num [n_zero, primorial, range_succ, prod_filter, nat.not_prime_zero, nat.prime_two] }, end end
22c631d6dc9f08a6ab41780dc9cd21308a5d8d03
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/14.Inductive_Definitions/Data_Types/mynat.lean
bd87ec3faa6412703da4b1842c1ff777f819c61f
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
5,823
lean
namespace mynat /- Our own implementation of nat -/ inductive mynat : Type | zero : mynat | succ : mynat → mynat /- Convenient names for first few terms -/ def zero := mynat.zero def one := mynat.succ zero def two := mynat.succ one def three := mynat.succ (mynat.succ (mynat.succ zero)) #reduce one #reduce two #reduce three /- Unary functions -/ -- identity function on mynat def id_mynat (n: mynat) := n -- constant zero function def zero_mynat (n: mynat) := zero -- predecessor function def pred (n : mynat) := match n with | mynat.zero := zero | mynat.succ n' := n' end #reduce pred three #reduce pred zero def pred' (n: mynat) := match n with | mynat.succ n' := n' | _ := zero end example: pred = pred' := rfl /- There are two new and important concepts here. The first is a new kind of matching. The second is that we define the predecessor of zero to be zero. That's a bit odd. Look at the matching. The first pattern is familar. The second, though, it interesting. If we get here, we know n isn't zero, so it must by the successor of the next smaller mynat. Here we give that next smaller value the name n'. And of course that's the number we want to return as precessor! -/ /- Now let's see binary operations and recursive functions. To define a recursive function we have a new syntax/ -/ def add_mynat: mynat → mynat → mynat | mynat.zero m := m | (mynat.succ n') m := mynat.succ (add_mynat n' m) #reduce add_mynat three two /- Syntax notes: use explicit function type syntax. Omit any :=. Define how the function works by cases. Each case defines what the function does for the specific kinds of arguments used in the case. Omit commas between arguments All cases may be covered -/ -- It works! #reduce add_mynat one two #reduce add_mynat three three /- EXERCISES: (1) We just implemented addition as the recursive (iterated) application of the successor function. Now you are to implement multiplication as iterated addition. (2) Implement exponentiation as iterated multiplication. (3) Take this pattern one step further. What function did you implement? How would you write it in regular math notation? -/ def mul_mynat: mynat → mynat → mynat | mynat.zero m := zero | (mynat.succ n') m := add_mynat m (mul_mynat n' m) #reduce mul_mynat three three def exp_mynat : mynat → mynat → mynat | n mynat.zero := one | n (mynat.succ m') := mul_mynat n (exp_mynat n m') #reduce exp_mynat three three #reduce exp_mynat two three --#reduce mul_mynat three two --#reduce mul_mynat three three /- We can easily prove that for all m : ℕ, add_mynat 0 m = m, because the definition of add_mynat has a matching pattern (the first one), which explains exactly how to reduce a term with first argument zero. -/ theorem zero_left_id: ∀ m : mynat, add_mynat mynat.zero m = m := begin intro m, --apply rfl, simp [add_mynat], end /- We just asked Lean to simplify the goal using the "simplication rules" specified by the two cases in the definition of add_mynat. The result is m = m, which Lean takes care of with an automated application of rfl. -/ /- Unfortunately, we don't have such a simplification rule when the zero is on the right! For that we need a whole new proof strategy: proof by induction. -/ theorem zero_right_id : ∀ m : mynat, add_mynat m mynat.zero = m := begin intro m, /- cases m, apply rfl, -/ induction m with m' h, -- base case apply rfl, --simp [add_mynat], -- inductive case simp [add_mynat], assumption, end lemma add_n_succ_m : ∀ n m : mynat, add_mynat n (mynat.succ m) = mynat.succ (add_mynat n m) := begin intros n m, induction n with n' h, apply rfl, simp [add_mynat], assumption, end /- Property verification: our addition operation is commutative! -/ example : ∀ m n : mynat, add_mynat m n = add_mynat n m := begin intros m n, -- by induction on m induction m with m' h, --base case: m = zero simp [add_mynat], rw zero_right_id, -- inductive case: -- if true for m then true for succ m simp [add_mynat], rw add_n_succ_m, -- rewrite using induction hypothesis! rw h, end /- Proof by induction is proof by case analysis on the *constructors* for values of a given type, with the huge added benefit of an induction hypothesis. So, as an example, if we show that some predicate involving a natural number, n, is true no matter what *constructor* was used to "build" n, then we've' shown the predicate to be true for *all* (∀) values of n, because there are no n other than those that can be built by the given constructors. Proving a proposition is true for all constructors is thus tantamount to showing that it is true for all values, even if there are infinitely many. Let's think about the two constructors for values of type mynat. First, there is the zero constructor. That's the "base case". Second, there's the succ constructor. From a value, n, it constructs a value, succ n. Now if we prove the following two cases, we're done: (1) the predicate in question is true when n is zero (2) if the predicate is true for any n, then it is true for succ n. The reason we're done is that there are no other possibilities for n. The set of values of an inductively defined type is defined to be exactly the set of values that can be built by using the available constructors any *finite* number of times, and that there are no other values of the given type. -/ /- EXERCISE: try this proof using cases instead of induction. Cases also does case analysis on the constructors. Why does simple case analysis fail? -/ /- EXERCISES: To Come Shortly -/ end mynat
e806d8cbdb354d4cf061572313867ac640df0aad
07f5f86b00fed90a419ccda4298d8b795a68f657
/library/data/rbtree/find.lean
95444205d5ba9394499c544451aaaad0bf871463
[ "Apache-2.0" ]
permissive
VBaratham/lean
8ec5c3167b4835cfbcd7f25e2173d61ad9416b3a
450ca5834c1c35318e4b47d553bb9820c1b3eee7
refs/heads/master
1,629,649,471,814
1,512,060,373,000
1,512,060,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,226
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.rbtree.basic universe u /- TODO(Leo): remove after we cleanup stdlib simp lemmas -/ local attribute [-simp] or.comm or.left_comm or.assoc and.comm and.left_comm and.assoc namespace rbnode variables {α : Type u} @[elab_simple] lemma find.induction {p : rbnode α → Prop} (lt) [decidable_rel lt] (t x) (h₁ : p leaf) (h₂ : ∀ l y r (h : cmp_using lt x y = ordering.lt) (ih : p l), p (red_node l y r)) (h₃ : ∀ l y r (h : cmp_using lt x y = ordering.eq), p (red_node l y r)) (h₄ : ∀ l y r (h : cmp_using lt x y = ordering.gt) (ih : p r), p (red_node l y r)) (h₅ : ∀ l y r (h : cmp_using lt x y = ordering.lt) (ih : p l), p (black_node l y r)) (h₆ : ∀ l y r (h : cmp_using lt x y = ordering.eq), p (black_node l y r)) (h₇ : ∀ l y r (h : cmp_using lt x y = ordering.gt) (ih : p r), p (black_node l y r)) : p t := begin induction t, case leaf {assumption}, case red_node l y r { generalize h : cmp_using lt x y = c, cases c, case ordering.lt { apply h₂, assumption, assumption }, case ordering.eq { apply h₃, assumption }, case ordering.gt { apply h₄, assumption, assumption }, }, case black_node l y r { generalize h : cmp_using lt x y = c, cases c, case ordering.lt { apply h₅, assumption, assumption }, case ordering.eq { apply h₆, assumption }, case ordering.gt { apply h₇, assumption, assumption }, } end lemma find_correct {t : rbnode α} {lt x} [decidable_rel lt] [is_strict_weak_order α lt] : ∀ {lo hi} (hs : is_searchable lt t lo hi), mem lt x t ↔ ∃ y, find lt t x = some y ∧ x ≈[lt] y := begin apply find.induction lt t x; intros; simp only [mem, find, *], { simp, intro h, cases h with _ h, cases h, contradiction }, twice { -- red and black cases are identical { cases hs, apply iff.intro, { intro hm, blast_disjs, { exact iff.mp (ih hs₁) hm }, { simp at h, cases hm, contradiction }, { have hyx : lift lt (some y) (some x) := (range hs₂ hm).1, simp [lift] at hyx, have hxy : lt x y, { simp [cmp_using] at h, assumption }, exact absurd (trans_of lt hxy hyx) (irrefl_of lt x) } }, { intro hc, left, exact iff.mpr (ih hs₁) hc }, }, { simp at h, simp [h, strict_weak_order.equiv], existsi y, split, refl, assumption }, { cases hs, apply iff.intro, { intro hm, blast_disjs, { have hxy : lift lt (some x) (some y) := (range hs₁ hm).2, simp [lift] at hxy, have hyx : lt y x, { simp [cmp_using] at h, exact h.2 }, exact absurd (trans_of lt hxy hyx) (irrefl_of lt x) }, { simp at h, cases hm, contradiction }, { exact iff.mp (ih hs₂) hm } }, { intro hc, right, right, exact iff.mpr (ih hs₂) hc }, } } end lemma mem_of_mem_exact {lt} [is_irrefl α lt] {x t} : mem_exact x t → mem lt x t := begin induction t; simp [mem_exact, mem]; intro h, all_goals { blast_disjs, simp [ih_1 h], simp [h, irrefl_of lt val], simp [ih_2 h] } end lemma find_correct_exact {t : rbnode α} {lt x} [decidable_rel lt] [is_strict_weak_order α lt] : ∀ {lo hi} (hs : is_searchable lt t lo hi), mem_exact x t ↔ find lt t x = some x := begin apply find.induction lt t x; intros; simp only [mem_exact, find, *], { simp, intro h, contradiction }, twice { { cases hs, apply iff.intro, { intro hm, blast_disjs, { exact iff.mp (ih hs₁) hm }, { simp at h, subst x, exact absurd h (irrefl y) }, { have hyx : lift lt (some y) (some x) := (range hs₂ (mem_of_mem_exact hm)).1, simp [lift] at hyx, have hxy : lt x y, { simp [cmp_using] at h, assumption }, exact absurd (trans_of lt hxy hyx) (irrefl_of lt x) } }, { intro hc, left, exact iff.mpr (ih hs₁) hc }, }, { simp at h, cases hs, apply iff.intro, { intro hm, blast_disjs, { have hxy : lift lt (some x) (some y) := (range hs₁ (mem_of_mem_exact hm)).2, simp [lift] at hxy, exact absurd hxy h.1 }, { subst hm }, { have hyx : lift lt (some y) (some x) := (range hs₂ (mem_of_mem_exact hm)).1, simp [lift] at hyx, exact absurd hyx h.2 } }, { intro hm, injection hm, simp [*] } }, { cases hs, apply iff.intro, { intro hm, blast_disjs, { have hxy : lift lt (some x) (some y) := (range hs₁ (mem_of_mem_exact hm)).2, simp [lift] at hxy, have hyx : lt y x, { simp [cmp_using] at h, exact h.2 }, exact absurd (trans_of lt hxy hyx) (irrefl_of lt x) }, { simp at h, subst x, exact absurd h (irrefl y) }, { exact iff.mp (ih hs₂) hm } }, { intro hc, right, right, exact iff.mpr (ih hs₂) hc } } } end lemma eqv_of_find_some {t : rbnode α} {lt x y} [decidable_rel lt] [is_strict_weak_order α lt] : ∀ {lo hi} (hs : is_searchable lt t lo hi) (he : find lt t x = some y), x ≈[lt] y := begin apply find.induction lt t x; intros; simp only [mem, find, *] at *, { contradiction }, twice { { cases hs, exact ih hs₁ rfl }, { injection he, subst y, simp at h, exact h }, { cases hs, exact ih hs₂ rfl } } end lemma find_eq_find_of_eqv {lt a b} [decidable_rel lt] [is_strict_weak_order α lt] {t : rbnode α} : ∀ {lo hi} (hs : is_searchable lt t lo hi) (heqv : a ≈[lt] b), find lt t a = find lt t b := begin apply find.induction lt t a; intros; simp [mem, find, strict_weak_order.equiv, *] at *, twice { { have : lt b y := lt_of_incomp_of_lt heqv.swap h, simp [cmp_using, find, *], cases hs, apply ih hs₁ }, { have := incomp_trans_of lt heqv.swap h, simp [cmp_using, find, *] }, { have := lt_of_lt_of_incomp h heqv, have := not_lt_of_lt this, simp [cmp_using, find, *], cases hs, apply ih hs₂ } } end end rbnode
c1a379443fce491585b73bf4127abc1d1462b26a
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/Tactic/Cases.lean
860332baddd53742b0076da8d10adb95676aa0d5
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
16,234
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Subst namespace Lean.Meta private def throwInductiveTypeExpected {α} (type : Expr) : MetaM α := do throwError "failed to compile pattern matching, inductive type expected{indentExpr type}" def getInductiveUniverseAndParams (type : Expr) : MetaM (List Level × Array Expr) := do let type ← whnfD type matchConstInduct type.getAppFn (fun _ => throwInductiveTypeExpected type) fun val us => let I := type.getAppFn let Iargs := type.getAppArgs let params := Iargs.extract 0 val.numParams pure (us, params) private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do let lhsType ← inferType lhs let rhsType ← inferType rhs let u ← getLevel lhsType if (← isDefEq lhsType rhsType) then pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs) else pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs) private partial def withNewEqs {α} (targets targetsNew : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := let rec loop (i : Nat) (newEqs : Array Expr) (newRefls : Array Expr) := do if h : i < targets.size then let (newEqType, newRefl) ← mkEqAndProof targets[i] targetsNew[i] withLocalDeclD `h newEqType fun newEq => do loop (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls loop 0 #[] #[] def generalizeTargets (mvarId : MVarId) (motiveType : Expr) (targets : Array Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `generalizeTargets let (typeNew, eqRefls) ← forallTelescopeReducing motiveType fun targetsNew _ => do unless targetsNew.size == targets.size do throwError "invalid number of targets #{targets.size}, motive expects #{targetsNew.size}" withNewEqs targets targetsNew fun eqs eqRefls => do let type ← getMVarType mvarId let typeNew ← mkForallFVars eqs type let typeNew ← mkForallFVars targetsNew typeNew pure (typeNew, eqRefls) let mvarNew ← mkFreshExprSyntheticOpaqueMVar typeNew (← getMVarTag mvarId) assignExprMVar mvarId (mkAppN (mkAppN mvarNew targets) eqRefls) pure mvarNew.mvarId! structure GeneralizeIndicesSubgoal where mvarId : MVarId indicesFVarIds : Array FVarId fvarId : FVarId numEqs : Nat /-- Similar to `generalizeTargets` but customized for the `casesOn` motive. Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := withMVarContext mvarId do let lctx ← getLCtx let localInsts ← getLocalInstances checkNotAssigned mvarId `generalizeIndices let fvarDecl ← getLocalDecl fvarId let type ← whnf fvarDecl.type type.withApp fun f args => matchConstInduct f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") fun val _ => do unless val.numIndices > 0 do throwTacticEx `generalizeIndices mvarId "indexed inductive type expected" unless args.size == val.numIndices + val.numParams do throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype" let indices := args.extract (args.size - val.numIndices) args.size let IA := mkAppN f (args.extract 0 val.numParams) -- `I A` let IAType ← inferType IA forallTelescopeReducing IAType fun newIndices _ => do let newType := mkAppN IA newIndices withLocalDeclD fvarDecl.userName newType fun h' => withNewEqs indices newIndices fun newEqs newRefls => do let (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h' let newRefls := newRefls.push newRefl withLocalDeclD `h newEqType fun newEq => do let newEqs := newEqs.push newEq /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ let target ← getMVarType mvarId let tag ← getMVarTag mvarId let auxType ← mkForallFVars newEqs target let auxType ← mkForallFVars #[h'] auxType let auxType ← mkForallFVars newIndices auxType let newMVar ← mkFreshExprMVarAt lctx localInsts auxType MetavarKind.syntheticOpaque tag /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls) let (indicesFVarIds, newMVarId) ← introNP newMVar.mvarId! newIndices.size let (fvarId, newMVarId) ← intro1P newMVarId pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } structure CasesSubgoal extends InductionSubgoal where ctorName : Name namespace Cases structure Context where inductiveVal : InductiveVal casesOnVal : DefinitionVal nminors : Nat := inductiveVal.ctors.length majorDecl : LocalDecl majorTypeFn : Expr majorTypeArgs : Array Expr majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.numIndices) majorTypeArgs.size private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do let env ← getEnv if !env.contains `Eq || !env.contains `HEq then pure none else let majorDecl ← getLocalDecl majorFVarId let majorType ← whnf majorDecl.type majorType.withApp fun f args => matchConstInduct f (fun _ => pure none) fun ival _ => if args.size != ival.numIndices + ival.numParams then pure none else match env.find? (Name.mkStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := do if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any fun i => i.any fun j => ctx.majorTypeIndices[i] == ctx.majorTypeIndices[j] then /- An index ocurrs more than once -/ pure false else let lctx ← getLCtx let mctx ← getMCtx pure $ lctx.all fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := let indicesFVarIds := s₁.indicesFVarIds s₂.mapM fun s => do indicesFVarIds.foldlM (init := s) fun s indexFVarId => match s.subst.get indexFVarId with | Expr.fvar indexFVarId' _ => (do let mvarId ← clear s.mvarId indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId }) <|> (pure s) | _ => pure s /- Convert `s` into an array of `CasesSubgoal`, by attaching the corresponding constructor name, and adding the substitution `majorFVarId -> ctor_i us params fields` into each subgoal. -/ private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) (majorFVarId : FVarId) (us : List Level) (params : Array Expr) : Array CasesSubgoal := s.mapIdx fun i s => let ctorName := ctorNames[i] let ctorApp := mkAppN (mkAppN (mkConst ctorName us) params) s.fields let s := { s with subst := s.subst.insert majorFVarId ctorApp } { ctorName := ctorName, toInductionSubgoal := s } /- Convert heterogeneous equality into a homegeneous one -/ private def heqToEq (mvarId : MVarId) (eqDecl : LocalDecl) : MetaM MVarId := do /- Convert heterogeneous equality into a homegeneous one -/ let prf ← mkEqOfHEq (mkFVar eqDecl.fvarId) let aEqb ← whnf (← inferType prf) let mvarId ← assert mvarId eqDecl.userName aEqb prf clear mvarId eqDecl.fvarId partial def unifyEqs (numEqs : Nat) (mvarId : MVarId) (subst : FVarSubst) (caseName? : Option Name := none): MetaM (Option (MVarId × FVarSubst)) := do if numEqs == 0 then pure (some (mvarId, subst)) else let (eqFVarId, mvarId) ← intro1 mvarId withMVarContext mvarId do let eqDecl ← getLocalDecl eqFVarId if eqDecl.type.isHEq then let mvarId ← heqToEq mvarId eqDecl unifyEqs numEqs mvarId subst caseName? else match eqDecl.type.eq? with | none => throwError "equality expected{indentExpr eqDecl.type}" | some (α, a, b) => /- Remark: we do not check `isDefeq` here because we would fail to substitute equalities such as `x = t` and `t = x` when `x` and `t` are proofs (proof irrelanvance). -/ /- Remark: we use `let rec` here because otherwise the compiler would generate an insane amount of code. We can remove the `rec` after we fix the eagerly inlining issue in the compiler. -/ let rec substEq (symm : Bool) := do /- TODO: support for acyclicity (e.g., `xs ≠ x :: xs`) -/ /- Remark: `substCore` fails if the equation is of the form `x = x` -/ if let some (substNew, mvarId) ← observing? (substCore mvarId eqFVarId symm subst) then unifyEqs (numEqs - 1) mvarId substNew caseName? else if (← isDefEq a b) then /- Skip equality -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst caseName? else throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}" let rec injection (a b : Expr) := do let env ← getEnv if a.isConstructorApp env && b.isConstructorApp env then /- ctor_i ... = ctor_j ... -/ match (← injectionCore mvarId eqFVarId) with | InjectionResultCore.solved => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqsNew => unifyEqs (numEqs - 1 + numEqsNew) mvarId subst caseName? else let a' ← whnf a let b' ← whnf b if a' != a || b' != b then /- Reduced lhs/rhs of current equality -/ let prf := mkFVar eqFVarId let aEqb' ← mkEq a' b' let mvarId ← assert mvarId eqDecl.userName aEqb' prf let mvarId ← clear mvarId eqFVarId unifyEqs numEqs mvarId subst caseName? else match caseName? with | none => throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}" | some caseName => throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}\nat case {mkConst caseName}" let a ← instantiateMVars a let b ← instantiateMVars b match a, b with | Expr.fvar aFVarId _, Expr.fvar bFVarId _ => /- x = y -/ let aDecl ← getLocalDecl aFVarId let bDecl ← getLocalDecl bFVarId substEq (aDecl.index < bDecl.index) | Expr.fvar .., _ => /- x = t -/ substEq (symm := false) | _, Expr.fvar .. => /- t = x -/ substEq (symm := true) | a, b => if (← isDefEq a b) then /- Skip equality -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst caseName? else injection a b private def unifyCasesEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (init := #[]) fun subgoals s => do match (← unifyEqs numEqs s.mvarId s.subst s.ctorName) with | none => pure subgoals | some (mvarId, subst) => pure $ subgoals.push { s with mvarId := mvarId, subst := subst, fields := s.fields.map (subst.apply ·) } private def inductionCasesOn (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames) (ctx : Context) : MetaM (Array CasesSubgoal) := do withMVarContext mvarId do let majorType ← inferType (mkFVar majorFVarId) let (us, params) ← getInductiveUniverseAndParams majorType let casesOn := mkCasesOnName ctx.inductiveVal.name let ctors := ctx.inductiveVal.ctors.toArray let s ← induction mvarId majorFVarId casesOn givenNames return toCasesSubgoals s ctors majorFVarId us params def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := withMVarContext mvarId do checkNotAssigned mvarId `cases let context? ← mkCasesContext? majorFVarId match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => /- Remark: if caller does not need a `FVarSubst` (variable substitution), and `hasIndepIndices ctx` is true, then we can also use the simple case. This is a minor optimization, and we currently do not even allow callers to specify whether they want the `FVarSubst` or not. -/ if ctx.inductiveVal.numIndices == 0 then -- Simple case inductionCasesOn mvarId majorFVarId givenNames ctx else let s₁ ← generalizeIndices mvarId majorFVarId trace[Meta.Tactic.cases] "after generalizeIndices\n{MessageData.ofGoal s₁.mvarId}" let s₂ ← inductionCasesOn s₁.mvarId s₁.fvarId givenNames ctx let s₂ ← elimAuxIndices s₁ s₂ unifyCasesEqs s₁.numEqs s₂ end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames def casesRec (mvarId : MVarId) (p : LocalDecl → MetaM Bool) : MetaM (List MVarId) := saturate mvarId fun mvarId => withMVarContext mvarId do for localDecl in (← getLCtx) do if (← p localDecl) then let r? ← observing? do let r ← cases mvarId localDecl.fvarId return r.toList.map (·.mvarId) if r?.isSome then return r? return none def casesAnd (mvarId : MVarId) : MetaM MVarId := do let mvarIds ← casesRec mvarId fun localDecl => return (← instantiateMVars localDecl.type).isAppOfArity ``And 2 exactlyOne mvarIds def substEqs (mvarId : MVarId) : MetaM MVarId := do let mvarIds ← casesRec mvarId fun localDecl => do let type ← instantiateMVars localDecl.type return type.isEq || type.isHEq exactlyOne mvarIds builtin_initialize registerTraceClass `Meta.Tactic.cases end Lean.Meta
ef083011e99c8608e668d35a67deacec3340fc91
8cd4726d66eec7673bcc0325fed07d5ba5bf17c4
/hw3b.lean
4679cbdbbd66cdcfdcce8275613008303c397ead
[]
no_license
justinqcai/CS2102
8c5fddedffa6147fedd4b6ee7d5d39fc21f0ddab
d309f0db3f1df52eb77206ee1e8665a3b49d7a0c
refs/heads/master
1,590,108,991,894
1,557,610,044,000
1,557,610,044,000
186,064,169
0
0
null
null
null
null
UTF-8
Lean
false
false
2,654
lean
/- Justin Cai, jc5pz CS 2102 Spring 2019 Homework #3b The first part of your homework this week is to make a new copy of the *blank* homework #2 assignment in your "work" directory, now called "hw3a.lean", then complete the questions that you did *not* complete last week. To rename the file after copying it, click on the file name, hit enter, then enter a new name for the file. This file contains the second half of the homework for this week, which everyone in CS2102 is to complete. The purpose of this part of the homework assignment for this week is to help you learn how to write propositions of various kinds in formal predicate logic. -/ /- To this end, you are to translate the informally stated propositions we give you into formal and mechanically checked propositions using Lean. To prepare to do this work, we strong recommend that you reread the very recently updated version of Chapter 2.5 in the notes, on Propositions. So here we go. -/ /- #1. 10 points To start, write the Lean code using the axiom keyword needed to introduce the assumptions that "ItsRaining" and "TheStreetsAreWet" are propositions. Write your answer just below this comment block and before the next one. -/ axioms ItsRaining TheStreetsAreWet : Prop -- Your answer here /- #2. 90 points Now, write formal (using Lean) versions of each of the following informally stated propositions. Do this by writing your expressions in place of the underscore characters in the following incomplete definitions. -/ /- If it's raining, then the streets are wet. -/ def p1 : Prop := ItsRaining → TheStreetsAreWet /- It's raining and the streets are wet. -/ def p2 : Prop := ItsRaining ∧ TheStreetsAreWet /- It's not raining. -/ def p3 : Prop := ¬ ItsRaining /- It's raining or the streets are wet. -/ def p4 : Prop := ItsRaining ∨ TheStreetsAreWet /- It's raining if and only if the streets are wet. -/ def p5 : Prop := ItsRaining ↔ TheStreetsAreWet /- It's raining or the streets are not wet. -/ def p6 : Prop := ItsRaining ∨ ¬ TheStreetsAreWet /- If it's raining then (if the streets are wet then it's raining). -/ def p7 : Prop := ItsRaining → (TheStreetsAreWet → ItsRaining) /- If (if it's raining then the streets are wet) then it's raining. -/ def p8 : Prop := (ItsRaining → TheStreetsAreWet) → ItsRaining /- If the streets are wet and it's raining then the streets are wet. -/ def p9 : Prop := TheStreetsAreWet ∧ ItsRaining → TheStreetsAreWet /- The streets are wet and the streets are not wet implies a contradiction (false). -/ def p10 : Prop := (TheStreetsAreWet ∧ ¬ TheStreetsAreWet) → ff
554d3c2b21273f65805dda2ce801f3d1310ed1dd
cbb817439c51008d66b37ce6b1964fea61434d35
/theorem-proving-in-lean/src/chap_2.lean
a09b3e5f2692f748e258a09ab0940378aa5da97d
[]
no_license
tomhoule/theorem-proving-in-lean-exercises
a07f99d4f6b41ce003e8a0274c7bc46359fa62b2
60ccc71b8a6df6924e7cc90aab713b804f78da9f
refs/heads/master
1,663,582,321,828
1,590,352,467,000
1,590,352,476,000
257,107,936
3
0
null
null
null
null
UTF-8
Lean
false
false
1,106
lean
def Do_Twice : ((ℕ → ℕ) → (ℕ → ℕ)) → (ℕ → ℕ) → (ℕ → ℕ) := λ doubler, λ original, doubler $ doubler original -- Exercise 1 def do_twice (f : ℕ → ℕ) (x : ℕ) : ℕ := f (f x) def double (n : ℕ) : ℕ := n * 2 -- test def doubling_two_twice : ℕ := do_twice double 2 #reduce doubling_two_twice #reduce Do_Twice do_twice double 2 -- Exercise 2 def curry (α β γ : Type) (f : α × β → γ) : α → β → γ := λ (a: α), λ (b: β), f (a, b) def uncurry (α β γ : Type) (f : α → β → γ) : α × β → γ := λ (pair : (α × β)), f pair.1 pair.2 #check curry #check uncurry -- Exercise 3 namespace vecadd universe u constant vec : Type u -> ℕ -> Type u constant vec_add : Π { len : ℕ }, vec ℕ len -> vec ℕ len -> vec ℕ len #check vec_add constant vec_reverse : Π { α : Type } { len: ℕ }, vec α len -> vec α len #check vec_reverse #check let add_vecs_then_reverse := λ (len : nat) (v1 : vec _ len) v2, vec_reverse (vec_add v1 v2) in add_vecs_then_reverse end vecadd -- Exercise 4
2fc8e78249cd3e2a9ce36d30fc3f3d7eda4380ec
6dafe3cbeb81b4a792fbf679e64eccb29225af1c
/equiv_relns_partitions.lean
63c229fc89214a192cc5b451782d8eadcd93668a
[]
no_license
Shiney/xena
9bdf22f0036baa7b22753e1e0b8101ca367551b6
8ff8f04d79b29a7a33bfefa318fd552388d0b989
refs/heads/master
1,623,652,579,961
1,586,444,931,000
1,586,444,931,000
254,480,076
0
0
null
1,586,466,973,000
1,586,466,973,000
null
UTF-8
Lean
false
false
4,344
lean
import data.equiv.basic structure partition (X : Type) := (C : set (set X)) (Hnonempty : ∀ c ∈ C, c ≠ ∅) (Hcover : ∀ x, ∃ c ∈ C, x ∈ c) (Hunique : ∀ c d ∈ C, c ∩ d ≠ ∅ → c = d) def partition.ext {X : Type} (P Q : partition X) (H : P.C = Q.C) : P = Q := begin cases P, cases Q, rwa partition.mk.inj_eq, end def equivalence_class {X : Type} (R : X → X → Prop) (x : X) := {y : X | R x y} lemma mem_class {X : Type} {R : X → X → Prop} (HR : equivalence R) (x : X) : x ∈ equivalence_class R x := begin cases HR with HRR HR, exact HRR x, end example (X : Type) : {R : X → X → Prop // equivalence R} ≃ partition X := { to_fun := λ R, { C := { S : set X | ∃ x : X, S = equivalence_class R x}, Hnonempty := begin intro c, intro hc, cases hc with x hx, rw set.ne_empty_iff_exists_mem, use x, rw hx, exact mem_class R.2 x, end, Hcover := begin intro x, use equivalence_class R x, existsi _, { exact mem_class R.2 x }, use x, end, Hunique := begin intros c d hc hd hcd, rw set.ne_empty_iff_exists_mem at hcd, cases hcd with x hx, cases hc with a ha, cases hd with b hb, cases R with R HR, cases hx with hxc hxd, rw ha at *, rw hb at *, change R a x at hxc, change R b x at hxd, rcases HR with ⟨HRR, HRS, HRT⟩, apply set.subset.antisymm, { intros y hy, change R a y at hy, change R b y, refine HRT hxd _, refine HRT _ hy, apply HRS, assumption }, { intros y hy, change R a y, change R b y at hy, refine HRT hxc _, refine HRT _ hy, apply HRS, assumption, } end }, inv_fun := λ P, ⟨λ x y, ∃ c ∈ P.C, x ∈ c ∧ y ∈ c, begin split, { intro x, cases P.Hcover x with c hc, cases hc with hc hxc, use c, use hc, split; assumption, }, split, { intros x y hxy, cases hxy with c hc, cases hc with hc1 hc2, use c, use hc1, cases hc2 with hx hy, split; assumption }, { rintros x y z ⟨c, hc, hxc, hyc⟩ ⟨d, hd, hyd, hzd⟩, use c, use hc, split, exact hxc, have hcd : c = d, { apply P.Hunique c d, use hc, use hd, rw set.ne_empty_iff_exists_mem, use y, split, use hyc, use hyd, }, rw hcd, use hzd, } end⟩, left_inv := begin rintro ⟨R, HRR, HRS, HRT⟩, dsimp, -- not taught in NNG rw subtype.ext, -- not taught in NNG dsimp, -- not taught in NNG ext x y, -- not taught in NNG split, { rintro ⟨c, ⟨z, rfl⟩, ⟨hx, hy⟩⟩, refine HRT _ hy, apply HRS, exact hx, }, { intro H, use equivalence_class R x, use x, split, exact HRR x, exact H, } end, right_inv := begin intro P, dsimp, cases P with C _ _ _, dsimp, apply partition.ext, dsimp, -- dsimps everywhere ext c, split, { intro h, dsimp at h, cases h with x hx, rw hx, clear hx, rcases P_Hcover x with ⟨d, hd, hxd⟩, convert hd, -- not taught in NNG clear c, ext y, split, { intro hy, unfold equivalence_class at hy, dsimp at hy, rcases hy with ⟨e, he, hxe, hye⟩, convert hye, -- not taught refine P_Hunique d e hd he _, rw set.ne_empty_iff_exists_mem, use x, split;assumption }, { intro hyd, unfold equivalence_class, dsimp, use d, use hd, split;assumption }, }, { intro hc, dsimp, have h := P_Hnonempty c hc, rw set.ne_empty_iff_exists_mem at h, cases h with x hxc, use x, unfold equivalence_class, ext y, split, { intro hyc, dsimp, use c, use hc, split;assumption, }, { intro h, dsimp at h, rcases h with ⟨d, hd, hxd, hyd⟩, convert hyd, apply P_Hunique c d hc hd, rw set.ne_empty_iff_exists_mem, use x, split;assumption } } end }
6845aac84a6201a6f32654327b523bf11acdaba0
439bc6c3e74a118aa51df633b8e1f24415804d86
/yoneda.lean
91f11b7726240dc747a9356b0dec82c0ada8029d
[]
no_license
jcommelin/lt2019_slides
4ca498db02b5187c5778c21b985126d52d260696
3234cd92920d3d4321cc2cef78b48e5fa55be413
refs/heads/master
1,586,718,101,957
1,546,930,855,000
1,546,930,855,000
162,697,592
1
0
null
null
null
null
UTF-8
Lean
false
false
463
lean
variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def yoneda : C ⥤ ((Cᵒᵖ) ⥤ (Type v₁)) := { obj := λ X, { obj := λ Y : C, Y ⟶ X, map := λ Y Y' f g, f ≫ g, map_comp' := begin intros X_1 Y Z f g, ext1, dsimp at *, erw [category.assoc] end, map_id' := begin intros X_1, ext1, dsimp at *, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } }
6e9d5cc0d6868ee4454c6433fc6d140bfeb36e47
32da3d0f92cab08875472ef6cacc1931c2b3eafa
/src/measure_theory/pi.lean
a21472892ca8e66042dc4086e1a494f2539d1691
[ "Apache-2.0" ]
permissive
karthiknadig/mathlib
b6073c3748860bfc9a3e55da86afcddba62dc913
33a86cfff12d7f200d0010cd03b95e9b69a6c1a5
refs/heads/master
1,676,389,371,851
1,610,061,127,000
1,610,061,127,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,432
lean
/- Copyright (c) 2020 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.prod /-! # Product measures In this file we define and prove properties about finite products of measures (and at some point, countable products of measures). ## Main definition * `measure_theory.measure.pi`: The product of finitely many σ-finite measures. Given `μ : Π i : ι, measure (α i)` for `[fintype ι]` it has type `measure (Π i : ι, α i)`. ## Implementation Notes We define `measure_theory.outer_measure.pi`, the product of finitely many outer measures, as the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{ s i | i : ι }`. We then show that this induces a product of measures, called `measure_theory.measure.pi`. For a collection of σ-finite measures `μ` and a collection of measurable sets `s` we show that `measure.pi μ (pi univ s) = ∏ i, m i (s i)`. To do this, we follow the following steps: * We know that there is some ordering on `ι`, given by an element of `[encodable ι]`. * Using this, we have an equivalence `measurable_equiv.pi_measurable_equiv_tprod` between `Π ι, α i` and an iterated product of `α i`, called `list.tprod α l` for some list `l`. * On this iterated product we can easily define a product measure `measure_theory.measure.tprod` by iterating `measure_theory.measure.prod` * Using the previous two steps we construct `measure_theory.measure.pi'` on `Π ι, α i` for encodable `ι`. * We know that `measure_theory.measure.pi'` sends products of sets to products of measures, and since `measure_theory.measure.pi` is the maximal such measure (or at least, it comes from an outer measure which is the maximal such outer measure), we get the same rule for `measure_theory.measure.pi`. ## Tags finitary product measure -/ noncomputable theory open function set measure_theory.outer_measure open_locale classical big_operators topological_space namespace measure_theory variables {ι : Type*} [fintype ι] {α : ι → Type*} {m : Π i, outer_measure (α i)} /-- An upper bound for the measure in a finite product space. It is defined to by taking the image of the set under all projections, and taking the product of the measures of these images. For measurable boxes it is equal to the correct measure. -/ @[simp] def pi_premeasure (m : Π i, outer_measure (α i)) (s : set (Π i, α i)) : ennreal := ∏ i, m i (eval i '' s) lemma pi_premeasure_pi {s : Π i, set (α i)} (hs : (pi univ s).nonempty) : pi_premeasure m (pi univ s) = ∏ i, m i (s i) := by simp [hs] lemma pi_premeasure_pi' [nonempty ι] {s : Π i, set (α i)} : pi_premeasure m (pi univ s) = ∏ i, m i (s i) := begin cases (pi univ s).eq_empty_or_nonempty with h h, { rcases univ_pi_eq_empty_iff.mp h with ⟨i, hi⟩, have : ∃ i, m i (s i) = 0 := ⟨i, by simp [hi]⟩, simpa [h, finset.card_univ, zero_pow (fintype.card_pos_iff.mpr _inst_2), @eq_comm _ (0 : ennreal), finset.prod_eq_zero_iff] }, { simp [h] } end lemma pi_premeasure_pi_mono {s t : set (Π i, α i)} (h : s ⊆ t) : pi_premeasure m s ≤ pi_premeasure m t := finset.prod_le_prod' (λ i _, (m i).mono' (image_subset _ h)) lemma pi_premeasure_pi_eval [nonempty ι] {s : set (Π i, α i)} : pi_premeasure m (pi univ (λ i, eval i '' s)) = pi_premeasure m s := by simp [pi_premeasure_pi'] namespace outer_measure /-- `outer_measure.pi m` is the finite product of the outer measures `{m i | i : ι}`. It is defined to be the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{ s i | i : ι }`. -/ protected def pi (m : Π i, outer_measure (α i)) : outer_measure (Π i, α i) := bounded_by (pi_premeasure m) lemma pi_pi_le (m : Π i, outer_measure (α i)) (s : Π i, set (α i)) : outer_measure.pi m (pi univ s) ≤ ∏ i, m i (s i) := by { cases (pi univ s).eq_empty_or_nonempty with h h, simp [h], exact (bounded_by_le _).trans_eq (pi_premeasure_pi h) } lemma le_pi {m : Π i, outer_measure (α i)} {n : outer_measure (Π i, α i)} : n ≤ outer_measure.pi m ↔ ∀ (s : Π i, set (α i)), (pi univ s).nonempty → n (pi univ s) ≤ ∏ i, m i (s i) := begin rw [outer_measure.pi, le_bounded_by'], split, { intros h s hs, refine (h _ hs).trans_eq (pi_premeasure_pi hs) }, { intros h s hs, refine le_trans (n.mono $ subset_pi_eval_image univ s) (h _ _), simp [univ_pi_nonempty_iff, hs] } end end outer_measure namespace measure variables [Π i, measurable_space (α i)] (μ : Π i, measure (α i)) section tprod open list variables {δ : Type*} {π : δ → Type*} [∀ x, measurable_space (π x)] /-- A product of measures in `tprod α l`. -/ -- for some reason the equation compiler doesn't like this definition protected def tprod (l : list δ) (μ : Π i, measure (π i)) : measure (tprod π l) := by { induction l with i l ih, exact dirac punit.star, exact (μ i).prod ih } @[simp] lemma tprod_nil (μ : Π i, measure (π i)) : measure.tprod [] μ = dirac punit.star := rfl @[simp] lemma tprod_cons (i : δ) (l : list δ) (μ : Π i, measure (π i)) : measure.tprod (i :: l) μ = (μ i).prod (measure.tprod l μ) := rfl instance sigma_finite_tprod (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)] : sigma_finite (measure.tprod l μ) := begin induction l with i l ih, { rw [tprod_nil], apply_instance }, { rw [tprod_cons], resetI, apply_instance } end lemma tprod_tprod (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)] {s : Π i, set (π i)} (hs : ∀ i, is_measurable (s i)) : measure.tprod l μ (set.tprod l s) = (l.map (λ i, (μ i) (s i))).prod := begin induction l with i l ih, { simp }, simp_rw [tprod_cons, set.tprod, prod_prod (hs i) (is_measurable.tprod l hs), map_cons, prod_cons, ih] end lemma tprod_tprod_le (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)] (s : Π i, set (π i)) : measure.tprod l μ (set.tprod l s) ≤ (l.map (λ i, (μ i) (s i))).prod := begin induction l with i l ih, { simp [le_refl] }, simp_rw [tprod_cons, set.tprod, map_cons, prod_cons], refine (prod_prod_le _ _).trans _, exact ennreal.mul_left_mono ih end end tprod section encodable open list measurable_equiv variables [encodable ι] /-- The product measure on an encodable finite type, defined by mapping `measure.tprod` along the equivalence `measurable_equiv.pi_measurable_equiv_tprod`. The definition `measure_theory.measure.pi` should be used instead of this one. -/ def pi' : measure (Π i, α i) := measure.map (tprod.elim' encodable.mem_sorted_univ) (measure.tprod (encodable.sorted_univ ι) μ) lemma pi'_pi [∀ i, sigma_finite (μ i)] {s : Π i, set (α i)} (hs : ∀ i, is_measurable (s i)) : pi' μ (pi univ s) = ∏ i, μ i (s i) := begin have hl := λ i : ι, encodable.mem_sorted_univ i, have hnd := @encodable.sorted_univ_nodup ι _ _, rw [pi', map_apply (measurable_tprod_elim' hl) (is_measurable.pi_fintype (λ i _, hs i)), elim_preimage_pi hnd, tprod_tprod _ μ hs, ← list.prod_to_finset _ hnd], congr' with i, simp [hl] end lemma pi'_pi_le [∀ i, sigma_finite (μ i)] {s : Π i, set (α i)} : pi' μ (pi univ s) ≤ ∏ i, μ i (s i) := begin have hl := λ i : ι, encodable.mem_sorted_univ i, have hnd := @encodable.sorted_univ_nodup ι _ _, apply ((pi_measurable_equiv_tprod hnd hl).symm.map_apply (pi univ s)).trans_le, dsimp only [pi_measurable_equiv_tprod, tprod.pi_equiv_tprod, coe_symm_mk, equiv.coe_fn_symm_mk], rw [elim_preimage_pi hnd], refine (tprod_tprod_le _ _ _).trans_eq _, rw [← list.prod_to_finset _ hnd], congr' with i, simp [hl] end end encodable lemma pi_caratheodory : measurable_space.pi ≤ (outer_measure.pi (λ i, (μ i).to_outer_measure)).caratheodory := begin refine supr_le _, intros i s hs, rw [measurable_space.comap] at hs, rcases hs with ⟨s, hs, rfl⟩, apply bounded_by_caratheodory, intro t, simp_rw [pi_premeasure], refine finset.prod_add_prod_le' (finset.mem_univ i) _ _ _, { simp [image_inter_preimage, image_diff_preimage, (μ i).caratheodory hs, le_refl] }, { rintro j - hj, apply mono', apply image_subset, apply inter_subset_left }, { rintro j - hj, apply mono', apply image_subset, apply diff_subset } end /-- `measure.pi μ` is the finite product of the measures `{μ i | i : ι}`. It is defined to be measure corresponding to `measure_theory.outer_measure.pi`. -/ protected def pi : measure (Π i, α i) := to_measure (outer_measure.pi (λ i, (μ i).to_outer_measure)) (pi_caratheodory μ) local attribute [instance] encodable.fintype.encodable lemma pi_pi [∀ i, sigma_finite (μ i)] (s : Π i, set (α i)) (hs : ∀ i, is_measurable (s i)) : measure.pi μ (pi univ s) = ∏ i, μ i (s i) := begin refine le_antisymm _ _, { rw [measure.pi, to_measure_apply _ _ (is_measurable.pi_fintype (λ i _, hs i))], apply outer_measure.pi_pi_le }, { rw [← pi'_pi], work_on_goal 1 { exact hs }, simp_rw [measure.pi, to_measure_apply _ _ (is_measurable.pi_fintype (λ i _, hs i)), ← to_outer_measure_apply], suffices : (pi' μ).to_outer_measure ≤ outer_measure.pi (λ i, (μ i).to_outer_measure), { exact this _ }, clear hs s, rw [outer_measure.le_pi], intros s hs, simp_rw [to_outer_measure_apply], exact pi'_pi_le μ } end lemma pi_eval_preimage_null [∀ i, sigma_finite (μ i)] {i : ι} {s : set (α i)} (hs : μ i s = 0) : measure.pi μ (eval i ⁻¹' s) = 0 := begin /- WLOG, `s` is measurable -/ rcases exists_is_measurable_superset_of_measure_eq_zero hs with ⟨t, hst, htm, hμt⟩, suffices : measure.pi μ (eval i ⁻¹' t) = 0, from measure_mono_null (preimage_mono hst) this, clear_dependent s, /- Now rewrite it as `set.pi`, and apply `pi_pi` -/ rw [← univ_pi_update_univ, pi_pi], { apply finset.prod_eq_zero (finset.mem_univ i), simp [hμt] }, { intro j, rcases em (j = i) with rfl | hj; simp * } end lemma pi_hyperplane [∀ i, sigma_finite (μ i)] (i : ι) [has_no_atoms (μ i)] (x : α i) : measure.pi μ {f : Π i, α i | f i = x} = 0 := show measure.pi μ (eval i ⁻¹' {x}) = 0, from pi_eval_preimage_null _ (measure_singleton x) instance [Π i, topological_space (α i)] [∀ i, opens_measurable_space (α i)] [∀ i, locally_finite_measure (μ i)] [∀ i, sigma_finite (μ i)]: locally_finite_measure (measure.pi μ) := begin refine ⟨λ x, _⟩, choose s hxs ho hμ using λ i, (μ i).exists_is_open_measure_lt_top (x i), refine ⟨pi univ s, set_pi_mem_nhds finite_univ (λ i hi, mem_nhds_sets (ho i) (hxs i)), _⟩, rw [pi_pi], exacts [ennreal.prod_lt_top (λ i _, hμ i), λ i, (ho i).is_measurable] end end measure instance measure_space.pi [Π i, measure_space (α i)] : measure_space (Π i, α i) := ⟨measure.pi (λ i, volume)⟩ lemma measure_space.pi_def [Π i, measure_space (α i)] : (volume : measure (Π i, α i)) = measure.pi (λ i, volume) := rfl lemma volume_pi [Π i, measure_space (α i)] [∀ i, sigma_finite (volume : measure (α i))] (s : Π i, set (α i)) (hs : ∀ i, is_measurable (s i)) : volume (pi univ s) = ∏ i, volume (s i) := measure.pi_pi (λ i, volume) s hs end measure_theory
3aaa5b9cef8917740a596547a6b4f63a817891d1
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/propext.lean
3d251c0644d6fed68a2a386beafa626fbdb57f34
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
933
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic constant propext {a b : Prop} : (a ↔ b) → a = b /- Additional congruence lemmas. -/ universe variables u v lemma forall_congr_eq {a : Sort u} {p q : a → Prop} (h : ∀ x, p x = q x) : (∀ x, p x) = ∀ x, q x := propext (forall_congr (λ a, (h a)^.to_iff)) lemma imp_congr_eq {a b c d : Prop} (h₁ : a = c) (h₂ : b = d) : (a → b) = (c → d) := propext (imp_congr h₁^.to_iff h₂^.to_iff) lemma imp_congr_ctx_eq {a b c d : Prop} (h₁ : a = c) (h₂ : c → (b = d)) : (a → b) = (c → d) := propext (imp_congr_ctx h₁^.to_iff (λ hc, (h₂ hc)^.to_iff)) lemma eq_true_intro {a : Prop} (h : a) : a = true := propext (iff_true_intro h) lemma eq_false_intro {a : Prop} (h : ¬a) : a = false := propext (iff_false_intro h)