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
eea99c450a2e1ea2aec2d3ef37c2d29bfbc09553
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/topology/uniform_space/basic.lean
ded0478c3148b4e5365d385ffebba473071be28b
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
67,485
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 order.filter.lift import topology.separation /-! # Uniform spaces Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * uniform continuity (in this file) * completeness (in `cauchy.lean`) * extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`) * totally bounded sets (in `cauchy.lean`) * totally bounded complete sets are compact (in `cauchy.lean`) A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means "for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages of `X`. The two main examples are: * If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V` * If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V` Those examples are generalizations in two different directions of the elementary example where `X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological group structure on `ℝ` and its metric space structure. Each uniform structure on `X` induces a topology on `X` characterized by > `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)` where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product constructor. The dictionary with metric spaces includes: * an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X` * a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}` for some `V ∈ 𝓤 X`, but the later is more general (it includes in particular both open and closed balls for suitable `V`). In particular we have: `is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s` The triangle inequality is abstracted to a statement involving the composition of relations in `X`. First note that the triangle inequality in a metric space is equivalent to `∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`. Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`. In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }` then the triangle inequality, as reformulated above, says `V ○ W` is contained in `{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`. In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`. Note that this discussion does not depend on any axiom imposed on the uniformity filter, it is simply captured by the definition of composition. The uniform space axioms ask the filter `𝓤 X` to satisfy the following: * every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that `x - x` belongs to every neighborhood of zero in the topological group case. * `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x` in a metric space, and to continuity of negation in the topological group case. * `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds to cutting the radius of a ball in half and applying the triangle inequality. In the topological group case, it comes from continuity of addition at `(0, 0)`. These three axioms are stated more abstractly in the definition below, in terms of operations on filters, without directly manipulating entourages. ## Main definitions * `uniform_space X` is a uniform space structure on a type `X` * `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r` In this file we also define a complete lattice structure on the type `uniform_space X` of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures coming from the pullback of filters. Like distance functions, uniform structures cannot be pushed forward in general. ## Notations Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`, and `○` for composition of relations, seen as terms with type `set (X × X)`. ## Implementation notes There is already a theory of relations in `data/rel.lean` where the main definition is `def rel (α β : Type*) := α → β → Prop`. The relations used in the current file involve only one type, but this is not the reason why we don't reuse `data/rel.lean`. We use `set (α × α)` instead of `rel α α` because we really need sets to use the filter library, and elements of filters on `α × α` have type `set (α × α)`. The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and an assumption saying those are compatible. This may not seem mathematically reasonable at first, but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance] below. ## References The formalization uses the books: * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] But it makes a more systematic use of the filter library. -/ open set filter classical open_locale classical topological_space filter set_option eqn_compiler.zeta true universes u /-! ### Relations, seen as `set (α × α)` -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} localized "infix ` ○ `:55 := comp_rel" in uniformity @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ @[mono] lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k := λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ s ○ t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : (r ○ s) ○ t = r ○ (s ○ t) := by ext p; cases p; simp only [mem_comp_rel]; tauto lemma subset_comp_self {α : Type*} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s := λ ⟨x, y⟩ xy_in, ⟨x, h (by rw mem_id_rel), xy_in⟩ /-- The relation is invariant under swapping factors. -/ def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V /-- The maximal symmetric relation contained in a given relation. -/ def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) := by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp] lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V := sep_subset _ _ @[mono] lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W := inter_subset_inter h $ preimage_mono h lemma symmetric_rel_inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) : symmetric_rel (U ∩ V) := begin unfold symmetric_rel at *, rw [preimage_inter, hU, hV], end /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : 𝓟 id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, s ○ s) ≤ uniformity) /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := by { congr, exact h } -- the topological structure is embedded in the uniform structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) /-- Alternative constructor for `uniform_space α` when a topology is already given. -/ @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, t ○ t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α} (h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) : tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) := begin refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity, filter_upwards [h₁₂ hs, h₂₃ hs], exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩ end /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α} (h : tendsto f l (𝓤 α)) : tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) := tendsto_swap_uniformity.comp h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ lemma tendsto_diag_uniformity (f : β → α) (l : filter β) : tendsto (λ x, (f x, f x)) l (𝓤 α) := assume s hs, mem_map.2 $ univ_mem_sets' $ λ x, refl_mem_uniformity hs lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := tendsto_diag_uniformity (λ _, a) f lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, λ a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α := begin apply (𝓤 α).inter_sets h, rw [← image_swap_eq_preimage_swap, uniformity_eq_symm], exact image_mem_map h, end theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (s ○ s)) = ((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, d ○ (d ○ d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), s ○ s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s := begin obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs, use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w], have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w, calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono ... ⊆ s : w_sub, end lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s := subset_comp_self (refl_le_uniformity h) lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s := begin rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩, rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩, use [t, t_in, t_symm], have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in, calc t ○ t ○ t ⊆ w ○ t : by mono ... ⊆ w ○ (t ○ t) : by mono ... ⊆ w ○ w : by mono ... ⊆ s : w_sub, end /-! ### Balls in uniform spaces -/ /-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/ def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V open uniform_space (ball) lemma uniform_space.mem_ball_self (x : α) {V : set (α × α)} (hV : V ∈ 𝓤 α) : x ∈ ball x V := refl_mem_uniformity hV /-- The triangle inequality for `uniform_space.ball` -/ lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W) := prod_mk_mem_comp_rel h h' lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) : ball x W ⊆ ball y V := λ z z_in, h' (mem_ball_comp h z_in) lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W := by tauto lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} : x ∈ ball y V ↔ y ∈ ball x V := show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV } lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} : ball x V = {y | (y, x) ∈ V} := by { ext y, rw mem_ball_symmetry hV, exact iff.rfl } lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V) (hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W := begin rw mem_ball_symmetry hV at hx, exact ⟨z, hx, hy⟩ end lemma uniform_space.is_open_ball (x : α) {V : set (α × α)} (hV : is_open V) : is_open (ball x V) := hV.preimage $ continuous_const.prod_mk continuous_id lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} : p ∈ V ○ M ○ W ↔ ((ball p.1 V).prod (ball p.2 W) ∩ M).nonempty := begin cases p with x y, split, { rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩, exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, }, { rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩, rwa mem_ball_symmetry hW' at z_in, use [z, w] ; tauto }, end /-! ### Neighborhoods in uniform spaces -/ lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ t ○ t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α := by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl } lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} : {p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F := by rw mem_comap_sets ; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, F.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux } lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity], exact iff.rfl, end lemma nhds_basis_uniformity' {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, ball x (s i)) := by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) } lemma nhds_basis_uniformity {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) := begin replace h := h.comap prod.swap, rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h, exact nhds_basis_uniformity' h end lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin rw [nhds_eq_comap_uniformity, mem_comap_sets], exact iff.rfl, end lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x := begin rw uniform_space.mem_nhds_iff, exact ⟨V, V_in, subset.refl _⟩ end lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s := begin rw uniform_space.mem_nhds_iff, split, { rintros ⟨V, V_in, V_sub⟩, use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V], exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub }, { rintros ⟨V, V_in, V_symm, V_sub⟩, exact ⟨V, V_in, V_sub⟩ } end lemma uniform_space.has_basis_nhds (x : α) : has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) := ⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩ open uniform_space lemma uniform_space.has_basis_nhds_prod (x y : α) : has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, (ball x s).prod (ball y s) := begin rw nhds_prod_eq, apply (has_basis_nhds x).prod' (has_basis_nhds y), rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩, exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, symmetric_rel_inter U_symm V_symm⟩, ball_mono (inter_subset_left U V) x, ball_mono (inter_subset_right U V) y⟩, end lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (ball x) := (nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := ball_mem_nhds x h lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : 𝓝 a ×ᶠ 𝓝 b = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, 𝓟 (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end /-- Entourages are neighborhoods of the diagonal. -/ lemma nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α := begin intros V V_in, rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩, have : (ball x w).prod (ball x w) ∈ 𝓝 (x, x), { rw nhds_prod_eq, exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) }, apply mem_sets_of_superset this, rintros ⟨u, v⟩ ⟨u_in, v_in⟩, exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in) end /-- Entourages are neighborhoods of the diagonal. -/ lemma supr_nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α := supr_le nhds_le_uniformity /-! ### Closure and interior in uniform spaces -/ lemma closure_eq_uniformity (s : set $ α × α) : closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V := begin ext ⟨x, y⟩, simp_rw [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter, mem_set_of_eq], apply forall_congr, intro V, apply forall_congr, rintros ⟨V_in, V_symm⟩, simp_rw [mem_comp_comp V_symm, inter_comm, exists_prop], exact iff.rfl, end lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id := begin refine filter.has_basis_self.2 (λ t h, _), rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩, refine ⟨closure w, mem_sets_of_superset w_in subset_closure, is_closed_closure, _⟩, refine subset.trans _ r, rw closure_eq_uniformity, apply Inter_subset_of_subset, apply Inter_subset, exact ⟨w_in, w_symm⟩ end /-- Closed entourages form a basis of the uniformity filter. -/ lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure := ⟨begin intro t, rw uniformity_has_basis_closed.mem_iff, split, { rintros ⟨r, ⟨r_in, r_closed⟩, r_sub⟩, use [r, r_in], convert r_sub, rw r_closed.closure_eq, refl }, { rintros ⟨r, r_in, r_sub⟩, exact ⟨closure r, ⟨mem_sets_of_superset r_in subset_closure, is_closed_closure⟩, r_sub⟩ } end⟩ lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ 𝓟 t ≠ ⊥) : mem_closure_iff_nhds_ne_bot ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) : begin rw [lift'_inf_principal_eq, ← ne_bot_iff, lift'_ne_bot_iff], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ s ○ (t ○ s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, d ○ (d ○ d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ λ x (hx : x ∈ t), let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_has_basis_closed.mem_iff.1 h in ⟨t, ht_mem, htc, hts⟩ /-- The uniform neighborhoods of all points of a dense set cover the whole space. -/ lemma dense.bUnion_uniformity_ball {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ 𝓤 α) : (⋃ x ∈ s, ball x U) = univ := begin refine bUnion_eq_univ_iff.2 (λ y, _), rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩, exact ⟨x, hxs, hxy⟩ end /-! ### Uniformity bases -/ /-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/ lemma uniformity_has_basis_open : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V) id := has_basis_self.2 $ λ s hs, ⟨interior s, interior_mem_uniformity hs, is_open_interior, interior_subset⟩ lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)} (h : (𝓤 α).has_basis p s) {t : set (α × α)} : t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t := h.mem_iff.trans $ by simp only [prod.forall, subset_def] /-- Symmetric entourages form a basis of `𝓤 α` -/ lemma uniform_space.has_basis_symmetric : (𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id := has_basis_self.2 $ λ t t_in, ⟨symmetrize_rel t, symmetrize_mem_uniformity t_in, symmetric_symmetrize_rel t, symmetrize_rel_subset_self t⟩ /-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis of `𝓤 α`. -/ lemma uniformity_has_basis_open_symmetric : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V ∧ symmetric_rel V) id := begin simp only [← and_assoc], refine uniformity_has_basis_open.restrict (λ s hs, ⟨symmetrize_rel s, _⟩), exact ⟨⟨symmetrize_mem_uniformity hs.1, is_open_inter hs.2 (hs.2.preimage continuous_swap)⟩, symmetric_symmetrize_rel s, symmetrize_rel_subset_self s⟩ end lemma uniform_space.has_seq_basis (h : is_countably_generated $ 𝓤 α) : ∃ V : ℕ → set (α × α), has_antimono_basis (𝓤 α) (λ _, true) V ∧ ∀ n, symmetric_rel (V n) := let ⟨U, hsym, hbasis⟩ := h.exists_antimono_subbasis uniform_space.has_basis_symmetric in ⟨U, hbasis, λ n, (hsym n).2⟩ /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) /-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `s`.-/ def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop := tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s.prod s)) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := uniform_continuous_of_const $ λ _ _, rfl lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} : uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i := (ha.tendsto_iff hb).trans $ by simp only [prod.forall] lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} : uniform_continuous_on f S ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i := ((ha.inf_principal (S.prod S)).tendsto_iff hb).trans $ by finish [prod.forall] end uniform_space open_locale uniformity section constructions instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := 𝓟 id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ instance inhabited_uniform_space_core : inhabited (uniform_space.core α) := ⟨@uniform_space.to_core _ (default _)⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ } end } lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓤 α = comap (prod.map f f) (𝓤 β) := by { rw h, refl } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_nhds_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) (a : α) : @nhds _ (@uniform_space.to_topological_space _ u₁) a ≤ @nhds _ (@uniform_space.to_topological_space _ u₂) a := by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h le_rfl) lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ to_nhds_mono h lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume ⟨x, hx⟩, have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := begin by_cases h : nonempty ι, { resetI, refine (eq_of_nhds_eq_nhds $ assume a, _), rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, rw [infi_uniformity, lift'_infi], { simp only [nhds_eq_uniformity], refl }, { exact assume a b, rfl } }, { rw [infi_of_empty h, infi_of_empty h, to_topological_space_top] } end lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi], simp only [← to_topological_space_infi], end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space unit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) := begin unfold uniform_continuous_on set.restrict uniform_continuous tendsto, rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl, uniformity_comap rfl, show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl], conv in (map _ (comap _ _)) { rw ← filter.map_map }, rw subtype_coe_map_comap_prod, refl, end lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (h : uniform_continuous_on f s) : continuous_on f s := begin rw uniform_continuous_on_iff_restrict at h, rw continuous_on_iff_continuous_restrict, exact h.continuous end section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := (hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] local notation f `∘₂` g := function.bicompr f g /-- Uniform continuity for functions of two variables. -/ def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (uncurry f) := h lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [uniform_continuous₂, uncurry_curry] lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (bicompl f ga gb) := hf.uniform_continuous.comp (hga.prod_map hgb) end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions -- For a version of the Lebesgue number lemma assuming only a sequentially compact space, -- see topology/sequences.lean /-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/ lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, (bInter_mem_sets b_fin).2 bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end /-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/ lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform variables [uniform_space α] theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) := ⟨λ H, tendsto_left_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩ theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) := ⟨λ H, tendsto_right_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩ theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_right] theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_left] theorem continuous_at_iff_prod [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x : β × β, (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) := ⟨λ H, le_trans (H.prod_map' H) (nhds_le_uniformity _), λ H, continuous_at_iff'_left.2 $ H.comp $ tendsto_id.prod_mk_nhds tendsto_const_nhds⟩ theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_right] theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_left] theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_right] theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_left] theorem continuous_iff'_right [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right theorem continuous_iff'_left [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left end uniform lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto g l (𝓝 b) := uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) := ⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
0121c41b80f230b2d6521159f3adf2e5b0465226
83c8119e3298c0bfc53fc195c41a6afb63d01513
/library/init/meta/tactic.lean
1d24029195c0774bc9942f4f98852331128c9ed3
[ "Apache-2.0" ]
permissive
anfelor/lean
584b91c4e87a6d95f7630c2a93fb082a87319ed0
31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1
refs/heads/master
1,610,067,141,310
1,585,992,232,000
1,585,992,232,000
251,683,543
0
0
Apache-2.0
1,585,676,570,000
1,585,676,569,000
null
UTF-8
Lean
false
false
62,657
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.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ /-- `tactic` is the monad for building tactics. You use this to: - View and modify the local goals and hypotheses in the prover's state. - Invoke type checking and elaboration of terms. - View and modify the environment. - Build new tactics out of existing ones such as `simp` and `rewrite`. -/ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) /-- Cause the tactic to fail with no error message. -/ meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace interactive /-- Typeclass for custom interaction monads, which provides the information required to convert an interactive-mode construction to a `tactic` which can actually be executed. Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end` block, or a `by ...` statement into a `tactic α` which can actually be executed. The `inhabited` first argument facilitates the passing of an optional configuration parameter `config`, using the syntax: ``` begin [custom_monad] with config, ... end ``` -/ meta class executor (m : Type → Type u) [monad m] := (config_type : Type) [inhabited : inhabited config_type] (execute_with : config_type → m unit → tactic unit) attribute [inline] executor.execute_with @[inline] meta def executor.execute_explicit (m : Type → Type u) [monad m] [e : executor m] : m unit → tactic unit := executor.execute_with e.inhabited.default @[inline] meta def executor.execute_with_explicit (m : Type → Type u) [monad m] [executor m] : executor.config_type m → m unit → tactic unit := executor.execute_with /-- Default `executor` instance for `tactic`s themselves -/ meta instance : executor tactic := { config_type := unit, inhabited := ⟨()⟩, execute_with := λ _, id } end interactive namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) /-- Does nothing. -/ meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | result.success _ s' := try (try_lst tacs) s' | result.exception e p s' := match try_lst tacs s' with | result.exception _ _ _ := result.exception e p s' | r := r end end meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (interaction_monad.result.exception _ _ s') := success () s | (interaction_monad.result.success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s end open nat /-- (iterate_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def iterate_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, iterate_at_most n t) <|> skip /-- (iterate_exactly n t) : execute t n times -/ meta def iterate_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, iterate_exactly n t /-- Repeat the given tactic forever. -/ meta def iterate : tactic unit → tactic unit := iterate_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg. -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) /-- Set the tactic_state. -/ @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' /-- Get the tactic_state. -/ @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨λ l, to_fmt <$> l.mmap pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s /-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal. By default, theorem declarations are never unfolded. - `all` will unfold everything, including macros and theorems. Except projection macros. - `semireducible` will unfold everything except theorems and definitions tagged as irreducible. - `instances` will unfold all class instance definitions and definitions tagged with reducible. - `reducible` will only unfold definitions tagged with the `reducible` attribute. - `none` will never unfold anything. [NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes. [NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems. -/ inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit /-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target. If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants. Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant head_zeta : expr → tactic expr /-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr /-- Get the `local_const` expr for the given `name`. -/ meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) /-- Get a fresh name that is guaranteed to not be in use in the local context. If `n` is provided and `n` is not in use, then `n` is returned. Otherwise a number `i` is appended to give `"n_i"`. -/ meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst_core : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/ meta constant rotate_left : nat → tactic unit /-- Gets a list of metavariables, one for each goal. -/ meta constant get_goals : tactic (list expr) /-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/ meta constant set_goals : list expr → tactic unit /-- How to order the new goals made from an `apply` tactic. Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q` - `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on. - `non_dep_only` would produce goal `⊢ P(?m)`. - `all` would produce goals `⊢ α`, `⊢ P(?m)`. -/ inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `md` sets how aggressively definitions are unfolded. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`. All of the metavariables that are not assigned are added as new metavariables. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool /-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/ meta constant mk_fresh_name : tactic name /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. The new environment does not need to be a descendant of the old one. Use with care. -/ meta constant set_env_core : environment → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- `doc_string env d k` returns the doc string for `d` (if available) -/ meta constant doc_string : name → tactic string /-- Set the docstring for the given declaration. -/ meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr /-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones. The returned object is a list of modules, indexed by `(some filename)` for imported modules and `none` for the active one, where each module in the list is paired with a list of `(position_in_file, docstring)` pairs. -/ meta constant olean_doc_strings : tactic (list (option string × (list (pos × string)))) /-- Returns a list of docstrings in the active module. An entry in the list can be either: - a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)` - a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/ meta def module_doc_strings : tactic (list (option name × string)) := do /- Obtain a list of top-level docs in current module. -/ mod_docs ← olean_doc_strings, let mod_docs: list (list (option name × string)) := mod_docs.filter_map (λ d, if d.1.is_none then some (d.2.map (λ pos_doc, ⟨none, pos_doc.2⟩)) else none), let mod_docs := mod_docs.join, /- Obtain list of declarations in current module. -/ e ← get_env, let decls := environment.fold e ([]: list name) (λ d acc, let n := d.to_name in if (environment.decl_olean e n).is_none then n::acc else acc), /- Map declarations to those which have docstrings. -/ decls ← decls.mfoldl (λa n, (doc_string n >>= λ doc, pure $ (some n, doc) :: a) <|> pure a) [], pure (mod_docs ++ decls) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority and whether or not the attribute is persistent. -/ meta constant has_attribute : name → name → tactic (bool × nat) /-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/ meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit := try $ do (p', prio) ← has_attribute attr_name src, let p := p.get_or_else p', set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/ def tag : Type := list name /-- Enable/disable goal tagging. -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag /-- By default, Lean only considers local instances in the header of declarations. This has two main benefits. 1- Results produced by the type class resolution procedure can be easily cached. 2- The set of local instances does not have to be recomputed. This approach has the following disadvantages: 1- Frozen local instances cannot be reverted. 2- Local instances defined inside of a declaration are not considered during type class resolution. This tactic resets the set of local instances. After executing this tactic, the set of local instances will be recomputed and the cache will be frequently reset. Note that, the cache is still used when executing a single tactic that may generate many type class resolution problems (e.g., `simp`). -/ meta constant unfreeze_local_instances : tactic unit /- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/ meta constant frozen_local_instances : tactic (option (list expr)) meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. The tactic does not check whether `e` is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/ meta def unsafe_change (e : expr) : tactic unit := change e ff /-- Pi or elet introduction. Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`. Returns the new local constant. Similarly for `elet` expressions. If the target is not a Pi or elet it will try to put it in WHNF. -/ meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n /-- Like `intro` except the name is derived from the bound name in the Π. -/ meta def intro1 : tactic expr := intro `_ /-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction.-/ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end /-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/ meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies. -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q /-- Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta def revert (l : expr) : tactic nat := revert_lst [l] /- Revert "all" hypotheses. Actually, the tactic only reverts hypotheses occurring after the last frozen local instance. Recall that frozen local instances cannot be reverted. We can use `unfreeze_local_instances` to workaround this limitation. -/ meta def revert_all : tactic nat := do lctx ← local_context, lis ← frozen_local_instances, match lis with | none := revert_lst lctx | some [] := revert_lst lctx /- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/ | some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) [] end meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times. [NOTE] We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) /-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/ meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r /-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} /-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit := do c ← mk_const c, apply c cfg, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute [instance] classical.prop_decidable' is used, all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list name) := if e.is_local_constant then do r ← cases_core e ids md, return $ r.map (λ t, t.1) else do n ← revert_kdependencies e dmd, x ← get_unused_name, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 (do r ← cases_core h ids md, all_goals (intron n), return $ r.map (λ t, t.1)) /-- The same as `exact` except you can add proof holes. -/ meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq (apply tm >> skip) (intro h >> skip) meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs | pure `_, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) /-- add declaration `d` as a protected declaration -/ meta def add_protected_decl (d : declaration) : tactic unit := updateex_env $ λ e, e.add_protected d /-- check if `n` is the name of a protected declaration -/ meta def is_protected_decl (n : name) : tactic bool := do env ← get_env, return $ env.is_protected n /-- `add_defn_equations` adds a definition specified by a list of equations. The arguments: * `lp`: list of universe parameters * `params`: list of parameters (binders before the colon); * `fn`: a local constant giving the name and type of the declaration (with `params` in the local context); * `eqns`: a list of equations, each of which is a list of patterns (constructors applied to new local constants) and the branch expression; * `is_meta`: is the definition meta? `add_defn_equations` can be used as: do my_add ← mk_local_def `my_add `(ℕ → ℕ), a ← mk_local_def `a ℕ, b ← mk_local_def `b ℕ, add_defn_equations [a] my_add [ ([``(nat.zero)], a), ([``(nat.succ %%b)], my_add b) ]) ff -- non-meta to create the following definition: def my_add (a : ℕ) : ℕ → ℕ | nat.zero := a | (nat.succ b) := my_add b -/ meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr) (eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit := do opt ← get_options, updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t meta def subst (h : expr) : tactic unit := (do guard h.is_local_constant, some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h, is_def_eq α β, new_h_type ← mk_app `eq [lhs, rhs], new_h_pr ← mk_app `eq_of_heq [h], new_h ← assertv h.local_pp_name new_h_type new_h_pr, try (clear h), subst_core new_h) <|> subst_core h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ /-- Try to prove with `iff.refl`.-/ meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
fad5646d53bd5ac4df6ae47ba546d50c9ff10f46
5ae26df177f810c5006841e9c73dc56e01b978d7
/test/rcases.lean
65cd7f7782e4ee5e5169945a5f1a3164b4085b02
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
1,867
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.rcases universe u variables {α β γ : Type u} example (x : α × β × γ) : true := begin rcases x with ⟨a, b, c⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example (x : α × β × γ) : true := begin rcases x with ⟨a, ⟨b, c⟩⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example (x : (α × β) × γ) : true := begin rcases x with ⟨⟨a, b⟩, c⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example : inhabited α × option β ⊕ γ → true := begin rintro (⟨⟨a⟩, _ | b⟩ | c), { guard_hyp a := α, trivial }, { guard_hyp a := α, guard_hyp b := β, trivial }, { guard_hyp c := γ, trivial } end example (x y : ℕ) (h : x = y) : true := begin rcases x with _|⟨⟩|z, { guard_hyp h := nat.zero = y, trivial }, { guard_hyp h := nat.succ nat.zero = y, trivial }, { guard_hyp z := ℕ, guard_hyp h := z.succ.succ = y, trivial }, end -- from equiv.sum_empty example (s : α ⊕ empty) : true := begin rcases s with _ | ⟨⟨⟩⟩, { guard_hyp s := α, trivial } end example : true := begin obtain ⟨n, h, f⟩ : ∃ n : ℕ, n = n ∧ true, { existsi 0, simp }, guard_hyp n := ℕ, guard_hyp h := n = n, guard_hyp f := true, trivial end example : true := begin obtain : ∃ n : ℕ, n = n ∧ true, { existsi 0, simp }, trivial end example : true := begin obtain h | ⟨⟨⟩⟩ : true ∨ false, { left, trivial }, guard_hyp h := true, trivial end example : true := begin obtain h | ⟨⟨⟩⟩ : true ∨ false := or.inl trivial, guard_hyp h := true, trivial end
bd6901cc1eb9d105f0bd1da28351ed7242a8215a
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/algebra/category/constructions/functor.hlean
866e72be7a4f9ef2bdfb1c10416db352092168e4
[ "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
16,094
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Functor precategory and category -/ import ..nat_trans ..category .opposite open eq category is_trunc nat_trans iso is_equiv category.hom namespace functor definition precategory_functor [instance] [constructor] (D C : Precategory) : precategory (functor C D) := precategory.mk (λa b, nat_trans a b) (λ a b c g f, nat_trans.compose g f) (λ a, nat_trans.id) (λ a b c d h g f, !nat_trans.assoc) (λ a b f, !nat_trans.id_left) (λ a b f, !nat_trans.id_right) definition Precategory_functor [reducible] [constructor] (D C : Precategory) : Precategory := precategory.Mk (precategory_functor D C) infixr ` ^c `:80 := Precategory_functor section /- we prove that if a natural transformation is pointwise an iso, then it is an iso -/ variables {C D : Precategory} {F G : C ⇒ D} (η : F ⟹ G) [iso : Π(a : C), is_iso (η a)] include iso definition nat_trans_inverse [constructor] : G ⟹ F := nat_trans.mk (λc, (η c)⁻¹) (λc d f, abstract begin apply comp_inverse_eq_of_eq_comp, transitivity (natural_map η d)⁻¹ ∘ to_fun_hom G f ∘ natural_map η c, {apply eq_inverse_comp_of_comp_eq, symmetry, apply naturality}, {apply assoc} end end) definition nat_trans_left_inverse : nat_trans_inverse η ∘n η = 1 := begin fapply (apd011 nat_trans.mk), apply eq_of_homotopy, intro c, apply left_inverse, apply eq_of_homotopy, intros, apply eq_of_homotopy, intros, apply eq_of_homotopy, intros, apply is_set.elim end definition nat_trans_right_inverse : η ∘n nat_trans_inverse η = 1 := begin fapply (apd011 nat_trans.mk), apply eq_of_homotopy, intro c, apply right_inverse, apply eq_of_homotopy, intros, apply eq_of_homotopy, intros, apply eq_of_homotopy, intros, apply is_set.elim end definition is_natural_iso [constructor] : is_iso η := is_iso.mk _ (nat_trans_left_inverse η) (nat_trans_right_inverse η) variable (iso) definition natural_iso.mk [constructor] : F ≅ G := iso.mk _ (is_natural_iso η) omit iso variables (F G) definition is_natural_inverse (η : Πc, F c ≅ G c) (nat : Π⦃a b : C⦄ (f : hom a b), G f ∘ to_hom (η a) = to_hom (η b) ∘ F f) {a b : C} (f : hom a b) : F f ∘ to_inv (η a) = to_inv (η b) ∘ G f := let η' : F ⟹ G := nat_trans.mk (λc, to_hom (η c)) @nat in naturality (nat_trans_inverse η') f definition is_natural_inverse' (η₁ : Πc, F c ≅ G c) (η₂ : F ⟹ G) (p : η₁ ~ η₂) {a b : C} (f : hom a b) : F f ∘ to_inv (η₁ a) = to_inv (η₁ b) ∘ G f := is_natural_inverse F G η₁ abstract λa b g, (p a)⁻¹ ▸ (p b)⁻¹ ▸ naturality η₂ g end f variables {F G} definition natural_iso.MK [constructor] (η : Πc, F c ⟶ G c) (p : Π(c c' : C) (f : c ⟶ c'), G f ∘ η c = η c' ∘ F f) (θ : Πc, G c ⟶ F c) (r : Πc, θ c ∘ η c = id) (q : Πc, η c ∘ θ c = id) : F ≅ G := iso.mk (nat_trans.mk η p) (@(is_natural_iso _) (λc, is_iso.mk (θ c) (r c) (q c))) end section /- and conversely, if a natural transformation is an iso, it is componentwise an iso -/ variables {A B C D : Precategory} {F G : C ⇒ D} (η : hom F G) [isoη : is_iso η] (c : C) include isoη definition componentwise_is_iso [constructor] : is_iso (η c) := @is_iso.mk _ _ _ _ _ (natural_map η⁻¹ c) (ap010 natural_map ( left_inverse η) c) (ap010 natural_map (right_inverse η) c) local attribute componentwise_is_iso [instance] variable {isoη} definition natural_map_inverse : natural_map η⁻¹ c = (η c)⁻¹ := idp variable [isoη] definition naturality_iso {c c' : C} (f : c ⟶ c') : G f = η c' ∘ F f ∘ (η c)⁻¹ := calc G f = (G f ∘ η c) ∘ (η c)⁻¹ : by rewrite comp_inverse_cancel_right ... = (η c' ∘ F f) ∘ (η c)⁻¹ : by rewrite naturality ... = η c' ∘ F f ∘ (η c)⁻¹ : by rewrite assoc definition naturality_iso' {c c' : C} (f : c ⟶ c') : (η c')⁻¹ ∘ G f ∘ η c = F f := calc (η c')⁻¹ ∘ G f ∘ η c = (η c')⁻¹ ∘ η c' ∘ F f : by rewrite naturality ... = F f : by rewrite inverse_comp_cancel_left omit isoη definition componentwise_iso (η : F ≅ G) (c : C) : F c ≅ G c := iso.mk (natural_map (to_hom η) c) (@componentwise_is_iso _ _ _ _ (to_hom η) (struct η) c) definition componentwise_iso_id (c : C) : componentwise_iso (iso.refl F) c = iso.refl (F c) := iso_eq (idpath (ID (F c))) definition componentwise_iso_iso_of_eq (p : F = G) (c : C) : componentwise_iso (iso_of_eq p) c = iso_of_eq (ap010 to_fun_ob p c) := eq.rec_on p !componentwise_iso_id theorem naturality_iso_id {F : C ⇒ C} (η : F ≅ 1) (c : C) : componentwise_iso η (F c) = F (componentwise_iso η c) := comp.cancel_left (to_hom (componentwise_iso η c)) ((naturality (to_hom η)) (to_hom (componentwise_iso η c))) definition natural_map_hom_of_eq (p : F = G) (c : C) : natural_map (hom_of_eq p) c = hom_of_eq (ap010 to_fun_ob p c) := eq.rec_on p idp definition natural_map_inv_of_eq (p : F = G) (c : C) : natural_map (inv_of_eq p) c = hom_of_eq (ap010 to_fun_ob p c)⁻¹ := eq.rec_on p idp definition hom_of_eq_compose_right {H : B ⇒ C} (p : F = G) : hom_of_eq (ap (λx, x ∘f H) p) = hom_of_eq p ∘nf H := eq.rec_on p idp definition inv_of_eq_compose_right {H : B ⇒ C} (p : F = G) : inv_of_eq (ap (λx, x ∘f H) p) = inv_of_eq p ∘nf H := eq.rec_on p idp definition hom_of_eq_compose_left {H : D ⇒ C} (p : F = G) : hom_of_eq (ap (λx, H ∘f x) p) = H ∘fn hom_of_eq p := by induction p; exact !fn_id⁻¹ definition inv_of_eq_compose_left {H : D ⇒ C} (p : F = G) : inv_of_eq (ap (λx, H ∘f x) p) = H ∘fn inv_of_eq p := by induction p; exact !fn_id⁻¹ definition assoc_natural [constructor] (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) : H ∘f (G ∘f F) ⟹ (H ∘f G) ∘f F := change_natural_map (hom_of_eq !functor.assoc) (λa, id) (λa, !natural_map_hom_of_eq ⬝ ap hom_of_eq !ap010_assoc) definition assoc_natural_rev [constructor] (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) : (H ∘f G) ∘f F ⟹ H ∘f (G ∘f F) := change_natural_map (inv_of_eq !functor.assoc) (λa, id) (λa, !natural_map_inv_of_eq ⬝ ap (λx, hom_of_eq x⁻¹) !ap010_assoc) definition id_left_natural [constructor] (F : C ⇒ D) : functor.id ∘f F ⟹ F := change_natural_map (hom_of_eq !functor.id_left) (λc, id) (λc, by induction F; exact !natural_map_hom_of_eq ⬝ ap hom_of_eq !ap010_functor_mk_eq_constant) definition id_left_natural_rev [constructor] (F : C ⇒ D) : F ⟹ functor.id ∘f F := change_natural_map (inv_of_eq !functor.id_left) (λc, id) (λc, by induction F; exact !natural_map_inv_of_eq ⬝ ap (λx, hom_of_eq x⁻¹) !ap010_functor_mk_eq_constant) definition id_right_natural [constructor] (F : C ⇒ D) : F ∘f functor.id ⟹ F := change_natural_map (hom_of_eq !functor.id_right) (λc, id) (λc, by induction F; exact !natural_map_hom_of_eq ⬝ ap hom_of_eq !ap010_functor_mk_eq_constant) definition id_right_natural_rev [constructor] (F : C ⇒ D) : F ⟹ F ∘f functor.id := change_natural_map (inv_of_eq !functor.id_right) (λc, id) (λc, by induction F; exact !natural_map_inv_of_eq ⬝ ap (λx, hom_of_eq x⁻¹) !ap010_functor_mk_eq_constant) end section variables {C D E : Precategory} {G G' : D ⇒ E} {F F' : C ⇒ D} {J : D ⇒ D} definition is_iso_nf_compose [constructor] (G : D ⇒ E) (η : F ⟹ F') [H : is_iso η] : is_iso (G ∘fn η) := is_iso.mk (G ∘fn @inverse (C ⇒ D) _ _ _ η _) abstract !fn_n_distrib⁻¹ ⬝ ap (λx, G ∘fn x) (@left_inverse (C ⇒ D) _ _ _ η _) ⬝ !fn_id end abstract !fn_n_distrib⁻¹ ⬝ ap (λx, G ∘fn x) (@right_inverse (C ⇒ D) _ _ _ η _) ⬝ !fn_id end definition is_iso_fn_compose [constructor] (η : G ⟹ G') (F : C ⇒ D) [H : is_iso η] : is_iso (η ∘nf F) := is_iso.mk (@inverse (D ⇒ E) _ _ _ η _ ∘nf F) abstract !n_nf_distrib⁻¹ ⬝ ap (λx, x ∘nf F) (@left_inverse (D ⇒ E) _ _ _ η _) ⬝ !id_nf end abstract !n_nf_distrib⁻¹ ⬝ ap (λx, x ∘nf F) (@right_inverse (D ⇒ E) _ _ _ η _) ⬝ !id_nf end definition functor_iso_compose [constructor] (G : D ⇒ E) (η : F ≅ F') : G ∘f F ≅ G ∘f F' := iso.mk _ (is_iso_nf_compose G (to_hom η)) definition iso_functor_compose [constructor] (η : G ≅ G') (F : C ⇒ D) : G ∘f F ≅ G' ∘f F := iso.mk _ (is_iso_fn_compose (to_hom η) F) infixr ` ∘fi ` :62 := functor_iso_compose infixr ` ∘if ` :62 := iso_functor_compose /- TODO: also needs n_nf_distrib and id_nf for these compositions definition nidf_compose [constructor] (η : J ⟹ 1) (F : C ⇒ D) [H : is_iso η] : is_iso (η ∘n1f F) := is_iso.mk (@inverse (D ⇒ D) _ _ _ η _ ∘1nf F) abstract _ end _ definition idnf_compose [constructor] (η : 1 ⟹ J) (F : C ⇒ D) [H : is_iso η] : is_iso (η ∘1nf F) := is_iso.mk _ _ _ definition fnid_compose [constructor] (F : D ⇒ E) (η : J ⟹ 1) [H : is_iso η] : is_iso (F ∘fn1 η) := is_iso.mk _ _ _ definition fidn_compose [constructor] (F : D ⇒ E) (η : 1 ⟹ J) [H : is_iso η] : is_iso (F ∘f1n η) := is_iso.mk _ _ _ -/ end namespace functor variables {C : Precategory} {D : Category} {F G : D ^c C} definition eq_of_iso_ob (η : F ≅ G) (c : C) : F c = G c := by apply eq_of_iso; apply componentwise_iso; exact η local attribute functor.to_fun_hom [reducible] definition eq_of_iso (η : F ≅ G) : F = G := begin fapply functor_eq, {exact (eq_of_iso_ob η)}, {intro c c' f, esimp [eq_of_iso_ob, inv_of_eq, hom_of_eq, eq_of_iso], rewrite [*right_inv iso_of_eq], symmetry, apply @naturality_iso _ _ _ _ _ (iso.struct _) } end definition iso_of_eq_eq_of_iso (η : F ≅ G) : iso_of_eq (eq_of_iso η) = η := begin apply iso_eq, apply nat_trans_eq, intro c, rewrite natural_map_hom_of_eq, esimp [eq_of_iso], rewrite ap010_functor_eq, esimp [hom_of_eq,eq_of_iso_ob], rewrite (right_inv iso_of_eq), end definition eq_of_iso_iso_of_eq (p : F = G) : eq_of_iso (iso_of_eq p) = p := begin apply functor_eq2, intro c, esimp [eq_of_iso], rewrite ap010_functor_eq, esimp [eq_of_iso_ob], rewrite componentwise_iso_iso_of_eq, rewrite (left_inv iso_of_eq) end definition is_univalent (D : Category) (C : Precategory) : is_univalent (D ^c C) := λF G, adjointify _ eq_of_iso iso_of_eq_eq_of_iso eq_of_iso_iso_of_eq end functor definition category_functor [instance] [constructor] (D : Category) (C : Precategory) : category (D ^c C) := category.mk (D ^c C) (functor.is_univalent D C) definition Category_functor [constructor] (D : Category) (C : Precategory) : Category := category.Mk (D ^c C) !category_functor --this definition is only useful if the exponent is a category, -- and the elaborator has trouble with inserting the coercion definition Category_functor' [constructor] (D C : Category) : Category := Category_functor D C namespace ops infixr ` ^c2 `:35 := Category_functor end ops namespace functor variables {C : Precategory} {D : Category} {F G : D ^c C} definition eq_of_pointwise_iso (η : F ⟹ G) (iso : Π(a : C), is_iso (η a)) : F = G := eq_of_iso (natural_iso.mk η iso) definition iso_of_eq_eq_of_pointwise_iso (η : F ⟹ G) (iso : Π(c : C), is_iso (η c)) : iso_of_eq (eq_of_pointwise_iso η iso) = natural_iso.mk η iso := !iso_of_eq_eq_of_iso definition hom_of_eq_eq_of_pointwise_iso (η : F ⟹ G) (iso : Π(c : C), is_iso (η c)) : hom_of_eq (eq_of_pointwise_iso η iso) = η := !hom_of_eq_eq_of_iso definition inv_of_eq_eq_of_pointwise_iso (η : F ⟹ G) (iso : Π(c : C), is_iso (η c)) : inv_of_eq (eq_of_pointwise_iso η iso) = nat_trans_inverse η := !inv_of_eq_eq_of_iso end functor /- functors involving only the functor category (see ..functor.curry for some other functors involving also products) -/ variables {C D I : Precategory} definition constant2_functor [constructor] (F : I ⇒ D ^c C) (c : C) : I ⇒ D := functor.mk (λi, to_fun_ob (F i) c) (λi j f, natural_map (F f) c) abstract (λi, ap010 natural_map !respect_id c ⬝ proof idp qed) end abstract (λi j k g f, ap010 natural_map !respect_comp c) end definition constant2_functor_natural [constructor] (F : I ⇒ D ^c C) {c d : C} (f : c ⟶ d) : constant2_functor F c ⟹ constant2_functor F d := nat_trans.mk (λi, to_fun_hom (F i) f) (λi j k, (naturality (F k) f)⁻¹) definition functor_flip [constructor] (F : I ⇒ D ^c C) : C ⇒ D ^c I := functor.mk (constant2_functor F) @(constant2_functor_natural F) abstract begin intros, apply nat_trans_eq, intro i, esimp, apply respect_id end end abstract begin intros, apply nat_trans_eq, intro i, esimp, apply respect_comp end end definition eval_functor [constructor] (C D : Precategory) (d : D) : C ^c D ⇒ C := begin fapply functor.mk: esimp, { intro F, exact F d}, { intro G F η, exact η d}, { intro F, reflexivity}, { intro H G F η θ, reflexivity}, end definition precomposition_functor [constructor] {C D} (E) (F : C ⇒ D) : E ^c D ⇒ E ^c C := begin fapply functor.mk: esimp, { intro G, exact G ∘f F}, { intro G H η, exact η ∘nf F}, { intro G, reflexivity}, { intro G H I η θ, reflexivity}, end definition postcomposition_functor [constructor] {C D} (E) (F : C ⇒ D) : C ^c E ⇒ D ^c E := begin fapply functor.mk: esimp, { intro G, exact F ∘f G}, { intro G H η, exact F ∘fn η}, { intro G, apply fn_id}, { intro G H I η θ, apply fn_n_distrib}, end definition constant_diagram [constructor] (C D) : C ⇒ C ^c D := begin fapply functor.mk: esimp, { intro c, exact constant_functor D c}, { intro c d f, exact constant_nat_trans D f}, { intro c, fapply nat_trans_eq, reflexivity}, { intro c d e g f, fapply nat_trans_eq, reflexivity}, end definition opposite_functor_opposite_left [constructor] (C D : Precategory) : (C ^c D)ᵒᵖ ⇒ Cᵒᵖ ^c Dᵒᵖ := begin fapply functor.mk: esimp, { exact opposite_functor}, { intro F G, exact opposite_nat_trans}, { intro F, apply nat_trans_eq, reflexivity}, { intro u v w g f, apply nat_trans_eq, reflexivity} end definition opposite_functor_opposite_right [constructor] (C D : Precategory) : Cᵒᵖ ^c Dᵒᵖ ⇒ (C ^c D)ᵒᵖ := begin fapply functor.mk: esimp, { exact opposite_functor_rev}, { apply @opposite_rev_nat_trans}, { intro F, apply nat_trans_eq, intro d, reflexivity}, { intro F G H η θ, apply nat_trans_eq, intro d, reflexivity} end definition constant_diagram_opposite [constructor] (C D) : (constant_diagram C D)ᵒᵖᶠ = opposite_functor_opposite_right C D ∘f constant_diagram Cᵒᵖ Dᵒᵖ := begin fapply functor_eq, { reflexivity}, { intro c c' f, esimp at *, refine !nat_trans.id_right ⬝ !nat_trans.id_left ⬝ _, apply nat_trans_eq, intro d, reflexivity} end end functor
951d4841d6c925e0e2e571a562ba54bb9eefd9e7
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/data/finset/comb.lean
14f22cbabb9da34eef6276f6c0c57685410a2823
[ "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
18,908
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad Combinators for finite sets. -/ import data.finset.basic logic.identities open list quot subtype decidable perm function namespace finset /- image (corresponds to map on list) -/ section image variables {A B : Type} variable [h : decidable_eq B] include h definition image (f : A → B) (s : finset A) : finset B := quot.lift_on s (λ l, to_finset (list.map f (elt_of l))) (λ l₁ l₂ p, quot.sound (perm_erase_dup_of_perm (perm_map _ p))) notation [priority finset.prio] f `'[`:max a `]` := image f a theorem image_empty (f : A → B) : image f ∅ = ∅ := rfl theorem mem_image_of_mem (f : A → B) {s : finset A} {a : A} : a ∈ s → f a ∈ image f s := quot.induction_on s (take l, assume H : a ∈ elt_of l, mem_to_finset (mem_map f H)) theorem mem_image {f : A → B} {s : finset A} {a : A} {b : B} (H1 : a ∈ s) (H2 : f a = b) : b ∈ image f s := eq.subst H2 (mem_image_of_mem f H1) theorem exists_of_mem_image {f : A → B} {s : finset A} {b : B} : b ∈ image f s → ∃a, a ∈ s ∧ f a = b := quot.induction_on s (take l, assume H : b ∈ erase_dup (list.map f (elt_of l)), exists_of_mem_map (mem_of_mem_erase_dup H)) theorem mem_image_iff (f : A → B) {s : finset A} {y : B} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y := iff.intro exists_of_mem_image (assume H, obtain x (H₁ : x ∈ s) (H₂ : f x = y), from H, mem_image H₁ H₂) theorem mem_image_eq (f : A → B) {s : finset A} {y : B} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y := propext (mem_image_iff f) theorem mem_image_of_mem_image_of_subset {f : A → B} {s t : finset A} {y : B} (H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t := obtain x (H3: x ∈ s) (H4 : f x = y), from exists_of_mem_image H1, have H5 : x ∈ t, from mem_of_subset_of_mem H2 H3, show y ∈ image f t, from mem_image H5 H4 theorem image_insert [h' : decidable_eq A] (f : A → B) (s : finset A) (a : A) : image f (insert a s) = insert (f a) (image f s) := ext (take y, iff.intro (assume H : y ∈ image f (insert a s), obtain x (H1l : x ∈ insert a s) (H1r :f x = y), from exists_of_mem_image H, have x = a ∨ x ∈ s, from eq_or_mem_of_mem_insert H1l, or.elim this (suppose x = a, have f a = y, from eq.subst this H1r, show y ∈ insert (f a) (image f s), from eq.subst this !mem_insert) (suppose x ∈ s, have f x ∈ image f s, from mem_image_of_mem f this, show y ∈ insert (f a) (image f s), from eq.subst H1r (mem_insert_of_mem _ this))) (suppose y ∈ insert (f a) (image f s), have y = f a ∨ y ∈ image f s, from eq_or_mem_of_mem_insert this, or.elim this (suppose y = f a, have f a ∈ image f (insert a s), from mem_image_of_mem f !mem_insert, show y ∈ image f (insert a s), from eq.subst (eq.symm `y = f a`) this) (suppose y ∈ image f s, show y ∈ image f (insert a s), from mem_image_of_mem_image_of_subset this !subset_insert))) lemma image_compose {C : Type} [deceqC : decidable_eq C] {f : B → C} {g : A → B} {s : finset A} : image (f∘g) s = image f (image g s) := ext (take z, iff.intro (suppose z ∈ image (f∘g) s, obtain x (Hx : x ∈ s) (Hgfx : f (g x) = z), from exists_of_mem_image this, by rewrite -Hgfx; apply mem_image_of_mem _ (mem_image_of_mem _ Hx)) (suppose z ∈ image f (image g s), obtain y (Hy : y ∈ image g s) (Hfy : f y = z), from exists_of_mem_image this, obtain x (Hx : x ∈ s) (Hgx : g x = y), from exists_of_mem_image Hy, mem_image Hx (by esimp; rewrite [Hgx, Hfy]))) lemma image_subset {a b : finset A} (f : A → B) (H : a ⊆ b) : f '[a] ⊆ f '[b] := subset_of_forall (take y, assume Hy : y ∈ f '[a], obtain x (Hx₁ : x ∈ a) (Hx₂ : f x = y), from exists_of_mem_image Hy, mem_image (mem_of_subset_of_mem H Hx₁) Hx₂) theorem image_union [h' : decidable_eq A] (f : A → B) (s t : finset A) : image f (s ∪ t) = image f s ∪ image f t := ext (take y, iff.intro (assume H : y ∈ image f (s ∪ t), obtain x [(xst : x ∈ s ∪ t) (fxy : f x = y)], from exists_of_mem_image H, or.elim (mem_or_mem_of_mem_union xst) (assume xs, mem_union_l (mem_image xs fxy)) (assume xt, mem_union_r (mem_image xt fxy))) (assume H : y ∈ image f s ∪ image f t, or.elim (mem_or_mem_of_mem_union H) (assume yifs : y ∈ image f s, obtain x [(xs : x ∈ s) (fxy : f x = y)], from exists_of_mem_image yifs, mem_image (mem_union_l xs) fxy) (assume yift : y ∈ image f t, obtain x [(xt : x ∈ t) (fxy : f x = y)], from exists_of_mem_image yift, mem_image (mem_union_r xt) fxy))) end image /- separation and set-builder notation -/ section sep variables {A : Type} [deceq : decidable_eq A] include deceq variables (p : A → Prop) [decp : decidable_pred p] (s : finset A) {x : A} include decp definition sep : finset A := quot.lift_on s (λl, to_finset_of_nodup (list.filter p (subtype.elt_of l)) (list.nodup_filter p (subtype.has_property l))) (λ l₁ l₂ u, quot.sound (perm.perm_filter u)) notation [priority finset.prio] `{` binder ` ∈ ` s ` | ` r:(scoped:1 p, sep p s) `}` := r theorem sep_empty : sep p ∅ = ∅ := rfl variables {p s} theorem of_mem_sep : x ∈ sep p s → p x := quot.induction_on s (take l, list.of_mem_filter) theorem mem_of_mem_sep : x ∈ sep p s → x ∈ s := quot.induction_on s (take l, list.mem_of_mem_filter) theorem mem_sep_of_mem {x : A} : x ∈ s → p x → x ∈ sep p s := quot.induction_on s (take l, list.mem_filter_of_mem) variables (p s) theorem mem_sep_iff : x ∈ sep p s ↔ x ∈ s ∧ p x := iff.intro (assume H, and.intro (mem_of_mem_sep H) (of_mem_sep H)) (assume H, mem_sep_of_mem (and.left H) (and.right H)) theorem mem_sep_eq : x ∈ sep p s = (x ∈ s ∧ p x) := propext !mem_sep_iff variable t : finset A theorem mem_sep_union_iff : x ∈ sep p (s ∪ t) ↔ x ∈ sep p s ∨ x ∈ sep p t := by rewrite [*mem_sep_iff, mem_union_iff, and.right_distrib] end sep section variables {A : Type} [deceqA : decidable_eq A] include deceqA theorem eq_sep_of_subset {s t : finset A} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := ext (take x, iff.intro (suppose x ∈ s, mem_sep_of_mem (mem_of_subset_of_mem ssubt this) this) (suppose x ∈ {x ∈ t | x ∈ s}, of_mem_sep this)) theorem mem_singleton_eq' (x a : A) : x ∈ '{a} = (x = a) := by rewrite [mem_insert_eq, mem_empty_eq, or_false] end /- set difference -/ section diff variables {A : Type} [deceq : decidable_eq A] include deceq definition diff (s t : finset A) : finset A := {x ∈ s | x ∉ t} infix [priority finset.prio] ` \ `:70 := diff theorem mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∈ s := mem_of_mem_sep H theorem not_mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∉ t := of_mem_sep H theorem mem_diff {s t : finset A} {x : A} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := mem_sep_of_mem H1 H2 theorem mem_diff_iff (s t : finset A) (x : A) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.intro (assume H, and.intro (mem_of_mem_diff H) (not_mem_of_mem_diff H)) (assume H, mem_diff (and.left H) (and.right H)) theorem mem_diff_eq (s t : finset A) (x : A) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := propext !mem_diff_iff theorem union_diff_cancel {s t : finset A} (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (suppose x ∈ s ∪ (t \ s), or.elim (mem_or_mem_of_mem_union this) (suppose x ∈ s, mem_of_subset_of_mem H this) (suppose x ∈ t \ s, mem_of_mem_diff this)) (suppose x ∈ t, decidable.by_cases (suppose x ∈ s, mem_union_left _ this) (suppose x ∉ s, mem_union_right _ (mem_diff `x ∈ t` this)))) theorem diff_union_cancel {s t : finset A} (H : s ⊆ t) : (t \ s) ∪ s = t := eq.subst !union.comm (!union_diff_cancel H) end diff /- set complement -/ section complement variables {A : Type} [deceqA : decidable_eq A] [h : fintype A] include deceqA h definition complement (s : finset A) : finset A := univ \ s prefix [priority finset.prio] - := complement theorem mem_complement {s : finset A} {x : A} (H : x ∉ s) : x ∈ -s := mem_diff !mem_univ H theorem not_mem_of_mem_complement {s : finset A} {x : A} (H : x ∈ -s) : x ∉ s := not_mem_of_mem_diff H theorem mem_complement_iff (s : finset A) (x : A) : x ∈ -s ↔ x ∉ s := iff.intro not_mem_of_mem_complement mem_complement section open classical theorem union_eq_comp_comp_inter_comp (s t : finset A) : s ∪ t = -(-s ∩ -t) := ext (take x, by rewrite [mem_union_iff, mem_complement_iff, mem_inter_iff, *mem_complement_iff, or_iff_not_and_not]) theorem inter_eq_comp_comp_union_comp (s t : finset A) : s ∩ t = -(-s ∪ -t) := ext (take x, by rewrite [mem_inter_iff, mem_complement_iff, mem_union_iff, *mem_complement_iff, and_iff_not_or_not]) end end complement /- all -/ section all variables {A : Type} definition all (s : finset A) (p : A → Prop) : Prop := quot.lift_on s (λ l, all (elt_of l) p) (λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !and.left_comm) p true) theorem all_empty (p : A → Prop) : all ∅ p = true := rfl theorem of_mem_of_all {p : A → Prop} {a : A} {s : finset A} : a ∈ s → all s p → p a := quot.induction_on s (λ l i h, list.of_mem_of_all i h) theorem forall_of_all {p : A → Prop} {s : finset A} (H : all s p) : ∀{a}, a ∈ s → p a := λ a H', of_mem_of_all H' H theorem all_of_forall {p : A → Prop} {s : finset A} : (∀a, a ∈ s → p a) → all s p := quot.induction_on s (λ l H, list.all_of_forall H) theorem all_iff_forall (p : A → Prop) (s : finset A) : all s p ↔ (∀a, a ∈ s → p a) := iff.intro forall_of_all all_of_forall definition decidable_all [instance] (p : A → Prop) [h : decidable_pred p] (s : finset A) : decidable (all s p) := quot.rec_on_subsingleton s (λ l, list.decidable_all p (elt_of l)) theorem all_implies {p q : A → Prop} {s : finset A} : all s p → (∀ x, p x → q x) → all s q := quot.induction_on s (λ l h₁ h₂, list.all_implies h₁ h₂) variable [h : decidable_eq A] include h theorem all_union {p : A → Prop} {s₁ s₂ : finset A} : all s₁ p → all s₂ p → all (s₁ ∪ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a₁ a₂, all_union a₁ a₂) theorem all_of_all_union_left {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₁ p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_left a) theorem all_of_all_union_right {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₂ p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_right a) theorem all_insert_of_all {p : A → Prop} {a : A} {s : finset A} : p a → all s p → all (insert a s) p := quot.induction_on s (λ l h₁ h₂, list.all_insert_of_all h₁ h₂) theorem all_erase_of_all {p : A → Prop} (a : A) {s : finset A}: all s p → all (erase a s) p := quot.induction_on s (λ l h, list.all_erase_of_all a h) theorem all_inter_of_all_left {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₁ p → all (s₁ ∩ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_inter_of_all_left _ h) theorem all_inter_of_all_right {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₂ p → all (s₁ ∩ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_inter_of_all_right _ h) theorem subset_iff_all (s t : finset A) : s ⊆ t ↔ all s (λ x, x ∈ t) := iff.intro (suppose s ⊆ t, all_of_forall (take x, suppose x ∈ s, mem_of_subset_of_mem `s ⊆ t` `x ∈ s`)) (suppose all s (λ x, x ∈ t), subset_of_forall (take x, suppose x ∈ s, of_mem_of_all `x ∈ s` `all s (λ x, x ∈ t)`)) definition decidable_subset [instance] (s t : finset A) : decidable (s ⊆ t) := decidable_of_decidable_of_iff _ (iff.symm !subset_iff_all) end all /- any -/ section any variables {A : Type} definition any (s : finset A) (p : A → Prop) : Prop := quot.lift_on s (λ l, any (elt_of l) p) (λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !or.left_comm) p false) theorem any_empty (p : A → Prop) : any ∅ p = false := rfl theorem exists_of_any {p : A → Prop} {s : finset A} : any s p → ∃a, a ∈ s ∧ p a := quot.induction_on s (λ l H, list.exists_of_any H) theorem any_of_mem {p : A → Prop} {s : finset A} {a : A} : a ∈ s → p a → any s p := quot.induction_on s (λ l H1 H2, list.any_of_mem H1 H2) theorem any_of_exists {p : A → Prop} {s : finset A} (H : ∃a, a ∈ s ∧ p a) : any s p := obtain a H₁ H₂, from H, any_of_mem H₁ H₂ theorem any_iff_exists (p : A → Prop) (s : finset A) : any s p ↔ (∃a, a ∈ s ∧ p a) := iff.intro exists_of_any any_of_exists theorem any_of_insert [h : decidable_eq A] {p : A → Prop} (s : finset A) {a : A} (H : p a) : any (insert a s) p := any_of_mem (mem_insert a s) H theorem any_of_insert_right [h : decidable_eq A] {p : A → Prop} {s : finset A} (a : A) (H : any s p) : any (insert a s) p := obtain b (H₁ : b ∈ s) (H₂ : p b), from exists_of_any H, any_of_mem (mem_insert_of_mem a H₁) H₂ definition decidable_any [instance] (p : A → Prop) [h : decidable_pred p] (s : finset A) : decidable (any s p) := quot.rec_on_subsingleton s (λ l, list.decidable_any p (elt_of l)) end any section product variables {A B : Type} definition product (s₁ : finset A) (s₂ : finset B) : finset (A × B) := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (product (elt_of l₁) (elt_of l₂)) (nodup_product (has_property l₁) (has_property l₂))) (λ v₁ v₂ w₁ w₂ p₁ p₂, begin apply @quot.sound, apply perm_product p₁ p₂ end) infix [priority finset.prio] * := product theorem empty_product (s : finset B) : @empty A * s = ∅ := quot.induction_on s (λ l, rfl) theorem mem_product {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : a ∈ s₁ → b ∈ s₂ → (a, b) ∈ s₁ * s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i₁ i₂, list.mem_product i₁ i₂) theorem mem_of_mem_product_left {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : (a, b) ∈ s₁ * s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_product_left i) theorem mem_of_mem_product_right {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : (a, b) ∈ s₁ * s₂ → b ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_product_right i) theorem product_empty (s : finset A) : s * @empty B = ∅ := ext (λ p, match p with | (a, b) := iff.intro (λ i, absurd (mem_of_mem_product_right i) !not_mem_empty) (λ i, absurd i !not_mem_empty) end) end product /- powerset -/ section powerset variables {A : Type} [deceqA : decidable_eq A] include deceqA section list_powerset open list definition list_powerset : list A → finset (finset A) | [] := '{∅} | (a :: l) := list_powerset l ∪ image (insert a) (list_powerset l) end list_powerset private theorem image_insert_comm (a b : A) (s : finset (finset A)) : image (insert a) (image (insert b) s) = image (insert b) (image (insert a) s) := have aux' : ∀ a b : A, ∀ x : finset A, x ∈ image (insert a) (image (insert b) s) → x ∈ image (insert b) (image (insert a) s), from begin intros [a, b, x, H], cases (exists_of_mem_image H) with [y, Hy], cases Hy with [Hy1, Hy2], cases (exists_of_mem_image Hy1) with [z, Hz], cases Hz with [Hz1, Hz2], substvars, rewrite insert.comm, repeat (apply mem_image_of_mem), assumption end, ext (take x, iff.intro (aux' a b x) (aux' b a x)) theorem list_powerset_eq_list_powerset_of_perm {l₁ l₂ : list A} (p : l₁ ~ l₂) : list_powerset l₁ = list_powerset l₂ := perm.induction_on p rfl (λ x l₁ l₂ p ih, by rewrite [↑list_powerset, ih]) (λ x y l, by rewrite [↑list_powerset, ↑list_powerset, *image_union, image_insert_comm, *union.assoc, union.left_comm (finset.image (finset.insert x) _)]) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) definition powerset (s : finset A) : finset (finset A) := quot.lift_on s (λ l, list_powerset (elt_of l)) (λ l₁ l₂ p, list_powerset_eq_list_powerset_of_perm p) prefix [priority finset.prio] `𝒫`:100 := powerset theorem powerset_empty : 𝒫 (∅ : finset A) = '{∅} := rfl theorem powerset_insert {a : A} {s : finset A} : a ∉ s → 𝒫 (insert a s) = 𝒫 s ∪ image (insert a) (𝒫 s) := quot.induction_on s (λ l, assume H : a ∉ quot.mk l, calc 𝒫 (insert a (quot.mk l)) = list_powerset (list.insert a (elt_of l)) : rfl ... = list_powerset (#list a :: elt_of l) : by rewrite [list.insert_eq_of_not_mem H] ... = 𝒫 (quot.mk l) ∪ image (insert a) (𝒫 (quot.mk l)) : rfl) theorem mem_powerset_iff_subset (s : finset A) : ∀ x, x ∈ 𝒫 s ↔ x ⊆ s := begin induction s with a s nains ih, intro x, rewrite powerset_empty, show x ∈ '{∅} ↔ x ⊆ ∅, by rewrite [mem_singleton_eq', subset_empty_iff], intro x, rewrite [powerset_insert nains, mem_union_iff, ih, mem_image_iff], exact (iff.intro (assume H, or.elim H (suppose x ⊆ s, subset.trans this !subset_insert) (suppose ∃ y, y ∈ 𝒫 s ∧ insert a y = x, obtain y [yps iay], from this, show x ⊆ insert a s, begin rewrite [-iay], apply insert_subset_insert, rewrite -ih, apply yps end)) (assume H : x ⊆ insert a s, assert H' : erase a x ⊆ s, from erase_subset_of_subset_insert H, decidable.by_cases (suppose a ∈ x, or.inr (exists.intro (erase a x) (and.intro (show erase a x ∈ 𝒫 s, by rewrite ih; apply H') (show insert a (erase a x) = x, from insert_erase this)))) (suppose a ∉ x, or.inl (show x ⊆ s, by rewrite [(erase_eq_of_not_mem this) at H']; apply H')))) end theorem subset_of_mem_powerset {s t : finset A} (H : s ∈ 𝒫 t) : s ⊆ t := iff.mp (mem_powerset_iff_subset t s) H theorem mem_powerset_of_subset {s t : finset A} (H : s ⊆ t) : s ∈ 𝒫 t := iff.mpr (mem_powerset_iff_subset t s) H theorem empty_mem_powerset (s : finset A) : ∅ ∈ 𝒫 s := mem_powerset_of_subset (empty_subset s) end powerset end finset
1f65df8f2ce1bde54cf5c8e457c06287f8971031
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/matrix/charpoly/finite_field.lean
429b18e1a6f644b74e198ae6deb4083a5fc1de74
[ "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
2,347
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import linear_algebra.matrix.charpoly.coeff import field_theory.finite.basic import data.matrix.char_p /-! # Results on characteristic polynomials and traces over finite fields. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ noncomputable theory open polynomial matrix open_locale polynomial variables {n : Type*} [decidable_eq n] [fintype n] @[simp] lemma finite_field.matrix.charpoly_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) : (M ^ (fintype.card K)).charpoly = M.charpoly := begin casesI (is_empty_or_nonempty n).symm, { cases char_p.exists K with p hp, letI := hp, rcases finite_field.card K p with ⟨⟨k, kpos⟩, ⟨hp, hk⟩⟩, haveI : fact p.prime := ⟨hp⟩, dsimp at hk, rw hk at *, apply (frobenius_inj K[X] p).iterate k, repeat { rw iterate_frobenius, rw ← hk }, rw ← finite_field.expand_card, unfold charpoly, rw [alg_hom.map_det, ← coe_det_monoid_hom, ← (det_monoid_hom : matrix n n K[X] →* K[X]).map_pow], apply congr_arg det, refine mat_poly_equiv.injective _, rw [alg_equiv.map_pow, mat_poly_equiv_charmatrix, hk, sub_pow_char_pow_of_commute, ← C_pow], { exact (id (mat_poly_equiv_eq_X_pow_sub_C (p ^ k) M) : _) }, { exact (C M).commute_X } }, { exact congr_arg _ (subsingleton.elim _ _), }, end @[simp] lemma zmod.charpoly_pow_card {p : ℕ} [fact p.prime] (M : matrix n n (zmod p)) : (M ^ p).charpoly = M.charpoly := by { have h := finite_field.matrix.charpoly_pow_card M, rwa zmod.card at h, } lemma finite_field.trace_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) : trace (M ^ (fintype.card K)) = trace M ^ (fintype.card K) := begin casesI is_empty_or_nonempty n, { simp [zero_pow fintype.card_pos, matrix.trace], }, rw [matrix.trace_eq_neg_charpoly_coeff, matrix.trace_eq_neg_charpoly_coeff, finite_field.matrix.charpoly_pow_card, finite_field.pow_card] end lemma zmod.trace_pow_card {p : ℕ} [fact p.prime] (M : matrix n n (zmod p)) : trace (M ^ p) = (trace M)^p := by { have h := finite_field.trace_pow_card M, rwa zmod.card at h, }
80ad05fbfd64bd90f73fea46f04a338b7ecdda42
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/category_theory/products/basic.lean
ebc352011d5c8d01009ec2c571860edf4f38a24b
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
5,750
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.eq_to_hom namespace category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation section variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] /-- `prod C D` gives the cartesian product of two categories. See https://stacks.math.columbia.edu/tag/001K. -/ instance prod : category.{max v₁ v₂} (C × D) := { hom := λ X Y, ((X.1) ⟶ (Y.1)) × ((X.2) ⟶ (Y.2)), id := λ X, ⟨ 𝟙 (X.1), 𝟙 (X.2) ⟩, comp := λ _ _ _ f g, (f.1 ≫ g.1, f.2 ≫ g.2) } -- rfl lemmas for category.prod @[simp] lemma prod_id (X : C) (Y : D) : 𝟙 (X, Y) = (𝟙 X, 𝟙 Y) := rfl @[simp] lemma prod_comp {P Q R : C} {S T U : D} (f : (P, S) ⟶ (Q, T)) (g : (Q, T) ⟶ (R, U)) : f ≫ g = (f.1 ≫ g.1, f.2 ≫ g.2) := rfl @[simp] lemma prod_id_fst (X : prod C D) : prod.fst (𝟙 X) = 𝟙 X.fst := rfl @[simp] lemma prod_id_snd (X : prod C D) : prod.snd (𝟙 X) = 𝟙 X.snd := rfl @[simp] lemma prod_comp_fst {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).1 = f.1 ≫ g.1 := rfl @[simp] lemma prod_comp_snd {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).2 = f.2 ≫ g.2 := rfl end section variables (C : Type u₁) [category.{v₁} C] (D : Type u₁) [category.{v₁} D] /-- `prod.category.uniform C D` is an additional instance specialised so both factors have the same universe levels. This helps typeclass resolution. -/ instance uniform_prod : category (C × D) := category_theory.prod C D end -- Next we define the natural functors into and out of product categories. For now this doesn't -- address the universal properties. namespace prod /-- `sectl C Z` is the functor `C ⥤ C × D` given by `X ↦ (X, Z)`. -/ @[simps] def sectl (C : Type u₁) [category.{v₁} C] {D : Type u₂} [category.{v₂} D] (Z : D) : C ⥤ C × D := { obj := λ X, (X, Z), map := λ X Y f, (f, 𝟙 Z) } /-- `sectr Z D` is the functor `D ⥤ C × D` given by `Y ↦ (Z, Y)` . -/ @[simps] def sectr {C : Type u₁} [category.{v₁} C] (Z : C) (D : Type u₂) [category.{v₂} D] : D ⥤ C × D := { obj := λ X, (Z, X), map := λ X Y f, (𝟙 Z, f) } variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] /-- `fst` is the functor `(X, Y) ↦ X`. -/ @[simps] def fst : C × D ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.1 } /-- `snd` is the functor `(X, Y) ↦ Y`. -/ @[simps] def snd : C × D ⥤ D := { obj := λ X, X.2, map := λ X Y f, f.2 } /-- The functor swapping the factors of a cartesian product of categories, `C × D ⥤ D × C`. -/ @[simps] def swap : C × D ⥤ D × C := { obj := λ X, (X.2, X.1), map := λ _ _ f, (f.2, f.1) } /-- Swapping the factors of a cartesion product of categories twice is naturally isomorphic to the identity functor. -/ @[simps] def symmetry : swap C D ⋙ swap D C ≅ 𝟭 (C × D) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } /-- The equivalence, given by swapping factors, between `C × D` and `D × C`. -/ @[simps] def braiding : C × D ≌ D × C := equivalence.mk (swap C D) (swap D C) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) instance swap_is_equivalence : is_equivalence (swap C D) := (by apply_instance : is_equivalence (braiding C D).functor) end prod section variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] /-- The "evaluation at `X`" functor, such that `(evaluation.obj X).obj F = F.obj X`, which is functorial in both `X` and `F`. -/ @[simps] def evaluation : C ⥤ (C ⥤ D) ⥤ D := { obj := λ X, { obj := λ F, F.obj X, map := λ F G α, α.app X, }, map := λ X Y f, { app := λ F, F.map f, naturality' := λ F G α, eq.symm (α.naturality f) } } /-- The "evaluation of `F` at `X`" functor, as a functor `C × (C ⥤ D) ⥤ D`. -/ @[simps] def evaluation_uncurried : C × (C ⥤ D) ⥤ D := { obj := λ p, p.2.obj p.1, map := λ x y f, (x.2.map f.1) ≫ (f.2.app y.1), map_comp' := λ X Y Z f g, begin cases g, cases f, cases Z, cases Y, cases X, simp only [prod_comp, nat_trans.comp_app, functor.map_comp, category.assoc], rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app, category.assoc, nat_trans.naturality], end } end variables {A : Type u₁} [category.{v₁} A] {B : Type u₂} [category.{v₂} B] {C : Type u₃} [category.{v₃} C] {D : Type u₄} [category.{v₄} D] namespace functor /-- The cartesian product of two functors. -/ @[simps] def prod (F : A ⥤ B) (G : C ⥤ D) : A × C ⥤ B × D := { obj := λ X, (F.obj X.1, G.obj X.2), map := λ _ _ f, (F.map f.1, G.map f.2) } /- Because of limitations in Lean 3's handling of notations, we do not setup a notation `F × G`. You can use `F.prod G` as a "poor man's infix", or just write `functor.prod F G`. -/ end functor namespace nat_trans /-- The cartesian product of two natural transformations. -/ @[simps] def prod {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) : F.prod H ⟶ G.prod I := { app := λ X, (α.app X.1, β.app X.2), naturality' := λ X Y f, begin cases X, cases Y, simp only [functor.prod_map, prod.mk.inj_iff, prod_comp], split; rw naturality end } /- Again, it is inadvisable in Lean 3 to setup a notation `α × β`; use instead `α.prod β` or `nat_trans.prod α β`. -/ end nat_trans end category_theory
caa291221cb0fff2e6e282cd9d6e0bbae7985b6f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/number_theory/basic.lean
90457329569749b5992946e3a8b514b7bd7c3bc3
[]
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
526
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.geom_sum import Mathlib.ring_theory.ideal.basic import Mathlib.PostPort universes u_1 namespace Mathlib theorem dvd_sub_pow_of_dvd_sub {R : Type u_1} [comm_ring R] {p : ℕ} {a : R} {b : R} (h : ↑p ∣ a - b) (k : ℕ) : ↑p ^ (k + 1) ∣ a ^ p ^ k - b ^ p ^ k := sorry
b883ec210dfed16bfa75320dc01d20762f5e98f7
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/elab_bug1.lean
0afe714e73a0e7a6019c6cabca5526790df7a40f
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
2,669
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Microsoft Corporation. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Jeremy Avigad ---------------------------------------------------------------------------------------------------- import logic open eq open function namespace congruence -- TODO: move this somewhere else definition reflexive {T : Type} (R : T → T → Prop) : Prop := ∀x, R x x -- Congruence classes for unary and binary functions -- ------------------------------------------------- inductive congruence [class] {T1 : Type} {T2 : Type} (R1 : T1 → T1 → Prop) (R2 : T2 → T2 → Prop) (f : T1 → T2) : Prop := mk : (∀x y : T1, R1 x y → R2 (f x) (f y)) → congruence R1 R2 f -- to trigger class inference theorem congr_app {T1 : Type} {T2 : Type} (R1 : T1 → T1 → Prop) (R2 : T2 → T2 → Prop) (f : T1 → T2) {C : congruence R1 R2 f} {x y : T1} : R1 x y → R2 (f x) (f y) := congruence.rec id C x y -- General tools to build instances -- -------------------------------- theorem congr_trivial [instance] {T : Type} (R : T → T → Prop) : congruence R R id := congruence.mk (take x y H, H) theorem congr_const {T2 : Type} (R2 : T2 → T2 → Prop) (H : reflexive R2) : ∀(T1 : Type) (R1 : T1 → T1 → Prop) (c : T2), congruence R1 R2 (const T1 c) := take T1 R1 c, congruence.mk (take x y H1, H c) -- congruences for logic theorem congr_const_iff [instance] (T1 : Type) (R1 : T1 → T1 → Prop) (c : Prop) : congruence R1 iff (const T1 c) := congr_const iff iff.refl T1 R1 c theorem congr_or [instance] (T : Type) (R : T → T → Prop) (f1 f2 : T → Prop) [H1 : congruence R iff f1] [H2 : congruence R iff f2] : congruence R iff (λx, f1 x ∨ f2 x) := sorry theorem congr_implies [instance] (T : Type) (R : T → T → Prop) (f1 f2 : T → Prop) [H1 : congruence R iff f1] [H2 : congruence R iff f2] : congruence R iff (λx, f1 x → f2 x) := sorry theorem congr_iff [instance] (T : Type) (R : T → T → Prop) (f1 f2 : T → Prop) [H1 : congruence R iff f1] [H2 : congruence R iff f2] : congruence R iff (λx, f1 x ↔ f2 x) := sorry theorem congr_not [instance] (T : Type) (R : T → T → Prop) (f : T → Prop) [H : congruence R iff f] : congruence R iff (λx, ¬ f x) := sorry theorem subst_iff {T : Type} {R : T → T → Prop} {P : T → Prop} [C : congruence R iff P] {a b : T} (H : R a b) (H1 : P a) : P b := -- iff_mp_left (congruence.rec id C a b H) H1 iff.elim_left (@congr_app _ _ R iff P C a b H) H1 end congruence
3527b103000496c4130dd151ac544f92a5b05eb9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/real/ennreal.lean
d733c10d3bff9e61905bdefcc9d20a78681f5556
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
62,462
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import data.real.nnreal import data.set.intervals /-! # Extended non-negative reals We define `ennreal = ℝ≥0∞ := with_no ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and a linear order on `ℝ≥0∞` and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`. ## Main definitions * `ℝ≥0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ℝ≥0∞` into a canonically ordered commutative semiring of characteristic zero. * Coercions to/from other types: - coercion `ℝ≥0 → ℝ≥0∞` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ℝ≥0∞`, and Lean will apply `coe` automatically; - `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`; - `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ennreal.of_real := coe ∘ real.to_nnreal` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ℝ≥0∞ // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `can_lift ℝ≥0∞ ℝ≥0` instance, so one of the ways to prove theorems about an `ℝ≥0∞` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ℝ≥0∞) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0∞`: the type of the extended nonnegative real numbers; * `ℝ≥0`: the type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`; * `∞`: a localized notation in `ℝ≥0∞` for `⊤ : ℝ≥0∞`. -/ noncomputable theory open classical set open_locale classical big_operators nnreal variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered, derive nontrivial] def ennreal := with_top ℝ≥0 localized "notation `ℝ≥0∞` := ennreal" in ennreal localized "notation `∞` := (⊤ : ennreal)" in ennreal instance : linear_ordered_add_comm_monoid ℝ≥0∞ := { .. ennreal.canonically_ordered_comm_semiring, .. ennreal.complete_linear_order } namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} instance : inhabited ℝ≥0∞ := ⟨0⟩ instance : has_coe ℝ≥0 ℝ≥0∞ := ⟨ option.some ⟩ instance : can_lift ℝ≥0∞ ℝ≥0 := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ℝ≥0∞) = ∞ := rfl @[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ℝ≥0∞ → ℝ≥0 | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ℝ≥0∞) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ℝ≥0∞ := coe (real.to_nnreal r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ℝ≥0∞).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ℝ≥0∞}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ℝ≥0∞} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, real.coe_to_nnreal _ h] lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl lemma coe_to_nnreal_le_self : ∀{a:ℝ≥0∞}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : ℝ≥0) : (r : ℝ≥0∞) = ennreal.of_real r := by { rw [ennreal.of_real, real.to_nnreal], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe ℝ≥0 ℝ≥0∞ _ (⟨x, h⟩ : ℝ≥0) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ℝ≥0∞) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ℝ≥0∞) := rfl @[simp] lemma to_real_nonneg {a : ℝ≥0∞} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ℝ≥0∞).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ℝ≥0∞).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : ℝ≥0) : (r : ℝ≥0∞).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ℝ≥0∞).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ℝ≥0∞).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ℝ≥0∞) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ℝ≥0∞} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ℝ≥0∞ → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma forall_ne_top {p : ℝ≥0∞ → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r := option.ball_ne_none lemma exists_ne_top {p : ℝ≥0∞ → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := option.bex_ne_none lemma to_nnreal_eq_zero_iff (x : ℝ≥0∞) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:ℝ≥0) = (0:ℝ≥0∞) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ℝ≥0∞) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ℝ≥0∞) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ℝ≥0∞) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ℝ≥0∞) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ℝ≥0∞) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ℝ≥0∞) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : ℝ≥0 → ℝ≥0∞) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ℝ≥0∞) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ℝ≥0∞) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ℝ≥0∞) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ℝ≥0∞) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ℝ≥0∞) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ℝ≥0∞) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ℝ≥0∞) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ℝ≥0∞) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ℝ≥0∞) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ℝ≥0∞) = bit1 r := by simp [bit1] lemma coe_two : ((2:ℝ≥0) : ℝ≥0∞) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ℝ≥0∞) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1 : ℝ≥0∞) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _) @[simp] lemma zero_lt_two : (0:ℝ≥0∞) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ℝ≥0∞) ≠ 0 := (ne_of_lt zero_lt_two).symm lemma two_ne_top : (2:ℝ≥0∞) ≠ ∞ := coe_two ▸ coe_ne_top /-- The set of numbers in `ℝ≥0∞` that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe } lemma cinfi_ne_top [has_Inf α] (f : ℝ≥0∞ → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x := eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl lemma infi_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x := by rw [infi_subtype', cinfi_ne_top] lemma csupr_ne_top [has_Sup α] (f : ℝ≥0∞ → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x := @cinfi_ne_top (order_dual α) _ _ lemma supr_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x := @infi_ne_top (order_dual α) _ _ lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} : (⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨λ r, inf_le_of_left_le $ infi_le _ _, inf_le_right⟩) lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} : (⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @infi_ennreal (order_dual α) _ _ @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ℝ≥0∞` as a `ring_hom`. -/ def of_nnreal_hom : ℝ≥0 →+* ℝ≥0∞ := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl section actions /-- A `mul_action` over `ℝ≥0∞` restricts to a `mul_action` over `ℝ≥0`. -/ instance {M : Type*} [mul_action ℝ≥0∞ M] : mul_action ℝ≥0 M := mul_action.comp_hom M of_nnreal_hom.to_monoid_hom lemma smul_def {M : Type*} [mul_action ℝ≥0∞ M] (c : ℝ≥0) (x : M) : c • x = (c : ℝ≥0∞) • x := rfl instance {M N : Type*} [mul_action ℝ≥0∞ M] [mul_action ℝ≥0∞ N] [has_scalar M N] [is_scalar_tower ℝ≥0∞ M N] : is_scalar_tower ℝ≥0 M N := { smul_assoc := λ r, (smul_assoc (r : ℝ≥0∞) : _)} instance smul_comm_class_left {M N : Type*} [mul_action ℝ≥0∞ N] [has_scalar M N] [smul_comm_class ℝ≥0∞ M N] : smul_comm_class ℝ≥0 M N := { smul_comm := λ r, (smul_comm (r : ℝ≥0∞) : _)} instance smul_comm_class_right {M N : Type*} [mul_action ℝ≥0∞ N] [has_scalar M N] [smul_comm_class M ℝ≥0∞ N] : smul_comm_class M ℝ≥0 N := { smul_comm := λ m r, (smul_comm m (r : ℝ≥0∞) : _)} /-- A `distrib_mul_action` over `ℝ≥0∞` restricts to a `distrib_mul_action` over `ℝ≥0`. -/ instance {M : Type*} [add_monoid M] [distrib_mul_action ℝ≥0∞ M] : distrib_mul_action ℝ≥0 M := distrib_mul_action.comp_hom M of_nnreal_hom.to_monoid_hom /-- A `module` over `ℝ≥0∞` restricts to a `module` over `ℝ≥0`. -/ instance {M : Type*} [add_comm_monoid M] [module ℝ≥0∞ M] : module ℝ≥0 M := module.comp_hom M of_nnreal_hom /-- An `algebra` over `ℝ≥0∞` restricts to an `algebra` over `ℝ≥0`. -/ instance {A : Type*} [semiring A] [algebra ℝ≥0∞ A] : algebra ℝ≥0 A := { smul := (•), commutes' := λ r x, by simp [algebra.commutes], smul_def' := λ r x, by simp [←algebra.smul_def (r : ℝ≥0∞) x, smul_def], to_ring_hom := ((algebra_map ℝ≥0∞ A).comp (of_nnreal_hom : ℝ≥0 →+* ℝ≥0∞)) } -- verify that the above produces instances we might care about example : algebra ℝ≥0 ℝ≥0∞ := by apply_instance example : distrib_mul_action (units ℝ≥0) ℝ≥0∞ := by apply_instance end actions @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ≥0∞) = s.indicator (λ x, f x) a := (of_nnreal_hom : ℝ≥0 →+ ℝ≥0∞).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ℝ≥0∞) = r^n := of_nnreal_hom.map_pow r n @[simp] lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top @[simp] lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top lemma to_nnreal_add {r₁ r₂ : ℝ≥0∞} (h₁ : r₁ < ∞) (h₂ : r₂ < ∞) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ℝ≥0∞ _ _ ∞, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma not_lt_top {x : ℝ≥0∞} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_lt_top : a < ∞ → b < ∞ → a * b < ∞ := with_top.mul_lt_top lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using mul_lt_top lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a ≠ ∞ := by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 } lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b ≠ ∞ := ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma lt_top_of_mul_lt_top_left (h : a * b < ∞) (hb : b ≠ 0) : a < ∞ := by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb } lemma lt_top_of_mul_lt_top_right (h : a * b < ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha lemma mul_lt_top_iff {a b : ℝ≥0∞} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 := begin split, { intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha, exact ⟨lt_top_of_mul_lt_top_left h hb, lt_top_of_mul_lt_top_right h ha⟩ }, { rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha hb, simp, simp] } end lemma mul_self_lt_top_iff {a : ℝ≥0∞} : a * a < ⊤ ↔ a < ⊤ := by { rw [ennreal.mul_lt_top_iff, and_self, or_self, or_iff_left_iff_imp], rintro rfl, norm_num } @[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, by { rw pow_succ at o, exact (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left } lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ℝ≥0∞) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ℝ≥0∞) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ℝ≥0∞) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ℝ≥0∞) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ℝ≥0∞) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ℝ≥0∞) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ℝ≥0∞) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ℝ≥0∞) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : ℕ) : ((n : ℝ≥0) : ℝ≥0∞) = n := with_top.coe_nat n @[simp] lemma of_real_coe_nat (n : ℕ) : ennreal.of_real n = n := by simp [ennreal.of_real] @[simp] lemma nat_ne_top (n : ℕ) : (n : ℝ≥0∞) ≠ ∞ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : ℕ) : ∞ ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe lemma to_real_le_coe_of_le_coe {a : ℝ≥0∞} {b : ℝ≥0} (h : a ≤ b) : a.to_real ≤ b := show ↑a.to_nnreal ≤ ↑b, begin have : ↑a.to_nnreal = a := ennreal.coe_to_nnreal (lt_of_le_of_lt h coe_lt_top).ne, rw ← this at h, exact_mod_cast h end @[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup (λ x, (f x : ℝ≥0∞)) := finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [nonpos_iff_eq_zero.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [pos_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ∞ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ∞ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ∞) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_pos_le_add : ∀{a b : ℝ≥0∞}, (∀ε:ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_pos_le_add h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < real.to_nnreal q ∧ (real.to_nnreal q:ℝ≥0∞) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases exists_between h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ℝ≥0∞) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ℝ≥0∞) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_self_add) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : ℝ≥0 := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : real.to_nnreal c = d, by { rw [← nnreal.coe_eq, real.coe_to_nnreal _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ℝ≥0∞) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ℝ≥0∞) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[simp, norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ℝ≥0∞) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ℝ≥0∞) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ℝ≥0∞) := λ _ _, coe_nat_lt_coe_nat.2 @[simp, norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ℝ≥0∞) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ℝ≥0∞ := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ℝ≥0∞} (h : r ≠ ∞) : ∃n:ℕ, r < n := begin lift r to ℝ≥0 using h, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin lift a to ℝ≥0 using ne_top_of_lt ac, lift b to ℝ≥0 using ne_top_of_lt bd, cases c, { simp }, cases d, { simp }, simp only [← coe_add, some_eq_coe, coe_lt_coe] at *, exact add_lt_add ac bd end @[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ℝ≥0∞) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ℝ≥0∞) = max r p := coe_mono.map_max lemma le_of_top_imp_top_of_to_nnreal_le {a b : ℝ≥0∞} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) : a ≤ b := begin by_cases ha : a = ⊤, { rw h ha, exact le_top, }, by_cases hb : b = ⊤, { rw hb, exact le_top, }, rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe], exact h_nnreal ha hb, end end order section complete_lattice lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ℝ≥0∞) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ℝ≥0∞) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ℝ≥0∞} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set ℝ≥0} : ↑r ∈ upper_bounds ((coe : ℝ≥0 → ℝ≥0∞) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} end complete_lattice section mul @[mono] lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul @[mono] lemma mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d := begin rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩, lift a to ℝ≥0 using ne_top_of_lt aa', rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩, lift b to ℝ≥0 using ne_top_of_lt bb', norm_cast at *, calc ↑(a * b) < ↑(a' * b') : coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa')) ... = ↑a' * ↑b' : coe_mul ... ≤ c * d : mul_le_mul a'c.le b'd.le end lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (pos_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end mul section sub instance : has_sub ℝ≥0∞ := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ℝ≥0∞) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ℝ≥0∞) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ℝ≥0∞}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ℝ≥0∞}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right h _) (assume h : a ≤ c + b, Inf_le h) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_self : a ≠ ∞ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, pos_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact pos_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ℝ≥0∞) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_self_add @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _ ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ℝ≥0∞} (ha : a < ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top {s : finset α} {f : α → ℝ≥0∞} (h : ∀a∈s, f a < ∞) : (∏ a in s, f a) < ∞ := with_top.prod_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ℝ≥0∞} : (∀a∈s, f a < ∞) → ∑ a in s, f a < ∞ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ℝ≥0∞} : ∑ a in s, f a < ∞ ↔ (∀a∈s, f a < ∞) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ℝ≥0∞} : (∑ x in s, f x) = ∞ ↔ (∃a∈s, f a = ∞) := with_top.sum_eq_top_iff /-- seeing `ℝ≥0∞` as `ℝ≥0` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀a∈s, f a < ∞) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, exact (coe_to_nnreal (hf x hx).ne).symm }, { exact (sum_lt_top hf).ne } end /-- seeing `ℝ≥0∞` as `real` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀a∈s, f a < ∞) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } lemma of_real_sum_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ennreal.of_real (∑ i in s, f i) = ∑ i in s, ennreal.of_real (f i) := begin simp_rw [ennreal.of_real, ←coe_finset_sum, coe_eq_coe], exact real.to_nnreal_sum_of_nonneg hf, end end sum section interval variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ∞ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ℝ≥0∞ := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : div_inv_monoid ℝ≥0∞ := { inv := has_inv.inv, .. (infer_instance : monoid ℝ≥0∞) } @[simp] lemma inv_zero : (0 : ℝ≥0∞)⁻¹ = ∞ := show Inf {b : ℝ≥0∞ | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : ∞⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ℝ≥0∞) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ℝ≥0∞) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, inv_zero, coe_zero, le_top] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:ℝ≥0):ℝ≥0∞) = 2⁻¹ := by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ℝ≥0∞) = p / r := by rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ℝ≥0∞)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 inv_one @[simp] lemma div_one {a : ℝ≥0∞} : a / 1 = a := by rw [div_eq_mul_inv, inv_one, mul_one] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv (pow_ne_zero _ h), ← inv_pow', coe_pow] end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ℝ≥0∞, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ℝ≥0∞, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_lt_top {x : ℝ≥0∞} : x⁻¹ < ∞ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] } lemma div_lt_top {x y : ℝ≥0∞} (h1 : x < ∞) (h2 : 0 < y) : x / y < ∞ := mul_lt_top h1 (inv_lt_top.mpr h2) @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := pos_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [pos_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_le_one : a⁻¹ ≤ 1 ↔ 1 ≤ a := inv_le_iff_inv_le.trans $ by rw inv_one lemma one_le_inv : 1 ≤ a⁻¹ ↔ a ≤ 1 := le_inv_iff_le_inv.trans $ by rw inv_one @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] lemma pow_le_pow_of_le_one {n m : ℕ} (ha : a ≤ 1) (h : n ≤ m) : a ^ m ≤ a ^ n := begin rw [← @inv_inv a, ← ennreal.inv_pow, ← @ennreal.inv_pow a⁻¹, inv_le_inv], exact pow_le_pow (one_le_inv.2 ha) h end @[simp] lemma div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero] @[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_eq_mul_inv, top_mul] lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by { lift a to ℝ≥0 using h, exact top_div_coe } lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [top_div_of_ne_top, *] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) := by simp [div_eq_mul_inv, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ℝ≥0∞) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_eq_mul_inv, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ∞, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_eq_mul_inv], refine (le_div_iff_mul_le _ _).symm; simpa end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ∞, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_eq_mul_inv, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := begin lift a to ℝ≥0 using ht, norm_cast at *, exact mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ℝ≥0∞} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y := begin refine le_of_forall_ge_of_dense (λ r hr, _), lift r to ℝ≥0 using ne_top_of_lt hr, exact h r hr end lemma eq_top_of_forall_nnreal_le {x : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r ≤ x) : x = ∞ := top_unique $ le_of_forall_nnreal_lt $ λ r hr, h r lemma div_add_div_same {a b c : ℝ≥0∞} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_eq_mul_inv, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma mul_div_le : a * (b / a) ≤ b := begin by_cases h0 : a = 0, { simp [h0] }, by_cases hI : a = ∞, { simp [hI] }, rw mul_div_cancel' h0 hI, exact le_refl b end lemma inv_two_add_inv_two : (2:ℝ≥0∞)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_eq_mul_inv, div_self two_ne_zero two_ne_top] lemma add_halves (a : ℝ≥0∞) : a / 2 + a / 2 = a := by rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_eq_mul_inv] @[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [pos_iff_ne_zero, not_or_distrib] lemma half_pos {a : ℝ≥0∞} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ℝ≥0∞) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ℝ≥0∞} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a := begin lift a to ℝ≥0 using ht, have h : (2 : ℝ≥0∞) = ((2 : ℝ≥0) : ℝ≥0∞), from rfl, have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to ℝ≥0 using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end @[simp] lemma one_sub_inv_two : (1:ℝ≥0∞) - 2⁻¹ = 2⁻¹ := by simpa only [div_eq_mul_inv, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ℝ≥0∞} (h : a ≠ 0) : ∃n:ℕ, (n:ℝ≥0∞)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := begin have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), have : 0 < (n : ℝ≥0∞), from (zero_le _).trans_lt hn, refine ⟨coe_nat_lt_coe_nat.1 this, _⟩, rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ℝ≥0∞)⁻¹ * a < b := begin rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩, have : (n : ℝ≥0∞) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne', use [n, npos], rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top, mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)] end lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := begin rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩, use (n : ℝ≥0)⁻¹, simp [*, npos.ne', zero_lt_one] end lemma exists_inv_two_pow_lt (ha : a ≠ 0) : ∃ n : ℕ, 2⁻¹ ^ n < a := begin rcases exists_inv_nat_lt ha with ⟨n, hn⟩, simp only [← ennreal.inv_pow], refine ⟨n, lt_trans (inv_lt_inv.2 _) hn⟩, norm_cast, exact n.lt_two_pow end end inv section real lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, real.to_nnreal_add hp hq] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 real.to_nnreal_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_mono (hb : b ≠ ∞) (h : a ≤ b) : a.to_real ≤ b.to_real := (to_real_le_to_real (h.trans_lt (lt_top_iff_ne_top.2 hb)).ne hb).2 h @[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_strict_mono (hb : b ≠ ∞) (h : a < b) : a.to_real < b.to_real := (to_real_lt_to_real (h.trans (lt_top_iff_ne_top.2 hb)).ne hb).2 h lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, real.to_nnreal_le_to_nnreal h] lemma of_real_le_of_le_to_real {a : ℝ} {b : ℝ≥0∞} (h : a ≤ ennreal.to_real b) : ennreal.of_real a ≤ b := (of_real_le_of_real h).trans of_real_to_real_le @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, real.to_nnreal_le_to_nnreal_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, real.to_nnreal_lt_to_nnreal_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, real.to_nnreal_lt_to_nnreal_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ℝ≥0∞} (hb : b ≠ ∞) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using real.to_nnreal_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ℝ≥0∞} (ha : 0 ≤ a) (hb : b ≠ ∞) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using real.to_nnreal_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using real.le_to_nnreal_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ℝ≥0∞} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using real.lt_to_nnreal_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact real.to_nnreal_mul hp } lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) : (ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ := by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (real.to_nnreal x) (by simp [hx]), coe_eq_coe, real.to_nnreal_inv.symm] lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) : ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y := by rw [div_eq_inv_mul, div_eq_mul_inv, of_real_mul (inv_nonneg.2 hy.le), of_real_inv_of_pos hy, mul_comm] lemma to_real_of_real_mul (c : ℝ) (a : ℝ≥0∞) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply real.coe_to_nnreal, exact h } end @[simp] lemma to_nnreal_mul_top (a : ℝ≥0∞) : ennreal.to_nnreal (a * ∞) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_nnreal] }, { rw [mul_top, if_neg h, top_to_nnreal] } end @[simp] lemma to_nnreal_top_mul (a : ℝ≥0∞) : ennreal.to_nnreal (∞ * a) = 0 := by rw [mul_comm, to_nnreal_mul_top] @[simp] lemma to_real_mul_top (a : ℝ≥0∞) : ennreal.to_real (a * ∞) = 0 := by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero] @[simp] lemma to_real_top_mul (a : ℝ≥0∞) : ennreal.to_real (∞ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real (ha : a < ∞) (hb : b < ∞) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin lift a to ℝ≥0 using ha.ne, lift b to ℝ≥0 using hb.ne, simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real], end /-- `ennreal.to_nnreal` as a `monoid_hom`. -/ def to_nnreal_hom : ℝ≥0∞ →* ℝ≥0 := { to_fun := ennreal.to_nnreal, map_one' := to_nnreal_coe, map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe, to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] } lemma to_nnreal_mul {a b : ℝ≥0∞}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal := to_nnreal_hom.map_mul a b lemma to_nnreal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n := to_nnreal_hom.map_pow a n lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} : (∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal := to_nnreal_hom.map_prod _ _ /-- `ennreal.to_real` as a `monoid_hom`. -/ def to_real_hom : ℝ≥0∞ →* ℝ := (nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real := to_real_hom.map_mul a b lemma to_real_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n := to_real_hom.map_pow a n lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} : (∏ i in s, f i).to_real = ∏ i in s, (f i).to_real := to_real_hom.map_prod _ _ lemma of_real_prod_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ennreal.of_real (∏ i in s, f i) = ∏ i in s, ennreal.of_real (f i) := begin simp_rw [ennreal.of_real, ←coe_finset_prod, coe_eq_coe], exact real.to_nnreal_prod_of_nonneg hf, end @[simp] lemma to_nnreal_bit0 {x : ℝ≥0∞} : (bit0 x).to_nnreal = bit0 (x.to_nnreal) := begin by_cases hx_top : x = ∞, { simp [hx_top, bit0_eq_top_iff.mpr rfl], }, exact to_nnreal_add (lt_top_iff_ne_top.mpr hx_top) (lt_top_iff_ne_top.mpr hx_top), end @[simp] lemma to_nnreal_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) : (bit1 x).to_nnreal = bit1 (x.to_nnreal) := by simp [bit1, bit1, to_nnreal_add (lt_top_iff_ne_top.mpr (by rwa [ne.def, bit0_eq_top_iff])) ennreal.one_lt_top] @[simp] lemma to_real_bit0 {x : ℝ≥0∞} : (bit0 x).to_real = bit0 (x.to_real) := by simp [ennreal.to_real] @[simp] lemma to_real_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) : (bit1 x).to_real = bit1 (x.to_real) := by simp [ennreal.to_real, hx_top] @[simp] lemma of_real_bit0 {r : ℝ} (hr : 0 ≤ r) : ennreal.of_real (bit0 r) = bit0 (ennreal.of_real r) := of_real_add hr hr @[simp] lemma of_real_bit1 {r : ℝ} (hr : 0 ≤ r) : ennreal.of_real (bit1 r) = bit1 (ennreal.of_real r) := (of_real_add (by simp [hr]) zero_le_one).trans (by simp [real.to_nnreal_one, bit1, hr]) end real section infi variables {ι : Sort*} {f g : ι → ℝ≥0∞} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ℝ≥0∞} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ℝ≥0∞} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ℝ≥0∞} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] lemma infi_mul {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : infi f * x = ⨅i, f i * x := begin by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const], refine le_antisymm (le_infi $ λ i, mul_right_mono $ infi_le _ _) ((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _) end lemma mul_infi {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : x * infi f = ⨅i, x * f i := by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption } /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ end infi section supr @[simp] lemma supr_eq_zero {ι : Sort*} {f : ι → ℝ≥0∞} : (⨆ i, f i) = 0 ↔ ∀ i, f i = 0 := supr_eq_bot @[simp] lemma supr_zero_eq_zero {ι : Sort*} : (⨆ i : ι, (0 : ℝ≥0∞)) = 0 := by simp lemma sup_eq_zero {a b : ℝ≥0∞} : a ⊔ b = 0 ↔ a = 0 ∧ b = 0 := sup_eq_bot_iff lemma supr_coe_nat : (⨆n:ℕ, (n : ℝ≥0∞)) = ∞ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ℝ≥0∞` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_left {a b c : ℝ≥0∞} : a < ∞ → a + b ≤ a + c → b ≤ c := by cases a; cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe] /-- `le_of_add_le_add_right` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ℝ≥0∞` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_right {a b c : ℝ≥0∞} : a < ∞ → b + a ≤ c + a → b ≤ c := by simpa only [add_comm _ a] using le_of_add_le_add_left end ennreal
22b45b8dd4ed52cd067b170bbe4454fa2e0f580b
ec5e5a9dbe7f60fa5784d15211d8bf24ada0825c
/src/LLVMOutput.lean
5fca24462a5814d08282c4c7838d1bf45e2ee172
[]
no_license
pnwamk/lean-llvm
fcd9a828e52e80eb197f7d9032b3846f2e09ef74
ebc3bca9a57a6aef29529d46394f560398fb5c9c
refs/heads/master
1,668,418,078,706
1,593,548,643,000
1,593,548,643,000
258,617,753
0
0
null
1,587,760,298,000
1,587,760,298,000
null
UTF-8
Lean
false
false
5,789
lean
import Init.Data.Array import Init.Data.Int import Init.Data.RBMap import Init.System.IO import LeanLLVM.AST import LeanLLVM.PP import LeanLLVM.DataLayout import LeanLLVM.LLVMCodes import LeanLLVM.LLVMFFI namespace LLVM namespace Output @[reducible] def SymMap := RBMap Symbol FFI.Value (λx y => decide (x < y)) @[reducible] def BlockMap := RBMap BlockLabel FFI.Value (λx y => decide (x.label < y.label)) @[reducible] def ValueMap := RBMap Ident FFI.Value (λx y => decide (x < y)) @[reducible] def TypeMap := RBMap String FFI.Type_ (λx y => decide (x < y)) structure ValueContext := (symbolMap : SymMap) (blockMap : BlockMap) (valueMap : ValueMap) (typeMap : TypeMap) def ValueContext.init : ValueContext := { symbolMap := RBMap.empty, blockMap := RBMap.empty, valueMap := RBMap.empty, typeMap := RBMap.empty } end Output @[reducible] def Output (a:Type) := IO.Ref Output.ValueContext → IO a. namespace Output instance monad : Monad Output := { bind := λa b mx mf r => mx r >>= λx => mf x r , pure := λa x r => pure x } instance monadExcept : MonadExcept IO.Error Output := { throw := λa err r => throw err, catch := λa m handle r => catch (m r) (λerr => handle err r), } instance mIO : MonadIO Output := { monadLift := λa m r => m } def run {a:Type} (m:Output a) : IO (Output.ValueContext × a) := do r <- IO.mkRef Output.ValueContext.init; a <- m r; vc <- r.get; pure (vc, a) def alterSymbolMap (f:SymMap → SymMap) : Output Unit := λr => r.modify (λvc => { vc with symbolMap := f vc.symbolMap }) def lookupAlias (nm:String) : Output (Option FFI.Type_) := λr => do vc <- r.get; pure (vc.typeMap.find? nm) /- def createFunction (m:Module) (nm:symbol) : Output LLVMFunction := do f <- newFunction m nm.symbol; alterSymbolMap (λsm => sm.insert -/ end Output def outputFloatType : FloatType → Code.TypeID | FloatType.half => Code.TypeID.half | FloatType.float => Code.TypeID.float | FloatType.double => Code.TypeID.double | FloatType.fp128 => Code.TypeID.fp128 | FloatType.x86FP80 => Code.TypeID.x86FP80 | FloatType.ppcFP128 => Code.TypeID.ppcFP128 def outputPrimType (ctx:FFI.Context) : PrimType → IO FFI.Type_ | PrimType.label => FFI.newPrimitiveType ctx Code.TypeID.label | PrimType.token => FFI.newPrimitiveType ctx Code.TypeID.token | PrimType.void => FFI.newPrimitiveType ctx Code.TypeID.void | PrimType.floatType ft => FFI.newPrimitiveType ctx (outputFloatType ft) | PrimType.x86mmx => FFI.newPrimitiveType ctx Code.TypeID.x86mmx | PrimType.metadata => FFI.newPrimitiveType ctx Code.TypeID.metadata | PrimType.integer n => FFI.newIntegerType ctx n partial def outputType (ctx:FFI.Context) : LLVMType → Output FFI.Type_ | LLVMType.prim pt => monadLift (outputPrimType ctx pt) | LLVMType.alias nm => do x <- Output.lookupAlias nm; match x with | some tp => pure tp | none => throw (IO.userError ("Unknown type alias: " ++ nm)) | LLVMType.array n t => do t' <- outputType t; monadLift $ FFI.newArrayType n t' | LLVMType.vector n t => do t' <- outputType t; monadLift $ FFI.newVectorType n t' | LLVMType.ptr t => do t' <- outputType t; monadLift $ FFI.newPointerType t' | LLVMType.funType ret args varargs => do ret' <- outputType ret; args' <- Array.mapM outputType args; monadLift $ FFI.newFunctionType ret' args' varargs | LLVMType.struct packed tps => do tps' <- tps.mapM outputType; monadLift $ FFI.newLiteralStructType packed tps' def setupTypeAlias (ctx:FFI.Context) (nm:String) : Output FFI.Type_ := λr => do vc <- r.get; tp <- FFI.newOpaqueStructType ctx nm; let vc' := { vc with typeMap := vc.typeMap.insert nm tp }; r.set vc'; pure tp def finalizeTypeAlias (ctx:FFI.Context) (ty:FFI.Type_) : TypeDeclBody → Output Unit | TypeDeclBody.opaque => pure () | TypeDeclBody.defn (LLVMType.struct packed tps) => do tps' <- tps.mapM (outputType ctx); monadLift (FFI.setStructTypeBody ty packed tps'); pure () | TypeDeclBody.defn _ => throw (IO.userError "type alias defintion must be a struct body") -- Process type aliases in two phases. First, allocate named, opaque struct -- types for each alias and record them in the value context. Next, process -- the bodies of type aliases and set the body of the non-opaque named struct types. -- -- This two-phase approach ensures that recursive struct groups are properly handled. def outputTypeAliases (ctx:FFI.Context) (tds:Array TypeDecl) : Output Unit := do fs <- tds.mapM (λtd => setupTypeAlias ctx td.name >>= λty => pure (finalizeTypeAlias ctx ty td.decl)); Array.iterateM fs () (λ_ action _ => action) def outputDeclare (ctx:FFI.Context) (m:FFI.Module) (d:Declare) : Output Unit := do funtp <- outputType ctx (LLVMType.funType d.retType d.args d.varArgs); f <- monadLift (FFI.newFunction m funtp d.name.symbol); Output.alterSymbolMap (λsm => sm.insert d.name (FFI.functionToValue f)) def outputDefine (ctx:FFI.Context) (m:FFI.Module) (d:Define) : Output Unit := do let argTypes := d.args.map (λa => a.type); funtp <- outputType ctx (LLVMType.funType d.retType argTypes d.varArgs); f <- monadLift (FFI.newFunction m funtp d.name.symbol); Output.alterSymbolMap (λsm => sm.insert d.name (FFI.functionToValue f)); -- TODO!!! pure () def outputModule (ctx:FFI.Context) (m:Module) : Output FFI.Module := do outputTypeAliases ctx m.types; let modnm := match m.sourceName with | some nm => nm | none => ""; ffimod <- monadLift (FFI.newModule ctx modnm); Array.iterateM m.declares () (λ_ decl _ => outputDeclare ctx ffimod decl); Array.iterateM m.defines () (λ_ defn _ => outputDefine ctx ffimod defn); pure ffimod end LLVM
458e01fe00cde993b2eaf59c9f86d80423eae811
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/floor_ring_auto.lean
ec5fe3b7a2cd855f67a3a043d1521b485af40f40
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,734
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker Basic topological facts (limits and continuity) about `floor`, `ceil` and `fract` in a `floor_ring`. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.ordered import Mathlib.algebra.floor import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib theorem tendsto_floor_at_top {α : Type u_1} [linear_ordered_ring α] [floor_ring α] : filter.tendsto floor filter.at_top filter.at_top := sorry theorem tendsto_floor_at_bot {α : Type u_1} [linear_ordered_ring α] [floor_ring α] : filter.tendsto floor filter.at_bot filter.at_bot := monotone.tendsto_at_bot_at_bot (fun (a b : α) (hab : a ≤ b) => floor_mono hab) fun (b : ℤ) => Exists.intro (↑b) (eq.mpr (id (Eq._oldrec (Eq.refl (floor ↑b ≤ b)) (floor_coe b))) (le_refl b)) theorem tendsto_ceil_at_top {α : Type u_1} [linear_ordered_ring α] [floor_ring α] : filter.tendsto ceil filter.at_top filter.at_top := filter.tendsto.comp filter.tendsto_neg_at_bot_at_top (filter.tendsto.comp tendsto_floor_at_bot filter.tendsto_neg_at_top_at_bot) theorem tendsto_ceil_at_bot {α : Type u_1} [linear_ordered_ring α] [floor_ring α] : filter.tendsto ceil filter.at_bot filter.at_bot := filter.tendsto.comp filter.tendsto_neg_at_top_at_bot (filter.tendsto.comp tendsto_floor_at_top filter.tendsto_neg_at_bot_at_top) theorem continuous_on_floor {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] (n : ℤ) : continuous_on (fun (x : α) => ↑(floor x)) (set.Ico (↑n) (↑n + 1)) := iff.mpr (continuous_on_congr (floor_eq_on_Ico' n)) continuous_on_const theorem continuous_on_ceil {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] (n : ℤ) : continuous_on (fun (x : α) => ↑(ceil x)) (set.Ioc (↑n - 1) ↑n) := iff.mpr (continuous_on_congr (ceil_eq_on_Ioc' n)) continuous_on_const theorem tendsto_floor_right' {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] (n : ℤ) : filter.tendsto (fun (x : α) => ↑(floor x)) (nhds_within (↑n) (set.Ici ↑n)) (nhds ↑n) := sorry theorem tendsto_ceil_left' {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] (n : ℤ) : filter.tendsto (fun (x : α) => ↑(ceil x)) (nhds_within (↑n) (set.Iic ↑n)) (nhds ↑n) := sorry theorem tendsto_floor_right {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] (n : ℤ) : filter.tendsto (fun (x : α) => ↑(floor x)) (nhds_within (↑n) (set.Ici ↑n)) (nhds_within (↑n) (set.Ici ↑n)) := sorry theorem tendsto_ceil_left {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] (n : ℤ) : filter.tendsto (fun (x : α) => ↑(ceil x)) (nhds_within (↑n) (set.Iic ↑n)) (nhds_within (↑n) (set.Iic ↑n)) := sorry theorem tendsto_floor_left {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] (n : ℤ) : filter.tendsto (fun (x : α) => ↑(floor x)) (nhds_within (↑n) (set.Iio ↑n)) (nhds_within (↑n - 1) (set.Iic (↑n - 1))) := sorry theorem tendsto_ceil_right {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] (n : ℤ) : filter.tendsto (fun (x : α) => ↑(ceil x)) (nhds_within (↑n) (set.Ioi ↑n)) (nhds_within (↑n + 1) (set.Ici (↑n + 1))) := sorry theorem tendsto_floor_left' {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] (n : ℤ) : filter.tendsto (fun (x : α) => ↑(floor x)) (nhds_within (↑n) (set.Iio ↑n)) (nhds (↑n - 1)) := sorry theorem tendsto_ceil_right' {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] (n : ℤ) : filter.tendsto (fun (x : α) => ↑(ceil x)) (nhds_within (↑n) (set.Ioi ↑n)) (nhds (↑n + 1)) := sorry theorem continuous_on_fract {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [topological_add_group α] (n : ℤ) : continuous_on fract (set.Ico (↑n) (↑n + 1)) := continuous_on.sub continuous_on_id (continuous_on_floor n) theorem tendsto_fract_left' {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] [topological_add_group α] (n : ℤ) : filter.tendsto fract (nhds_within (↑n) (set.Iio ↑n)) (nhds 1) := sorry theorem tendsto_fract_left {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] [topological_add_group α] (n : ℤ) : filter.tendsto fract (nhds_within (↑n) (set.Iio ↑n)) (nhds_within 1 (set.Iio 1)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within fract (tendsto_fract_left' n) (filter.eventually_of_forall fract_lt_one) theorem tendsto_fract_right' {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] [topological_add_group α] (n : ℤ) : filter.tendsto fract (nhds_within (↑n) (set.Ici ↑n)) (nhds 0) := sorry theorem tendsto_fract_right {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] [order_closed_topology α] [topological_add_group α] (n : ℤ) : filter.tendsto fract (nhds_within (↑n) (set.Ici ↑n)) (nhds_within 0 (set.Ici 0)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within fract (tendsto_fract_right' n) (filter.eventually_of_forall fract_nonneg) theorem continuous_on.comp_fract' {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] {β : Type u_2} {γ : Type u_3} [order_topology α] [topological_add_group α] [topological_space β] [topological_space γ] {f : β → α → γ} (h : continuous_on (function.uncurry f) (set.prod set.univ (set.Icc 0 1))) (hf : ∀ (s : β), f s 0 = f s 1) : continuous fun (st : β × α) => f (prod.fst st) (fract (prod.snd st)) := sorry theorem continuous_on.comp_fract {α : Type u_1} [linear_ordered_ring α] [floor_ring α] [topological_space α] {β : Type u_2} [order_topology α] [topological_add_group α] [topological_space β] {f : α → β} (h : continuous_on f (set.Icc 0 1)) (hf : f 0 = f 1) : continuous (f ∘ fract) := sorry end Mathlib
f01caca4d6ec3aee0675b27cd9ba6ccd64930ee2
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/analysis/special_functions/pow.lean
83b13ad9b09af920ec8bc8751dd85dbeb2abcab0
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
69,661
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.trigonometric import analysis.calculus.extend_deriv /-! # Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We construct the power functions `x ^ y` where * `x` and `y` are complex numbers, * or `x` and `y` are real numbers, * or `x` is a nonnegative real number and `y` is a real number; * or `x` is a number from `[0, +∞]` (a.k.a. `ℝ≥0∞`) and `y` is a real number. We also prove basic properties of these functions. -/ noncomputable theory open_locale classical real topological_space nnreal ennreal filter open filter namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl lemma cpow_def_of_ne_zero {x : ℂ} (hx : x ≠ 0) (y : ℂ) : x ^ y = exp (log x * y) := if_neg hx @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp only [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] lemma cpow_sub {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, cpow_add _ _ hx, cpow_neg, div_eq_mul_inv] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := begin suffices : im (log x * n⁻¹) ∈ set.Ioc (-π) π, { rw [← cpow_nat_cast, ← cpow_mul _ this.1 this.2, inv_mul_cancel, cpow_one], exact_mod_cast hn.ne' }, rw [mul_comm, ← of_real_nat_cast, ← of_real_inv, of_real_mul_im, ← div_eq_inv_mul], have hn' : 0 < (n : ℝ), by assumption_mod_cast, have hn1 : 1 ≤ (n : ℝ), by exact_mod_cast (nat.succ_le_iff.2 hn), split, { rw lt_div_iff hn', calc -π * n ≤ -π * 1 : mul_le_mul_of_nonpos_left hn1 (neg_nonpos.2 real.pi_pos.le) ... = -π : mul_one _ ... < im (log x) : neg_pi_lt_log_im _ }, { rw div_le_iff hn', calc im (log x) ≤ π : log_im_le_pi _ ... = π * 1 : (mul_one π).symm ... ≤ π * n : mul_le_mul_of_nonneg_left hn1 real.pi_pos.le } end lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := begin have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp }, have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono (λ p hp, cpow_def_of_ne_zero hp _), rw [cpow_sub _ _ A, cpow_one, mul_div_comm, mul_smul, mul_smul, ← smul_add], refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, smul_smul, add_comm] using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp end lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y := begin rcases em (x = 0) with rfl|hx, { replace h := h.neg_resolve_left rfl, rw [log_zero, mul_zero], refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _, exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) }, { simpa only [cpow_def_of_ne_zero hx, mul_one] using ((has_strict_deriv_at_id y).const_mul (log x)).cexp } end lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := (has_strict_fderiv_at_cpow hp).has_fderiv_at instance : has_measurable_pow ℂ ℂ := ⟨measurable.ite (measurable_fst (measurable_set_singleton 0)) (measurable.ite (measurable_snd (measurable_set_singleton 0)) measurable_one measurable_zero) (measurable_fst.clog.mul measurable_snd).cexp⟩ end complex section lim open complex variables {α : Type*} lemma filter.tendsto.cpow {l : filter α} {f g : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) (ha : 0 < a.re ∨ a.im ≠ 0) : tendsto (λ x, f x ^ g x) l (𝓝 (a ^ b)) := (@has_fderiv_at_cpow (a, b) ha).continuous_at.tendsto.comp (hf.prod_mk_nhds hg) lemma filter.tendsto.const_cpow {l : filter α} {f : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 b)) (h : a ≠ 0 ∨ b ≠ 0) : tendsto (λ x, a ^ f x) l (𝓝 (a ^ b)) := (has_strict_deriv_at_const_cpow h).continuous_at.tendsto.comp hf variables [topological_space α] {f g : α → ℂ} {s : set α} {a : α} lemma continuous_within_at.cpow (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_within_at (λ x, f x ^ g x) s a := hf.cpow hg h0 lemma continuous_within_at.const_cpow {b : ℂ} (hf : continuous_within_at f s a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_within_at (λ x, b ^ f x) s a := hf.const_cpow h lemma continuous_at.cpow (hf : continuous_at f a) (hg : continuous_at g a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_at (λ x, f x ^ g x) a := hf.cpow hg h0 lemma continuous_at.const_cpow {b : ℂ} (hf : continuous_at f a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_at (λ x, b ^ f x) a := hf.const_cpow h lemma continuous_on.cpow (hf : continuous_on f s) (hg : continuous_on g s) (h0 : ∀ a ∈ s, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_on (λ x, f x ^ g x) s := λ a ha, (hf a ha).cpow (hg a ha) (h0 a ha) lemma continuous_on.const_cpow {b : ℂ} (hf : continuous_on f s) (h : b ≠ 0 ∨ ∀ a ∈ s, f a ≠ 0) : continuous_on (λ x, b ^ f x) s := λ a ha, (hf a ha).const_cpow (h.imp id $ λ h, h a ha) lemma continuous.cpow (hf : continuous f) (hg : continuous g) (h0 : ∀ a, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous (λ x, f x ^ g x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.cpow hg.continuous_at (h0 a)) lemma continuous.const_cpow {b : ℂ} (hf : continuous f) (h : b ≠ 0 ∨ ∀ a, f a ≠ 0) : continuous (λ x, b ^ f x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.const_cpow $ h.imp id $ λ h, h a) end lim section fderiv open complex variables {E : Type*} [normed_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : set E} {c : ℂ} lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ x, f x ^ g x) x := (hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_at ℂ (λ x, c ^ f x) x := (hf.has_fderiv_at.const_cpow h0).differentiable_at lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x) (hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ x, f x ^ g x) s x := (hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_within_at ℂ (λ x, c ^ f x) s x := (hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at end fderiv section deriv open complex variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form expected by lemmas like `has_deriv_at.cpow`. -/ private lemma aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul'] lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h).comp x hf lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).comp x hf lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x := by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf end deriv namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y := by rw [rpow_def_of_pos (exp_pos _), log_exp] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, { simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring }, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := begin rcases lt_trichotomy 0 x with (hx|rfl|hx), { rw [abs_of_pos hx, abs_of_pos (rpow_pos_of_pos hx _)] }, { rw [abs_zero, abs_of_nonneg (rpow_nonneg_of_nonneg le_rfl _)] }, { rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log, abs_mul, abs_of_pos (exp_pos _)], exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) } end lemma abs_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : abs (x ^ y) = (abs x) ^ y := begin have h_rpow_nonneg : 0 ≤ x ^ y, from real.rpow_nonneg_of_nonneg hx_nonneg _, rw [abs_eq_self.mpr hx_nonneg, abs_eq_self.mpr h_rpow_nonneg], end lemma norm_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : ∥x ^ y∥ = ∥x∥ ^ y := by { simp_rw real.norm_eq_abs, exact abs_rpow_of_nonneg hx_nonneg, } end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real variables {x y z : ℝ} lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def, not_false_iff, zero_eq_mul], by_contradiction F, push_neg at F, apply h, simp [F] }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by { simp only [sub_eq_add_neg] at h ⊢, simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] } @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, fpow_one, fpow_neg], end lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, { cases lt_or_eq_of_le h with h₂ h₂, { exact h₂ }, exfalso, apply h_2, exact eq.symm h₂ }, have hy : 0 < y, { cases lt_or_eq_of_le h₁ with h₂ h₂, { exact h₂ }, exfalso, apply h_3, exact eq.symm h₂ }, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁ }, { exact h }, { exact mul_nonneg h h₁ }, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := begin by_cases hy0 : y = 0, { simp [*] }, by_cases hx0 : x = 0, { simp [*] }, simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false, hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg] end lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x^y) = y * (log x) := begin apply exp_injective, rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y], end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz } lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz } lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm } lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm } lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z := by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz } lemma one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm } lemma one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm } lemma rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx, log_neg_iff hx] lemma rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, zero_lt_one] }, { simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] } end lemma one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 := by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx, log_neg_iff hx] lemma one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, (@zero_lt_one ℝ _ _).not_lt] }, { simp [one_lt_rpow_iff_of_pos hx, hx] } end lemma rpow_le_one_iff_of_pos (hx : 0 < x) : x ^ y ≤ 1 ↔ 1 ≤ x ∧ y ≤ 0 ∨ x ≤ 1 ∧ 0 ≤ y := by rw [rpow_def_of_pos hx, exp_le_one_iff, mul_nonpos_iff, log_nonneg_iff hx, log_nonpos_iff hx] lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert (is_open_lt' (0:ℝ)).prod is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert (is_open_gt' (0:ℝ)).prod is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_univ.prod (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section prove_rpow_is_differentiable lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x, { convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1, field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h], ring }, apply this.congr_of_eventually_eq, have : set.Ioi (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Ioi h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _) end lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x, { convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _ using 1, field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h], ring }, apply this.congr_of_eventually_eq, have : set.Iio (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Iio h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _) end lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin rcases lt_trichotomy x 0 with H|H|H, { exact has_deriv_at_rpow_of_neg H p }, { exact (h H).elim }, { exact has_deriv_at_rpow_of_pos H p }, end lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 := begin apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p), { exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h)) continuous_id continuous_const).continuous_at }, { rcases le_iff_eq_or_lt.1 h with rfl|h, { simp [continuous_const.continuous_at] }, { exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h) continuous_id continuous_const)).continuous_at } } end lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin by_cases hx : x = 0, { rw hx, exact has_deriv_at_rpow_zero_of_one_le h }, { exact has_deriv_at_rpow hx p } end end prove_rpow_is_differentiable section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end end sqrt instance : has_measurable_pow ℝ ℝ := ⟨complex.measurable_re.comp $ ((complex.measurable_of_real.comp measurable_fst).pow (complex.measurable_of_real.comp measurable_snd))⟩ end real section differentiability open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ) /- Differentiability statements for the power of a function, when the function does not vanish and the exponent is arbitrary-/ lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow p hx end lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow p hx).differentiable_within_at @[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow p hx).differentiable_at lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow p (hx x h) @[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow p (hx x) lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow p hx).deriv_within hxs @[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow p hx).deriv /- Differentiability statements for the power of a function, when the function may vanish but the exponent is at least one. -/ variable {p} lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_of_one_le hp end lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at @[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow_of_one_le hp).differentiable_at lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow_of_one_le hp @[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow_of_one_le hp lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs @[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_of_one_le hp).deriv end differentiability section limits open real filter /-- The function `x ^ y` tends to `+∞` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ y) at_top at_top := begin rw tendsto_at_top_at_top, intro b, use (max b 0) ^ (1/y), intros x hx, exact le_of_max_le_left (by { convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1/y)) hx (le_of_lt hy), rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, rpow_one] }), end /-- The function `x ^ (-y)` tends to `0` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_neg_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ (-y)) at_top (𝓝 0) := tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) (λ x hx, (rpow_neg (le_of_lt hx) y).symm)) (tendsto_rpow_at_top hy).inv_tendsto_at_top /-- The function `x ^ (a / (b * x + c))` tends to `1` at `+∞`, for any real numbers `a`, `b`, and `c` such that `b` is nonzero. -/ lemma tendsto_rpow_div_mul_add (a b c : ℝ) (hb : 0 ≠ b) : tendsto (λ x, x ^ (a / (b*x+c))) at_top (𝓝 1) := begin refine tendsto.congr' _ ((tendsto_exp_nhds_0_nhds_1.comp (by simpa only [mul_zero, pow_one] using ((@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_at_top b c 1 hb (by norm_num))))).comp (tendsto_log_at_top)), apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)), intros x hx, simp only [set.mem_Ioi, function.comp_app] at hx ⊢, rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))], field_simp, end /-- The function `x ^ (1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_div : tendsto (λ x, x ^ ((1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (1:ℝ) _ (0:ℝ) zero_ne_one, ring_nf } /-- The function `x ^ (-1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_neg_div : tendsto (λ x, x ^ (-(1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (-(1:ℝ)) _ (0:ℝ) zero_ne_one, ring_nf } end limits namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (pos_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (pos_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := real.rpow_lt_one_of_one_lt_of_neg hx hz lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := real.rpow_le_one_of_one_le_of_nonpos hx hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end lemma of_real_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : nnreal.of_real (x ^ y) = (nnreal.of_real x) ^ y := begin nth_rewrite 0 ← nnreal.coe_of_real x hx, rw [←nnreal.coe_rpow, nnreal.of_real_coe], end instance : has_measurable_pow ℝ≥0 ℝ := ⟨(measurable_fst.nnreal_coe.pow measurable_snd).subtype_mk⟩ end nnreal open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (hx.prod_mk_nhds hy) namespace nnreal lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) : continuous_at (λ z, z^y) x := h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $ λ h, h.eq_or_lt.elim (λ h, h ▸ by simp only [rpow_zero, continuous_at_const]) (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h)) lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) : continuous (λ x : ℝ≥0, x^y) := continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h) end nnreal namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ℝ≥0∞` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ℝ≥0∞ → ℝ → ℝ≥0∞ | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ℝ≥0∞ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0∞) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ℝ≥0∞} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ℝ≥0∞) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ℝ≥0∞) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ℝ≥0∞) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ℝ≥0∞) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ℝ≥0∞) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ℝ≥0∞) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end lemma coe_rpow_def (x : ℝ≥0) (y : ℝ) : (x : ℝ≥0∞) ^ y = if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) := rfl @[simp] lemma rpow_one (x : ℝ≥0∞) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0∞) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_eq_top_iff_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : x ^ y = ⊤ ↔ x = ⊤ := by simp [rpow_eq_top_iff, hy, asymm hy] lemma rpow_eq_top_of_nonneg (x : ℝ≥0∞) {y : ℝ} (hy0 : 0 ≤ y) : x ^ y = ⊤ → x = ⊤ := begin rw ennreal.rpow_eq_top_iff, intro h, cases h, { exfalso, rw lt_iff_not_ge at h, exact h.right hy0, }, { exact h.left, }, end lemma rpow_ne_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y ≠ ⊤ := mt (ennreal.rpow_eq_top_of_nonneg x hy0) h lemma rpow_lt_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y < ⊤ := ennreal.lt_top_iff_ne_top.mpr (ennreal.rpow_ne_top_of_nonneg hy0 h) lemma rpow_add {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ℝ≥0∞) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_sub {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, rpow_add _ _ hx h'x, rpow_neg, div_eq_mul_inv] lemma rpow_neg_one (x : ℝ≥0∞) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ℝ≥0∞) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0∞) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ℝ≥0∞) * y) ^ z = x^z * y^z := begin rcases lt_trichotomy z 0 with H|H|H, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_neg, H] }, { have : (y : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] }, { have : (x : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, { simp [H] }, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_pos, H] }, { have : (y : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] }, { have : (x : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, end lemma mul_rpow_of_ne_top {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := begin lift x to ℝ≥0 using hx, lift y to ℝ≥0 using hy, exact coe_mul_rpow x y z end lemma mul_rpow_of_ne_zero {x y : ℝ≥0∞} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := begin rcases lt_trichotomy z 0 with H|H|H, { cases x; cases y, { simp [hx, hy, top_rpow_of_neg, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } }, { simp [H] }, { cases x; cases y, { simp [hx, hy, top_rpow_of_pos, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } } end lemma mul_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := begin rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] }, by_cases h : x = 0 ∨ y = 0, { cases h; simp [h, zero_rpow_of_pos H] }, push_neg at h, exact mul_rpow_of_ne_zero h.1 h.2 z end lemma inv_rpow_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : (x⁻¹) ^ y = (x ^ y)⁻¹ := begin by_cases h0 : x = 0, { rw [h0, zero_rpow_of_pos hy, inv_zero, top_rpow_of_pos hy], }, by_cases h_top : x = ⊤, { rw [h_top, top_rpow_of_pos hy, inv_top, zero_rpow_of_pos hy], }, rw ←coe_to_nnreal h_top, have h : x.to_nnreal ≠ 0, { rw [ne.def, to_nnreal_eq_zero_iff], simp [h0, h_top], }, rw [←coe_inv h, coe_rpow_of_nonneg _ (le_of_lt hy), coe_rpow_of_nonneg _ (le_of_lt hy), ←coe_inv], { rw coe_eq_coe, exact nnreal.inv_rpow x.to_nnreal y, }, { simp [h], }, end lemma div_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x / y) ^ z = x ^ z / y ^ z := begin by_cases h0 : z = 0, { simp [h0], }, rw ←ne.def at h0, have hz_pos : 0 < z, from lt_of_le_of_ne hz h0.symm, rw [div_eq_mul_inv, mul_rpow_of_nonneg x y⁻¹ hz, inv_rpow_of_pos hz_pos, ←div_eq_mul_inv], end lemma rpow_le_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] }, cases y, { simp [top_rpow_of_pos H] }, cases x, { exact (not_top_le_coe h₁).elim }, simp at h₁, simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂] end lemma rpow_lt_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := begin cases x, { exact (not_top_lt h₁).elim }, cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] }, simp at h₁, simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂] end lemma rpow_le_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := begin refine ⟨λ h, _, λ h, rpow_le_rpow h (le_of_lt hz)⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul, ←one_div], exact rpow_le_rpow h (by simp [le_of_lt hz]), end lemma rpow_lt_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := begin refine ⟨λ h_lt, _, λ h, rpow_lt_rpow h hz⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul], exact rpow_lt_rpow h_lt (by simp [hz]), end lemma le_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ≤ y ^ (1 / z) ↔ x ^ z ≤ y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_le_rpow_iff _ _ (1/z) (by simp [hz])], end lemma lt_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x < y ^ (1 / z) ↔ x ^ z < y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_lt_rpow_iff _ _ (1/z) (by simp [hz])], end lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0∞} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0∞} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0∞} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0∞} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_self_of_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := begin nth_rewrite 1 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_ge hx h_one_le, end lemma le_rpow_self_of_one_le {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (h_one_le : 1 ≤ z) : x ≤ x ^ z := begin nth_rewrite 0 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_le hx h_one_le, end lemma rpow_pos_of_nonneg {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hp_nonneg : 0 ≤ p) : 0 < x^p := begin by_cases hp_zero : p = 0, { simp [hp_zero, ennreal.zero_lt_one], }, { rw ←ne.def at hp_zero, have hp_pos := lt_of_le_of_ne hp_nonneg hp_zero.symm, rw ←zero_rpow_of_pos hp_pos, exact rpow_lt_rpow hx_pos hp_pos, }, end lemma rpow_pos {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hx_ne_top : x ≠ ⊤) : 0 < x^p := begin cases lt_or_le 0 p with hp_pos hp_nonpos, { exact rpow_pos_of_nonneg hx_pos (le_of_lt hp_pos), }, { rw [←neg_neg p, rpow_neg, inv_pos], exact rpow_ne_top_of_nonneg (by simp [hp_nonpos]) hx_ne_top, }, end lemma rpow_lt_one {x : ℝ≥0∞} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top), simp only [coe_lt_one_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz], end lemma rpow_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top), simp only [coe_le_one_iff] at hx, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz], end lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] }, end lemma rpow_le_one_of_one_le_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] }, end lemma one_lt_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma one_le_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] }, end lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top), simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz], end lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z < 0) : 1 ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)], end lemma to_nnreal_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_nnreal) ^ z = (x ^ z).to_nnreal := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end lemma to_real_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := by rw [ennreal.to_real, ennreal.to_real, ←nnreal.coe_rpow, ennreal.to_nnreal_rpow] lemma of_real_rpow_of_pos {x p : ℝ} (hx_pos : 0 < x) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin simp_rw ennreal.of_real, rw [coe_rpow_of_ne_zero, coe_eq_coe, nnreal.of_real_rpow_of_nonneg hx_pos.le], simp [hx_pos], end lemma of_real_rpow_of_nonneg {x p : ℝ} (hx_nonneg : 0 ≤ x) (hp_nonneg : 0 ≤ p) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hx0 : x = 0, { rw ← ne.def at hp0, have hp_pos : 0 < p := lt_of_le_of_ne hp_nonneg hp0.symm, simp [hx0, hp_pos, hp_pos.ne.symm], }, rw ← ne.def at hx0, exact of_real_rpow_of_pos (hx_nonneg.lt_of_ne hx0.symm), end lemma rpow_left_injective {x : ℝ} (hx : x ≠ 0) : function.injective (λ y : ℝ≥0∞, y^x) := begin intros y z hyz, dsimp only at hyz, rw [←rpow_one y, ←rpow_one z, ←_root_.mul_inv_cancel hx, rpow_mul, rpow_mul, hyz], end lemma rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : function.surjective (λ y : ℝ≥0∞, y^x) := λ y, ⟨y ^ x⁻¹, by simp_rw [←rpow_mul, _root_.inv_mul_cancel hx, rpow_one]⟩ lemma rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : function.bijective (λ y : ℝ≥0∞, y^x) := ⟨rpow_left_injective hx, rpow_left_surjective hx⟩ lemma rpow_left_monotone_of_nonneg {x : ℝ} (hx : 0 ≤ x) : monotone (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_le_rpow hyz hx lemma rpow_left_strict_mono_of_pos {x : ℝ} (hx : 0 < x) : strict_mono (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_lt_rpow hyz hx instance : has_measurable_pow ℝ≥0∞ ℝ := begin refine ⟨ennreal.measurable_of_measurable_nnreal_prod _ _⟩, { simp_rw ennreal.coe_rpow_def, refine measurable.ite _ measurable_const (measurable_fst.pow measurable_snd).ennreal_coe, exact measurable_set.inter (measurable_fst (measurable_set_singleton 0)) (measurable_snd measurable_set_Iio), }, { simp_rw ennreal.top_rpow_def, refine measurable.ite measurable_set_Ioi measurable_const _, exact measurable.ite (measurable_set_singleton 0) measurable_const measurable_const, }, end end ennreal
ea283ddc80a6e4de8cf8ce691c57fe2b4b1c0b52
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/group/ulift.lean
1e790e3fd147d2c8148a5ccf1b7d89eef055c4e4
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,098
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 data.equiv.mul_add import tactic.pi_instances /-! # `ulift` instances for groups and monoids This file defines instances for group, monoid, semigroup and related structures on `ulift` types. (Recall `ulift α` is just a "copy" of a type `α` in a higher universe.) We use `tactic.pi_instance_derive_field`, even though it wasn't intended for this purpose, which seems to work fine. We also provide `ulift.mul_equiv : ulift R ≃* R` (and its additive analogue). -/ universes u v variables {α : Type u} {x y : ulift.{v} α} namespace ulift @[to_additive] instance has_one [has_one α] : has_one (ulift α) := ⟨⟨1⟩⟩ @[simp, to_additive] lemma one_down [has_one α] : (1 : ulift α).down = 1 := rfl @[to_additive] instance has_mul [has_mul α] : has_mul (ulift α) := ⟨λ f g, ⟨f.down * g.down⟩⟩ @[simp, to_additive] lemma mul_down [has_mul α] : (x * y).down = x.down * y.down := rfl @[to_additive] instance has_div [has_div α] : has_div (ulift α) := ⟨λ f g, ⟨f.down / g.down⟩⟩ @[simp, to_additive] lemma div_down [has_div α] : (x / y).down = x.down / y.down := rfl @[to_additive] instance has_inv [has_inv α] : has_inv (ulift α) := ⟨λ f, ⟨f.down⁻¹⟩⟩ @[simp, to_additive] lemma inv_down [has_inv α] : x⁻¹.down = (x.down)⁻¹ := rfl /-- The multiplicative equivalence between `ulift α` and `α`. -/ @[to_additive "The additive equivalence between `ulift α` and `α`."] def mul_equiv [has_mul α] : ulift α ≃* α := { to_fun := ulift.down, inv_fun := ulift.up, map_mul' := λ x y, rfl, left_inv := by tidy, right_inv := by tidy, } @[to_additive] instance semigroup [semigroup α] : semigroup (ulift α) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance comm_semigroup [comm_semigroup α] : comm_semigroup (ulift α) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance mul_one_class [mul_one_class α] : mul_one_class (ulift α) := by refine_struct { mul := (*), one := (1 : ulift α), .. }; tactic.pi_instance_derive_field instance monoid [monoid α] : monoid (ulift α) := by refine_struct { one := (1 : ulift α), mul := (*), npow := λ n f, ⟨npow n f.down⟩ }; tactic.pi_instance_derive_field instance add_monoid [add_monoid α] : add_monoid (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), nsmul := λ n f, ⟨nsmul n f.down⟩ }; tactic.pi_instance_derive_field attribute [to_additive] ulift.monoid @[to_additive] instance comm_monoid [comm_monoid α] : comm_monoid (ulift α) := by refine_struct { one := (1 : ulift α), mul := (*), npow := λ n f, ⟨npow n f.down⟩ }; tactic.pi_instance_derive_field @[to_additive] instance group [group α] : group (ulift α) := by refine_struct { one := (1 : ulift α), mul := (*), inv := has_inv.inv, div := has_div.div, npow := λ n f, ⟨npow n f.down⟩, gpow := λ n f, ⟨gpow n f.down⟩ }; tactic.pi_instance_derive_field @[to_additive] instance comm_group [comm_group α] : comm_group (ulift α) := by refine_struct { one := (1 : ulift α), mul := (*), inv := has_inv.inv, div := has_div.div, npow := λ n f, ⟨npow n f.down⟩, gpow := λ n f, ⟨gpow n f.down⟩ }; tactic.pi_instance_derive_field @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [left_cancel_semigroup α] : left_cancel_semigroup (ulift α) := begin refine_struct { mul := (*) }; tactic.pi_instance_derive_field, have := congr_arg ulift.down ‹_›, assumption, end @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [right_cancel_semigroup α] : right_cancel_semigroup (ulift α) := begin refine_struct { mul := (*) }; tactic.pi_instance_derive_field, have := congr_arg ulift.down ‹_›, assumption, end -- TODO we don't do `ordered_cancel_comm_monoid` or `ordered_comm_group` -- We'd need to add instances for `ulift` in `order.basic`. end ulift
3f6279e73f3eec1e740063f10fce6623169224d9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/number_theory/dioph.lean
303868f07b3099700cede045788770e649571981
[]
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
25,510
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.number_theory.pell import Mathlib.data.pfun import Mathlib.data.fin2 import Mathlib.PostPort universes u u_1 u_2 u_3 namespace Mathlib namespace int theorem eq_nat_abs_iff_mul (x : ℤ) (n : ℕ) : nat_abs x = n ↔ (x - ↑n) * (x + ↑n) = 0 := sorry end int /-- Alternate definition of `vector` based on `fin2`. -/ def vector3 (α : Type u) (n : ℕ) := fin2 n → α namespace vector3 /-- The empty vector -/ def nil {α : Type u_1} : vector3 α 0 := sorry /-- The vector cons operation -/ def cons {α : Type u_1} {n : ℕ} (a : α) (v : vector3 α n) : vector3 α (Nat.succ n) := fun (i : fin2 (Nat.succ n)) => fin2.cases' a v i infixr:67 " :: " => Mathlib.vector3.cons /- We do not want to make the following notation global, because then these expressions will be overloaded, and only the expected type will be able to disambiguate the meaning. Worse: Lean will try to insert a coercion from `vector3 α _` to `list α`, if a list is expected. -/ @[simp] theorem cons_fz {α : Type u_1} {n : ℕ} (a : α) (v : vector3 α n) : cons a v fin2.fz = a := rfl @[simp] theorem cons_fs {α : Type u_1} {n : ℕ} (a : α) (v : vector3 α n) (i : fin2 n) : cons a v (fin2.fs i) = v i := rfl /-- Get the `i`th element of a vector -/ def nth {α : Type u_1} {n : ℕ} (i : fin2 n) (v : vector3 α n) : α := v i /-- Construct a vector from a function on `fin2`. -/ def of_fn {α : Type u_1} {n : ℕ} (f : fin2 n → α) : vector3 α n := f /-- Get the head of a nonempty vector. -/ def head {α : Type u_1} {n : ℕ} (v : vector3 α (Nat.succ n)) : α := v fin2.fz /-- Get the tail of a nonempty vector. -/ def tail {α : Type u_1} {n : ℕ} (v : vector3 α (Nat.succ n)) : vector3 α n := fun (i : fin2 n) => v (fin2.fs i) theorem eq_nil {α : Type u_1} (v : vector3 α 0) : v = nil := sorry theorem cons_head_tail {α : Type u_1} {n : ℕ} (v : vector3 α (Nat.succ n)) : head v :: tail v = v := funext fun (i : fin2 (Nat.succ n)) => fin2.cases' rfl (fun (_x : fin2 n) => rfl) i def nil_elim {α : Type u_1} {C : vector3 α 0 → Sort u} (H : C nil) (v : vector3 α 0) : C v := eq.mpr sorry H def cons_elim {α : Type u_1} {n : ℕ} {C : vector3 α (Nat.succ n) → Sort u} (H : (a : α) → (t : vector3 α n) → C (a :: t)) (v : vector3 α (Nat.succ n)) : C v := eq.mpr sorry (H (head v) (tail v)) @[simp] theorem cons_elim_cons {α : Type u_1} {n : ℕ} {C : vector3 α (Nat.succ n) → Sort u_2} {H : (a : α) → (t : vector3 α n) → C (a :: t)} {a : α} {t : vector3 α n} : cons_elim H (a :: t) = H a t := rfl protected def rec_on {α : Type u_1} {C : {n : ℕ} → vector3 α n → Sort u} {n : ℕ} (v : vector3 α n) (H0 : C nil) (Hs : {n : ℕ} → (a : α) → (w : vector3 α n) → C w → C (a :: w)) : C v := nat.rec_on n (fun (v : vector3 α 0) => nil_elim H0 v) (fun (n : ℕ) (IH : (_a : vector3 α n) → C _a) (v : vector3 α (Nat.succ n)) => cons_elim (fun (a : α) (t : vector3 α n) => Hs a t (IH t)) v) v @[simp] theorem rec_on_nil {α : Type u_1} {C : {n : ℕ} → vector3 α n → Sort u_2} {H0 : C nil} {Hs : {n : ℕ} → (a : α) → (w : vector3 α n) → C w → C (a :: w)} : vector3.rec_on nil H0 Hs = H0 := rfl @[simp] theorem rec_on_cons {α : Type u_1} {C : {n : ℕ} → vector3 α n → Sort u_2} {H0 : C nil} {Hs : {n : ℕ} → (a : α) → (w : vector3 α n) → C w → C (a :: w)} {n : ℕ} {a : α} {v : vector3 α n} : vector3.rec_on (a :: v) H0 Hs = Hs a v (vector3.rec_on v H0 Hs) := rfl /-- Append two vectors -/ def append {α : Type u_1} {m : ℕ} (v : vector3 α m) {n : ℕ} (w : vector3 α n) : vector3 α (n + m) := nat.rec_on m (fun (_x : vector3 α 0) => w) (fun (m : ℕ) (IH : vector3 α m → vector3 α (n + m)) (v : vector3 α (Nat.succ m)) => cons_elim (fun (a : α) (t : vector3 α m) => fin2.cases' a (IH t)) v) v @[simp] theorem append_nil {α : Type u_1} {n : ℕ} (w : vector3 α n) : append nil w = w := rfl @[simp] theorem append_cons {α : Type u_1} (a : α) {m : ℕ} (v : vector3 α m) {n : ℕ} (w : vector3 α n) : append (a :: v) w = a :: append v w := rfl @[simp] theorem append_left {α : Type u_1} {m : ℕ} (i : fin2 m) (v : vector3 α m) {n : ℕ} (w : vector3 α n) : append v w (fin2.left n i) = v i := sorry @[simp] theorem append_add {α : Type u_1} {m : ℕ} (v : vector3 α m) {n : ℕ} (w : vector3 α n) (i : fin2 n) : append v w (fin2.add i m) = w i := sorry /-- Insert `a` into `v` at index `i`. -/ def insert {α : Type u_1} (a : α) {n : ℕ} (v : vector3 α n) (i : fin2 (Nat.succ n)) : vector3 α (Nat.succ n) := fun (j : fin2 (Nat.succ n)) => cons a v (fin2.insert_perm i j) @[simp] theorem insert_fz {α : Type u_1} (a : α) {n : ℕ} (v : vector3 α n) : insert a v fin2.fz = a :: v := sorry @[simp] theorem insert_fs {α : Type u_1} (a : α) {n : ℕ} (b : α) (v : vector3 α n) (i : fin2 (Nat.succ n)) : insert a (b :: v) (fin2.fs i) = b :: insert a v i := sorry theorem append_insert {α : Type u_1} (a : α) {k : ℕ} (t : vector3 α k) {n : ℕ} (v : vector3 α n) (i : fin2 (Nat.succ n)) (e : Nat.succ n + k = Nat.succ (n + k)) : insert a (append t v) (eq.rec_on e (fin2.add i k)) = eq.rec_on e (append t (insert a v i)) := sorry end vector3 /-- "Curried" exists, i.e. ∃ x1 ... xn, f [x1, ..., xn] -/ def vector_ex {α : Type u_1} (k : ℕ) : (vector3 α k → Prop) → Prop := sorry /-- "Curried" forall, i.e. ∀ x1 ... xn, f [x1, ..., xn] -/ def vector_all {α : Type u_1} (k : ℕ) : (vector3 α k → Prop) → Prop := sorry theorem exists_vector_zero {α : Type u_1} (f : vector3 α 0 → Prop) : Exists f ↔ f vector3.nil := sorry theorem exists_vector_succ {α : Type u_1} {n : ℕ} (f : vector3 α (Nat.succ n) → Prop) : Exists f ↔ ∃ (x : α), ∃ (v : vector3 α n), f (x :: v) := sorry theorem vector_ex_iff_exists {α : Type u_1} {n : ℕ} (f : vector3 α n → Prop) : vector_ex n f ↔ Exists f := sorry theorem vector_all_iff_forall {α : Type u_1} {n : ℕ} (f : vector3 α n → Prop) : vector_all n f ↔ ∀ (v : vector3 α n), f v := sorry /-- `vector_allp p v` is equivalent to `∀ i, p (v i)`, but unfolds directly to a conjunction, i.e. `vector_allp p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ def vector_allp {α : Type u_1} (p : α → Prop) {n : ℕ} (v : vector3 α n) := vector3.rec_on v True fun (n : ℕ) (a : α) (v : vector3 α n) (IH : Prop) => vector3.rec_on v (p a) fun (n : ℕ) (b : α) (v' : vector3 α n) (_x : Prop) => p a ∧ IH @[simp] theorem vector_allp_nil {α : Type u_1} (p : α → Prop) : vector_allp p vector3.nil = True := rfl @[simp] theorem vector_allp_singleton {α : Type u_1} (p : α → Prop) (x : α) : vector_allp p (x :: vector3.nil) = p x := rfl @[simp] theorem vector_allp_cons {α : Type u_1} (p : α → Prop) {n : ℕ} (x : α) (v : vector3 α n) : vector_allp p (x :: v) ↔ p x ∧ vector_allp p v := vector3.rec_on v (iff.symm (and_true (vector_allp p (x :: vector3.nil)))) fun (n : ℕ) (a : α) (v : vector3 α n) (IH : vector_allp p (x :: v) ↔ p x ∧ vector_allp p v) => iff.rfl theorem vector_allp_iff_forall {α : Type u_1} (p : α → Prop) {n : ℕ} (v : vector3 α n) : vector_allp p v ↔ ∀ (i : fin2 n), p (v i) := sorry theorem vector_allp.imp {α : Type u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (x : α), p x → q x) {n : ℕ} {v : vector3 α n} (al : vector_allp p v) : vector_allp q v := iff.mpr (vector_allp_iff_forall q v) fun (i : fin2 n) => h (v i) (iff.mp (vector_allp_iff_forall p v) al i) /-- `list_all p l` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `list_all p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def list_all {α : Type u_1} (p : α → Prop) : List α → Prop := sorry @[simp] theorem list_all_cons {α : Type u_1} (p : α → Prop) (x : α) (l : List α) : list_all p (x :: l) ↔ p x ∧ list_all p l := list.cases_on l (idRhs (list_all p [x] ↔ list_all p [x] ∧ True) (iff.symm (and_true (list_all p [x])))) fun (l_hd : α) (l_tl : List α) => idRhs (list_all p (x :: l_hd :: l_tl) ↔ list_all p (x :: l_hd :: l_tl)) iff.rfl theorem list_all_iff_forall {α : Type u_1} (p : α → Prop) (l : List α) : list_all p l ↔ ∀ (x : α), x ∈ l → p x := sorry theorem list_all.imp {α : Type u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (x : α), p x → q x) {l : List α} : list_all p l → list_all q l := sorry @[simp] theorem list_all_map {α : Type u_1} {β : Type u_2} {p : β → Prop} (f : α → β) {l : List α} : list_all p (list.map f l) ↔ list_all (p ∘ f) l := sorry theorem list_all_congr {α : Type u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (x : α), p x ↔ q x) {l : List α} : list_all p l ↔ list_all q l := { mp := list_all.imp fun (x : α) => iff.mp (h x), mpr := list_all.imp fun (x : α) => iff.mpr (h x) } protected instance decidable_list_all {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : List α) : Decidable (list_all p l) := decidable_of_decidable_of_iff (list.decidable_ball (fun (x : α) => p x) l) sorry /- poly -/ /-- A predicate asserting that a function is a multivariate integer polynomial. (We are being a bit lazy here by allowing many representations for multiplication, rather than only allowing monomials and addition, but the definition is equivalent and this is easier to use.) -/ inductive is_poly {α : Sort u_1} : ((α → ℕ) → ℤ) → Prop where | proj : ∀ (i : α), is_poly fun (x : α → ℕ) => ↑(x i) | const : ∀ (n : ℤ), is_poly fun (x : α → ℕ) => n | sub : ∀ {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly fun (x : α → ℕ) => f x - g x | mul : ∀ {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly fun (x : α → ℕ) => f x * g x /-- The type of multivariate integer polynomials -/ def poly (α : Type u) := Subtype fun (f : (α → ℕ) → ℤ) => is_poly f namespace poly protected instance has_coe_to_fun {α : Type u} : has_coe_to_fun (poly α) := has_coe_to_fun.mk (fun (f : poly α) => (α → ℕ) → ℤ) fun (f : poly α) => subtype.val f /-- The underlying function of a `poly` is a polynomial -/ theorem isp {α : Type u} (f : poly α) : is_poly ⇑f := subtype.property f /-- Extensionality for `poly α` -/ theorem ext {α : Type u} {f : poly α} {g : poly α} (e : ∀ (x : α → ℕ), coe_fn f x = coe_fn g x) : f = g := subtype.eq (funext e) /-- Construct a `poly` given an extensionally equivalent `poly`. -/ def subst {α : Type u} (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀ (x : α → ℕ), coe_fn f x = g x) : poly α := { val := g, property := sorry } @[simp] theorem subst_eval {α : Type u} (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀ (x : α → ℕ), coe_fn f x = g x) (x : α → ℕ) : coe_fn (subst f g e) x = g x := rfl /-- The `i`th projection function, `x_i`. -/ def proj {α : Type u} (i : α) : poly α := { val := fun (x : α → ℕ) => ↑(x i), property := is_poly.proj i } @[simp] theorem proj_eval {α : Type u} (i : α) (x : α → ℕ) : coe_fn (proj i) x = ↑(x i) := rfl /-- The constant function with value `n : ℤ`. -/ def const {α : Type u} (n : ℤ) : poly α := { val := fun (x : α → ℕ) => n, property := is_poly.const n } @[simp] theorem const_eval {α : Type u} (n : ℤ) (x : α → ℕ) : coe_fn (const n) x = n := rfl /-- The zero polynomial -/ def zero {α : Type u} : poly α := const 0 protected instance has_zero {α : Type u} : HasZero (poly α) := { zero := zero } @[simp] theorem zero_eval {α : Type u} (x : α → ℕ) : coe_fn 0 x = 0 := rfl /-- The zero polynomial -/ def one {α : Type u} : poly α := const 1 protected instance has_one {α : Type u} : HasOne (poly α) := { one := one } @[simp] theorem one_eval {α : Type u} (x : α → ℕ) : coe_fn 1 x = 1 := rfl /-- Subtraction of polynomials -/ def sub {α : Type u} : poly α → poly α → poly α := sorry protected instance has_sub {α : Type u} : Sub (poly α) := { sub := sub } @[simp] theorem sub_eval {α : Type u} (f : poly α) (g : poly α) (x : α → ℕ) : coe_fn (f - g) x = coe_fn f x - coe_fn g x := sorry /-- Negation of a polynomial -/ def neg {α : Type u} (f : poly α) : poly α := 0 - f protected instance has_neg {α : Type u} : Neg (poly α) := { neg := neg } @[simp] theorem neg_eval {α : Type u} (f : poly α) (x : α → ℕ) : coe_fn (-f) x = -coe_fn f x := sorry /-- Addition of polynomials -/ def add {α : Type u} : poly α → poly α → poly α := sorry protected instance has_add {α : Type u} : Add (poly α) := { add := add } @[simp] theorem add_eval {α : Type u} (f : poly α) (g : poly α) (x : α → ℕ) : coe_fn (f + g) x = coe_fn f x + coe_fn g x := sorry /-- Multiplication of polynomials -/ def mul {α : Type u} : poly α → poly α → poly α := sorry protected instance has_mul {α : Type u} : Mul (poly α) := { mul := mul } @[simp] theorem mul_eval {α : Type u} (f : poly α) (g : poly α) (x : α → ℕ) : coe_fn (f * g) x = coe_fn f x * coe_fn g x := sorry protected instance comm_ring {α : Type u} : comm_ring (poly α) := comm_ring.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry sorry theorem induction {α : Type u} {C : poly α → Prop} (H1 : ∀ (i : α), C (proj i)) (H2 : ∀ (n : ℤ), C (const n)) (H3 : ∀ (f g : poly α), C f → C g → C (f - g)) (H4 : ∀ (f g : poly α), C f → C g → C (f * g)) (f : poly α) : C f := sorry /-- The sum of squares of a list of polynomials. This is relevant for Diophantine equations, because it means that a list of equations can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is equivalent to `x^2 + y^2 + z^2 = 0`. -/ def sumsq {α : Type u} : List (poly α) → poly α := sorry theorem sumsq_nonneg {α : Type u} (x : α → ℕ) (l : List (poly α)) : 0 ≤ coe_fn (sumsq l) x := sorry theorem sumsq_eq_zero {α : Type u} (x : α → ℕ) (l : List (poly α)) : coe_fn (sumsq l) x = 0 ↔ list_all (fun (a : poly α) => coe_fn a x = 0) l := sorry /-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/ def remap {α : Type u_1} {β : Type u_2} (f : α → β) (g : poly α) : poly β := { val := fun (v : β → ℕ) => coe_fn g (v ∘ f), property := sorry } @[simp] theorem remap_eval {α : Type u_1} {β : Type u_2} (f : α → β) (g : poly α) (v : β → ℕ) : coe_fn (remap f g) v = coe_fn g (v ∘ f) := rfl end poly namespace sum /-- combine two functions into a function on the disjoint union -/ def join {α : Type u_1} {β : Type u_2} {γ : Sort u_3} (f : α → γ) (g : β → γ) : α ⊕ β → γ := sum.rec f g end sum namespace option /-- Functions from `option` can be combined similarly to `vector.cons` -/ def cons {α : Type u_1} {β : Sort u_2} (a : β) (v : α → β) : Option α → β := Option.rec a v infixr:67 " :: " => Mathlib.option.cons @[simp] theorem cons_head_tail {α : Type u_1} {β : Sort u_2} (v : Option α → β) : v none :: v ∘ some = v := sorry end option /- dioph -/ /-- A set `S ⊆ ℕ^α` is diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/ def dioph {α : Type u} (S : set (α → ℕ)) := Exists fun {β : Type u} => ∃ (p : poly (α ⊕ β)), ∀ (v : α → ℕ), S v ↔ ∃ (t : β → ℕ), coe_fn p (sum.join v t) = 0 namespace dioph theorem ext {α : Type u} {S : set (α → ℕ)} {S' : set (α → ℕ)} (d : dioph S) (H : ∀ (v : α → ℕ), S v ↔ S' v) : dioph S' := Eq._oldrec d ((fun (this : S = S') => this) (set.ext H)) theorem of_no_dummies {α : Type u} (S : set (α → ℕ)) (p : poly α) (h : ∀ (v : α → ℕ), S v ↔ coe_fn p v = 0) : dioph S := sorry theorem inject_dummies_lem {α : Type u} {β : Type u} {γ : Type u} (f : β → γ) (g : γ → Option β) (inv : ∀ (x : β), g (f x) = some x) (p : poly (α ⊕ β)) (v : α → ℕ) : (∃ (t : β → ℕ), coe_fn p (sum.join v t) = 0) ↔ ∃ (t : γ → ℕ), coe_fn (poly.remap (sum.join sum.inl (sum.inr ∘ f)) p) (sum.join v t) = 0 := sorry theorem inject_dummies {α : Type u} {β : Type u} {γ : Type u} {S : set (α → ℕ)} (f : β → γ) (g : γ → Option β) (inv : ∀ (x : β), g (f x) = some x) (p : poly (α ⊕ β)) (h : ∀ (v : α → ℕ), S v ↔ ∃ (t : β → ℕ), coe_fn p (sum.join v t) = 0) : ∃ (q : poly (α ⊕ γ)), ∀ (v : α → ℕ), S v ↔ ∃ (t : γ → ℕ), coe_fn q (sum.join v t) = 0 := Exists.intro (poly.remap (sum.join sum.inl (sum.inr ∘ f)) p) fun (v : α → ℕ) => iff.trans (h v) (inject_dummies_lem f g inv p v) theorem reindex_dioph {α : Type u} {β : Type u} {S : set (α → ℕ)} (d : dioph S) (f : α → β) : dioph fun (v : β → ℕ) => S (v ∘ f) := sorry theorem dioph_list_all {α : Type u} (l : List (set (α → ℕ))) (d : list_all dioph l) : dioph fun (v : α → ℕ) => list_all (fun (S : set (α → ℕ)) => S v) l := sorry theorem and_dioph {α : Type u} {S : set (α → ℕ)} {S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph fun (v : α → ℕ) => S v ∧ S' v := dioph_list_all [S, S'] { left := d, right := d' } theorem or_dioph {α : Type u} {S : set (α → ℕ)} {S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph fun (v : α → ℕ) => S v ∨ S' v := sorry /-- A partial function is Diophantine if its graph is Diophantine. -/ def dioph_pfun {α : Type u} (f : (α → ℕ) →. ℕ) := dioph fun (v : Option α → ℕ) => pfun.graph f (v ∘ some, v none) /-- A function is Diophantine if its graph is Diophantine. -/ def dioph_fn {α : Type u} (f : (α → ℕ) → ℕ) := dioph fun (v : Option α → ℕ) => f (v ∘ some) = v none theorem reindex_dioph_fn {α : Type u} {β : Type u} {f : (α → ℕ) → ℕ} (d : dioph_fn f) (g : α → β) : dioph_fn fun (v : β → ℕ) => f (v ∘ g) := reindex_dioph d (Functor.map g) theorem ex_dioph {α : Type u} {β : Type u} {S : set (α ⊕ β → ℕ)} : dioph S → dioph fun (v : α → ℕ) => ∃ (x : β → ℕ), S (sum.join v x) := sorry theorem ex1_dioph {α : Type u} {S : set (Option α → ℕ)} : dioph S → dioph fun (v : α → ℕ) => ∃ (x : ℕ), S (x :: v) := sorry theorem dom_dioph {α : Type u} {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph (pfun.dom f) := cast (congr_arg dioph (set.ext fun (v : α → ℕ) => iff.symm (pfun.dom_iff_graph f v))) (ex1_dioph d) theorem dioph_fn_iff_pfun {α : Type u} (f : (α → ℕ) → ℕ) : dioph_fn f = dioph_pfun ↑f := congr_arg dioph (set.ext fun (v : Option α → ℕ) => iff.symm pfun.lift_graph) theorem abs_poly_dioph {α : Type u} (p : poly α) : dioph_fn fun (v : α → ℕ) => int.nat_abs (coe_fn p v) := of_no_dummies (fun (v : Option α → ℕ) => (fun (v : α → ℕ) => int.nat_abs (coe_fn p v)) (v ∘ some) = v none) ((poly.remap some p - poly.proj none) * (poly.remap some p + poly.proj none)) fun (v : Option α → ℕ) => int.eq_nat_abs_iff_mul (coe_fn p (v ∘ some)) (v none) theorem proj_dioph {α : Type u} (i : α) : dioph_fn fun (v : α → ℕ) => v i := abs_poly_dioph (poly.proj i) theorem dioph_pfun_comp1 {α : Type u} {S : set (Option α → ℕ)} (d : dioph S) {f : (α → ℕ) →. ℕ} (df : dioph_pfun f) : dioph fun (v : α → ℕ) => ∃ (h : pfun.dom f v), S (pfun.fn f v h :: v) := sorry theorem dioph_fn_comp1 {α : Type u} {S : set (Option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) : dioph fun (v : α → ℕ) => S (f v :: v) := sorry theorem dioph_fn_vec_comp1 {n : ℕ} {S : set (vector3 ℕ (Nat.succ n))} (d : dioph S) {f : vector3 ℕ n → ℕ} (df : dioph_fn f) : dioph fun (v : vector3 ℕ n) => S (f v :: v) := sorry theorem vec_ex1_dioph (n : ℕ) {S : set (vector3 ℕ (Nat.succ n))} (d : dioph S) : dioph fun (v : vector3 ℕ n) => ∃ (x : ℕ), S (x :: v) := sorry theorem dioph_fn_vec {n : ℕ} (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph fun (v : vector3 ℕ (Nat.succ n)) => f (v ∘ fin2.fs) = v fin2.fz := { mp := fun (h : dioph_fn f) => reindex_dioph h (fin2.fz :: fin2.fs), mpr := fun (h : dioph fun (v : vector3 ℕ (Nat.succ n)) => f (v ∘ fin2.fs) = v fin2.fz) => reindex_dioph h (none :: some) } theorem dioph_pfun_vec {n : ℕ} (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph fun (v : vector3 ℕ (Nat.succ n)) => pfun.graph f (v ∘ fin2.fs, v fin2.fz) := sorry theorem dioph_fn_compn {α : Type} {n : ℕ} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f) : dioph fun (v : α → ℕ) => S (sum.join v fun (i : fin2 n) => f i v) := sorry theorem dioph_comp {α : Type} {n : ℕ} {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph fun (v : α → ℕ) => S fun (i : fin2 n) => f i v := dioph_fn_compn (reindex_dioph d sum.inr) df theorem dioph_fn_comp {α : Type} {n : ℕ} {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn fun (v : α → ℕ) => f fun (i : fin2 n) => g i v := sorry theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [fin2.is_lt m n] : dioph_fn fun (v : vector3 ℕ n) => v (fin2.of_nat' m) := proj_dioph (fin2.of_nat' m) theorem const_dioph {α : Type} (n : ℕ) : dioph_fn (function.const (α → ℕ) n) := abs_poly_dioph (poly.const ↑n) theorem dioph_comp2 {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) {S : ℕ → ℕ → Prop} (d : dioph fun (v : vector3 ℕ (bit0 1)) => S (v (fin2.of_nat' 0)) (v (fin2.of_nat' 1))) : dioph fun (v : α → ℕ) => S (f v) (g v) := dioph_comp d (f :: g :: vector3.nil) { left := df, right := dg } theorem dioph_fn_comp2 {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) {h : ℕ → ℕ → ℕ} (d : dioph_fn fun (v : vector3 ℕ (bit0 1)) => h (v (fin2.of_nat' 0)) (v (fin2.of_nat' 1))) : dioph_fn fun (v : α → ℕ) => h (f v) (g v) := dioph_fn_comp d (f :: g :: vector3.nil) { left := df, right := dg } theorem eq_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph fun (v : α → ℕ) => f v = g v := sorry theorem add_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph_fn fun (v : α → ℕ) => f v + g v := dioph_fn_comp2 df dg (abs_poly_dioph (poly.proj (fin2.of_nat' 0) + poly.proj (fin2.of_nat' 1))) theorem mul_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph_fn fun (v : α → ℕ) => f v * g v := dioph_fn_comp2 df dg (abs_poly_dioph (poly.proj (fin2.of_nat' 0) * poly.proj (fin2.of_nat' 1))) theorem le_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph fun (v : α → ℕ) => f v ≤ g v := sorry theorem lt_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph fun (v : α → ℕ) => f v < g v := le_dioph (add_dioph df (const_dioph 1)) dg theorem ne_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph fun (v : α → ℕ) => f v ≠ g v := ext (or_dioph (lt_dioph df dg) (lt_dioph dg df)) fun (v : α → ℕ) => iff.symm ne_iff_lt_or_gt theorem sub_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph_fn fun (v : α → ℕ) => f v - g v := sorry theorem dvd_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph fun (v : α → ℕ) => f v ∣ g v := sorry theorem mod_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph_fn fun (v : α → ℕ) => f v % g v := sorry theorem modeq_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph fun (v : α → ℕ) => nat.modeq (h v) (f v) (g v) := eq_dioph (mod_dioph df dh) (mod_dioph dg dh) theorem div_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph_fn fun (v : α → ℕ) => f v / g v := sorry theorem pell_dioph : dioph fun (v : vector3 ℕ (bit0 (bit0 1))) => ∃ (h : 1 < v (fin2.of_nat' 0)), pell.xn h (v (fin2.of_nat' 1)) = v (fin2.of_nat' (bit0 1)) ∧ pell.yn h (v (fin2.of_nat' 1)) = v (fin2.of_nat' (bit1 1)) := sorry theorem xn_dioph : dioph_pfun fun (v : vector3 ℕ (bit0 1)) => roption.mk (1 < v (fin2.of_nat' 0)) fun (h : 1 < v (fin2.of_nat' 0)) => pell.xn h (v (fin2.of_nat' 1)) := sorry theorem pow_dioph {α : Type} {f : (α → ℕ) → ℕ} {g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) : dioph_fn fun (v : α → ℕ) => f v ^ g v := sorry
fe7dbc23f5e2ef1fcd318babcf2cc7a3cf50c8ce
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/algebra/pi_instances.lean
be69235c017fd746a17e5e90c410ee0c9eda8a84
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
15,016
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot Pi instances for algebraic structures. -/ import order.basic import algebra.module algebra.group import data.finset import tactic.pi_instances namespace pi universes u v variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equiped with instances variables (x y : Π i, f i) (i : I) instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩ @[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩ @[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl attribute [to_additive pi.has_zero] pi.has_one attribute [to_additive pi.zero_apply] pi.one_apply instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩ @[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩ @[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl attribute [to_additive pi.has_add] pi.has_mul attribute [to_additive pi.add_apply] pi.mul_apply instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩ @[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩ @[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl attribute [to_additive pi.has_neg] pi.has_inv attribute [to_additive pi.neg_apply] pi.inv_apply instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) := by pi_instance instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule α} instance vector_space (α) {r : discrete_field α} [∀ i, add_comm_group $ f i] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) := {..pi.module α} instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) := by pi_instance instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) := by pi_instance instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) := by pi_instance attribute [to_additive pi.add_semigroup] pi.semigroup attribute [to_additive pi.add_comm_semigroup] pi.comm_semigroup attribute [to_additive pi.add_monoid] pi.monoid attribute [to_additive pi.add_comm_monoid] pi.comm_monoid attribute [to_additive pi.add_group] pi.group attribute [to_additive pi.add_comm_group] pi.comm_group attribute [to_additive pi.add_left_cancel_semigroup] pi.left_cancel_semigroup attribute [to_additive pi.add_right_cancel_semigroup] pi.right_cancel_semigroup @[to_additive pi.list_sum_apply] lemma list_prod_apply {α : Type*} {β} [monoid β] (a : α) : ∀ (l : list (α → β)), l.prod a = (l.map (λf:α → β, f a)).prod | [] := rfl | (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l] @[to_additive pi.multiset_sum_apply] lemma multiset_prod_apply {α : Type*} {β} [comm_monoid β] (a : α) (s : multiset (α → β)) : s.prod a = (s.map (λf:α → β, f a)).prod := quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end @[to_additive pi.finset_sum_apply] lemma finset_prod_apply {α : Type*} {β γ} [comm_monoid β] (a : α) (s : finset γ) (g : γ → α → β) : s.prod g a = s.prod (λc, g c a) := show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod, by rw [multiset_prod_apply, multiset.map_map] end pi namespace prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β} instance [has_add α] [has_add β] : has_add (α × β) := ⟨λp q, (p.1 + q.1, p.2 + q.2)⟩ @[to_additive prod.has_add] instance [has_mul α] [has_mul β] : has_mul (α × β) := ⟨λp q, (p.1 * q.1, p.2 * q.2)⟩ @[simp, to_additive prod.fst_add] lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive prod.snd_add] lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive prod.mk_add_mk] lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩ @[to_additive prod.has_zero] instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩ @[simp, to_additive prod.fst_zero] lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl @[simp, to_additive prod.snd_zero] lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl @[to_additive prod.zero_eq_mk] lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩ @[to_additive prod.has_neg] instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive prod.fst_neg] lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive prod.snd_neg] lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl @[to_additive prod.neg_mk] lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) := { add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩, .. prod.has_add } @[to_additive prod.add_semigroup] instance [semigroup α] [semigroup β] : semigroup (α × β) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } instance [add_monoid α] [add_monoid β] : add_monoid (α × β) := { zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩, add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩, .. prod.add_semigroup, .. prod.has_zero } @[to_additive prod.add_monoid] instance [monoid α] [monoid β] : monoid (α × β) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.semigroup, .. prod.has_one } instance [add_group α] [add_group β] : add_group (α × β) := { add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩, .. prod.add_monoid, .. prod.has_neg } @[to_additive prod.add_group] instance [group α] [group β] : group (α × β) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, .. prod.monoid, .. prod.has_inv } instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) := { add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩, .. prod.add_semigroup } @[to_additive prod.add_comm_semigroup] instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) := { .. prod.add_comm_semigroup, .. prod.add_monoid } @[to_additive prod.add_comm_monoid] instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) := { .. prod.comm_semigroup, .. prod.monoid } instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) := { .. prod.add_comm_semigroup, .. prod.add_group } @[to_additive prod.add_comm_group] instance [comm_group α] [comm_group β] : comm_group (α × β) := { .. prod.comm_semigroup, .. prod.group } @[to_additive prod.fst_sum] lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).1 = t.prod (λc, (f c).1) := (finset.prod_hom prod.fst (show (1:α×β).1 = 1, from rfl) $ assume x y, rfl).symm @[to_additive prod.snd_sum] lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).2 = t.prod (λc, (f c).2) := (finset.prod_hom prod.snd (show (1:α×β).2 = 1, from rfl) $ assume x y, rfl).symm instance [semiring α] [semiring β] : semiring (α × β) := { zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩, right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩, ..prod.add_comm_monoid, ..prod.monoid } instance [ring α] [ring β] : ring (α × β) := { ..prod.add_comm_group, ..prod.semiring } instance [comm_ring α] [comm_ring β] : comm_ring (α × β) := { ..prod.ring, ..prod.comm_monoid } instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) := { zero_ne_one := mt (congr_arg prod.fst) zero_ne_one, ..prod.comm_ring } /-- Left injection function for the inner product From a vector space (and also group and module) perspective the product is the same as the sum of two vector spaces. `inl` and `inr` provide the corresponding injection functions. -/ def inl [has_zero β] (a : α) : α × β := (a, 0) /-- Right injection function for the inner product -/ def inr [has_zero α] (b : β) : α × β := (0, b) lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) := assume x y h, (prod.mk.inj_iff.mp h).1 lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) := assume x y h, (prod.mk.inj_iff.mp h).2 @[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ := iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl) @[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ := iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl) @[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} : inl a = inr b ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} : inr b = inl a ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl @[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl @[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl @[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl @[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl @[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ] (a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ] [semimodule α β] [semimodule α γ] : semimodule α (β × γ) := { smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _, one_smul _⟩, zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _, zero_smul _⟩, smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩, .. prod.has_scalar } instance {r : ring α} [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] : module α (β × γ) := {} instance {r : discrete_field α} [add_comm_group β] [add_comm_group γ] [vector_space α β] [vector_space α γ] : vector_space α (β × γ) := {} end prod namespace finset @[to_additive finset.prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) end finset
056c778b6d3920611196eb245ecab706d1f11ac8
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/Basic.lean
c08f136ca8fe7a259e54fbdec09a2f520e6e66d8
[ "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
73,186
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.Trace import Lean.Util.RecDepth import Lean.Util.PPExt import Lean.Util.ReplaceExpr import Lean.Util.OccursCheck import Lean.Util.MonadBacktrack import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode import Lean.Meta.DiscrTreeTypes import Lean.Eval import Lean.CoreM /-! This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck /-- Configuration flags for the `MetaM` monad. Many of them are used to control the `isDefEq` function that checks whether two terms are definitionally equal or not. Recall that when `isDefEq` is trying to check whether `?m@C a₁ ... aₙ` and `t` are definitionally equal (`?m@C a₁ ... aₙ =?= t`), where `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. We solve it using the assignment `?m := fun a₁ ... aₙ => t` if 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` -/ structure Config where /-- If `foApprox` is set to true, and some `aᵢ` is not a free variable, then we use first-order unification ``` ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k ``` reduces to ``` ?m a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k ``` -/ foApprox : Bool := false /-- When `ctxApprox` is set to true, we relax condition 4, by creating an auxiliary metavariable `?n'` with a smaller context than `?m'`. -/ ctxApprox : Bool := false /-- When `quasiPatternApprox` is set to true, we ignore condition 2. -/ quasiPatternApprox : Bool := false /-- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ constApprox : Bool := false /-- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ isDefEqStuckEx : Bool := false /-- Controls which definitions and theorems can be unfolded by `isDefEq` and `whnf`. -/ transparency : TransparencyMode := TransparencyMode.default /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ zetaNonDep : Bool := true /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ trackZeta : Bool := false /-- Enable/disable the unification hints feature. -/ unificationHints : Bool := true /-- Enables proof irrelevance at `isDefEq` -/ proofIrrelevance : Bool := true /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make sure typing constraints resolved during elaboration should not "fill" holes that are supposed to be filled using tactics. However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because this last unification step is not really part of the term elaboration. -/ assignSyntheticOpaque : Bool := false /-- When `ignoreLevelDepth` is `false`, only universe level metavariables with depth == metavariable context depth can be assigned. We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few cases. Recall that universe levels are often ignored by users, they may not even be aware they exist. We still use this restriction for regular metavariables. See discussion at the beginning of `MetavarContext.lean`. We claim it is reasonable to ignore this restriction for universe metavariables because their values are often contrained by the terms is instances and simp theorems. TODO: we should delete this configuration option and the method `isReadOnlyLevelMVar` after we have more tests. -/ ignoreLevelMVarDepth : Bool := true /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/ offsetCnstrs : Bool := true /-- Eta for structures configuration mode. -/ etaStruct : EtaStructMode := .all /-- Function parameter information cache. -/ structure ParamInfo where /-- The binder annotation for the parameter. -/ binderInfo : BinderInfo := BinderInfo.default /-- `hasFwdDeps` is true if there is another parameter whose type depends on this one. -/ hasFwdDeps : Bool := false /-- `backDeps` contains the backwards dependencies. That is, the (0-indexed) position of previous parameters that this one depends on. -/ backDeps : Array Nat := #[] /-- `isProp` is true if the parameter is always a proposition. -/ isProp : Bool := false /-- `isDecInst` is true if the parameter's type is of the form `Decidable ...`. This information affects the generation of congruence theorems. -/ isDecInst : Bool := false /-- `higherOrderOutParam` is true if this parameter is a higher-order output parameter of local instance. Example: ``` getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` This flag is true for the parameter `dom` because it is output parameter of `[self : GetElem cont idx elem dom]` -/ higherOrderOutParam : Bool := false /-- `dependsOnHigherOrderOutParam` is true if the type of this parameter depends on the higher-order output parameter of a previous local instance. Example: ``` getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` This flag is true for the parameter with type `dom xs i` since `dom` is an output parameter of the instance `[self : GetElem cont idx elem dom]` -/ dependsOnHigherOrderOutParam : Bool := false deriving Inhabited def ParamInfo.isImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.implicit def ParamInfo.isInstImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.instImplicit def ParamInfo.isStrictImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.strictImplicit def ParamInfo.isExplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.default || p.binderInfo == BinderInfo.auxDecl /-- Function information cache. See `ParamInfo`. -/ structure FunInfo where /-- Parameter information cache. -/ paramInfo : Array ParamInfo := #[] /-- `resultDeps` contains the function result type backwards dependencies. That is, the (0-indexed) position of parameters that the result type depends on. -/ resultDeps : Array Nat := #[] /-- Key for the function information cache. -/ structure InfoCacheKey where /-- The transparency mode used to compute the `FunInfo`. -/ transparency : TransparencyMode /-- The function being cached information about. It is quite often an `Expr.const`. -/ expr : Expr /-- `nargs? = some n` if the cached information was computed assuming the function has arity `n`. If `nargs? = none`, then the cache information consumed the arrow type as much as possible unsing the current transparency setting. X-/ nargs? : Option Nat deriving Inhabited, BEq namespace InfoCacheKey instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩ end InfoCacheKey open Std (PersistentArray PersistentHashMap) abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) abbrev InferTypeCache := PersistentExprStructMap Expr abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo abbrev WhnfCache := PersistentExprStructMap Expr /-- A mapping `(s, t) ↦ isDefEq s t`. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache). We should also investigate the impact on memory consumption. -/ abbrev DefEqCache := PersistentHashMap (Expr × Expr) Bool /-- Cache datastructures for type inference, type class resolution, whnf, and definitional equality. -/ structure Cache where inferType : InferTypeCache := {} funInfo : FunInfoCache := {} synthInstance : SynthInstanceCache := {} whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default` whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all` defEq : DefEqCache := {} deriving Inhabited /-- "Context" for a postponed universe constraint. `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created. -/ structure DefEqContext where lhs : Expr rhs : Expr lctx : LocalContext localInstances : LocalInstances /-- Auxiliary structure for representing postponed universe constraints. Remark: the fields `ref` and `rootDefEq?` are used for error message generation only. Remark: we may consider improving the error message generation in the future. -/ structure PostponedEntry where /-- We save the `ref` at entry creation time. This is used for reporting errors back to the user. -/ ref : Syntax lhs : Level rhs : Level /-- Context for the surrounding `isDefEq` call when entry was created. -/ ctx? : Option DefEqContext deriving Inhabited /-- `MetaM` monad state. -/ structure State where mctx : MetavarContext := {} cache : Cache := {} /-- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ zetaFVarIds : FVarIdSet := {} /-- Array of postponed universe level constraints -/ postponed : PersistentArray PostponedEntry := {} deriving Inhabited /-- Backtrackable state for the `MetaM` monad. -/ structure SavedState where core : Core.State meta : State deriving Inhabited /-- Contextual information for the `MetaM` monad. -/ structure Context where config : Config := {} /-- Local context -/ lctx : LocalContext := {} /-- Local instances in `lctx`. -/ localInstances : LocalInstances := #[] /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/ defEqCtx? : Option DefEqContext := none /-- Track the number of nested `synthPending` invocations. Nested invocations can happen when the type class resolution invokes `synthPending`. Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`. We will add a configuration option if necessary. -/ synthPendingDepth : Nat := 0 /-- A predicate to control whether a constant can be unfolded or not at `whnf`. Note that we do not cache results at `whnf` when `canUnfold?` is not `none`. -/ canUnfold? : Option (Config → ConstantInfo → CoreM Bool) := none abbrev MetaM := ReaderT Context $ StateRefT State CoreM -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind } instance : Inhabited (MetaM α) where default := fun _ _ => default instance : MonadLCtx MetaM where getLCtx := return (← read).lctx instance : MonadMCtx MetaM where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : MonadEnv MetaM where getEnv := return (← getThe Core.State).env modifyEnv f := do modifyThe Core.State fun s => { s with env := f s.env, cache := {} }; modify fun s => { s with cache := {} } instance : AddMessageContext MetaM where addMessageContext := addMessageContextFull protected def saveState : MetaM SavedState := return { core := (← getThe Core.State), meta := (← get) } /-- Restore backtrackable parts of the state. -/ def SavedState.restore (b : SavedState) : MetaM Unit := do Core.restore b.core modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed } instance : MonadBacktrack SavedState MetaM where saveState := Meta.saveState restoreState s := s.restore @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck : MetaM α := throw <| Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug export Core (instantiateTypeLevelParams instantiateValueLevelParams) @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f <| runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase <| k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c section Methods variable [MonadControlT MetaM n] [Monad n] @[inline] def modifyCache (f : Cache → Cache) : MetaM Unit := modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩ @[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit := modifyCache fun ⟨ic, c1, c2, c3, c4, c5⟩ => ⟨f ic, c1, c2, c3, c4, c5⟩ @[inline] def modifyDefEqCache (f : DefEqCache → DefEqCache) : MetaM Unit := modifyCache fun ⟨c1, c2, c3, c4, c5, defeq⟩ => ⟨c1, c2, c3, c4, c5, f defeq⟩ def getLocalInstances : MetaM LocalInstances := return (← read).localInstances def getConfig : MetaM Config := return (← read).config def resetZetaFVarIds : MetaM Unit := modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : MetaM FVarIdSet := return (← get).zetaFVarIds /-- Return the array of postponed universe level constraints. -/ def getPostponed : MetaM (PersistentArray PostponedEntry) := return (← get).postponed /-- Set the array of postponed universe level constraints. -/ def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := postponed } /-- Modify the array of postponed universe level constraints. -/ @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := f s.postponed } /-- `useEtaStruct inductName` return `true` if we eta for structures is enabled for for the inductive datatype `inductName`. Recall we have three different settings: `.none` (never use it), `.all` (always use it), `.notClasses` (enabled only for structure-like inductive types that are not classes). The parameter `inductName` affects the result only if the current setting is `.notClasses`. -/ def useEtaStruct (inductName : Name) : MetaM Bool := do match (← getConfig).etaStruct with | .none => return false | .all => return true | .notClasses => return !isClass (← getEnv) inductName /-! WARNING: The following 4 constants are a hack for simulating forward declarations. They are defined later using the `export` attribute. This is hackish because we have to hard-code the true arity of these definitions here, and make sure the C names match. We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/ /-- Reduces an expression to its Weak Head Normal Form. This is when the topmost expression has been fully reduced, but may contain subexpressions which have not been reduced. -/ @[extern 6 "lean_whnf"] opaque whnf : Expr → MetaM Expr /-- Returns the inferred type of the given expression, or fails if it is not type-correct. -/ @[extern 6 "lean_infer_type"] opaque inferType : Expr → MetaM Expr @[extern 7 "lean_is_expr_def_eq"] opaque isExprDefEqAux : Expr → Expr → MetaM Bool @[extern 7 "lean_is_level_def_eq"] opaque isLevelDefEqAux : Level → Level → MetaM Bool @[extern 6 "lean_synth_pending"] protected opaque synthPending : MVarId → MetaM Bool def whnfForall (e : Expr) : MetaM Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; return mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore (← mkFreshMVarId) lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : MetaM Level := do let mvarId ← mkFreshLMVarId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; return mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do mkFreshExprMVarAt (← getLCtx) (← getLocalInstances) type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /-- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore mvarId (← getLCtx) (← getLocalInstances) type kind userName numScopeArgs def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def mkFreshLevelMVars (num : Nat) : MetaM (List Level) := num.foldM (init := []) fun _ us => return (← mkFreshLevelMVar)::us def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) := mkFreshLevelMVars info.numLevelParams /-- Create a constant with the given name and new universe metavariables. Example: ``mkConstWithFreshMVarLevels `Monad`` returns `@Monad.{?u, ?v}` -/ def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do let info ← getConstInfo declName return mkConst declName (← mkFreshLevelMVarsFor info) /-- Return current transparency setting/mode. -/ def getTransparency : MetaM TransparencyMode := return (← getConfig).transparency def shouldReduceAll : MetaM Bool := return (← getTransparency) == TransparencyMode.all def shouldReduceReducibleOnly : MetaM Bool := return (← getTransparency) == TransparencyMode.reducible /-- Return `some mvarDecl` where `mvarDecl` is `mvarId` declaration in the current metavariable context. Return `none` if `mvarId` has no declaration in the current metavariable context. -/ def _root_.Lean.MVarId.findDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) := return (← getMCtx).findDecl? mvarId @[deprecated MVarId.findDecl?] def findMVarDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) := mvarId.findDecl? /-- Return `mvarId` declaration in the current metavariable context. Throw an exception if `mvarId` is not declarated in the current metavariable context. -/ def _root_.Lean.MVarId.getDecl (mvarId : MVarId) : MetaM MetavarDecl := do match (← mvarId.findDecl?) with | some d => pure d | none => throwError "unknown metavariable '?{mvarId.name}'" @[deprecated MVarId.getDecl] def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do mvarId.getDecl /-- Return `mvarId` kind. Throw an exception if `mvarId` is not declarated in the current metavariable context. -/ def _root_.Lean.MVarId.getKind (mvarId : MVarId) : MetaM MetavarKind := return (← mvarId.getDecl).kind @[deprecated MVarId.getKind] def getMVarDeclKind (mvarId : MVarId) : MetaM MetavarKind := mvarId.getKind /-- Reture `true` if `e` is a synthetic (or synthetic opaque) metavariable -/ def isSyntheticMVar (e : Expr) : MetaM Bool := do if e.isMVar then return (← e.mvarId!.getKind) matches .synthetic | .syntheticOpaque else return false /-- Set `mvarId` kind in the current metavariable context. -/ def _root_.Lean.MVarId.setKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarKind mvarId kind @[deprecated MVarId.setKind] def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := mvarId.setKind kind /-- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def _root_.Lean.MVarId.setType (mvarId : MVarId) (type : Expr) : MetaM Unit := do modifyMCtx fun mctx => mctx.setMVarType mvarId type @[deprecated MVarId.setType] def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do mvarId.setType type /-- Return true if the given metavariable is "read-only". That is, its `depth` is different from the current metavariable context depth. -/ def _root_.Lean.MVarId.isReadOnly (mvarId : MVarId) : MetaM Bool := do return (← mvarId.getDecl).depth != (← getMCtx).depth @[deprecated MVarId.isReadOnly] def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do mvarId.isReadOnly /-- Return true if `mvarId.isReadOnly` return true or if `mvarId` is a synthetic opaque metavariable. Recall `isDefEq` will not assign a value to `mvarId` if `mvarId.isReadOnlyOrSyntheticOpaque`. -/ def _root_.Lean.MVarId.isReadOnlyOrSyntheticOpaque (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← mvarId.getDecl match mvarDecl.kind with | MetavarKind.syntheticOpaque => return !(← getConfig).assignSyntheticOpaque | _ => return mvarDecl.depth != (← getMCtx).depth @[deprecated MVarId.isReadOnlyOrSyntheticOpaque] def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do mvarId.isReadOnlyOrSyntheticOpaque /-- Return the level of the given universe level metavariable. -/ def _root_.Lean.LMVarId.getLevel (mvarId : LMVarId) : MetaM Nat := do match (← getMCtx).findLevelDepth? mvarId with | some depth => return depth | _ => throwError "unknown universe metavariable '?{mvarId.name}'" @[deprecated LMVarId.getLevel] def getLevelMVarDepth (mvarId : LMVarId) : MetaM Nat := mvarId.getLevel /-- Return true if the given universe metavariable is "read-only". That is, its `depth` is different from the current metavariable context depth. -/ def _root_.Lean.LMVarId.isReadOnly (mvarId : LMVarId) : MetaM Bool := do if (← getConfig).ignoreLevelMVarDepth then return false else return (← mvarId.getLevel) != (← getMCtx).depth @[deprecated LMVarId.isReadOnly] def isReadOnlyLevelMVar (mvarId : LMVarId) : MetaM Bool := do mvarId.isReadOnly /-- Set the user-facing name for the given metavariable. -/ def _root_.Lean.MVarId.setUserName (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarUserName mvarId newUserName @[deprecated MVarId.setUserName] def setMVarUserName (mvarId : MVarId) (userNameNew : Name) : MetaM Unit := mvarId.setUserName userNameNew /-- Throw an exception saying `fvarId` is not declared in the current local context. -/ def _root_.Lean.FVarId.throwUnknown (fvarId : FVarId) : CoreM α := throwError "unknown free variable '{mkFVar fvarId}'" @[deprecated FVarId.throwUnknown] def throwUnknownFVar (fvarId : FVarId) : MetaM α := fvarId.throwUnknown /-- Return `some decl` if `fvarId` is declared in the current local context. -/ def _root_.Lean.FVarId.findDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := return (← getLCtx).find? fvarId @[deprecated FVarId.findDecl?] def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := fvarId.findDecl? /-- Return the local declaration for the given free variable. Throw an exception if local declaration is not in the current local context. -/ def _root_.Lean.FVarId.getDecl (fvarId : FVarId) : MetaM LocalDecl := do match (← getLCtx).find? fvarId with | some d => return d | none => fvarId.throwUnknown @[deprecated FVarId.getDecl] def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do fvarId.getDecl /-- Return the type of the given free variable. -/ def _root_.Lean.FVarId.getType (fvarId : FVarId) : MetaM Expr := return (← fvarId.getDecl).type /-- Return the binder information for the given free variable. -/ def _root_.Lean.FVarId.getBinderInfo (fvarId : FVarId) : MetaM BinderInfo := return (← fvarId.getDecl).binderInfo /-- Return `some value` if the given free variable is a let-declaration, and `none` otherwise. -/ def _root_.Lean.FVarId.getValue? (fvarId : FVarId) : MetaM (Option Expr) := return (← fvarId.getDecl).value? /-- Return the user-facing name for the given free variable. -/ def _root_.Lean.FVarId.getUserName (fvarId : FVarId) : MetaM Name := return (← fvarId.getDecl).userName /-- Return `true` is the free variable is a let-variable. -/ def _root_.Lean.FVarId.isLetVar (fvarId : FVarId) : MetaM Bool := return (← fvarId.getDecl).isLet /-- Get the local declaration associated to the given `Expr` in the current local context. Fails if the given expression is not a fvar or if no such declaration exists. -/ def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := fvar.fvarId!.getDecl /-- Given a user-facing name for a free variable, return its declaration in the current local context. Throw an exception if free variable is not declared. -/ def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError "unknown local declaration '{userName}'" /-- Lift a `MkBindingM` monadic action `x` to `MetaM`. -/ @[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do match x { lctx := (← getLCtx), mainModule := (← getEnv).mainModule } { mctx := (← getMCtx), ngen := (← getNGen), nextMacroScope := (← getThe Core.State).nextMacroScope } with | .ok e sNew => do setMCtx sNew.mctx modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope } pure e | .error (.revertFailure ..) sNew => do setMCtx sNew.mctx modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope } throwError "failed to create binder due to failure when reverting variable dependencies" /-- Similar to `abstracM` but consider only the first `min n xs.size` entries in `xs` It is also similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. -/ def _root_.Lean.Expr.abstractRangeM (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := liftMkBindingM <| MetavarContext.abstractRange e n xs @[deprecated Expr.abstractRangeM] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := e.abstractRangeM n xs /-- Replace free (or meta) variables `xs` with loose bound variables. Similar to `Expr.abstract`, but handles metavariables correctly. -/ def _root_.Lean.Expr.abstractM (e : Expr) (xs : Array Expr) : MetaM Expr := e.abstractRangeM xs.size xs @[deprecated Expr.abstractM] def abstract (e : Expr) (xs : Array Expr) : MetaM Expr := e.abstractM xs /-- Collect forward dependencies for the free variables in `toRevert`. Recall that when reverting free variables `xs`, we must also revert their forward dependencies. -/ def collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MetaM (Array Expr) := do liftMkBindingM <| MetavarContext.collectForwardDeps toRevert preserveOrder /-- Takes an array `xs` of free variables or metavariables and a term `e` that may contain those variables, and abstracts and binds them as universal quantifiers. - if `usedOnly = true` then only variables that the expression body depends on will appear. - if `usedLetOnly = true` same as `usedOnly` except for let-bound variables. (That is, local constants which have been assigned a value.) -/ def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly binderInfoForMVars /-- Takes an array `xs` of free variables and metavariables and a body term `e` and creates `fun ..xs => e`, suitably abstracting `e` and the types in `xs`. -/ def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly binderInfoForMVars def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := mkLambdaFVars xs e (usedLetOnly := usedLetOnly) (binderInfoForMVars := binderInfoForMVars) /-- `fun _ : Unit => a` -/ def mkFunUnit (a : Expr) : MetaM Expr := return Lean.mkLambda (← mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder /-- `withConfig f x` executes `x` using the updated configuration object obtained by applying `f`. -/ @[inline] def withConfig (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withoutProofIrrelevance (x : n α) : n α := withConfig (fun cfg => { cfg with proofIrrelevance := false }) x @[inline] def withTransparency (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) /-- `withDefault x` excutes `x` using the default transparency setting. -/ @[inline] def withDefault (x : n α) : n α := withTransparency TransparencyMode.default x /-- `withReducible x` excutes `x` using the reducible transparency setting. In this setting only definitions tagged as `[reducible]` are unfolded. -/ @[inline] def withReducible (x : n α) : n α := withTransparency TransparencyMode.reducible x /-- `withReducibleAndInstances x` excutes `x` using the `.instances` transparency setting. In this setting only definitions tagged as `[reducible]` or type class instances are unfolded. -/ @[inline] def withReducibleAndInstances (x : n α) : n α := withTransparency TransparencyMode.instances x /-- Execute `x` ensuring the transparency setting is at least `mode`. Recall that `.all > .default > .instances > .reducible`. -/ @[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x /-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/ @[inline] def withAssignableSyntheticOpaque (x : n α) : n α := withConfig (fun config => { config with assignSyntheticOpaque := true }) x /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do let savedCache := (← get).cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache : n α → n α := mapMetaM savingCacheImpl def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do if (← shouldReduceAll) then return some info else return none private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← getTransparency) with | TransparencyMode.all => return some info | TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none /-- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`. This method is only used to implement `isClassQuickConst?`. It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/ private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do match (← getEnv).find? constName with | some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do if isClass (← getEnv) constName then return .some constName else match (← getConstTemp? constName) with | some (.defnInfo ..) => return .undef -- We may be able to unfold the definition | _ => return .none private partial def isClassQuick? : Expr → MetaM (LOption Name) | .bvar .. => return .none | .lit .. => return .none | .fvar .. => return .none | .sort .. => return .none | .lam .. => return .none | .letE .. => return .undef | .proj .. => return .undef | .forallE _ _ b _ => isClassQuick? b | .mdata _ e => isClassQuick? e | .const n _ => isClassQuickConst? n | .mvar mvarId => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => return .none | .app f _ => match f.getAppFn with | .const n .. => isClassQuickConst? n | .lam .. => return .undef | _ => return .none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let savedSythInstance := (← get).cache.synthInstance modifyCache fun c => { c with synthInstance := {} } return savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modifyCache fun c => { c with synthInstance := cache } @[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/ match localDecl.binderInfo with | .auxDecl => k | _ => resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α := mapMetaM <| withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | .none => withNewLocalInstancesImp fvars (i+1) k | .undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k | .some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | .forallE n d b bi => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d bi let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? (type : Expr) : MetaM (Option Name) := withReducible do -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun _ type => do let env ← getEnv match type.getAppFn with | .const c _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← whnf type).getAppFn with | .const c _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | .none => return none | .some c => return (some c) | .undef => isClassExpensive? type end /-- `isClass? type` return `some ClsName` if `type` is an instance of the class `ClsName`. Example: ``` #eval do let x ← mkAppM ``Inhabited #[mkConst ``Nat] IO.println (← isClass? x) -- (some Inhabited) ``` -/ def isClass? (type : Expr) : MetaM (Option Name) := try isClassImp? type catch _ => return none private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImp fvars j partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImpAux fvars j @[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do process consumeLet (← getLCtx) #[] 0 e where process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, .lam n d b bi => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d bi let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, .letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e /-- Similar to `lambdaTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope (e : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp e true k) k /-- Given `e` of the form `fun ..xs => A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def lambdaTelescope (e : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp e false k) k /-- Return the parameter names for the given global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do forallTelescopeReducing (← getConstInfo declName).type fun xs _ => do xs.mapM fun x => do let localDecl ← x.fvarId!.getDecl return localDecl.userName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do if maxMVars?.isEqSome mvars.size then let type := type.instantiateRevRange j mvars.size mvars; return (mvars, bis, type) else match type with | .forallE n d b bi => let d := d.instantiateRevRange j mvars.size mvars let k := if bi.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push bi process mvars bis j b | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else return (mvars, bis, type) else return (mvars, bis, type) /-- Given `e` of the form `forall ..xs, A`, this combinator will create a new metavariable for each `x` in `xs` and instantiate `A` with these. Returns a product containing - the new metavariables - the binder info for the `xs` - the instantiated `A` -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallMetaTelescope`, but if `e = forall ..xs, A` it will reduce `A` to construct further mvars. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/ def forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind) /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars return (mvars, bis, type) if maxMVars?.isEqSome mvars.size then finalize () else match type with | .lam _ d b bi => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push bi process mvars bis j b | _ => finalize () private def withNewFVar (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do match (← isClass? fvarType) with | none => k fvar | some c => withNewLocalInstance c fvar <| k fvar private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k /-- Create a free variable `x` with name, binderInfo and type, add it to the context and run in `k`. Then revert the context. -/ def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k) k def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k /-- Append an array of free variables `xs` to the local context and execute `k xs`. declInfos takes the form of an array consisting of: - the name of the variable - the binder info of the variable - a type constructor for the variable, where the array consists of all of the free variables defined prior to this one. This is needed because the type of the variable may depend on prior variables. -/ partial def withLocalDecls [Inhabited α] (declInfos : Array (Name × BinderInfo × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := loop #[] where loop [Inhabited α] (acc : Array Expr) : n α := do if acc.size < declInfos.size then let (name, bi, typeCtor) := declInfos[acc.size]! withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x) else k acc def withLocalDeclsD [Inhabited α] (declInfos : Array (Name × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := withLocalDecls (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) => lctx.setBinderInfo fvarId bi withReader (fun ctx => { ctx with lctx := lctx }) k def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α := mapMetaM (fun k => withNewBinderInfosImp bs k) k /-- Execute `k` using a local context where any `x` in `xs` that is tagged as instance implicit is treated as a regular implicit. -/ def withInstImplicitAsImplict (xs : Array Expr) (k : MetaM α) : MetaM α := do let newBinderInfos ← xs.filterMapM fun x => do let bi ← x.fvarId!.getBinderInfo if bi == .instImplicit then return some (x.fvarId!, .implicit) else return none withNewBinderInfos newBinderInfos k private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k /-- Add the local declaration `<name> : <type> := <val>` to the local context and execute `k x`, where `x` is a new free variable corresponding to the `let`-declaration. After executing `k x`, the local context is restored. -/ def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLetDeclImp name type val k) k def withLocalInstancesImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let localInsts := (← read).localInstances let size := localInsts.size let localInstsNew ← decls.foldlM (init := localInsts) fun localInstsNew decl => do match (← isClass? decl.type) with | none => return localInstsNew | some className => return localInstsNew.push { className, fvar := decl.toExpr } if localInstsNew.size == size then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := localInstsNew }) k /-- Register any local instance in `decls` -/ def withLocalInstances (decls : List LocalDecl) : n α → n α := mapMetaM <| withLocalInstancesImp decls private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do withLocalInstancesImp decls k /-- `withExistingLocalDecls decls k`, adds the given local declarations to the local context, and then executes `k`. This method assumes declarations in `decls` have valid `FVarId`s. After executing `k`, the local context is restored. Remark: this method is used, for example, to implement the `match`-compiler. Each `match`-alternative commes with a local declarations (corresponding to pattern variables), and we use `withExistingLocalDecls` to add them to the local context before we process them. -/ def withExistingLocalDecls (decls : List LocalDecl) : n α → n α := mapMetaM <| withExistingLocalDeclsImp decls private def withNewMCtxDepthImp (x : MetaM α) : MetaM α := do let saved ← get modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} } try x finally modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed } /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. Metavariable context depths are used to control which metavariables may be assigned in `isDefEq`. See the docstring of `isDefEq` for more information. -/ def withNewMCtxDepth : n α → n α := mapMetaM withNewMCtxDepthImp private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x /-- `withLCtx lctx localInsts k` replaces the local context and local instances, and then executes `k`. The local context and instances are restored after executing `k`. This method assumes that the local instances in `localInsts` are in the local context `lctx`. -/ def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM <| withLocalContextImp lctx localInsts private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← mvarId.getDecl withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def _root_.Lean.MVarId.withContext (mvarId : MVarId) : n α → n α := mapMetaM <| withMVarContextImp mvarId @[deprecated MVarId.withContext] def withMVarContext (mvarId : MVarId) : n α → n α := mvarId.withContext private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' /-- `withMCtx mctx k` replaces the metavariable context and then executes `k`. The metavariable context is restored after executing `k`. This method is used to implement the type class resolution procedure. -/ def withMCtx (mctx : MetavarContext) : n α → n α := mapMetaM <| withMCtxImp mctx @[inline] private def approxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq : n α → n α := mapMetaM fullApproxDefEqImp /-- Instantiate assigned universe metavariables in `u`, and then normalize it. -/ def normalizeLevel (u : Level) : MetaM Level := do let u ← instantiateLevelMVars u pure u.normalize /-- `whnf` with reducible transparency.-/ def whnfR (e : Expr) : MetaM Expr := withTransparency TransparencyMode.reducible <| whnf e /-- `whnf` with default transparency.-/ def whnfD (e : Expr) : MetaM Expr := withTransparency TransparencyMode.default <| whnf e /-- `whnf` with instances transparency.-/ def whnfI (e : Expr) : MetaM Expr := withTransparency TransparencyMode.instances <| whnf e /-- Mark declaration `declName` with the attribute `[inline]`. This method does not check whether the given declaration is a definition. Recall that this attribute can only be set in the same module where `declName` has been declared. -/ def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | .ok env => setEnv env | .error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | .forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else return e /-- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | .lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else return e /-- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateLambdaAux ps 0 e /-- Pretty-print the given expression. -/ def ppExpr (e : Expr) : MetaM Format := do let ctxCore ← readThe Core.Context Lean.ppExpr { env := (← getEnv), mctx := (← getMCtx), lctx := (← getLCtx), opts := (← getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e @[inline] protected def orElse (x : MetaM α) (y : Unit → MetaM α) : MetaM α := do let s ← saveState try x catch _ => s.restore; y () instance : OrElse (MetaM α) := ⟨Meta.orElse⟩ instance : Alternative MetaM where failure := fun {_} => throwError "failed" orElse := Meta.orElse @[inline] private def orelseMergeErrorsImp (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ _ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ _ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw <| Exception.error ref <| f msg | ex => throw ex @[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- Sort free variables using an order `x < y` iff `x` was defined before `y`. If a free variable is not in the local context, we use their id. -/ def sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do let lctx ← getLCtx return fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index < d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁.name fvarId₂.name end Methods /-- Return `true` if `declName` is an inductive predicate. That is, `inductive` type in `Prop`. -/ def isInductivePredicate (declName : Name) : MetaM Bool := do match (← getEnv).find? declName with | some (.inductInfo { type := type, ..}) => forallTelescopeReducing type fun _ type => do match (← whnfD type) with | .sort u .. => return u == levelZero | _ => return false | _ => return false def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false def getNumPostponed : MetaM Nat := do return (← getPostponed).size def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps /-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/ private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr := e.replace fun | .const _ us => if us.any p then some (e.setPPUniverses true) else none | .sort u => if p u then some (e.setPPUniverses true) else none | _ => none private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do match entry.ctx? with | none => return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}" | some ctx => withLCtx ctx.lctx ctx.localInstances do let s := entry.lhs.collectMVars entry.rhs.collectMVars /- `p u` is true if it contains a universe metavariable in `s` -/ let p (u : Level) := u.any fun | .mvar m => s.contains m | _ => false let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p try addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}" catch _ => addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}" def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "stuck at solving universe constraint" entry def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "failed to solve universe constraint" entry private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := do let ps ← getResetPostponed for p in ps do unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do if exceptionOnFailure then withRef p.ref do throwError (← mkLevelErrorMessage p) else return false return true partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else let numPostponedBegin ← getNumPostponed withTraceNode `Meta.isLevelDefEq.postponed (fun _ => return m!"processing #{numPostponedBegin} postponed is-def-eq level constraints") do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else if !(← processPostponedStep exceptionOnFailure) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints" return mayPostpone loop /-- `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning. We currently try to postpone universe constraints as much as possible, even when by postponing them we are not sure whether `x` really succeeded or not. -/ @[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let s ← saveState /- It is not safe to use the `isDefEq` cache between different `isDefEq` calls. Reason: different configuration settings, and result depends on the state of the `MetavarContext` We have tried in the past to track when the result was independent of the `MetavarContext` state but it was not effective. It is more important to cache aggressively inside of a single `isDefEq` call because some of the heuristics create many similar subproblems. See issue #1102 for an example that triggers an exponential blowup if we don't use this more aggresive form of caching. -/ modifyDefEqCache fun _ => {} let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then let newPostponed ← getPostponed setPostponed (postponed ++ newPostponed) return true else s.restore return false else s.restore return false catch ex => s.restore throw ex /-- Determines whether two universe level expressions are definitionally equal to each other. -/ def isLevelDefEq (u v : Level) : MetaM Bool := checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v /-- See `isDefEq`. -/ def isExprDefEq (t s : Expr) : MetaM Bool := withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s /-- Determines whether two expressions are definitionally equal to each other. To control how metavariables are assigned and unified, metavariables and their context have a "depth". Given a metavariable `?m` and a `MetavarContext` `mctx`, `?m` is not assigned if `?m.depth != mctx.depth`. The combinator `withNewMCtxDepth x` will bump the depth while executing `x`. So, `withNewMCtxDepth (isDefEq a b)` is `isDefEq` without any mvar assignment happening whereas `isDefEq a b` will assign any metavariables of the current depth in `a` and `b` to unify them. For matching (where only mvars in `b` should be assigned), we create the term inside the `withNewMCtxDepth`. For an example, see [Lean.Meta.Simp.tryTheoremWithExtraArgs?](https://github.com/leanprover/lean4/blob/master/src/Lean/Meta/Tactic/Simp/Rewrite.lean#L100-L106) -/ abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false /-- Similar to `isDefEq`, but returns `false` if an exception has been thrown. -/ abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s /-- Eta expand the given expression. Example: ``` etaExpand (mkConst ``Nat.add) ``` produces `fun x y => Nat.add x y` -/ def etaExpand (e : Expr) : MetaM Expr := withDefault do forallTelescopeReducing (← inferType e) fun xs _ => mkLambdaFVars xs (mkAppN e xs) end Meta builtin_initialize registerTraceClass `Meta.isLevelDefEq.postponed export Meta (MetaM) end Lean
2658a3f4495f5b3c9473ec428bb265ffd190e1da
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/list/basic.lean
c1f1c5adea7c13a55291696b3f6727d596b321ac
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
154,184
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import algebra.group import data.nat.basic /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /-! ### mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] /-! ### length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ lemma injective_length_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end lemma injective_length [subsingleton α] : injective (length : list α → ℕ) := injective_length_iff.mpr $ by apply_instance /-! ### set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq [decidable_eq α] (x : α) : ({x} : list α) = [x] := by refl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [y, x] := by { rw [insert_neg, singleton_eq], show y ∉ [x], rw [mem_singleton], exact h.symm } /-! ### bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [mem_cons_iff, forall_mem_cons'] theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /-! ### list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_right h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /-! ### repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /-! ### bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ /-! ### concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by simp theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by simp /-! ### reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl theorem reverse_injective : injective (@reverse α) := injective_of_left_inverse reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /-! ### is_nil -/ lemma is_nil_iff_eq_nil {l : list α} : l.is_nil ↔ l = [] := list.cases_on l (by simp [is_nil]) (by simp [is_nil]) /-! ### last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l | [] h := absurd rfl h | [a] h := or.inl rfl | (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) } /-! ### last' -/ @[simp] theorem last'_is_none : ∀ {l : list α}, (last' l).is_none ↔ l = [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_none (b::l)] @[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_some (b::l)] theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h | [] x hx := false.elim $ by simpa using hx | [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩ | (a::b::l) x hx := begin rw last' at hx, rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩, use cons_ne_nil _ _, rwa [last_cons] end theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l := let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _ theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l | [] a ha := (option.not_mem_none a ha).elim | [a] _ rfl := rfl | (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] } theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget | [] := by simp [ilast, arbitrary] | [a] := rfl | [a, b] := rfl | [a, b, c] := rfl | (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)] @[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α), last' (l₁ ++ a :: l₂) = last' (a :: l₂) | [] a l₂ := rfl | [b] a l₂ := rfl | (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons] theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []), last' (l₁ ++ l₂) = last' l₂ | [] hl₂ := by contradiction | (b::l₂) _ := last'_append_cons l₁ b l₂ /-! ### head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l | [] h := (option.not_mem_none _ h).elim | (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl } @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l | [] a h := by contradiction | (b::l) a h := by { simp at h, simp [h] } theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l | [] h := by contradiction | (a::l) h := rfl theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := cons_head'_tail (head_mem_head' h) @[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl /-! ### sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact ih.append_right [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff] using h.reverse, λ h, h.append_right l⟩ theorem sublist.append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (hl.append_right _).trans ((append_sublist_append_left _).2 hr) theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (sublist.subset s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, h.subset (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ s.subset theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /-! ### index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp, priority 990] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp, priority 980] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /-! ### nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ /-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as `hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make such a rewrite, with `rw (nth_le_of_eq h)`. -/ lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) : nth_le L i hi = nth_le L' i (h ▸ hi) := by { congr, exact h} @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) : L.nth_le 0 h = L.head := by { cases L, cases h, simp, } lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) : (list.repeat a n).nth_le m h = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[ext] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], } @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) : l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] := begin refine ext_le (by convert h) (λ n h₁ h₂, _), simp only [nth_le_singleton], congr, exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂) end lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /-! ### map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem injective_map_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /-! ### map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /-! ### take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m) | n 0 := by simp | 0 m := by simp | (succ n) (succ m) := by simp [min_succ_succ, take_repeat] lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] /-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first `i` elements of `l₂` to `l₁`. -/ lemma take_append {l₁ l₂ : list α} (i : ℕ) : take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self] end /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) : nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) := by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ } /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) : nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) := by { simp at hi, rw nth_le_take L _ hi.1 } @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_length (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] /-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements up to `i` in `l₂`. -/ lemma drop_append {l₁ l₂ : list α} (i : ℕ) : drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, drop, l₁_ih] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) : nth_le L (i + j) h = nth_le (L.drop i) j begin have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h, rw (take_append_drop i L).symm at h, simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h end := begin have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)], rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right]; simp [A] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) : nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) := by rw nth_le_drop @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /-! ### foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp /- scanl -/ lemma length_scanl {β : Type*} {f : α → β → α} : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /-! ### mfoldl, mfoldr -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl variables [is_lawful_monad m] @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /-! ### prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[to_additive] theorem prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] @[to_additive] theorem prod_eq_foldr : l.prod = foldr (*) 1 l := list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α → β) [is_monoid_hom f] : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, (is_monoid_hom.map_one f).symm], exact l.foldl_hom _ _ _ 1 (is_monoid_hom.map_mul f) } -- `to_additive` chokes on the next few lemmas, so we do them by hand below @[simp] lemma prod_take_mul_prod_drop : ∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], } @[simp] lemma prod_take_succ : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], } /-- A list with product not one must have positive length. -/ lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } end monoid @[simp] lemma sum_take_add_sum_drop [add_monoid α] : ∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], } @[simp] lemma sum_take_succ [add_monoid α] : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], } lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length) (h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' := begin apply ext_le h (λ i h₁ h₂, _), have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁), rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this, exact add_left_cancel this end lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) : monotone (λ i, (L.take i).sum) := begin apply monotone_of_monotone_nat (λ n, _), by_cases h : n < L.length, { rw sum_take_succ _ _ h, exact le_add_right (le_refl _) }, { push_neg at h, simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] } end /-- A list with sum not zero must have positive length. -/ lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } /-- If all elements in a list are bounded below by `1`, then the length of the list is bounded by the sum of the elements. -/ lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum := begin induction L with j L IH h, { simp }, rw [sum_cons, length, add_comm], exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi))) end -- Now we tie those lemmas back to their multiplicative versions. attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one /-- A list with positive sum must have positive length. -/ -- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications. lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) : 0 < L.length := length_pos_of_sum_ne_zero L (ne_of_gt h) @[simp, to_additive] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end -- Several lemmas about sum/head/tail for `list ℕ`. -- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`. -- We'd like to state this as `L.head * L.tail.prod = L.prod`, -- but because `L.head` relies on an inhabited instances and -- returns a garbage value for the empty list, this is not possible. -- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`, -- and below, restate the lemma just for `ℕ`. @[to_additive] lemma head_mul_tail_prod' [monoid α] (L : list α) : (L.nth 0).get_or_else 1 * L.tail.prod = L.prod := by { cases L, { simp, refl, }, { simp, }, } lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum := by { cases L, { simp, refl, }, { simp, }, } lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L) lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head := by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel] /-! ### join -/ attribute [simp] join theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end /-! ### lexicographic ordering -/ /-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which `[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`. The definition is given for any relation `r`, not only strict orders. -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /-! ### all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /-! ### map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap /-! ### find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /-! ### lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /-! ### filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem sublist.map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := filter_map_eq_map f ▸ s.filter_map _ /-! ### filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := (filter_sublist l).subset theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := filter_map_eq_filter p ▸ s.filter_map _ theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /-! ### count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /-! ### prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /-! ### sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s, { simp only [sublists'_nil, mem_singleton], exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, simp only [sublists'_cons, mem_append, IH, mem_map], split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ h }, { exact cons_sublist_cons _ h }, { cases h with _ _ _ h s _ _ h, { exact or.inl h }, { exact or.inr ⟨s, h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, pow_succ, mul_succ, mul_zero, zero_add] @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc] theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih, {refl}, simp only [ih, foldr_cons] end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil] | (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := rfl | (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l] theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind], congr, funext x, apply congr_arg _, rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map, map_eq_map, map_id' (append_nil), append_nil] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l with hd tl ih; [refl, simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro, {rwa foldr}, simp only [foldr, mem_cons_iff, false_or, not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp only [map, map_append, sublists_concat]; exact ((append_sublist_append_left _).2 $ singleton_sublist.2 $ mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans ((append_sublist_append_right _).2 IH) /-! ### sublists_len -/ /-- Auxiliary function to construct the list of all sublists of a given length. Given an integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/ def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β | 0 l f r := f [] :: r | (n+1) [] f r := r | (n+1) (a::l) f r := sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ list.cons a) r) /-- The list of all sublists of a list `l` that are of length `n`. For instance, for `l = [0, 1, 2, 3]` and `n = 2`, one gets `[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/ def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) := sublists_len_aux n l id [] lemma sublists_len_aux_append {α β γ : Type*} : ∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ), sublists_len_aux n l (g ∘ f) (r.map g ++ s) = (sublists_len_aux n l f r).map g ++ s | 0 l f g r s := rfl | (n+1) [] f g r s := rfl | (n+1) (a::l) f g r s := begin unfold sublists_len_aux, rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl, sublists_len_aux_append, sublists_len_aux_append] end lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) : sublists_len_aux n l f r = (sublists_len n l).map f ++ r := by rw [sublists_len, ← sublists_len_aux_append]; refl lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) : sublists_len_aux 0 l f r = f [] :: r := by cases l; refl @[simp] lemma sublists_len_zero {α : Type*} (l : list α) : sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _ @[simp] lemma sublists_len_succ_nil {α : Type*} (n) : sublists_len (n+1) (@nil α) = [] := rfl @[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) : sublists_len (n + 1) (a::l) = sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) := by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id, append_nil]; refl @[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α), length (sublists_len n l) = nat.choose (length l) n | 0 l := by simp | (n+1) [] := by simp | (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α), sublists_len n l <+ sublists' l | 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _)) | (n+1) [] := nil_sublist _ | (n+1) (a::l) := begin rw [sublists_len_succ_cons, sublists'_cons], exact (sublists_len_sublist_sublists' _ _).append ((sublists_len_sublist_sublists' _ _).map _) end lemma sublists_len_sublist_of_sublist {α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl}, { refine IH.trans _, rw sublists_len_succ_cons, apply sublist_append_left }, { simp [sublists_len_succ_cons], exact IH.append ((IHn s).map _) } end lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α}, l' ∈ sublists_len n l → length l' = n | 0 l l' (or.inl rfl) := rfl | (n+1) (a::l) l' h := begin rw [sublists_len_succ_cons, mem_append, mem_map] at h, rcases h with h | ⟨l', h, rfl⟩, { exact length_of_sublists_len h }, { exact congr_arg (+1) (length_of_sublists_len h) }, end lemma mem_sublists_len_self {α : Type*} {l l' : list α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH, { exact or.inl rfl }, { cases l₁ with b l₁, { exact or.inl rfl }, { rw [length, sublists_len_succ_cons], exact mem_append_left _ IH } }, { rw [length, sublists_len_succ_cons], exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) } end @[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := ⟨λ h, ⟨mem_sublists'.1 ((sublists_len_sublist_sublists' _ _).subset h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩ /-! ### permutations -/ section permutations @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl end permutations /-! ### insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /-! ### erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := (erasep_sublist l).subset theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /-! ### erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp, priority 980] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := (erase_sublist a l).subset theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact sublist.erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /-! ### diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := (diff_sublist _ _).subset theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, (h.erase _).diff_right] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (h.erase b) end diff /-! ### enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : ∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end /-! ### product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /-! ### sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /-! ### disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] := by rw disjoint_comm; exact disjoint_nil_left _ @[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /-! ### union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /-! ### inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter section choose variables (p : α → Prop) [decidable_pred p] (l : list α) lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose -- A jumble of lost lemmas: theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val end list @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm namespace list @[to_additive] theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) : (L.map (g ∘ f)).prod = g ((L.map f).prod) := by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm} theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, r * f b)).sum = r * (L.map f).sum := sum_map_hom L f $ add_monoid_hom.mul_left r theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, f b * r)).sum = (L.map f).sum * r := sum_map_hom L f $ add_monoid_hom.mul_right r end list
03895f76548765badb77eca8ea812a68657792ae
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/test/lint.lean
298ca38530bedad72a00efa37622188e8553d474
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
4,325
lean
import tactic.lint import algebra.ring.basic def foo1 (n m : ℕ) : ℕ := n + 1 def foo2 (n m : ℕ) : m = m := by refl lemma foo3 (n m : ℕ) : ℕ := n - m lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances lemma foo.bar (ε > 0) : ε = ε := rfl -- >/≥ is allowed in binders (and in fact, in all hypotheses) -- section -- local attribute [instance, priority 1001] classical.prop_decidable -- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) -- end open tactic meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d run_cmd do let t := name × list ℕ, e ← get_env, let l := e.filter (λ d, e.in_current_file' d.to_name ∧ ¬ d.is_auto_or_internal e), l2 ← fold_over_with_cond l (return ∘ check_unused_arguments), guard $ l2.length = 4, let l2 : list t := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ (⟨`foo1, [2]⟩ : t) ∈ l2, guard $ (⟨`foo2, [1]⟩ : t) ∈ l2, guard $ (⟨`foo.foo, [2]⟩ : t) ∈ l2, guard $ (⟨`foo.bar, [2]⟩ : t) ∈ l2, l2 ← fold_over_with_cond l linter.def_lemma.test, guard $ l2.length = 2, let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3, l3 ← fold_over_with_cond l linter.dup_namespace.test, guard $ l3.length = 1, guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo, l4 ← fold_over_with_cond l linter.ge_or_gt.test, guard $ l4.length = 1, guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo, -- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4, (_, s) ← lint ff, guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string, (_, s2) ← lint tt, guard $ s.to_string ≠ s2.to_string, skip /- check customizability and nolint -/ meta def dummy_check (d : declaration) : tactic (option string) := return $ if d.to_name.last = "foo" then some "gotcha!" else none meta def linter.dummy_linter : linter := { test := dummy_check, auto_decls := ff, no_errors_found := "found nothing", errors_found := "found something" } @[nolint dummy_linter] def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) run_cmd do (_, s) ← lint tt tt [`linter.dummy_linter] tt, guard $ "/- found something: -/\n#print foo.foo /- gotcha! -/\n".is_suffix_of s.to_string def incorrect_type_class_argument_test {α : Type} (x : α) [x = x] [decidable_eq α] [group α] : unit := () run_cmd do d ← get_decl `incorrect_type_class_argument_test, x ← linter.incorrect_type_class_argument.test d, guard $ x = some "These are not classes. argument 3: [_inst_1 : x = x]" section def impossible_instance_test {α β : Type} [add_group α] : has_add α := infer_instance local attribute [instance] impossible_instance_test run_cmd do d ← get_decl `impossible_instance_test, x ← linter.impossible_instance.test d, guard $ x = some "Impossible to infer argument 2: {β : Type}" def dangerous_instance_test {α β γ : Type} [ring α] [add_comm_group β] [has_coe α β] [has_inv γ] : has_add β := infer_instance local attribute [instance] dangerous_instance_test run_cmd do d ← get_decl `dangerous_instance_test, x ← linter.dangerous_instance.test d, guard $ x = some "The following arguments become metavariables. argument 1: {α : Type}, argument 3: {γ : Type}" end section def foo_has_mul {α} [has_mul α] : has_mul α := infer_instance local attribute [instance, priority 1] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 20 d, guard $ s = "type-class inference timed out" local attribute [instance, priority 10000] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end /- test of `apply_to_fresh_variables` -/ run_cmd do e ← mk_const `id, e2 ← apply_to_fresh_variables e, type_check e2, `(@id %%α %%a) ← instantiate_mvars e2, expr.sort (level.succ $ level.mvar u) ← infer_type α, skip
07757cfe30d4f9e37a411464dfa22b5205618a14
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/preadditive/default.lean
e7e601d26845e83c37067be615cc6942ac308cd7
[ "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
13,328
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Jakob von Raumer -/ import algebra.big_operators.basic import algebra.hom.group import algebra.module.basic import category_theory.endomorphism import category_theory.limits.shapes.kernels /-! # Preadditive categories A preadditive category is a category in which `X ⟶ Y` is an abelian group in such a way that composition of morphisms is linear in both variables. This file contains a definition of preadditive category that directly encodes the definition given above. The definition could also be phrased as follows: A preadditive category is a category enriched over the category of Abelian groups. Once the general framework to state this in Lean is available, the contents of this file should become obsolete. ## Main results * Definition of preadditive categories and basic properties * In a preadditive category, `f : Q ⟶ R` is mono if and only if `g ≫ f = 0 → g = 0` for all composable `g`. * A preadditive category with kernels has equalizers. ## Implementation notes The simp normal form for negation and composition is to push negations as far as possible to the outside. For example, `f ≫ (-g)` and `(-f) ≫ g` both become `-(f ≫ g)`, and `(-f) ≫ (-g)` is simplified to `f ≫ g`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] ## Tags additive, preadditive, Hom group, Ab-category, Ab-enriched -/ universes v u open category_theory.limits open_locale big_operators namespace category_theory variables (C : Type u) [category.{v} C] /-- A category is called preadditive if `P ⟶ Q` is an abelian group such that composition is linear in both variables. -/ class preadditive := (hom_group : Π P Q : C, add_comm_group (P ⟶ Q) . tactic.apply_instance) (add_comp' : ∀ (P Q R : C) (f f' : P ⟶ Q) (g : Q ⟶ R), (f + f') ≫ g = f ≫ g + f' ≫ g . obviously) (comp_add' : ∀ (P Q R : C) (f : P ⟶ Q) (g g' : Q ⟶ R), f ≫ (g + g') = f ≫ g + f ≫ g' . obviously) attribute [instance] preadditive.hom_group restate_axiom preadditive.add_comp' restate_axiom preadditive.comp_add' attribute [simp,reassoc] preadditive.add_comp attribute [reassoc] preadditive.comp_add -- (the linter doesn't like `simp` on this lemma) attribute [simp] preadditive.comp_add end category_theory open category_theory namespace category_theory namespace preadditive section preadditive open add_monoid_hom variables {C : Type u} [category.{v} C] [preadditive C] section induced_category universes u' variables {C} {D : Type u'} (F : D → C) instance induced_category.category : preadditive.{v} (induced_category C F) := { hom_group := λ P Q, @preadditive.hom_group C _ _ (F P) (F Q), add_comp' := λ P Q R f f' g, add_comp' _ _ _ _ _ _, comp_add' := λ P Q R f g g', comp_add' _ _ _ _ _ _, } end induced_category instance (X : C) : add_comm_group (End X) := by { dsimp [End], apply_instance, } instance (X : C) : ring (End X) := { left_distrib := λ f g h, preadditive.add_comp X X X g h f, right_distrib := λ f g h, preadditive.comp_add X X X h f g, ..(infer_instance : add_comm_group (End X)), ..(infer_instance : monoid (End X)) } /-- Composition by a fixed left argument as a group homomorphism -/ def left_comp {P Q : C} (R : C) (f : P ⟶ Q) : (Q ⟶ R) →+ (P ⟶ R) := mk' (λ g, f ≫ g) $ λ g g', by simp /-- Composition by a fixed right argument as a group homomorphism -/ def right_comp (P : C) {Q R : C} (g : Q ⟶ R) : (P ⟶ Q) →+ (P ⟶ R) := mk' (λ f, f ≫ g) $ λ f f', by simp variables {P Q R : C} (f f' : P ⟶ Q) (g g' : Q ⟶ R) /-- Composition as a bilinear group homomorphism -/ def comp_hom : (P ⟶ Q) →+ (Q ⟶ R) →+ (P ⟶ R) := add_monoid_hom.mk' (λ f, left_comp _ f) $ λ f₁ f₂, add_monoid_hom.ext $ λ g, (right_comp _ g).map_add f₁ f₂ @[simp, reassoc] lemma sub_comp : (f - f') ≫ g = f ≫ g - f' ≫ g := map_sub (right_comp P g) f f' -- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma comp_sub : f ≫ (g - g') = f ≫ g - f ≫ g' := map_sub (left_comp R f) g g' @[simp, reassoc] lemma neg_comp : (-f) ≫ g = -(f ≫ g) := map_neg (right_comp P g) f /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma comp_neg : f ≫ (-g) = -(f ≫ g) := map_neg (left_comp R f) g @[reassoc] lemma neg_comp_neg : (-f) ≫ (-g) = f ≫ g := by simp lemma nsmul_comp (n : ℕ) : (n • f) ≫ g = n • (f ≫ g) := map_nsmul (right_comp P g) n f lemma comp_nsmul (n : ℕ) : f ≫ (n • g) = n • (f ≫ g) := map_nsmul (left_comp R f) n g lemma zsmul_comp (n : ℤ) : (n • f) ≫ g = n • (f ≫ g) := map_zsmul (right_comp P g) n f lemma comp_zsmul (n : ℤ) : f ≫ (n • g) = n • (f ≫ g) := map_zsmul (left_comp R f) n g @[reassoc] lemma comp_sum {P Q R : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (Q ⟶ R)) : f ≫ ∑ j in s, g j = ∑ j in s, f ≫ g j := map_sum (left_comp R f) _ _ @[reassoc] lemma sum_comp {P Q R : C} {J : Type*} (s : finset J) (f : J → (P ⟶ Q)) (g : Q ⟶ R) : (∑ j in s, f j) ≫ g = ∑ j in s, f j ≫ g := map_sum (right_comp P g) _ _ instance {P Q : C} {f : P ⟶ Q} [epi f] : epi (-f) := ⟨λ R g g' H, by rwa [neg_comp, neg_comp, ←comp_neg, ←comp_neg, cancel_epi, neg_inj] at H⟩ instance {P Q : C} {f : P ⟶ Q} [mono f] : mono (-f) := ⟨λ R g g' H, by rwa [comp_neg, comp_neg, ←neg_comp, ←neg_comp, cancel_mono, neg_inj] at H⟩ @[priority 100] instance preadditive_has_zero_morphisms : has_zero_morphisms C := { has_zero := infer_instance, comp_zero' := λ P Q f R, show left_comp R f 0 = 0, from map_zero _, zero_comp' := λ P Q R f, show right_comp P f 0 = 0, from map_zero _ } instance module_End_right {X Y : C} : module (End Y) (X ⟶ Y) := { smul_add := λ r f g, add_comp _ _ _ _ _ _, smul_zero := λ r, zero_comp, add_smul := λ r s f, comp_add _ _ _ _ _ _, zero_smul := λ r, comp_zero } lemma mono_of_cancel_zero {Q R : C} (f : Q ⟶ R) (h : ∀ {P : C} (g : P ⟶ Q), g ≫ f = 0 → g = 0) : mono f := ⟨λ P g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (right_comp P f) g g').trans $ sub_eq_zero.2 hg⟩ lemma mono_iff_cancel_zero {Q R : C} (f : Q ⟶ R) : mono f ↔ ∀ (P : C) (g : P ⟶ Q), g ≫ f = 0 → g = 0 := ⟨λ m P g, by exactI zero_of_comp_mono _, mono_of_cancel_zero f⟩ lemma mono_of_kernel_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)] (w : kernel.ι f = 0) : mono f := mono_of_cancel_zero f (λ P g h, by rw [←kernel.lift_ι f g h, w, limits.comp_zero]) lemma epi_of_cancel_zero {P Q : C} (f : P ⟶ Q) (h : ∀ {R : C} (g : Q ⟶ R), f ≫ g = 0 → g = 0) : epi f := ⟨λ R g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (left_comp R f) g g').trans $ sub_eq_zero.2 hg⟩ lemma epi_iff_cancel_zero {P Q : C} (f : P ⟶ Q) : epi f ↔ ∀ (R : C) (g : Q ⟶ R), f ≫ g = 0 → g = 0 := ⟨λ e R g, by exactI zero_of_epi_comp _, epi_of_cancel_zero f⟩ lemma epi_of_cokernel_zero {X Y : C} {f : X ⟶ Y} [has_colimit (parallel_pair f 0 )] (w : cokernel.π f = 0) : epi f := epi_of_cancel_zero f (λ P g h, by rw [←cokernel.π_desc f g h, w, limits.zero_comp]) namespace is_iso @[simp] lemma comp_left_eq_zero [is_iso f] : f ≫ g = 0 ↔ g = 0 := by rw [← is_iso.eq_inv_comp, limits.comp_zero] @[simp] lemma comp_right_eq_zero [is_iso g] : f ≫ g = 0 ↔ f = 0 := by rw [← is_iso.eq_comp_inv, limits.zero_comp] end is_iso open_locale zero_object variables [has_zero_object C] lemma mono_of_kernel_iso_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)] (w : kernel f ≅ 0) : mono f := mono_of_kernel_zero (zero_of_source_iso_zero _ w) lemma epi_of_cokernel_iso_zero {X Y : C} {f : X ⟶ Y} [has_colimit (parallel_pair f 0)] (w : cokernel f ≅ 0) : epi f := epi_of_cokernel_zero (zero_of_target_iso_zero _ w) end preadditive section equalizers variables {C : Type u} [category.{v} C] [preadditive C] section variables {X Y : C} {f : X ⟶ Y} {g : X ⟶ Y} /-- Map a kernel cone on the difference of two morphisms to the equalizer fork. -/ def fork_of_kernel_fork (c : kernel_fork (f - g)) : fork f g := fork.of_ι c.ι $ by rw [← sub_eq_zero, ← comp_sub, c.condition] /-- Map any equalizer fork to a cone on the difference of the two morphisms. -/ def kernel_fork_of_fork (c : fork f g) : kernel_fork (f - g) := fork.of_ι c.ι $ by rw [comp_sub, comp_zero, sub_eq_zero, c.condition] @[simp] lemma kernel_fork_of_fork_ι (c : fork f g) : (kernel_fork_of_fork c).ι = c.ι := rfl @[simp] lemma kernel_fork_of_fork_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (kernel_fork_of_fork (fork.of_ι ι w)) = kernel_fork.of_ι ι (by simp [w]) := rfl /-- A kernel of `f - g` is an equalizer of `f` and `g`. -/ def is_limit_fork_of_kernel_fork {c : kernel_fork (f - g)} (i : is_limit c) : is_limit (fork_of_kernel_fork c) := fork.is_limit.mk' _ $ λ s, ⟨i.lift (kernel_fork_of_fork s), i.fac _ _, λ m h, by apply fork.is_limit.hom_ext i; tidy⟩ @[simp] lemma is_limit_fork_of_kernel_fork_lift {c : kernel_fork (f - g)} (i : is_limit c) (s : fork f g) : (is_limit_fork_of_kernel_fork i).lift s = i.lift (kernel_fork_of_fork s) := rfl /-- An equalizer of `f` and `g` is a kernel of `f - g`. -/ def is_limit_kernel_fork_of_fork {c : fork f g} (i : is_limit c) : is_limit (kernel_fork_of_fork c) := fork.is_limit.mk' _ $ λ s, ⟨i.lift (fork_of_kernel_fork s), i.fac _ _, λ m h, by apply fork.is_limit.hom_ext i; tidy⟩ variables (f g) /-- A preadditive category has an equalizer for `f` and `g` if it has a kernel for `f - g`. -/ lemma has_equalizer_of_has_kernel [has_kernel (f - g)] : has_equalizer f g := has_limit.mk { cone := fork_of_kernel_fork _, is_limit := is_limit_fork_of_kernel_fork (equalizer_is_equalizer (f - g) 0) } /-- A preadditive category has a kernel for `f - g` if it has an equalizer for `f` and `g`. -/ lemma has_kernel_of_has_equalizer [has_equalizer f g] : has_kernel (f - g) := has_limit.mk { cone := kernel_fork_of_fork (equalizer.fork f g), is_limit := is_limit_kernel_fork_of_fork (limit.is_limit (parallel_pair f g)) } variables {f g} /-- Map a cokernel cocone on the difference of two morphisms to the coequalizer cofork. -/ def cofork_of_cokernel_cofork (c : cokernel_cofork (f - g)) : cofork f g := cofork.of_π c.π $ by rw [← sub_eq_zero, ← sub_comp, c.condition] /-- Map any coequalizer cofork to a cocone on the difference of the two morphisms. -/ def cokernel_cofork_of_cofork (c : cofork f g) : cokernel_cofork (f - g) := cofork.of_π c.π $ by rw [sub_comp, zero_comp, sub_eq_zero, c.condition] @[simp] lemma cokernel_cofork_of_cofork_π (c : cofork f g) : (cokernel_cofork_of_cofork c).π = c.π := rfl @[simp] lemma cokernel_cofork_of_cofork_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cokernel_cofork_of_cofork (cofork.of_π π w)) = cokernel_cofork.of_π π (by simp [w]) := rfl /-- A cokernel of `f - g` is a coequalizer of `f` and `g`. -/ def is_colimit_cofork_of_cokernel_cofork {c : cokernel_cofork (f - g)} (i : is_colimit c) : is_colimit (cofork_of_cokernel_cofork c) := cofork.is_colimit.mk' _ $ λ s, ⟨i.desc (cokernel_cofork_of_cofork s), i.fac _ _, λ m h, by apply cofork.is_colimit.hom_ext i; tidy⟩ @[simp] lemma is_colimit_cofork_of_cokernel_cofork_desc {c : cokernel_cofork (f - g)} (i : is_colimit c) (s : cofork f g) : (is_colimit_cofork_of_cokernel_cofork i).desc s = i.desc (cokernel_cofork_of_cofork s) := rfl /-- A coequalizer of `f` and `g` is a cokernel of `f - g`. -/ def is_colimit_cokernel_cofork_of_cofork {c : cofork f g} (i : is_colimit c) : is_colimit (cokernel_cofork_of_cofork c) := cofork.is_colimit.mk' _ $ λ s, ⟨i.desc (cofork_of_cokernel_cofork s), i.fac _ _, λ m h, by apply cofork.is_colimit.hom_ext i; tidy⟩ variables (f g) /-- A preadditive category has a coequalizer for `f` and `g` if it has a cokernel for `f - g`. -/ lemma has_coequalizer_of_has_cokernel [has_cokernel (f - g)] : has_coequalizer f g := has_colimit.mk { cocone := cofork_of_cokernel_cofork _, is_colimit := is_colimit_cofork_of_cokernel_cofork (coequalizer_is_coequalizer (f - g) 0) } /-- A preadditive category has a cokernel for `f - g` if it has a coequalizer for `f` and `g`. -/ lemma has_cokernel_of_has_coequalizer [has_coequalizer f g] : has_cokernel (f - g) := has_colimit.mk { cocone := cokernel_cofork_of_cofork (coequalizer.cofork f g), is_colimit := is_colimit_cokernel_cofork_of_cofork (colimit.is_colimit (parallel_pair f g)) } end /-- If a preadditive category has all kernels, then it also has all equalizers. -/ lemma has_equalizers_of_has_kernels [has_kernels C] : has_equalizers C := @has_equalizers_of_has_limit_parallel_pair _ _ (λ _ _ f g, has_equalizer_of_has_kernel f g) /-- If a preadditive category has all cokernels, then it also has all coequalizers. -/ lemma has_coequalizers_of_has_cokernels [has_cokernels C] : has_coequalizers C := @has_coequalizers_of_has_colimit_parallel_pair _ _ (λ _ _ f g, has_coequalizer_of_has_cokernel f g) end equalizers end preadditive end category_theory
159badc638a7b0014d0ad83063b78f8449f8283a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/decomposition/lebesgue.lean
b6c8c243b82d2c915014354464d75f019efb4221
[ "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
63,440
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.measure.complex import measure_theory.measure.sub import measure_theory.decomposition.jordan import measure_theory.measure.with_density_vector_measure import measure_theory.function.ae_eq_of_integral /-! # Lebesgue decomposition > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves the Lebesgue decomposition theorem. The Lebesgue decomposition theorem states that, given two σ-finite measures `μ` and `ν`, there exists a σ-finite measure `ξ` and a measurable function `f` such that `μ = ξ + fν` and `ξ` is mutually singular with respect to `ν`. The Lebesgue decomposition provides the Radon-Nikodym theorem readily. ## Main definitions * `measure_theory.measure.have_lebesgue_decomposition` : A pair of measures `μ` and `ν` is said to `have_lebesgue_decomposition` if there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f` * `measure_theory.measure.singular_part` : If a pair of measures `have_lebesgue_decomposition`, then `singular_part` chooses the measure from `have_lebesgue_decomposition`, otherwise it returns the zero measure. * `measure_theory.measure.rn_deriv`: If a pair of measures `have_lebesgue_decomposition`, then `rn_deriv` chooses the measurable function from `have_lebesgue_decomposition`, otherwise it returns the zero function. * `measure_theory.signed_measure.have_lebesgue_decomposition` : A signed measure `s` and a measure `μ` is said to `have_lebesgue_decomposition` if both the positive part and negative part of `s` `have_lebesgue_decomposition` with respect to `μ`. * `measure_theory.signed_measure.singular_part` : The singular part between a signed measure `s` and a measure `μ` is simply the singular part of the positive part of `s` with respect to `μ` minus the singular part of the negative part of `s` with respect to `μ`. * `measure_theory.signed_measure.rn_deriv` : The Radon-Nikodym derivative of a signed measure `s` with respect to a measure `μ` is the Radon-Nikodym derivative of the positive part of `s` with respect to `μ` minus the Radon-Nikodym derivative of the negative part of `s` with respect to `μ`. ## Main results * `measure_theory.measure.have_lebesgue_decomposition_of_sigma_finite` : the Lebesgue decomposition theorem. * `measure_theory.measure.eq_singular_part` : Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `s = μ.singular_part ν`. * `measure_theory.measure.eq_rn_deriv` : Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `f = μ.rn_deriv ν`. * `measure_theory.signed_measure.singular_part_add_with_density_rn_deriv_eq` : the Lebesgue decomposition theorem between a signed measure and a σ-finite positive measure. # Tags Lebesgue decomposition theorem -/ noncomputable theory open_locale classical measure_theory nnreal ennreal open set variables {α β : Type*} {m : measurable_space α} {μ ν : measure_theory.measure α} include m namespace measure_theory namespace measure /-- A pair of measures `μ` and `ν` is said to `have_lebesgue_decomposition` if there exists a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f`. -/ class have_lebesgue_decomposition (μ ν : measure α) : Prop := (lebesgue_decomposition : ∃ (p : measure α × (α → ℝ≥0∞)), measurable p.2 ∧ p.1 ⟂ₘ ν ∧ μ = p.1 + ν.with_density p.2) /-- If a pair of measures `have_lebesgue_decomposition`, then `singular_part` chooses the measure from `have_lebesgue_decomposition`, otherwise it returns the zero measure. For sigma-finite measures, `μ = μ.singular_part ν + ν.with_density (μ.rn_deriv ν)`. -/ @[irreducible] def singular_part (μ ν : measure α) : measure α := if h : have_lebesgue_decomposition μ ν then (classical.some h.lebesgue_decomposition).1 else 0 /-- If a pair of measures `have_lebesgue_decomposition`, then `rn_deriv` chooses the measurable function from `have_lebesgue_decomposition`, otherwise it returns the zero function. For sigma-finite measures, `μ = μ.singular_part ν + ν.with_density (μ.rn_deriv ν)`.-/ @[irreducible] def rn_deriv (μ ν : measure α) : α → ℝ≥0∞ := if h : have_lebesgue_decomposition μ ν then (classical.some h.lebesgue_decomposition).2 else 0 lemma have_lebesgue_decomposition_spec (μ ν : measure α) [h : have_lebesgue_decomposition μ ν] : measurable (μ.rn_deriv ν) ∧ (μ.singular_part ν) ⟂ₘ ν ∧ μ = (μ.singular_part ν) + ν.with_density (μ.rn_deriv ν) := begin rw [singular_part, rn_deriv, dif_pos h, dif_pos h], exact classical.some_spec h.lebesgue_decomposition, end lemma have_lebesgue_decomposition_add (μ ν : measure α) [have_lebesgue_decomposition μ ν] : μ = (μ.singular_part ν) + ν.with_density (μ.rn_deriv ν) := (have_lebesgue_decomposition_spec μ ν).2.2 instance have_lebesgue_decomposition_smul (μ ν : measure α) [have_lebesgue_decomposition μ ν] (r : ℝ≥0) : (r • μ).have_lebesgue_decomposition ν := { lebesgue_decomposition := begin obtain ⟨hmeas, hsing, hadd⟩ := have_lebesgue_decomposition_spec μ ν, refine ⟨⟨r • μ.singular_part ν, r • μ.rn_deriv ν⟩, _, hsing.smul _, _⟩, { change measurable ((r : ℝ≥0∞) • _), -- cannot remove this line exact hmeas.const_smul _ }, { change _ = (r : ℝ≥0∞) • _ + ν.with_density ((r : ℝ≥0∞) • _), rw [with_density_smul _ hmeas, ← smul_add, ← hadd], refl } end } @[measurability] lemma measurable_rn_deriv (μ ν : measure α) : measurable $ μ.rn_deriv ν := begin by_cases h : have_lebesgue_decomposition μ ν, { exactI (have_lebesgue_decomposition_spec μ ν).1 }, { rw [rn_deriv, dif_neg h], exact measurable_zero } end lemma mutually_singular_singular_part (μ ν : measure α) : μ.singular_part ν ⟂ₘ ν := begin by_cases h : have_lebesgue_decomposition μ ν, { exactI (have_lebesgue_decomposition_spec μ ν).2.1 }, { rw [singular_part, dif_neg h], exact mutually_singular.zero_left } end lemma singular_part_le (μ ν : measure α) : μ.singular_part ν ≤ μ := begin by_cases hl : have_lebesgue_decomposition μ ν, { casesI (have_lebesgue_decomposition_spec μ ν).2 with _ h, conv_rhs { rw h }, exact measure.le_add_right le_rfl }, { rw [singular_part, dif_neg hl], exact measure.zero_le μ } end lemma with_density_rn_deriv_le (μ ν : measure α) : ν.with_density (μ.rn_deriv ν) ≤ μ := begin by_cases hl : have_lebesgue_decomposition μ ν, { casesI (have_lebesgue_decomposition_spec μ ν).2 with _ h, conv_rhs { rw h }, exact measure.le_add_left le_rfl }, { rw [rn_deriv, dif_neg hl, with_density_zero], exact measure.zero_le μ } end instance [is_finite_measure μ] : is_finite_measure (μ.singular_part ν) := is_finite_measure_of_le μ $ singular_part_le μ ν instance [sigma_finite μ] : sigma_finite (μ.singular_part ν) := sigma_finite_of_le μ $ singular_part_le μ ν instance [topological_space α] [is_locally_finite_measure μ] : is_locally_finite_measure (μ.singular_part ν) := is_locally_finite_measure_of_le $ singular_part_le μ ν instance [is_finite_measure μ] : is_finite_measure (ν.with_density $ μ.rn_deriv ν) := is_finite_measure_of_le μ $ with_density_rn_deriv_le μ ν instance [sigma_finite μ] : sigma_finite (ν.with_density $ μ.rn_deriv ν) := sigma_finite_of_le μ $ with_density_rn_deriv_le μ ν instance [topological_space α] [is_locally_finite_measure μ] : is_locally_finite_measure (ν.with_density $ μ.rn_deriv ν) := is_locally_finite_measure_of_le $ with_density_rn_deriv_le μ ν lemma lintegral_rn_deriv_lt_top_of_measure_ne_top {μ : measure α} (ν : measure α) {s : set α} (hs : μ s ≠ ∞) : ∫⁻ x in s, μ.rn_deriv ν x ∂ν < ∞ := begin by_cases hl : have_lebesgue_decomposition μ ν, { haveI := hl, obtain ⟨-, -, hadd⟩ := have_lebesgue_decomposition_spec μ ν, suffices : ∫⁻ x in to_measurable μ s, μ.rn_deriv ν x ∂ν < ∞, from lt_of_le_of_lt (lintegral_mono_set (subset_to_measurable _ _)) this, rw [← with_density_apply _ (measurable_set_to_measurable _ _)], refine lt_of_le_of_lt (le_add_left le_rfl : _ ≤ μ.singular_part ν (to_measurable μ s) + ν.with_density (μ.rn_deriv ν) (to_measurable μ s)) _, rw [← measure.add_apply, ← hadd, measure_to_measurable], exact hs.lt_top }, { erw [measure.rn_deriv, dif_neg hl, lintegral_zero], exact with_top.zero_lt_top }, end lemma lintegral_rn_deriv_lt_top (μ ν : measure α) [is_finite_measure μ] : ∫⁻ x, μ.rn_deriv ν x ∂ν < ∞ := begin rw [← set_lintegral_univ], exact lintegral_rn_deriv_lt_top_of_measure_ne_top _ (measure_lt_top _ _).ne, end /-- The Radon-Nikodym derivative of a sigma-finite measure `μ` with respect to another measure `ν` is `ν`-almost everywhere finite. -/ theorem rn_deriv_lt_top (μ ν : measure α) [sigma_finite μ] : ∀ᵐ x ∂ν, μ.rn_deriv ν x < ∞ := begin suffices : ∀ n, ∀ᵐ x ∂ν, x ∈ spanning_sets μ n → μ.rn_deriv ν x < ∞, { filter_upwards [ae_all_iff.2 this] with _ hx using hx _ (mem_spanning_sets_index _ _), }, assume n, rw ← ae_restrict_iff' (measurable_spanning_sets _ _), apply ae_lt_top (measurable_rn_deriv _ _), refine (lintegral_rn_deriv_lt_top_of_measure_ne_top _ _).ne, exact (measure_spanning_sets_lt_top _ _).ne end /-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `s = μ.singular_part μ`. This theorem provides the uniqueness of the `singular_part` in the Lebesgue decomposition theorem, while `measure_theory.measure.eq_rn_deriv` provides the uniqueness of the `rn_deriv`. -/ theorem eq_singular_part {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f) (hs : s ⟂ₘ ν) (hadd : μ = s + ν.with_density f) : s = μ.singular_part ν := begin haveI : have_lebesgue_decomposition μ ν := ⟨⟨⟨s, f⟩, hf, hs, hadd⟩⟩, obtain ⟨hmeas, hsing, hadd'⟩ := have_lebesgue_decomposition_spec μ ν, obtain ⟨⟨S, hS₁, hS₂, hS₃⟩, ⟨T, hT₁, hT₂, hT₃⟩⟩ := ⟨hs, hsing⟩, rw hadd' at hadd, have hνinter : ν (S ∩ T)ᶜ = 0, { rw compl_inter, refine nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) _), rw [hT₃, hS₃, add_zero], exact le_rfl }, have heq : s.restrict (S ∩ T)ᶜ = (μ.singular_part ν).restrict (S ∩ T)ᶜ, { ext1 A hA, have hf : ν.with_density f (A ∩ (S ∩ T)ᶜ) = 0, { refine with_density_absolutely_continuous ν _ _, rw ← nonpos_iff_eq_zero, exact hνinter ▸ measure_mono (inter_subset_right _ _) }, have hrn : ν.with_density (μ.rn_deriv ν) (A ∩ (S ∩ T)ᶜ) = 0, { refine with_density_absolutely_continuous ν _ _, rw ← nonpos_iff_eq_zero, exact hνinter ▸ measure_mono (inter_subset_right _ _) }, rw [restrict_apply hA, restrict_apply hA, ← add_zero (s (A ∩ (S ∩ T)ᶜ)), ← hf, ← add_apply, ← hadd, add_apply, hrn, add_zero] }, have heq' : ∀ A : set α, measurable_set A → s A = s.restrict (S ∩ T)ᶜ A, { intros A hA, have hsinter : s (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hS₂ ▸ measure_mono ((inter_subset_right _ _).trans (inter_subset_left _ _)) }, rw [restrict_apply hA, ← diff_eq, ae_disjoint.measure_diff_left hsinter] }, ext1 A hA, have hμinter : μ.singular_part ν (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hT₂ ▸ measure_mono ((inter_subset_right _ _).trans (inter_subset_right _ _)) }, rw [heq' A hA, heq, restrict_apply hA, ← diff_eq, ae_disjoint.measure_diff_left hμinter] end lemma singular_part_zero (ν : measure α) : (0 : measure α).singular_part ν = 0 := begin refine (eq_singular_part measurable_zero mutually_singular.zero_left _).symm, rw [zero_add, with_density_zero], end lemma singular_part_smul (μ ν : measure α) (r : ℝ≥0) : (r • μ).singular_part ν = r • (μ.singular_part ν) := begin by_cases hr : r = 0, { rw [hr, zero_smul, zero_smul, singular_part_zero] }, by_cases hl : have_lebesgue_decomposition μ ν, { haveI := hl, refine (eq_singular_part ((measurable_rn_deriv μ ν).const_smul (r : ℝ≥0∞)) (mutually_singular.smul r (have_lebesgue_decomposition_spec _ _).2.1) _).symm, rw [with_density_smul _ (measurable_rn_deriv _ _), ← smul_add, ← have_lebesgue_decomposition_add μ ν, ennreal.smul_def] }, { rw [singular_part, singular_part, dif_neg hl, dif_neg, smul_zero], refine λ hl', hl _, rw ← inv_smul_smul₀ hr μ, exact @measure.have_lebesgue_decomposition_smul _ _ _ _ hl' _ } end lemma singular_part_add (μ₁ μ₂ ν : measure α) [have_lebesgue_decomposition μ₁ ν] [have_lebesgue_decomposition μ₂ ν] : (μ₁ + μ₂).singular_part ν = μ₁.singular_part ν + μ₂.singular_part ν := begin refine (eq_singular_part ((measurable_rn_deriv μ₁ ν).add (measurable_rn_deriv μ₂ ν)) ((have_lebesgue_decomposition_spec _ _).2.1.add_left (have_lebesgue_decomposition_spec _ _).2.1) _).symm, erw with_density_add_left (measurable_rn_deriv μ₁ ν), conv_rhs { rw [add_assoc, add_comm (μ₂.singular_part ν), ← add_assoc, ← add_assoc] }, rw [← have_lebesgue_decomposition_add μ₁ ν, add_assoc, add_comm (ν.with_density (μ₂.rn_deriv ν)), ← have_lebesgue_decomposition_add μ₂ ν] end lemma singular_part_with_density (ν : measure α) {f : α → ℝ≥0∞} (hf : measurable f) : (ν.with_density f).singular_part ν = 0 := begin have : ν.with_density f = 0 + ν.with_density f, by rw zero_add, exact (eq_singular_part hf mutually_singular.zero_left this).symm, end /-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `f = μ.rn_deriv ν`. This theorem provides the uniqueness of the `rn_deriv` in the Lebesgue decomposition theorem, while `measure_theory.measure.eq_singular_part` provides the uniqueness of the `singular_part`. Here, the uniqueness is given in terms of the measures, while the uniqueness in terms of the functions is given in `eq_rn_deriv`. -/ theorem eq_with_density_rn_deriv {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f) (hs : s ⟂ₘ ν) (hadd : μ = s + ν.with_density f) : ν.with_density f = ν.with_density (μ.rn_deriv ν) := begin haveI : have_lebesgue_decomposition μ ν := ⟨⟨⟨s, f⟩, hf, hs, hadd⟩⟩, obtain ⟨hmeas, hsing, hadd'⟩ := have_lebesgue_decomposition_spec μ ν, obtain ⟨⟨S, hS₁, hS₂, hS₃⟩, ⟨T, hT₁, hT₂, hT₃⟩⟩ := ⟨hs, hsing⟩, rw hadd' at hadd, have hνinter : ν (S ∩ T)ᶜ = 0, { rw compl_inter, refine nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) _), rw [hT₃, hS₃, add_zero], exact le_rfl }, have heq : (ν.with_density f).restrict (S ∩ T) = (ν.with_density (μ.rn_deriv ν)).restrict (S ∩ T), { ext1 A hA, have hs : s (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hS₂ ▸ measure_mono ((inter_subset_right _ _).trans (inter_subset_left _ _)) }, have hsing : μ.singular_part ν (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hT₂ ▸ measure_mono ((inter_subset_right _ _).trans (inter_subset_right _ _)) }, rw [restrict_apply hA, restrict_apply hA, ← add_zero (ν.with_density f (A ∩ (S ∩ T))), ← hs, ← add_apply, add_comm, ← hadd, add_apply, hsing, zero_add] }, have heq' : ∀ A : set α, measurable_set A → ν.with_density f A = (ν.with_density f).restrict (S ∩ T) A, { intros A hA, have hνfinter : ν.with_density f (A ∩ (S ∩ T)ᶜ) = 0, { rw ← nonpos_iff_eq_zero, exact with_density_absolutely_continuous ν f hνinter ▸ measure_mono (inter_subset_right _ _) }, rw [restrict_apply hA, ← add_zero (ν.with_density f (A ∩ (S ∩ T))), ← hνfinter, ← diff_eq, measure_inter_add_diff _ (hS₁.inter hT₁)] }, ext1 A hA, have hνrn : ν.with_density (μ.rn_deriv ν) (A ∩ (S ∩ T)ᶜ) = 0, { rw ← nonpos_iff_eq_zero, exact with_density_absolutely_continuous ν (μ.rn_deriv ν) hνinter ▸ measure_mono (inter_subset_right _ _) }, rw [heq' A hA, heq, ← add_zero ((ν.with_density (μ.rn_deriv ν)).restrict (S ∩ T) A), ← hνrn, restrict_apply hA, ← diff_eq, measure_inter_add_diff _ (hS₁.inter hT₁)] end /-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `f = μ.rn_deriv ν`. This theorem provides the uniqueness of the `rn_deriv` in the Lebesgue decomposition theorem, while `measure_theory.measure.eq_singular_part` provides the uniqueness of the `singular_part`. Here, the uniqueness is given in terms of the functions, while the uniqueness in terms of the functions is given in `eq_with_density_rn_deriv`. -/ theorem eq_rn_deriv [sigma_finite ν] {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f) (hs : s ⟂ₘ ν) (hadd : μ = s + ν.with_density f) : f =ᵐ[ν] μ.rn_deriv ν := begin refine ae_eq_of_forall_set_lintegral_eq_of_sigma_finite hf (measurable_rn_deriv μ ν) _, assume a ha h'a, calc ∫⁻ (x : α) in a, f x ∂ν = ν.with_density f a : (with_density_apply f ha).symm ... = ν.with_density (μ.rn_deriv ν) a : by rw eq_with_density_rn_deriv hf hs hadd ... = ∫⁻ (x : α) in a, μ.rn_deriv ν x ∂ν : with_density_apply _ ha end /-- The Radon-Nikodym derivative of `f ν` with respect to `ν` is `f`. -/ theorem rn_deriv_with_density (ν : measure α) [sigma_finite ν] {f : α → ℝ≥0∞} (hf : measurable f) : (ν.with_density f).rn_deriv ν =ᵐ[ν] f := begin have : ν.with_density f = 0 + ν.with_density f, by rw zero_add, exact (eq_rn_deriv hf mutually_singular.zero_left this).symm, end /-- The Radon-Nikodym derivative of the restriction of a measure to a measurable set is the indicator function of this set. -/ theorem rn_deriv_restrict (ν : measure α) [sigma_finite ν] {s : set α} (hs : measurable_set s) : (ν.restrict s).rn_deriv ν =ᵐ[ν] s.indicator 1 := begin rw ← with_density_indicator_one hs, exact rn_deriv_with_density _ (measurable_one.indicator hs) end open vector_measure signed_measure /-- If two finite measures `μ` and `ν` are not mutually singular, there exists some `ε > 0` and a measurable set `E`, such that `ν(E) > 0` and `E` is positive with respect to `μ - εν`. This lemma is useful for the Lebesgue decomposition theorem. -/ lemma exists_positive_of_not_mutually_singular (μ ν : measure α) [is_finite_measure μ] [is_finite_measure ν] (h : ¬ μ ⟂ₘ ν) : ∃ ε : ℝ≥0, 0 < ε ∧ ∃ E : set α, measurable_set E ∧ 0 < ν E ∧ 0 ≤[E] μ.to_signed_measure - (ε • ν).to_signed_measure := begin -- for all `n : ℕ`, obtain the Hahn decomposition for `μ - (1 / n) ν` have : ∀ n : ℕ, ∃ i : set α, measurable_set i ∧ 0 ≤[i] (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ∧ (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ≤[iᶜ] 0, { intro, exact exists_compl_positive_negative _ }, choose f hf₁ hf₂ hf₃ using this, -- set `A` to be the intersection of all the negative parts of obtained Hahn decompositions -- and we show that `μ A = 0` set A := ⋂ n, (f n)ᶜ with hA₁, have hAmeas : measurable_set A, { exact measurable_set.Inter (λ n, (hf₁ n).compl) }, have hA₂ : ∀ n : ℕ, (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ≤[A] 0, { intro n, exact restrict_le_restrict_subset _ _ (hf₁ n).compl (hf₃ n) (Inter_subset _ _) }, have hA₃ : ∀ n : ℕ, μ A ≤ (1 / (n + 1) : ℝ≥0) * ν A, { intro n, have := nonpos_of_restrict_le_zero _ (hA₂ n), rwa [to_signed_measure_sub_apply hAmeas, sub_nonpos, ennreal.to_real_le_to_real] at this, exacts [ne_of_lt (measure_lt_top _ _), ne_of_lt (measure_lt_top _ _)] }, have hμ : μ A = 0, { lift μ A to ℝ≥0 using ne_of_lt (measure_lt_top _ _) with μA, lift ν A to ℝ≥0 using ne_of_lt (measure_lt_top _ _) with νA, rw ennreal.coe_eq_zero, by_cases hb : 0 < νA, { suffices : ∀ b, 0 < b → μA ≤ b, { by_contra, have h' := this (μA / 2) (half_pos (zero_lt_iff.2 h)), rw ← @not_not (μA ≤ μA / 2) at h', exact h' (not_le.2 (nnreal.half_lt_self h)) }, intros c hc, have : ∃ n : ℕ, 1 / (n + 1 : ℝ) < c * νA⁻¹, refine exists_nat_one_div_lt _, { refine mul_pos hc _, rw _root_.inv_pos, exact hb }, rcases this with ⟨n, hn⟩, have hb₁ : (0 : ℝ) < νA⁻¹, { rw _root_.inv_pos, exact hb }, have h' : 1 / (↑n + 1) * νA < c, { rw [← nnreal.coe_lt_coe, ← mul_lt_mul_right hb₁, nnreal.coe_mul, mul_assoc, ← nnreal.coe_inv, ← nnreal.coe_mul, _root_.mul_inv_cancel, ← nnreal.coe_mul, mul_one, nnreal.coe_inv], { exact hn }, { exact ne.symm (ne_of_lt hb) } }, refine le_trans _ (le_of_lt h'), rw [← ennreal.coe_le_coe, ennreal.coe_mul], exact hA₃ n }, { rw [not_lt, le_zero_iff] at hb, specialize hA₃ 0, simp [hb, le_zero_iff] at hA₃, assumption } }, -- since `μ` and `ν` are not mutually singular, `μ A = 0` implies `ν Aᶜ > 0` rw mutually_singular at h, push_neg at h, have := h _ hAmeas hμ, simp_rw [hA₁, compl_Inter, compl_compl] at this, -- as `Aᶜ = ⋃ n, f n`, `ν Aᶜ > 0` implies there exists some `n` such that `ν (f n) > 0` obtain ⟨n, hn⟩ := exists_measure_pos_of_not_measure_Union_null this, -- thus, choosing `f n` as the set `E` suffices exact ⟨1 / (n + 1), by simp, f n, hf₁ n, hn, hf₂ n⟩, end namespace lebesgue_decomposition /-- Given two measures `μ` and `ν`, `measurable_le μ ν` is the set of measurable functions `f`, such that, for all measurable sets `A`, `∫⁻ x in A, f x ∂μ ≤ ν A`. This is useful for the Lebesgue decomposition theorem. -/ def measurable_le (μ ν : measure α) : set (α → ℝ≥0∞) := { f | measurable f ∧ ∀ (A : set α) (hA : measurable_set A), ∫⁻ x in A, f x ∂μ ≤ ν A } lemma zero_mem_measurable_le : (0 : α → ℝ≥0∞) ∈ measurable_le μ ν := ⟨measurable_zero, λ A hA, by simp⟩ lemma sup_mem_measurable_le {f g : α → ℝ≥0∞} (hf : f ∈ measurable_le μ ν) (hg : g ∈ measurable_le μ ν) : (λ a, f a ⊔ g a) ∈ measurable_le μ ν := begin simp_rw ennreal.sup_eq_max, refine ⟨measurable.max hf.1 hg.1, λ A hA, _⟩, have h₁ := hA.inter (measurable_set_le hf.1 hg.1), have h₂ := hA.inter (measurable_set_lt hg.1 hf.1), rw [set_lintegral_max hf.1 hg.1], refine (add_le_add (hg.2 _ h₁) (hf.2 _ h₂)).trans_eq _, { simp only [← not_le, ← compl_set_of, ← diff_eq], exact measure_inter_add_diff _ (measurable_set_le hf.1 hg.1) } end lemma supr_succ_eq_sup {α} (f : ℕ → α → ℝ≥0∞) (m : ℕ) (a : α) : (⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) = f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a := begin ext x, simp only [option.mem_def, ennreal.some_eq_coe], split; intro h; rw ← h, symmetry, all_goals { set c := (⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) with hc, set d := (f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a) with hd, rw [@le_antisymm_iff ℝ≥0∞, hc, hd], -- Specifying the type is weirdly necessary refine ⟨_, _⟩, { refine supr₂_le (λ n hn, _), rcases nat.of_le_succ hn with (h | h), { exact le_sup_of_le_right (le_supr₂ n h) }, { exact h ▸ le_sup_left } }, { refine sup_le _ (bsupr_mono $ λ n hn, hn.trans m.le_succ), convert @le_supr₂ _ _ (λ i, i ≤ m + 1) _ _ m.succ le_rfl, refl } } end lemma supr_mem_measurable_le (f : ℕ → α → ℝ≥0∞) (hf : ∀ n, f n ∈ measurable_le μ ν) (n : ℕ) : (λ x, ⨆ k (hk : k ≤ n), f k x) ∈ measurable_le μ ν := begin induction n with m hm, { refine ⟨_, _⟩, { simp [(hf 0).1] }, { intros A hA, simp [(hf 0).2 A hA] } }, { have : (λ (a : α), ⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) = (λ a, f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a), { exact funext (λ _, supr_succ_eq_sup _ _ _) }, refine ⟨measurable_supr (λ n, measurable.supr_Prop _ (hf n).1), λ A hA, _⟩, rw this, exact (sup_mem_measurable_le (hf m.succ) hm).2 A hA } end lemma supr_mem_measurable_le' (f : ℕ → α → ℝ≥0∞) (hf : ∀ n, f n ∈ measurable_le μ ν) (n : ℕ) : (⨆ k (hk : k ≤ n), f k) ∈ measurable_le μ ν := begin convert supr_mem_measurable_le f hf n, ext, simp end section supr_lemmas --TODO: these statements should be moved elsewhere omit m lemma supr_monotone {α : Type*} (f : ℕ → α → ℝ≥0∞) : monotone (λ n x, ⨆ k (hk : k ≤ n), f k x) := λ n m hnm x, bsupr_mono $ λ i, ge_trans hnm lemma supr_monotone' {α : Type*} (f : ℕ → α → ℝ≥0∞) (x : α) : monotone (λ n, ⨆ k (hk : k ≤ n), f k x) := λ n m hnm, supr_monotone f hnm x lemma supr_le_le {α : Type*} (f : ℕ → α → ℝ≥0∞) (n k : ℕ) (hk : k ≤ n) : f k ≤ λ x, ⨆ k (hk : k ≤ n), f k x := λ x, le_supr₂ k hk end supr_lemmas /-- `measurable_le_eval μ ν` is the set of `∫⁻ x, f x ∂μ` for all `f ∈ measurable_le μ ν`. -/ def measurable_le_eval (μ ν : measure α) : set ℝ≥0∞ := (λ f : α → ℝ≥0∞, ∫⁻ x, f x ∂μ) '' measurable_le μ ν end lebesgue_decomposition open lebesgue_decomposition /-- Any pair of finite measures `μ` and `ν`, `have_lebesgue_decomposition`. That is to say, there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f`. This is not an instance since this is also shown for the more general σ-finite measures with `measure_theory.measure.have_lebesgue_decomposition_of_sigma_finite`. -/ theorem have_lebesgue_decomposition_of_finite_measure [is_finite_measure μ] [is_finite_measure ν] : have_lebesgue_decomposition μ ν := ⟨begin have h := @exists_seq_tendsto_Sup _ _ _ _ _ (measurable_le_eval ν μ) ⟨0, 0, zero_mem_measurable_le, by simp⟩ (order_top.bdd_above _), choose g hmono hg₂ f hf₁ hf₂ using h, -- we set `ξ` to be the supremum of an increasing sequence of functions obtained from above set ξ := ⨆ n k (hk : k ≤ n), f k with hξ, -- we see that `ξ` has the largest integral among all functions in `measurable_le` have hξ₁ : Sup (measurable_le_eval ν μ) = ∫⁻ a, ξ a ∂ν, { have := @lintegral_tendsto_of_tendsto_of_monotone _ _ ν (λ n, ⨆ k (hk : k ≤ n), f k) (⨆ n k (hk : k ≤ n), f k) _ _ _, { refine tendsto_nhds_unique _ this, refine tendsto_of_tendsto_of_tendsto_of_le_of_le hg₂ tendsto_const_nhds _ _, { intro n, rw ← hf₂ n, apply lintegral_mono, simp only [supr_apply, supr_le_le f n n le_rfl] }, { intro n, exact le_Sup ⟨⨆ (k : ℕ) (hk : k ≤ n), f k, supr_mem_measurable_le' _ hf₁ _, rfl⟩ } }, { intro n, refine measurable.ae_measurable _, convert (supr_mem_measurable_le _ hf₁ n).1, ext, simp }, { refine filter.eventually_of_forall (λ a, _), simp [supr_monotone' f _] }, { refine filter.eventually_of_forall (λ a, _), simp [tendsto_at_top_supr (supr_monotone' f a)] } }, have hξm : measurable ξ, { convert measurable_supr (λ n, (supr_mem_measurable_le _ hf₁ n).1), ext, simp [hξ] }, -- `ξ` is the `f` in the theorem statement and we set `μ₁` to be `μ - ν.with_density ξ` -- since we need `μ₁ + ν.with_density ξ = μ` set μ₁ := μ - ν.with_density ξ with hμ₁, have hle : ν.with_density ξ ≤ μ, { intros B hB, rw [hξ, with_density_apply _ hB], simp_rw [supr_apply], rw lintegral_supr (λ i, (supr_mem_measurable_le _ hf₁ i).1) (supr_monotone _), exact supr_le (λ i, (supr_mem_measurable_le _ hf₁ i).2 B hB) }, haveI : is_finite_measure (ν.with_density ξ), { refine is_finite_measure_with_density _, have hle' := hle univ measurable_set.univ, rw [with_density_apply _ measurable_set.univ, measure.restrict_univ] at hle', exact ne_top_of_le_ne_top (measure_ne_top _ _) hle' }, refine ⟨⟨μ₁, ξ⟩, hξm, _, _⟩, { by_contra, -- if they are not mutually singular, then from `exists_positive_of_not_mutually_singular`, -- there exists some `ε > 0` and a measurable set `E`, such that `μ(E) > 0` and `E` is -- positive with respect to `ν - εμ` obtain ⟨ε, hε₁, E, hE₁, hE₂, hE₃⟩ := exists_positive_of_not_mutually_singular μ₁ ν h, simp_rw hμ₁ at hE₃, have hξle : ∀ A, measurable_set A → ∫⁻ a in A, ξ a ∂ν ≤ μ A, { intros A hA, rw hξ, simp_rw [supr_apply], rw lintegral_supr (λ n, (supr_mem_measurable_le _ hf₁ n).1) (supr_monotone _), exact supr_le (λ n, (supr_mem_measurable_le _ hf₁ n).2 A hA) }, -- since `E` is positive, we have `∫⁻ a in A ∩ E, ε + ξ a ∂ν ≤ μ (A ∩ E)` for all `A` have hε₂ : ∀ A : set α, measurable_set A → ∫⁻ a in A ∩ E, ε + ξ a ∂ν ≤ μ (A ∩ E), { intros A hA, have := subset_le_of_restrict_le_restrict _ _ hE₁ hE₃ (inter_subset_right A E), rwa [zero_apply, to_signed_measure_sub_apply (hA.inter hE₁), measure.sub_apply (hA.inter hE₁) hle, ennreal.to_real_sub_of_le _ (ne_of_lt (measure_lt_top _ _)), sub_nonneg, le_sub_iff_add_le, ← ennreal.to_real_add, ennreal.to_real_le_to_real, measure.coe_smul, pi.smul_apply, with_density_apply _ (hA.inter hE₁), show ε • ν (A ∩ E) = (ε : ℝ≥0∞) * ν (A ∩ E), by refl, ← set_lintegral_const, ← lintegral_add_left measurable_const] at this, { rw [ne.def, ennreal.add_eq_top, not_or_distrib], exact ⟨ne_of_lt (measure_lt_top _ _), ne_of_lt (measure_lt_top _ _)⟩ }, { exact ne_of_lt (measure_lt_top _ _) }, { exact ne_of_lt (measure_lt_top _ _) }, { exact ne_of_lt (measure_lt_top _ _) }, { rw with_density_apply _ (hA.inter hE₁), exact hξle (A ∩ E) (hA.inter hE₁) }, { apply_instance } }, -- from this, we can show `ξ + ε * E.indicator` is a function in `measurable_le` with -- integral greater than `ξ` have hξε : ξ + E.indicator (λ _, ε) ∈ measurable_le ν μ, { refine ⟨measurable.add hξm (measurable.indicator measurable_const hE₁), λ A hA, _⟩, have : ∫⁻ a in A, (ξ + E.indicator (λ _, ε)) a ∂ν = ∫⁻ a in A ∩ E, ε + ξ a ∂ν + ∫⁻ a in A \ E, ξ a ∂ν, { simp only [lintegral_add_left measurable_const, lintegral_add_left hξm, set_lintegral_const, add_assoc, lintegral_inter_add_diff _ _ hE₁, pi.add_apply, lintegral_indicator _ hE₁, restrict_apply hE₁], rw [inter_comm, add_comm] }, rw [this, ← measure_inter_add_diff A hE₁], exact add_le_add (hε₂ A hA) (hξle (A \ E) (hA.diff hE₁)) }, have : ∫⁻ a, ξ a + E.indicator (λ _, ε) a ∂ν ≤ Sup (measurable_le_eval ν μ) := le_Sup ⟨ξ + E.indicator (λ _, ε), hξε, rfl⟩, -- but this contradicts the maximality of `∫⁻ x, ξ x ∂ν` refine not_lt.2 this _, rw [hξ₁, lintegral_add_left hξm, lintegral_indicator _ hE₁, set_lintegral_const], refine ennreal.lt_add_right _ (ennreal.mul_pos_iff.2 ⟨ennreal.coe_pos.2 hε₁, hE₂⟩).ne', have := measure_ne_top (ν.with_density ξ) univ, rwa [with_density_apply _ measurable_set.univ, measure.restrict_univ] at this }, -- since `ν.with_density ξ ≤ μ`, it is clear that `μ = μ₁ + ν.with_density ξ` { rw hμ₁, ext1 A hA, rw [measure.coe_add, pi.add_apply, measure.sub_apply hA hle, add_comm, add_tsub_cancel_of_le (hle A hA)] }, end⟩ local attribute [instance] have_lebesgue_decomposition_of_finite_measure instance {S : μ.finite_spanning_sets_in {s : set α | measurable_set s}} (n : ℕ) : is_finite_measure (μ.restrict $ S.set n) := ⟨by { rw [restrict_apply measurable_set.univ, univ_inter], exact S.finite _ }⟩ /-- **The Lebesgue decomposition theorem**: Any pair of σ-finite measures `μ` and `ν` `have_lebesgue_decomposition`. That is to say, there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f` -/ @[priority 100] -- see Note [lower instance priority] instance have_lebesgue_decomposition_of_sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] : have_lebesgue_decomposition μ ν := ⟨begin -- Since `μ` and `ν` are both σ-finite, there exists a sequence of pairwise disjoint spanning -- sets which are finite with respect to both `μ` and `ν` obtain ⟨S, T, h₁, h₂⟩ := exists_eq_disjoint_finite_spanning_sets_in μ ν, have h₃ : pairwise (disjoint on T.set) := h₁ ▸ h₂, -- We define `μn` and `νn` as sequences of measures such that `μn n = μ ∩ S n` and -- `νn n = ν ∩ S n` where `S` is the aforementioned finite spanning set sequence. -- Since `S` is spanning, it is clear that `sum μn = μ` and `sum νn = ν` set μn : ℕ → measure α := λ n, μ.restrict (S.set n) with hμn, have hμ : μ = sum μn, { rw [hμn, ← restrict_Union h₂ S.set_mem, S.spanning, restrict_univ] }, set νn : ℕ → measure α := λ n, ν.restrict (T.set n) with hνn, have hν : ν = sum νn, { rw [hνn, ← restrict_Union h₃ T.set_mem, T.spanning, restrict_univ] }, -- As `S` is finite with respect to both `μ` and `ν`, it is clear that `μn n` and `νn n` are -- finite measures for all `n : ℕ`. Thus, we may apply the finite Lebesgue decomposition theorem -- to `μn n` and `νn n`. We define `ξ` as the sum of the singular part of the Lebesgue -- decompositions of `μn n` and `νn n`, and `f` as the sum of the Radon-Nikodym derviatives of -- `μn n` and `νn n` restricted on `S n` set ξ := sum (λ n, singular_part (μn n) (νn n)) with hξ, set f := ∑' n, (S.set n).indicator (rn_deriv (μn n) (νn n)) with hf, -- I claim `ξ` and `f` form a Lebesgue decomposition of `μ` and `ν` refine ⟨⟨ξ, f⟩, _, _, _⟩, { exact measurable.ennreal_tsum' (λ n, measurable.indicator (measurable_rn_deriv (μn n) (νn n)) (S.set_mem n)) }, -- We show that `ξ` is mutually singular with respect to `ν` { choose A hA₁ hA₂ hA₃ using λ n, mutually_singular_singular_part (μn n) (νn n), simp only [hξ], -- We use the set `B := ⋃ j, (S.set j) ∩ A j` where `A n` is the set provided as -- `singular_part (μn n) (νn n) ⟂ₘ νn n` refine ⟨⋃ j, (S.set j) ∩ A j, measurable_set.Union (λ n, (S.set_mem n).inter (hA₁ n)), _, _⟩, -- `ξ B = 0` since `ξ B = ∑ i j, singular_part (μn j) (νn j) (S.set i ∩ A i)` -- `= ∑ i, singular_part (μn i) (νn i) (S.set i ∩ A i)` -- `≤ ∑ i, singular_part (μn i) (νn i) (A i) = 0` -- where the second equality follows as `singular_part (μn j) (νn j) (S.set i ∩ A i)` vanishes -- for all `i ≠ j` { rw [measure_Union], { have : ∀ i, (sum (λ n, (μn n).singular_part (νn n))) (S.set i ∩ A i) = (μn i).singular_part (νn i) (S.set i ∩ A i), { intro i, rw [sum_apply _ ((S.set_mem i).inter (hA₁ i)), tsum_eq_single i], { intros j hij, rw [hμn, ← nonpos_iff_eq_zero], refine le_trans ((singular_part_le _ _) _ ((S.set_mem i).inter (hA₁ i))) (le_of_eq _), rw [restrict_apply ((S.set_mem i).inter (hA₁ i)), inter_comm, ← inter_assoc], have : disjoint (S.set j) (S.set i) := h₂ hij, rw disjoint_iff_inter_eq_empty at this, rw [this, empty_inter, measure_empty] }, { apply_instance } }, simp_rw [this, tsum_eq_zero_iff ennreal.summable], intro n, exact measure_mono_null (inter_subset_right _ _) (hA₂ n) }, { exact h₂.mono (λ i j, disjoint.mono inf_le_left inf_le_left) }, { exact λ n, (S.set_mem n).inter (hA₁ n) } }, -- We will now show `ν Bᶜ = 0`. This follows since `Bᶜ = ⋃ n, S.set n ∩ (A n)ᶜ` and thus, -- `ν Bᶜ = ∑ i, ν (S.set i ∩ (A i)ᶜ) = ∑ i, (νn i) (A i)ᶜ = 0` { have hcompl : is_compl (⋃ n, (S.set n ∩ A n)) (⋃ n, S.set n ∩ (A n)ᶜ), { split, { rw disjoint_iff_inf_le, rintro x ⟨hx₁, hx₂⟩, rw mem_Union at hx₁ hx₂, obtain ⟨⟨i, hi₁, hi₂⟩, ⟨j, hj₁, hj₂⟩⟩ := ⟨hx₁, hx₂⟩, have : i = j, { by_contra hij, exact (h₂ hij).le_bot ⟨hi₁, hj₁⟩ }, exact hj₂ (this ▸ hi₂) }, { rw codisjoint_iff_le_sup, intros x hx, simp only [mem_Union, sup_eq_union, mem_inter_iff, mem_union, mem_compl_iff, or_iff_not_imp_left], intro h, push_neg at h, rw [top_eq_univ, ← S.spanning, mem_Union] at hx, obtain ⟨i, hi⟩ := hx, exact ⟨i, hi, h i hi⟩ } }, rw [hcompl.compl_eq, measure_Union, tsum_eq_zero_iff ennreal.summable], { intro n, rw [inter_comm, ← restrict_apply (hA₁ n).compl, ← hA₃ n, hνn, h₁] }, { exact h₂.mono (λ i j, disjoint.mono inf_le_left inf_le_left) }, { exact λ n, (S.set_mem n).inter (hA₁ n).compl } } }, -- Finally, it remains to show `μ = ξ + ν.with_density f`. Since `μ = sum μn`, and -- `ξ + ν.with_density f = ∑ n, singular_part (μn n) (νn n)` -- `+ ν.with_density (rn_deriv (μn n) (νn n)) ∩ (S.set n)`, -- it suffices to show that the individual summands are equal. This follows by the -- Lebesgue decomposition properties on the individual `μn n` and `νn n` { simp only [hξ, hf, hμ], rw [with_density_tsum _, sum_add_sum], { refine sum_congr (λ n, _), conv_lhs { rw have_lebesgue_decomposition_add (μn n) (νn n) }, suffices heq : (νn n).with_density ((μn n).rn_deriv (νn n)) = ν.with_density ((S.set n).indicator ((μn n).rn_deriv (νn n))), { rw heq }, rw [hν, with_density_indicator (S.set_mem n), restrict_sum _ (S.set_mem n)], suffices hsumeq : sum (λ (i : ℕ), (νn i).restrict (S.set n)) = νn n, { rw hsumeq }, ext1 s hs, rw [sum_apply _ hs, tsum_eq_single n, hνn, h₁, restrict_restrict (T.set_mem n), inter_self], { intros m hm, rw [hνn, h₁, restrict_restrict (T.set_mem n), (h₃ hm.symm).inter_eq, restrict_empty, coe_zero, pi.zero_apply] }, { apply_instance } }, { exact λ n, measurable.indicator (measurable_rn_deriv _ _) (S.set_mem n) } }, end⟩ end measure namespace signed_measure open measure /-- A signed measure `s` is said to `have_lebesgue_decomposition` with respect to a measure `μ` if the positive part and the negative part of `s` both `have_lebesgue_decomposition` with respect to `μ`. -/ class have_lebesgue_decomposition (s : signed_measure α) (μ : measure α) : Prop := (pos_part : s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition μ) (neg_part : s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition μ) attribute [instance] have_lebesgue_decomposition.pos_part attribute [instance] have_lebesgue_decomposition.neg_part lemma not_have_lebesgue_decomposition_iff (s : signed_measure α) (μ : measure α) : ¬ s.have_lebesgue_decomposition μ ↔ ¬ s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition μ ∨ ¬ s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition μ := ⟨λ h, not_or_of_imp (λ hp hn, h ⟨hp, hn⟩), λ h hl, (not_and_distrib.2 h) ⟨hl.1, hl.2⟩⟩ -- `infer_instance` directly does not work @[priority 100] -- see Note [lower instance priority] instance have_lebesgue_decomposition_of_sigma_finite (s : signed_measure α) (μ : measure α) [sigma_finite μ] : s.have_lebesgue_decomposition μ := { pos_part := infer_instance, neg_part := infer_instance } instance have_lebesgue_decomposition_neg (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] : (-s).have_lebesgue_decomposition μ := { pos_part := by { rw [to_jordan_decomposition_neg, jordan_decomposition.neg_pos_part], apply_instance }, neg_part := by { rw [to_jordan_decomposition_neg, jordan_decomposition.neg_neg_part], apply_instance } } instance have_lebesgue_decomposition_smul (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ≥0) : (r • s).have_lebesgue_decomposition μ := { pos_part := by { rw [to_jordan_decomposition_smul, jordan_decomposition.smul_pos_part], apply_instance }, neg_part := by { rw [to_jordan_decomposition_smul, jordan_decomposition.smul_neg_part], apply_instance } } instance have_lebesgue_decomposition_smul_real (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ) : (r • s).have_lebesgue_decomposition μ := begin by_cases hr : 0 ≤ r, { lift r to ℝ≥0 using hr, exact s.have_lebesgue_decomposition_smul μ _ }, { rw not_le at hr, refine { pos_part := by { rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_pos_part_neg _ _ hr], apply_instance }, neg_part := by { rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_neg_part_neg _ _ hr], apply_instance } } } end /-- Given a signed measure `s` and a measure `μ`, `s.singular_part μ` is the signed measure such that `s.singular_part μ + μ.with_densityᵥ (s.rn_deriv μ) = s` and `s.singular_part μ` is mutually singular with respect to `μ`. -/ def singular_part (s : signed_measure α) (μ : measure α) : signed_measure α := (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure - (s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure section lemma singular_part_mutually_singular (s : signed_measure α) (μ : measure α) : s.to_jordan_decomposition.pos_part.singular_part μ ⟂ₘ s.to_jordan_decomposition.neg_part.singular_part μ := begin by_cases hl : s.have_lebesgue_decomposition μ, { haveI := hl, obtain ⟨i, hi, hpos, hneg⟩ := s.to_jordan_decomposition.mutually_singular, rw s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition_add μ at hpos, rw s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition_add μ at hneg, rw [add_apply, add_eq_zero_iff] at hpos hneg, exact ⟨i, hi, hpos.1, hneg.1⟩ }, { rw not_have_lebesgue_decomposition_iff at hl, cases hl with hp hn, { rw [measure.singular_part, dif_neg hp], exact mutually_singular.zero_left }, { rw [measure.singular_part, measure.singular_part, dif_neg hn], exact mutually_singular.zero_right } } end lemma singular_part_total_variation (s : signed_measure α) (μ : measure α) : (s.singular_part μ).total_variation = s.to_jordan_decomposition.pos_part.singular_part μ + s.to_jordan_decomposition.neg_part.singular_part μ := begin have : (s.singular_part μ).to_jordan_decomposition = ⟨s.to_jordan_decomposition.pos_part.singular_part μ, s.to_jordan_decomposition.neg_part.singular_part μ, singular_part_mutually_singular s μ⟩, { refine jordan_decomposition.to_signed_measure_injective _, rw to_signed_measure_to_jordan_decomposition, refl }, { rw [total_variation, this] }, end lemma mutually_singular_singular_part (s : signed_measure α) (μ : measure α) : singular_part s μ ⟂ᵥ μ.to_ennreal_vector_measure := begin rw [mutually_singular_ennreal_iff, singular_part_total_variation], change _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ), rw vector_measure.equiv_measure.right_inv μ, exact (mutually_singular_singular_part _ _).add_left (mutually_singular_singular_part _ _) end end /-- The Radon-Nikodym derivative between a signed measure and a positive measure. `rn_deriv s μ` satisfies `μ.with_densityᵥ (s.rn_deriv μ) = s` if and only if `s` is absolutely continuous with respect to `μ` and this fact is known as `measure_theory.signed_measure.absolutely_continuous_iff_with_density_rn_deriv_eq` and can be found in `measure_theory.decomposition.radon_nikodym`. -/ def rn_deriv (s : signed_measure α) (μ : measure α) : α → ℝ := λ x, (s.to_jordan_decomposition.pos_part.rn_deriv μ x).to_real - (s.to_jordan_decomposition.neg_part.rn_deriv μ x).to_real variables {s t : signed_measure α} @[measurability] lemma measurable_rn_deriv (s : signed_measure α) (μ : measure α) : measurable (rn_deriv s μ) := begin rw [rn_deriv], measurability, end lemma integrable_rn_deriv (s : signed_measure α) (μ : measure α) : integrable (rn_deriv s μ) μ := begin refine integrable.sub _ _; { split, { apply measurable.ae_strongly_measurable, measurability }, exact has_finite_integral_to_real_of_lintegral_ne_top (lintegral_rn_deriv_lt_top _ μ).ne } end variables (s μ) /-- **The Lebesgue Decomposition theorem between a signed measure and a measure**: Given a signed measure `s` and a σ-finite measure `μ`, there exist a signed measure `t` and a measurable and integrable function `f`, such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`. In this case `t = s.singular_part μ` and `f = s.rn_deriv μ`. -/ theorem singular_part_add_with_density_rn_deriv_eq [s.have_lebesgue_decomposition μ] : s.singular_part μ + μ.with_densityᵥ (s.rn_deriv μ) = s := begin conv_rhs { rw [← to_signed_measure_to_jordan_decomposition s, jordan_decomposition.to_signed_measure] }, rw [singular_part, rn_deriv, with_densityᵥ_sub' (integrable_to_real_of_lintegral_ne_top _ _) (integrable_to_real_of_lintegral_ne_top _ _), with_densityᵥ_to_real, with_densityᵥ_to_real, sub_eq_add_neg, sub_eq_add_neg, add_comm (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure, ← add_assoc, add_assoc (-(s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure), ← to_signed_measure_add, add_comm, ← add_assoc, ← neg_add, ← to_signed_measure_add, add_comm, ← sub_eq_add_neg], convert rfl, -- `convert rfl` much faster than `congr` { exact (s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition_add μ) }, { rw add_comm, exact (s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition_add μ) }, all_goals { exact (lintegral_rn_deriv_lt_top _ _).ne <|> measurability } end variables {s μ} lemma jordan_decomposition_add_with_density_mutually_singular {f : α → ℝ} (hf : measurable f) (htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) : t.to_jordan_decomposition.pos_part + μ.with_density (λ (x : α), ennreal.of_real (f x)) ⟂ₘ t.to_jordan_decomposition.neg_part + μ.with_density (λ (x : α), ennreal.of_real (-f x)) := begin rw [mutually_singular_ennreal_iff, total_variation_mutually_singular_iff] at htμ, change _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) ∧ _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv] at htμ, exact ((jordan_decomposition.mutually_singular _).add_right (htμ.1.mono_ac (refl _) (with_density_absolutely_continuous _ _))).add_left ((htμ.2.symm.mono_ac (with_density_absolutely_continuous _ _) (refl _)).add_right (with_density_of_real_mutually_singular hf)) end lemma to_jordan_decomposition_eq_of_eq_add_with_density {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.to_jordan_decomposition = @jordan_decomposition.mk α _ (t.to_jordan_decomposition.pos_part + μ.with_density (λ x, ennreal.of_real (f x))) (t.to_jordan_decomposition.neg_part + μ.with_density (λ x, ennreal.of_real (- f x))) (by { haveI := is_finite_measure_with_density_of_real hfi.2, apply_instance }) (by { haveI := is_finite_measure_with_density_of_real hfi.neg.2, apply_instance }) (jordan_decomposition_add_with_density_mutually_singular hf htμ) := begin haveI := is_finite_measure_with_density_of_real hfi.2, haveI := is_finite_measure_with_density_of_real hfi.neg.2, refine to_jordan_decomposition_eq _, simp_rw [jordan_decomposition.to_signed_measure, hadd], ext i hi, rw [vector_measure.sub_apply, to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi, add_apply, add_apply, ennreal.to_real_add, ennreal.to_real_add, add_sub_add_comm, ← to_signed_measure_apply_measurable hi, ← to_signed_measure_apply_measurable hi, ← vector_measure.sub_apply, ← jordan_decomposition.to_signed_measure, to_signed_measure_to_jordan_decomposition, vector_measure.add_apply, ← to_signed_measure_apply_measurable hi, ← to_signed_measure_apply_measurable hi, with_densityᵥ_eq_with_density_pos_part_sub_with_density_neg_part hfi, vector_measure.sub_apply]; exact (measure_lt_top _ _).ne end private lemma have_lebesgue_decomposition_mk' (μ : measure α) {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.have_lebesgue_decomposition μ := begin have htμ' := htμ, rw mutually_singular_ennreal_iff at htμ, change _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv, total_variation_mutually_singular_iff] at htμ, refine { pos_part := by { use ⟨t.to_jordan_decomposition.pos_part, λ x, ennreal.of_real (f x)⟩, refine ⟨hf.ennreal_of_real, htμ.1, _⟩, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd }, neg_part := by { use ⟨t.to_jordan_decomposition.neg_part, λ x, ennreal.of_real (-f x)⟩, refine ⟨hf.neg.ennreal_of_real, htμ.2, _⟩, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd } } end lemma have_lebesgue_decomposition_mk (μ : measure α) {f : α → ℝ} (hf : measurable f) (htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.have_lebesgue_decomposition μ := begin by_cases hfi : integrable f μ, { exact have_lebesgue_decomposition_mk' μ hf hfi htμ hadd }, { rw [with_densityᵥ, dif_neg hfi, add_zero] at hadd, refine have_lebesgue_decomposition_mk' μ measurable_zero (integrable_zero _ _ μ) htμ _, rwa [with_densityᵥ_zero, add_zero] } end private theorem eq_singular_part' (t : signed_measure α) {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : t = s.singular_part μ := begin have htμ' := htμ, rw [mutually_singular_ennreal_iff, total_variation_mutually_singular_iff] at htμ, change _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) ∧ _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv] at htμ, { rw [singular_part, ← t.to_signed_measure_to_jordan_decomposition, jordan_decomposition.to_signed_measure], congr, { have hfpos : measurable (λ x, ennreal.of_real (f x)), { measurability }, refine eq_singular_part hfpos htμ.1 _, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd }, { have hfneg : measurable (λ x, ennreal.of_real (-f x)), { measurability }, refine eq_singular_part hfneg htμ.2 _, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd } }, end /-- Given a measure `μ`, signed measures `s` and `t`, and a function `f` such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`, we have `t = singular_part s μ`, i.e. `t` is the singular part of the Lebesgue decomposition between `s` and `μ`. -/ theorem eq_singular_part (t : signed_measure α) (f : α → ℝ) (htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : t = s.singular_part μ := begin by_cases hfi : integrable f μ, { refine eq_singular_part' t hfi.1.measurable_mk (hfi.congr hfi.1.ae_eq_mk) htμ _, convert hadd using 2, exact with_densityᵥ_eq.congr_ae hfi.1.ae_eq_mk.symm }, { rw [with_densityᵥ, dif_neg hfi, add_zero] at hadd, refine eq_singular_part' t measurable_zero (integrable_zero _ _ μ) htμ _, rwa [with_densityᵥ_zero, add_zero] } end lemma singular_part_zero (μ : measure α) : (0 : signed_measure α).singular_part μ = 0 := begin refine (eq_singular_part 0 0 vector_measure.mutually_singular.zero_left _).symm, rw [zero_add, with_densityᵥ_zero], end lemma singular_part_neg (s : signed_measure α) (μ : measure α) : (-s).singular_part μ = - s.singular_part μ := begin have h₁ : ((-s).to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure = (s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure, { refine to_signed_measure_congr _, rw [to_jordan_decomposition_neg, jordan_decomposition.neg_pos_part] }, have h₂ : ((-s).to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure = (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure, { refine to_signed_measure_congr _, rw [to_jordan_decomposition_neg, jordan_decomposition.neg_neg_part] }, rw [singular_part, singular_part, neg_sub, h₁, h₂], end lemma singular_part_smul_nnreal (s : signed_measure α) (μ : measure α) (r : ℝ≥0) : (r • s).singular_part μ = r • s.singular_part μ := begin rw [singular_part, singular_part, smul_sub, ← to_signed_measure_smul, ← to_signed_measure_smul], conv_lhs { congr, congr, rw [to_jordan_decomposition_smul, jordan_decomposition.smul_pos_part, singular_part_smul], skip, congr, rw [to_jordan_decomposition_smul, jordan_decomposition.smul_neg_part, singular_part_smul] } end lemma singular_part_smul (s : signed_measure α) (μ : measure α) (r : ℝ) : (r • s).singular_part μ = r • s.singular_part μ := begin by_cases hr : 0 ≤ r, { lift r to ℝ≥0 using hr, exact singular_part_smul_nnreal s μ r }, { rw [singular_part, singular_part], conv_lhs { congr, congr, rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_pos_part_neg _ _ (not_le.1 hr), singular_part_smul], skip, congr, rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_neg_part_neg _ _ (not_le.1 hr), singular_part_smul] }, rw [to_signed_measure_smul, to_signed_measure_smul, ← neg_sub, ← smul_sub], change -(((-r).to_nnreal : ℝ) • _) = _, rw [← neg_smul, real.coe_to_nnreal _ (le_of_lt (neg_pos.mpr (not_le.1 hr))), neg_neg] } end lemma singular_part_add (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] : (s + t).singular_part μ = s.singular_part μ + t.singular_part μ := begin refine (eq_singular_part _ (s.rn_deriv μ + t.rn_deriv μ) ((mutually_singular_singular_part s μ).add_left (mutually_singular_singular_part t μ)) _).symm, erw [with_densityᵥ_add (integrable_rn_deriv s μ) (integrable_rn_deriv t μ)], rw [add_assoc, add_comm (t.singular_part μ), add_assoc, add_comm _ (t.singular_part μ), singular_part_add_with_density_rn_deriv_eq, ← add_assoc, singular_part_add_with_density_rn_deriv_eq], end lemma singular_part_sub (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] : (s - t).singular_part μ = s.singular_part μ - t.singular_part μ := by { rw [sub_eq_add_neg, sub_eq_add_neg, singular_part_add, singular_part_neg] } /-- Given a measure `μ`, signed measures `s` and `t`, and a function `f` such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`, we have `f = rn_deriv s μ`, i.e. `f` is the Radon-Nikodym derivative of `s` and `μ`. -/ theorem eq_rn_deriv (t : signed_measure α) (f : α → ℝ) (hfi : integrable f μ) (htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : f =ᵐ[μ] s.rn_deriv μ := begin set f' := hfi.1.mk f, have hadd' : s = t + μ.with_densityᵥ f', { convert hadd using 2, exact with_densityᵥ_eq.congr_ae hfi.1.ae_eq_mk.symm }, haveI := have_lebesgue_decomposition_mk μ hfi.1.measurable_mk htμ hadd', refine (integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) hfi _).symm, rw [← add_right_inj t, ← hadd, eq_singular_part _ f htμ hadd, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_neg (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] : (-s).rn_deriv μ =ᵐ[μ] - s.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) (integrable_rn_deriv _ _).neg _, rw [with_densityᵥ_neg, ← add_right_inj ((-s).singular_part μ), singular_part_add_with_density_rn_deriv_eq, singular_part_neg, ← neg_add, singular_part_add_with_density_rn_deriv_eq] end lemma rn_deriv_smul (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ) : (r • s).rn_deriv μ =ᵐ[μ] r • s.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) ((integrable_rn_deriv _ _).smul r) _, change _ = μ.with_densityᵥ ((r : ℝ) • s.rn_deriv μ), rw [with_densityᵥ_smul (rn_deriv s μ) (r : ℝ), ← add_right_inj ((r • s).singular_part μ), singular_part_add_with_density_rn_deriv_eq, singular_part_smul], change _ = _ + r • _, rw [← smul_add, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_add (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] [(s + t).have_lebesgue_decomposition μ] : (s + t).rn_deriv μ =ᵐ[μ] s.rn_deriv μ + t.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) ((integrable_rn_deriv _ _).add (integrable_rn_deriv _ _)) _, rw [← add_right_inj ((s + t).singular_part μ), singular_part_add_with_density_rn_deriv_eq, with_densityᵥ_add (integrable_rn_deriv _ _) (integrable_rn_deriv _ _), singular_part_add, add_assoc, add_comm (t.singular_part μ), add_assoc, add_comm _ (t.singular_part μ), singular_part_add_with_density_rn_deriv_eq, ← add_assoc, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_sub (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] [hst : (s - t).have_lebesgue_decomposition μ] : (s - t).rn_deriv μ =ᵐ[μ] s.rn_deriv μ - t.rn_deriv μ := begin rw sub_eq_add_neg at hst, rw [sub_eq_add_neg, sub_eq_add_neg], exactI ae_eq_trans (rn_deriv_add _ _ _) (filter.eventually_eq.add (ae_eq_refl _) (rn_deriv_neg _ _)), end end signed_measure namespace complex_measure /-- A complex measure is said to `have_lebesgue_decomposition` with respect to a positive measure if both its real and imaginary part `have_lebesgue_decomposition` with respect to that measure. -/ class have_lebesgue_decomposition (c : complex_measure α) (μ : measure α) : Prop := (re_part : c.re.have_lebesgue_decomposition μ) (im_part : c.im.have_lebesgue_decomposition μ) attribute [instance] have_lebesgue_decomposition.re_part attribute [instance] have_lebesgue_decomposition.im_part /-- The singular part between a complex measure `c` and a positive measure `μ` is the complex measure satisfying `c.singular_part μ + μ.with_densityᵥ (c.rn_deriv μ) = c`. This property is given by `measure_theory.complex_measure.singular_part_add_with_density_rn_deriv_eq`. -/ def singular_part (c : complex_measure α) (μ : measure α) : complex_measure α := (c.re.singular_part μ).to_complex_measure (c.im.singular_part μ) /-- The Radon-Nikodym derivative between a complex measure and a positive measure. -/ def rn_deriv (c : complex_measure α) (μ : measure α) : α → ℂ := λ x, ⟨c.re.rn_deriv μ x, c.im.rn_deriv μ x⟩ variable {c : complex_measure α} lemma integrable_rn_deriv (c : complex_measure α) (μ : measure α) : integrable (c.rn_deriv μ) μ := begin rw [← mem_ℒp_one_iff_integrable, ← mem_ℒp_re_im_iff], exact ⟨mem_ℒp_one_iff_integrable.2 (signed_measure.integrable_rn_deriv _ _), mem_ℒp_one_iff_integrable.2 (signed_measure.integrable_rn_deriv _ _)⟩ end theorem singular_part_add_with_density_rn_deriv_eq [c.have_lebesgue_decomposition μ] : c.singular_part μ + μ.with_densityᵥ (c.rn_deriv μ) = c := begin conv_rhs { rw [← c.to_complex_measure_to_signed_measure] }, ext i hi : 1, rw [vector_measure.add_apply, signed_measure.to_complex_measure_apply], ext, { rw [complex.add_re, with_densityᵥ_apply (c.integrable_rn_deriv μ) hi, ←is_R_or_C.re_eq_complex_re, ←integral_re (c.integrable_rn_deriv μ).integrable_on, is_R_or_C.re_eq_complex_re, ← with_densityᵥ_apply _ hi], { change (c.re.singular_part μ + μ.with_densityᵥ (c.re.rn_deriv μ)) i = _, rw c.re.singular_part_add_with_density_rn_deriv_eq μ }, { exact (signed_measure.integrable_rn_deriv _ _) } }, { rw [complex.add_im, with_densityᵥ_apply (c.integrable_rn_deriv μ) hi, ←is_R_or_C.im_eq_complex_im, ←integral_im (c.integrable_rn_deriv μ).integrable_on, is_R_or_C.im_eq_complex_im, ← with_densityᵥ_apply _ hi], { change (c.im.singular_part μ + μ.with_densityᵥ (c.im.rn_deriv μ)) i = _, rw c.im.singular_part_add_with_density_rn_deriv_eq μ }, { exact (signed_measure.integrable_rn_deriv _ _) } }, end end complex_measure end measure_theory
b49814c87a6d7cdddf00f067928cddf4f05ed49e
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/monoidal/of_has_finite_products.lean
a9b349549d152268f1cd94eeb53bdc1432b3ebac
[ "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
4,490
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Simon Hudon -/ import category_theory.monoidal.category import category_theory.limits.shapes.binary_products import category_theory.limits.types /-! # The natural monoidal structure on any category with finite (co)products. A category with a monoidal structure provided in this way is sometimes called a (co)cartesian category, although this is also sometimes used to mean a finitely complete category. (See <https://ncatlab.org/nlab/show/cartesian+category>.) As this works with either products or coproducts, and sometimes we want to think of a different monoidal structure entirely, we don't set up either construct as an instance. ## Implementation For the sake of nicer definitional properties, we rely on `has_terminal` and `has_binary_products` instead of `has_finite_products`, so that if a particular category provides customised instances of these we pick those up instead. -/ universes v u namespace category_theory open category_theory.limits variables (C : Type u) [category.{v} C] section local attribute [tidy] tactic.case_bash /-- A category with a terminal object and binary products has a natural monoidal structure. -/ def monoidal_of_has_finite_products [has_terminal.{v} C] [has_binary_products.{v} C] : monoidal_category C := { tensor_unit := ⊤_ C, tensor_obj := λ X Y, X ⨯ Y, tensor_hom := λ _ _ _ _ f g, limits.prod.map f g, associator := prod.associator, left_unitor := prod.left_unitor, right_unitor := prod.right_unitor, pentagon' := prod.pentagon, triangle' := prod.triangle, associator_naturality' := @prod.associator_naturality _ _ _, } end namespace monoidal_of_has_finite_products variables [has_terminal.{v} C] [has_binary_products.{v} C] local attribute [instance] monoidal_of_has_finite_products @[simp] lemma left_unitor_hom (X : C) : (λ_ X).hom = limits.prod.snd := rfl @[simp] lemma left_unitor_inv (X : C) : (λ_ X).inv = prod.lift (terminal.from X) (𝟙 _) := rfl @[simp] lemma right_unitor_hom (X : C) : (ρ_ X).hom = limits.prod.fst := rfl @[simp] lemma right_unitor_inv (X : C) : (ρ_ X).inv = prod.lift (𝟙 _) (terminal.from X) := rfl -- We don't mark this as a simp lemma, even though in many particular -- categories the right hand side will simplify significantly further. -- For now, we'll plan to create specialised simp lemmas in each particular category. lemma associator_hom (X Y Z : C) : (α_ X Y Z).hom = prod.lift (limits.prod.fst ≫ limits.prod.fst) (prod.lift (limits.prod.fst ≫ limits.prod.snd) limits.prod.snd) := rfl end monoidal_of_has_finite_products section local attribute [tidy] tactic.case_bash /-- A category with an initial object and binary coproducts has a natural monoidal structure. -/ def monoidal_of_has_finite_coproducts [has_initial.{v} C] [has_binary_coproducts.{v} C] : monoidal_category C := { tensor_unit := ⊥_ C, tensor_obj := λ X Y, X ⨿ Y, tensor_hom := λ _ _ _ _ f g, limits.coprod.map f g, associator := coprod.associator, left_unitor := coprod.left_unitor, right_unitor := coprod.right_unitor, pentagon' := coprod.pentagon, triangle' := coprod.triangle, associator_naturality' := @coprod.associator_naturality _ _ _, } end namespace monoidal_of_has_finite_coproducts variables [has_initial.{v} C] [has_binary_coproducts.{v} C] local attribute [instance] monoidal_of_has_finite_coproducts @[simp] lemma left_unitor_hom (X : C) : (λ_ X).hom = coprod.desc (initial.to X) (𝟙 _) := rfl @[simp] lemma right_unitor_hom (X : C) : (ρ_ X).hom = coprod.desc (𝟙 _) (initial.to X) := rfl @[simp] lemma left_unitor_inv (X : C) : (λ_ X).inv = limits.coprod.inr := rfl @[simp] lemma right_unitor_inv (X : C) : (ρ_ X).inv = limits.coprod.inl := rfl -- We don't mark this as a simp lemma, even though in many particular -- categories the right hand side will simplify significantly further. -- For now, we'll plan to create specialised simp lemmas in each particular category. lemma associator_hom (X Y Z : C) : (α_ X Y Z).hom = coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr) := rfl end monoidal_of_has_finite_coproducts end category_theory -- TODO in fact, a category with finite products is braided, and symmetric, -- and we should say that here, once braided categories arrive in mathlib.
85218c5767456eaafb71f80cf654704a5427a088
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/complete_lattice.lean
8c07ab547779d3989a233ad36d2598da4806d67c
[ "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
56,566
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.bool.set import data.nat.basic import order.bounds /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we also use `bsupr`/`binfi` for "bounded" supremum or infimum, i.e. one of `⨆ i ∈ s, f i`, `⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set function variables {α β β₂ : Type*} {ι ι₂ : Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ /-- Note that we rarely use `complete_semilattice_Sup` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ @[ancestor partial_order has_Sup] class complete_semilattice_Sup (α : Type*) extends partial_order α, has_Sup α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) section variables [complete_semilattice_Sup α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_semilattice_Sup.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_semilattice_Sup.Sup_le s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_Sup s) lemma le_Sup_iff : a ≤ Sup s ↔ (∀ b ∈ upper_bounds s, a ≤ b) := ⟨λ h b hb, le_trans h (Sup_le hb), λ hb, hb _ (λ x, le_Sup)⟩ theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_Sup_iff.2 $ λ b hb, Sup_le $ λ a ha, let ⟨c, hct, hac⟩ := h a ha in hac.trans (hb hct) -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq end /-- Note that we rarely use `complete_semilattice_Inf` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ @[ancestor partial_order has_Inf] class complete_semilattice_Inf (α : Type*) extends partial_order α, has_Inf α := (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) section variables [complete_semilattice_Inf α] {s t : set α} {a b : α} @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_semilattice_Inf.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_semilattice_Inf.le_Inf s a lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_Inf s) lemma Inf_le_iff : Inf s ≤ a ↔ (∀ b, (∀ x ∈ s, b ≤ x) → b ≤ a) := ⟨λ h b hb, le_trans (le_Inf hb) h, λ hb, hb _ (λ x, Inf_le)⟩ theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le begin simp only [le_Inf_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y,hy,hy'⟩, solve_by_elim [le_trans _ hy'] end -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq end /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ @[protect_proj, ancestor lattice complete_semilattice_Sup complete_semilattice_Inf has_top has_bot] class complete_lattice (α : Type*) extends lattice α, complete_semilattice_Sup α, complete_semilattice_Inf α, has_top α, has_bot α := (le_top : ∀ x : α, x ≤ ⊤) (bot_le : ∀ x : α, ⊥ ≤ x) @[priority 100] -- see Note [lower instance priority] instance complete_lattice.to_bounded_order [h : complete_lattice α] : bounded_order α := { ..h } /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Sup, bot, top ..complete_lattice_of_Inf my_T _ } ``` -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Inf` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Inf`. -/ def complete_lattice_of_complete_semilattice_Inf (α : Type*) [complete_semilattice_Inf α] : complete_lattice α := complete_lattice_of_Inf α (λ s, is_glb_Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Inf, bot, top ..complete_lattice_of_Sup my_T _ } ``` -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Sup` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Sup`. -/ def complete_lattice_of_complete_semilattice_Sup (α : Type*) [complete_semilattice_Sup α] : complete_lattice α := complete_lattice_of_Sup α (λ s, is_lub_Sup s) /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α renaming max → sup min → inf namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice (order_dual α) := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α, .. order_dual.bounded_order α } instance [complete_linear_order α] : complete_linear_order (order_dual α) := { .. order_dual.complete_lattice α, .. order_dual.linear_order α } end order_dual section variables [complete_lattice α] {s t : set α} {a b : α} theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := Sup_le $ λ b hb, le_inf (le_Sup hb.1) (le_Sup hb.2) /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @Sup_inter_le (order_dual α) _ _ _ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := (@is_lub_empty α _ _).Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _ _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _ _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := (@is_glb_univ α _ _).Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq theorem Sup_le_Sup_of_subset_insert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t := le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq)) theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s := le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h) theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := iff.intro (assume h a ha, top_unique $ h ▸ Inf_le ha) (assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha) lemma eq_singleton_top_of_Inf_eq_top_of_nonempty {s : set α} (h_inf : Inf s = ⊤) (hne : s.nonempty) : s = {⊤} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Inf_eq_top at h_inf, exact ⟨hne, h_inf⟩, } @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := @Inf_eq_top (order_dual α) _ _ lemma eq_singleton_bot_of_Sup_eq_bot_of_nonempty {s : set α} (h_sup : Sup s = ⊥) (hne : s.nonempty) : s = {⊥} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Sup_eq_bot at h_sup, exact ⟨hne, h_sup⟩, } /--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b` is larger than all elements of `s`, and that this is not the case of any `w < b`. See `cSup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem Sup_eq_of_forall_le_of_forall_lt_exists_gt (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have h : (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (Sup_le ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_Sup ‹a ∈ s›), show false, from lt_irrefl _ this, show Sup s = b, from or.resolve_left h this /--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b` is smaller than all elements of `s`, and that this is not the case of any `w > b`. See `cInf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem Inf_eq_of_forall_ge_of_forall_gt_exists_lt (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := @Sup_eq_of_forall_le_of_forall_lt_exists_gt (order_dual α) _ _ ‹_› ‹_› ‹_› end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := is_glb_lt_iff (is_glb_Inf s) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := lt_is_lub_iff (is_lub_Sup s) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) := @Sup_eq_top (order_dual α) _ _ lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- ### supr & infi -/ section variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _ lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _ lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) : f i hi ≤ ⨆ i hi, f i hi := le_supr_of_le i $ le_supr (f i) hi theorem le_bsupr_of_le {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) (h : a ≤ f i hi) : a ≤ ⨆ i hi, f i hi := le_trans h (le_bsupr i hi) theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) : (⨆ i (hi : p i), f i hi) ≤ a := supr_le $ λ i, supr_le $ h i theorem bsupr_le_supr (p : ι → Prop) (f : ι → α) : (⨆ i (H : p i), f i) ≤ ⨆ i, f i := bsupr_le (λ i hi, le_supr f i) theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi := bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi) theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h theorem bsupr_le_bsupr' {p q : ι → Prop} (hpq : ∀ i, p i → q i) {f : ι → α} : (⨆ i (hpi : p i), f i) ≤ ⨆ i (hqi : q i), f i := supr_le_supr $ λ i, supr_le_supr_const (hpq i) @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := (is_lub_le_iff is_lub_supr).trans forall_range_iff theorem supr_lt_iff : supr s < a ↔ ∃ b < a, ∀ i, s i ≤ b := ⟨λ h, ⟨supr s, h, λ i, le_supr s i⟩, λ ⟨b, hba, hsb⟩, (supr_le hsb).trans_lt hba⟩ theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma Sup_eq_supr' {α} [has_Sup α] (s : set α) : Sup s = ⨆ x : s, (x : α) := by rw [supr, subtype.range_coe] lemma Sup_sUnion {s : set (set α)} : Sup (⋃₀ s) = ⨆ (t ∈ s), Sup t := begin apply le_antisymm, { apply Sup_le (λ b hb, _), rcases hb with ⟨t, ts, bt⟩, apply le_trans _ (le_supr _ t), exact le_trans (le_Sup bt) (le_supr _ ts), }, { apply supr_le (λ t, _), exact supr_le (λ ts, Sup_le_Sup (λ x xt, ⟨t, ts, xt⟩)) } end lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : (⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) := calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) : supr_le_supr $ λ i, hf.le_map_supr ... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆a∈s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr2 _ lemma order_iso.map_supr [complete_lattice β] (f : α ≃o β) (x : ι → α) : f (⨆ i, x i) = ⨆ i, f (x i) := eq_of_forall_ge_iff $ f.surjective.forall.2 $ λ x, by simp only [f.le_iff_le, supr_le_iff] lemma order_iso.map_Sup [complete_lattice β] (f : α ≃o β) (s : set α) : f (Sup s) = ⨆ a ∈ s, f a := by simp only [Sup_eq_supr, order_iso.map_supr] lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_le_supr2 $ λ x, ⟨_, le_rfl⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi) lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂} (hf : surjective f) (g : ι₂ → α) : (⨆ x, g (f x)) = ⨆ y, g y := by simp only [supr, hf.range_comp] lemma supr_congr {α : Type*} [has_Sup α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { convert h1.supr_comp g, exact (funext h2).symm } -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin have := propext pq, subst this, congr' with x, apply f end theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) : (⨅ i hi, f i hi) ≤ f i hi := infi_le_of_le i $ infi_le (f i) hi theorem binfi_le_of_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) (h : f i hi ≤ a) : (⨅ i hi, f i hi) ≤ a := le_trans (binfi_le i hi) h theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) : a ≤ ⨅ i hi, f i hi := le_infi $ λ i, le_infi $ h i theorem infi_le_binfi (p : ι → Prop) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (H : p i), f i := le_binfi (λ i hi, infi_le f i) theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi := le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi) theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := @Sup_eq_supr (order_dual α) _ _ theorem Inf_eq_infi' {α} [has_Inf α] (s : set α) : Inf s = ⨅ a : s, a := @Sup_eq_supr' (order_dual α) _ _ lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) : f (infi s) ≤ (⨅ i, f (s i)) := le_infi $ λ i, hf $ infi_le _ _ lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) := @monotone.le_map_supr2 (order_dual α) (order_dual β) _ _ _ f hf.dual _ _ lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a∈s, f a := by rw [Inf_eq_infi]; exact hf.map_infi2_le _ lemma order_iso.map_infi [complete_lattice β] (f : α ≃o β) (x : ι → α) : f (⨅ i, x i) = ⨅ i, f (x i) := order_iso.map_supr f.dual _ lemma order_iso.map_Inf [complete_lattice β] (f : α ≃o β) (s : set α) : f (Inf s) = ⨅ a ∈ s, f a := order_iso.map_Sup f.dual _ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_le_infi2 $ λ x, ⟨_, le_rfl⟩ lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂} (hf : surjective f) (g : ι₂ → α) : (⨅ x, g (f x)) = ⨅ y, g y := @function.surjective.supr_comp _ _ (order_dual α) _ f hf g lemma infi_congr {α : Type*} [has_Inf α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := @supr_congr _ _ (order_dual α) _ _ _ h h1 h2 @[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := @supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f lemma supr_const_le {x : α} : (⨆ (h : ι), x) ≤ x := supr_le (λ _, le_rfl) lemma le_infi_const {x : α} : x ≤ (⨅ (h : ι), x) := le_infi (λ _, le_rfl) -- We will generalize this to conditionally complete lattices in `cinfi_const`. theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, Inf_singleton] -- We will generalize this to conditionally complete lattices in `csupr_const`. theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := @infi_const (order_dual α) _ _ _ _ @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_rfl @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := @infi_top (order_dual α) _ _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := Inf_eq_top.trans forall_range_iff @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := Sup_eq_bot.trans forall_range_iff @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_rfl) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_rfl) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le /--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b` is larger than `f i` for all `i`, and that this is not the case of any `w<b`. See `csupr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem supr_eq_of_forall_le_of_forall_lt_exists_gt {f : ι → α} (h₁ : ∀ i, f i ≤ b) (h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b := Sup_eq_of_forall_le_of_forall_lt_exists_gt (forall_range_iff.mpr h₁) (λ w hw, exists_range_iff.mpr $ h₂ w hw) /--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b` is smaller than `f i` for all `i`, and that this is not the case of any `w>b`. See `cinfi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem infi_eq_of_forall_ge_of_forall_gt_exists_lt {f : ι → α} (h₁ : ∀ i, b ≤ f i) (h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b := @supr_eq_of_forall_le_of_forall_lt_exists_gt (order_dual α) _ _ _ ‹_› ‹_› ‹_› lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆h:p, a h) = (if h : p then a h else ⊥) := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆h:p, a) = (if p then a else ⊥) := supr_eq_dif (λ _, a) lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅h:p, a h) = (if h : p then a h else ⊤) := @supr_eq_dif (order_dual α) _ _ _ _ lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := infi_eq_dif (λ _, a) -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := @infi_comm (order_dual α) _ _ _ _ @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_rfl end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_rfl end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := @infi_infi_eq_left (order_dual α) _ _ _ _ @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := @infi_infi_eq_right (order_dual α) _ _ _ _ attribute [ematch] le_refl theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_of_left_le $ infi_le _ _) (inf_le_of_right_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := by rw [infi_inf_eq, infi_const] lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf]; simp [inf_comm] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩); rw [infi_subtype', infi_subtype', infi_inf] lemma inf_binfi {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : a ⊓ (⨅i (h : p i), f i h) = (⨅ i (h : p i), a ⊓ f i h) := by simpa only [inf_comm] using binfi_inf h theorem supr_sup_eq {f g : ι → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := @infi_inf_eq (order_dual α) ι _ _ _ lemma supr_sup [h : nonempty ι] {f : ι → α} {a : α} : (⨆ x, f x) ⊔ a = (⨆ x, f x ⊔ a) := @infi_inf (order_dual α) _ _ _ _ _ lemma sup_supr [nonempty ι] {f : ι → α} {a : α} : a ⊔ (⨆ x, f x) = (⨆ x, a ⊔ f x) := @inf_infi (order_dual α) _ _ _ _ _ /-! ### `supr` and `infi` under `Prop` -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le theorem infi_true {s : true → α} : infi s = s trivial := infi_pos trivial theorem supr_true {s : true → α} : supr s = s trivial := supr_pos trivial @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := @infi_exists (order_dual α) _ _ _ _ theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact infi_and } theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := @infi_and (order_dual α) _ _ _ _ /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact supr_and } theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_rfl⟩) (infi_le_infi2 $ assume j, ⟨_, le_rfl⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_of_left_le $ infi_le _ _ | or.inr j := inf_le_of_right_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := @infi_or (order_dual α) _ _ _ _ section variables (p : ι → Prop) [decidable_pred p] lemma supr_dite (f : Π i, p i → α) (g : Π i, ¬p i → α) : (⨆ i, if h : p i then f i h else g i h) = (⨆ i (h : p i), f i h) ⊔ (⨆ i (h : ¬ p i), g i h) := begin rw ←supr_sup_eq, congr' 1 with i, split_ifs with h; simp [h], end lemma supr_ite (f g : ι → α) : (⨆ i, if p i then f i else g i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), g i) := supr_dite _ _ _ lemma infi_dite (f : Π i, p i → α) (g : Π i, ¬p i → α) : (⨅ i, if h : p i then f i h else g i h) = (⨅ i (h : p i), f i h) ⊓ (⨅ i (h : ¬ p i), g i h) := supr_dite p (show Π i, p i → order_dual α, from f) g lemma infi_ite (f g : ι → α) : (⨅ i, if p i then f i else g i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), g i) := infi_dite _ _ _ end lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl lemma supr_range' {α} [has_Sup α] (g : β → α) (f : ι → β) : (⨆ b : range f, g b) = ⨆ i, g (f i) := by rw [supr, supr, ← image_eq_range, ← range_comp] lemma infi_range' {α} [has_Inf α] (g : β → α) (f : ι → β) : (⨅ b : range f, g b) = ⨅ i, g (f i) := @supr_range' _ _ (order_dual α) _ _ _ lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := by rw [← infi_subtype'', infi_range'] lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := @infi_range (order_dual α) _ _ _ _ _ theorem Inf_image' {α} [has_Inf α] {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a : s, f a) := by rw [infi, image_eq_range] theorem Sup_image' {α} [has_Sup α] {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a : s, f a) := @Inf_image' _ (order_dual α) _ _ _ theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := by rw [← infi_subtype'', Inf_image'] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := @Inf_image (order_dual α) _ _ _ _ /- ### supr and infi under set constructions -/ theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := by simp theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := by simp only [← infi_inf_eq, infi_or] lemma infi_split (f : β → α) (p : β → Prop) : (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) := by convert infi_split _ _; simp theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := @infi_union (order_dual α) _ _ _ _ _ lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := @infi_split (order_dual α) _ _ _ _ lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) := @infi_split_single (order_dual α) _ _ _ _ theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := @infi_le_infi_of_subset (order_dual α) _ _ _ _ _ h theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := @infi_singleton (order_dual α) _ _ _ _ theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := by rw [← Inf_image, ← Inf_image, ← image_comp] lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := @infi_image (order_dual α) _ _ _ _ _ _ theorem supr_extend_bot {e : ι → β} (he : injective e) (f : ι → α) : (⨆ j, extend e f ⊥ j) = ⨆ i, f i := begin rw supr_split _ (λ j, ∃ i, e i = j), simp [extend_apply he, extend_apply', @supr_comm _ β ι] { contextual := tt } end /-! ### `supr` and `infi` under `Type` -/ theorem supr_of_empty' {α ι} [has_Sup α] [is_empty ι] (f : ι → α) : supr f = Sup (∅ : set α) := congr_arg Sup (range_eq_empty f) theorem supr_of_empty [is_empty ι] (f : ι → α) : supr f = ⊥ := (supr_of_empty' f).trans Sup_empty theorem infi_of_empty' {α ι} [has_Inf α] [is_empty ι] (f : ι → α) : infi f = Inf (∅ : set α) := congr_arg Inf (range_eq_empty f) theorem infi_of_empty [is_empty ι] (f : ι → α) : infi f = ⊤ := @supr_of_empty (order_dual α) _ _ _ f lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := by rw [supr, bool.range_eq, Sup_pair, sup_comm] lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq (order_dual α) _ _ lemma sup_eq_supr (x y : α) : x ⊔ y = ⨆ b : bool, cond b x y := by rw [supr_bool_eq, bool.cond_tt, bool.cond_ff] lemma inf_eq_infi (x y : α) : x ⊓ y = ⨅ b : bool, cond b x y := @sup_eq_supr (order_dual α) _ _ _ lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_subtype (order_dual α) _ _ _ _ lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma supr_subtype'' {ι} (s : set ι) (f : ι → α) : (⨆ i : s, f i) = ⨆ (t : ι) (H : t ∈ s), f t := supr_subtype lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := eq_of_forall_le_iff $ λ c, by simp only [le_infi_iff, sigma.forall] theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_sigma (order_dual α) _ _ _ _ theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := eq_of_forall_le_iff $ λ c, by simp only [le_infi_iff, prod.forall] theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := @infi_prod (order_dual α) _ _ _ _ theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff, le_infi_iff, sum.forall] theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := @infi_sum (order_dual α) _ _ _ _ theorem supr_option (f : option β → α) : (⨆ o, f o) = f none ⊔ ⨆ b, f (option.some b) := eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, sup_le_iff, option.forall] theorem infi_option (f : option β → α) : (⨅ o, f o) = f none ⊓ ⨅ b, f (option.some b) := @supr_option (order_dual α) _ _ _ /-- A version of `supr_option` useful for rewriting right-to-left. -/ lemma supr_option_elim (a : α) (f : β → α) : (⨆ o : option β, o.elim a f) = a ⊔ ⨆ b, f b := by simp [supr_option] /-- A version of `infi_option` useful for rewriting right-to-left. -/ lemma infi_option_elim (a : α) (f : β → α) : (⨅ o : option β, o.elim a f) = a ⊓ ⨅ b, f b := @supr_option_elim (order_dual α) _ _ _ _ /-- When taking the supremum of `f : ι → α`, the elements of `ι` on which `f` gives `⊥` can be dropped, without changing the result. -/ lemma supr_ne_bot_subtype (f : ι → α) : (⨆ i : {i // f i ≠ ⊥}, f i) = ⨆ i, f i := begin by_cases htriv : ∀ i, f i = ⊥, { simp only [htriv, supr_bot] }, refine le_antisymm (supr_comp_le f _) (supr_le_supr2 _), intros i, by_cases hi : f i = ⊥, { rw hi, obtain ⟨i₀, hi₀⟩ := not_forall.mp htriv, exact ⟨⟨i₀, hi₀⟩, bot_le⟩ }, { exact ⟨⟨i, hi⟩, rfl.le⟩ }, end /-- When taking the infimum of `f : ι → α`, the elements of `ι` on which `f` gives `⊤` can be dropped, without changing the result. -/ lemma infi_ne_top_subtype (f : ι → α) : (⨅ i : {i // f i ≠ ⊤}, f i) = ⨅ i, f i := @supr_ne_bot_subtype (order_dual α) ι _ f /-! ### `supr` and `infi` under `ℕ` -/ lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) := begin apply le_antisymm; simp only [supr_le_iff], { exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw tsub_add_cancel_of_le hi }⟩ }, { exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ } end lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) := @supr_ge_eq_supr_nat_add (order_dual α) _ _ _ lemma monotone.supr_nat_add {f : ℕ → α} (hf : monotone f) (k : ℕ) : (⨆ n, f (n + k)) = ⨆ n, f n := le_antisymm (supr_le (λ i, le_rfl.trans (le_supr _ (i + k)))) (supr_le_supr (λ i, hf (nat.le_add_right i k))) @[simp] lemma supr_infi_ge_nat_add (f : ℕ → α) (k : ℕ) : (⨆ n, ⨅ i ≥ n, f (i + k)) = ⨆ n, ⨅ i ≥ n, f i := begin have hf : monotone (λ n, ⨅ i ≥ n, f i), from λ n m hnm, le_infi (λ i, (infi_le _ i).trans (le_infi (λ h, infi_le _ (hnm.trans h)))), rw ←monotone.supr_nat_add hf k, { simp_rw [infi_ge_eq_infi_nat_add, ←nat.add_assoc], }, end lemma sup_supr_nat_succ (u : ℕ → α) : u 0 ⊔ (⨆ i, u (i + 1)) = ⨆ i, u i := begin refine eq_of_forall_ge_iff (λ c, _), simp only [sup_le_iff, supr_le_iff], refine ⟨λ h, _, λ h, ⟨h _, λ i, h _⟩⟩, rintro (_|i), exacts [h.1, h.2 i] end lemma inf_infi_nat_succ (u : ℕ → α) : u 0 ⊓ (⨅ i, u (i + 1)) = ⨅ i, u i := @sup_supr_nat_succ (order_dual α) _ u end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /-! ### Instances -/ instance Prop.complete_lattice : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, .. Prop.bounded_order, .. Prop.distrib_lattice } @[simp] lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl @[simp] lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl @[simp] lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) := le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i) @[simp] lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_order, .. pi.lattice } lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅ f : s, (f : Πa, β a) a) := rfl @[simp] lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f:s, (f : Πa, β a) a) := rfl lemma unary_relation_Sup_iff {α : Type*} (s : set (α → Prop)) {a : α} : Sup s a ↔ ∃ (r : α → Prop), r ∈ s ∧ r a := by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] } lemma binary_relation_Sup_iff {α β : Type*} (s : set (α → β → Prop)) {a : α} {b : β} : Sup s a b ↔ ∃ (r : α → β → Prop), r ∈ s ∧ r a b := by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] } @[simp] lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := @infi_apply α (λ i, order_dual (β i)) _ _ f a section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h end complete_lattice namespace prod variables (α β) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := assume s p h, ⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := assume s p h, ⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, .. prod.lattice α β, .. prod.bounded_order α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod section complete_lattice variables [complete_lattice α] {a : α} {s : set α} /-- This is a weaker version of `sup_Inf_eq` -/ lemma sup_Inf_le_infi_sup : a ⊔ Inf s ≤ (⨅ b ∈ s, a ⊔ b) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_left (Inf_le h) _ /-- This is a weaker version of `Inf_sup_eq` -/ lemma Inf_sup_le_infi_sup : Inf s ⊔ a ≤ (⨅ b ∈ s, b ⊔ a) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_right (Inf_le h) _ /-- This is a weaker version of `inf_Sup_eq` -/ lemma supr_inf_le_inf_Sup : (⨆ b ∈ s, a ⊓ b) ≤ a ⊓ Sup s := supr_le $ assume i, supr_le $ assume h, inf_le_inf_left _ (le_Sup h) /-- This is a weaker version of `Sup_inf_eq` -/ lemma supr_inf_le_Sup_inf : (⨆ b ∈ s, b ⊓ a) ≤ Sup s ⊓ a := supr_le $ assume i, supr_le $ assume h, inf_le_inf_right _ (le_Sup h) lemma disjoint_Sup_left {a : set α} {b : α} (d : disjoint (Sup a) b) {i} (hi : i ∈ a) : disjoint i b := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_Sup_inf.trans (d : _)) i : _) hi : _) lemma disjoint_Sup_right {a : set α} {b : α} (d : disjoint b (Sup a)) {i} (hi : i ∈ a) : disjoint b i := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_inf_Sup.trans (d : _)) i : _) hi : _) end complete_lattice namespace complete_lattice variables [complete_lattice α] /-- An independent set of elements in a complete lattice is one in which every element is disjoint from the `Sup` of the rest. -/ def set_independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a})) variables {s : set α} (hs : set_independent s) @[simp] lemma set_independent_empty : set_independent (∅ : set α) := λ x hx, (set.not_mem_empty x hx).elim theorem set_independent.mono {t : set α} (hst : t ⊆ s) : set_independent t := λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst)) /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma set_independent.disjoint {x y : α} (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : disjoint x y := disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, by simp [h.symm]⟩) include hs /-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some subset of the rest. -/ lemma set_independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) : disjoint x (Sup y) := begin have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _), rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this, exact this, end omit hs /-- An independent indexed family of elements in a complete lattice is one in which every element is disjoint from the `supr` of the rest. Example: an indexed family of non-zero elements in a vector space is linearly independent iff the indexed family of subspaces they generate is independent in this sense. Example: an indexed family of submodules of a module is independent in this sense if and only the natural map from the direct sum of the submodules to the module is injective. -/ def independent {ι : Sort*} {α : Type*} [complete_lattice α] (t : ι → α) : Prop := ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) lemma set_independent_iff {α : Type*} [complete_lattice α] (s : set α) : set_independent s ↔ independent (coe : s → α) := begin simp_rw [independent, set_independent, set_coe.forall, Sup_eq_supr], refine forall₂_congr (λ a ha, _), congr' 2, convert supr_subtype.symm, simp [supr_and], end variables {t : ι → α} (ht : independent t) theorem independent_def : independent t ↔ ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) := iff.rfl theorem independent_def' {ι : Type*} {t : ι → α} : independent t ↔ ∀ i, disjoint (t i) (Sup (t '' {j | j ≠ i})) := by {simp_rw Sup_image, refl} theorem independent_def'' {ι : Type*} {t : ι → α} : independent t ↔ ∀ i, disjoint (t i) (Sup {a | ∃ j ≠ i, t j = a}) := by {rw independent_def', tidy} @[simp] lemma independent_empty (t : empty → α) : independent t. @[simp] lemma independent_pempty (t : pempty → α) : independent t. /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma independent.disjoint {x y : ι} (h : x ≠ y) : disjoint (t x) (t y) := disjoint_Sup_right (ht x) ⟨y, by simp [h.symm]⟩ lemma independent.mono {ι : Type*} {α : Type*} [complete_lattice α] {s t : ι → α} (hs : independent s) (hst : t ≤ s) : independent t := λ i, (hs i).mono (hst i) (supr_le_supr $ λ j, supr_le_supr $ λ _, hst j) /-- Composing an independent indexed family with an injective function on the index results in another indepedendent indexed family. -/ lemma independent.comp {ι ι' : Sort*} {α : Type*} [complete_lattice α] {s : ι → α} (hs : independent s) (f : ι' → ι) (hf : function.injective f) : independent (s ∘ f) := λ i, (hs (f i)).mono_right begin refine (supr_le_supr $ λ i, _).trans (supr_comp_le _ f), exact supr_le_supr_const hf.ne, end /-- Composing an indepedent indexed family with an order isomorphism on the elements results in another indepedendent indexed family. -/ lemma independent.map_order_iso {ι : Sort*} {α β : Type*} [complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} (ha : independent a) : independent (f ∘ a) := λ i, ((ha i).map_order_iso f).mono_right (f.monotone.le_map_supr2 _) @[simp] lemma independent_map_order_iso_iff {ι : Sort*} {α β : Type*} [complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} : independent (f ∘ a) ↔ independent a := ⟨ λ h, have hf : f.symm ∘ f ∘ a = a := congr_arg (∘ a) f.left_inv.comp_eq_id, hf ▸ h.map_order_iso f.symm, λ h, h.map_order_iso f⟩ /-- If the elements of a set are independent, then any element is disjoint from the `supr` of some subset of the rest. -/ lemma independent.disjoint_bsupr {ι : Type*} {α : Type*} [complete_lattice α] {t : ι → α} (ht : independent t) {x : ι} {y : set ι} (hx : x ∉ y) : disjoint (t x) (⨆ i ∈ y, t i) := disjoint.mono_right (bsupr_le_bsupr' $ λ i hi, (ne_of_mem_of_not_mem hi hx : _)) (ht x) end complete_lattice
0a5610f00f6545c9d0ee72a471ef789f4c9642b5
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/analysis/normed_space/indicator_function.lean
eda49b24d8215566391e7b982a5791a7d65910a1
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
1,166
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import data.indicator_function import analysis.normed_space.basic /-! # Indicator function and norm This file contains a few simple lemmas about `set.indicator` and `norm`. ## Tags indicator, norm -/ variables {α E : Type*} [normed_group E] {s t : set α} (f : α → E) (a : α) open set lemma norm_indicator_eq_indicator_norm : ∥indicator s f a∥ = indicator s (λa, ∥f a∥) a := flip congr_fun a (indicator_comp_of_zero norm_zero).symm lemma norm_indicator_le_of_subset (h : s ⊆ t) (f : α → E) (a : α) : ∥indicator s f a∥ ≤ ∥indicator t f a∥ := begin simp only [norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset ‹_› (λ _, norm_nonneg _) _ end lemma indicator_norm_le_norm_self : indicator s (λa, ∥f a∥) a ≤ ∥f a∥ := indicator_le_self' (λ _ _, norm_nonneg _) a lemma norm_indicator_le_norm_self : ∥indicator s f a∥ ≤ ∥f a∥ := by { rw norm_indicator_eq_indicator_norm, apply indicator_norm_le_norm_self }
5fb1b5a05a7d3b7d2653c560223661431a4f15e7
fe84e287c662151bb313504482b218a503b972f3
/src/commutative_algebra/localization.lean
c9caba1e30f9835f93922fcaf8ff729c470740d0
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
15,079
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This is about localization of commutative rings and semirings. The most common approach is to start with a commutative ring `A` and a subset `S` that contains `1` and is closed under multiplication. We then define a set `A[S⁻¹]` of equivalence classes of fractions `a/s` (with `a ∈ A` and `s ∈ S`), and introduce a ring structure on `A[S⁻¹]`, and prove various things about it. In particular, we prove a universal property. In this file, we deviate in various ways from the above approach. Firstly, we work with semirings rather than rings. This wider generality has some applications in stable homotopy theory, for example: given a finite group `G` it is useful to be able to work with the Burnside semiring of isomorphism classes of finite `G`-sets, or the representation semiring of isomorphism classes of finite-dimensional representation, rather than immediately passing to the group completion. Secondly, it is technically convenient to take `S` to be a commutative monoid equipped with a homomorphism `i` from `S` to the multiplicative monoid of `A`, without insisting that `i` is just the inclusion of a submonoid, or even that `i` is injective. For example, when forming `A[a⁻¹]` for a single element `a`, we take `S = ℕ` and `i n = aⁿ`. This does not cause any real issues. Triples `(A,S,i)` of this type play a central role in the theory of log geometry, so we have chosen to call them "prelog semirings". We have bundled the ingredients together as a structure; it is not clear whether this is the best approach. Next, to stay as long as possible in the constructive/ effectively computable world, it is useful to introduce as much structure as possible on the set `A × S` of unreduced fractions, before passing to equivalence classes. All semiring operations can be defined in this context, and most axioms are satisfied, and the remaining axioms fail in a well-controlled way. One thing that is currently missing is as follows. Suppose we have `S` and `i` as before, and a semiring homomorphism `f : A → B`. Suppose that the homomorphism `f ∘ i` lands in invertible elements of `B`, or more constructively, that we have a given homomorphism `j : S → units B` lifting `f ∘ i`. (There are some wrinkles here about the fact that unique existence statements do not give computable witnesses, which is why we need to qualify the above statement.) We then get an induced map `A[S⁻¹] → B`. We would like to have a simple criterion for when this map is an isomorphism, or equivalently when `B` also has the universal property that characterises `A[S⁻¹]`. It is not yet clear what is the best way to formulate this. Ideally, the resulting maps out of `B` should be effectively computable in some natural cases. -/ import algebra.ring group_theory.submonoid ring_theory.ideal.basic linear_algebra.basic import tactic.ring tactic.abel namespace localization_alt universes u v w x structure prelog_semiring := (A : Type u) (S : Type v) (A_comm_semiring : comm_semiring A) (S_comm_monoid : comm_monoid S) (i : S →* A) namespace prelog_semiring open prelog_semiring instance to_comm_semiring (P : prelog_semiring) : comm_semiring P.A := P.A_comm_semiring instance to_comm_monoid_S (P : prelog_semiring) : comm_monoid P.S := P.S_comm_monoid instance to_comm_monoid_A (P : prelog_semiring) : comm_monoid P.A := @comm_semiring.to_comm_monoid P.A P.A_comm_semiring instance to_monoid_S (P : prelog_semiring) : monoid P.S := @comm_monoid.to_monoid P.S (@prelog_semiring.to_comm_monoid_S P) instance to_monoid_A (P : prelog_semiring) : monoid P.A := @comm_monoid.to_monoid P.A (@prelog_semiring.to_comm_monoid_A P) structure preloc (P : prelog_semiring) := (numer : P.A) (denom : P.S) namespace preloc open preloc variable {P : prelog_semiring} notation a `/₀` s := preloc.mk a s @[ext] lemma ext : ∀ (a₁ a₂ : P.A) (s₁ s₂ : P.S), a₁ = a₂ → s₁ = s₂ → (a₁ /₀ s₁) = (a₂ /₀ s₂) := by { intros; congr; assumption } lemma ext' : ∀ {x₁ x₂ : preloc P}, x₁ = x₂ ↔ (x₁.numer = x₂.numer) ∧ (x₁.denom = x₂.denom) | ⟨_,_⟩ ⟨_,_⟩ := by { simp } instance : comm_monoid (preloc P) := begin let one : (preloc P) := (1 /₀ 1), let mul : (preloc P) → (preloc P) → (preloc P) := λ x y, ((x.numer * y.numer) /₀ (x.denom * y.denom)), let one_mul : ∀ (x : preloc P), mul one x = x := begin intro x,cases x with a s, exact congr (congr_arg preloc.mk (one_mul a)) (one_mul s), end, let mul_one : ∀ (x : preloc P), mul x one = x := begin intro x,cases x with a s, exact congr (congr_arg preloc.mk (mul_one a)) (mul_one s), end, let mul_comm : ∀ x y, mul x y = mul y x := begin intros x y,cases x with a s,cases y with b t, exact @congr P.S (preloc P) _ _ _ _ (congr_arg (@preloc.mk P) (mul_comm a b)) (mul_comm s t), end, let mul_assoc : ∀ x y z, mul (mul x y) z = mul x (mul y z) := begin intros x y z,cases x with a s, cases y with b t, cases z with c u, exact @congr P.S (preloc P) _ _ _ _ (congr_arg (@preloc.mk P) (mul_assoc a b c)) (mul_assoc s t u), end, exact { one := one, mul := mul, mul_one := mul_one, one_mul := one_mul, mul_comm := mul_comm, mul_assoc := mul_assoc } end instance : add_comm_monoid (preloc P) := begin let zero : (preloc P) := (0 /₀ 1), let add : (preloc P) → (preloc P) → (preloc P) := λ x y, ((x.numer * (P.i y.denom) + (P.i x.denom) * y.numer) /₀ (x.denom * y.denom)), let zero_add : ∀ (x : preloc P), add zero x = x := begin intro x,cases x with a s, let h0 := (congr_fun (congr_arg P.A_comm_semiring.mul P.i.map_one) a), let h1 := congr (congr_arg P.A_comm_semiring.add (zero_mul (P.i s))) h0, let h2 := h1.trans ((zero_add (1 * a)).trans (one_mul a)), exact congr (congr_arg preloc.mk h2) (one_mul s), end, let add_zero : ∀ (x : preloc P), add x zero = x := begin intro x,cases x with a s, dsimp[zero,add], let h0 := (congr_arg ((*) a) P.i.map_one).trans (mul_one a), let h1 := (congr (congr_arg (+) h0) (mul_zero (P.i s))).trans (add_zero a), exact congr (congr_arg preloc.mk h1) (mul_one s), end, let add_comm : ∀ x y, add x y = add y x := begin intros x y,cases x with a s,cases y with b t, dsimp[add], rw[mul_comm s t,mul_comm a (P.i t),mul_comm (P.i s) b,add_comm], end, let add_assoc : ∀ x y z, add (add x y) z = add x (add y z) := begin intros x y z,cases x with a s, cases y with b t, cases z with c u, dsimp[add], rw[P.i.map_mul,P.i.map_mul,add_mul,mul_add], rw[add_assoc,mul_assoc s t u,mul_assoc a (P.i t) (P.i u), mul_assoc (P.i s) b (P.i u),mul_assoc (P.i s) (P.i t) c], end, exact { zero := zero, add := add, add_zero := add_zero, zero_add := zero_add, add_comm := add_comm, add_assoc := add_assoc }, end lemma numer_def (a : P.A) (s : P.S) : (a /₀ s).numer = a := rfl lemma denom_def (a : P.A) (s : P.S) : (a /₀ s).denom = s := rfl lemma numer_zero : @preloc.numer P 0 = 0 := rfl lemma denom_zero : @preloc.denom P 0 = 1 := rfl lemma numer_one : @preloc.numer P 1 = 1 := rfl lemma denom_one : @preloc.denom P 1 = 1 := rfl lemma one_def : (1 : preloc P) = (1 /₀ 1) := rfl lemma mul_def (x y : preloc P) : x * y = ((x.numer * y.numer) /₀ (x.denom * y.denom)) := rfl lemma mul_def' (a b : P.A) (s t : P.S) : (a /₀ s) * (b /₀ t) = ((a * b) /₀ (s * t)) := rfl lemma zero_def : (0 : preloc P) = (0 /₀ 1) := rfl lemma add_def (x y : preloc P) : x + y = (((x.numer * (P.i y.denom) + (P.i x.denom) * y.numer):P.A) /₀ (x.denom * y.denom)) := rfl lemma add_def' (a b : P.A) (s t : P.S) : (a /₀ s) + (b /₀ t) = (((a * (P.i t) + (P.i s) * b)) /₀ (s * t)) := rfl def η₀ (a : P.A) : preloc P := a /₀ 1 lemma numer_eta (a : P.A) : (η₀ a).numer = a := rfl lemma denom_eta (a : P.A) : (η₀ a).denom = 1 := rfl lemma eta_map_zero : @η₀ P 0 = 0 := rfl lemma eta_map_one : @η₀ P 1 = 1 := rfl lemma eta_map_mul (a b : P.A) : η₀ (a * b) = (η₀ a) * (η₀ b) := begin ext, rw[numer_eta,numer_eta], rw[denom_eta,denom_eta,mul_one] end lemma eta_map_add (a b : P.A) : η₀ (a + b) = (η₀ a) + (η₀ b) := begin ext, rw[numer_eta,numer_eta,denom_eta,denom_eta, P.i.map_one,mul_one,one_mul], rw[denom_eta,denom_eta,mul_one], end structure R (x x' : preloc P) := (s : P.S) (e : P.i (s * x'.denom) * x.numer = P.i (s * x.denom) * x'.numer) def R_refl (x : preloc P) : R x x := {s := 1, e := rfl} def R_symm {x x' : preloc P} (m : R x x') : R x' x := {s := m.s, e := m.e.symm} def R_trans {x x' x'' : preloc P} (m : R x x') (n : R x' x'') : R x x'' := begin rcases x with ⟨a,u⟩, rcases x' with ⟨a',u'⟩, rcases x'' with ⟨a'',u''⟩, let ss := m.s * n.s * u', let ee := calc P.i (ss * u'') * a = P.i (n.s * u'') * (P.i (m.s * u') * a) : by {repeat {rw[P.i.map_mul]}, ring,} ... = P.i (n.s * u'') * (P.i (m.s * u) * a') : by rw[m.e] ... = P.i (m.s * u) * (P.i (n.s * u'') * a') : by ring ... = P.i (m.s * u) * (P.i (n.s * u') * a'') : by rw[n.e] ... = P.i (ss * u) * a'' : by {repeat {rw[P.i.map_mul]}, ring,}, exact { s := ss, e := ee } end def R_zero : (R 0 0) := R_refl (0 : preloc P) def R_one : (R 1 1) := R_refl (1 : preloc P) def R_add {x y x' y' : preloc P} (m : R x x') (n : R y y') : R (x + y) (x' + y') := begin rcases x with ⟨a,u⟩, rcases x' with ⟨a',u'⟩, rcases y with ⟨b,v⟩, rcases y' with ⟨b',v'⟩, let ss := m.s * n.s, let ee := calc (P.i (ss * (u' * v'))) * (a * (P.i v) + (P.i u) * b) = P.i (n.s * v * v') * (P.i (m.s * u') * a) + P.i (m.s * u * u') * (P.i (n.s * v') * b) : by {repeat {rw[P.i.map_mul]}, ring,} ... = P.i (n.s * v * v') * (P.i (m.s * u) * a') + P.i (m.s * u * u') * (P.i (n.s * v) * b') : by rw[m.e,n.e] ... = (P.i (ss * (u * v))) * (a' * (P.i v') + (P.i u') * b') : by {repeat {rw[P.i.map_mul]}, ring,}, exact { s := ss, e := ee }, end def R_mul {x y x' y' : preloc P} (m : R x x') (n : R y y') : R (x * y) (x' * y') := begin rcases x with ⟨a,u⟩, rcases x' with ⟨a',u'⟩, rcases y with ⟨b,v⟩, rcases y' with ⟨b',v'⟩, let ss := m.s * n.s, let ee := calc (P.i (ss * (u' * v'))) * (a * b) = (P.i (m.s * u') * a) * (P.i (n.s * v') * b) : by {repeat {rw[P.i.map_mul]}, ring,} ... = (P.i (m.s * u) * a') * (P.i (n.s * v) * b') : by rw[m.e,n.e] ... = (P.i (ss * (u * v))) * (a' * b') : by {repeat {rw[P.i.map_mul]}, ring,}, exact { s := ss, e := ee }, end def R_zero_mul : ∀ (x : preloc P), R (0 * x) 0 | ⟨a,u⟩ := {s := 1,e := begin show (P.i (1 * 1)) * (0 * a) = (P.i (1 * (1 * u))) * 0, rw[_root_.zero_mul,_root_.mul_zero,_root_.mul_zero], end} def R_mul_zero : ∀ (x : preloc P), R (x * 0) 0 | ⟨a,u⟩ := {s := 1,e := begin show (P.i (1 * 1)) * (a * 0) = (P.i (1 * (u * 1))) * 0, repeat {rw[_root_.mul_zero]}, end} def R_mul_add (x y z : preloc P) : R (x * (y + z)) (x * y + x * z) := begin rcases x with ⟨a,u⟩, rcases y with ⟨b,v⟩, rcases z with ⟨c,w⟩, have e : (P.i (1 * ((u * v) * (u * w)))) * (a * (b * (P.i w) + (P.i v) * c)) = (P.i (1 * (u * (v *w)))) * ((a * b) * P.i (u * w) + P.i (u * v) * (a * c)) := by {repeat {rw[P.i.map_mul]}, ring,}, exact {s := 1, e := e}, end def R_add_mul (x y z : preloc P) : R ((x + y) * z) (x * z + y * z) := begin rcases x with ⟨a,u⟩, rcases y with ⟨b,v⟩, rcases z with ⟨c,w⟩, have e : (P.i (1 * ((u * w) * (v * w)))) * ((a * (P.i v) + (P.i u) * b) * c) = (P.i (1 * (u * v *w))) * ((a * c) * P.i (v * w) + P.i (u * w) * (b * c)) := by {repeat {rw[P.i.map_mul]}, ring,}, exact {s := 1, e := e}, end variable (P) instance loc_equiv : setoid (preloc P) := { r := λ x x', nonempty (R x x'), iseqv := ⟨λ x,⟨R_refl x⟩, λ x x',by {rintro ⟨m⟩,exact ⟨R_symm m⟩}, λ x x' x'',by {rintros ⟨m⟩ ⟨n⟩, exact ⟨R_trans m n⟩}⟩ } lemma r_add {x y x' y' : preloc P} : ∀ (m : x ≈ x') (n : y ≈ y'), (x + y) ≈ (x' + y') | ⟨m⟩ ⟨n⟩ := ⟨R_add m n⟩ lemma r_mul {x y x' y' : preloc P} : ∀ (m : x ≈ x') (n : y ≈ y'), (x * y) ≈ (x' * y') | ⟨m⟩ ⟨n⟩ := ⟨R_mul m n⟩ end preloc def loc (P : prelog_semiring) := quotient (preloc.loc_equiv P) namespace loc variable {P : prelog_semiring} def mk0 : (preloc P) → (loc P) := quotient.mk def mk (a : P.A) (s : P.S) : loc P := mk0 (a /₀ s) notation a `/₁` s := loc.mk a s instance : comm_semiring (loc P) := { zero := mk0 0, one := mk0 1, add := quotient.lift₂ (λ x y, mk0 (x + y)) (λ x y x' y' m n, quotient.sound (@preloc.r_add P x y x' y' m n)), mul := quotient.lift₂ (λ x y, mk0 (x * y)) (λ x y x' y' m n, quotient.sound (@preloc.r_mul P x y x' y' m n)), zero_add := λ x,by {rcases x,exact congr_arg mk0 (zero_add x),}, add_zero := λ x,by {rcases x,exact congr_arg mk0 (add_zero x),}, one_mul := λ x,by {rcases x,exact congr_arg mk0 (one_mul x),}, mul_one := λ x,by {rcases x,exact congr_arg mk0 (mul_one x),}, zero_mul := λ x,by {rcases x,exact quotient.sound ⟨preloc.R_zero_mul x⟩,}, mul_zero := λ x,by {rcases x,exact quotient.sound ⟨preloc.R_mul_zero x⟩,}, add_comm := λ x y,by {rcases x, rcases y, exact congr_arg mk0 (add_comm x y)}, mul_comm := λ x y,by {rcases x, rcases y, exact congr_arg mk0 (mul_comm x y)}, add_assoc := λ x y z,by {rcases x,rcases y,rcases z, exact congr_arg mk0 (add_assoc x y z)}, mul_assoc := λ x y z,by {rcases x,rcases y,rcases z, exact congr_arg mk0 (mul_assoc x y z)}, left_distrib := λ x y z,by {rcases x,rcases y,rcases z, exact quotient.sound ⟨@preloc.R_mul_add P x y z⟩, }, right_distrib := λ x y z,by {rcases x,rcases y,rcases z, exact quotient.sound ⟨@preloc.R_add_mul P x y z⟩, }, } def η {P : prelog_semiring} : P.A →+* (loc P) := { to_fun := λ a, a /₁ 1, map_zero' := rfl, map_one' := rfl, map_add' := λ a b,congr_arg mk0 (preloc.eta_map_add a b), map_mul' := λ a b, begin have := preloc.eta_map_mul a b, have := congr_arg mk0 this, exact this end } def ζ (s : P.S) : units (loc P) := begin let val : loc P := ((P.i s) /₁ 1), let inv : loc P := (1 /₁ s), let val_inv : val * inv = 1 := begin show mk0 (((P.i s) * 1) /₀ (1 * s)) = mk0 (1 /₀ 1), let h : (((P.i s) * 1) /₀ (1 * s)) ≈ (1 /₀ 1) := ⟨{ s := 1 , e := by {simp[P.i.map_one],}}⟩ , exact quotient.sound h, end, let inv_val := (mul_comm inv val).trans val_inv, exact { val := val, inv := inv, val_inv := val_inv, inv_val := inv_val }, end end loc end prelog_semiring end localization_alt
eb985dd6b93def1a305cf171da02fff537dbadb6
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/Elab/Tactic/Basic.lean
2b0ff5806cbad24dc25cfbb3dfe2a88461f26cb4
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,554
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectMVars import Lean.Parser.Command import Lean.Meta.PPGoal import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Contradiction import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Subst import Lean.Elab.Util import Lean.Elab.Term import Lean.Elab.Binders namespace Lean.Elab open Meta /- Assign `mvarId := sorry` -/ def admitGoal (mvarId : MVarId) : MetaM Unit := withMVarContext mvarId do let mvarType ← inferType (mkMVar mvarId) assignExprMVar mvarId (← mkSorry mvarType (synthetic := true)) def goalsToMessageData (goals : List MVarId) : MessageData := MessageData.joinSep (goals.map $ MessageData.ofGoal) m!"\n\n" def Term.reportUnsolvedGoals (goals : List MVarId) : TermElabM Unit := withPPInaccessibleNames do logError <| MessageData.tagged `Tactic.unsolvedGoals <| m!"unsolved goals\n{goalsToMessageData goals}" goals.forM fun mvarId => admitGoal mvarId namespace Tactic structure Context where main : MVarId -- declaration name of the executing elaborator, used by `mkTacticInfo` to persist it in the info tree elaborator : Name structure State where goals : List MVarId deriving Inhabited structure SavedState where term : Term.SavedState tactic : State abbrev TacticM := ReaderT Context $ StateRefT State TermElabM abbrev Tactic := Syntax → TacticM Unit -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad TacticM := let i := inferInstanceAs (Monad TacticM); { pure := i.pure, bind := i.bind } def getGoals : TacticM (List MVarId) := return (← get).goals def setGoals (mvarIds : List MVarId) : TacticM Unit := modify fun s => { s with goals := mvarIds } def pruneSolvedGoals : TacticM Unit := do let gs ← getGoals let gs ← gs.filterM fun g => not <$> isExprMVarAssigned g setGoals gs def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals getGoals @[inline] private def TacticM.runCore (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) := x ctx |>.run s @[inline] private def TacticM.runCore' (x : TacticM α) (ctx : Context) (s : State) : TermElabM α := Prod.fst <$> x.runCore ctx s def run (mvarId : MVarId) (x : TacticM Unit) : TermElabM (List MVarId) := withMVarContext mvarId do let savedSyntheticMVars := (← get).syntheticMVars modify fun s => { s with syntheticMVars := [] } let aux : TacticM (List MVarId) := /- Important: the following `try` does not backtrack the state. This is intentional because we don't want to backtrack the error messages when we catch the "abort internal exception" We must define `run` here because we define `MonadExcept` instance for `TacticM` -/ try x; getUnsolvedGoals catch ex => if isAbortTacticException ex then getUnsolvedGoals else throw ex try aux.runCore' { main := mvarId, elaborator := Name.anonymous } { goals := [mvarId] } finally modify fun s => { s with syntheticMVars := savedSyntheticMVars } protected def saveState : TacticM SavedState := return { term := (← Term.saveState), tactic := (← get) } def SavedState.restore (b : SavedState) : TacticM Unit := do b.term.restore set b.tactic protected def getCurrMacroScope : TacticM MacroScope := do pure (← readThe Term.Context).currMacroScope protected def getMainModule : TacticM Name := do pure (← getEnv).mainModule unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) := mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic" @[builtinInit mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic def mkTacticInfo (mctxBefore : MetavarContext) (goalsBefore : List MVarId) (stx : Syntax) : TacticM Info := return Info.ofTacticInfo { elaborator := (← read).elaborator mctxBefore := mctxBefore goalsBefore := goalsBefore stx := stx mctxAfter := (← getMCtx) goalsAfter := (← getUnsolvedGoals) } def mkInitialTacticInfo (stx : Syntax) : TacticM (TacticM Info) := do let mctxBefore ← getMCtx let goalsBefore ← getUnsolvedGoals return mkTacticInfo mctxBefore goalsBefore stx @[inline] def withTacticInfoContext (stx : Syntax) (x : TacticM α) : TacticM α := do withInfoContext x (← mkInitialTacticInfo stx) /- Important: we must define `evalTacticUsing` and `expandTacticMacroFns` before we define the instance `MonadExcept` for `TacticM` since it backtracks the state including error messages, and this is bad when rethrowing the exception at the `catch` block in these methods. We marked these places with a `(*)` in these methods. -/ private def evalTacticUsing (s : SavedState) (stx : Syntax) (tactics : List (KeyedDeclsAttribute.AttributeEntry Tactic)) : TacticM Unit := do let rec loop | [] => throwErrorAt stx "unexpected syntax {indentD stx}" | evalFn::evalFns => do try withReader ({ · with elaborator := evalFn.decl }) <| withTacticInfoContext stx <| evalFn.value stx catch | ex@(Exception.error _ _) => match evalFns with | [] => throw ex -- (*) | evalFns => s.restore; loop evalFns | ex@(Exception.internal id _) => if id == unsupportedSyntaxExceptionId then s.restore; loop evalFns else throw ex loop tactics mutual partial def expandTacticMacroFns (stx : Syntax) (macros : List (KeyedDeclsAttribute.AttributeEntry Macro)) : TacticM Unit := let rec loop | [] => throwErrorAt stx "tactic '{stx.getKind}' has not been implemented" | m::ms => do let scp ← getCurrMacroScope try withReader ({ · with elaborator := m.decl }) do withTacticInfoContext stx do let stx' ← adaptMacro m.value stx evalTactic stx' catch ex => if ms.isEmpty then throw ex -- (*) loop ms loop macros partial def expandTacticMacro (stx : Syntax) : TacticM Unit := do expandTacticMacroFns stx (macroAttribute.getEntries (← getEnv) stx.getKind) partial def evalTacticAux (stx : Syntax) : TacticM Unit := withRef stx $ withIncRecDepth $ withFreshMacroScope $ match stx with | Syntax.node k args => if k == nullKind then -- Macro writers create a sequence of tactics `t₁ ... tₙ` using `mkNullNode #[t₁, ..., tₙ]` stx.getArgs.forM evalTactic else do trace[Elab.step] "{stx}" let s ← Tactic.saveState match tacticElabAttribute.getEntries (← getEnv) stx.getKind with | [] => expandTacticMacro stx | evalFns => evalTacticUsing s stx evalFns | _ => throwError m!"unexpected tactic{indentD stx}" partial def evalTactic (stx : Syntax) : TacticM Unit := evalTacticAux stx end def throwNoGoalsToBeSolved : TacticM α := throwError "no goals to be solved" def done : TacticM Unit := do let gs ← getUnsolvedGoals unless gs.isEmpty do Term.reportUnsolvedGoals gs throwAbortTactic def focus (x : TacticM α) : TacticM α := do let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved setGoals [mvarId] let a ← x let mvarIds' ← getUnsolvedGoals setGoals (mvarIds' ++ mvarIds) pure a def focusAndDone (tactic : TacticM α) : TacticM α := focus do let a ← tactic done pure a /- Close the main goal using the given tactic. If it fails, log the error and `admit` -/ def closeUsingOrAdmit (tac : TacticM Unit) : TacticM Unit := do /- Important: we must define `closeUsingOrAdmit` before we define the instance `MonadExcept` for `TacticM` since it backtracks the state including error messages. -/ let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved try focusAndDone tac catch ex => logException ex admitGoal mvarId setGoals mvarIds instance : MonadBacktrack SavedState TacticM where saveState := Tactic.saveState restoreState b := b.restore @[inline] protected def tryCatch {α} (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do let b ← saveState try x catch ex => b.restore; h ex instance : MonadExcept Exception TacticM where throw := throw tryCatch := Tactic.tryCatch @[inline] protected def orElse {α} (x y : TacticM α) : TacticM α := do try x catch _ => y instance {α} : OrElse (TacticM α) where orElse := Tactic.orElse /- Save the current tactic state for a token `stx`. This method is a no-op if `stx` has no position information. We use this method to save the tactic state at punctuation such as `;` -/ def saveTacticInfoForToken (stx : Syntax) : TacticM Unit := do unless stx.getPos?.isNone do withTacticInfoContext stx (pure ()) /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α := withMacroExpansionInfo beforeStx afterStx do withTheReader Term.Context (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /-- Adapt a syntax transformation to a regular tactic evaluator. -/ def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' $ evalTactic stx' def appendGoals (mvarIds : List MVarId) : TacticM Unit := modify fun s => { s with goals := s.goals ++ mvarIds } def replaceMainGoal (mvarIds : List MVarId) : TacticM Unit := do let (mvarId :: mvarIds') ← getGoals | throwNoGoalsToBeSolved modify fun s => { s with goals := mvarIds ++ mvarIds' } /-- Return the first goal. -/ def getMainGoal : TacticM MVarId := do loop (← getGoals) where loop : List MVarId → TacticM MVarId | [] => throwNoGoalsToBeSolved | mvarId :: mvarIds => do if (← isExprMVarAssigned mvarId) then loop mvarIds else setGoals (mvarId :: mvarIds) return mvarId /-- Return the main goal metavariable declaration. -/ def getMainDecl : TacticM MetavarDecl := do getMVarDecl (← getMainGoal) /-- Return the main goal tag. -/ def getMainTag : TacticM Name := return (← getMainDecl).userName /-- Return expected type for the main goal. -/ def getMainTarget : TacticM Expr := do instantiateMVars (← getMainDecl).type /-- Execute `x` using the main goal local context and instances -/ def withMainContext (x : TacticM α) : TacticM α := do withMVarContext (← getMainGoal) x /-- Evaluate `tac` at `mvarId`, and return the list of resulting subgoals. -/ def evalTacticAt (tac : Syntax) (mvarId : MVarId) : TacticM (List MVarId) := do let gs ← getGoals try setGoals [mvarId] evalTactic tac pruneSolvedGoals getGoals finally setGoals gs def ensureHasNoMVars (e : Expr) : TacticM Unit := do let e ← instantiateMVars e let pendingMVars ← getMVars e discard <| Term.logUnassignedUsingErrorInfos pendingMVars if e.hasExprMVar then throwError "tactic failed, resulting expression contains metavariables{indentExpr e}" /-- Close main goal using the given expression. If `checkUnassigned == true`, then `val` must not contain unassinged metavariables. -/ def closeMainGoal (val : Expr) (checkUnassigned := true): TacticM Unit := do if checkUnassigned then ensureHasNoMVars val assignExprMVar (← getMainGoal) val replaceMainGoal [] @[inline] def liftMetaMAtMain (x : MVarId → MetaM α) : TacticM α := do withMainContext do x (← getMainGoal) @[inline] def liftMetaTacticAux (tac : MVarId → MetaM (α × List MVarId)) : TacticM α := do withMainContext do let (a, mvarIds) ← tac (← getMainGoal) replaceMainGoal mvarIds pure a @[inline] def liftMetaTactic (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit := liftMetaTacticAux fun mvarId => do let gs ← tactic mvarId pure ((), gs) @[inline] def liftMetaTactic1 (tactic : MVarId → MetaM (Option MVarId)) : TacticM Unit := withMainContext do if let some mvarId ← tactic (← getMainGoal) then replaceMainGoal [mvarId] else replaceMainGoal [] def tryTactic? (tactic : TacticM α) : TacticM (Option α) := do try pure (some (← tactic)) catch _ => pure none def tryTactic (tactic : TacticM α) : TacticM Bool := do try discard tactic pure true catch _ => pure false /-- Use `parentTag` to tag untagged goals at `newGoals`. If there are multiple new untagged goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`. If there is only one new untagged goal, then we just use `parentTag` -/ def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do let mctx ← getMCtx let mut numAnonymous := 0 for g in newGoals do if mctx.isAnonymousMVar g then numAnonymous := numAnonymous + 1 modifyMCtx fun mctx => do let mut mctx := mctx let mut idx := 1 for g in newGoals do if mctx.isAnonymousMVar g then if numAnonymous == 1 then mctx := mctx.renameMVar g parentTag else mctx := mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx) idx := idx + 1 pure mctx /- Recall that `ident' := ident <|> Term.hole` -/ def getNameOfIdent' (id : Syntax) : Name := if id.isIdent then id.getId else `_ def getFVarId (id : Syntax) : TacticM FVarId := withRef id do let fvar? ← Term.isLocalIdent? id; match fvar? with | some fvar => pure fvar.fvarId! | none => throwError "unknown variable '{id.getId}'" def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do withMainContext do ids.mapM getFVarId /-- Use position of `=> $body` for error messages. If there is a line break before `body`, the message will be displayed on `=>` only, but the "full range" for the info view will still include `body`. -/ def withCaseRef [Monad m] [MonadRef m] (arrow body : Syntax) (x : m α) : m α := withRef (mkNullNode #[arrow, body]) x builtin_initialize registerTraceClass `Elab.tactic end Lean.Elab.Tactic
bb7bcaa100a5c7226a85b7c6f07e57b8ffdbb013
618003631150032a5676f229d13a079ac875ff77
/src/data/real/pi.lean
d053659b3fc6ea9c2372f0f3e0ae6d1b81e52ea1
[ "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
12,559
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import analysis.special_functions.trigonometric namespace real variable (x : ℝ) /-- the series `sqrt_two_add_series x n` is `sqrt(2 + sqrt(2 + ... ))` with `n` square roots, starting with `x`. We define it here because `cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2` -/ @[simp] noncomputable def sqrt_two_add_series (x : ℝ) : ℕ → ℝ | 0 := x | (n+1) := sqrt (2 + sqrt_two_add_series n) lemma sqrt_two_add_series_zero : sqrt_two_add_series x 0 = x := by simp lemma sqrt_two_add_series_one : sqrt_two_add_series 0 1 = sqrt 2 := by simp lemma sqrt_two_add_series_two : sqrt_two_add_series 0 2 = sqrt (2 + sqrt 2) := by simp lemma sqrt_two_add_series_zero_nonneg : ∀(n : ℕ), sqrt_two_add_series 0 n ≥ 0 | 0 := le_refl 0 | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_nonneg {x : ℝ} (h : 0 ≤ x) : ∀(n : ℕ), sqrt_two_add_series x n ≥ 0 | 0 := h | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_lt_two : ∀(n : ℕ), sqrt_two_add_series 0 n < 2 | 0 := by norm_num | (n+1) := begin refine lt_of_lt_of_le _ (le_of_eq $ sqrt_sqr $ le_of_lt two_pos), rw [sqrt_two_add_series, sqrt_lt], apply add_lt_of_lt_sub_left, apply lt_of_lt_of_le (sqrt_two_add_series_lt_two n), norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num end lemma sqrt_two_add_series_succ (x : ℝ) : ∀(n : ℕ), sqrt_two_add_series x (n+1) = sqrt_two_add_series (sqrt (2 + x)) n | 0 := rfl | (n+1) := by rw [sqrt_two_add_series, sqrt_two_add_series_succ, sqrt_two_add_series] lemma sqrt_two_add_series_monotone_left {x y : ℝ} (h : x ≤ y) : ∀(n : ℕ), sqrt_two_add_series x n ≤ sqrt_two_add_series y n | 0 := h | (n+1) := begin rw [sqrt_two_add_series, sqrt_two_add_series], apply sqrt_le_sqrt, apply add_le_add_left, apply sqrt_two_add_series_monotone_left end @[simp] lemma cos_pi_over_two_pow : ∀(n : ℕ), cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2 | 0 := by simp | (n+1) := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_two_add_series, sqrt_eq_iff_sqr_eq, mul_pow, cos_square, ←mul_div_assoc, nat.add_succ, pow_succ, mul_div_mul_left, cos_pi_over_two_pow, add_mul], congr, norm_num, rw [mul_comm, pow_two, mul_assoc, ←mul_div_assoc, mul_div_cancel_left, ←mul_div_assoc, mul_div_cancel_left], norm_num, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num, apply le_of_lt, apply cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two, { transitivity (0 : ℝ), rw neg_lt_zero, apply pi_div_two_pos, apply div_pos pi_pos, apply pow_pos, norm_num }, apply div_lt_div' (le_refl pi) _ pi_pos _, refine lt_of_le_of_lt (le_of_eq (pow_one _).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_lt_succ, apply nat.succ_pos, all_goals {norm_num} end lemma sin_square_pi_over_two_pow (n : ℕ) : sin (pi / 2 ^ (n+1)) ^ 2 = 1 - (sqrt_two_add_series 0 n / 2) ^ 2 := by rw [sin_square, cos_pi_over_two_pow] lemma sin_square_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) ^ 2 = 1 / 2 - sqrt_two_add_series 0 n / 4 := begin rw [sin_square_pi_over_two_pow, sqrt_two_add_series, div_pow, sqr_sqrt, add_div, ←sub_sub], congr, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, end @[simp] lemma sin_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) = sqrt (2 - sqrt_two_add_series 0 n) / 2 := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_eq_iff_sqr_eq, mul_pow, sin_square_pi_over_two_pow_succ, sub_mul], { congr, norm_num, rw [mul_comm], convert mul_div_cancel' _ _, norm_num, norm_num }, { rw [sub_nonneg], apply le_of_lt, apply sqrt_two_add_series_lt_two }, apply le_of_lt, apply mul_pos, apply sin_pos_of_pos_of_lt_pi, { apply div_pos pi_pos, apply pow_pos, norm_num }, refine lt_of_lt_of_le _ (le_of_eq (div_one _)), rw [div_lt_div_left], refine lt_of_le_of_lt (le_of_eq (pow_zero 2).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_pos, apply pi_pos, apply pow_pos, all_goals {norm_num} end lemma cos_pi_div_four : cos (pi / 4) = sqrt 2 / 2 := by { transitivity cos (pi / 2 ^ 2), congr, norm_num, simp } lemma sin_pi_div_four : sin (pi / 4) = sqrt 2 / 2 := by { transitivity sin (pi / 2 ^ 2), congr, norm_num, simp } lemma cos_pi_div_eight : cos (pi / 8) = sqrt (2 + sqrt 2) / 2 := by { transitivity cos (pi / 2 ^ 3), congr, norm_num, simp } lemma sin_pi_div_eight : sin (pi / 8) = sqrt (2 - sqrt 2) / 2 := by { transitivity sin (pi / 2 ^ 3), congr, norm_num, simp } lemma cos_pi_div_sixteen : cos (pi / 16) = sqrt (2 + sqrt (2 + sqrt 2)) / 2 := by { transitivity cos (pi / 2 ^ 4), congr, norm_num, simp } lemma sin_pi_div_sixteen : sin (pi / 16) = sqrt (2 - sqrt (2 + sqrt 2)) / 2 := by { transitivity sin (pi / 2 ^ 4), congr, norm_num, simp } lemma cos_pi_div_thirty_two : cos (pi / 32) = sqrt (2 + sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity cos (pi / 2 ^ 5), congr, norm_num, simp } lemma sin_pi_div_thirty_two : sin (pi / 32) = sqrt (2 - sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity sin (pi / 2 ^ 5), congr, norm_num, simp } lemma pi_gt_sqrt_two_add_series (n : ℕ) : pi > 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) := begin have : pi > sqrt (2 - sqrt_two_add_series 0 n) / 2 * 2 ^ (n+2), { apply mul_lt_of_lt_div, apply pow_pos, norm_num, rw [←sin_pi_over_two_pow_succ], apply sin_lt, apply div_pos pi_pos, apply pow_pos, norm_num }, apply lt_of_le_of_lt (le_of_eq _) this, rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num end lemma pi_lt_sqrt_two_add_series (n : ℕ) : pi < 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) + 1 / 4 ^ n := begin have : pi < (sqrt (2 - sqrt_two_add_series 0 n) / 2 + 1 / (2 ^ n) ^ 3 / 4) * 2 ^ (n+2), { rw [←div_lt_iff, ←sin_pi_over_two_pow_succ], refine lt_of_lt_of_le (lt_add_of_sub_right_lt (sin_gt_sub_cube _ _)) _, { apply div_pos pi_pos, apply pow_pos, norm_num }, { apply div_le_of_le_mul, apply pow_pos, norm_num, refine le_trans pi_le_four _, simp only [show ((4 : ℝ) = 2 ^ 2), by norm_num, mul_one], apply pow_le_pow, norm_num, apply le_add_of_nonneg_left, apply nat.zero_le }, apply add_le_add_left, rw div_le_div_right, apply le_div_of_mul_le, apply pow_pos, apply pow_pos, norm_num, rw [←mul_pow], refine le_trans _ (le_of_eq (one_pow 3)), apply pow_le_pow_of_le_left, { apply le_of_lt, apply mul_pos, apply div_pos pi_pos, apply pow_pos, norm_num, apply pow_pos, norm_num }, apply mul_le_of_le_div, apply pow_pos, norm_num, refine le_trans ((div_le_div_right _).mpr pi_le_four) _, apply pow_pos, norm_num, rw [pow_succ, pow_succ, ←mul_assoc, ←div_div_eq_div_mul], convert le_refl _, norm_num, norm_num, apply pow_pos, norm_num }, apply lt_of_lt_of_le this (le_of_eq _), rw [add_mul], congr' 1, { rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num }, rw [pow_succ, ←pow_mul, mul_comm n 2, pow_mul, show (2 : ℝ) ^ 2 = 4, by norm_num, pow_succ, pow_succ, ←mul_assoc (2 : ℝ), show (2 : ℝ) * 2 = 4, by norm_num, ←mul_assoc, div_mul_cancel, mul_comm ((2 : ℝ) ^ n), ←div_div_eq_div_mul, div_mul_cancel], apply pow_ne_zero, norm_num, norm_num end /-- From an upper bound on `sqrt_two_add_series 0 n = 2 cos (pi / 2 ^ (n+1))` of the form `sqrt_two_add_series 0 n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2)`, one can deduce the lower bound `a < pi` thanks to basic trigonometric inequalities as expressed in `pi_gt_sqrt_two_add_series`. -/ theorem pi_lower_bound_start (n : ℕ) {a} (h : sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2) : a < pi := begin refine lt_of_le_of_lt _ (pi_gt_sqrt_two_add_series n), rw [mul_comm], refine le_mul_of_div_le (pow_pos (by norm_num) _) (le_sqrt_of_sqr_le _), rwa [le_sub, show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div]], end lemma sqrt_two_add_series_step_up (c d : ℕ) {a b n : ℕ} {z : ℝ} (hz : sqrt_two_add_series (c/d) n ≤ z) (hb : 0 < b) (hd : 0 < d) (h : (2 * b + a) * d ^ 2 ≤ c ^ 2 * b) : sqrt_two_add_series (a/b) (n+1) ≤ z := begin refine le_trans _ hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [sqrt_le_left (div_nonneg (nat.cast_nonneg _) hd'), div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hb'), div_le_div_iff hb' (pow_pos hd' _)], exact_mod_cast h end /-- Create a proof of `a < pi` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≤ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ a/2^(n+1)`. -/ meta def pi_lower_bound (l : list ℚ) : tactic unit := do let n := l.length, tactic.apply `(@pi_lower_bound_start %%(reflect n)), l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_up %%(reflect a) %%(reflect b))); [tactic.skip, `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num1] /-- From a lower bound on `sqrt_two_add_series 0 n = 2 cos (pi / 2 ^ (n+1))` of the form `2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series 0 n`, one can deduce the upper bound `pi < a` thanks to basic trigonometric formulas as expressed in `pi_lt_sqrt_two_add_series`. -/ theorem pi_upper_bound_start (n : ℕ) {a} (h : 2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n) (h₂ : 1 / 4 ^ n ≤ a) : pi < a := begin refine lt_of_lt_of_le (pi_lt_sqrt_two_add_series n) _, rw [← le_sub_iff_add_le, ← le_div_iff', sqrt_le_left, sub_le], { rwa [nat.cast_zero, zero_div] at h }, { exact div_nonneg (sub_nonneg.2 h₂) (pow_pos two_pos _) }, { exact pow_pos two_pos _ } end lemma sqrt_two_add_series_step_down (a b : ℕ) {c d n : ℕ} {z : ℝ} (hz : z ≤ sqrt_two_add_series (a/b) n) (hb : 0 < b) (hd : 0 < d) (h : a ^ 2 * d ≤ (2 * d + c) * b ^ 2) : z ≤ sqrt_two_add_series (c/d) (n+1) := begin apply le_trans hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, apply le_sqrt_of_sqr_le, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hd'), div_le_div_iff (pow_pos hb' _) hd'], exact_mod_cast h end /-- Create a proof of `pi < a` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≥ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ (a - 1/4^n) / 2^(n+1)`. -/ meta def pi_upper_bound (l : list ℚ) : tactic unit := do let n := l.length, (() <$ tactic.apply `(@pi_upper_bound_start %%(reflect n))); [pure (), `[norm_num1]], l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_down %%(reflect a) %%(reflect b))); [pure (), `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num] lemma pi_gt_three : 3 < pi := by pi_lower_bound [23/16] lemma pi_gt_314 : 3.14 < pi := by pi_lower_bound [99/70, 874/473, 1940/989, 1447/727] lemma pi_lt_315 : pi < 3.15 := by pi_upper_bound [140/99, 279/151, 51/26, 412/207] lemma pi_gt_31415 : 3.1415 < pi := by pi_lower_bound [ 11482/8119, 5401/2923, 2348/1197, 11367/5711, 25705/12868, 23235/11621] lemma pi_lt_31416 : pi < 3.1416 := by pi_upper_bound [ 4756/3363, 101211/54775, 505534/257719, 83289/41846, 411278/205887, 438142/219137, 451504/225769, 265603/132804, 849938/424971] lemma pi_gt_3141592 : 3.141592 < pi := by pi_lower_bound [ 11482/8119, 7792/4217, 54055/27557, 949247/476920, 3310126/1657059, 2635492/1318143, 1580265/790192, 1221775/610899, 3612247/1806132, 849943/424972] lemma pi_lt_3141593 : pi < 3.141593 := by pi_upper_bound [ 27720/19601, 56935/30813, 49359/25163, 258754/130003, 113599/56868, 1101994/551163, 8671537/4336095, 3877807/1938940, 52483813/26242030, 56946167/28473117, 23798415/11899211] end real
9e43b14a0c1e9f3f2dee4820513949f6098d9ad1
df561f413cfe0a88b1056655515399c546ff32a5
/8-inequality-world/l5.lean
db45687e1f7a743ea2d4a80769df0bfabc335702
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
177
lean
theorem le_trans (a b c : mynat) (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := begin cases hab with d hd, cases hbc with e he, use (d + e), rw he, rw hd, rw add_assoc, refl, end
cdcd02a1b25593adcd95c711188a836f42d6e2b0
1446f520c1db37e157b631385707cc28a17a595e
/stage0/src/Init/Data/Option/Basic.lean
b1c2f156e102cb79460038ad9876352535badea9
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,135
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.Control.Monad import Init.Control.Alternative import Init.Coe open Decidable universes u v namespace Option def toMonad {m : Type → Type} [Monad m] [Alternative m] {A} : Option A → m A | none => failure | some a => pure a @[macroInline] def getD {α : Type u} : Option α → α → α | some x, _ => x | none, e => e @[inline] def toBool {α : Type u} : Option α → Bool | some _ => true | none => false @[inline] def isSome {α : Type u} : Option α → Bool | some _ => true | none => false @[inline] def isNone {α : Type u} : Option α → Bool | some _ => false | none => true @[inline] protected def bind {α : Type u} {β : Type v} : Option α → (α → Option β) → Option β | none, b => none | some a, b => b a @[inline] protected def map {α β} (f : α → β) (o : Option α) : Option β := Option.bind o (some ∘ f) theorem mapId {α} : (Option.map id : Option α → Option α) = id := funext (fun o => match o with | none => rfl | some x => rfl) instance : Monad Option := {pure := @some, bind := @Option.bind, map := @Option.map} @[inline] protected def filter {α} (p : α → Bool) : Option α → Option α | some a => if p a then some a else none | none => none @[macroInline] protected def orelse {α : Type u} : Option α → Option α → Option α | some a, _ => some a | none, b => b /- Remark: when using the polymorphic notation `a <|> b` is not a `[macroInline]`. Thus, `a <|> b` will make `Option.orelse` to behave like it was marked as `[inline]`. -/ instance : Alternative Option := { failure := @none, orelse := @Option.orelse, ..Option.Monad } @[inline] protected def lt {α : Type u} (r : α → α → Prop) : Option α → Option α → Prop | none, some x => True | some x, some y => r x y | _, _ => False instance decidableRelLt {α : Type u} (r : α → α → Prop) [s : DecidableRel r] : DecidableRel (Option.lt r) | none, some y => isTrue trivial | some x, some y => s x y | some x, none => isFalse notFalse | none, none => isFalse notFalse end Option instance (α : Type u) : Inhabited (Option α) := ⟨none⟩ instance {α : Type u} [DecidableEq α] : DecidableEq (Option α) := fun a b => match a, b with | none, none => isTrue rfl | none, (some v₂) => isFalse (fun h => Option.noConfusion h) | (some v₁), none => isFalse (fun h => Option.noConfusion h) | (some v₁), (some v₂) => match decEq v₁ v₂ with | (isTrue e) => isTrue (congrArg (@some α) e) | (isFalse n) => isFalse (fun h => Option.noConfusion h (fun e => absurd e n)) instance {α : Type u} [HasBeq α] : HasBeq (Option α) := ⟨fun a b => match a, b with | none, none => true | none, (some v₂) => false | (some v₁), none => false | (some v₁), (some v₂) => v₁ == v₂⟩ instance {α : Type u} [HasLess α] : HasLess (Option α) := ⟨Option.lt HasLess.Less⟩
2eecbccfadd7e974dc5d1c05a0a0cfe31f91cee3
cabd1ea95170493667c024ef2045eb86d981b133
/src/super/prover.lean
dd3e1c09723803f77a248531e1a08301bba43cfc
[]
no_license
semorrison/super
31db4b5aa5ef4c2313dc5803b8c79a95f809815b
0c6c03ba9c7470f801eb4d055294f424ff090308
refs/heads/master
1,630,272,140,541
1,511,054,739,000
1,511,054,756,000
114,317,807
0
0
null
1,513,304,776,000
1,513,304,775,000
null
UTF-8
Lean
false
false
3,649
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state import .misc_preprocessing import .selection import .trim -- default inferences -- 0 import .clausifier -- 10 import .demod import .inhabited import .datatypes -- 20 import .subsumption -- 30 import .splitting -- 40 import .factoring import .resolution import .superposition import .equality import .simp import .defs open monad tactic expr declare_trace super namespace super meta def trace_clauses : prover unit := do state ← state_t.read, trace state meta def run_prover_loop (literal_selection : selection_strategy) (clause_selection : clause_selection_strategy) (preprocessing_rules : list (prover unit)) (inference_rules : list inference) : ℕ → prover (option expr) | i := do sequence' preprocessing_rules, new ← take_newly_derived, new.mmap' register_as_passive, when (is_trace_enabled_for `super) $ new.mmap' $ λn, tactic.trace { n with c := { (n.c) with proof := const (mk_simple_name "derived") [] } }, needs_sat_run ← flip monad.lift state_t.read (λst, st.needs_sat_run), if needs_sat_run then do res ← do_sat_run, match res with | some proof := return (some proof) | none := do model ← flip monad.lift state_t.read (λst, st.current_model), when (is_trace_enabled_for `super) (do pp_model ← pp (model.to_list.map (λlit, if lit.2 = tt then lit.1 else `(not %%lit.1))), trace $ to_fmt "sat model: " ++ pp_model), run_prover_loop i end else do passive ← get_passive, if passive.size = 0 then return none else do given_name ← clause_selection i, given ← option.to_monad (passive.find given_name), -- trace_clauses, remove_passive given_name, given ← literal_selection given, when (is_trace_enabled_for `super) (do fmt ← pp given, trace (to_fmt "given: " ++ fmt)), add_active given, seq_inferences inference_rules given, run_prover_loop (i+1) meta def default_preprocessing : list (prover unit) := [ clausify_pre, clause_normalize_pre, factor_dup_lits_pre, remove_duplicates_pre, refl_r_pre, diff_constr_eq_l_pre, tautology_removal_pre, subsumption_interreduction_pre, forward_subsumption_pre, return () ] end super open super meta def super (sos_lemmas : list expr) : tactic unit := with_trim $ do as_refutation, local_false ← target, clauses ← clauses_of_context, sos_clauses ← sos_lemmas.mmap (clause.of_proof local_false), initial_state ← prover_state.initial local_false (clauses ++ sos_clauses), inf_names ← attribute.get_instances `super.inf, infs ← inf_names.mmap $ λn, eval_expr inf_decl (const n []), infs ← return $ list.map inf_decl.inf $ list.sort_on inf_decl.prio infs, res ← run_prover_loop selection21 (age_weight_clause_selection 3 4) default_preprocessing infs 0 initial_state, match res with | (some empty_clause, st) := apply empty_clause | (none, saturation) := do sat_fmt ← pp saturation, fail $ to_fmt "saturation:" ++ format.line ++ sat_fmt end namespace tactic.interactive open lean.parser open interactive open interactive.types meta def with_lemmas (ls : parse $ many ident) : tactic unit := ls.mmap' $ λl, do p ← mk_const l, t ← infer_type p, n ← get_unused_name p.get_app_fn.const_name none, tactic.assertv n t p meta def super (extra_clause_names : parse $ many ident) (extra_lemma_names : parse with_ident_list) : tactic unit := do with_lemmas extra_clause_names, extra_lemmas ← extra_lemma_names.mmap mk_const, _root_.super extra_lemmas end tactic.interactive
3d70bf67fbcf125c323ac2a219d80443fd32e01c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/integral/mean_inequalities.lean
ea58ec559bf9cccb61311cdf8e5bc31b7edeedb5
[ "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
19,528
lean
/- Copyright (c) 2020 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.integral.lebesgue import analysis.mean_inequalities import analysis.mean_inequalities_pow import measure_theory.function.special_functions /-! # Mean value inequalities for integrals In this file we prove several inequalities on integrals, notably the Hölder inequality and the Minkowski inequality. The versions for finite sums are in `analysis.mean_inequalities`. ## Main results Hölder's inequality for the Lebesgue integral of `ℝ≥0∞` and `ℝ≥0` functions: we prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents and `α→(e)nnreal` functions in two cases, * `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions, * `nnreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0 functions. Minkowski's inequality for the Lebesgue integral of measurable functions with `ℝ≥0∞` values: we prove `(∫ (f + g)^p ∂μ) ^ (1/p) ≤ (∫ f^p ∂μ) ^ (1/p) + (∫ g^p ∂μ) ^ (1/p)` for `1 ≤ p`. -/ section lintegral /-! ### Hölder's inequality for the Lebesgue integral of ℝ≥0∞ and nnreal functions We prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents and `α→(e)nnreal` functions in several cases, the first two being useful only to prove the more general results: * `ennreal.lintegral_mul_le_one_of_lintegral_rpow_eq_one` : ℝ≥0∞ functions for which the integrals on the right are equal to 1, * `ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top` : ℝ≥0∞ functions for which the integrals on the right are neither ⊤ nor 0, * `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions, * `nnreal.lintegral_mul_le_Lp_mul_Lq` : nnreal functions. -/ noncomputable theory open_locale classical big_operators nnreal ennreal open measure_theory variables {α : Type*} [measurable_space α] {μ : measure α} namespace ennreal lemma lintegral_mul_le_one_of_lintegral_rpow_eq_one {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_norm : ∫⁻ a, (f a)^p ∂μ = 1) (hg_norm : ∫⁻ a, (g a)^q ∂μ = 1) : ∫⁻ a, (f * g) a ∂μ ≤ 1 := begin calc ∫⁻ (a : α), ((f * g) a) ∂μ ≤ ∫⁻ (a : α), ((f a)^p / ennreal.of_real p + (g a)^q / ennreal.of_real q) ∂μ : lintegral_mono (λ a, young_inequality (f a) (g a) hpq) ... = 1 : begin simp only [div_eq_mul_inv], rw lintegral_add_left', { rw [lintegral_mul_const'' _ (hf.pow_const p), lintegral_mul_const', hf_norm, hg_norm, ← div_eq_mul_inv, ← div_eq_mul_inv, hpq.inv_add_inv_conj_ennreal], simp [hpq.symm.pos], }, { exact (hf.pow_const _).mul_const _, }, end end /-- Function multiplied by the inverse of its p-seminorm `(∫⁻ f^p ∂μ) ^ 1/p`-/ def fun_mul_inv_snorm (f : α → ℝ≥0∞) (p : ℝ) (μ : measure α) : α → ℝ≥0∞ := λ a, (f a) * ((∫⁻ c, (f c) ^ p ∂μ) ^ (1 / p))⁻¹ lemma fun_eq_fun_mul_inv_snorm_mul_snorm {p : ℝ} (f : α → ℝ≥0∞) (hf_nonzero : ∫⁻ a, (f a) ^ p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) {a : α} : f a = (fun_mul_inv_snorm f p μ a) * (∫⁻ c, (f c)^p ∂μ)^(1/p) := by simp [fun_mul_inv_snorm, mul_assoc, inv_mul_cancel, hf_nonzero, hf_top] lemma fun_mul_inv_snorm_rpow {p : ℝ} (hp0 : 0 < p) {f : α → ℝ≥0∞} {a : α} : (fun_mul_inv_snorm f p μ a) ^ p = (f a)^p * (∫⁻ c, (f c) ^ p ∂μ)⁻¹ := begin rw [fun_mul_inv_snorm, mul_rpow_of_nonneg _ _ (le_of_lt hp0)], suffices h_inv_rpow : ((∫⁻ (c : α), f c ^ p ∂μ) ^ (1 / p))⁻¹ ^ p = (∫⁻ (c : α), f c ^ p ∂μ)⁻¹, by rw h_inv_rpow, rw [inv_rpow, ← rpow_mul, one_div_mul_cancel hp0.ne', rpow_one] end lemma lintegral_rpow_fun_mul_inv_snorm_eq_one {p : ℝ} (hp0_lt : 0 < p) {f : α → ℝ≥0∞} (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) : ∫⁻ c, (fun_mul_inv_snorm f p μ c)^p ∂μ = 1 := begin simp_rw fun_mul_inv_snorm_rpow hp0_lt, rw [lintegral_mul_const', mul_inv_cancel hf_nonzero hf_top], rwa inv_ne_top end /-- Hölder's inequality in case of finite non-zero integrals -/ lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_nontop : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) (hg_nontop : ∫⁻ a, (g a)^q ∂μ ≠ ⊤) (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) := begin let npf := (∫⁻ (c : α), (f c) ^ p ∂μ) ^ (1/p), let nqg := (∫⁻ (c : α), (g c) ^ q ∂μ) ^ (1/q), calc ∫⁻ (a : α), (f * g) a ∂μ = ∫⁻ (a : α), ((fun_mul_inv_snorm f p μ * fun_mul_inv_snorm g q μ) a) * (npf * nqg) ∂μ : begin refine lintegral_congr (λ a, _), rw [pi.mul_apply, fun_eq_fun_mul_inv_snorm_mul_snorm f hf_nonzero hf_nontop, fun_eq_fun_mul_inv_snorm_mul_snorm g hg_nonzero hg_nontop, pi.mul_apply], ring, end ... ≤ npf * nqg : begin rw lintegral_mul_const' (npf * nqg) _ (by simp [hf_nontop, hg_nontop, hf_nonzero, hg_nonzero]), nth_rewrite 1 ←one_mul (npf * nqg), refine mul_le_mul _ (le_refl (npf * nqg)), have hf1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.pos hf_nonzero hf_nontop, have hg1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.symm.pos hg_nonzero hg_nontop, exact lintegral_mul_le_one_of_lintegral_rpow_eq_one hpq (hf.mul_const _) hf1 hg1, end end lemma ae_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0 : 0 ≤ p) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) : f =ᵐ[μ] 0 := begin rw lintegral_eq_zero_iff' (hf.pow_const p) at hf_zero, refine filter.eventually.mp hf_zero (filter.eventually_of_forall (λ x, _)), dsimp only, rw [pi.zero_apply, ← not_imp_not], exact λ hx, (rpow_pos_of_nonneg (pos_iff_ne_zero.2 hx) hp0).ne' end lemma lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0 : 0 ≤ p) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) : ∫⁻ a, (f * g) a ∂μ = 0 := begin rw ←@lintegral_zero_fun α _ μ, refine lintegral_congr_ae _, suffices h_mul_zero : f * g =ᵐ[μ] 0 * g , by rwa zero_mul at h_mul_zero, have hf_eq_zero : f =ᵐ[μ] 0, from ae_eq_zero_of_lintegral_rpow_eq_zero hp0 hf hf_zero, exact hf_eq_zero.mul (ae_eq_refl g), end lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top {p q : ℝ} (hp0_lt : 0 < p) (hq0 : 0 ≤ q) {f g : α → ℝ≥0∞} (hf_top : ∫⁻ a, (f a)^p ∂μ = ⊤) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) := begin refine le_trans le_top (le_of_eq _), have hp0_inv_lt : 0 < 1/p, by simp [hp0_lt], rw [hf_top, ennreal.top_rpow_of_pos hp0_inv_lt], simp [hq0, hg_nonzero], end /-- Hölder's inequality for functions `α → ℝ≥0∞`. The integral of the product of two functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem lintegral_mul_le_Lp_mul_Lq (μ : measure α) {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) := begin by_cases hf_zero : ∫⁻ a, (f a) ^ p ∂μ = 0, { refine eq.trans_le _ (zero_le _), exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.nonneg hf hf_zero, }, by_cases hg_zero : ∫⁻ a, (g a) ^ q ∂μ = 0, { refine eq.trans_le _ (zero_le _), rw mul_comm, exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.symm.nonneg hg hg_zero, }, by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤, { exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.pos hpq.symm.nonneg hf_top hg_zero, }, by_cases hg_top : ∫⁻ a, (g a) ^ q ∂μ = ⊤, { rw [mul_comm, mul_comm ((∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p))], exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.symm.pos hpq.nonneg hg_top hf_zero, }, -- non-⊤ non-zero case exact ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top hpq hf hf_top hg_top hf_zero hg_zero end lemma lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top {p : ℝ} {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ < ⊤) (hg_top : ∫⁻ a, (g a) ^ p ∂μ < ⊤) (hp1 : 1 ≤ p) : ∫⁻ a, ((f + g) a) ^ p ∂μ < ⊤ := begin have hp0_lt : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, calc ∫⁻ (a : α), (f a + g a) ^ p ∂μ ≤ ∫⁻ a, ((2:ℝ≥0∞)^(p-1) * (f a) ^ p + (2:ℝ≥0∞)^(p-1) * (g a) ^ p) ∂ μ : begin refine lintegral_mono (λ a, _), dsimp only, have h_zero_lt_half_rpow : (0 : ℝ≥0∞) < (1 / 2) ^ p, { rw [←ennreal.zero_rpow_of_pos hp0_lt], exact ennreal.rpow_lt_rpow (by simp [zero_lt_one]) hp0_lt, }, have h_rw : (1 / 2) ^ p * (2:ℝ≥0∞) ^ (p - 1) = 1 / 2, { rw [sub_eq_add_neg, ennreal.rpow_add _ _ ennreal.two_ne_zero ennreal.coe_ne_top, ←mul_assoc, ←ennreal.mul_rpow_of_nonneg _ _ hp0, one_div, ennreal.inv_mul_cancel ennreal.two_ne_zero ennreal.coe_ne_top, ennreal.one_rpow, one_mul, ennreal.rpow_neg_one], }, rw ←ennreal.mul_le_mul_left (ne_of_lt h_zero_lt_half_rpow).symm _, { rw [mul_add, ← mul_assoc, ← mul_assoc, h_rw, ←ennreal.mul_rpow_of_nonneg _ _ hp0, mul_add], refine ennreal.rpow_arith_mean_le_arith_mean2_rpow (1/2 : ℝ≥0∞) (1/2 : ℝ≥0∞) (f a) (g a) _ hp1, rw [ennreal.div_add_div_same, one_add_one_eq_two, ennreal.div_self ennreal.two_ne_zero ennreal.coe_ne_top], }, { rw ← lt_top_iff_ne_top, refine ennreal.rpow_lt_top_of_nonneg hp0 _, rw [one_div, ennreal.inv_ne_top], exact ennreal.two_ne_zero, }, end ... < ⊤ : begin have h_two : (2 : ℝ≥0∞) ^ (p - 1) ≠ ⊤, from ennreal.rpow_ne_top_of_nonneg (by simp [hp1]) ennreal.coe_ne_top, rw [lintegral_add_left', lintegral_const_mul'' _ (hf.pow_const p), lintegral_const_mul' _ _ h_two, ennreal.add_lt_top], { exact ⟨ennreal.mul_lt_top h_two hf_top.ne, ennreal.mul_lt_top h_two hg_top.ne⟩ }, { exact (hf.pow_const p).const_mul _ } end end lemma lintegral_Lp_mul_le_Lq_mul_Lr {α} [measurable_space α] {p q r : ℝ} (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) (μ : measure α) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : (∫⁻ a, ((f * g) a)^p ∂μ) ^ (1/p) ≤ (∫⁻ a, (f a)^q ∂μ) ^ (1/q) * (∫⁻ a, (g a)^r ∂μ) ^ (1/r) := begin have hp0_ne : p ≠ 0, from (ne_of_lt hp0_lt).symm, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, have hq0_lt : 0 < q, from lt_of_le_of_lt hp0 hpq, have hq0_ne : q ≠ 0, from (ne_of_lt hq0_lt).symm, have h_one_div_r : 1/r = 1/p - 1/q, by simp [hpqr], have hr0_ne : r ≠ 0, { have hr_inv_pos : 0 < 1/r, by rwa [h_one_div_r, sub_pos, one_div_lt_one_div hq0_lt hp0_lt], rw [one_div, _root_.inv_pos] at hr_inv_pos, exact (ne_of_lt hr_inv_pos).symm, }, let p2 := q/p, let q2 := p2.conjugate_exponent, have hp2q2 : p2.is_conjugate_exponent q2, from real.is_conjugate_exponent_conjugate_exponent (by simp [lt_div_iff, hpq, hp0_lt]), calc (∫⁻ (a : α), ((f * g) a) ^ p ∂μ) ^ (1 / p) = (∫⁻ (a : α), (f a)^p * (g a)^p ∂μ) ^ (1 / p) : by simp_rw [pi.mul_apply, ennreal.mul_rpow_of_nonneg _ _ hp0] ... ≤ ((∫⁻ a, (f a)^(p * p2) ∂ μ)^(1/p2) * (∫⁻ a, (g a)^(p * q2) ∂ μ)^(1/q2)) ^ (1/p) : begin refine ennreal.rpow_le_rpow _ (by simp [hp0]), simp_rw ennreal.rpow_mul, exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hp2q2 (hf.pow_const _) (hg.pow_const _) end ... = (∫⁻ (a : α), (f a) ^ q ∂μ) ^ (1 / q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1 / r) : begin rw [@ennreal.mul_rpow_of_nonneg _ _ (1/p) (by simp [hp0]), ←ennreal.rpow_mul, ←ennreal.rpow_mul], have hpp2 : p * p2 = q, { symmetry, rw [mul_comm, ←div_eq_iff hp0_ne], }, have hpq2 : p * q2 = r, { rw [← inv_inv r, ← one_div, ← one_div, h_one_div_r], field_simp [q2, real.conjugate_exponent, p2, hp0_ne, hq0_ne] }, simp_rw [div_mul_div_comm, mul_one, mul_comm p2, mul_comm q2, hpp2, hpq2], end end lemma lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) : ∫⁻ a, (f a) * (g a) ^ (p - 1) ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^p ∂μ) ^ (1/q) := begin refine le_trans (ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf (hg.pow_const _)) _, by_cases hf_zero_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) = 0, { rw [hf_zero_rpow, zero_mul], exact zero_le _, }, have hf_top_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) ≠ ⊤, { by_contra h, refine hf_top _, have hp_not_neg : ¬ p < 0, by simp [hpq.nonneg], simpa [hpq.pos, hp_not_neg] using h, }, refine (ennreal.mul_le_mul_left hf_zero_rpow hf_top_rpow).mpr (le_of_eq _), congr, ext1 a, rw [←ennreal.rpow_mul, hpq.sub_one_mul_conj], end lemma lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) : ∫⁻ a, ((f + g) a)^p ∂ μ ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p)) * (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) := begin calc ∫⁻ a, ((f+g) a) ^ p ∂μ ≤ ∫⁻ a, ((f + g) a) * ((f + g) a) ^ (p - 1) ∂μ : begin refine lintegral_mono (λ a, _), dsimp only, by_cases h_zero : (f + g) a = 0, { rw [h_zero, ennreal.zero_rpow_of_pos hpq.pos], exact zero_le _, }, by_cases h_top : (f + g) a = ⊤, { rw [h_top, ennreal.top_rpow_of_pos hpq.sub_one_pos, ennreal.top_mul_top], exact le_top, }, refine le_of_eq _, nth_rewrite 1 ←ennreal.rpow_one ((f + g) a), rw [←ennreal.rpow_add _ _ h_zero h_top, add_sub_cancel'_right], end ... = ∫⁻ (a : α), f a * (f + g) a ^ (p - 1) ∂μ + ∫⁻ (a : α), g a * (f + g) a ^ (p - 1) ∂μ : begin have h_add_m : ae_measurable (λ (a : α), ((f + g) a) ^ (p-1)) μ, from (hf.add hg).pow_const _, have h_add_apply : ∫⁻ (a : α), (f + g) a * (f + g) a ^ (p - 1) ∂μ = ∫⁻ (a : α), (f a + g a) * (f + g) a ^ (p - 1) ∂μ, from rfl, simp_rw [h_add_apply, add_mul], rw lintegral_add_left' (hf.mul h_add_m), end ... ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p)) * (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) : begin rw add_mul, exact add_le_add (lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hf (hf.add hg) hf_top) (lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hg (hf.add hg) hg_top), end end private lemma lintegral_Lp_add_le_aux {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) (h_add_zero : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ 0) (h_add_top : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤) : (∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) := begin have hp_not_nonpos : ¬ p ≤ 0, by simp [hpq.pos], have htop_rpow : (∫⁻ a, ((f+g) a) ^ p ∂μ)^(1/p) ≠ ⊤, { by_contra h, exact h_add_top (@ennreal.rpow_eq_top_of_nonneg _ (1/p) (by simp [hpq.nonneg]) h), }, have h0_rpow : (∫⁻ a, ((f+g) a) ^ p ∂ μ) ^ (1/p) ≠ 0, by simp [h_add_zero, h_add_top, hpq.nonneg, hp_not_nonpos, -pi.add_apply], suffices h : 1 ≤ (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ -(1/p) * ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)), by rwa [←mul_le_mul_left h0_rpow htop_rpow, ←mul_assoc, ←rpow_add _ _ h_add_zero h_add_top, ←sub_eq_add_neg, _root_.sub_self, rpow_zero, one_mul, mul_one] at h, have h : ∫⁻ (a : α), ((f+g) a)^p ∂μ ≤ ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)) * (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ (1/q), from lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add hpq hf hf_top hg hg_top, have h_one_div_q : 1/q = 1 - 1/p, by { nth_rewrite 1 ←hpq.inv_add_inv_conj, ring, }, simp_rw [h_one_div_q, sub_eq_add_neg 1 (1/p), ennreal.rpow_add _ _ h_add_zero h_add_top, rpow_one] at h, nth_rewrite 1 mul_comm at h, nth_rewrite 0 ←one_mul (∫⁻ (a : α), ((f+g) a) ^ p ∂μ) at h, rwa [←mul_assoc, ennreal.mul_le_mul_right h_add_zero h_add_top, mul_comm] at h, end /-- Minkowski's inequality for functions `α → ℝ≥0∞`: the `ℒp` seminorm of the sum of two functions is bounded by the sum of their `ℒp` seminorms. -/ theorem lintegral_Lp_add_le {p : ℝ} {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : (∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) := begin have hp_pos : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤, { simp [hf_top, hp_pos], }, by_cases hg_top : ∫⁻ a, (g a) ^ p ∂μ = ⊤, { simp [hg_top, hp_pos], }, by_cases h1 : p = 1, { refine le_of_eq _, simp_rw [h1, one_div_one, ennreal.rpow_one], exact lintegral_add_left' hf _, }, have hp1_lt : 1 < p, by { refine lt_of_le_of_ne hp1 _, symmetry, exact h1, }, have hpq := real.is_conjugate_exponent_conjugate_exponent hp1_lt, by_cases h0 : ∫⁻ a, ((f+g) a) ^ p ∂ μ = 0, { rw [h0, @ennreal.zero_rpow_of_pos (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1])], exact zero_le _, }, have htop : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤, { rw ← ne.def at hf_top hg_top, rw ← lt_top_iff_ne_top at hf_top hg_top ⊢, exact lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top hf hf_top hg_top hp1, }, exact lintegral_Lp_add_le_aux hpq hf hf_top hg hg_top h0 htop, end end ennreal /-- Hölder's inequality for functions `α → ℝ≥0`. The integral of the product of two functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem nnreal.lintegral_mul_le_Lp_mul_Lq {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) := begin simp_rw [pi.mul_apply, ennreal.coe_mul], exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf.coe_nnreal_ennreal hg.coe_nnreal_ennreal, end end lintegral
8b531b8cd7112ac0d875886e4be94b2e4ec52525
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/propositional_logic/hw8.lean
a46b72f59106e3967d472e7538cce2865364027e
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
242
lean
/- In this homework you first reconceptualize our implementation of propositional logic as a language of Boolean arithmetic. Then you apply what you've learned to extend it with relational expressions that evaluate to truth values. -/
3e8e21ff18baeed2eb50c8bafdd05294d14e29eb
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/bool.lean
632b51c7276039f9616ee1eebfc70e49aac967cc
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
6,482
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad -/ /-! # booleans This file proves various trivial lemmas about booleans and their relation to decidable propositions. ## Notations This file introduces the notation `!b` for `bnot b`, the boolean "not". ## Tags bool, boolean, De Morgan -/ prefix `!`:90 := bnot namespace bool @[simp] theorem coe_sort_tt : coe_sort.{1 1} tt = true := eq_true_intro rfl @[simp] theorem coe_sort_ff : coe_sort.{1 1} ff = false := eq_false_intro ff_ne_tt @[simp] theorem to_bool_true {h} : @to_bool true h = tt := show _ = to_bool true, by congr @[simp] theorem to_bool_false {h} : @to_bool false h = ff := show _ = to_bool false, by congr @[simp] theorem to_bool_coe (b:bool) {h} : @to_bool b h = b := (show _ = to_bool b, by congr).trans (by cases b; refl) theorem coe_to_bool (p : Prop) [decidable p] : to_bool p ↔ p := to_bool_iff _ @[simp] lemma of_to_bool_iff {p : Prop} [decidable p] : to_bool p ↔ p := ⟨of_to_bool_true, _root_.to_bool_true⟩ @[simp] lemma tt_eq_to_bool_iff {p : Prop} [decidable p] : tt = to_bool p ↔ p := eq_comm.trans of_to_bool_iff @[simp] lemma ff_eq_to_bool_iff {p : Prop} [decidable p] : ff = to_bool p ↔ ¬ p := eq_comm.trans (to_bool_ff_iff _) @[simp] theorem to_bool_not (p : Prop) [decidable p] : to_bool (¬ p) = bnot (to_bool p) := by by_cases p; simp * @[simp] theorem to_bool_and (p q : Prop) [decidable p] [decidable q] : to_bool (p ∧ q) = p && q := by by_cases p; by_cases q; simp * @[simp] theorem to_bool_or (p q : Prop) [decidable p] [decidable q] : to_bool (p ∨ q) = p || q := by by_cases p; by_cases q; simp * @[simp] theorem to_bool_eq {p q : Prop} [decidable p] [decidable q] : to_bool p = to_bool q ↔ (p ↔ q) := ⟨λ h, (coe_to_bool p).symm.trans $ by simp [h], to_bool_congr⟩ lemma not_ff : ¬ ff := by simp @[simp] theorem default_bool : default bool = ff := rfl theorem dichotomy (b : bool) : b = ff ∨ b = tt := by cases b; simp @[simp] theorem forall_bool {p : bool → Prop} : (∀ b, p b) ↔ p ff ∧ p tt := ⟨λ h, by simp [h], λ ⟨h₁, h₂⟩ b, by cases b; assumption⟩ @[simp] theorem exists_bool {p : bool → Prop} : (∃ b, p b) ↔ p ff ∨ p tt := ⟨λ ⟨b, h⟩, by cases b; [exact or.inl h, exact or.inr h], λ h, by cases h; exact ⟨_, h⟩⟩ /-- If `p b` is decidable for all `b : bool`, then `∀ b, p b` is decidable -/ instance decidable_forall_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∀ b, p b) := decidable_of_decidable_of_iff and.decidable forall_bool.symm /-- If `p b` is decidable for all `b : bool`, then `∃ b, p b` is decidable -/ instance decidable_exists_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∃ b, p b) := decidable_of_decidable_of_iff or.decidable exists_bool.symm @[simp] theorem cond_ff {α} (t e : α) : cond ff t e = e := rfl @[simp] theorem cond_tt {α} (t e : α) : cond tt t e = t := rfl @[simp] theorem cond_to_bool {α} (p : Prop) [decidable p] (t e : α) : cond (to_bool p) t e = if p then t else e := by by_cases p; simp * theorem coe_bool_iff : ∀ {a b : bool}, (a ↔ b) ↔ a = b := dec_trivial theorem eq_tt_of_ne_ff : ∀ {a : bool}, a ≠ ff → a = tt := dec_trivial theorem eq_ff_of_ne_tt : ∀ {a : bool}, a ≠ tt → a = ff := dec_trivial theorem bor_comm : ∀ a b, a || b = b || a := dec_trivial @[simp] theorem bor_assoc : ∀ a b c, (a || b) || c = a || (b || c) := dec_trivial theorem bor_left_comm : ∀ a b c, a || (b || c) = b || (a || c) := dec_trivial theorem bor_inl {a b : bool} (H : a) : a || b := by simp [H] theorem bor_inr {a b : bool} (H : b) : a || b := by simp [H] theorem band_comm : ∀ a b, a && b = b && a := dec_trivial @[simp] theorem band_assoc : ∀ a b c, (a && b) && c = a && (b && c) := dec_trivial theorem band_left_comm : ∀ a b c, a && (b && c) = b && (a && c) := dec_trivial theorem band_elim_left : ∀ {a b : bool}, a && b → a := dec_trivial theorem band_intro : ∀ {a b : bool}, a → b → a && b := dec_trivial theorem band_elim_right : ∀ {a b : bool}, a && b → b := dec_trivial @[simp] theorem bnot_false : bnot ff = tt := rfl @[simp] theorem bnot_true : bnot tt = ff := rfl theorem eq_tt_of_bnot_eq_ff : ∀ {a : bool}, bnot a = ff → a = tt := dec_trivial theorem eq_ff_of_bnot_eq_tt : ∀ {a : bool}, bnot a = tt → a = ff := dec_trivial theorem bxor_comm : ∀ a b, bxor a b = bxor b a := dec_trivial @[simp] theorem bxor_assoc : ∀ a b c, bxor (bxor a b) c = bxor a (bxor b c) := dec_trivial theorem bxor_left_comm : ∀ a b c, bxor a (bxor b c) = bxor b (bxor a c) := dec_trivial @[simp] theorem bxor_bnot_left : ∀ a, bxor (!a) a = tt := dec_trivial @[simp] theorem bxor_bnot_right : ∀ a, bxor a (!a) = tt := dec_trivial @[simp] theorem bxor_bnot_bnot : ∀ a b, bxor (!a) (!b) = bxor a b := dec_trivial @[simp] theorem bxor_ff_left : ∀ a, bxor ff a = a := dec_trivial @[simp] theorem bxor_ff_right : ∀ a, bxor a ff = a := dec_trivial lemma bxor_iff_ne : ∀ {x y : bool}, bxor x y = tt ↔ x ≠ y := dec_trivial /-! ### De Morgan's laws for booleans-/ @[simp] lemma bnot_band : ∀ (a b : bool), !(a && b) = !a || !b := dec_trivial @[simp] lemma bnot_bor : ∀ (a b : bool), !(a || b) = !a && !b := dec_trivial lemma bnot_inj : ∀ {a b : bool}, !a = !b → a = b := dec_trivial end bool instance : decidable_linear_order bool := begin constructor, show bool → bool → Prop, { exact λ a b, a = ff ∨ b = tt }, all_goals {apply_instance <|> exact dec_trivial} end namespace bool /-- convert a `bool` to a `ℕ`, `false -> 0`, `true -> 1` -/ def to_nat (b : bool) : ℕ := cond b 1 0 /-- convert a `ℕ` to a `bool`, `0 -> false`, everything else -> `true` -/ def of_nat (n : ℕ) : bool := to_bool (n ≠ 0) lemma of_nat_le_of_nat {n m : ℕ} (h : n ≤ m) : of_nat n ≤ of_nat m := begin simp [of_nat]; cases nat.decidable_eq n 0; cases nat.decidable_eq m 0; simp only [to_bool], { subst m, have h := le_antisymm h (nat.zero_le _), contradiction }, { left, refl } end lemma to_nat_le_to_nat {b₀ b₁ : bool} (h : b₀ ≤ b₁) : to_nat b₀ ≤ to_nat b₁ := by cases h; subst h; [cases b₁, cases b₀]; simp [to_nat,nat.zero_le] lemma of_nat_to_nat (b : bool) : of_nat (to_nat b) = b := by cases b; simp only [of_nat,to_nat]; exact dec_trivial end bool
daed9d839f07a3318717ad12fbaacbd79ab2b781
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/zipper.lean
5e1f081aa88f3b56fb27a77e792c56af1d66137b
[ "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
1,405
lean
structure ListZipper (α : Type) := (xs : List α) (bs : List α) -- set_option trace.compiler.ir.rc true variables {α : Type} namespace ListZipper def goForward : ListZipper α → ListZipper α | ⟨[], bs⟩ => ⟨[], bs⟩ | ⟨x::xs, bs⟩ => ⟨xs, x::bs⟩ def goBackward : ListZipper α → ListZipper α | ⟨xs, []⟩ => ⟨xs, []⟩ | ⟨xs, b::bs⟩ => ⟨b::xs, bs⟩ def insert : ListZipper α → α → ListZipper α | ⟨xs, bs⟩, x => ⟨xs, x::bs⟩ def erase : ListZipper α → ListZipper α | ⟨[], bs⟩ => ⟨[], bs⟩ | ⟨x::xs, bs⟩ => ⟨xs, bs⟩ def curr [Inhabited α] : ListZipper α → α | ⟨[], bs⟩ => arbitrary | ⟨x::xs, bs⟩ => x def currOpt : ListZipper α → Option α | ⟨[], bs⟩ => none | ⟨x::xs, bs⟩ => some x def toList : ListZipper α → List α | ⟨xs, bs⟩ => bs.reverse ++ xs def atEnd (z : ListZipper α) : Bool := z.xs.isEmpty end ListZipper def List.toListZipper (xs : List α) : ListZipper α := ⟨xs, []⟩ partial def testAux : ListZipper Nat → ListZipper Nat | z => if z.atEnd then z else if z.curr % 2 == 0 then testAux (z.goForward.insert 0) else if z.curr > 20 then testAux z.erase else testAux z.goForward -- testAux z.goForward def test (xs : List Nat) : List Nat := (testAux xs.toListZipper).toList #eval (IO.println (test [10, 11, 13, 20, 22, 40, 41, 11]) : IO Unit)
20074c1db556392e5333af5402c3fea1cde7bbd8
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/nat/modeq.lean
53ee3cded32c970d9eb12dae9367d1f6c152ce4d
[ "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
20,874
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.gcd import data.list.rotate import tactic.abel /-! # Congruences modulo a natural number This file defines the equivalence relation `a ≡ b [MOD n]` on the natural numbers, and proves basic properties about it such as the Chinese Remainder Theorem `modeq_and_modeq_iff_modeq_mul`. ## Notations `a ≡ b [MOD n]` is notation for `nat.modeq n a b`, which is defined to mean `a % n = b % n`. ## Tags modeq, congruence, mod, MOD, modulo -/ namespace nat /-- Modular equality. `n.modeq a b`, or `a ≡ b [MOD n]`, means that `a - b` is a multiple of `n`. -/ @[derive decidable] def modeq (n a b : ℕ) := a % n = b % n notation a ` ≡ `:50 b ` [MOD `:50 n `]`:0 := modeq n a b variables {m n a b c d : ℕ} namespace modeq @[refl] protected theorem refl (a : ℕ) : a ≡ a [MOD n] := @rfl _ _ protected theorem rfl : a ≡ a [MOD n] := modeq.refl _ instance : is_refl _ (modeq n) := ⟨modeq.refl⟩ @[symm] protected theorem symm : a ≡ b [MOD n] → b ≡ a [MOD n] := eq.symm @[trans] protected theorem trans : a ≡ b [MOD n] → b ≡ c [MOD n] → a ≡ c [MOD n] := eq.trans protected theorem comm : a ≡ b [MOD n] ↔ b ≡ a [MOD n] := ⟨modeq.symm, modeq.symm⟩ end modeq theorem modeq_zero_iff_dvd : a ≡ 0 [MOD n] ↔ n ∣ a := by rw [modeq, zero_mod, dvd_iff_mod_eq_zero] lemma _root_.has_dvd.dvd.modeq_zero_nat (h : n ∣ a) : a ≡ 0 [MOD n] := modeq_zero_iff_dvd.2 h lemma _root_.has_dvd.dvd.zero_modeq_nat (h : n ∣ a) : 0 ≡ a [MOD n] := h.modeq_zero_nat.symm theorem modeq_iff_dvd : a ≡ b [MOD n] ↔ (n:ℤ) ∣ b - a := by rw [modeq, eq_comm, ← int.coe_nat_inj', int.coe_nat_mod, int.coe_nat_mod, int.mod_eq_mod_iff_mod_sub_eq_zero, int.dvd_iff_mod_eq_zero] protected theorem modeq.dvd : a ≡ b [MOD n] → (n:ℤ) ∣ b - a := modeq_iff_dvd.1 theorem modeq_of_dvd : (n:ℤ) ∣ b - a → a ≡ b [MOD n] := modeq_iff_dvd.2 /-- A variant of `modeq_iff_dvd` with `nat` divisibility -/ theorem modeq_iff_dvd' (h : a ≤ b) : a ≡ b [MOD n] ↔ n ∣ b - a := by rw [modeq_iff_dvd, ←int.coe_nat_dvd, int.coe_nat_sub h] theorem mod_modeq (a n) : a % n ≡ a [MOD n] := mod_mod _ _ namespace modeq protected theorem modeq_of_dvd (d : m ∣ n) (h : a ≡ b [MOD n]) : a ≡ b [MOD m] := modeq_of_dvd ((int.coe_nat_dvd.2 d).trans h.dvd) protected theorem mul_left' (c : ℕ) (h : a ≡ b [MOD n]) : c * a ≡ c * b [MOD (c * n)] := by unfold modeq at *; rw [mul_mod_mul_left, mul_mod_mul_left, h] protected theorem mul_left (c : ℕ) (h : a ≡ b [MOD n]) : c * a ≡ c * b [MOD n] := (h.mul_left' _ ).modeq_of_dvd (dvd_mul_left _ _) protected theorem mul_right' (c : ℕ) (h : a ≡ b [MOD n]) : a * c ≡ b * c [MOD (n * c)] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact h.mul_left' c protected theorem mul_right (c : ℕ) (h : a ≡ b [MOD n]) : a * c ≡ b * c [MOD n] := by rw [mul_comm a, mul_comm b]; exact h.mul_left c protected theorem mul (h₁ : a ≡ b [MOD n]) (h₂ : c ≡ d [MOD n]) : a * c ≡ b * d [MOD n] := (h₂.mul_left _ ).trans (h₁.mul_right _) protected theorem pow (m : ℕ) (h : a ≡ b [MOD n]) : a ^ m ≡ b ^ m [MOD n] := begin induction m with d hd, {refl}, rw [pow_succ, pow_succ], exact h.mul hd, end protected theorem add (h₁ : a ≡ b [MOD n]) (h₂ : c ≡ d [MOD n]) : a + c ≡ b + d [MOD n] := begin rw [modeq_iff_dvd, int.coe_nat_add, int.coe_nat_add, add_sub_add_comm], exact dvd_add h₁.dvd h₂.dvd, end protected theorem add_left (c : ℕ) (h : a ≡ b [MOD n]) : c + a ≡ c + b [MOD n] := modeq.rfl.add h protected theorem add_right (c : ℕ) (h : a ≡ b [MOD n]) : a + c ≡ b + c [MOD n] := h.add modeq.rfl protected theorem add_left_cancel (h₁ : a ≡ b [MOD n]) (h₂ : a + c ≡ b + d [MOD n]) : c ≡ d [MOD n] := begin simp only [modeq_iff_dvd, int.coe_nat_add] at *, rw add_sub_add_comm at h₂, convert _root_.dvd_sub h₂ h₁ using 1, rw add_sub_cancel', end protected theorem add_left_cancel' (c : ℕ) (h : c + a ≡ c + b [MOD n]) : a ≡ b [MOD n] := modeq.rfl.add_left_cancel h protected theorem add_right_cancel (h₁ : c ≡ d [MOD n]) (h₂ : a + c ≡ b + d [MOD n]) : a ≡ b [MOD n] := by { rw [add_comm a, add_comm b] at h₂, exact h₁.add_left_cancel h₂ } protected theorem add_right_cancel' (c : ℕ) (h : a + c ≡ b + c [MOD n]) : a ≡ b [MOD n] := modeq.rfl.add_right_cancel h protected theorem mul_left_cancel' {a b c m : ℕ} (hc : c ≠ 0) : c * a ≡ c * b [MOD c * m] → a ≡ b [MOD m] := by simp [modeq_iff_dvd, ←mul_sub, mul_dvd_mul_iff_left (by simp [hc] : (c : ℤ) ≠ 0)] protected theorem mul_left_cancel_iff' {a b c m : ℕ} (hc : c ≠ 0) : c * a ≡ c * b [MOD c * m] ↔ a ≡ b [MOD m] := ⟨modeq.mul_left_cancel' hc, modeq.mul_left' _⟩ protected theorem mul_right_cancel' {a b c m : ℕ} (hc : c ≠ 0) : a * c ≡ b * c [MOD m * c] → a ≡ b [MOD m] := by simp [modeq_iff_dvd, ←sub_mul, mul_dvd_mul_iff_right (by simp [hc] : (c : ℤ) ≠ 0)] protected theorem mul_right_cancel_iff' {a b c m : ℕ} (hc : c ≠ 0) : a * c ≡ b * c [MOD m * c] ↔ a ≡ b [MOD m] := ⟨modeq.mul_right_cancel' hc, modeq.mul_right' _⟩ theorem of_modeq_mul_left (m : ℕ) (h : a ≡ b [MOD m * n]) : a ≡ b [MOD n] := by { rw [modeq_iff_dvd] at *, exact (dvd_mul_left (n : ℤ) (m : ℤ)).trans h } theorem of_modeq_mul_right (m : ℕ) : a ≡ b [MOD n * m] → a ≡ b [MOD n] := mul_comm m n ▸ of_modeq_mul_left _ end modeq theorem modeq_one : a ≡ b [MOD 1] := modeq_of_dvd (one_dvd _) lemma modeq_sub (h : b ≤ a) : a ≡ b [MOD a - b] := (modeq_of_dvd $ by rw [int.coe_nat_sub h]).symm @[simp] lemma modeq_zero_iff {a b : ℕ} : a ≡ b [MOD 0] ↔ a = b := by rw [nat.modeq, nat.mod_zero, nat.mod_zero] @[simp] lemma add_modeq_left {a n : ℕ} : n + a ≡ a [MOD n] := by rw [nat.modeq, nat.add_mod_left] @[simp] lemma add_modeq_right {a n : ℕ} : a + n ≡ a [MOD n] := by rw [nat.modeq, nat.add_mod_right] namespace modeq lemma le_of_lt_add (h1 : a ≡ b [MOD m]) (h2 : a < b + m) : a ≤ b := (le_total a b).elim id (λ h3, nat.le_of_sub_eq_zero (eq_zero_of_dvd_of_lt ((modeq_iff_dvd' h3).mp h1.symm) ((tsub_lt_iff_left h3).mpr h2))) lemma add_le_of_lt (h1 : a ≡ b [MOD m]) (h2 : a < b) : a + m ≤ b := le_of_lt_add (add_modeq_right.trans h1) (add_lt_add_right h2 m) lemma dvd_iff_of_modeq_of_dvd {a b d m : ℕ} (h : a ≡ b [MOD m]) (hdm : d ∣ m) : d ∣ a ↔ d ∣ b := begin simp only [←modeq_zero_iff_dvd], replace h := h.modeq_of_dvd hdm, exact ⟨h.symm.trans, h.trans⟩, end lemma gcd_eq_of_modeq {a b m : ℕ} (h : a ≡ b [MOD m]) : gcd a m = gcd b m := begin have h1 := gcd_dvd_right a m, have h2 := gcd_dvd_right b m, exact dvd_antisymm (dvd_gcd ((dvd_iff_of_modeq_of_dvd h h1).mp (gcd_dvd_left a m)) h1) (dvd_gcd ((dvd_iff_of_modeq_of_dvd h h2).mpr (gcd_dvd_left b m)) h2), end lemma eq_of_modeq_of_abs_lt {a b m : ℕ} (h : a ≡ b [MOD m]) (h2 : | (b:ℤ) - a | < m) : a = b := begin apply int.coe_nat_inj, rw [eq_comm, ←sub_eq_zero], exact int.eq_zero_of_abs_lt_dvd (modeq_iff_dvd.mp h) h2, end /-- To cancel a common factor `c` from a `modeq` we must divide the modulus `m` by `gcd m c` -/ lemma modeq_cancel_left_div_gcd {a b c m : ℕ} (hm : 0 < m) (h : c * a ≡ c * b [MOD m]) : a ≡ b [MOD m / gcd m c] := begin let d := gcd m c, have hmd := gcd_dvd_left m c, have hcd := gcd_dvd_right m c, rw modeq_iff_dvd, refine int.dvd_of_dvd_mul_right_of_gcd_one _ _, show (m/d : ℤ) ∣ (c/d) * (b - a), { rw [mul_comm, ←int.mul_div_assoc (b - a) (int.coe_nat_dvd.mpr hcd), mul_comm], apply int.div_dvd_div (int.coe_nat_dvd.mpr hmd), rw mul_sub, exact modeq_iff_dvd.mp h }, show int.gcd (m/d) (c/d) = 1, { simp only [←int.coe_nat_div, int.coe_nat_gcd (m / d) (c / d), gcd_div hmd hcd, nat.div_self (gcd_pos_of_pos_left c hm)] }, end lemma modeq_cancel_right_div_gcd {a b c m : ℕ} (hm : 0 < m) (h : a * c ≡ b * c [MOD m]) : a ≡ b [MOD m / gcd m c] := by { apply modeq_cancel_left_div_gcd hm, simpa [mul_comm] using h } lemma modeq_cancel_left_div_gcd' {a b c d m : ℕ} (hm : 0 < m) (hcd : c ≡ d [MOD m]) (h : c * a ≡ d * b [MOD m]) : a ≡ b [MOD m / gcd m c] := modeq_cancel_left_div_gcd hm (h.trans (modeq.mul_right b hcd).symm) lemma modeq_cancel_right_div_gcd' {a b c d m : ℕ} (hm : 0 < m) (hcd : c ≡ d [MOD m]) (h : a * c ≡ b * d [MOD m]) : a ≡ b [MOD m / gcd m c] := by { apply modeq_cancel_left_div_gcd' hm hcd, simpa [mul_comm] using h } /-- A common factor that's coprime with the modulus can be cancelled from a `modeq` -/ lemma modeq_cancel_left_of_coprime {a b c m : ℕ} (hmc : gcd m c = 1) (h : c * a ≡ c * b [MOD m]) : a ≡ b [MOD m] := begin rcases m.eq_zero_or_pos with rfl | hm, { simp only [gcd_zero_left] at hmc, simp only [gcd_zero_left, hmc, one_mul, modeq_zero_iff] at h, subst h }, simpa [hmc] using modeq_cancel_left_div_gcd hm h end /-- A common factor that's coprime with the modulus can be cancelled from a `modeq` -/ lemma modeq_cancel_right_of_coprime {a b c m : ℕ} (hmc : gcd m c = 1) (h : a * c ≡ b * c [MOD m]) : a ≡ b [MOD m] := by { apply modeq_cancel_left_of_coprime hmc, simpa [mul_comm] using h } end modeq local attribute [semireducible] int.nonneg /-- The natural number less than `lcm n m` congruent to `a` mod `n` and `b` mod `m` -/ def chinese_remainder' (h : a ≡ b [MOD gcd n m]) : {k // k ≡ a [MOD n] ∧ k ≡ b [MOD m]} := if hn : n = 0 then ⟨a, begin rw [hn, gcd_zero_left] at h, split, refl, exact h end⟩ else if hm : m = 0 then ⟨b, begin rw [hm, gcd_zero_right] at h, split, exact h.symm, refl end⟩ else ⟨let (c, d) := xgcd n m in int.to_nat (((n * c * b + m * d * a) / gcd n m) % lcm n m), begin rw xgcd_val, dsimp [chinese_remainder'._match_1], rw [modeq_iff_dvd, modeq_iff_dvd, int.to_nat_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero.2 (lcm_ne_zero hn hm)))], have hnonzero : (gcd n m : ℤ) ≠ 0 := begin norm_cast, rw [nat.gcd_eq_zero_iff, not_and], exact λ _, hm, end, have hcoedvd : ∀ t, (gcd n m : ℤ) ∣ t * (b - a) := λ t, h.dvd.mul_left _, have := gcd_eq_gcd_ab n m, split; rw [int.mod_def, ← sub_add]; refine dvd_add _ (dvd_mul_of_dvd_left _ _); try {norm_cast}, { rw ← sub_eq_iff_eq_add' at this, rw [← this, sub_mul, ← add_sub_assoc, add_comm, add_sub_assoc, ← mul_sub, int.add_div_of_dvd_left, int.mul_div_cancel_left _ hnonzero, int.mul_div_assoc _ h.dvd, ← sub_sub, sub_self, zero_sub, dvd_neg, mul_assoc], exact dvd_mul_right _ _, norm_cast, exact dvd_mul_right _ _, }, { exact dvd_lcm_left n m, }, { rw ← sub_eq_iff_eq_add at this, rw [← this, sub_mul, sub_add, ← mul_sub, int.sub_div_of_dvd, int.mul_div_cancel_left _ hnonzero, int.mul_div_assoc _ h.dvd, ← sub_add, sub_self, zero_add, mul_assoc], exact dvd_mul_right _ _, exact hcoedvd _ }, { exact dvd_lcm_right n m, }, end⟩ /-- The natural number less than `n*m` congruent to `a` mod `n` and `b` mod `m` -/ def chinese_remainder (co : coprime n m) (a b : ℕ) : {k // k ≡ a [MOD n] ∧ k ≡ b [MOD m]} := chinese_remainder' (by convert modeq_one) lemma chinese_remainder'_lt_lcm (h : a ≡ b [MOD gcd n m]) (hn : n ≠ 0) (hm : m ≠ 0) : ↑(chinese_remainder' h) < lcm n m := begin dsimp only [chinese_remainder'], rw [dif_neg hn, dif_neg hm, subtype.coe_mk, xgcd_val, ←int.to_nat_coe_nat (lcm n m)], have lcm_pos := int.coe_nat_pos.mpr (nat.pos_of_ne_zero (lcm_ne_zero hn hm)), exact (int.to_nat_lt_to_nat lcm_pos).mpr (int.mod_lt_of_pos _ lcm_pos), end lemma chinese_remainder_lt_mul (co : coprime n m) (a b : ℕ) (hn : n ≠ 0) (hm : m ≠ 0) : ↑(chinese_remainder co a b) < n * m := lt_of_lt_of_le (chinese_remainder'_lt_lcm _ hn hm) (le_of_eq co.lcm_eq_mul) lemma modeq_and_modeq_iff_modeq_mul {a b m n : ℕ} (hmn : coprime m n) : a ≡ b [MOD m] ∧ a ≡ b [MOD n] ↔ (a ≡ b [MOD m * n]) := ⟨λ h, begin rw [nat.modeq_iff_dvd, nat.modeq_iff_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd] at h, rw [nat.modeq_iff_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd], exact hmn.mul_dvd_of_dvd_of_dvd h.1 h.2 end, λ h, ⟨h.of_modeq_mul_right _, h.of_modeq_mul_left _⟩⟩ lemma coprime_of_mul_modeq_one (b : ℕ) {a n : ℕ} (h : a * b ≡ 1 [MOD n]) : coprime a n := nat.coprime_of_dvd' (λ k kp ⟨ka, hka⟩ ⟨kb, hkb⟩, int.coe_nat_dvd.1 begin rw [hka, hkb, modeq_iff_dvd] at h, cases h with z hz, rw [sub_eq_iff_eq_add] at hz, rw [hz, int.coe_nat_mul, mul_assoc, mul_assoc, int.coe_nat_mul, ← mul_add], exact dvd_mul_right _ _, end) @[simp] lemma mod_mul_right_mod (a b c : ℕ) : a % (b * c) % b = a % b := (mod_modeq _ _).of_modeq_mul_right _ @[simp] lemma mod_mul_left_mod (a b c : ℕ) : a % (b * c) % c = a % c := (mod_modeq _ _).of_modeq_mul_left _ lemma div_mod_eq_mod_mul_div (a b c : ℕ) : a / b % c = a % (b * c) / b := if hb0 : b = 0 then by simp [hb0] else by rw [← @add_right_cancel_iff _ _ (c * (a / b / c)), mod_add_div, nat.div_div_eq_div_mul, ← nat.mul_right_inj (nat.pos_of_ne_zero hb0),← @add_left_cancel_iff _ _ (a % b), mod_add_div, mul_add, ← @add_left_cancel_iff _ _ (a % (b * c) % b), add_left_comm, ← add_assoc (a % (b * c) % b), mod_add_div, ← mul_assoc, mod_add_div, mod_mul_right_mod] lemma add_mod_add_ite (a b c : ℕ) : (a + b) % c + (if c ≤ a % c + b % c then c else 0) = a % c + b % c := have (a + b) % c = (a % c + b % c) % c, from ((mod_modeq _ _).add $ mod_modeq _ _).symm, if hc0 : c = 0 then by simp [hc0] else begin rw this, split_ifs, { have h2 : (a % c + b % c) / c < 2, from nat.div_lt_of_lt_mul (by rw mul_two; exact add_lt_add (nat.mod_lt _ (nat.pos_of_ne_zero hc0)) (nat.mod_lt _ (nat.pos_of_ne_zero hc0))), have h0 : 0 < (a % c + b % c) / c, from nat.div_pos h (nat.pos_of_ne_zero hc0), rw [← @add_right_cancel_iff _ _ (c * ((a % c + b % c) / c)), add_comm _ c, add_assoc, mod_add_div, le_antisymm (le_of_lt_succ h2) h0, mul_one, add_comm] }, { rw [nat.mod_eq_of_lt (lt_of_not_ge h), add_zero] } end lemma add_mod_of_add_mod_lt {a b c : ℕ} (hc : a % c + b % c < c) : (a + b) % c = a % c + b % c := by rw [← add_mod_add_ite, if_neg (not_le_of_lt hc), add_zero] lemma add_mod_add_of_le_add_mod {a b c : ℕ} (hc : c ≤ a % c + b % c) : (a + b) % c + c = a % c + b % c := by rw [← add_mod_add_ite, if_pos hc] lemma add_div {a b c : ℕ} (hc0 : 0 < c) : (a + b) / c = a / c + b / c + if c ≤ a % c + b % c then 1 else 0 := begin rw [← nat.mul_right_inj hc0, ← @add_left_cancel_iff _ _ ((a + b) % c + a % c + b % c)], suffices : (a + b) % c + c * ((a + b) / c) + a % c + b % c = a % c + c * (a / c) + (b % c + c * (b / c)) + c * (if c ≤ a % c + b % c then 1 else 0) + (a + b) % c, { simpa only [mul_add, add_comm, add_left_comm, add_assoc] }, rw [mod_add_div, mod_add_div, mod_add_div, mul_ite, add_assoc, add_assoc], conv_lhs { rw ← add_mod_add_ite }, simp, ac_refl end lemma add_div_eq_of_add_mod_lt {a b c : ℕ} (hc : a % c + b % c < c) : (a + b) / c = a / c + b / c := if hc0 : c = 0 then by simp [hc0] else by rw [add_div (nat.pos_of_ne_zero hc0), if_neg (not_le_of_lt hc), add_zero] protected lemma add_div_of_dvd_right {a b c : ℕ} (hca : c ∣ a) : (a + b) / c = a / c + b / c := if h : c = 0 then by simp [h] else add_div_eq_of_add_mod_lt begin rw [nat.mod_eq_zero_of_dvd hca, zero_add], exact nat.mod_lt _ (pos_iff_ne_zero.mpr h), end protected lemma add_div_of_dvd_left {a b c : ℕ} (hca : c ∣ b) : (a + b) / c = a / c + b / c := by rwa [add_comm, nat.add_div_of_dvd_right, add_comm] lemma add_div_eq_of_le_mod_add_mod {a b c : ℕ} (hc : c ≤ a % c + b % c) (hc0 : 0 < c) : (a + b) / c = a / c + b / c + 1 := by rw [add_div hc0, if_pos hc] lemma add_div_le_add_div (a b c : ℕ) : a / c + b / c ≤ (a + b) / c := if hc0 : c = 0 then by simp [hc0] else by rw [nat.add_div (nat.pos_of_ne_zero hc0)]; exact nat.le_add_right _ _ lemma le_mod_add_mod_of_dvd_add_of_not_dvd {a b c : ℕ} (h : c ∣ a + b) (ha : ¬ c ∣ a) : c ≤ a % c + b % c := by_contradiction $ λ hc, have (a + b) % c = a % c + b % c, from add_mod_of_add_mod_lt (lt_of_not_ge hc), by simp [dvd_iff_mod_eq_zero, *] at * lemma odd_mul_odd {n m : ℕ} : n % 2 = 1 → m % 2 = 1 → (n * m) % 2 = 1 := by simpa [nat.modeq] using @modeq.mul 2 n 1 m 1 lemma odd_mul_odd_div_two {m n : ℕ} (hm1 : m % 2 = 1) (hn1 : n % 2 = 1) : (m * n) / 2 = m * (n / 2) + m / 2 := have hm0 : 0 < m := nat.pos_of_ne_zero (λ h, by simp * at *), have hn0 : 0 < n := nat.pos_of_ne_zero (λ h, by simp * at *), (nat.mul_right_inj zero_lt_two).1 $ by rw [mul_add, two_mul_odd_div_two hm1, mul_left_comm, two_mul_odd_div_two hn1, two_mul_odd_div_two (nat.odd_mul_odd hm1 hn1), mul_tsub, mul_one, ← add_tsub_assoc_of_le (succ_le_of_lt hm0), tsub_add_cancel_of_le (le_mul_of_one_le_right (nat.zero_le _) hn0)] lemma odd_of_mod_four_eq_one {n : ℕ} : n % 4 = 1 → n % 2 = 1 := by simpa [modeq, show 2 * 2 = 4, by norm_num] using @modeq.of_modeq_mul_left 2 n 1 2 lemma odd_of_mod_four_eq_three {n : ℕ} : n % 4 = 3 → n % 2 = 1 := by simpa [modeq, show 2 * 2 = 4, by norm_num, show 3 % 4 = 3, by norm_num] using @modeq.of_modeq_mul_left 2 n 3 2 /-- A natural number is odd iff it has residue `1` or `3` mod `4`-/ lemma odd_mod_four_iff {n : ℕ} : n % 2 = 1 ↔ n % 4 = 1 ∨ n % 4 = 3 := have help : ∀ (m : ℕ), m < 4 → m % 2 = 1 → m = 1 ∨ m = 3 := dec_trivial, ⟨λ hn, help (n % 4) (mod_lt n (by norm_num)) $ (mod_mod_of_dvd n (by norm_num : 2 ∣ 4)).trans hn, λ h, or.dcases_on h odd_of_mod_four_eq_one odd_of_mod_four_eq_three⟩ end nat namespace list variable {α : Type*} lemma nth_rotate : ∀ {l : list α} {n m : ℕ} (hml : m < l.length), (l.rotate n).nth m = l.nth ((m + n) % l.length) | [] n m hml := (nat.not_lt_zero _ hml).elim | l 0 m hml := by simp [nat.mod_eq_of_lt hml] | (a::l) (n+1) m hml := have h₃ : m < list.length (l ++ [a]), by simpa using hml, (lt_or_eq_of_le (nat.le_of_lt_succ $ nat.mod_lt (m + n) (lt_of_le_of_lt (nat.zero_le _) hml))).elim (λ hml', have h₁ : (m + (n + 1)) % ((a :: l : list α).length) = (m + n) % ((a :: l : list α).length) + 1, from calc (m + (n + 1)) % (l.length + 1) = ((m + n) % (l.length + 1) + 1) % (l.length + 1) : add_assoc m n 1 ▸ nat.modeq.add_right 1 (nat.mod_mod _ _).symm ... = (m + n) % (l.length + 1) + 1 : nat.mod_eq_of_lt (nat.succ_lt_succ hml'), have h₂ : (m + n) % (l ++ [a]).length < l.length, by simpa [nat.add_one] using hml', by rw [list.rotate_cons_succ, nth_rotate h₃, list.nth_append h₂, h₁, list.nth]; simp) (λ hml', have h₁ : (m + (n + 1)) % (l.length + 1) = 0, from calc (m + (n + 1)) % (l.length + 1) = (l.length + 1) % (l.length + 1) : add_assoc m n 1 ▸ nat.modeq.add_right 1 (hml'.trans (nat.mod_eq_of_lt (nat.lt_succ_self _)).symm) ... = 0 : by simp, by rw [list.length, list.rotate_cons_succ, nth_rotate h₃, list.length_append, list.length_cons, list.length, zero_add, hml', h₁, list.nth_concat_length]; refl) lemma rotate_eq_self_iff_eq_repeat [hα : nonempty α] : ∀ {l : list α}, (∀ n, l.rotate n = l) ↔ ∃ a, l = list.repeat a l.length | [] := ⟨λ h, nonempty.elim hα (λ a, ⟨a, by simp⟩), by simp⟩ | (a::l) := ⟨λ h, ⟨a, list.ext_le (by simp) $ λ n hn h₁, begin rw [← option.some_inj, ← list.nth_le_nth], conv {to_lhs, rw ← h ((list.length (a :: l)) - n)}, rw [nth_rotate hn, add_tsub_cancel_of_le (le_of_lt hn), nat.mod_self, nth_le_repeat], refl end⟩, λ ⟨a, ha⟩ n, ha.symm ▸ list.ext_le (by simp) (λ m hm h, have hm' : (m + n) % (list.repeat a (list.length (a :: l))).length < list.length (a :: l), by rw list.length_repeat; exact nat.mod_lt _ (nat.succ_pos _), by rw [nth_le_repeat, ← option.some_inj, ← list.nth_le_nth, nth_rotate h, list.nth_le_nth, nth_le_repeat]; simp * at *)⟩ lemma rotate_repeat (a : α) (n : ℕ) (k : ℕ) : (list.repeat a n).rotate k = list.repeat a n := let h : nonempty α := ⟨a⟩ in by exactI rotate_eq_self_iff_eq_repeat.mpr ⟨a, by rw length_repeat⟩ k lemma rotate_one_eq_self_iff_eq_repeat [nonempty α] {l : list α} : l.rotate 1 = l ↔ ∃ a : α, l = list.repeat a l.length := ⟨λ h, rotate_eq_self_iff_eq_repeat.mp (λ n, nat.rec l.rotate_zero (λ n hn, by rwa [nat.succ_eq_add_one, ←l.rotate_rotate, hn]) n), λ h, rotate_eq_self_iff_eq_repeat.mpr h 1⟩ end list
78b4e6a4c05859ecfc9fbc5abfbd022c6b2fe87f
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/omega/nat/form.lean
930a3b6d216eb85c55f92e9d6f488c5a4debebbf
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
5,770
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Linear natural number arithmetic preformulas in pre-normalized preform. -/ import tactic.omega.nat.preterm namespace omega namespace nat /-- Intermediate shadow syntax for LNA formulas that includes unreified exprs -/ meta inductive exprform | eq : exprterm → exprterm → exprform | le : exprterm → exprterm → exprform | not : exprform → exprform | or : exprform → exprform → exprform | and : exprform → exprform → exprform /-- Intermediate shadow syntax for LNA formulas that includes non-canonical terms -/ @[derive has_reflect, derive inhabited] inductive preform | eq : preterm → preterm → preform | le : preterm → preterm → preform | not : preform → preform | or : preform → preform → preform | and : preform → preform → preform localized "notation x ` =* ` y := omega.nat.preform.eq x y" in omega.nat localized "notation x ` ≤* ` y := omega.nat.preform.le x y" in omega.nat localized "notation `¬* ` p := omega.nat.preform.not p" in omega.nat localized "notation p ` ∨* ` q := omega.nat.preform.or p q" in omega.nat localized "notation p ` ∧* ` q := omega.nat.preform.and p q" in omega.nat namespace preform /-- Evaluate a preform into prop using the valuation `v`. -/ @[simp] def holds (v : nat → nat) : preform → Prop | (t =* s) := t.val v = s.val v | (t ≤* s) := t.val v ≤ s.val v | (¬* p) := ¬ p.holds | (p ∨* q) := p.holds ∨ q.holds | (p ∧* q) := p.holds ∧ q.holds end preform /-- `univ_close p n` := `p` closed by prepending `n` universal quantifiers -/ @[simp] def univ_close (p : preform) : (nat → nat) → nat → Prop | v 0 := p.holds v | v (k+1) := ∀ i : nat, univ_close (update_zero i v) k namespace preform /-- Argument is free of negations -/ def neg_free : preform → Prop | (t =* s) := true | (t ≤* s) := true | (p ∨* q) := neg_free p ∧ neg_free q | (p ∧* q) := neg_free p ∧ neg_free q | _ := false /-- Return expr of proof that argument is free of subtractions -/ def sub_free : preform → Prop | (t =* s) := t.sub_free ∧ s.sub_free | (t ≤* s) := t.sub_free ∧ s.sub_free | (¬* p) := p.sub_free | (p ∨* q) := p.sub_free ∧ q.sub_free | (p ∧* q) := p.sub_free ∧ q.sub_free /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preform → nat | (t =* s) := max t.fresh_index s.fresh_index | (t ≤* s) := max t.fresh_index s.fresh_index | (¬* p) := p.fresh_index | (p ∨* q) := max p.fresh_index q.fresh_index | (p ∧* q) := max p.fresh_index q.fresh_index lemma holds_constant {v w : nat → nat} : ∀ p : preform, ( (∀ x < p.fresh_index, v x = w x) → (p.holds v ↔ p.holds w) ) | (t =* s) h1 := begin simp only [holds], apply pred_mono_2; apply preterm.val_constant; intros x h2; apply h1 _ (lt_of_lt_of_le h2 _), apply le_max_left, apply le_max_right end | (t ≤* s) h1 := begin simp only [holds], apply pred_mono_2; apply preterm.val_constant; intros x h2; apply h1 _ (lt_of_lt_of_le h2 _), apply le_max_left, apply le_max_right end | (¬* p) h1 := begin apply not_iff_not_of_iff, apply holds_constant p h1 end | (p ∨* q) h1 := begin simp only [holds], apply pred_mono_2'; apply holds_constant; intros x h2; apply h1 _ (lt_of_lt_of_le h2 _), apply le_max_left, apply le_max_right end | (p ∧* q) h1 := begin simp only [holds], apply pred_mono_2'; apply holds_constant; intros x h2; apply h1 _ (lt_of_lt_of_le h2 _), apply le_max_left, apply le_max_right end /-- All valuations satisfy argument -/ def valid (p : preform) : Prop := ∀ v, holds v p /-- There exists some valuation that satisfies argument -/ def sat (p : preform) : Prop := ∃ v, holds v p /-- `implies p q` := under any valuation, `q` holds if `p` holds -/ def implies (p q : preform) : Prop := ∀ v, (holds v p → holds v q) /-- `equiv p q` := under any valuation, `p` holds iff `q` holds -/ def equiv (p q : preform) : Prop := ∀ v, (holds v p ↔ holds v q) lemma sat_of_implies_of_sat {p q : preform} : implies p q → sat p → sat q := begin intros h1 h2, apply exists_imp_exists h1 h2 end lemma sat_or {p q : preform} : sat (p ∨* q) ↔ sat p ∨ sat q := begin constructor; intro h1, { cases h1 with v h1, cases h1 with h1 h1; [left,right]; refine ⟨v,_⟩; assumption }, { cases h1 with h1 h1; cases h1 with v h1; refine ⟨v,_⟩; [left,right]; assumption } end /-- There does not exist any valuation that satisfies argument -/ def unsat (p : preform) : Prop := ¬ sat p def repr : preform → string | (t =* s) := "(" ++ t.repr ++ " = " ++ s.repr ++ ")" | (t ≤* s) := "(" ++ t.repr ++ " ≤ " ++ s.repr ++ ")" | (¬* p) := "¬" ++ p.repr | (p ∨* q) := "(" ++ p.repr ++ " ∨ " ++ q.repr ++ ")" | (p ∧* q) := "(" ++ p.repr ++ " ∧ " ++ q.repr ++ ")" instance has_repr : has_repr preform := ⟨repr⟩ meta instance has_to_format : has_to_format preform := ⟨λ x, x.repr⟩ end preform lemma univ_close_of_valid {p : preform} : ∀ {m : nat} {v : nat → nat}, p.valid → univ_close p v m | 0 v h1 := h1 _ | (m+1) v h1 := λ i, univ_close_of_valid h1 lemma valid_of_unsat_not {p : preform} : (¬*p).unsat → p.valid := begin simp only [preform.sat, preform.unsat, preform.valid, preform.holds], rw classical.not_exists_not, intro h, assumption end /-- Tactic for setting up proof by induction over preforms. -/ meta def preform.induce (t : tactic unit := tactic.skip) : tactic unit := `[ intro p, induction p with t s t s p ih p q ihp ihq p q ihp ihq; t ] end nat end omega
26a682b5b058ada81d0d31a90f988e1ecf58fb1f
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/lcnf1.lean
dc87a411fe13f78615daff5fa1d0c5bc35ad7371
[ "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
2,720
lean
import Lean open Lean #eval Compiler.compile #[``List.map] #eval Compiler.compile #[``Lean.Elab.Term.synthesizeInstMVarCore] #eval Compiler.compile #[``Eq.ndrec] def g1 (x : Nat) (h : Nat = Int) : Int := (h ▸ x) + 1 #eval Compiler.compile #[``g1] def f (h : False) (x : Nat) : Nat := (h.rec : Nat → Nat) x #eval Compiler.compile #[``f] def g (as : Array (Nat → Nat)) (h : i < as.size ∧ q) : Nat := h.casesOn (fun _ _ => as[i]) i #eval Compiler.compile #[``g] def f2 {r : Nat → Nat → Prop} (q : Quot r) : Nat := (q.lift (·+·) sorry : Nat → Nat) 2 #eval Compiler.compile #[``f2] 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 Vec.head : Vec α (n+1) → α | .cons a _ => a #eval Compiler.compile #[``Lean.Elab.Term.reportStuckSyntheticMVar] #eval Compiler.compile #[``Lean.Elab.Term.synthesizeSyntheticMVars] set_option profiler true set_option trace.Compiler.step true #eval Compiler.compile #[``Lean.Meta.isExprDefEqAuxImpl] def foo (a b : Nat) := let d := match a with | .zero => b | .succ c => c let e := match b with | .zero => a | .succ f => f Nat.add d e #eval Compiler.compile #[``foo] #eval Compiler.compile #[``Vec.zip] structure Foo where α : Sort u x : α def foo1 := Foo.mk Type Nat #eval Compiler.compile #[``foo1] def Tuple (α : Type u) : Nat → Type u | 0 => PUnit | 1 => α | n+2 => α × Tuple α (n+1) def mkConstTuple (a : α) : (n : Nat) → Tuple α n | 0 => ⟨⟩ | 1 => a | n+2 => (a, mkConstTuple a (n+1)) def Tuple.map (f : α → β) (xs : Tuple α n) : Tuple β n := match n with | 0 => ⟨⟩ | 1 => f xs | _+2 => match xs with | (a, xs) => (f a, Tuple.map f xs) def Tuple.example (a b : Nat) := Tuple.map (n := 2) (· + 1) (a, b) #eval Compiler.compile #[``mkConstTuple] #eval Compiler.compile #[``Tuple.map] #eval Compiler.compile #[``Tuple.example] def gebner1 (x : UInt64) : UInt64 := assert! x > 0; x - 1 -- set_option pp.letVarTypes true in #eval Compiler.compile #[``gebner1] def gebner2 (x : UInt64) := x &&& ((1 : UInt64) <<< 5 : UInt64) -- set_option pp.letVarTypes true in #eval Compiler.compile #[``gebner2] #eval Compiler.compile #[``Lean.Meta.instMonadMetaM] #eval Compiler.compile #[``Lean.Core.instMonadCoreM] #eval Compiler.compile #[``instMonadEIO] -- set_option pp.explicit true in #eval Compiler.compile #[``EStateM.instMonadEStateM] #eval do let some decl ← Compiler.getStage1Decl? ``List.length | throwError "not found" IO.println (← decl.toString)
d775ecd71de7edcc009d2158cb8333b1ab717483
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/algebra/infinite_sum.lean
7af2ba7247d4c6a78b15a1b871fa4537b5063b41
[ "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
61,033
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.big_operators.intervals import algebra.big_operators.nat_antidiagonal import data.equiv.encodable.lattice import topology.algebra.mul_action import topology.algebra.ordered.monotone_convergence import topology.instances.real /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators nnreal variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 -- see Note [operator precedence of big operators] notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma has_sum_empty [is_empty β] : has_sum f 0 := by convert has_sum_zero lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma summable_empty [is_empty β] : summable f := has_sum_empty.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 := by simp [tsum, h] lemma summable_congr (hfg : ∀b, f b = g b) : summable f ↔ summable g := iff_of_eq (congr_arg summable $ funext hfg) lemma summable.congr (hf : summable f) (hfg : ∀b, f b = g b) : summable g := (summable_congr hfg).mp hf lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator_subset] @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma function.injective.has_sum_range_iff {g : γ → β} (hg : injective g) : has_sum (λ x : set.range g, f x) a ↔ has_sum (f ∘ g) a := (equiv.of_injective g hg).has_sum_iff.symm lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) (g : α →+ γ) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ g.map_sum _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) (g : α →+ γ) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma equiv.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := ⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, λ ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩ variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff]) (by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp, forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_disjoint {s t : set β} (hs : disjoint s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum (f ∘ coe : s ∪ t → α) (a + b) := begin rw has_sum_subtype_iff_indicator at *, rw set.indicator_union_of_disjoint hs, exact ha.add hb end lemma has_sum.add_is_compl {s t : set β} (hs : is_compl s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum f (a + b) := by simpa [← hs.compl_eq] using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl hb lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl.symm hb lemma has_sum.even_add_odd {f : ℕ → α} (he : has_sum (λ k, f (2 * k)) a) (ho : has_sum (λ k, f (2 * k + 1)) b) : has_sum f (a + b) := begin have := mul_right_injective₀ (@two_ne_zero ℕ _ _), replace he := this.has_sum_range_iff.2 he, replace ho := ((add_left_injective 1).comp this).has_sum_range_iff.2 ho, refine he.add_is_compl _ ho, simpa [(∘)] using nat.is_compl_even_odd end lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma summable.even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : summable f := (he.has_sum.even_add_odd ho.has_sum).summable lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid α] [topological_space α] lemma tsum_congr_subtype (f : β → α) {s t : set β} (h : s = t) : ∑' (x : s), f x = ∑' (x : t), f x := by rw h variables [t2_space α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_zero : ∑'b:β, (0:α) = 0 := has_sum_zero.tsum_eq @[simp] lemma tsum_empty [is_empty β] : ∑'b, f b = 0 := has_sum_empty.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : ∑' b, f b = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_congr {α β : Type*} [add_comm_monoid α] [topological_space α] {f g : β → α} (hfg : ∀ b, f b = g b) : ∑' b, f b = ∑' b, g b := congr_arg tsum (funext hfg) lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b := (has_sum_fintype f).tsum_eq lemma tsum_bool (f : bool → α) : ∑' i : bool, f i = f false + f true := by { rw [tsum_fintype, finset.sum_eq_add]; simp } @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : ∑' x : {x // x ∈ s}, f x = ∑ x in s, f x := (s.has_sum f).tsum_eq @[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) : ∑' x : (s : set β), f x = ∑ x in s, f x := s.tsum_subtype f lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : ∑'b, f b = f b := (has_sum_single b hf).tsum_eq @[simp] lemma tsum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : ∑' b', (if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma tsum_dite_right (P : Prop) [decidable P] (x : β → ¬ P → α) : ∑' (b : β), (if h : P then (0 : α) else x b h) = if h : P then (0 : α) else ∑' (b : β), x b h := by by_cases hP : P; simp [hP] lemma tsum_dite_left (P : Prop) [decidable P] (x : β → P → α) : ∑' (b : β), (if h : P then x b h else 0) = if h : P then (∑' (b : β), x b h) else 0 := by by_cases hP : P; simp [hP] lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : ∑' b, f b = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : ∑'b, f b = ∑'c, g c := (equiv.refl α).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : ∑' x, f x = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set β) (f : β → α) : ∑' x:s, f x = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : ∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [regular_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : ∑'p, f p = ∑'b c, f (b, c) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : ∑' c b, f b c = ∑' b c, f b c := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq], refl, assumption end end has_continuous_add section encodable open encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode₂ [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode₂ γ i, s b) = ∑' b : γ, m (s b) := begin have H : ∀ n, m (⨆ b ∈ decode₂ γ n, s b) ≠ 0 → (decode₂ γ n).is_some, { intros n h, cases decode₂ γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode₂.1 (option.get_mem (H n hn)), rwa [← e, mem_decode₂.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek₂] at h ⊢, convert h, simp [set.ext_iff, encodek₂] }, { exact option.get_of_mem _ (encodek₂ _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode₂ γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode₂` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode₂ (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : ∑' i, m (⋃ b ∈ decode₂ γ i, s b) = ∑' b, m (s b) := tsum_supr_decode₂ m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i)) (s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) := by { rw [← supr_decode₂, ← tsum_supr_decode₂ _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _, rw [← finset.tsum_subtype], assumption } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end encodable variables [has_continuous_add α] lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma tsum_union_disjoint {s t : set β} (hd : disjoint s t) (hs : summable (f ∘ coe : s → α)) (ht : summable (f ∘ coe : t → α)) : (∑' x : s ∪ t, f x) = (∑' x : s, f x) + (∑' x : t, f x) := (hs.has_sum.add_disjoint hd ht.has_sum).tsum_eq lemma tsum_even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : (∑' k, f (2 * k)) + (∑' k, f (2 * k + 1)) = ∑' k, f k := (he.has_sum.even_add_odd ho.has_sum).tsum_eq.symm end tsum section prod variables [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ] lemma has_sum.prod_mk {f : β → α} {g : β → γ} {a : α} {b : γ} (hf : has_sum f a) (hg : has_sum g b) : has_sum (λ x, (⟨f x, g x⟩ : α × γ)) ⟨a, b⟩ := by simp [has_sum, ← prod_mk_sum, filter.tendsto.prod_mk_nhds hf hg] end prod section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp only [has_sum, tendsto_pi_nhds, sum_apply] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp only [summable, pi.has_sum, skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp only [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma summable.trans_sub (hg : summable g) (hfg : summable (λb, f b - g b)) : summable f := by simpa only [sub_add_cancel] using hfg.add hg lemma summable_iff_of_summable_sub (hfg : summable (λb, f b - g b)) : summable f ↔ summable g := ⟨λ hf, hf.trans_sub $ by simpa only [neg_sub] using hfg.neg, λ hg, hg.trans_sub hfg⟩ lemma has_sum.update (hf : has_sum f a₁) (b : β) [decidable_eq β] (a : α) : has_sum (update f b a) (a - f b + a₁) := begin convert ((has_sum_ite_eq b _).add hf), ext b', by_cases h : b' = b, { rw [h, update_same], simp only [eq_self_iff_true, if_true, sub_add_cancel] }, simp only [h, update_noteq, if_false, ne.def, zero_add, not_false_iff], end lemma summable.update (hf : summable f) (b : β) [decidable_eq β] (a : α) : summable (update f b a) := (hf.has_sum.update b a).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff lemma has_sum_ite_eq_extract [decidable_eq β] (hf : has_sum f a) (b : β) : has_sum (λ n, ite (n = b) 0 (f n)) (a - f b) := begin convert hf.update b 0 using 1, { ext n, rw function.update_apply, }, { rw [sub_add_eq_add_sub, zero_add], }, end section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : ∑'b, - f b = - ∑'b, f b := hf.has_sum.neg.tsum_eq lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b := (hf.has_sum.sub hg.has_sum).tsum_eq lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm /-- Let `f : β → α` be a sequence with summable series and let `b ∈ β` be an index. Lemma `tsum_ite_eq_extract` writes `Σ f n` as the sum of `f b` plus the series of the remaining terms. -/ lemma tsum_ite_eq_extract [decidable_eq β] (hf : summable f) (b : β) : ∑' n, f n = f b + ∑' n, ite (n = b) 0 (f n) := begin rw (has_sum_ite_eq_extract hf.has_sum b).tsum_eq, exact (add_sub_cancel'_right _ _).symm, end end tsum /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i := by simpa only [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : ∑'b, f b = f 0 + ∑'b, f (b + 1) := by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm /-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin by_cases hf : summable f, { have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i), { ext1 i, rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] }, have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds, simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat }, { convert tendsto_const_nhds, ext1 i, rw ← summable_nat_add_iff i at hf, { exact tsum_eq_zero_of_not_summable hf }, { apply_instance } } end end subtype end topological_group section topological_ring variables [semiring α] [topological_space α] [topological_ring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma summable.tsum_mul_left (a) (hf : summable f) : ∑'b, a * f b = a * ∑'b, f b := (hf.has_sum.mul_left _).tsum_eq lemma summable.tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq end tsum end topological_ring section const_smul variables {R : Type*} [monoid R] [topological_space R] [topological_space α] [add_comm_monoid α] [distrib_mul_action R α] [has_continuous_smul R α] {f : β → α} lemma has_sum.const_smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) := hf.map (distrib_mul_action.to_add_monoid_hom α r) (continuous_const.smul continuous_id) lemma summable.const_smul {r : R} (hf : summable f) : summable (λ z, r • f z) := hf.has_sum.const_smul.summable lemma tsum_const_smul [t2_space α] {r : R} (hf : summable f) : ∑' z, r • f z = r • ∑' z, f z := hf.has_sum.const_smul.tsum_eq end const_smul section smul_const variables {R : Type*} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [module R α] [has_continuous_smul R α] {f : β → R} lemma has_sum.smul_const {a : α} {r : R} (hf : has_sum f r) : has_sum (λ z, f z • a) (r • a) := hf.map ((smul_add_hom R α).flip a) (continuous_id.smul continuous_const) lemma summable.smul_const {a : α} (hf : summable f) : summable (λ z, f z • a) := hf.has_sum.smul_const.summable lemma tsum_smul_const [t2_space α] {a : α} (hf : summable f) : ∑' z, f z • a = (∑' z, f z) • a := hf.has_sum.smul_const.tsum_eq end smul_const section division_ring variables [division_ring α] [topological_space α] [topological_ring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.div_const (h : has_sum f a) (b : α) : has_sum (λ x, f x / b) (a / b) := by simp only [div_eq_mul_inv, h.mul_right b⁻¹] lemma summable.div_const (h : summable f) (b : α) : summable (λ x, f x / b) := (h.has_sum.div_const b).summable lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := ⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a₂⁻¹⟩ lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := ⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a⁻¹⟩ lemma tsum_mul_left [t2_space α] : (∑' x, a * f x) = a * ∑' x, f x := if hf : summable f then hf.tsum_mul_left a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_left_iff ha).2 hf), mul_zero] lemma tsum_mul_right [t2_space α] : (∑' x, f x * a) = (∑' x, f x) * a := if hf : summable f then hf.tsum_mul_right a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_right_iff ha).2 hf), zero_mul] end division_ring section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b @[mono] lemma has_sum_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f ≤ g) : a₁ ≤ a₂ := has_sum_le h hf hg lemma has_sum_le_of_sum_le (hf : has_sum f a) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : a ≤ a₂ := le_of_tendsto' hf h lemma le_has_sum_of_le_sum (hf : has_sum f a) (h : ∀ s : finset β, a₂ ≤ ∑ b in s, f b) : a₂ ≤ a := ge_of_tendsto' hf h lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ c₂ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : ∑ b in s, f b ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma is_lub_has_sum (h : ∀ b, 0 ≤ f b) (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a := is_lub_of_tendsto_at_top (finset.sum_mono_set_of_nonneg h) hf lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a := calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : ∑ b in s, f b ≤ ∑' b, f b := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : ∑'b, f b ≤ ∑'b, g b := has_sum_le h hf.has_sum hg.has_sum @[mono] lemma tsum_mono (hf : summable f) (hg : summable g) (h : f ≤ g) : ∑' n, f n ≤ ∑' n, g n := tsum_le_tsum h hf hg lemma tsum_le_of_sum_le (hf : summable f) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : ∑' b, f b ≤ a₂ := has_sum_le_of_sum_le hf.has_sum h lemma tsum_le_of_sum_le' (ha₂ : 0 ≤ a₂) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : ∑' b, f b ≤ a₂ := begin by_cases hf : summable f, { exact tsum_le_of_sum_le hf h }, { rw tsum_eq_zero_of_not_summable hf, exact ha₂ } end lemma has_sum.nonneg (h : ∀ b, 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha lemma has_sum.nonpos (h : ∀ b, g b ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ ∑'b, g b := begin by_cases hg : summable g, { exact hg.has_sum.nonneg h }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : ∑'b, f b ≤ 0 := begin by_cases hf : summable f, { exact hf.has_sum.nonpos h }, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section ordered_topological_group variables [ordered_add_comm_group α] [topological_space α] [topological_add_group α] [order_closed_topology α] {f g : β → α} {a₁ a₂ : α} lemma has_sum_lt {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ < a₂ := have update f i 0 ≤ update g i 0 := update_le_update_iff.mpr ⟨rfl.le, λ i _, h i⟩, have 0 - f i + a₁ ≤ 0 - g i + a₂ := has_sum_le this (hf.update i 0) (hg.update i 0), by simpa only [zero_sub, add_neg_cancel_left] using add_lt_add_of_lt_of_le hi this @[mono] lemma has_sum_strict_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f < g) : a₁ < a₂ := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : summable f) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi hf.has_sum hg.has_sum @[mono] lemma tsum_strict_mono (hf : summable f) (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hf hg lemma tsum_pos (hsum : summable g) (hg : ∀ b, 0 ≤ g b) (i : β) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum hg hi summable_zero hsum } lemma has_sum_zero_iff_of_nonneg (hf : ∀ i, 0 ≤ f i) : has_sum f 0 ↔ f = 0 := begin split, { intros hf', ext i, by_contra hi', have hi : 0 < f i := lt_of_le_of_ne (hf i) (ne.symm hi'), simpa using has_sum_lt hf hi has_sum_zero hf' }, { rintros rfl, exact has_sum_zero }, end end ordered_topological_group section canonically_ordered variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] variables {f : β → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b := le_tsum hf b $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (pos_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : ∑' i, f i = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] lemma tsum_ne_zero_iff (hf : summable f) : ∑' i, f i ≠ 0 ↔ ∃ x, f x ≠ 0 := by rw [ne.def, tsum_eq_zero_iff hf, not_forall] lemma is_lub_has_sum' (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a := is_lub_of_tendsto_at_top (finset.sum_mono_set f) hf end canonically_ordered section uniform_group variables [add_comm_group α] [uniform_space α] lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_of_le_left le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end local attribute [instance] topological_add_group.regular_space /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero [t1_space α] (f : β → α) : tendsto (λ (s : finset β), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin by_cases H : summable f, { assume e he, rcases nhds_is_closed he with ⟨o, ho, oe, o_closed⟩, simp only [le_eq_subset, set.mem_preimage, mem_at_top_sets, filter.mem_map, ge_iff_le], obtain ⟨s, hs⟩ : ∃ (s : finset β), ∀ (t : finset β), disjoint t s → ∑ (b : β) in t, f b ∈ o := cauchy_seq_finset_iff_vanishing.1 (tendsto.cauchy_seq H.has_sum) o ho, refine ⟨s, λ a sa, oe _⟩, have A : summable (λ b : {x // x ∉ a}, f b) := a.summable_compl_iff.2 H, apply is_closed.mem_of_tendsto o_closed A.has_sum (eventually_of_forall (λ b, _)), have : disjoint (finset.image (λ (i : {x // x ∉ a}), (i : β)) b) s, { apply disjoint_left.2 (λ i hi his, _), rcases mem_image.1 hi with ⟨i', hi', rfl⟩, exact i'.2 (sa his), }, convert hs _ this using 1, rw sum_image, assume i hi j hj hij, exact subtype.ext hij }, { convert tendsto_const_nhds, ext s, apply tsum_eq_zero_of_not_summable, rwa finset.summable_compl_iff } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [t1_space α] {f : β × γ → α} (h : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_prod' h h.prod_factor lemma tsum_comm [t1_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : ∑' c b, f b c = ∑' b c, f b c := tsum_comm' h h.prod_factor h.prod_symm.prod_factor end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (disjoint_singleton_left.2 hx) end lemma summable.tendsto_at_top_zero {f : ℕ → G} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact hf.tendsto_cofinite_zero } lemma summable.tendsto_top_of_pos {α : Type*} [linear_ordered_field α] [topological_space α] [order_topology α] {f : ℕ → α} (hf : summable f⁻¹) (hf' : ∀ n, 0 < f n) : tendsto f at_top at_top := begin rw [show f = f⁻¹⁻¹, by { ext, simp }], apply filter.tendsto.inv_tendsto_zero, apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (summable.tendsto_at_top_zero hf), rw eventually_iff_exists_mem, refine ⟨set.Ioi 0, Ioi_mem_at_top _, λ _ _, _⟩, rw [set.mem_Ioi, inv_eq_one_div, one_div, pi.inv_apply, _root_.inv_pos], exact hf' _, end end topological_group section linear_order /-! For infinite sums taking values in a linearly ordered monoid, the existence of a least upper bound for the finite sums is a criterion for summability. This criterion is useful when applied in a linearly ordered monoid which is also a complete or conditionally complete linear order, such as `ℝ`, `ℝ≥0`, `ℝ≥0∞`, because it is then easy to check the existence of a least upper bound. -/ lemma has_sum_of_is_lub_of_nonneg [linear_ordered_add_comm_monoid β] [topological_space β] [order_topology β] {f : α → β} (b : β) (h : ∀ b, 0 ≤ f b) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set_of_nonneg h) hf lemma has_sum_of_is_lub [canonically_linear_ordered_add_monoid β] [topological_space β] [order_topology β] {f : α → β} (b : β) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set f) hf lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : summable (λ x, |f x|) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, |f x| = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, |f x| = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, |f x|) ↔ summable (λ x : {x | 0 ≤ f x}, |f x|) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, |f x|) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs lemma finite_of_summable_const [linear_ordered_add_comm_group β] [archimedean β] [topological_space β] [order_closed_topology β] {b : β} (hb : 0 < b) (hf : summable (λ a : α, b)) : set.finite (set.univ : set α) := begin have H : ∀ s : finset α, s.card • b ≤ ∑' a : α, b, { intros s, simpa using sum_le_has_sum s (λ a ha, hb.le) hf.has_sum }, obtain ⟨n, hn⟩ := archimedean.arch (∑' a : α, b) hb, have : ∀ s : finset α, s.card ≤ n, { intros s, simpa [nsmul_le_nsmul_iff hb] using (H s).trans hn }, haveI : fintype α := fintype_of_finset_card_le n this, exact set.finite_univ end end linear_order section cauchy_seq open filter /-- If the extended distance between consecutive points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [pseudo_emetric_space α] {f : ℕ → α} (d : ℕ → ℝ≥0) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, add_tsub_cancel_left] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consecutive points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ |∑ x in Ico N n, d x| : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_rfl) h lemma dist_le_tsum_of_dist_le_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_rfl) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq /-! ## Multipliying two infinite sums In this section, we prove various results about `(∑' x : β, f x) * (∑' y : γ, g y)`. Note that we always assume that the family `λ x : β × γ, f x.1 * g x.2` is summable, since there is no way to deduce this from the summmabilities of `f` and `g` in general, but if you are working in a normed space, you may want to use the analogous lemmas in `analysis/normed_space/basic` (e.g `tsum_mul_tsum_of_summable_norm`). We first establish results about arbitrary index types, `β` and `γ`, and then we specialize to `β = γ = ℕ` to prove the Cauchy product formula (see `tsum_mul_tsum_eq_tsum_sum_antidiagonal`). ### Arbitrary index types -/ section tsum_mul_tsum variables [topological_space α] [regular_space α] [semiring α] [topological_ring α] {f : β → α} {g : γ → α} {s t u : α} lemma has_sum.mul_eq (hf : has_sum f s) (hg : has_sum g t) (hfg : has_sum (λ (x : β × γ), f x.1 * g x.2) u) : s * t = u := have key₁ : has_sum (λ b, f b * t) (s * t), from hf.mul_right t, have this : ∀ b : β, has_sum (λ c : γ, f b * g c) (f b * t), from λ b, hg.mul_left (f b), have key₂ : has_sum (λ b, f b * t) u, from has_sum.prod_fiberwise hfg this, key₁.unique key₂ lemma has_sum.mul (hf : has_sum f s) (hg : has_sum g t) (hfg : summable (λ (x : β × γ), f x.1 * g x.2)) : has_sum (λ (x : β × γ), f x.1 * g x.2) (s * t) := let ⟨u, hu⟩ := hfg in (hf.mul_eq hg hu).symm ▸ hu /-- Product of two infinites sums indexed by arbitrary types. See also `tsum_mul_tsum_of_summable_norm` if `f` and `g` are abolutely summable. -/ lemma tsum_mul_tsum (hf : summable f) (hg : summable g) (hfg : summable (λ (x : β × γ), f x.1 * g x.2)) : (∑' x, f x) * (∑' y, g y) = (∑' z : β × γ, f z.1 * g z.2) := hf.has_sum.mul_eq hg.has_sum hfg.has_sum end tsum_mul_tsum section cauchy_product /-! ### `ℕ`-indexed families (Cauchy product) We prove two versions of the Cauchy product formula. The first one is `tsum_mul_tsum_eq_tsum_sum_range`, where the `n`-th term is a sum over `finset.range (n+1)` involving `nat` substraction. In order to avoid `nat` substraction, we also provide `tsum_mul_tsum_eq_tsum_sum_antidiagonal`, where the `n`-th term is a sum over all pairs `(k, l)` such that `k+l=n`, which corresponds to the `finset` `finset.nat.antidiagonal n` -/ variables {f : ℕ → α} {g : ℕ → α} open finset variables [topological_space α] [semiring α] /- The family `(k, l) : ℕ × ℕ ↦ f k * g l` is summable if and only if the family `(n, k, l) : Σ (n : ℕ), nat.antidiagonal n ↦ f k * g l` is summable. -/ lemma summable_mul_prod_iff_summable_mul_sigma_antidiagonal {f g : ℕ → α} : summable (λ x : ℕ × ℕ, f x.1 * g x.2) ↔ summable (λ x : (Σ (n : ℕ), nat.antidiagonal n), f (x.2 : ℕ × ℕ).1 * g (x.2 : ℕ × ℕ).2) := nat.sigma_antidiagonal_equiv_prod.summable_iff.symm variables [regular_space α] [topological_ring α] lemma summable_sum_mul_antidiagonal_of_summable_mul {f g : ℕ → α} (h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) : summable (λ n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) := begin rw summable_mul_prod_iff_summable_mul_sigma_antidiagonal at h, conv {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]}, exact h.sigma' (λ n, (has_sum_fintype _).summable), end /-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`, expressed by summing on `finset.nat.antidiagonal`. See also `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm` if `f` and `g` are absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_antidiagonal (hf : summable f) (hg : summable g) (hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) : (∑' n, f n) * (∑' n, g n) = (∑' n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) := begin conv_rhs {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]}, rw [tsum_mul_tsum hf hg hfg, ← nat.sigma_antidiagonal_equiv_prod.tsum_eq (_ : ℕ × ℕ → α)], exact tsum_sigma' (λ n, (has_sum_fintype _).summable) (summable_mul_prod_iff_summable_mul_sigma_antidiagonal.mp hfg) end lemma summable_sum_mul_range_of_summable_mul {f g : ℕ → α} (h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) : summable (λ n, ∑ k in range (n+1), f k * g (n - k)) := begin simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact summable_sum_mul_antidiagonal_of_summable_mul h end /-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`, expressed by summing on `finset.range`. See also `tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm` if `f` and `g` are absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_range (hf : summable f) (hg : summable g) (hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) : (∑' n, f n) * (∑' n, g n) = (∑' n, ∑ k in range (n+1), f k * g (n - k)) := begin simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact tsum_mul_tsum_eq_tsum_sum_antidiagonal hf hg hfg end end cauchy_product
afa00f818cb949e4e0cf1446bbf518a68c0a013f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo2005_q4.lean
ac90ef53f0bccddf599648f2d2106895e1b08d02
[ "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
4,607
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import field_theory.finite.basic /-! # IMO 2005 Q4 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Problem: Determine all positive integers relatively prime to all the terms of the infinite sequence `a n = 2 ^ n + 3 ^ n + 6 ^ n - 1`, for `n ≥ 1`. This is quite an easy problem, in which the key point is a modular arithmetic calculation with the sequence `a n` relative to an arbitrary prime. -/ namespace imo2005_q4 /-- The sequence considered in the problem, `2 ^ n + 3 ^ n + 6 ^ n - 1`. -/ def a (n : ℕ) : ℤ := 2 ^ n + 3 ^ n + 6 ^ n - 1 /-- Key lemma (a modular arithmetic calculation): Given a prime `p` other than `2` or `3`, the `p - 2`th term of the sequence has `p` as a factor. -/ lemma find_specified_factor {p : ℕ} (hp : nat.prime p) (hp' : is_coprime (6:ℤ) p) : ↑p ∣ a (p - 2) := begin rw [← int.modeq_zero_iff_dvd], -- Since `p` and `6` are coprime, `6` has an inverse mod `p` obtain ⟨b, hb⟩ : ∃ (b : ℤ), 6 * b ≡ 1 [ZMOD p], { refine int.mod_coprime _, exact nat.is_coprime_iff_coprime.mp hp' }, -- Also since `p` is coprime to `6`, it's coprime to `2` and `3` have hp₂ : is_coprime (2:ℤ) p := (id hp' : is_coprime (3 * 2 : ℤ) p).of_mul_left_right, have hp₃ : is_coprime (3:ℤ) p := (id hp' : is_coprime (2 * 3 : ℤ) p).of_mul_left_right, -- Slightly painful nat-subtraction calculation have hp_sub_one : p - 1 = (p - 2) + 1, { have : 1 ≤ p - 1 := le_tsub_of_add_le_right hp.two_le, conv_lhs { rw ← nat.sub_add_cancel this }, refl }, -- Main calculation: `6 * a (p - 2)` is a multiple of `p` have H : (6:ℤ) * a (p - 2) ≡ 0 [ZMOD p], calc (6:ℤ) * a (p - 2) = 3 * 2 ^ (p - 1) + 2 * 3 ^ (p - 1) + 6 ^ (p - 1) - 6 : by { simp only [a, mul_add, mul_sub, hp_sub_one, pow_succ], ring, } ... ≡ 3 * 1 + 2 * 1 + 1 - 6 [ZMOD p] : -- At this step we use Fermat's little theorem by { apply_rules [int.modeq.sub_right, int.modeq.add, int.modeq.mul_left, int.modeq.pow_card_sub_one_eq_one hp] } ... = 0 : by norm_num, -- Since `6` has an inverse mod `p`, `a (p - 2)` itself is a multiple of `p` calc (a (p - 2) : ℤ) = 1 * a (p - 2) : by ring ... ≡ (6 * b) * a (p - 2) [ZMOD p] : int.modeq.mul_right _ hb.symm ... = b * (6 * a (p - 2)) : by ring ... ≡ b * 0 [ZMOD p] : int.modeq.mul_left _ H ... = 0 : by ring, end end imo2005_q4 open imo2005_q4 /-- Main statement: The only positive integer coprime to all terms of the sequence `a` is `1`. -/ theorem imo2005_q4 {k : ℕ} (hk : 0 < k) : (∀ n : ℕ, 1 ≤ n → is_coprime (a n) k) ↔ k = 1 := begin split, rotate, { -- The property is clearly true for `k = 1` rintros rfl n hn, exact is_coprime_one_right }, intros h, -- Conversely, suppose `k` is a number with the property, and let `p` be `k.min_fac` (by -- definition this is the minimal prime factor of `k` if `k ≠ 1`, and otherwise `1`. let p := k.min_fac, -- Testing the special property of `k` for `48`, the second term of the sequence, we see that `p` -- is coprime to `6`. have hp₆ : is_coprime (6:ℤ) p, { refine is_coprime.of_coprime_of_dvd_right _ (int.coe_nat_dvd.mpr k.min_fac_dvd), exact (id (h 2 one_le_two) : is_coprime (8 * 6 : ℤ) k).of_mul_left_right, }, -- In particular `p` is coprime to `2` (we record the `nat.coprime` version since that's what's -- needed later). have hp₂ : nat.coprime 2 p, { rw ← nat.is_coprime_iff_coprime, exact (id hp₆ : is_coprime (3 * 2 : ℤ) p).of_mul_left_right }, -- Suppose for the sake of contradiction that `k ≠ 1`. Then `p` is genuinely a prime factor of -- `k`. by_contra hk', have hp : nat.prime p := nat.min_fac_prime hk', -- So `3 ≤ p` have hp₃ : 3 ≤ p, { have : 2 ≠ p := by rwa nat.coprime_primes nat.prime_two hp at hp₂, apply nat.lt_of_le_and_ne hp.two_le this, }, -- Testing the special property of `k` for the `p - 2`th term of the sequence, we see that `p` is -- coprime to `a (p - 2)`. have : is_coprime ↑p (a (p - 2)), { refine ((h (p - 2) _).of_coprime_of_dvd_right (int.coe_nat_dvd.mpr k.min_fac_dvd)).symm, exact le_tsub_of_add_le_right hp₃ }, rw (nat.prime_iff_prime_int.mp hp).coprime_iff_not_dvd at this, -- But also, by our previous lemma, `p` divides `a (p - 2)`. have : ↑p ∣ a (p - 2) := find_specified_factor hp hp₆, -- Contradiction! contradiction, end
4f1295b953de64c884c3fbaee97c6ab75d14acb9
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/universal/product.lean
24d66f33d750e8cb1bea70b4a581c163b773f2d3
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
5,098
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .homomorphism import .identity namespace universal variables {τ : Type} {σ : Type*} (sig : signature τ σ) namespace algebra section pi variables {sig} {ι : Type*} (alg : ι → algebra sig) definition pi : algebra sig := { sort := λ t, Π j, (alg j).sort t , func := λ f xs j, (alg j).func f (λ i, xs i j) } @[simp] theorem pi_func (f) (xs) (j) : (pi alg).func f xs j = (alg j).func f (λ i, xs i j) := rfl definition pi_proj (j) : homomorphism (pi alg) (alg j) := { map := λ _ x, x j , func := λ _ _, rfl } theorem pi_eval {dom} : ∀ {cod} (t : term sig dom cod) (xs) (j), (pi alg).eval t xs j = (alg j).eval t (λ i, xs i j) | _ (term.proj _) _ _ := rfl | _ (term.func f ts) xs j := have (λ i, (pi alg).eval (ts i) xs j) = (λ i, (alg j).eval (ts i) (λ i, xs i j)), from funext $ λ i, pi_eval (ts i) xs j, calc _ = (alg j).func f (λ i, (pi alg).eval (ts i) xs j) : rfl ... = (alg j).func f (λ i, (alg j).eval (ts i) (λ i, xs i j)) : by rw this ... = (alg j).eval (term.func f ts) (λ i, xs i j) : by reflexivity theorem pi_satisfies (e : identity sig) : (∀ i, (alg i).satisfies e) → (pi alg).satisfies e := begin intros H val, funext, rw pi_eval, rw pi_eval, apply H, end section universal_property variables {alg} {alg₀ : algebra sig} (h : Π j, homomorphism alg₀ (alg j)) definition pi_hom : homomorphism alg₀ (pi alg) := { map := λ t x j, (h j).map t x , func := λ _ _, funext $ λ j, by simp [(h j).func] } @[simp] theorem pi_hom_proj (j) : (pi_proj alg j).comp (pi_hom h) = h j := homomorphism.ext $ λ _ _, rfl theorem pi_univ (h₀ : homomorphism alg₀ (pi alg)) : (∀ j, (pi_proj alg j).comp h₀ = h j) → h₀ = pi_hom h := λ H, homomorphism.ext $ λ t x, funext $ λ j, begin transitivity ((pi_proj alg j).comp h₀).map t x, reflexivity, rw H, reflexivity, end end universal_property end pi section prod variables {sig} (alg₁ : algebra sig) (alg₂ : algebra sig) definition prod : algebra sig := { sort := λ t, alg₁.sort t × alg₂.sort t , func := λ f xs, (alg₁.func f (λ i, (xs i).fst), alg₂.func f (λ i, (xs i).snd)) } @[simp] theorem prod_func (f) (xs) : (prod alg₁ alg₂).func f xs = (alg₁.func f (λ i, (xs i).fst), alg₂.func f (λ i, (xs i).snd)) := rfl definition prod_fst : homomorphism (prod alg₁ alg₂) alg₁ := { map := λ _, prod.fst , func := λ _ _, rfl } definition prod_snd : homomorphism (prod alg₁ alg₂) alg₂ := { map := λ _, prod.snd , func := λ _ _, rfl } theorem prod_eval {dom} : ∀ {cod} (t : term sig dom cod) (xs), (prod alg₁ alg₂).eval t xs = (alg₁.eval t (λ i, (xs i).fst), alg₂.eval t (λ i, (xs i).snd)) | _ (term.proj _) _ := prod.eq rfl rfl | _ (term.func f ts) xs := have (λ i, (prod alg₁ alg₂).eval (ts i) xs) = (λ i, (alg₁.eval (ts i) (λ i, (xs i).fst), alg₂.eval (ts i) (λ i, (xs i).snd))), from funext $ λ i, prod_eval (ts i) xs, calc (prod alg₁ alg₂).eval (term.func f ts) xs = (prod alg₁ alg₂).func f (λ i, (prod alg₁ alg₂).eval (ts i) xs) : rfl ... = (prod alg₁ alg₂).func f (λ i, (alg₁.eval (ts i) (λ i, (xs i).fst), alg₂.eval (ts i) (λ i, (xs i).snd))) : by rw this ... = (alg₁.eval (term.func f ts) (λ i, (xs i).fst), alg₂.eval (term.func f ts) (λ i, (xs i).snd)) : by reflexivity theorem prod_eval_fst {dom} {cod} (t : term sig dom cod) (xs) : ((prod alg₁ alg₂).eval t xs).fst = alg₁.eval t (λ i, (xs i).fst) := by rw prod_eval theorem prod_eval_snd {dom} {cod} (t : term sig dom cod) (xs) : ((prod alg₁ alg₂).eval t xs).snd = alg₂.eval t (λ i, (xs i).snd) := by rw prod_eval theorem prod_satisfies (e : identity sig) : alg₁.satisfies e → alg₂.satisfies e → (prod alg₁ alg₂).satisfies e := begin intros H₁ H₂ val, rw prod_eval, rw prod_eval, apply prod.eq, apply H₁, apply H₂, end section universal_property variables {alg₁ alg₂} {alg : algebra sig} (h₁ : homomorphism alg alg₁) (h₂ : homomorphism alg alg₂) include h₁ h₂ definition prod_hom : homomorphism alg (prod alg₁ alg₂) := { map := λ t x, (h₁.map t x, h₂.map t x) , func := λ f xs, prod.eq (by simp [h₁.func f]) (by simp [h₂.func f]) } @[simp] theorem prod_hom_fst : (prod_fst alg₁ alg₂).comp (prod_hom h₁ h₂) = h₁ := homomorphism.ext $ λ _ _, rfl @[simp] theorem prod_hom_snd : (prod_snd alg₁ alg₂).comp (prod_hom h₁ h₂) = h₂ := homomorphism.ext $ λ _ _, rfl theorem prod_univ (h : homomorphism alg (prod alg₁ alg₂)) : (prod_fst alg₁ alg₂).comp h = h₁ → (prod_snd alg₁ alg₂).comp h = h₂ → h = prod_hom h₁ h₂ := λ H₁ H₂, homomorphism.ext $ λ t x, prod.eq (begin transitivity ((prod_fst alg₁ alg₂).comp h).map t x, reflexivity, rw H₁, reflexivity, end) (begin transitivity ((prod_snd alg₁ alg₂).comp h).map t x, reflexivity, rw H₂, reflexivity, end) end universal_property end prod end algebra end universal
a2d66d557ee92156347a4f4c89abbde46d2ad3ee
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/init/equiv.hlean
48f936cf849d80cdf2fac5f72dbb4d5f262e492e
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
19,108
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .path .function open eq function lift /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A → B) := mk' :: (inv : B → A) (right_inv : Πb, f (inv b) = b) (left_inv : Πa, inv (f a) = a) (adj : Πx, right_inv (f x) = ap f (left_inv x)) attribute is_equiv.inv [reducible] -- A more bundled version of equivalence structure equiv (A B : Type) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix ⁻¹ := inv /- a second notation for the inverse, which is not overloaded -/ postfix [parsing_only] `⁻¹ᶠ`:std.prec.max_plus := inv section variables {A B C : Type} (g : B → C) (f : A → B) {f' : A → B} -- The variant of mk' where f is explicit. protected definition mk [constructor] := @is_equiv.mk' A B f -- The identity function is an equivalence. definition is_equiv_id [instance] [constructor] (A : Type) : (is_equiv (id : A → A)) := is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹) abstract (λc, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) end abstract (λa, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) end abstract (λa, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝ (ap_compose f (inv f) _ ◾ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose g f _)⁻¹) end -- Any function equal to an equivalence is an equivlance as well. variable {f} definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' := eq.rec_on Heq Hf end section parameters {A B : Type} (f : A → B) (g : B → A) (ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a) definition adjointify_left_inv' [unfold_full] (a : A) : g (f a) = a := ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) := let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rewrite idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !con_idp ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con, show ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con eq3 definition adjointify [constructor] : is_equiv f := is_equiv.mk f g ret adjointify_left_inv' adjointify_adj' end -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [constructor] {A B : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (Hty : f ~ f') : is_equiv f' := adjointify f' (inv f) (λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b) (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a) definition inv_homotopy_closed [constructor] {A B : Type} {f : A → B} {f' : B → A} [Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f := adjointify f f' (λ b, ap f !Hty⁻¹ ⬝ right_inv f b) (λ a, !Hty⁻¹ ⬝ left_inv f a) definition inv_homotopy_inv {A B : Type} {f g : A → B} [is_equiv f] [is_equiv g] (p : f ~ g) : f⁻¹ ~ g⁻¹ := λb, (left_inv g (f⁻¹ b))⁻¹ ⬝ ap g⁻¹ ((p (f⁻¹ b))⁻¹ ⬝ right_inv f b) definition is_equiv_up [instance] [constructor] (A : Type) : is_equiv (up : A → lift A) := adjointify up down (λa, by induction a;reflexivity) (λa, idp) section variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C) include Hf -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition is_equiv_rect (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition is_equiv_rect' (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition is_equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x := calc is_equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apdt df (left_inv f x)) theorem adj_inv (b : B) : left_inv f (f⁻¹ b) = ap f⁻¹ (right_inv f b) := is_equiv_rect f _ (λa, eq.cancel_right (left_inv f (id a)) (whisker_left _ !ap_id⁻¹ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝ !ap_compose ⬝ ap02 f⁻¹ (adj f a)⁻¹) b --The inverse of an equivalence is, again, an equivalence. definition is_equiv_inv [instance] [constructor] [priority 500] : is_equiv f⁻¹ := is_equiv.mk f⁻¹ f (left_inv f) (right_inv f) (adj_inv f) -- The 2-out-of-3 properties definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (g ∘ f) f⁻¹) (λb, ap g (@right_inv _ _ f _ b)) definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (f ∘ g)) (λa, left_inv f (g a)) definition eq_of_fn_eq_fn' [unfold 4] {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := !ap_con ⬝ whisker_right _ !ap_con ⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹) ◾ (inverse (ap_compose f f⁻¹ _)) ◾ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (right_inv f) _ _ ⬝ whisker_right _ !con.left_inv ⬝ !idp_con definition eq_of_fn_eq_fn'_ap {x y : A} (q : x = y) : eq_of_fn_eq_fn' f (ap f q) = q := by induction q; apply con.left_inv definition is_equiv_ap [instance] [constructor] (x y : A) : is_equiv (ap f : x = y → f x = f y) := adjointify (ap f) (eq_of_fn_eq_fn' f) (ap_eq_of_fn_eq_fn' f) (eq_of_fn_eq_fn'_ap f) end section variables {A B C : Type} {f : A → B} [Hf : is_equiv f] include Hf section rewrite_rules variables {a : A} {b : B} definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end rewrite_rules variable (f) section pre_compose variables (α : A → C) (β : B → C) definition homotopy_of_homotopy_inv_pre (p : β ~ α ∘ f⁻¹) : β ∘ f ~ α := λ a, p (f a) ⬝ ap α (left_inv f a) definition homotopy_of_inv_homotopy_pre (p : α ∘ f⁻¹ ~ β) : α ~ β ∘ f := λ a, (ap α (left_inv f a))⁻¹ ⬝ p (f a) definition inv_homotopy_of_homotopy_pre (p : α ~ β ∘ f) : α ∘ f⁻¹ ~ β := λ b, p (f⁻¹ b) ⬝ ap β (right_inv f b) definition homotopy_inv_of_homotopy_pre (p : β ∘ f ~ α) : β ~ α ∘ f⁻¹ := λ b, (ap β (right_inv f b))⁻¹ ⬝ p (f⁻¹ b) end pre_compose section post_compose variables (α : C → A) (β : C → B) definition homotopy_of_homotopy_inv_post (p : α ~ f⁻¹ ∘ β) : f ∘ α ~ β := λ c, ap f (p c) ⬝ (right_inv f (β c)) definition homotopy_of_inv_homotopy_post (p : f⁻¹ ∘ β ~ α) : β ~ f ∘ α := λ c, (right_inv f (β c))⁻¹ ⬝ ap f (p c) definition inv_homotopy_of_homotopy_post (p : β ~ f ∘ α) : f⁻¹ ∘ β ~ α := λ c, ap f⁻¹ (p c) ⬝ (left_inv f (α c)) definition homotopy_inv_of_homotopy_post (p : f ∘ α ~ β) : α ~ f⁻¹ ∘ β := λ c, (left_inv f (α c))⁻¹ ⬝ ap f⁻¹ (p c) end post_compose end --Transporting is an equivalence definition is_equiv_tr [constructor] {A : Type} (P : A → Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p) -- a version where the transport is a cast. Note: A and B live in the same universe here. definition is_equiv_cast [constructor] {A B : Type} (H : A = B) : is_equiv (cast H) := is_equiv_tr (λX, X) H section variables {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)] {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) include H definition inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) definition fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := eq_of_fn_eq_fn' f⁻¹ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹) definition ap_inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : ap f (inv_commute' @f @h @h' p c) = right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹ := !ap_eq_of_fn_eq_fn' -- inv_commute'_fn is in types.equiv end -- This is inv_commute' for A ≡ unit definition inv_commute1' {B C : Type} (f : B → C) [is_equiv f] (h : B → B) (h' : C → C) (p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) end is_equiv open is_equiv namespace eq local attribute is_equiv_tr [instance] definition tr_inv_fn {A : Type} {B : A → Type} {a a' : A} (p : a = a') : transport B p⁻¹ = (transport B p)⁻¹ := idp definition tr_inv {A : Type} {B : A → Type} {a a' : A} (p : a = a') (b : B a') : p⁻¹ ▸ b = (transport B p)⁻¹ b := idp definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp end eq infix ` ≃ `:25 := equiv attribute equiv.to_is_equiv [instance] namespace equiv attribute to_fun [coercion] section variables {A B C : Type} protected definition MK [reducible] [constructor] (f : A → B) (g : B → A) (right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B := equiv.mk f (adjointify f g right_inv left_inv) definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B → A := f⁻¹ definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b := right_inv f b definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a := left_inv f a protected definition rfl [refl] [constructor] : A ≃ A := equiv.mk id !is_equiv_id protected definition refl [constructor] [reducible] (A : Type) : A ≃ A := @equiv.rfl A protected definition symm [symm] [constructor] (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ !is_equiv_inv protected definition trans [trans] [constructor] (f : A ≃ B) (g : B ≃ C) : A ≃ C := equiv.mk (g ∘ f) !is_equiv_compose infixl ` ⬝e `:75 := equiv.trans postfix `⁻¹ᵉ`:(max + 1) := equiv.symm -- notation for inverse which is not overloaded abbreviation erfl [constructor] := @equiv.rfl definition to_inv_trans [reducible] [unfold_full] (f : A ≃ B) (g : B ≃ C) : to_inv (f ⬝e g) = to_fun (g⁻¹ᵉ ⬝e f⁻¹ᵉ) := idp definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B := equiv.mk f' (is_equiv.homotopy_closed f Heq) definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ ~ f') : A ≃ B := equiv.mk f (inv_homotopy_closed Heq) --rename: eq_equiv_fn_eq_fn_of_is_equiv definition eq_equiv_fn_eq [constructor] (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap --rename: eq_equiv_fn_eq_fn definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition equiv_ap [constructor] (P : A → Type) {a b : A} (p : a = b) : P a ≃ P b := equiv.mk (transport P p) !is_equiv_tr definition equiv_of_eq [constructor] {A B : Type} (p : A = B) : A ≃ B := equiv.mk (cast p) !is_equiv_tr definition equiv_of_eq_refl [reducible] [unfold_full] (A : Type) : equiv_of_eq (refl A) = equiv.refl A := idp definition eq_of_fn_eq_fn [unfold 3] (f : A ≃ B) {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition eq_of_fn_eq_fn_inv [unfold 3] (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y := (right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y definition ap_eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := ap_eq_of_fn_eq_fn' f q definition eq_of_fn_eq_fn_ap (f : A ≃ B) {x y : A} (q : x = y) : eq_of_fn_eq_fn' f (ap f q) = q := eq_of_fn_eq_fn'_ap f q definition to_inv_homotopy_inv {f g : A ≃ B} (p : f ~ g) : f⁻¹ᵉ ~ g⁻¹ᵉ := inv_homotopy_inv p --we need this theorem for the funext_of_ua proof theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ := eq.rec_on p idp definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C := equiv_of_eq p ⬝e q definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C := p ⬝e equiv_of_eq q definition equiv_lift [constructor] (A : Type) : A ≃ lift A := equiv.mk up _ definition equiv_rect (f : A ≃ B) (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition equiv_rect' (f : A ≃ B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition equiv_rect_comp (f : A ≃ B) (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apdt df (left_inv f x)) end section variables {A B : Type} (f : A ≃ B) {a : A} {b : B} definition to_eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition to_eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition to_inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition to_eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end section variables {A : Type} {B C : A → Type} (f : Π{a}, B a ≃ C a) {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) definition inv_commute (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute' @f @h @h' p c definition fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := fun_commute_of_inv_commute' @f @h @h' p b definition inv_commute1 {B C : Type} (f : B ≃ C) (h : B → B) (h' : C → C) (p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute1' (to_fun f) h h' p c end infixl ` ⬝pe `:75 := equiv_of_equiv_of_eq infixl ` ⬝ep `:75 := equiv_of_eq_of_equiv end equiv open equiv namespace is_equiv definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A ≃ B) {f' : A → B} (Hty : f ~ f') : is_equiv f' := @(homotopy_closed f) f' _ Hty end is_equiv export [unfold] equiv export [unfold] is_equiv
e5d43dce1301ea0352994338e7cd71fb7d44ef40
4fa161becb8ce7378a709f5992a594764699e268
/src/data/nat/sqrt.lean
cfd161773b815bcd6c702796670afae107e2fec2
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
7,010
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro An efficient binary implementation of a (sqrt n) function that returns s s.t. s*s ≤ n ≤ s*s + s + s -/ import data.nat.cast import init_.data.int.order namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 := have b0:_, from ne_of_gt (@pos_pow_of_pos 2 m dec_trivial), nat.mul_ne_zero b0 b0, have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [nat.sub_lt_right_iff_lt_add h₁], simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_comm, add_assoc, add_left_comm] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply nat.sub_eq_of_eq_add, rw [← add_assoc, (_ : r*r + _ = _)], exact (nat.add_sub_cancel' hl).symm, simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_assoc] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intros; simp; [exact ⟨h₁, a⟩, exact ⟨a, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, nat.pow_succ, div2_val, mul_comm, mul_left_comm]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intros, { have := sqrt_aux_is_sqrt m r h₁ a, simpa [nat.pow_succ, mul_comm, mul_assoc] }, { rw [nat.pow_succ, mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) a h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [nat.pow_succ, mul_comm, mul_left_comm] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := lt_iff_lt_of_le_iff_le le_sqrt theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, λ e, e.symm ▸ rfl⟩ theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) := ⟨λ e, e.symm ▸ sqrt_is_sqrt n, λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩ theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ := le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $ le_trans (sqrt_le_add n) $ add_le_add_right (by refine add_le_add (mul_le_mul_right _ _) _; exact le_add_right _ 2) _ theorem exists_mul_self (x : ℕ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩ end nat
abc2e992c56753b42def81d8c0e33acafc5555af
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/algebra/filter_basis.lean
9112cdc01372e2cc3721e227ce91aec1853d9de9
[ "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
15,934
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import order.filter.bases import topology.algebra.module.basic /-! # Group and ring filter bases A `group_filter_basis` is a `filter_basis` on a group with some properties relating the basis to the group structure. The main theorem is that a `group_filter_basis` on a group gives a topology on the group which makes it into a topological group with neighborhoods of the neutral element generated by the given basis. ## Main definitions and results Given a group `G` and a ring `R`: * `group_filter_basis G`: the type of filter bases that will become neighborhood of `1` for a topology on `G` compatible with the group structure * `group_filter_basis.topology`: the associated topology * `group_filter_basis.is_topological_group`: the compatibility between the above topology and the group structure * `ring_filter_basis R`: the type of filter bases that will become neighborhood of `0` for a topology on `R` compatible with the ring structure * `ring_filter_basis.topology`: the associated topology * `ring_filter_basis.is_topological_ring`: the compatibility between the above topology and the ring structure ## References * [N. Bourbaki, *General Topology*][bourbaki1966] -/ open filter set topological_space function open_locale topological_space filter pointwise universe u /-- A `group_filter_basis` on a group is a `filter_basis` satisfying some additional axioms. Example : if `G` is a topological group then the neighbourhoods of the identity are a `group_filter_basis`. Conversely given a `group_filter_basis` one can define a topology compatible with the group structure on `G`. -/ class group_filter_basis (G : Type u) [group G] extends filter_basis G := (one' : ∀ {U}, U ∈ sets → (1 : G) ∈ U) (mul' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V * V ⊆ U) (inv' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x⁻¹) ⁻¹' U) (conj' : ∀ x₀, ∀ {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x₀*x*x₀⁻¹) ⁻¹' U) /-- A `add_group_filter_basis` on an additive group is a `filter_basis` satisfying some additional axioms. Example : if `G` is a topological group then the neighbourhoods of the identity are a `add_group_filter_basis`. Conversely given a `add_group_filter_basis` one can define a topology compatible with the group structure on `G`. -/ class add_group_filter_basis (A : Type u) [add_group A] extends filter_basis A := (zero' : ∀ {U}, U ∈ sets → (0 : A) ∈ U) (add' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V + V ⊆ U) (neg' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, -x) ⁻¹' U) (conj' : ∀ x₀, ∀ {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x₀+x+-x₀) ⁻¹' U) attribute [to_additive] group_filter_basis attribute [to_additive] group_filter_basis.one' attribute [to_additive] group_filter_basis.mul' attribute [to_additive] group_filter_basis.inv' attribute [to_additive] group_filter_basis.conj' attribute [to_additive] group_filter_basis.to_filter_basis /-- `group_filter_basis` constructor in the commutative group case. -/ @[to_additive "`add_group_filter_basis` constructor in the commutative group case."] def group_filter_basis_of_comm {G : Type*} [comm_group G] (sets : set (set G)) (nonempty : sets.nonempty) (inter_sets : ∀ (x y), x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) (one : ∀ U ∈ sets, (1 : G) ∈ U) (mul : ∀ U ∈ sets, ∃ V ∈ sets, V * V ⊆ U) (inv : ∀ U ∈ sets, ∃ V ∈ sets, V ⊆ (λ x, x⁻¹) ⁻¹' U) : group_filter_basis G := { sets := sets, nonempty := nonempty, inter_sets := inter_sets, one' := one, mul' := mul, inv' := inv, conj' := λ x U U_in, ⟨U, U_in, by simp⟩ } namespace group_filter_basis variables {G : Type u} [group G] {B : group_filter_basis G} @[to_additive] instance : has_mem (set G) (group_filter_basis G) := ⟨λ s f, s ∈ f.sets⟩ @[to_additive] lemma one {U : set G} : U ∈ B → (1 : G) ∈ U := group_filter_basis.one' @[to_additive] lemma mul {U : set G} : U ∈ B → ∃ V ∈ B, V*V ⊆ U := group_filter_basis.mul' @[to_additive] lemma inv {U : set G} : U ∈ B → ∃ V ∈ B, V ⊆ (λ x, x⁻¹) ⁻¹' U := group_filter_basis.inv' @[to_additive] lemma conj : ∀ x₀, ∀ {U}, U ∈ B → ∃ V ∈ B, V ⊆ (λ x, x₀*x*x₀⁻¹) ⁻¹' U := group_filter_basis.conj' /-- The trivial group filter basis consists of `{1}` only. The associated topology is discrete. -/ @[to_additive "The trivial additive group filter basis consists of `{0}` only. The associated topology is discrete."] instance : inhabited (group_filter_basis G) := ⟨begin refine { sets := {{1}}, nonempty := singleton_nonempty _, .. }, all_goals { simp only [exists_prop, mem_singleton_iff] }, { rintros - - rfl rfl, use {1}, simp }, { simp }, { rintro - rfl, use {1}, simp }, { rintro - rfl, use {1}, simp }, { rintro x₀ - rfl, use {1}, simp } end⟩ @[to_additive] lemma prod_subset_self (B : group_filter_basis G) {U : set G} (h : U ∈ B) : U ⊆ U * U := λ x x_in, ⟨1, x, one h, x_in, one_mul x⟩ /-- The neighborhood function of a `group_filter_basis` -/ @[to_additive "The neighborhood function of a `add_group_filter_basis`"] def N (B : group_filter_basis G) : G → filter G := λ x, map (λ y, x*y) B.to_filter_basis.filter @[simp, to_additive] lemma N_one (B : group_filter_basis G) : B.N 1 = B.to_filter_basis.filter := by simp only [N, one_mul, map_id'] @[to_additive] protected lemma has_basis (B : group_filter_basis G) (x : G) : has_basis (B.N x) (λ V : set G, V ∈ B) (λ V, (λ y, x*y) '' V) := has_basis.map (λ y, x * y) to_filter_basis.has_basis /-- The topological space structure coming from a group filter basis. -/ @[to_additive "The topological space structure coming from an additive group filter basis."] def topology (B : group_filter_basis G) : topological_space G := topological_space.mk_of_nhds B.N @[to_additive] lemma nhds_eq (B : group_filter_basis G) {x₀ : G} : @nhds G (B.topology) x₀ = B.N x₀ := begin rw [topological_space.nhds_mk_of_nhds], { intros x U U_in, rw (B.has_basis x).mem_iff at U_in, rcases U_in with ⟨V, V_in, H⟩, simpa [mem_pure] using H (mem_image_of_mem _ (group_filter_basis.one V_in)), }, { intros x U U_in, rw (B.has_basis x).mem_iff at U_in, rcases U_in with ⟨V, V_in, H⟩, rcases group_filter_basis.mul V_in with ⟨W, W_in, hW⟩, use [(λ y, x*y) '' W, image_mem_map (filter_basis.mem_filter_of_mem _ W_in)], split, { rw image_subset_iff at H ⊢, exact ((B.prod_subset_self W_in).trans hW).trans H }, { rintros y ⟨t, tW, rfl⟩, rw (B.has_basis _).mem_iff, use [W, W_in], apply subset.trans _ H, clear H, rintros z ⟨w, wW, rfl⟩, exact ⟨t*w, hW (mul_mem_mul tW wW), by simp [mul_assoc]⟩ } } end @[to_additive] lemma nhds_one_eq (B : group_filter_basis G) : @nhds G (B.topology) (1 : G) = B.to_filter_basis.filter := by { rw B.nhds_eq, simp only [N, one_mul], exact map_id } @[to_additive] lemma nhds_has_basis (B : group_filter_basis G) (x₀ : G) : has_basis (@nhds G B.topology x₀) (λ V : set G, V ∈ B) (λ V, (λ y, x₀ * y) '' V) := by { rw B.nhds_eq, apply B.has_basis } @[to_additive] lemma nhds_one_has_basis (B : group_filter_basis G) : has_basis (@nhds G B.topology 1) (λ V : set G, V ∈ B) id := by { rw B.nhds_one_eq, exact B.to_filter_basis.has_basis } @[to_additive] lemma mem_nhds_one (B : group_filter_basis G) {U : set G} (hU : U ∈ B) : U ∈ @nhds G B.topology 1 := begin rw B.nhds_one_has_basis.mem_iff, exact ⟨U, hU, rfl.subset⟩ end /-- If a group is endowed with a topological structure coming from a group filter basis then it's a topological group. -/ @[to_additive, priority 100] instance is_topological_group (B : group_filter_basis G) : @topological_group G B.topology _ := begin letI := B.topology, have basis := B.nhds_one_has_basis, have basis' := basis.prod basis, refine topological_group.of_nhds_one _ _ _ _, { rw basis'.tendsto_iff basis, suffices : ∀ U ∈ B, ∃ V W, (V ∈ B ∧ W ∈ B) ∧ ∀ a b, a ∈ V → b ∈ W → a * b ∈ U, by simpa, intros U U_in, rcases mul U_in with ⟨V, V_in, hV⟩, use [V, V, V_in, V_in], intros a b a_in b_in, exact hV ⟨a, b, a_in, b_in, rfl⟩ }, { rw basis.tendsto_iff basis, intros U U_in, simpa using inv U_in }, { intro x₀, rw [nhds_eq, nhds_one_eq], refl }, { intro x₀, rw basis.tendsto_iff basis, intros U U_in, exact conj x₀ U_in } end end group_filter_basis /-- A `ring_filter_basis` on a ring is a `filter_basis` satisfying some additional axioms. Example : if `R` is a topological ring then the neighbourhoods of the identity are a `ring_filter_basis`. Conversely given a `ring_filter_basis` on a ring `R`, one can define a topology on `R` which is compatible with the ring structure. -/ class ring_filter_basis (R : Type u) [ring R] extends add_group_filter_basis R := (mul' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V * V ⊆ U) (mul_left' : ∀ (x₀ : R) {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x₀*x) ⁻¹' U) (mul_right' : ∀ (x₀ : R) {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x*x₀) ⁻¹' U) namespace ring_filter_basis variables {R : Type u} [ring R] (B : ring_filter_basis R) instance : has_mem (set R) (ring_filter_basis R) := ⟨λ s B, s ∈ B.sets⟩ lemma mul {U : set R} (hU : U ∈ B) : ∃ V ∈ B, V * V ⊆ U := mul' hU lemma mul_left (x₀ : R) {U : set R} (hU : U ∈ B) : ∃ V ∈ B, V ⊆ (λ x, x₀*x) ⁻¹' U := mul_left' x₀ hU lemma mul_right (x₀ : R) {U : set R} (hU : U ∈ B) : ∃ V ∈ B, V ⊆ (λ x, x*x₀) ⁻¹' U := mul_right' x₀ hU /-- The topology associated to a ring filter basis. It has the given basis as a basis of neighborhoods of zero. -/ def topology : topological_space R := B.to_add_group_filter_basis.topology /-- If a ring is endowed with a topological structure coming from a ring filter basis then it's a topological ring. -/ @[priority 100] instance is_topological_ring {R : Type u} [ring R] (B : ring_filter_basis R) : @topological_ring R B.topology _ := begin let B' := B.to_add_group_filter_basis, letI := B'.topology, have basis := B'.nhds_zero_has_basis, have basis' := basis.prod basis, haveI := B'.is_topological_add_group, apply topological_ring.of_add_group_of_nhds_zero, { rw basis'.tendsto_iff basis, suffices : ∀ U ∈ B', ∃ V W, (V ∈ B' ∧ W ∈ B') ∧ ∀ a b, a ∈ V → b ∈ W → a * b ∈ U, by simpa, intros U U_in, rcases B.mul U_in with ⟨V, V_in, hV⟩, use [V, V, V_in, V_in], intros a b a_in b_in, exact hV ⟨a, b, a_in, b_in, rfl⟩ }, { intro x₀, rw basis.tendsto_iff basis, intros U, simpa using B.mul_left x₀ }, { intro x₀, rw basis.tendsto_iff basis, intros U, simpa using B.mul_right x₀ }, end end ring_filter_basis /-- A `module_filter_basis` on a module is a `filter_basis` satisfying some additional axioms. Example : if `M` is a topological module then the neighbourhoods of zero are a `module_filter_basis`. Conversely given a `module_filter_basis` one can define a topology compatible with the module structure on `M`. -/ structure module_filter_basis (R M : Type*) [comm_ring R] [topological_space R] [add_comm_group M] [module R M] extends add_group_filter_basis M := (smul' : ∀ {U}, U ∈ sets → ∃ (V ∈ 𝓝 (0 : R)) (W ∈ sets), V • W ⊆ U) (smul_left' : ∀ (x₀ : R) {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x₀ • x) ⁻¹' U) (smul_right' : ∀ (m₀ : M) {U}, U ∈ sets → ∀ᶠ x in 𝓝 (0 : R), x • m₀ ∈ U) namespace module_filter_basis variables {R M : Type*} [comm_ring R] [topological_space R] [add_comm_group M] [module R M] (B : module_filter_basis R M) instance group_filter_basis.has_mem : has_mem (set M) (module_filter_basis R M) := ⟨λ s B, s ∈ B.sets⟩ lemma smul {U : set M} (hU : U ∈ B) : ∃ (V ∈ 𝓝 (0 : R)) (W ∈ B), V • W ⊆ U := B.smul' hU lemma smul_left (x₀ : R) {U : set M} (hU : U ∈ B) : ∃ V ∈ B, V ⊆ (λ x, x₀ • x) ⁻¹' U := B.smul_left' x₀ hU lemma smul_right (m₀ : M) {U : set M} (hU : U ∈ B) : ∀ᶠ x in 𝓝 (0 : R), x • m₀ ∈ U := B.smul_right' m₀ hU /-- If `R` is discrete then the trivial additive group filter basis on any `R`-module is a module filter basis. -/ instance [discrete_topology R] : inhabited (module_filter_basis R M) := ⟨{ smul' := begin rintro U (h : U ∈ {{(0 : M)}}), rw mem_singleton_iff at h, use [univ, univ_mem, {0}, rfl], rintros a ⟨x, m, -, hm, rfl⟩, simp [mem_singleton_iff.1 hm, h] end, smul_left' := begin rintro x₀ U (h : U ∈ {{(0 : M)}}), rw mem_singleton_iff at h, use [{0}, rfl], simp [h] end, smul_right' := begin rintro m₀ U (h : U ∈ {{(0 : M)}}), rw mem_singleton_iff at h, simp [h, nhds_discrete] end, ..show add_group_filter_basis M, from default }⟩ /-- The topology associated to a module filter basis on a module over a topological ring. It has the given basis as a basis of neighborhoods of zero. -/ def topology : topological_space M := B.to_add_group_filter_basis.topology /-- The topology associated to a module filter basis on a module over a topological ring. It has the given basis as a basis of neighborhoods of zero. This version gets the ring topology by unification instead of type class inference. -/ def topology' {R M : Type*} [comm_ring R] {tR : topological_space R} [add_comm_group M] [module R M] (B : module_filter_basis R M) : topological_space M := B.to_add_group_filter_basis.topology /-- If a module is endowed with a topological structure coming from a module filter basis then it's a topological module. -/ @[priority 100] instance has_continuous_smul [topological_ring R] : @has_continuous_smul R M _ _ B.topology := begin let B' := B.to_add_group_filter_basis, letI := B'.topology, have basis := B'.nhds_zero_has_basis, haveI := B'.is_topological_add_group, apply has_continuous_smul.of_nhds_zero, { rw basis.tendsto_right_iff, intros U U_in, rcases B.smul U_in with ⟨V, V_in, W, W_in, H⟩, apply mem_of_superset (prod_mem_prod V_in $ B'.mem_nhds_zero W_in), rintros ⟨v, w⟩ ⟨v_in : v ∈ V, w_in : w ∈ W⟩, exact H (set.mem_smul_of_mem v_in w_in) }, { intro m₀, rw basis.tendsto_right_iff, intros U U_in, exact B.smul_right m₀ U_in }, { intro x₀, rw basis.tendsto_right_iff, intros U U_in, rcases B.smul_left x₀ U_in with ⟨V, V_in, hV⟩, exact mem_of_superset (B'.mem_nhds_zero V_in) hV }, end /-- Build a module filter basis from compatible ring and additive group filter bases. -/ def of_bases {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] (BR : ring_filter_basis R) (BM : add_group_filter_basis M) (smul : ∀ {U}, U ∈ BM → ∃ (V ∈ BR) (W ∈ BM), V • W ⊆ U) (smul_left : ∀ (x₀ : R) {U}, U ∈ BM → ∃ V ∈ BM, V ⊆ (λ x, x₀ • x) ⁻¹' U) (smul_right : ∀ (m₀ : M) {U}, U ∈ BM → ∃ V ∈ BR, V ⊆ (λ x, x • m₀) ⁻¹' U) : @module_filter_basis R M _ BR.topology _ _ := { smul' := begin intros U U_in, rcases smul U_in with ⟨V, V_in, W, W_in, H⟩, exact ⟨V, BR.to_add_group_filter_basis.mem_nhds_zero V_in, W, W_in, H⟩ end, smul_left' := smul_left, smul_right' := begin intros m₀ U U_in, rcases smul_right m₀ U_in with ⟨V, V_in, H⟩, exact mem_of_superset (BR.to_add_group_filter_basis.mem_nhds_zero V_in) H end, ..BM } end module_filter_basis
4febb45df3c90922a96e5cdacd0e55cf2648c8d3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/ToExpr.lean
9abc4fb15d07f8f1992de3bd50bcab240e09cb23
[ "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
3,928
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.LCNF.Basic namespace Lean.Compiler.LCNF namespace ToExpr private abbrev LevelMap := FVarIdMap Nat private def _root_.Lean.FVarId.toExpr (offset : Nat) (m : LevelMap) (fvarId : FVarId) : Expr := match m.find? fvarId with | some level => .bvar (offset - level - 1) | none => .fvar fvarId private def _root_.Lean.Expr.abstract' (offset : Nat) (m : LevelMap) (e : Expr) : Expr := go offset e where go (o : Nat) (e : Expr) : Expr := match e with | .fvar fvarId => fvarId.toExpr o m | .lit .. | .const .. | .sort .. | .mvar .. | .bvar .. => e | .app f a => .app (go o f) (go o a) | .mdata k b => .mdata k (go o b) | .proj s i b => .proj s i (go o b) | .forallE n d b bi => .forallE n (go o d) (go (o+1) b) bi | .lam n d b bi => .lam n (go o d) (go (o+1) b) bi | .letE n t v b nd => .letE n (go o t) (go o v) (go (o+1) b) nd abbrev ToExprM := ReaderT Nat $ StateM LevelMap abbrev mkLambdaM (params : Array Param) (e : Expr) : ToExprM Expr := return go (← read) (← get) params.size e where go (offset : Nat) (m : LevelMap) (i : Nat) (e : Expr) : Expr := if i > 0 then let param := params[i-1]! let domain := param.type.abstract' (offset - 1) m go (offset - 1) m (i - 1) (.lam param.binderName domain e .default) else e private abbrev _root_.Lean.FVarId.toExprM (fvarId : FVarId) : ToExprM Expr := return fvarId.toExpr (← read) (← get) abbrev abstractM (e : Expr) : ToExprM Expr := return e.abstract' (← read) (← get) @[inline] def withFVar (fvarId : FVarId) (k : ToExprM α) : ToExprM α := do let offset ← read modify fun s => s.insert fvarId offset withReader (·+1) k @[inline] partial def withParams (params : Array Param) (k : ToExprM α) : ToExprM α := go 0 where @[specialize] go (i : Nat) : ToExprM α := do if h : i < params.size then withFVar params[i].fvarId (go (i+1)) else k @[inline] def run (x : ToExprM α) (offset : Nat := 0) (levelMap : LevelMap := {}) : α := x |>.run offset |>.run' levelMap @[inline] def run' (x : ToExprM α) (xs : Array FVarId) : α := let map := xs.foldl (init := {}) fun map x => map.insert x map.size run x xs.size map end ToExpr open ToExpr private def Arg.toExprM (arg : Arg) : ToExprM Expr := return arg.toExpr.abstract' (← read) (← get) mutual partial def FunDeclCore.toExprM (decl : FunDecl) : ToExprM Expr := withParams decl.params do mkLambdaM decl.params (← decl.value.toExprM) partial def Code.toExprM (code : Code) : ToExprM Expr := do match code with | .let decl k => let type ← abstractM decl.type let value ← abstractM decl.value.toExpr let body ← withFVar decl.fvarId k.toExprM return .letE decl.binderName type value body true | .fun decl k | .jp decl k => let type ← abstractM decl.type let value ← decl.toExprM let body ← withFVar decl.fvarId k.toExprM return .letE decl.binderName type value body true | .return fvarId => fvarId.toExprM | .jmp fvarId args => return mkAppN (← fvarId.toExprM) (← args.mapM Arg.toExprM) | .unreach type => return mkApp (mkConst ``lcUnreachable) (← abstractM type) | .cases c => let alts ← c.alts.mapM fun | .alt _ params k => withParams params do mkLambdaM params (← k.toExprM) | .default k => k.toExprM return mkAppN (mkConst `cases) (#[← c.discr.toExprM] ++ alts) end def Code.toExpr (code : Code) (xs : Array FVarId := #[]) : Expr := run' code.toExprM xs def FunDeclCore.toExpr (decl : FunDecl) (xs : Array FVarId := #[]) : Expr := run' decl.toExprM xs def Decl.toExpr (decl : Decl) : Expr := run do withParams decl.params do mkLambdaM decl.params (← decl.value.toExprM) end Lean.Compiler.LCNF
f23d5427d48d4d6a63e8488fab3e7d2940186082
724b37749f589c3ad15e106a1a0610240659c140
/fingerTree.lean
e4dd06223e2deae1c52563ba7b1ec4495369fa94
[ "Apache-2.0" ]
permissive
Vtec234/lean4-bits
3865b6f11edbcdf82ea3a0a89d6ac8046fc41ef9
0d9340285b208553e0e0b31acfb2c9097ff4546a
refs/heads/master
1,688,039,348,308
1,627,783,881,000
1,627,784,253,000
391,503,122
0
0
null
null
null
null
UTF-8
Lean
false
false
10,767
lean
/-! https://www.cs.tufts.edu/~nr/cs257/archive/koen-claessen/finger-trees.pdf -/ /-! Idea: normal list. -/ namespace Finger₀ inductive Seq α where | nil : Seq α | cons : α → Seq α → Seq α deriving Inhabited variable [Inhabited α] def Seq.head : Seq α → α | cons a as => a | nil => panic! "no last" def Seq.last : Seq α → α | cons a nil => a | cons a as => last as -- linear time :( | nil => panic! "no last" end Finger₀ /-! Idea: constant-time head/last via a symmetric representation. -/ namespace Finger₁ inductive Seq α where | nil : Seq α | unit : α → Seq α | more : α → Seq α → α → Seq α deriving Inhabited variable [Inhabited α] def Seq.head : Seq α → α | unit h => h | more h .. => h | nil => panic! "no head" def Seq.last : Seq α → α | unit l => l | more _ _ l => l | nil => panic! "no last" def Seq.cons (h : α) : Seq α → Seq α | unit l => more h nil l | more a as l => more h (cons a as) l -- now cons is linear | nil => unit h def Seq.snoc : Seq α → α → Seq α | unit h, l => more h nil l | more h as a, l => more h (snoc as a) l | nil, l => unit l def Seq.tail : Seq α → Seq α | unit _ => nil | more _ as l => more as.head as.tail l | nil => panic! "no tail" end Finger₁ /-! Idea: logarithmic complexity by recursively doubling the amount of values per node. -/ namespace Finger₂ inductive Seq : Type u → Type (u + 1) where | nil : Seq α | unit : α → Seq α | more : α → Seq (α × α) → α → Seq α instance : Inhabited (Seq α) := ⟨Seq.nil⟩ def Seq.cons (h : α) : Seq α → Seq α | nil => unit h | unit l => more h nil l | more a as l => more h sorry l -- now we can't represent sequences of odd length end Finger₂ /-! Idea: represent odd lengths with one/two elements in head/last positions. -/ namespace Finger₃ inductive Some α where | one : α → Some α | two : α → α → Some α inductive Seq : Type u → Type (u + 1) where | nil : Seq α | unit : α → Seq α | more : Some α → Seq (α × α) → Some α → Seq α instance : Inhabited (Seq α) := ⟨Seq.nil⟩ variable [Inhabited α] open Some def Seq.head : Seq α → α | unit h => h | more (one h) .. => h | more (two h _) .. => h | nil => panic! "no head" def Seq.last : Seq α → α | unit l => l | more _ _ (one l) => l | more _ _ (two _ l) => l | nil => panic! "no last" def Seq.cons {α : Type u} (h : α) : Seq α → Seq α | nil => unit h | unit l => more (one h) nil (one l) | more (one a) as l => more (two h a) as l | more (two a a') as l => more (one h) (cons (a, a') as) l partial def Seq.tail {α : Type u} [Inhabited α] : Seq α → Seq α | unit _ => nil | more (one _) as l => moreSnoc as l | more (two _ h) as l => more (one h) as l | nil => panic! "no tail" where moreSnoc : Seq (α × α) → Some α → Seq α | nil, (one a) => unit a | nil, (two h l) => more (one h) nil (one l) | as, ls => let (h, a) := as.head more (two h a) as.tail ls -- now we can't implement append sub-linearly because we'd need to destruct -- all pairs in `more _ as _` when odd-length sequences appear in certain places end Finger₃ /-! Idea: also allow the log-recursion base to be odd or even. -/ namespace Finger₄ inductive Some α where | one (a : α) | two (a b : α) deriving Inhabited inductive Tuple α where | pair (a b : α) | triple (a b c : α) deriving Inhabited inductive Seq : Type u → Type (u + 1) where | nil : Seq α | unit : α → Seq α | more : Some α → Seq (Tuple α) → Some α → Seq α instance : Inhabited (Seq α) := ⟨Seq.nil⟩ variable [Inhabited α] open Some Tuple def Seq.head : Seq α → α | unit h => h | more (one h) .. => h | more (two h _) .. => h | nil => panic! "no head" def Seq.last : Seq α → α | unit l => l | more _ _ (one l) => l | more _ _ (two _ l) => l | nil => panic! "no last" def Seq.cons {α : Type u} (h : α) : Seq α → Seq α | nil => unit h | unit l => more (one h) nil (one l) | more (one a) as l => more (two h a) as l | more (two a a') as l => more (one h) (cons (pair a a') as) l def Seq.snoc {α : Type u} (s : Seq α) (l : α) : Seq α := match s with | nil => unit l | unit h => more (one h) nil (one l) | more hs as (one a) => more hs as (two a l) | more hs as (two a' a) => more hs (snoc as (pair a' a)) (one l) partial def Seq.tail {α : Type u} [Inhabited α] : Seq α → Seq α | unit _ => nil | more (one _) as l => moreSnoc as l | more (two _ h) as l => more (one h) as l | nil => panic! "no tail" where moreSnoc : Seq (Tuple α) → Some α → Seq α | nil, (one a) => unit a | nil, (two h l) => more (one h) nil (one l) | as, ls => match as.head with | pair h a => more (two h a) as.tail ls | triple h a b => more (one h) (map1 chop as) ls map1 {α : Type u} (f : α → α) : Seq α → Seq α | nil => nil | unit h => unit (f h) | more (one h) as ls => more (one $ f h) as ls | more (two h a) as ls => more (two (f h) a) as ls chop : Tuple α → Tuple α | triple a b c => pair b c | pair a b => unreachable! def Some.toList : Some α → List α | one a => [a] | two a b => [a, b] private def toTuples : List α → List (Tuple α) | [] => [] | [a, b] => [pair a b] | [a, b, c] => [triple a b c] | [a, b, c, d] => [pair a b, pair c d] | [a, b, c, d, e] => [triple a b c, pair d e] | [a, b, c, d, e, f] => [triple a b c, triple d e f] | _ => unreachable! private def Seq.glue {α : Type u} : Seq α → List α → Seq α → Seq α | nil, as, s₂ => as.foldr Seq.cons s₂ | s₁, as, nil => as.foldl Seq.snoc s₁ | unit h, as, s₂ => (h :: as).foldr Seq.cons s₂ | s₁, as, unit l => (as ++ [l]).foldl Seq.snoc s₁ | more hs₁ s₁ ls₁, as, more hs₂ s₂ ls₂ => more hs₁ (glue s₁ (toTuples (ls₁.toList ++ as ++ hs₂.toList)) s₂) ls₂ def append : Seq α → Seq α → Seq α | as, bs => Seq.glue as [] bs end Finger₄ /-! Idea: add a *third* possible head/last length so that there are cases in which neither cons nor tail needs to recurse, resulting in amortized constant-time complexity. -/ namespace Finger₅ inductive Some α where | one (a : α) | two (a b : α) | three (a b c : α) deriving Inhabited inductive Tuple α where | pair (a b : α) | triple (a b c : α) deriving Inhabited inductive Seq : Type u → Type (u + 1) where | nil : Seq α | unit : α → Seq α | more : Some α → Seq (Tuple α) → Some α → Seq α instance : Inhabited (Seq α) := ⟨Seq.nil⟩ variable [Inhabited α] open Some Tuple def Seq.head : Seq α → α | unit h => h | more (one h) .. => h | more (two h ..) .. => h | more (three h ..) .. => h | nil => panic! "no head" def Seq.last : Seq α → α | unit l => l | more _ _ (one l) => l | more _ _ (two _ l) => l | more _ _ (three _ _ l) => l | nil => panic! "no last" def Seq.cons {α : Type u} (h : α) : Seq α → Seq α | nil => unit h | unit l => more (one h) nil (one l) | more (one a) as l => more (two h a) as l | more (two a b) as l => more (three h a b) as l | more (three a b c) as l => more (two h a) (cons (pair b c) as) l def Seq.snoc {α : Type u} (s : Seq α) (l : α) : Seq α := match s with | nil => unit l | unit h => more (one h) nil (one l) | more hs as (one a) => more hs as (two a l) | more hs as (two a b) => more hs as (three a b l) | more hs as (three a b c) => more hs (snoc as (pair a b)) (two c l) partial def Seq.tail {α : Type u} [Inhabited α] : Seq α → Seq α | unit _ => nil | more (one _) as l => moreSnoc as l | more (two _ h) as l => more (one h) as l | more (three _ h a) as l => more (two h a) as l | nil => panic! "no tail" where moreSnoc : Seq (Tuple α) → Some α → Seq α | nil, (one a) => unit a | nil, (two h l) => more (one h) nil (one l) | nil, (three h a l) => more (one h) nil (two a l) | as, ls => match as.head with | pair h a => more (two h a) as.tail ls | triple h a b => more (one h) (map1 chop as) ls map1 {α : Type u} (f : α → α) : Seq α → Seq α | nil => nil | unit h => unit (f h) | more (one h) as ls => more (one $ f h) as ls | more (two h a) as ls => more (two (f h) a) as ls | more (three h a b) as ls => more (three (f h) a b) as ls chop : Tuple α → Tuple α | triple a b c => pair b c | pair a b => unreachable! def Some.toList : Some α → List α | one a => [a] | two a b => [a, b] | three a b c => [a, b, c] -- TODO(WN): unrolled but unclear if needed -- TODO(WN): subtype proofs of in.length ∈ [2,9] and out.length ∈ [1,3] private def toTuples : List α → List (Tuple α) | [] => [] | [a, b] => [pair a b] | [a, b, c] => [triple a b c] | [a, b, c, d] => [pair a b, pair c d] | [a, b, c, d, e] => [triple a b c, pair d e] | [a, b, c, d, e, f] => [triple a b c, triple d e f] | [a, b, c, d, e, f, g] => [triple a b c, pair d e, pair f g] | [a, b, c, d, e, f, g, h] => [triple a b c, triple d e f, pair g h] | [a, b, c, d, e, f, g, h, i] => [triple a b c, triple d e f, triple g h i] | _ => unreachable! private def Seq.glue {α : Type u} : Seq α → List α → Seq α → Seq α | nil, as, s₂ => as.foldr Seq.cons s₂ | s₁, as, nil => as.foldl Seq.snoc s₁ | unit h, as, s₂ => (h :: as).foldr Seq.cons s₂ | s₁, as, unit l => (as ++ [l]).foldl Seq.snoc s₁ | more hs₁ s₁ ls₁, as, more hs₂ s₂ ls₂ => more hs₁ (glue s₁ (toTuples (ls₁.toList ++ as ++ hs₂.toList)) s₂) ls₂ instance : Append (Seq α) := ⟨fun as bs => Seq.glue as [] bs⟩ end Finger₅
37c0d34572583296d94ababfa103b3fe4885300f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/equiv_rw.lean
0617d9d45f1c31706c154c5eb1dcbf1f9a29b14a
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
12,096
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.simp_result import tactic.clear import control.equiv_functor.instances /-! # The `equiv_rw` tactic transports goals or hypotheses along equivalences. The basic syntax is `equiv_rw e`, where `e : α ≃ β` is an equivalence. This will try to replace occurrences of `α` in the goal with `β`, for example transforming * `⊢ α` to `⊢ β`, * `⊢ option α` to `⊢ option β` * `⊢ {a // P}` to `{b // P (⇑(equiv.symm e) b)}` The tactic can also be used to rewrite hypotheses, using the syntax `equiv_rw e at h`. ## Implementation details The main internal function is `equiv_rw_type e t`, which attempts to turn an expression `e : α ≃ β` into a new equivalence with left hand side `t`. As an example, with `t = option α`, it will generate `functor.map_equiv option e`. This is achieved by generating a new synthetic goal `%%t ≃ _`, and calling `solve_by_elim` with an appropriate set of congruence lemmas. To avoid having to specify the relevant congruence lemmas by hand, we mostly rely on `equiv_functor.map_equiv` and `bifunctor.map_equiv` along with some structural congruence lemmas such as * `equiv.arrow_congr'`, * `equiv.subtype_equiv_of_subtype'`, * `equiv.sigma_congr_left'`, and * `equiv.Pi_congr_left'`. The main `equiv_rw` function, when operating on the goal, simply generates a new equivalence `e'` with left hand side matching the target, and calls `apply e'.inv_fun`. When operating on a hypothesis `x : α`, we introduce a new fact `h : x = e.symm (e x)`, revert this, and then attempt to `generalize`, replacing all occurrences of `e x` with a new constant `y`, before `intro`ing and `subst`ing `h`, and renaming `y` back to `x`. ## Future improvements In a future PR I anticipate that `derive equiv_functor` should work on many examples, (internally using `transport`, which is in turn based on `equiv_rw`) and we can incrementally bootstrap the strength of `equiv_rw`. An ambitious project might be to add `equiv_rw!`, a tactic which, when failing to find appropriate `equiv_functor` instances, attempts to `derive` them on the spot. For now `equiv_rw` is entirely based on `equiv`, but the framework can readily be generalised to also work with other types of equivalences, for example specific notations such as ring equivalence (`≃+*`), or general categorical isomorphisms (`≅`). This will allow us to transport across more general types of equivalences, but this will wait for another subsequent PR. -/ namespace tactic /-- A list of lemmas used for constructing congruence equivalences. -/ -- Although this looks 'hard-coded', in fact the lemma `equiv_functor.map_equiv` -- allows us to extend `equiv_rw` simply by constructing new instance so `equiv_functor`. -- TODO: We should also use `category_theory.functorial` and `category_theory.hygienic` instances. -- (example goal: we could rewrite along an isomorphism of rings (either as `R ≅ S` or `R ≃+* S`) -- and turn an `x : mv_polynomial σ R` into an `x : mv_polynomial σ S`.). meta def equiv_congr_lemmas : list (tactic expr) := [ `equiv.of_iff, -- TODO decide what to do with this; it's an equiv_bifunctor? `equiv.equiv_congr, -- The function arrow is technically a bifunctor `Typeᵒᵖ → Type → Type`, -- but the pattern matcher will never see this. `equiv.arrow_congr', -- Allow rewriting in subtypes: `equiv.subtype_equiv_of_subtype', -- Allow rewriting in the first component of a sigma-type: `equiv.sigma_congr_left', -- Allow rewriting ∀s: -- (You might think that repeated application of `equiv.forall_congr' -- would handle the higher arity cases, but unfortunately unification is not clever enough.) `equiv.forall₃_congr', `equiv.forall₂_congr', `equiv.forall_congr', -- Allow rewriting in argument of Pi types: `equiv.Pi_congr_left', -- Handles `sum` and `prod`, and many others: `bifunctor.map_equiv, -- Handles `list`, `option`, `unique`, and many others: `equiv_functor.map_equiv, -- We have to filter results to ensure we don't cheat and use exclusively -- `equiv.refl` and `iff.refl`! `equiv.refl, `iff.refl ].map (λ n, mk_const n) declare_trace equiv_rw_type /-- Configuration structure for `equiv_rw`. * `max_depth` bounds the search depth for equivalences to rewrite along. The default value is 10. (e.g., if you're rewriting along `e : α ≃ β`, and `max_depth := 2`, you can rewrite `option (option α))` but not `option (option (option α))`. -/ meta structure equiv_rw_cfg := (max_depth : ℕ := 10) /-- Implementation of `equiv_rw_type`, using `solve_by_elim`. Expects a goal of the form `t ≃ _`, and tries to solve it using `eq : α ≃ β` and congruence lemmas. -/ meta def equiv_rw_type_core (eq : expr) (cfg : equiv_rw_cfg) : tactic unit := do /- We now call `solve_by_elim` to try to generate the requested equivalence. There are a few subtleties! * We make sure that `eq` is the first lemma, so it is applied whenever possible. * In `equiv_congr_lemmas`, we put `equiv.refl` last so it is only used when it is not possible to descend further. * Since some congruence lemmas generate subgoals with `∀` statements, we use the `pre_apply` subtactic of `solve_by_elim` to preprocess each new goal with `intros`. -/ solve_by_elim { use_symmetry := false, use_exfalso := false, lemma_thunks := some (pure eq :: equiv_congr_lemmas), ctx_thunk := pure [], max_depth := cfg.max_depth, -- Subgoals may contain function types, -- and we want to continue trying to construct equivalences after the binders. pre_apply := tactic.intros >> skip, backtrack_all_goals := tt, -- If solve_by_elim gets stuck, make sure it isn't because there's a later `≃` or `↔` goal -- that we should still attempt. discharger := `[success_if_fail { match_target _ ≃ _ }] >> `[success_if_fail { match_target _ ↔ _ }] >> (`[show _ ≃ _] <|> `[show _ ↔ _]) <|> trace_if_enabled `equiv_rw_type "Failed, no congruence lemma applied!" >> failed, -- We use the `accept` tactic in `solve_by_elim` to provide tracing. accept := λ goals, lock_tactic_state (do when_tracing `equiv_rw_type (do goals.mmap pp >>= λ goals, trace format!"So far, we've built: {goals}"), done <|> when_tracing `equiv_rw_type (do gs ← get_goals, gs ← gs.mmap (λ g, infer_type g >>= pp), trace format!"Attempting to adapt to {gs}")) } /-- `equiv_rw_type e t` rewrites the type `t` using the equivalence `e : α ≃ β`, returning a new equivalence `t ≃ t'`. -/ meta def equiv_rw_type (eqv : expr) (ty : expr) (cfg : equiv_rw_cfg) : tactic expr := do when_tracing `equiv_rw_type (do ty_pp ← pp ty, eqv_pp ← pp eqv, eqv_ty_pp ← infer_type eqv >>= pp, trace format!"Attempting to rewrite the type `{ty_pp}` using `{eqv_pp} : {eqv_ty_pp}`."), `(_ ≃ _) ← infer_type eqv | fail format!"{eqv} must be an `equiv`", -- We prepare a synthetic goal of type `(%%ty ≃ _)`, for some placeholder right hand side. equiv_ty ← to_expr ``(%%ty ≃ _), -- Now call `equiv_rw_type_core`. new_eqv ← prod.snd <$> (solve_aux equiv_ty $ equiv_rw_type_core eqv cfg), -- Check that we actually used the equivalence `eq` -- (`equiv_rw_type_core` will always find `equiv.refl`, -- but hopefully only after all other possibilities) new_eqv ← instantiate_mvars new_eqv, -- We previously had `guard (eqv.occurs new_eqv)` here, but `kdepends_on` is more reliable. kdepends_on new_eqv eqv >>= guardb <|> (do eqv_pp ← pp eqv, ty_pp ← pp ty, fail format!"Could not construct an equivalence from {eqv_pp} of the form: {ty_pp} ≃ _"), -- Finally we simplify the resulting equivalence, -- to compress away some `map_equiv equiv.refl` subexpressions. prod.fst <$> new_eqv.simp {fail_if_unchanged := ff} mk_simp_attribute equiv_rw_simp "The simpset `equiv_rw_simp` is used by the tactic `equiv_rw` to simplify applications of equivalences and their inverses." attribute [equiv_rw_simp] equiv.symm_symm equiv.apply_symm_apply equiv.symm_apply_apply /-- Attempt to replace the hypothesis with name `x` by transporting it along the equivalence in `e : α ≃ β`. -/ meta def equiv_rw_hyp (x : name) (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit := -- We call `dsimp_result` to perform the beta redex introduced by `revert` dsimp_result (do x' ← get_local x, x_ty ← infer_type x', -- Adapt `e` to an equivalence with left-hand-side `x_ty`. e ← equiv_rw_type e x_ty cfg, eq ← to_expr ``(%%x' = equiv.symm %%e (equiv.to_fun %%e %%x')), prf ← to_expr ``((equiv.symm_apply_apply %%e %%x').symm), h ← note_anon eq prf, -- Revert the new hypothesis, so it is also part of the goal. revert h, ex ← to_expr ``(equiv.to_fun %%e %%x'), -- Now call `generalize`, -- attempting to replace all occurrences of `e x`, -- calling it for now `j : β`, with `k : x = e.symm j`. generalize ex (by apply_opt_param) transparency.none, -- Reintroduce `x` (now of type `b`), and the hypothesis `h`. intro x, h ← intro1, -- Finally, if we're working on properties, substitute along `h`, then do some cleanup, -- and if we're working on data, just throw out the old `x`. b ← target >>= is_prop, if b then do subst h, `[try { simp only with equiv_rw_simp }] else -- We may need to unfreeze `x` before we can `clear` it. unfreezing_hyp x' (clear' tt [x']) <|> fail format!"equiv_rw expected to be able to clear the original hypothesis {x}, but couldn't.", skip) {fail_if_unchanged := ff} tt -- call `dsimp_result` with `no_defaults := tt`. /-- Rewrite the goal using an equiv `e`. -/ meta def equiv_rw_target (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit := do t ← target, e ← equiv_rw_type e t cfg, s ← to_expr ``(equiv.inv_fun %%e), tactic.eapply s, skip end tactic namespace tactic.interactive open lean.parser open interactive interactive.types open tactic local postfix `?`:9001 := optional /-- `equiv_rw e at h`, where `h : α` is a hypothesis, and `e : α ≃ β`, will attempt to transport `h` along `e`, producing a new hypothesis `h : β`, with all occurrences of `h` in other hypotheses and the goal replaced with `e.symm h`. `equiv_rw e` will attempt to transport the goal along an equivalence `e : α ≃ β`. In its minimal form it replaces the goal `⊢ α` with `⊢ β` by calling `apply e.inv_fun`. `equiv_rw` will also try rewriting under (equiv_)functors, so can turn a hypothesis `h : list α` into `h : list β` or a goal `⊢ unique α` into `⊢ unique β`. The maximum search depth for rewriting in subexpressions is controlled by `equiv_rw e {max_depth := n}`. -/ meta def equiv_rw (e : parse texpr) (loc : parse $ (tk "at" *> ident)?) (cfg : equiv_rw_cfg := {}) : itactic := do e ← to_expr e, match loc with | (some hyp) := equiv_rw_hyp hyp e cfg | none := equiv_rw_target e cfg end add_tactic_doc { name := "equiv_rw", category := doc_category.tactic, decl_names := [`tactic.interactive.equiv_rw], tags := ["rewriting", "equiv", "transport"] } /-- Solve a goal of the form `t ≃ _`, by constructing an equivalence from `e : α ≃ β`. This is the same equivalence that `equiv_rw` would use to rewrite a term of type `t`. A typical usage might be: ``` have e' : option α ≃ option β := by equiv_rw_type e ``` -/ meta def equiv_rw_type (e : parse texpr) (cfg : equiv_rw_cfg := {}) : itactic := do `(%%t ≃ _) ← target | fail "`equiv_rw_type` solves goals of the form `t ≃ _`.", e ← to_expr e, tactic.equiv_rw_type e t cfg >>= tactic.exact add_tactic_doc { name := "equiv_rw_type", category := doc_category.tactic, decl_names := [`tactic.interactive.equiv_rw_type], tags := ["rewriting", "equiv", "transport"] } end tactic.interactive
1dd93c954d940ddbe85bc917769098c396695879
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/elab8.lean
f53fed16db68d71d3ba2871d4c896544e0b105b8
[ "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
276
lean
set_option pp.notation false set_option pp.implicit true set_option pp.numerals false set_option pp.binder_types true variables (A : Type*) [has_add A] [has_one A] [has_lt A] (a : A) #check a + 1 #check λ (H : a > 1), a + 1 #check λ (H₁ : a > 1) (H₂ : a < 5), a + 1
88e4ea126fbdaee60c4c13ff5592ba34b461b022
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/eigenvectors/complex_adjoint.lean
3be374cac8d0417eaa878c467592843b0b5e0334
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
7,352
lean
import eigenvectors.hermitian_form -- import missing_mathlib.linear_algebra.basic noncomputable theory open_locale classical variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] variables {I : R ≃+* Rᵒᵖ} {H : hermitian_form R M I} namespace linear_map def has_adjoint (F G : M →ₗ[R] M) (H : hermitian_form R M I) : Prop := ∀ x y, H (F x) y = H x (G y) lemma has_adjoint_def {F G : M →ₗ[R] M} (hG : F.has_adjoint G H) : ∀ x y, H (F x) y = H x (G y) := hG lemma has_adjoint_symm {F G : M →ₗ[R] M} : F.has_adjoint G H ↔ G.has_adjoint F H := begin unfold has_adjoint, split, repeat { intros h x y, rw [←H.comm y _, ←H.comm _ x, h y x], } end lemma has_adjoint_unique_left {F F' G : M →ₗ[R] M} (hF : has_adjoint F G) (hF' : has_adjoint F' G) : F = F' := begin ext, rw ←sub_eq_zero, apply inner_product_space.definite, simp only [inner_sub_left, inner_sub_right], simp [has_adjoint_def hF, has_adjoint_def hF'] end lemma has_adjoint_unique_right {F G G' : V →ₗ[ℝ] V} (hG : has_adjoint F G) (hG' : has_adjoint F G') : G = G' := begin rw has_adjoint_symm at *, apply has_adjoint_unique_left hG hG' end lemma has_adjoint_zero : has_adjoint (0 : V →ₗ[ℝ] V) 0 := by simp [has_adjoint, linear_map.zero_apply, inner_zero_left, inner_zero_right] lemma has_adjoint_id : has_adjoint (id : V →ₗ[ℝ] V) id := by simp [has_adjoint, linear_map.id_apply] lemma has_adjoint_smul {F G : V →ₗ[ℝ] V} (c : ℝ) : has_adjoint F G → has_adjoint (c • F) (c • G) := by simp [has_adjoint, inner_smul_left, inner_smul_right] {contextual := tt} lemma has_adjoint_neg {F G : V →ₗ[ℝ] V} : has_adjoint F G → has_adjoint (- F) (- G) := begin rw ← neg_one_smul _ F, rw ← neg_one_smul _ G, apply has_adjoint_smul (-1), end lemma has_adjoint_add {F G F' G' : V →ₗ[ℝ] V} : has_adjoint F G → has_adjoint F' G' → has_adjoint (F + F') (G + G') := by simp [has_adjoint, inner_add_left, inner_add_right] {contextual := tt} lemma has_adjoint_sub {F G F' G' : V →ₗ[ℝ] V} : has_adjoint F G → has_adjoint F' G' → has_adjoint (F - F') (G - G') := by simp [has_adjoint, inner_add_left, inner_add_right] {contextual := tt} def adjoint (F : V →ₗ[ℝ] V) : V →ₗ[ℝ] V := if h : ∃ G, has_adjoint F G then classical.some h else 0 lemma adjoint_of_has_adjoint {F G : V →ₗ[ℝ] V} (hF : has_adjoint F G) : F.adjoint = G := begin apply has_adjoint_unique_right _ hF, rw [adjoint, dif_pos], apply classical.some_spec ⟨G, hF⟩, end lemma has_adjoint_adjoint {F : V →ₗ[ℝ] V} (h : ∃ G, has_adjoint F G) : has_adjoint F (adjoint F) := begin rcases h with ⟨w, hw⟩, rw adjoint_of_has_adjoint hw, apply hw, end lemma inner_adjoint {F : V →ₗ[ℝ] V} (h : ∃ G, has_adjoint F G) : ∀ x y, inner (F x) y = inner x (F.adjoint y) := has_adjoint_def (has_adjoint_adjoint h) lemma adjoint_adjoint {F : V →ₗ[ℝ] V} (h : ∃ G, has_adjoint F G) : F.adjoint.adjoint = F := begin rw adjoint_of_has_adjoint, rw has_adjoint_symm, apply has_adjoint_adjoint h, end lemma adjoint_zero : (0 : V →ₗ[ℝ] V).adjoint = 0 := adjoint_of_has_adjoint has_adjoint_zero lemma adjoint_id : (id : V →ₗ[ℝ] V).adjoint = id := adjoint_of_has_adjoint has_adjoint_id lemma adjoint_smul (c : ℝ) (F : V →ₗ[ℝ] V) (h : ∃ G, has_adjoint F G) : (c • F).adjoint = c • F.adjoint := adjoint_of_has_adjoint (has_adjoint_smul c (has_adjoint_adjoint h)) lemma adjoint_neg (F : V →ₗ[ℝ] V) (h : ∃ G, has_adjoint F G) : (- F).adjoint = - F.adjoint := adjoint_of_has_adjoint (has_adjoint_neg (has_adjoint_adjoint h)) lemma adjoint_add (F G : V →ₗ[ℝ] V) (hF : ∃ F', has_adjoint F F') (hG : ∃ G', has_adjoint G G'): (F + G).adjoint = F.adjoint + G.adjoint := adjoint_of_has_adjoint (has_adjoint_add (has_adjoint_adjoint hF) (has_adjoint_adjoint hG)) lemma adjoint_sub (F G : V →ₗ[ℝ] V) (hF : ∃ F', has_adjoint F F') (hG : ∃ G', has_adjoint G G'): (F - G).adjoint = F.adjoint - G.adjoint := adjoint_of_has_adjoint (has_adjoint_sub (has_adjoint_adjoint hF) (has_adjoint_adjoint hG)) def normal (F : V →ₗ[ℝ] V) : Prop := ∃ G, has_adjoint F G ∧ F.comp G = G.comp F lemma has_adjoint_of_normal {F : V →ₗ[ℝ] V} (h : normal F) : ∃ G, has_adjoint F G := begin unfold normal at h, rcases h with ⟨w, hw⟩, use w, apply hw.left, end lemma adjoint_comm_of_normal {F : V →ₗ[ℝ] V} (h : normal F) : F.comp F.adjoint = F.adjoint.comp F := begin unfold normal at h, rcases h with ⟨w, hw⟩, rw adjoint_of_has_adjoint hw.left, apply hw.right, end lemma normal_adjoint_of_normal {F : V →ₗ[ℝ] V} (h : normal F) : normal F.adjoint := begin use F, split, { rw has_adjoint_symm, apply has_adjoint_adjoint (has_adjoint_of_normal h) }, { rw adjoint_comm_of_normal h }, end lemma normal_of_has_adjoint_self {F : V →ₗ[ℝ] V} (h : has_adjoint F F) : normal F := ⟨F, ⟨h, rfl⟩⟩ lemma normal_zero : normal (0 : V →ₗ[ℝ] V) := normal_of_has_adjoint_self has_adjoint_zero lemma normal_id : normal (id : V →ₗ[ℝ] V) := normal_of_has_adjoint_self has_adjoint_id lemma normal_smul_of_normal {F : V →ₗ[ℝ] V} (c : ℝ) (h : normal F) : normal (c • F) := begin rcases h with ⟨G, hG_adjoint, hG_comm⟩, refine ⟨c • G, ⟨has_adjoint_smul c hG_adjoint, _⟩⟩, simp only [comp_smul, smul_comp, hG_comm] end lemma normal_neg_of_normal {F : V →ₗ[ℝ] V} (h : normal F) : normal (- F) := begin rw ← neg_one_smul _ F, apply normal_smul_of_normal (-1) h, end lemma normal_sub_algebra_map_of_normal {F G : V →ₗ[ℝ] V} (c : ℝ) (hF : normal F) : normal (F - algebra_map _ c) := begin rcases hF with ⟨G, hG_adjoint, hG_comm⟩, refine ⟨G - algebra_map _ c, ⟨has_adjoint_sub hG_adjoint (has_adjoint_smul c has_adjoint_id), _⟩⟩, simp only [comp_eq_mul] at *, simp [add_mul, mul_add, hG_comm, algebra.commutes] end lemma inner_adjoint_eq_inner_of_normal {F : V →ₗ[ℝ] V} (h : normal F) : ∀ x, inner (F.adjoint x) (F.adjoint x) = inner (F x) (F x) := begin intros x, rw inner_adjoint (has_adjoint_of_normal h), rw ←comp_apply, rw ←inner_adjoint (has_adjoint_of_normal h), rw ←comp_apply, rw adjoint_comm_of_normal h, apply inner_comm end lemma ker_adjoint_of_normal {F : V →ₗ[ℝ] V} (h : normal F) : F.adjoint.ker = F.ker := begin ext, rw [mem_ker, ←inner_self_eq_zero, inner_adjoint_eq_inner_of_normal h, mem_ker, ←inner_self_eq_zero], end lemma ker_pow_eq_ker_of_normal {F : V →ₗ[ℝ] V} (k : ℕ) (hn : normal F) : (F ^ k.succ).ker = F.ker := begin induction k with k ih, { refl }, { ext, split, { assume h : x ∈ ker (F ^ k.succ.succ), have h0 : F.adjoint ((F ^ k.succ) x) = 0, { rw [mem_ker, pow_succ, mul_app, ←mem_ker, ←ker_adjoint_of_normal hn, mem_ker] at h, exact h }, show x ∈ ker F, by rw [←ih, mem_ker, ←inner_self_eq_zero, pow_succ, mul_app, inner_adjoint (has_adjoint_of_normal hn), ←mul_app F, ←pow_succ, h0, inner_zero_right] }, { intro h, rw [mem_ker] at *, rw [pow_succ', mul_app, h, map_zero] } } end end linear_map
5ff32e0faeb6432a374539f13550908902a4261d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/structure.lean
2d47702d931628e35cd2b431e7b644ad730b5728
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,262
lean
import Lean open Lean structure S1 := (x y : Nat) structure S2 extends S1 := (z : Nat) structure S3 := (w : Nat) structure S4 extends S2, S3 := (s : Nat) def check (b : Bool) : CoreM Unit := unless b do throwError "check failed" class S5 := (x y : Nat) inductive D | mk (x y z : Nat) : D def tst : CoreM Unit := do let env ← getEnv IO.println (getStructureFields env `Lean.Environment) check $ getStructureFields env `S4 == #[`toS2, `toS3, `s] check $ getStructureFields env `S1 == #[`x, `y] check $ isSubobjectField? env `S4 `toS2 == some `S2 check $ getParentStructures env `S4 == #[`S2, `S3] check $ findField? env `S4 `x == some `S1 check $ findField? env `S4 `x1 == none check $ isStructure env `S1 check $ isStructure env `S2 check $ isStructure env `S3 check $ isStructure env `S4 check $ isStructure env `S5 check $ !isStructure env `Nat check $ !isStructure env `D IO.println (getStructureFieldsFlattened env `S4) IO.println (getStructureFields env `D) IO.println (getPathToBaseStructure? env `S1 `S4) IO.println (getParentStructures env `S4) IO.println (getAllParentStructures env `S4) check $ getPathToBaseStructure? env `S1 `S4 == some [`S4.toS2, `S2.toS1] pure () #eval tst
e60c40eb14d14e9bc5849f6a45ced3101d5bff81
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/covering/besicovitch.lean
186470555d8a252c408f468be879ce5cf9c8f696
[ "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
60,361
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.covering.differentiation import measure_theory.covering.vitali_family import measure_theory.integral.lebesgue import measure_theory.measure.regular import set_theory.ordinal.arithmetic import topology.metric_space.basic /-! # Besicovitch covering theorems The topological Besicovitch covering theorem ensures that, in a nice metric space, there exists a number `N` such that, from any family of balls with bounded radii, one can extract `N` families, each made of disjoint balls, covering together all the centers of the initial family. By "nice metric space", we mean a technical property stated as follows: there exists no satellite configuration of `N + 1` points (with a given parameter `τ > 1`). Such a configuration is a family of `N + 1` balls, where the first `N` balls all intersect the last one, but none of them contains the center of another one and their radii are controlled. This property is for instance satisfied by finite-dimensional real vector spaces. In this file, we prove the topological Besicovitch covering theorem, in `besicovitch.exist_disjoint_covering_families`. The measurable Besicovitch theorem ensures that, in the same class of metric spaces, if at every point one considers a class of balls of arbitrarily small radii, called admissible balls, then one can cover almost all the space by a family of disjoint admissible balls. It is deduced from the topological Besicovitch theorem, and proved in `besicovitch.exists_disjoint_closed_ball_covering_ae`. This implies that balls of small radius form a Vitali family in such spaces. Therefore, theorems on differentiation of measures hold as a consequence of general results. We restate them in this context to make them more easily usable. ## Main definitions and results * `satellite_config α N τ` is the type of all satellite configurations of `N + 1` points in the metric space `α`, with parameter `τ`. * `has_besicovitch_covering` is a class recording that there exist `N` and `τ > 1` such that there is no satellite configuration of `N + 1` points with parameter `τ`. * `exist_disjoint_covering_families` is the topological Besicovitch covering theorem: from any family of balls one can extract finitely many disjoint subfamilies covering the same set. * `exists_disjoint_closed_ball_covering` is the measurable Besicovitch covering theorem: from any family of balls with arbitrarily small radii at every point, one can extract countably many disjoint balls covering almost all the space. While the value of `N` is relevant for the precise statement of the topological Besicovitch theorem, it becomes irrelevant for the measurable one. Therefore, this statement is expressed using the `Prop`-valued typeclass `has_besicovitch_covering`. We also restate the following specialized versions of general theorems on differentiation of measures: * `besicovitch.ae_tendsto_rn_deriv` ensures that `ρ (closed_ball x r) / μ (closed_ball x r)` tends almost surely to the Radon-Nikodym derivative of `ρ` with respect to `μ` at `x`. * `besicovitch.ae_tendsto_measure_inter_div` states that almost every point in an arbitrary set `s` is a Lebesgue density point, i.e., `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` tends to `1` as `r` tends to `0`. A stronger version for measurable sets is given in `besicovitch.ae_tendsto_measure_inter_div_of_measurable_set`. ## Implementation #### Sketch of proof of the topological Besicovitch theorem: We choose balls in a greedy way. First choose a ball with maximal radius (or rather, since there is no guarantee the maximal radius is realized, a ball with radius within a factor `τ` of the supremum). Then, remove all balls whose center is covered by the first ball, and choose among the remaining ones a ball with radius close to maximum. Go on forever until there is no available center (this is a transfinite induction in general). Then define inductively a coloring of the balls. A ball will be of color `i` if it intersects already chosen balls of color `0`, ..., `i - 1`, but none of color `i`. In this way, balls of the same color form a disjoint family, and the space is covered by the families of the different colors. The nontrivial part is to show that at most `N` colors are used. If one needs `N + 1` colors, consider the first time this happens. Then the corresponding ball intersects `N` balls of the different colors. Moreover, the inductive construction ensures that the radii of all the balls are controlled: they form a satellite configuration with `N + 1` balls (essentially by definition of satellite configurations). Since we assume that there are no such configurations, this is a contradiction. #### Sketch of proof of the measurable Besicovitch theorem: From the topological Besicovitch theorem, one can find a disjoint countable family of balls covering a proportion `> 1 / (N + 1)` of the space. Taking a large enough finite subset of these balls, one gets the same property for finitely many balls. Their union is closed. Therefore, any point in the complement has around it an admissible ball not intersecting these finitely many balls. Applying again the topological Besicovitch theorem, one extracts from these a disjoint countable subfamily covering a proportion `> 1 / (N + 1)` of the remaining points, and then even a disjoint finite subfamily. Then one goes on again and again, covering at each step a positive proportion of the remaining points, while remaining disjoint from the already chosen balls. The union of all these balls is the desired almost everywhere covering. -/ noncomputable theory universe u open metric set filter fin measure_theory topological_space open_locale topological_space classical big_operators ennreal measure_theory nnreal /-! ### Satellite configurations -/ /-- A satellite configuration is a configuration of `N+1` points that shows up in the inductive construction for the Besicovitch covering theorem. It depends on some parameter `τ ≥ 1`. This is a family of balls (indexed by `i : fin N.succ`, with center `c i` and radius `r i`) such that the last ball intersects all the other balls (condition `inter`), and given any two balls there is an order between them, ensuring that the first ball does not contain the center of the other one, and the radius of the second ball can not be larger than the radius of the first ball (up to a factor `τ`). This order corresponds to the order of choice in the inductive construction: otherwise, the second ball would have been chosen before. This is the condition `h`. Finally, the last ball is chosen after all the other ones, meaning that `h` can be strengthened by keeping only one side of the alternative in `hlast`. -/ structure besicovitch.satellite_config (α : Type*) [metric_space α] (N : ℕ) (τ : ℝ) := (c : fin N.succ → α) (r : fin N.succ → ℝ) (rpos : ∀ i, 0 < r i) (h : ∀ i j, i ≠ j → (r i ≤ dist (c i) (c j) ∧ r j ≤ τ * r i) ∨ (r j ≤ dist (c j) (c i) ∧ r i ≤ τ * r j)) (hlast : ∀ i < last N, r i ≤ dist (c i) (c (last N)) ∧ r (last N) ≤ τ * r i) (inter : ∀ i < last N, dist (c i) (c (last N)) ≤ r i + r (last N)) /-- A metric space has the Besicovitch covering property if there exist `N` and `τ > 1` such that there are no satellite configuration of parameter `τ` with `N+1` points. This is the condition that guarantees that the measurable Besicovitch covering theorem holds. It is satified by finite-dimensional real vector spaces. -/ class has_besicovitch_covering (α : Type*) [metric_space α] : Prop := (no_satellite_config [] : ∃ (N : ℕ) (τ : ℝ), 1 < τ ∧ is_empty (besicovitch.satellite_config α N τ)) /-- There is always a satellite configuration with a single point. -/ instance {α : Type*} {τ : ℝ} [inhabited α] [metric_space α] : inhabited (besicovitch.satellite_config α 0 τ) := ⟨{ c := default, r := λ i, 1, rpos := λ i, zero_lt_one, h := λ i j hij, (hij (subsingleton.elim i j)).elim, hlast := λ i hi, by { rw subsingleton.elim i (last 0) at hi, exact (lt_irrefl _ hi).elim }, inter := λ i hi, by { rw subsingleton.elim i (last 0) at hi, exact (lt_irrefl _ hi).elim } }⟩ namespace besicovitch namespace satellite_config variables {α : Type*} [metric_space α] {N : ℕ} {τ : ℝ} (a : satellite_config α N τ) lemma inter' (i : fin N.succ) : dist (a.c i) (a.c (last N)) ≤ a.r i + a.r (last N) := begin rcases lt_or_le i (last N) with H|H, { exact a.inter i H }, { have I : i = last N := top_le_iff.1 H, have := (a.rpos (last N)).le, simp only [I, add_nonneg this this, dist_self] } end lemma hlast' (i : fin N.succ) (h : 1 ≤ τ) : a.r (last N) ≤ τ * a.r i := begin rcases lt_or_le i (last N) with H|H, { exact (a.hlast i H).2 }, { have : i = last N := top_le_iff.1 H, rw this, exact le_mul_of_one_le_left (a.rpos _).le h } end end satellite_config /-! ### Extracting disjoint subfamilies from a ball covering -/ /-- A ball package is a family of balls in a metric space with positive bounded radii. -/ structure ball_package (β : Type*) (α : Type*) := (c : β → α) (r : β → ℝ) (rpos : ∀ b, 0 < r b) (r_bound : ℝ) (r_le : ∀ b, r b ≤ r_bound) /-- The ball package made of unit balls. -/ def unit_ball_package (α : Type*) : ball_package α α := { c := id, r := λ _, 1, rpos := λ _, zero_lt_one, r_bound := 1, r_le := λ _, le_rfl } instance (α : Type*) : inhabited (ball_package α α) := ⟨unit_ball_package α⟩ /-- A Besicovitch tau-package is a family of balls in a metric space with positive bounded radii, together with enough data to proceed with the Besicovitch greedy algorithm. We register this in a single structure to make sure that all our constructions in this algorithm only depend on one variable. -/ structure tau_package (β : Type*) (α : Type*) extends ball_package β α := (τ : ℝ) (one_lt_tau : 1 < τ) instance (α : Type*) : inhabited (tau_package α α) := ⟨{ τ := 2, one_lt_tau := one_lt_two, .. unit_ball_package α }⟩ variables {α : Type*} [metric_space α] {β : Type u} namespace tau_package variables [nonempty β] (p : tau_package β α) include p /-- Choose inductively large balls with centers that are not contained in the union of already chosen balls. This is a transfinite induction. -/ noncomputable def index : ordinal.{u} → β | i := -- `Z` is the set of points that are covered by already constructed balls let Z := ⋃ (j : {j // j < i}), ball (p.c (index j)) (p.r (index j)), -- `R` is the supremum of the radii of balls with centers not in `Z` R := supr (λ b : {b : β // p.c b ∉ Z}, p.r b) in -- return an index `b` for which the center `c b` is not in `Z`, and the radius is at -- least `R / τ`, if such an index exists (and garbage otherwise). classical.epsilon (λ b : β, p.c b ∉ Z ∧ R ≤ p.τ * p.r b) using_well_founded {dec_tac := `[exact j.2]} /-- The set of points that are covered by the union of balls selected at steps `< i`. -/ def Union_up_to (i : ordinal.{u}) : set α := ⋃ (j : {j // j < i}), ball (p.c (p.index j)) (p.r (p.index j)) lemma monotone_Union_up_to : monotone p.Union_up_to := begin assume i j hij, simp only [Union_up_to], exact Union_mono' (λ r, ⟨⟨r, r.2.trans_le hij⟩, subset.rfl⟩), end /-- Supremum of the radii of balls whose centers are not yet covered at step `i`. -/ def R (i : ordinal.{u}) : ℝ := supr (λ b : {b : β // p.c b ∉ p.Union_up_to i}, p.r b) /-- Group the balls into disjoint families, by assigning to a ball the smallest color for which it does not intersect any already chosen ball of this color. -/ noncomputable def color : ordinal.{u} → ℕ | i := let A : set ℕ := ⋃ (j : {j // j < i}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty), {color j} in Inf (univ \ A) using_well_founded {dec_tac := `[exact j.2]} /-- `p.last_step` is the first ordinal where the construction stops making sense, i.e., `f` returns garbage since there is no point left to be chosen. We will only use ordinals before this step. -/ def last_step : ordinal.{u} := Inf {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b} lemma last_step_nonempty : {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b}.nonempty := begin by_contra, suffices H : function.injective p.index, from not_injective_of_ordinal p.index H, assume x y hxy, wlog x_le_y : x ≤ y := le_total x y using [x y, y x], rcases eq_or_lt_of_le x_le_y with rfl|H, { refl }, simp only [nonempty_def, not_exists, exists_prop, not_and, not_lt, not_le, mem_set_of_eq, not_forall] at h, specialize h y, have A : p.c (p.index y) ∉ p.Union_up_to y, { have : p.index y = classical.epsilon (λ b : β, p.c b ∉ p.Union_up_to y ∧ p.R y ≤ p.τ * p.r b), by { rw [tau_package.index], refl }, rw this, exact (classical.epsilon_spec h).1 }, simp only [Union_up_to, not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, subtype.exists, subtype.coe_mk] at A, specialize A x H, simp [hxy] at A, exact (lt_irrefl _ ((p.rpos (p.index y)).trans_le A)).elim end /-- Every point is covered by chosen balls, before `p.last_step`. -/ lemma mem_Union_up_to_last_step (x : β) : p.c x ∈ p.Union_up_to p.last_step := begin have A : ∀ (z : β), p.c z ∈ p.Union_up_to p.last_step ∨ p.τ * p.r z < p.R p.last_step, { have : p.last_step ∈ {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b} := Inf_mem p.last_step_nonempty, simpa only [not_exists, mem_set_of_eq, not_and_distrib, not_le, not_not_mem] }, by_contra, rcases A x with H|H, { exact h H }, have Rpos : 0 < p.R p.last_step, { apply lt_trans (mul_pos (_root_.zero_lt_one.trans p.one_lt_tau) (p.rpos _)) H }, have B : p.τ⁻¹ * p.R p.last_step < p.R p.last_step, { conv_rhs { rw ← one_mul (p.R p.last_step) }, exact mul_lt_mul (inv_lt_one p.one_lt_tau) le_rfl Rpos zero_le_one }, obtain ⟨y, hy1, hy2⟩ : ∃ (y : β), p.c y ∉ p.Union_up_to p.last_step ∧ (p.τ)⁻¹ * p.R p.last_step < p.r y, { simpa only [exists_prop, mem_range, exists_exists_and_eq_and, subtype.exists, subtype.coe_mk] using exists_lt_of_lt_cSup _ B, rw [← image_univ, nonempty_image_iff], exact ⟨⟨_, h⟩, mem_univ _⟩ }, rcases A y with Hy|Hy, { exact hy1 Hy }, { rw ← div_eq_inv_mul at hy2, have := (div_le_iff' (_root_.zero_lt_one.trans p.one_lt_tau)).1 hy2.le, exact lt_irrefl _ (Hy.trans_le this) } end /-- If there are no configurations of satellites with `N+1` points, one never uses more than `N` distinct families in the Besicovitch inductive construction. -/ lemma color_lt {i : ordinal.{u}} (hi : i < p.last_step) {N : ℕ} (hN : is_empty (satellite_config α N p.τ)) : p.color i < N := begin /- By contradiction, consider the first ordinal `i` for which one would have `p.color i = N`. Choose for each `k < N` a ball with color `k` that intersects the ball at color `i` (there is such a ball, otherwise one would have used the color `k` and not `N`). Then this family of `N+1` balls forms a satellite configuration, which is forbidden by the assumption `hN`. -/ induction i using ordinal.induction with i IH, let A : set ℕ := ⋃ (j : {j // j < i}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty), {p.color j}, have color_i : p.color i = Inf (univ \ A), by rw [color], rw color_i, have N_mem : N ∈ univ \ A, { simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, mem_closed_ball, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk], assume j ji hj, exact (IH j ji (ji.trans hi)).ne' }, suffices : Inf (univ \ A) ≠ N, { rcases (cInf_le (order_bot.bdd_below (univ \ A)) N_mem).lt_or_eq with H|H, { exact H }, { exact (this H).elim } }, assume Inf_eq_N, have : ∀ k, k < N → ∃ j, j < i ∧ (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty ∧ k = p.color j, { assume k hk, rw ← Inf_eq_N at hk, have : k ∈ A, by simpa only [true_and, mem_univ, not_not, mem_diff] using nat.not_mem_of_lt_Inf hk, simp at this, simpa only [exists_prop, mem_Union, mem_singleton_iff, mem_closed_ball, subtype.exists, subtype.coe_mk] }, choose! g hg using this, -- Choose for each `k < N` an ordinal `G k < i` giving a ball of color `k` intersecting -- the last ball. let G : ℕ → ordinal := λ n, if n = N then i else g n, have color_G : ∀ n, n ≤ N → p.color (G n) = n, { assume n hn, unfreezingI { rcases hn.eq_or_lt with rfl|H }, { simp only [G], simp only [color_i, Inf_eq_N, if_true, eq_self_iff_true] }, { simp only [G], simp only [H.ne, (hg n H).right.right.symm, if_false] } }, have G_lt_last : ∀ n, n ≤ N → G n < p.last_step, { assume n hn, unfreezingI { rcases hn.eq_or_lt with rfl|H }, { simp only [G], simp only [hi, if_true, eq_self_iff_true], }, { simp only [G], simp only [H.ne, (hg n H).left.trans hi, if_false] } }, have fGn : ∀ n, n ≤ N → p.c (p.index (G n)) ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r (p.index (G n)), { assume n hn, have: p.index (G n) = classical.epsilon (λ t, p.c t ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r t), by { rw index, refl }, rw this, have : ∃ t, p.c t ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r t, by simpa only [not_exists, exists_prop, not_and, not_lt, not_le, mem_set_of_eq, not_forall] using not_mem_of_lt_cInf (G_lt_last n hn) (order_bot.bdd_below _), exact classical.epsilon_spec this }, -- the balls with indices `G k` satisfy the characteristic property of satellite configurations. have Gab : ∀ (a b : fin (nat.succ N)), G a < G b → p.r (p.index (G a)) ≤ dist (p.c (p.index (G a))) (p.c (p.index (G b))) ∧ p.r (p.index (G b)) ≤ p.τ * p.r (p.index (G a)), { assume a b G_lt, have ha : (a : ℕ) ≤ N := nat.lt_succ_iff.1 a.2, have hb : (b : ℕ) ≤ N := nat.lt_succ_iff.1 b.2, split, { have := (fGn b hb).1, simp only [Union_up_to, not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, subtype.exists, subtype.coe_mk] at this, simpa only [dist_comm, mem_ball, not_lt] using this (G a) G_lt }, { apply le_trans _ (fGn a ha).2, have B : p.c (p.index (G b)) ∉ p.Union_up_to (G a), { assume H, exact (fGn b hb).1 (p.monotone_Union_up_to G_lt.le H) }, let b' : {t // p.c t ∉ p.Union_up_to (G a)} := ⟨p.index (G b), B⟩, apply @le_csupr _ _ _ (λ t : {t // p.c t ∉ p.Union_up_to (G a)}, p.r t) _ b', refine ⟨p.r_bound, λ t ht, _⟩, simp only [exists_prop, mem_range, subtype.exists, subtype.coe_mk] at ht, rcases ht with ⟨u, hu⟩, rw ← hu.2, exact p.r_le _ } }, -- therefore, one may use them to construct a satellite configuration with `N+1` points let sc : satellite_config α N p.τ := { c := λ k, p.c (p.index (G k)), r := λ k, p.r (p.index (G k)), rpos := λ k, p.rpos (p.index (G k)), h := begin assume a b a_ne_b, wlog G_le : G a ≤ G b := le_total (G a) (G b) using [a b, b a] tactic.skip, { have G_lt : G a < G b, { rcases G_le.lt_or_eq with H|H, { exact H }, have A : (a : ℕ) ≠ b := fin.coe_injective.ne a_ne_b, rw [← color_G a (nat.lt_succ_iff.1 a.2), ← color_G b (nat.lt_succ_iff.1 b.2), H] at A, exact (A rfl).elim }, exact or.inl (Gab a b G_lt) }, { assume a_ne_b, rw or_comm, exact this a_ne_b.symm } end, hlast := begin assume a ha, have I : (a : ℕ) < N := ha, have : G a < G (fin.last N), by { dsimp [G], simp [I.ne, (hg a I).1] }, exact Gab _ _ this, end, inter := begin assume a ha, have I : (a : ℕ) < N := ha, have J : G (fin.last N) = i, by { dsimp [G], simp only [if_true, eq_self_iff_true], }, have K : G a = g a, { dsimp [G], simp [I.ne, (hg a I).1] }, convert dist_le_add_of_nonempty_closed_ball_inter_closed_ball (hg _ I).2.1, end }, -- this is a contradiction exact (hN.false : _) sc end end tau_package open tau_package /-- The topological Besicovitch covering theorem: there exist finitely many families of disjoint balls covering all the centers in a package. More specifically, one can use `N` families if there are no satellite configurations with `N+1` points. -/ theorem exist_disjoint_covering_families {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : is_empty (satellite_config α N τ)) (q : ball_package β α) : ∃ s : fin N → set β, (∀ (i : fin N), (s i).pairwise_disjoint (λ j, closed_ball (q.c j) (q.r j))) ∧ (range q.c ⊆ ⋃ (i : fin N), ⋃ (j ∈ s i), ball (q.c j) (q.r j)) := begin -- first exclude the trivial case where `β` is empty (we need non-emptiness for the transfinite -- induction, to be able to choose garbage when there is no point left). casesI is_empty_or_nonempty β, { refine ⟨λ i, ∅, λ i, pairwise_disjoint_empty, _⟩, rw [← image_univ, eq_empty_of_is_empty (univ : set β)], simp }, -- Now, assume `β` is nonempty. let p : tau_package β α := { τ := τ, one_lt_tau := hτ, .. q }, -- we use for `s i` the balls of color `i`. let s := λ (i : fin N), ⋃ (k : ordinal.{u}) (hk : k < p.last_step) (h'k : p.color k = i), ({p.index k} : set β), refine ⟨s, λ i, _, _⟩, { -- show that balls of the same color are disjoint assume x hx y hy x_ne_y, obtain ⟨jx, jx_lt, jxi, rfl⟩ : ∃ (jx : ordinal), jx < p.last_step ∧ p.color jx = i ∧ x = p.index jx, by simpa only [exists_prop, mem_Union, mem_singleton_iff] using hx, obtain ⟨jy, jy_lt, jyi, rfl⟩ : ∃ (jy : ordinal), jy < p.last_step ∧ p.color jy = i ∧ y = p.index jy, by simpa only [exists_prop, mem_Union, mem_singleton_iff] using hy, wlog jxy : jx ≤ jy := le_total jx jy using [jx jy, jy jx] tactic.skip, swap, { assume h1 h2 h3 h4 h5 h6 h7, rw [function.on_fun, disjoint.comm], exact this h4 h5 h6 h1 h2 h3 h7.symm }, replace jxy : jx < jy, by { rcases lt_or_eq_of_le jxy with H|rfl, { exact H }, { exact (x_ne_y rfl).elim } }, let A : set ℕ := ⋃ (j : {j // j < jy}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index jy)) (p.r (p.index jy))).nonempty), {p.color j}, have color_j : p.color jy = Inf (univ \ A), by rw [tau_package.color], have : p.color jy ∈ univ \ A, { rw color_j, apply Inf_mem, refine ⟨N, _⟩, simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk], assume k hk H, exact (p.color_lt (hk.trans jy_lt) hN).ne' }, simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk] at this, specialize this jx jxy, contrapose! this, simpa only [jxi, jyi, and_true, eq_self_iff_true, ← not_disjoint_iff_nonempty_inter] }, { -- show that the balls of color at most `N` cover every center. refine range_subset_iff.2 (λ b, _), obtain ⟨a, ha⟩ : ∃ (a : ordinal), a < p.last_step ∧ dist (p.c b) (p.c (p.index a)) < p.r (p.index a), by simpa only [Union_up_to, exists_prop, mem_Union, mem_ball, subtype.exists, subtype.coe_mk] using p.mem_Union_up_to_last_step b, simp only [exists_prop, mem_Union, mem_ball, mem_singleton_iff, bUnion_and', exists_eq_left, Union_exists, exists_and_distrib_left], exact ⟨⟨p.color a, p.color_lt ha.1 hN⟩, a, rfl, ha⟩ } end /-! ### The measurable Besicovitch covering theorem -/ open_locale nnreal variables [second_countable_topology α] [measurable_space α] [opens_measurable_space α] /-- Consider, for each `x` in a set `s`, a radius `r x ∈ (0, 1]`. Then one can find finitely many disjoint balls of the form `closed_ball x (r x)` covering a proportion `1/(N+1)` of `s`, if there are no satellite configurations with `N+1` points. -/ lemma exist_finset_disjoint_balls_large_measure (μ : measure α) [is_finite_measure μ] {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : is_empty (satellite_config α N τ)) (s : set α) (r : α → ℝ) (rpos : ∀ x ∈ s, 0 < r x) (rle : ∀ x ∈ s, r x ≤ 1) : ∃ (t : finset α), (↑t ⊆ s) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) ≤ N/(N+1) * μ s ∧ (t : set α).pairwise_disjoint (λ x, closed_ball x (r x)) := begin -- exclude the trivial case where `μ s = 0`. rcases le_or_lt (μ s) 0 with hμs|hμs, { have : μ s = 0 := le_bot_iff.1 hμs, refine ⟨∅, by simp only [finset.coe_empty, empty_subset], _, _⟩, { simp only [this, diff_empty, Union_false, Union_empty, nonpos_iff_eq_zero, mul_zero] }, { simp only [finset.coe_empty, pairwise_disjoint_empty], } }, casesI is_empty_or_nonempty α, { simp only [eq_empty_of_is_empty s, measure_empty] at hμs, exact (lt_irrefl _ hμs).elim }, have Npos : N ≠ 0, { unfreezingI { rintros rfl }, inhabit α, exact (not_is_empty_of_nonempty _) hN }, -- introduce a measurable superset `o` with the same measure, for measure computations obtain ⟨o, so, omeas, μo⟩ : ∃ (o : set α), s ⊆ o ∧ measurable_set o ∧ μ o = μ s := exists_measurable_superset μ s, /- We will apply the topological Besicovitch theorem, giving `N` disjoint subfamilies of balls covering `s`. Among these, one of them covers a proportion at least `1/N` of `s`. A large enough finite subfamily will then cover a proportion at least `1/(N+1)`. -/ let a : ball_package s α := { c := λ x, x, r := λ x, r x, rpos := λ x, rpos x x.2, r_bound := 1, r_le := λ x, rle x x.2 }, rcases exist_disjoint_covering_families hτ hN a with ⟨u, hu, hu'⟩, have u_count : ∀ i, (u i).countable, { assume i, refine (hu i).countable_of_nonempty_interior (λ j hj, _), have : (ball (j : α) (r j)).nonempty := nonempty_ball.2 (a.rpos _), exact this.mono ball_subset_interior_closed_ball }, let v : fin N → set α := λ i, ⋃ (x : s) (hx : x ∈ u i), closed_ball x (r x), have : ∀ i, measurable_set (v i) := λ i, measurable_set.bUnion (u_count i) (λ b hb, measurable_set_closed_ball), have A : s = ⋃ (i : fin N), s ∩ v i, { refine subset.antisymm _ (Union_subset (λ i, inter_subset_left _ _)), assume x hx, obtain ⟨i, y, hxy, h'⟩ : ∃ (i : fin N) (i_1 : ↥s) (i : i_1 ∈ u i), x ∈ ball ↑i_1 (r ↑i_1), { have : x ∈ range a.c, by simpa only [subtype.range_coe_subtype, set_of_mem_eq], simpa only [mem_Union] using hu' this }, refine mem_Union.2 ⟨i, ⟨hx, _⟩⟩, simp only [v, exists_prop, mem_Union, set_coe.exists, exists_and_distrib_right, subtype.coe_mk], exact ⟨y, ⟨y.2, by simpa only [subtype.coe_eta]⟩, ball_subset_closed_ball h'⟩ }, have S : ∑ (i : fin N), μ s / N ≤ ∑ i, μ (s ∩ v i) := calc ∑ (i : fin N), μ s / N = μ s : begin simp only [finset.card_fin, finset.sum_const, nsmul_eq_mul], rw ennreal.mul_div_cancel', { simp only [Npos, ne.def, nat.cast_eq_zero, not_false_iff] }, { exact (ennreal.nat_ne_top _) } end ... ≤ ∑ i, μ (s ∩ v i) : by { conv_lhs { rw A }, apply measure_Union_fintype_le }, -- choose an index `i` of a subfamily covering at least a proportion `1/N` of `s`. obtain ⟨i, -, hi⟩ : ∃ (i : fin N) (hi : i ∈ finset.univ), μ s / N ≤ μ (s ∩ v i), { apply ennreal.exists_le_of_sum_le _ S, exact ⟨⟨0, bot_lt_iff_ne_bot.2 Npos⟩, finset.mem_univ _⟩ }, replace hi : μ s / (N + 1) < μ (s ∩ v i), { apply lt_of_lt_of_le _ hi, apply (ennreal.mul_lt_mul_left hμs.ne' (measure_lt_top μ s).ne).2, rw ennreal.inv_lt_inv, conv_lhs {rw ← add_zero (N : ℝ≥0∞) }, exact ennreal.add_lt_add_left (ennreal.nat_ne_top N) ennreal.zero_lt_one }, have B : μ (o ∩ v i) = ∑' (x : u i), μ (o ∩ closed_ball x (r x)), { have : o ∩ v i = ⋃ (x : s) (hx : x ∈ u i), o ∩ closed_ball x (r x), by simp only [inter_Union], rw [this, measure_bUnion (u_count i)], { refl }, { exact (hu i).mono (λ k, inter_subset_right _ _) }, { exact λ b hb, omeas.inter measurable_set_closed_ball } }, -- A large enough finite subfamily of `u i` will also cover a proportion `> 1/(N+1)` of `s`. -- Since `s` might not be measurable, we express this in terms of the measurable superset `o`. obtain ⟨w, hw⟩ : ∃ (w : finset (u i)), μ s / (N + 1) < ∑ (x : u i) in w, μ (o ∩ closed_ball (x : α) (r (x : α))), { have C : has_sum (λ (x : u i), μ (o ∩ closed_ball x (r x))) (μ (o ∩ v i)), by { rw B, exact ennreal.summable.has_sum }, have : μ s / (N+1) < μ (o ∩ v i) := hi.trans_le (measure_mono (inter_subset_inter_left _ so)), exact ((tendsto_order.1 C).1 _ this).exists }, -- Bring back the finset `w i` of `↑(u i)` to a finset of `α`, and check that it works by design. refine ⟨finset.image (λ (x : u i), x) w, _, _, _⟩, -- show that the finset is included in `s`. { simp only [image_subset_iff, coe_coe, finset.coe_image], assume y hy, simp only [subtype.coe_prop, mem_preimage] }, -- show that it covers a large enough proportion of `s`. For measure computations, we do not -- use `s` (which might not be measurable), but its measurable superset `o`. Since their measures -- are the same, this does not spoil the estimates { suffices H : μ (o \ ⋃ x ∈ w, closed_ball ↑x (r ↑x)) ≤ N/(N+1) * μ s, { rw [finset.set_bUnion_finset_image], exact le_trans (measure_mono (diff_subset_diff so (subset.refl _))) H }, rw [← diff_inter_self_eq_diff, measure_diff_le_iff_le_add _ (inter_subset_right _ _) ((measure_lt_top μ _).ne)], swap, { apply measurable_set.inter _ omeas, haveI : encodable (u i) := (u_count i).to_encodable, exact measurable_set.Union (λ b, measurable_set.Union (λ hb, measurable_set_closed_ball)) }, calc μ o = 1/(N+1) * μ s + N/(N+1) * μ s : by { rw [μo, ← add_mul, ennreal.div_add_div_same, add_comm, ennreal.div_self, one_mul]; simp } ... ≤ μ ((⋃ (x ∈ w), closed_ball ↑x (r ↑x)) ∩ o) + N/(N+1) * μ s : begin refine add_le_add _ le_rfl, rw [div_eq_mul_inv, one_mul, mul_comm, ← div_eq_mul_inv], apply hw.le.trans (le_of_eq _), rw [← finset.set_bUnion_coe, inter_comm _ o, inter_Union₂, finset.set_bUnion_coe, measure_bUnion_finset], { have : (w : set (u i)).pairwise_disjoint (λ (b : u i), closed_ball (b : α) (r (b : α))), by { assume k hk l hl hkl, exact hu i k.2 l.2 (subtype.coe_injective.ne hkl) }, exact this.mono (λ k, inter_subset_right _ _) }, { assume b hb, apply omeas.inter measurable_set_closed_ball } end }, -- show that the balls are disjoint { assume k hk l hl hkl, obtain ⟨k', k'w, rfl⟩ : ∃ (k' : u i), k' ∈ w ∧ ↑↑k' = k, by simpa only [mem_image, finset.mem_coe, coe_coe, finset.coe_image] using hk, obtain ⟨l', l'w, rfl⟩ : ∃ (l' : u i), l' ∈ w ∧ ↑↑l' = l, by simpa only [mem_image, finset.mem_coe, coe_coe, finset.coe_image] using hl, have k'nel' : (k' : s) ≠ l', by { assume h, rw h at hkl, exact hkl rfl }, exact hu i k'.2 l'.2 k'nel' } end variable [has_besicovitch_covering α] /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version assuming that the measure is sigma-finite, see `exists_disjoint_closed_ball_covering_ae_aux`. For a version giving the conclusion in a nicer form, see `exists_disjoint_closed_ball_covering_ae`. -/ theorem exists_disjoint_closed_ball_covering_ae_of_finite_measure_aux (μ : measure α) [is_finite_measure μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set (α × ℝ)), t.countable ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)) = 0 ∧ t.pairwise_disjoint (λ p, closed_ball p.1 p.2) := begin rcases has_besicovitch_covering.no_satellite_config α with ⟨N, τ, hτ, hN⟩, /- Introduce a property `P` on finsets saying that we have a nice disjoint covering of a subset of `s` by admissible balls. -/ let P : finset (α × ℝ) → Prop := λ t, (t : set (α × ℝ)).pairwise_disjoint (λ p, closed_ball p.1 p.2) ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1), /- Given a finite good covering of a subset `s`, one can find a larger finite good covering, covering additionally a proportion at least `1/(N+1)` of leftover points. This follows from `exist_finset_disjoint_balls_large_measure` applied to balls not intersecting the initial covering. -/ have : ∀ (t : finset (α × ℝ)), P t → ∃ (u : finset (α × ℝ)), t ⊆ u ∧ P u ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ u), closed_ball p.1 p.2)) ≤ N/(N+1) * μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)), { assume t ht, set B := ⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2 with hB, have B_closed : is_closed B := is_closed_bUnion (finset.finite_to_set _) (λ i hi, is_closed_ball), set s' := s \ B with hs', have : ∀ x ∈ s', ∃ r ∈ f x ∩ Ioo 0 1, disjoint B (closed_ball x r), { assume x hx, have xs : x ∈ s := ((mem_diff x).1 hx).1, rcases eq_empty_or_nonempty B with hB|hB, { have : (0 : ℝ) < 1 := zero_lt_one, rcases hf x xs 1 zero_lt_one with ⟨r, hr, h'r⟩, exact ⟨r, ⟨hr, h'r⟩, by simp only [hB, empty_disjoint]⟩ }, { let R := inf_dist x B, have : 0 < min R 1 := lt_min ((B_closed.not_mem_iff_inf_dist_pos hB).1 ((mem_diff x).1 hx).2) zero_lt_one, rcases hf x xs _ this with ⟨r, hr, h'r⟩, refine ⟨r, ⟨hr, ⟨h'r.1, h'r.2.trans_le (min_le_right _ _)⟩⟩, _⟩, rw disjoint.comm, exact disjoint_closed_ball_of_lt_inf_dist (h'r.2.trans_le (min_le_left _ _)) } }, choose! r hr using this, obtain ⟨v, vs', hμv, hv⟩ : ∃ (v : finset α), ↑v ⊆ s' ∧ μ (s' \ ⋃ (x ∈ v), closed_ball x (r x)) ≤ N/(N+1) * μ s' ∧ (v : set α).pairwise_disjoint (λ (x : α), closed_ball x (r x)), { have rI : ∀ x ∈ s', r x ∈ Ioo (0 : ℝ) 1 := λ x hx, (hr x hx).1.2, exact exist_finset_disjoint_balls_large_measure μ hτ hN s' r (λ x hx, (rI x hx).1) (λ x hx, (rI x hx).2.le) }, refine ⟨t ∪ (finset.image (λ x, (x, r x)) v), finset.subset_union_left _ _, ⟨_, _, _⟩, _⟩, { simp only [finset.coe_union, pairwise_disjoint_union, ht.1, true_and, finset.coe_image], split, { assume p hp q hq hpq, rcases (mem_image _ _ _).1 hp with ⟨p', p'v, rfl⟩, rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩, refine hv p'v q'v (λ hp'q', _), rw [hp'q'] at hpq, exact hpq rfl }, { assume p hp q hq hpq, rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩, apply disjoint_of_subset_left _ (hr q' (vs' q'v)).2, rw [hB, ← finset.set_bUnion_coe], exact subset_bUnion_of_mem hp } }, { assume p hp, rcases finset.mem_union.1 hp with h'p|h'p, { exact ht.2.1 p h'p }, { rcases finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩, exact ((mem_diff _).1 (vs' (finset.mem_coe.2 p'v))).1 } }, { assume p hp, rcases finset.mem_union.1 hp with h'p|h'p, { exact ht.2.2 p h'p }, { rcases finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩, exact (hr p' (vs' p'v)).1.1 } }, { convert hμv using 2, rw [finset.set_bUnion_union, ← diff_diff, finset.set_bUnion_finset_image] } }, /- Define `F` associating to a finite good covering the above enlarged good covering, covering a proportion `1/(N+1)` of leftover points. Iterating `F`, one will get larger and larger good coverings, missing in the end only a measure-zero set. -/ choose! F hF using this, let u := λ n, F^[n] ∅, have u_succ : ∀ (n : ℕ), u n.succ = F (u n) := λ n, by simp only [u, function.comp_app, function.iterate_succ'], have Pu : ∀ n, P (u n), { assume n, induction n with n IH, { simp only [u, P, prod.forall, id.def, function.iterate_zero], simp only [finset.not_mem_empty, is_empty.forall_iff, finset.coe_empty, forall_2_true_iff, and_self, pairwise_disjoint_empty] }, { rw u_succ, exact (hF (u n) IH).2.1 } }, refine ⟨⋃ n, u n, countable_Union (λ n, (u n).countable_to_set), _, _, _, _⟩, { assume p hp, rcases mem_Union.1 hp with ⟨n, hn⟩, exact (Pu n).2.1 p (finset.mem_coe.1 hn) }, { assume p hp, rcases mem_Union.1 hp with ⟨n, hn⟩, exact (Pu n).2.2 p (finset.mem_coe.1 hn) }, { have A : ∀ n, μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ ⋃ (n : ℕ), (u n : set (α × ℝ))), closed_ball p.fst p.snd) ≤ μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd), { assume n, apply measure_mono, apply diff_subset_diff (subset.refl _), exact bUnion_subset_bUnion_left (subset_Union (λ i, (u i : set (α × ℝ))) n) }, have B : ∀ n, μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd) ≤ (N/(N+1))^n * μ s, { assume n, induction n with n IH, { simp only [le_refl, diff_empty, one_mul, Union_false, Union_empty, pow_zero] }, calc μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n.succ), closed_ball p.fst p.snd) ≤ (N/(N+1)) * μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd) : by { rw u_succ, exact (hF (u n) (Pu n)).2.2 } ... ≤ (N/(N+1))^n.succ * μ s : by { rw [pow_succ, mul_assoc], exact ennreal.mul_le_mul le_rfl IH } }, have C : tendsto (λ (n : ℕ), ((N : ℝ≥0∞)/(N+1))^n * μ s) at_top (𝓝 (0 * μ s)), { apply ennreal.tendsto.mul_const _ (or.inr (measure_lt_top μ s).ne), apply ennreal.tendsto_pow_at_top_nhds_0_of_lt_1, rw [ennreal.div_lt_iff, one_mul], { conv_lhs {rw ← add_zero (N : ℝ≥0∞) }, exact ennreal.add_lt_add_left (ennreal.nat_ne_top N) ennreal.zero_lt_one }, { simp only [true_or, add_eq_zero_iff, ne.def, not_false_iff, one_ne_zero, and_false] }, { simp only [ennreal.nat_ne_top, ne.def, not_false_iff, or_true] } }, rw zero_mul at C, apply le_bot_iff.1, exact le_of_tendsto_of_tendsto' tendsto_const_nhds C (λ n, (A n).trans (B n)) }, { refine (pairwise_disjoint_Union _).2 (λ n, (Pu n).1), apply (monotone_nat_of_le_succ (λ n, _)).directed_le, rw u_succ, exact (hF (u n) (Pu n)).1 } end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version giving the conclusion in a nicer form, see `exists_disjoint_closed_ball_covering_ae`. -/ theorem exists_disjoint_closed_ball_covering_ae_aux (μ : measure α) [sigma_finite μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set (α × ℝ)), t.countable ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)) = 0 ∧ t.pairwise_disjoint (λ p, closed_ball p.1 p.2) := begin /- This is deduced from the finite measure case, by using a finite measure with respect to which the initial sigma-finite measure is absolutely continuous. -/ unfreezingI { rcases exists_absolutely_continuous_is_finite_measure μ with ⟨ν, hν, hμν⟩ }, rcases exists_disjoint_closed_ball_covering_ae_of_finite_measure_aux ν f s hf with ⟨t, t_count, ts, tr, tν, tdisj⟩, exact ⟨t, t_count, ts, tr, hμν tν, tdisj⟩, end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. We can even require that the radius at `x` is bounded by a given function `R x`. (Take `R = 1` if you don't need this additional feature). This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). -/ theorem exists_disjoint_closed_ball_covering_ae (μ : measure α) [sigma_finite μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) (R : α → ℝ) (hR : ∀ x ∈ s, 0 < R x): ∃ (t : set α) (r : α → ℝ), t.countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x ∩ Ioo 0 (R x)) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) = 0 ∧ t.pairwise_disjoint (λ x, closed_ball x (r x)) := begin let g := λ x, f x ∩ Ioo 0 (R x), have hg : ∀ x ∈ s, ∀ δ > 0, (g x ∩ Ioo 0 δ).nonempty, { assume x hx δ δpos, rcases hf x hx (min δ (R x)) (lt_min δpos (hR x hx)) with ⟨r, hr⟩, exact ⟨r, ⟨⟨hr.1, hr.2.1, hr.2.2.trans_le (min_le_right _ _)⟩, ⟨hr.2.1, hr.2.2.trans_le (min_le_left _ _)⟩⟩⟩ }, rcases exists_disjoint_closed_ball_covering_ae_aux μ g s hg with ⟨v, v_count, vs, vg, μv, v_disj⟩, let t := prod.fst '' v, have : ∀ x ∈ t, ∃ (r : ℝ), (x, r) ∈ v, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact ⟨q, hp⟩ }, choose! r hr using this, have im_t : (λ x, (x, r x)) '' t = v, { have I : ∀ (p : α × ℝ), p ∈ v → 0 ≤ p.2 := λ p hp, (vg p hp).2.1.le, apply subset.antisymm, { simp only [image_subset_iff], rintros ⟨x, p⟩ hxp, simp only [mem_preimage], exact hr _ (mem_image_of_mem _ hxp) }, { rintros ⟨x, p⟩ hxp, have hxrx : (x, r x) ∈ v := hr _ (mem_image_of_mem _ hxp), have : p = r x, { by_contra, have A : (x, p) ≠ (x, r x), by simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true, ne.def] using h, have H := v_disj hxp hxrx A, contrapose H, rw not_disjoint_iff_nonempty_inter, refine ⟨x, by simp [I _ hxp, I _ hxrx]⟩ }, rw this, apply mem_image_of_mem, exact mem_image_of_mem _ hxp } }, refine ⟨t, r, v_count.image _, _, _, _, _⟩, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact vs _ hp }, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact vg _ (hr _ hx) }, { have : (⋃ (x : α) (H : x ∈ t), closed_ball x (r x)) = (⋃ (p : α × ℝ) (H : p ∈ (λ x, (x, r x)) '' t), closed_ball p.1 p.2), by conv_rhs { rw bUnion_image }, rw [this, im_t], exact μv }, { have A : inj_on (λ x : α, (x, r x)) t, by simp only [inj_on, prod.mk.inj_iff, implies_true_iff, eq_self_iff_true] {contextual := tt}, rwa [← im_t, A.pairwise_disjoint_image] at v_disj } end /-- In a space with the Besicovitch property, any set `s` can be covered with balls whose measures add up to at most `μ s + ε`, for any positive `ε`. This works even if one restricts the set of allowed radii around a point `x` to a set `f x` which accumulates at `0`. -/ theorem exists_closed_ball_covering_tsum_measure_le (μ : measure α) [sigma_finite μ] [measure.outer_regular μ] {ε : ℝ≥0∞} (hε : ε ≠ 0) (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set α) (r : α → ℝ), t.countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x) ∧ s ⊆ (⋃ (x ∈ t), closed_ball x (r x)) ∧ ∑' (x : t), μ (closed_ball x (r x)) ≤ μ s + ε := begin /- For the proof, first cover almost all `s` with disjoint balls thanks to the usual Besicovitch theorem. Taking the balls included in a well-chosen open neighborhood `u` of `s`, one may ensure that their measures add at most to `μ s + ε / 2`. Let `s'` be the remaining set, of measure `0`. Applying the other version of Besicovitch, one may cover it with at most `N` disjoint subfamilies. Making sure that they are all included in a neighborhood `v` of `s'` of measure at most `ε / (2 N)`, the sum of their measures is at most `ε / 2`, completing the proof. -/ obtain ⟨u, su, u_open, μu⟩ : ∃ U ⊇ s, is_open U ∧ μ U ≤ μ s + ε / 2 := set.exists_is_open_le_add _ _ (by simpa only [or_false, ne.def, ennreal.div_zero_iff, ennreal.one_ne_top, ennreal.bit0_eq_top_iff] using hε), have : ∀ x ∈ s, ∃ R > 0, ball x R ⊆ u := λ x hx, metric.mem_nhds_iff.1 (u_open.mem_nhds (su hx)), choose! R hR using this, obtain ⟨t0, r0, t0_count, t0s, hr0, μt0, t0_disj⟩ : ∃ (t0 : set α) (r0 : α → ℝ), t0.countable ∧ t0 ⊆ s ∧ (∀ x ∈ t0, r0 x ∈ f x ∩ Ioo 0 (R x)) ∧ μ (s \ (⋃ (x ∈ t0), closed_ball x (r0 x))) = 0 ∧ t0.pairwise_disjoint (λ x, closed_ball x (r0 x)) := exists_disjoint_closed_ball_covering_ae μ f s hf R (λ x hx, (hR x hx).1), -- we have constructed an almost everywhere covering of `s` by disjoint balls. Let `s'` be the -- remaining set. let s' := s \ (⋃ (x ∈ t0), closed_ball x (r0 x)), have s's : s' ⊆ s := diff_subset _ _, obtain ⟨N, τ, hτ, H⟩ : ∃ N τ, 1 < τ ∧ is_empty (besicovitch.satellite_config α N τ) := has_besicovitch_covering.no_satellite_config α, obtain ⟨v, s'v, v_open, μv⟩ : ∃ v ⊇ s', is_open v ∧ μ v ≤ μ s' + (ε / 2) / N := set.exists_is_open_le_add _ _ (by simp only [hε, ennreal.nat_ne_top, with_top.mul_eq_top_iff, ne.def, ennreal.div_zero_iff, ennreal.one_ne_top, not_false_iff, and_false, false_and, or_self, ennreal.bit0_eq_top_iff]), have : ∀ x ∈ s', ∃ r1 ∈ (f x ∩ Ioo (0 : ℝ) 1), closed_ball x r1 ⊆ v, { assume x hx, rcases metric.mem_nhds_iff.1 (v_open.mem_nhds (s'v hx)) with ⟨r, rpos, hr⟩, rcases hf x (s's hx) (min r 1) (lt_min rpos zero_lt_one) with ⟨R', hR'⟩, exact ⟨R', ⟨hR'.1, hR'.2.1, hR'.2.2.trans_le (min_le_right _ _)⟩, subset.trans (closed_ball_subset_ball (hR'.2.2.trans_le (min_le_left _ _))) hr⟩, }, choose! r1 hr1 using this, let q : ball_package s' α := { c := λ x, x, r := λ x, r1 x, rpos := λ x, (hr1 x.1 x.2).1.2.1, r_bound := 1, r_le := λ x, (hr1 x.1 x.2).1.2.2.le }, -- by Besicovitch, we cover `s'` with at most `N` families of disjoint balls, all included in -- a suitable neighborhood `v` of `s'`. obtain ⟨S, S_disj, hS⟩ : ∃ S : fin N → set s', (∀ (i : fin N), (S i).pairwise_disjoint (λ j, closed_ball (q.c j) (q.r j))) ∧ (range q.c ⊆ ⋃ (i : fin N), ⋃ (j ∈ S i), ball (q.c j) (q.r j)) := exist_disjoint_covering_families hτ H q, have S_count : ∀ i, (S i).countable, { assume i, apply (S_disj i).countable_of_nonempty_interior (λ j hj, _), have : (ball (j : α) (r1 j)).nonempty := nonempty_ball.2 (q.rpos _), exact this.mono ball_subset_interior_closed_ball }, let r := λ x, if x ∈ s' then r1 x else r0 x, have r_t0 : ∀ x ∈ t0, r x = r0 x, { assume x hx, have : ¬ (x ∈ s'), { simp only [not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_lt, not_le, mem_diff, not_forall], assume h'x, refine ⟨x, hx, _⟩, rw dist_self, exact (hr0 x hx).2.1.le }, simp only [r, if_neg this] }, -- the desired covering set is given by the union of the families constructed in the first and -- second steps. refine ⟨t0 ∪ (⋃ (i : fin N), (coe : s' → α) '' (S i)), r, _, _, _, _, _⟩, -- it remains to check that they have the desired properties { exact t0_count.union (countable_Union (λ i, (S_count i).image _)) }, { simp only [t0s, true_and, union_subset_iff, image_subset_iff, Union_subset_iff], assume i x hx, exact s's x.2 }, { assume x hx, cases hx, { rw r_t0 x hx, exact (hr0 _ hx).1 }, { have h'x : x ∈ s', { simp only [mem_Union, mem_image] at hx, rcases hx with ⟨i, y, ySi, rfl⟩, exact y.2 }, simp only [r, if_pos h'x, (hr1 x h'x).1.1] } }, { assume x hx, by_cases h'x : x ∈ s', { obtain ⟨i, y, ySi, xy⟩ : ∃ (i : fin N) (y : ↥s') (ySi : y ∈ S i), x ∈ ball (y : α) (r1 y), { have A : x ∈ range q.c, by simpa only [not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, mem_set_of_eq, subtype.range_coe_subtype, mem_diff] using h'x, simpa only [mem_Union, mem_image] using hS A }, refine mem_Union₂.2 ⟨y, or.inr _, _⟩, { simp only [mem_Union, mem_image], exact ⟨i, y, ySi, rfl⟩ }, { have : (y : α) ∈ s' := y.2, simp only [r, if_pos this], exact ball_subset_closed_ball xy } }, { obtain ⟨y, yt0, hxy⟩ : ∃ (y : α), y ∈ t0 ∧ x ∈ closed_ball y (r0 y), by simpa [hx, -mem_closed_ball] using h'x, refine mem_Union₂.2 ⟨y, or.inl yt0, _⟩, rwa r_t0 _ yt0 } }, -- the only nontrivial property is the measure control, which we check now { -- the sets in the first step have measure at most `μ s + ε / 2` have A : ∑' (x : t0), μ (closed_ball x (r x)) ≤ μ s + ε / 2 := calc ∑' (x : t0), μ (closed_ball x (r x)) = ∑' (x : t0), μ (closed_ball x (r0 x)) : by { congr' 1, ext x, rw r_t0 x x.2 } ... = μ (⋃ (x : t0), closed_ball x (r0 x)) : begin haveI : encodable t0 := t0_count.to_encodable, rw measure_Union, { exact (pairwise_subtype_iff_pairwise_set _ _).2 t0_disj }, { exact λ i, measurable_set_closed_ball } end ... ≤ μ u : begin apply measure_mono, simp only [set_coe.forall, subtype.coe_mk, Union_subset_iff], assume x hx, apply subset.trans (closed_ball_subset_ball (hr0 x hx).2.2) (hR x (t0s hx)).2, end ... ≤ μ s + ε / 2 : μu, -- each subfamily in the second step has measure at most `ε / (2 N)`. have B : ∀ (i : fin N), ∑' (x : (coe : s' → α) '' (S i)), μ (closed_ball x (r x)) ≤ (ε / 2) / N := λ i, calc ∑' (x : (coe : s' → α) '' (S i)), μ (closed_ball x (r x)) = ∑' (x : S i), μ (closed_ball x (r x)) : begin have : inj_on (coe : s' → α) (S i) := subtype.coe_injective.inj_on _, let F : S i ≃ (coe : s' → α) '' (S i) := this.bij_on_image.equiv _, exact (F.tsum_eq (λ x, μ (closed_ball x (r x)))).symm, end ... = ∑' (x : S i), μ (closed_ball x (r1 x)) : by { congr' 1, ext x, have : (x : α) ∈ s' := x.1.2, simp only [r, if_pos this] } ... = μ (⋃ (x : S i), closed_ball x (r1 x)) : begin haveI : encodable (S i) := (S_count i).to_encodable, rw measure_Union, { exact (pairwise_subtype_iff_pairwise_set _ _).2 (S_disj i) }, { exact λ i, measurable_set_closed_ball } end ... ≤ μ v : begin apply measure_mono, simp only [set_coe.forall, subtype.coe_mk, Union_subset_iff], assume x xs' xSi, exact (hr1 x xs').2, end ... ≤ (ε / 2) / N : by { have : μ s' = 0 := μt0, rwa [this, zero_add] at μv }, -- add up all these to prove the desired estimate calc ∑' (x : (t0 ∪ ⋃ (i : fin N), (coe : s' → α) '' S i)), μ (closed_ball x (r x)) ≤ ∑' (x : t0), μ (closed_ball x (r x)) + ∑' (x : ⋃ (i : fin N), (coe : s' → α) '' S i), μ (closed_ball x (r x)) : ennreal.tsum_union_le (λ x, μ (closed_ball x (r x))) _ _ ... ≤ ∑' (x : t0), μ (closed_ball x (r x)) + ∑ (i : fin N), ∑' (x : (coe : s' → α) '' S i), μ (closed_ball x (r x)) : add_le_add le_rfl (ennreal.tsum_Union_le (λ x, μ (closed_ball x (r x))) _) ... ≤ (μ s + ε / 2) + ∑ (i : fin N), (ε / 2) / N : begin refine add_le_add A _, refine finset.sum_le_sum _, assume i hi, exact B i end ... ≤ (μ s + ε / 2) + ε / 2 : begin refine add_le_add le_rfl _, simp only [finset.card_fin, finset.sum_const, nsmul_eq_mul, ennreal.mul_div_le], end ... = μ s + ε : by rw [add_assoc, ennreal.add_halves] } end /-! ### Consequences on differentiation of measures -/ /-- In a space with the Besicovitch covering property, the set of closed balls with positive radius forms a Vitali family. This is essentially a restatement of the measurable Besicovitch theorem. -/ protected def vitali_family (μ : measure α) [sigma_finite μ] : vitali_family μ := { sets_at := λ x, (λ (r : ℝ), closed_ball x r) '' (Ioi (0 : ℝ)), measurable_set' := begin assume x y hy, obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = y, by simpa only [mem_image, mem_Ioi] using hy, exact is_closed_ball.measurable_set end, nonempty_interior := begin assume x y hy, obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = y, by simpa only [mem_image, mem_Ioi] using hy, simp only [nonempty.mono ball_subset_interior_closed_ball, rpos, nonempty_ball], end, nontrivial := λ x ε εpos, ⟨closed_ball x ε, mem_image_of_mem _ εpos, subset.refl _⟩, covering := begin assume s f fsubset ffine, let g : α → set ℝ := λ x, {r | 0 < r ∧ closed_ball x r ∈ f x}, have A : ∀ x ∈ s, ∀ δ > 0, (g x ∩ Ioo 0 δ).nonempty, { assume x xs δ δpos, obtain ⟨t, tf, ht⟩ : ∃ (t : set α) (H : t ∈ f x), t ⊆ closed_ball x (δ/2) := ffine x xs (δ/2) (half_pos δpos), obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = t, by simpa using fsubset x xs tf, rcases le_total r (δ/2) with H|H, { exact ⟨r, ⟨rpos, tf⟩, ⟨rpos, H.trans_lt (half_lt_self δpos)⟩⟩ }, { have : closed_ball x r = closed_ball x (δ/2) := subset.antisymm ht (closed_ball_subset_closed_ball H), rw this at tf, refine ⟨δ/2, ⟨half_pos δpos, tf⟩, ⟨half_pos δpos, half_lt_self δpos⟩⟩ } }, obtain ⟨t, r, t_count, ts, tg, μt, tdisj⟩ : ∃ (t : set α) (r : α → ℝ), t.countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ g x ∩ Ioo 0 1) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) = 0 ∧ t.pairwise_disjoint (λ x, closed_ball x (r x)) := exists_disjoint_closed_ball_covering_ae μ g s A (λ _, 1) (λ _ _, zero_lt_one), let F : α → α × set α := λ x, (x, closed_ball x (r x)), refine ⟨F '' t, _, _, _, _⟩, { rintros - ⟨x, hx, rfl⟩, exact ts hx }, { rintros p ⟨x, hx, rfl⟩ q ⟨y, hy, rfl⟩ hxy, exact tdisj hx hy (ne_of_apply_ne F hxy) }, { rintros - ⟨x, hx, rfl⟩, exact (tg x hx).1.2 }, { rwa bUnion_image } end } /-- The main feature of the Besicovitch Vitali family is that its filter at a point `x` corresponds to convergence along closed balls. We record one of the two implications here, which will enable us to deduce specific statements on differentiation of measures in this context from the general versions. -/ lemma tendsto_filter_at (μ : measure α) [sigma_finite μ] (x : α) : tendsto (λ r, closed_ball x r) (𝓝[>] 0) ((besicovitch.vitali_family μ).filter_at x) := begin assume s hs, simp only [mem_map], obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ (a : set α), a ∈ (besicovitch.vitali_family μ).sets_at x → a ⊆ closed_ball x ε → a ∈ s := (vitali_family.mem_filter_at_iff _).1 hs, have : Ioc (0 : ℝ) ε ∈ 𝓝[>] (0 : ℝ) := Ioc_mem_nhds_within_Ioi ⟨le_rfl, εpos⟩, filter_upwards [this] with _ hr, apply hε, { exact mem_image_of_mem _ hr.1 }, { exact closed_ball_subset_closed_ball hr.2 } end variables [metric_space β] [measurable_space β] [borel_space β] [second_countable_topology β] [has_besicovitch_covering β] /-- In a space with the Besicovitch covering property, the ratio of the measure of balls converges almost surely to to the Radon-Nikodym derivative. -/ lemma ae_tendsto_rn_deriv (ρ μ : measure β) [is_locally_finite_measure μ] [is_locally_finite_measure ρ] : ∀ᵐ x ∂μ, tendsto (λ r, ρ (closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 (ρ.rn_deriv μ x)) := begin filter_upwards [vitali_family.ae_tendsto_rn_deriv (besicovitch.vitali_family μ) ρ] with x hx, exact hx.comp (tendsto_filter_at μ x) end /-- Given a measurable set `s`, then `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` converges when `r` tends to `0`, for almost every `x`. The limit is `1` for `x ∈ s` and `0` for `x ∉ s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A version for non-measurable sets holds, but it only gives the first conclusion, see `ae_tendsto_measure_inter_div`. -/ lemma ae_tendsto_measure_inter_div_of_measurable_set (μ : measure β) [is_locally_finite_measure μ] {s : set β} (hs : measurable_set s) : ∀ᵐ x ∂μ, tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 (s.indicator 1 x)) := begin filter_upwards [vitali_family.ae_tendsto_measure_inter_div_of_measurable_set (besicovitch.vitali_family μ) hs], assume x hx, exact hx.comp (tendsto_filter_at μ x) end /-- Given an arbitrary set `s`, then `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` converges to `1` when `r` tends to `0`, for almost every `x` in `s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A stronger version holds for measurable sets, see `ae_tendsto_measure_inter_div_of_measurable_set`. See also `is_doubling_measure.ae_tendsto_measure_inter_div`. -/ lemma ae_tendsto_measure_inter_div (μ : measure β) [is_locally_finite_measure μ] (s : set β) : ∀ᵐ x ∂(μ.restrict s), tendsto (λ r, μ (s ∩ (closed_ball x r)) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1) := by filter_upwards [vitali_family.ae_tendsto_measure_inter_div (besicovitch.vitali_family μ)] with x hx using hx.comp (tendsto_filter_at μ x) end besicovitch
b8085d380065ded14e618227ebec94cf83cdaa8e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/field/power.lean
aa69291ff6968abac370dc38036b3bb31e2b7349
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,692
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import algebra.parity import algebra.char_zero.lemmas import algebra.group_with_zero.power import algebra.order.field.basic /-! # Lemmas about powers in ordered fields. -/ variables {α : Type*} open function section linear_ordered_semifield variables [linear_ordered_semifield α] {a b c d e : α} {m n : ℤ} /-! ### Integer powers -/ lemma zpow_le_of_le (ha : 1 ≤ a) (h : m ≤ n) : a ^ m ≤ a ^ n := begin have ha₀ : 0 < a, from one_pos.trans_le ha, lift n - m to ℕ using sub_nonneg.2 h with k hk, calc a ^ m = a ^ m * 1 : (mul_one _).symm ... ≤ a ^ m * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (zpow_nonneg ha₀.le _) ... = a ^ n : by rw [← zpow_coe_nat, ← zpow_add₀ ha₀.ne', hk, add_sub_cancel'_right] end lemma zpow_le_one_of_nonpos (ha : 1 ≤ a) (hn : n ≤ 0) : a ^ n ≤ 1 := (zpow_le_of_le ha hn).trans_eq $ zpow_zero _ lemma one_le_zpow_of_nonneg (ha : 1 ≤ a) (hn : 0 ≤ n) : 1 ≤ a ^ n := (zpow_zero _).symm.trans_le $ zpow_le_of_le ha hn protected lemma nat.zpow_pos_of_pos {a : ℕ} (h : 0 < a) (n : ℤ) : 0 < (a : α)^n := by { apply zpow_pos_of_pos, exact_mod_cast h } lemma nat.zpow_ne_zero_of_pos {a : ℕ} (h : 0 < a) (n : ℤ) : (a : α)^n ≠ 0 := (nat.zpow_pos_of_pos h n).ne' lemma one_lt_zpow (ha : 1 < a) : ∀ n : ℤ, 0 < n → 1 < a ^ n | (n : ℕ) h := (zpow_coe_nat _ _).symm.subst (one_lt_pow ha $ int.coe_nat_ne_zero.mp h.ne') | -[1+ n] h := ((int.neg_succ_not_pos _).mp h).elim lemma zpow_strict_mono (hx : 1 < a) : strict_mono ((^) a : ℤ → α) := strict_mono_int_of_lt_succ $ λ n, have xpos : 0 < a, from zero_lt_one.trans hx, calc a ^ n < a ^ n * a : lt_mul_of_one_lt_right (zpow_pos_of_pos xpos _) hx ... = a ^ (n + 1) : (zpow_add_one₀ xpos.ne' _).symm lemma zpow_strict_anti (h₀ : 0 < a) (h₁ : a < 1) : strict_anti ((^) a : ℤ → α) := strict_anti_int_of_succ_lt $ λ n, calc a ^ (n + 1) = a ^ n * a : zpow_add_one₀ h₀.ne' _ ... < a ^ n * 1 : (mul_lt_mul_left $ zpow_pos_of_pos h₀ _).2 h₁ ... = a ^ n : mul_one _ @[simp] lemma zpow_lt_iff_lt (hx : 1 < a) : a ^ m < a ^ n ↔ m < n := (zpow_strict_mono hx).lt_iff_lt @[simp] lemma zpow_le_iff_le (hx : 1 < a) : a ^ m ≤ a ^ n ↔ m ≤ n := (zpow_strict_mono hx).le_iff_le @[simp] lemma div_pow_le (ha : 0 ≤ a) (hb : 1 ≤ b) (k : ℕ) : a/b^k ≤ a := div_le_self ha $ one_le_pow_of_one_le hb _ lemma zpow_injective (h₀ : 0 < a) (h₁ : a ≠ 1) : injective ((^) a : ℤ → α) := begin rcases h₁.lt_or_lt with H|H, { exact (zpow_strict_anti h₀ H).injective }, { exact (zpow_strict_mono H).injective } end @[simp] lemma zpow_inj (h₀ : 0 < a) (h₁ : a ≠ 1) : a ^ m = a ^ n ↔ m = n := (zpow_injective h₀ h₁).eq_iff lemma zpow_le_max_of_min_le {x : α} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ -c ≤ max (x ^ -a) (x ^ -b) := begin have : antitone (λ n : ℤ, x ^ -n) := λ m n h, zpow_le_of_le hx (neg_le_neg h), exact (this h).trans_eq this.map_min, end lemma zpow_le_max_iff_min_le {x : α} (hx : 1 < x) {a b c : ℤ} : x ^ -c ≤ max (x ^ -a) (x ^ -b) ↔ min a b ≤ c := by simp_rw [le_max_iff, min_le_iff, zpow_le_iff_le hx, neg_le_neg_iff] end linear_ordered_semifield section linear_ordered_field variables [linear_ordered_field α] {a b c d : α} {n : ℤ} /-! ### Lemmas about powers to numerals. -/ lemma zpow_bit0_nonneg (a : α) (n : ℤ) : 0 ≤ a ^ bit0 n := (mul_self_nonneg _).trans_eq $ (zpow_bit0 _ _).symm lemma zpow_two_nonneg (a : α) : 0 ≤ a ^ (2 : ℤ) := zpow_bit0_nonneg _ _ lemma zpow_bit0_pos (h : a ≠ 0) (n : ℤ) : 0 < a ^ bit0 n := (zpow_bit0_nonneg a n).lt_of_ne (zpow_ne_zero _ h).symm lemma zpow_two_pos_of_ne_zero (h : a ≠ 0) : 0 < a ^ (2 : ℤ) := zpow_bit0_pos h _ @[simp] lemma zpow_bit0_pos_iff (hn : n ≠ 0) : 0 < a ^ bit0 n ↔ a ≠ 0 := ⟨by { rintro h rfl, refine (zero_zpow _ _).not_gt h, rwa bit0_ne_zero }, λ h, zpow_bit0_pos h _⟩ @[simp] lemma zpow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ zpow_nonneg h' _, λ h, by rw [bit1, zpow_add_one₀ h.ne]; exact mul_neg_of_pos_of_neg (zpow_bit0_pos h.ne _) h⟩ @[simp] lemma zpow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 zpow_bit1_neg_iff @[simp] lemma zpow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by rw [le_iff_lt_or_eq, le_iff_lt_or_eq, zpow_bit1_neg_iff, zpow_eq_zero_iff (int.bit1_ne_zero n)] @[simp] lemma zpow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le zpow_bit1_nonpos_iff protected lemma even.zpow_nonneg (hn : even n) (a : α) : 0 ≤ a ^ n := by obtain ⟨k, rfl⟩ := hn; exact zpow_bit0_nonneg _ _ lemma even.zpow_pos_iff (hn : even n) (h : n ≠ 0) : 0 < a ^ n ↔ a ≠ 0 := by obtain ⟨k, rfl⟩ := hn; exact zpow_bit0_pos_iff (by rintro rfl; simpa using h) lemma odd.zpow_neg_iff (hn : odd n) : a ^ n < 0 ↔ a < 0 := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_neg_iff protected lemma odd.zpow_nonneg_iff (hn : odd n) : 0 ≤ a ^ n ↔ 0 ≤ a := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_nonneg_iff lemma odd.zpow_nonpos_iff (hn : odd n) : a ^ n ≤ 0 ↔ a ≤ 0 := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_nonpos_iff lemma odd.zpow_pos_iff (hn : odd n) : 0 < a ^ n ↔ 0 < a := by cases hn with k hk; simpa only [hk, two_mul] using zpow_bit1_pos_iff alias even.zpow_pos_iff ↔ _ even.zpow_pos alias odd.zpow_neg_iff ↔ _ odd.zpow_neg alias odd.zpow_nonpos_iff ↔ _ odd.zpow_nonpos lemma even.zpow_abs {p : ℤ} (hp : even p) (a : α) : |a| ^ p = a ^ p := by cases abs_choice a with h h; simp only [h, hp.neg_zpow _] @[simp] lemma zpow_bit0_abs (a : α) (p : ℤ) : |a| ^ bit0 p = a ^ bit0 p := (even_bit0 _).zpow_abs _ /-! ### Miscellaneous lemmmas -/ /-- Bernoulli's inequality reformulated to estimate `(n : α)`. -/ lemma nat.cast_le_pow_sub_div_sub (H : 1 < a) (n : ℕ) : (n : α) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self zero_le_one).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub (H : 1 < a) (n : ℕ) : (n : α) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) end linear_ordered_field
71defb9ad58abc3e51cc5d12b0568989a73a33ab
53f7fd7840fe4979de24f9611c89f2ee1b4fc5dc
/src/backtrack.lean
0cb182c83ffc425f51b21bf1330796737559ddcc
[]
no_license
cipher1024/search-trees
6d1925283c6ce47d84bdf41ca40d8317ff2e64d7
0e0ea0ee59f0b0499ebad1ef6f34f09ec9666cde
refs/heads/master
1,673,300,158,759
1,603,984,112,000
1,603,984,112,000
308,132,998
1
0
null
null
null
null
UTF-8
Lean
false
false
989
lean
import control.monad.cont open tactic namespace tactic -- this should probably be PR-ed meta def bt_tac (α : Type) := ∀ r, cont_t r tactic α meta instance : monad bt_tac := { pure := λ α x r, pure x, bind := λ α β x f r, x r >>= λ a, f a r } meta instance bt_tac.alternative : alternative bt_tac := { failure := λ α r _, failure, orelse := λ α x y r f, x _ f <|> y _ f } meta def run_bt {α} (x : bt_tac α) : tactic α := x _ pure meta def bt_lift {α} (x : tactic α) : bt_tac α := λ r f, x >>= f meta def var : bt_tac expr := bt_lift mk_mvar meta def hyp (p : pexpr) : bt_tac expr := do p ← bt_lift $ to_expr p, ls ← bt_lift local_context, ls.mfirst $ λ h, bt_lift $ do t ← infer_type h, h <$ unify t p meta def hyp_with (p : pexpr) : bt_tac (expr × expr) := do p ← bt_lift $ to_expr p, ls ← bt_lift local_context, ls.mfirst $ λ h, bt_lift $ do t ← infer_type h, e ← kabstract t p, guard $ e.has_var, pure (h, e) end tactic
0d7fcbd9e20676aa3a2530ed655c81f3c6384b39
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0201/S0201.lean
e23ab6a4c0a60f2645c7492a9a3b761ea4b01b52
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,037
lean
import xenalib.M1Fstuff algebra.group_power xenalib.square_root -- automatic coercions to reals section M1F_Sheet02 -- #check arbitrary -- #print arbitrary -- #check default -- #print default -- ask about this /- example : arbitrary = default := begin unfold eq, end -/ -- set_option pp.all true def countable_union_from_zero {α : Type} (X : nat → set α ) := { t : α | exists i, t ∈ X i} def countable_union_from_one {α : Type} (X : nat → set α ) := { t : α | exists i, i > 0 ∧ t ∈ X i} def Q1a_sets : ℕ → set ℝ := λ n x, ↑n ≤ x ∧ x < (n+1) -- #check Q1a_sets /- def Q1a_sets2 : ℕ → set ℝ := λ n, { x | ↑ n ≤ x ∧ x < (n+1)} example : Q1a_sets = Q1a_sets2 := begin apply funext, intro n, unfold Q1a_sets, unfold Q1a_sets2, apply funext, intro x,unfold set_of, end -/ -- set_option pp.all true theorem Q1a : countable_union_from_zero Q1a_sets = { x | 0 ≤ x} := begin unfold countable_union_from_zero, unfold Q1a_sets, apply funext, intro x, unfold set_of, have H : ∃ (n : ℤ), ↑n ≤ x ∧ x < ↑n + 1, exact M1F.floor_real_exists x, apply propext, split, intro H2, cases H2 with i H3, have H4 : ↑i ≤ x, exact H3.left, have H5 : (0:ℤ) ≤ ↑i, exact int.coe_zero_le i, apply le_trans _ H4, simp [H5], intro H2, cases H with n H3, have H4 : ((0:ℤ):ℝ) < (n:real) +(1:real), exact lt_of_le_of_lt H2 H3.right, have H5 : ((0:ℤ):ℝ) < (n:ℝ) + ((1:ℤ):ℝ), rw [int.cast_one], exact H4, clear H4, -- rw [←int.cast_add] at H4, -- have H5 : (0:ℤ) < n + of_rat(1), -- exact H4, -- rw [of_rat_add,of_rat_lt] at H5, -- clear H4, rw [←int.cast_add,int.cast_lt] at H5, rw [int.lt_iff_add_one_le] at H5, simp at H5, have H : ∃ (n_1 : ℕ), n = ↑n_1, exact int.eq_coe_of_zero_le H5, cases H with i H4, clear H5 H2, existsi i, split, exact calc (i:ℝ) = ((i:ℤ):ℝ) : by simp ... = (n:ℝ) : int.cast_inj.mpr (eq.symm H4) ... ≤ x : H3.left, suffices H : (↑n : ℝ) = (↑i : ℝ), rw [←H],exact H3.right, rw [H4], refl, end /- def Q1b_sets : ℕ → set ℝ := λ n x, 1/(↑n) ≤ x ∧ x ≤ 1 -- set_option pp.notation false -- set_option class.instance_max_depth -- set_option pp.all true theorem Q1b : countable_union_from_one Q1b_sets = { x | 0 < x ∧ x ≤ 1} := begin unfold countable_union_from_one, unfold Q1b_sets, apply funext, intro x, unfold set_of, apply propext, split;intro H, cases H with i Hi, split, tactic.swap, exact Hi.right.right, suffices H2 : (0:ℝ) < 1/(↑i), exact lt_of_lt_of_le H2 Hi.right.left, -- have H3 : of_rat (((0:nat):int):rat) < of_rat ((i:int):rat), -- rw [of_rat_lt,rat.coe_int_lt,int.coe_nat_lt_coe_nat_iff], -- exact Hi.left, rw [←int.cast_zero], exact lt_div_of_mul_lt (nat.cast_lt.mpr Hi.left) (by simp [zero_lt_one]), have H2 : 0 < 1/x, exact lt_div_of_mul_lt H.left (by simp [zero_lt_one]), have H3 : ∃ (n : ℤ), ↑n ≤ 1 / x ∧ 1 / x < ↑n + 1, exact M1F.floor_real_exists (1/x), cases H3 with n Hn, have H3 : (0:ℝ) < (n:ℝ) + (1:ℝ), exact lt_of_lt_of_le H2 (le_of_lt Hn.right), rw [←int.cast_one,←int.cast_add,←int.cast_zero,int.cast_lt,int.lt_iff_add_one_le] at H3, have H4 : ↑0 ≤ n, apply le_of_add_le_add_right H3, cases n with nnat nfalse, tactic.swap, have H5 : (0:ℤ) < (0:ℤ), exact calc (0:ℤ) ≤ int.neg_succ_of_nat nfalse : H4 ... < 0 : int.neg_succ_of_nat_lt_zero nfalse, exfalso, apply H5, clear H3 H4, existsi (nnat+1), split, exact calc 0< nat.succ nnat : nat.zero_lt_succ nnat ... = nnat+1 : rfl, split, tactic.swap, exact H.right, have H4 : x > 0, unfold gt,exact H.left, have H5 : nnat+1>0, exact (nat.zero_lt_succ nnat), have H6 : (((nnat+1):ℕ):ℝ) > 0, exact nat.cast_lt.mpr H5, have H7 : ((int.of_nat nnat):ℝ) + 1 = (((nnat+1):ℕ):ℝ), simp, have Hnr : 1 / x < ↑(int.of_nat nnat) + 1, exact Hn.right, rw [H7] at Hnr, clear Hn H5, suffices H5 : 1 ≤ ↑(nnat+1)*x, exact div_le_of_le_mul H6 H5, exact (div_le_iff_le_mul_of_pos H4).mp (le_of_lt Hnr) end def Q1c_sets : ℕ → set ℝ := λ n x, -↑n < x ∧ x < n -- #check max, theorem Q1c : countable_union_from_one Q1c_sets = { x | true } := begin unfold countable_union_from_one, unfold Q1c_sets, apply funext, intro x, unfold set_of, apply propext, split;intro H, trivial, have H2 : ∃ (n : ℤ), ↑n ≤ x ∧ x < ↑n + 1, exact M1F.floor_real_exists x, have H3 : ∃ (m : ℤ), ↑m ≤ (-x) ∧ (-x) < ↑m + 1, exact M1F.floor_real_exists (-x), cases H2 with n Hn, cases H3 with m Hm, let iz:ℤ := max (1:ℤ) (max (n+1) ((m+1))), have H4 : iz ≥ 1, exact le_max_left (1:ℤ) _, have H5 : ∃ (i:ℕ), iz=i, exact int.eq_coe_of_zero_le (le_trans (le_of_lt (zero_lt_one)) H4), cases H5 with i Hi, existsi i, split, suffices H1 : 0<i, exact H1, rw [←int.coe_nat_lt_coe_nat_iff,←Hi], exact lt_of_lt_of_le zero_lt_one H4, split, suffices H1 : -↑i ≤ -(↑m + (1:ℝ)), exact lt_of_le_of_lt H1 (neg_lt.mp Hm.right), suffices H2 : (↑m+1)≤ (↑i:ℝ), exact neg_le_neg H2, rw [←int.cast_one,←int.cast_add], suffices H5 : (((m+1):ℤ):ℝ)≤((i:ℤ):ℝ), exact H5, rw [int.cast_le], rw [←Hi], exact calc m+1 ≤ max (n+1) (m+1) : le_max_right (n+1) (m+1) ... ≤ iz : le_max_right 1 _, suffices H1 : (n:ℝ)+1 ≤ i, -- of_rat ((n:ℤ):ℚ) + of_rat ((1:ℤ):ℚ) ≤ of_rat ((i:ℤ):ℚ), exact lt_of_lt_of_le Hn.right H1, rw [←int.cast_one,←int.cast_add], suffices H8 : (((n+1):ℤ):ℝ)≤ ((i:ℤ):ℝ), -- of_rat_add,of_rat_le_of_rat,←rat.coe_int_add,rat.coe_int_le], exact H8, rw [int.cast_le,←Hi], exact calc n+1 ≤ max (n+1) (m+1) : le_max_left (n+1) (m+1) ... ≤ iz : le_max_right 1 _, end def countable_intersection_from_one {α : Type} (X : nat → set α ) := { t : α | ∀ i, i>0 → t ∈ X i} -- part d has same sets as part c -- set_option pp.notation false theorem Q1d : countable_intersection_from_one Q1c_sets = {x | -1<x ∧ x<1} := begin unfold countable_intersection_from_one, unfold Q1c_sets, apply funext, intro x, unfold set_of, apply propext, unfold has_mem.mem set.mem, -- all that unfolding leaves us with /- x : ℝ ⊢ (∀ (i : ℕ), i > 0 → -↑i < x ∧ x < ↑i) ↔ -1 < x ∧ x < 1 -/ split;intro H, simpa using ((H 1) (zero_lt_one)), intro i, intro Hi, have i_le_one, exact nat.succ_le_of_lt Hi, split, exact calc -(i:ℝ) ≤ -↑1 : neg_le_neg (nat.cast_le.2 i_le_one) ... = -1 : by simp ... <x : H.left, exact calc x < 1 : H.right ... = ↑(1:ℕ) : by simp ... ≤ ↑i : nat.cast_le.2 i_le_one end -- question 2 def open_zero_one := { x : ℝ | 0<x ∧ x<1} theorem Q2 : forall x : ℝ, x ∈ open_zero_one → ∃ y : ℝ, y ∈ open_zero_one ∧ x<y := begin intro x, intro H, have H1 : (0:ℝ) < (2:ℝ), exact lt_add_of_le_of_pos zero_le_one zero_lt_one, existsi (x+1)/2, split, split, have H2 : 0<x, exact H.left, have H3 : 0 < (x+1), exact lt_add_of_lt_of_nonneg' H2 zero_le_one, exact lt_div_of_mul_lt H1 (by simp [H3]), suffices H2 : (x+1) < 2, -- tell nmario that without simp theres a timeout exact div_lt_of_mul_lt_of_pos H1 (by simp [H2]), exact add_lt_add_right H.right 1, have H2 : x*(1+1) < (x+1), rw [mul_add,mul_one,add_lt_add_iff_left], exact H.right, have H3 : x*2<(x+1), exact H2, exact lt_div_of_mul_lt H1 H3, -- simp [div_lt_div_of_lt_of_pos H2 H1], end -- set_option pp.notation false infix ` ** `: 80 := monoid.pow theorem Q3a (n : int) : (3:ℤ) ∣ n ** 2 → (3:ℤ) ∣ n := begin intro Hn2, -- let r := n % 3, -- let q := int.div n 3, -- have H : n = 3*q+r, have H : n % 3 < 3, exact @int.mod_lt_of_pos n 3 (by exact dec_trivial), have H2 : n%3 ≥ 0, exact int.mod_nonneg n (by exact dec_trivial), have H3 : exists r:ℕ, (n%3) = int.of_nat r, exact (int.eq_coe_of_zero_le H2), cases H3 with r Hr, have H3 : r<3, rw [←int.coe_nat_lt_coe_nat_iff,←int.of_nat_eq_coe,←Hr], exact H, cases r with r0, exact (int.dvd_iff_mod_eq_zero 3 n).mpr Hr, cases r0 with r1, clear H H2 H3, exfalso, have H : (n+2)%3=0, rw [←int.mod_add_mod,Hr], have H : int.of_nat 1 + 2 = 3, exact dec_trivial, rw [H], exact int.mod_self, have H2 : 3 ∣ ((n-2)*(n+2)), -- rw [←int.dvd_iff_mod_eq_zero], rw [←int.dvd_iff_mod_eq_zero] at H, exact dvd_trans H (dvd_mul_left _ _), simp at H2, rw [mul_add,add_mul,add_mul,add_assoc,←add_assoc (2*n) _ _,mul_comm 2 n,←mul_add,add_neg_self,mul_zero,zero_add] at H2, unfold monoid.pow at Hn2, have H3 : 3 ∣ n * (n * 1) - (n * n + 2 * -2), exact dvd_sub Hn2 H2, simp at H3, have H4 : ¬ ((3:ℤ) ∣ 2*2), exact dec_trivial, exact H4 H3, cases r1 with r2, clear H H2 H3, exfalso, have H : (n+1)%3=0, rw [←int.mod_add_mod,Hr], have H : int.of_nat 2 + 1 = 3, exact dec_trivial, rw [H], exact int.mod_self, have H2 : 3 ∣ ((n-1)*(n+1)), -- rw [←int.dvd_iff_mod_eq_zero], rw [←int.dvd_iff_mod_eq_zero] at H, exact dvd_trans H (dvd_mul_left _ _), simp at H2, rw [mul_add,add_mul,add_mul,add_assoc,←add_assoc (1*n) _ _,mul_comm 1 n,←mul_add,add_neg_self,mul_zero,zero_add] at H2, unfold monoid.pow at Hn2, have H3 : 3 ∣ n * (n * 1) - (n * n + 1 * -1), exact dvd_sub Hn2 H2, simp at H3, have H4 : ¬ ((3:ℤ) ∣ 1), exact dec_trivial, exact H4 H3, exfalso, have H4 : r2+4 ≤ 3, exact nat.succ_le_of_lt H3, repeat {rw [nat.succ_le_succ_iff] at H4}, have H5 : nat.succ r2 > 0, exact nat.zero_lt_succ r2, have H6 : 0 < 0, exact calc 0 < r2+1 : H5 ... ≤ 0 : H4, have H7 : 0 ≠ 0, exact ne_of_gt H6, have H8 : 0 = 0, refl, exact H7 H8 -- unfold int.nat_mod at r, -- unfold int.div at q, end -- square root of 3 def exists_sqrt_3 := square_root.exists_unique_square_root 3 (by norm_num) -- #check exists_sqrt_3 -- exists_sqrt_3 : ∃ (q : ℝ), q ≥ 0 ∧ q ^ 2 = 3 ∧ ∀ (s : ℝ), s ≥ 0 ∧ s ^ 2 = 3 → s = q noncomputable def sqrt3 := classical.some (exists_sqrt_3) def sqrt3_proof := classical.some_spec (exists_sqrt_3) -- #check sqrt3_proof example : sqrt3 ** 2 = 3 := sqrt3_proof.right.left noncomputable example : monoid ℝ := by apply_instance -- set_option pp.all true theorem no_rational_squared_is_three : ¬ (∃ (q:ℚ),q**2=3) := begin intro H0,cases H0 with q Hq2, rw [pow_two_eq_mul_self] at Hq2, let n:=q.num, let d0:=q.denom, have Hq_is_n_div_d : q=n/d0, rw [rat.num_denom q,rat.mk_eq_div], refl, have Hd0_not_zero : ¬ (d0=0), intro Hd0, have Hq0 : q=0, rwa [Hd0,nat.cast_zero,div_zero] at Hq_is_n_div_d, rw [Hq0,mul_zero] at Hq2, revert Hq2, norm_num, let d:ℤ:=↑d0, rw [rat.num_denom q] at Hq2, rw [rat.mk_eq_div] at Hq2, change q.denom with d0 at Hq2, change (d0:ℤ) with d at Hq2, have Hd_not_zero : ¬ (d=↑(0:ℕ)), intro H0, apply Hd0_not_zero, change d with ↑d0 at H0, exact int.of_nat.inj H0, -- tidy up change q.num with n at Hq2, clear Hq_is_n_div_d Hd0_not_zero, rw [div_mul_div] at Hq2, have H0 : (d:ℚ) * (d:ℚ) ≠ 0, intro H1, apply Hd_not_zero, rw [←int.cast_zero,←int.cast_mul,int.cast_inj] at H1, cases eq_zero_or_eq_zero_of_mul_eq_zero H1, assumption, assumption, have H1 : (3:ℚ) * (↑d * ↑d) = ↑n * ↑n, exact (eq_div_iff_mul_eq _ _ H0).mp (eq.symm Hq2), have H2 : ((3:ℤ):ℚ) * (↑d * ↑d) = ↑n * ↑n, exact H1, rw [←int.cast_mul,←int.cast_mul,←int.cast_mul,int.cast_inj] at H2, -- tidy up; now in Z. clear Hq2 H0 H1, -- coprimality of n and d0 built into rat have H0 : nat.coprime (int.nat_abs n) d0, exact q.cop, have H3 : n*n=n**2, exact mul_self_eq_pow_two, rw [H3] at H2, have H1 : (3:ℤ) ∣ n**2, exact ⟨d*d,eq.symm H2⟩, have H4 : (3:ℤ) ∣ n, exact Q3a n H1, cases H4 with n1 H5, rw [←H3,H5] at H2,clear H3, rw [mul_assoc] at H2, have H6 : d * d = n1 * (3 * n1), exact eq_of_mul_eq_mul_left (by norm_num) H2,clear H2, rw [mul_comm n1,mul_assoc] at H6, rw [mul_self_eq_pow_two] at H6, have H2 : (3:ℤ) ∣ d**2, exact ⟨n1 * n1, H6⟩, clear H1 H6, have H1 : (3:ℤ) ∣ d, exact Q3a d H2, clear H2, cases H1 with d1 H2, -- now know H5 : n=3*something, -- H2 : d = 3 * something, -- H0 : n coprime to d (modulo coercions) -- Seems like I now have to coerce everything down to nat let n0 := int.nat_abs n, clear Hd_not_zero, change int.nat_abs n with n0 at H0, let n2 := int.nat_abs n1, have H1 : n0 = 3 * n2, change (3:ℕ) with int.nat_abs (3:ℤ), rw [←int.nat_abs_mul,←H5], clear H5, let d2 := int.nat_abs d1, have H3 : d0 = 3 * d2, rw [←int.nat_abs_of_nat d0], change 3 with int.nat_abs (3:ℤ), change d2 with int.nat_abs d1, rw [←int.nat_abs_mul,←H2], rw [H1,H3] at H0, clear H3 H2 d d0 H1 n0 n q, have H1 : nat.coprime (3 * n2) 3, exact nat.coprime.coprime_mul_right_right H0, clear H0, rw [mul_comm] at H1, have H2 :nat.coprime 3 3, exact nat.coprime.coprime_mul_left H1, clear H1 n2 d2 n1 d1, have H0 : nat.gcd 3 3 = 1, exact H2,clear H2, have H1 : 3 ∣ nat.gcd 3 3, exact nat.dvd_gcd ⟨1,mul_one 3⟩ ⟨1,mul_one 3⟩, rw H0 at H1, clear H0, have H0 : 3 = 1, exact nat.eq_one_of_dvd_one H1, clear H1, revert H0, norm_num, end theorem Q3b : M1F.is_irrational (sqrt3) := begin unfold M1F.is_irrational, intro H, cases H with q Hq, have Hq2 : q*q = (3:ℚ), rw [←@rat.cast_inj ℝ _ _ (q*q) (3:ℚ),rat.cast_mul,Hq,mul_self_eq_pow_two], unfold sqrt3, rw [sqrt3_proof.right.left], norm_num, clear Hq, rw [mul_self_eq_pow_two] at Hq2, apply no_rational_squared_is_three, existsi q, exact Hq2, end -- #print no_rational_squared_is_three -- interesting with pp.all true #print Q3b theorem Q4a : ¬ (∀ (x y : ℝ), M1F.is_irrational x → M1F.is_irrational y → M1F.is_irrational (x+y)) := begin intro H, let H2 := H sqrt3 (-sqrt3) Q3b, have H3 : M1F.is_irrational (-sqrt3), unfold M1F.is_irrational, intro H4, cases H4 with q Hq, apply Q3b, exact ⟨-q, begin rw [rat.cast_neg], exact eq.symm (eq_neg_iff_eq_neg.mpr (Hq)), end ⟩, apply H2 H3, exact ⟨0, begin rw [add_neg_self,rat.cast_zero], end ⟩, end theorem Q4b : ¬ (∀ (a : ℝ), ∀ (b : ℚ), M1F.is_irrational a → M1F.is_irrational (a*b)) := begin intro H, let H2 := H sqrt3 0 Q3b, apply H2, exact ⟨0,by rw [rat.cast_zero,mul_zero]⟩, end theorem Q5a : ∀ (x : ℝ), ∃ (y:ℝ), x+y=2 := begin intro x, exact ⟨-x+2,by rw [←add_assoc,add_neg_self,zero_add]⟩, end theorem Q5b : ¬ (∃ (y:ℝ), ∀ (x:ℝ), x+y=2) := begin intro H, cases H with y Hy, let H := Hy (-y), rw [neg_add_self] at H, revert H, norm_num, end theorem Q6 : square_root.sqrt_abs 2 + square_root.sqrt_abs 6 < square_root.sqrt_abs 15 := begin let s2 := square_root.sqrt_abs 2, change square_root.sqrt_abs 2 with s2, -- let s6 := square_root.sqrt_abs 6, change square_root.sqrt_abs 6 with s6, -- let s15 := square_root.sqrt_abs 15, change square_root.sqrt_abs 15 with s15, -- I just want names for these variables. have Hs15 : s15**2 = 15, exact square_root.sqrt_abs_squared 15 (by norm_num), rw [pow_two_eq_mul_self] at Hs15, have Hs2 : s2**2 = 2, exact square_root.sqrt_abs_squared 2 (by norm_num), rw [pow_two_eq_mul_self] at Hs2, have Hs6 : s6**2 = 6, exact square_root.sqrt_abs_squared 6 (by norm_num), -- I know I'll need these things at some point. rw [pow_two_eq_mul_self] at Hs6, apply imp_of_not_or (le_or_gt s15 (s2 + s6)), intro H1, -- now square both sides of H1 have H2 : s15 ≥ 0, exact square_root.sqrt_abs_ge_zero 15, have H3 : s15*s15 ≤ (s2+s6)*(s2+s6) := mul_self_le_mul_self H2 H1, rw [Hs15,add_mul_self_eq,Hs2,Hs6] at H3, rw [←sub_le_iff_le_add,add_comm,←sub_le_iff_le_add] at H3, revert H3, norm_num, intro H3, have H4 : 7*7 ≤ (s2*(s6*2))*(s2*(s6*2)) := mul_self_le_mul_self (by norm_num) H3, have H5 : (49:ℝ) ≤ 48 := calc 49 = 7 * 7 : by norm_num ... ≤ s2 * (s6 * 2) * (s2 * (s6 * 2)) : H4 ... = (s2*s2)*(s6*s6)*(2*2) : by simp ... = (2:ℝ)*6*(2*2) : by rw [Hs2,Hs6] ... = 48 : by norm_num, revert H5, norm_num, end /- Q7 : are the following numbers rational or irrational (a) sqrt(2)+sqrt(3/2) (b) 1+sqrt(2)+sqrt(3/2) (c) 2sqrt(18)-3sqrt(8) -/ theorem Q7a : M1F.is_irrational (square_root.sqrt_abs 2 + square_root.sqrt_abs (3/2)) := begin let s2 := square_root.sqrt_abs 2, change square_root.sqrt_abs 2 with s2, have Hs2 : s2**2 = 2, exact square_root.sqrt_abs_squared 2 (by norm_num), rw [pow_two_eq_mul_self] at Hs2, let s3o2 := square_root.sqrt_abs (3/2), change square_root.sqrt_abs (3/2) with s3o2, have Hs3o2 : s3o2**2 = 3/2, exact square_root.sqrt_abs_squared (3/2) (by norm_num), rw [pow_two_eq_mul_self] at Hs3o2, intro H,cases H with q Hq, have H1 : (q:ℝ)*q = 2 + 2*s2*s3o2 + (3/2) := calc (q:ℝ)*q = (s2 + s3o2)*(s2+s3o2) : by rw [Hq] ... = _ : by rw [add_mul_self_eq] ... = 2 + 2*s2*s3o2 + (3/2) : by rw [Hs2,Hs3o2], rw [←sub_eq_iff_eq_add,add_comm,←sub_eq_iff_eq_add] at H1, let r:ℚ := q*q-3/2-2, have H2 : (r:ℝ)=↑q * ↑q - 3 / 2 - 2, norm_num, rw [←H2] at H1, let s:ℚ := r/2, have H2not0 : (2:ℝ) ≠ 0 := by norm_num, have Htemp : (2*(s2*s3o2))/2 = s2*s3o2 := mul_div_cancel_left (s2*s3o2) H2not0, rw ←mul_assoc at Htemp, have H3 : (s:ℝ)*s=3 := calc (s:ℝ)*s=(r/2)*(r/2) : by simp ... = ((2*s2*s3o2)/2)*((2*s2*s3o2)/2) : by rw [H1] ... = (s2*s3o2)*(s2*s3o2) : by rw [Htemp] -- simp [H2not0,mul_assoc,mul_div_cancel_left] -- rw [mul_assoc,mul_div_cancel_left,mul_assoc,mul_div_cancel_left];exact H2not0 ... = (s2*s2)*(s3o2*s3o2) : by simp ... = 2*(3/2) : by rw [Hs2,Hs3o2] ... = 3 : by norm_num, let t:ℚ := abs s, have H4 : (t:ℝ)*t=3, change t with abs s, rwa [←rat.cast_mul,abs_mul_abs_self,rat.cast_mul], have H4 : (t:ℝ) = sqrt3, apply sqrt3_proof.right.right t, split, change t with abs s, rw [rat.cast_abs], exact abs_nonneg (s:ℝ), rwa [pow_two_eq_mul_self], have Htemp2 :M1F.is_irrational (t:ℝ), rw [H4], exact Q3b, apply Htemp2, existsi t, refl, end theorem Q7b : M1F.is_irrational (1+square_root.sqrt_abs 2+square_root.sqrt_abs (3/2)) := begin intro H, apply Q7a, cases H with q Hq, existsi (q-1), rw [rat.cast_sub,Hq], simp, end theorem Q7c : exists q:ℚ, (q:ℝ) = 2*square_root.sqrt_abs 18 - 3 * square_root.sqrt_abs 8 := begin existsi (0:ℚ), rw [rat.cast_zero],apply eq.symm, rw [sub_eq_zero_iff_eq,mul_comm], -- apply eq.symm, apply mul_eq_of_eq_div, norm_num, apply eq.symm, apply square_root.sqrt_abs_unique, { norm_num}, split, apply div_nonneg_of_nonneg_of_pos _ _, apply mul_nonneg _ _, norm_num, apply square_root.sqrt_abs_ge_zero _, norm_num, -- rw [div_eq_mul_inv], exact calc 3 * square_root.sqrt_abs 8 / 2 * (3 * square_root.sqrt_abs 8 / 2) = (square_root.sqrt_abs 8) * (square_root.sqrt_abs 8) * 3 * 3 / 2 / 2 : by simp [div_eq_mul_inv] ... = 8*3*3/2/2 : by rw [square_root.sqrt_abs_mul_self 8 (by norm_num)] ... = 18 : by norm_num, end #print Q3b -/ end M1F_Sheet02
1b6159ff6a3a8e1a4cc5f71f4999694e1ebaa1d2
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/bytearray.lean
99b2cd680ad3d8d9ba25f9ef578346da69ee7884
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
231
lean
def tst : IO Unit := do let bs := [1, 2, 3].toByteArray; IO.println bs; let bs := bs.push 4; let bs := bs.set! 1 20; IO.println bs; let bs₁ := bs.set! 2 30; IO.println bs₁; IO.println bs; IO.println bs.size; pure () #eval tst
96159a4c1bfeb9916a0a700ca38e5afb6d920509
3446e92e64a5de7ed1f2109cfb024f83cd904c34
/src/game/world1/level3.lean
fd9c5a42bcd56197be546f55a550ac1f36fda034
[]
no_license
kckennylau/natural_number_game
019f4a5f419c9681e65234ecd124c564f9a0a246
ad8c0adaa725975be8a9f978c8494a39311029be
refs/heads/master
1,598,784,137,722
1,571,905,156,000
1,571,905,156,000
218,354,686
0
0
null
1,572,373,319,000
1,572,373,318,000
null
UTF-8
Lean
false
false
2,863
lean
import mynat.definition -- hide namespace mynat -- hide /- # World 1 : Tutorial world ## level 3: The rewrite (`rw`) tactic. The rewrite tactic is the way to "substitute in" the value of a variable. In general, If you have a hypothesis of the form `A = B`, and your goal mentions the left hand side `A` somewhere, then the `rewrite` tactic will replace the `A` in your goal with a `B`. Below is a theorem which looks obvious, but which cannot be proved using `refl` and `exact` alone -- you need a rewrite. Delete the sorry and take a look in the top right box at what we have. The variables `x`, `y` and `z` are natural numbers, and we have functions `f` and `g` from natural numbers to natural numbers. We have a proof `h` of `y = f(x)` and our goal is to prove that `g(y) = g(f(x))`. This goal is obvious -- we just substitute in `y = f(x)` into the goal and we're done. In Lean, we do this substitution using the `rw` tactic. So start your proof with `rw h,` and then hit enter. **don't forget the comma.** Did you see what happened to the goal? The goal doesn't close, but it *changes* from `⊢ g y = g (f x)` to `⊢ g (f x) = g (f x)` (note that computer scientists are a bit less liberal with brackets than mathematicians!). We can just close this goal with `refl,` written on the line after `rw h,`. Don't forget the comma, hit enter, and enjoy seeing the "Proof complete!" message in the top right window. The other reason you'll know you're done is that the bottom right window (the error window) becomes empty. -/ /- Lemma : no-side-bar For all natural numbers $x$, $y$ and $z$ and all functions $f$ and $g$ from the naturals to themselves, if $y = f(x)$ and then $g(y) = g(f(x))$. -/ lemma example3 (x y z : mynat) (f g : mynat → mynat) (h : y = f(x)) : g(y) = g(f(x)) := begin [less_leaky] rw h, refl end /- Tactic : rw The `rw` tactic is a way to do "substituting in". If `h : A = B` is a hypothesis (i.e., a proof of `A = B`) and your goal contains one or more `A`s, then `rw h` will change them all to `B`'s. If you want to change `B`s to `A`s instead, try `rw ←h` (get the arrow with `\l`). ### Example: If it looks like this in the top right hand box: ``` x y : mynat h : x = y + 3 ⊢ 1 + x = y + 4 ``` then `rw h,` will change the goal into `⊢ 1 + (y + 3) = y + 4`. Note of course that this goal is still far from solved. -/ /- ## Exploring your proof. 1) Click on `refl,` and then use the arrow keys to move your cursor around the proof. Go up and down and note that the goal changes -- indeed you can inspect Lean's "state" at each line of the proof (the hypotheses, and the goal). Try to figure out the exact place where the goal changes. The comma tells Lean "I've finished writing this tactic now, please process it." Lean ignores newlines, but pays great attention to commas. -/ end mynat -- hide
8a8ea119d63833f38bf3b09462798a96efe77c38
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/algebra/basic_auto.lean
a0c8a2245c8e3f1db16cf7bc33c52bb9263c93fe
[]
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
75,001
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.nth_rewrite.default import Mathlib.data.matrix.basic import Mathlib.data.equiv.ring_aut import Mathlib.linear_algebra.tensor_product import Mathlib.ring_theory.subring import Mathlib.deprecated.subring import Mathlib.algebra.opposites import Mathlib.PostPort universes u v l u_1 u_2 w u₁ v₁ u_3 u_4 namespace Mathlib /-! # Algebra over Commutative Semiring In this file we define `algebra`s over commutative (semi)rings, algebra homomorphisms `alg_hom`, algebra equivalences `alg_equiv`. We also define usual operations on `alg_hom`s (`id`, `comp`). `subalgebra`s are defined in `algebra.algebra.subalgebra`. If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replaced with `is_scalar_tower`. For the category of `R`-algebras, denoted `Algebra R`, see the file `algebra/category/Algebra/basic.lean`. ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ -- We set this priority to 0 later in this file /-- Given a commutative (semi)ring `R`, an `R`-algebra is a (possibly noncommutative) (semi)ring `A` endowed with a morphism of rings `R →+* A` which lands in the center of `A`. For convenience, this typeclass extends `has_scalar R A` where the scalar action must agree with left multiplication by the image of the structure morphism. Given an `algebra R A` instance, the structure morphism `R →+* A` is denoted `algebra_map R A`. -/ class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R →+* A where commutes' : ∀ (r : R) (x : A), ring_hom.to_fun _to_ring_hom r * x = x * ring_hom.to_fun _to_ring_hom r smul_def' : ∀ (r : R) (x : A), r • x = ring_hom.to_fun _to_ring_hom r * x /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R : Type u_1} {S : Type u_2} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ (c : R) (x : S), coe_fn i c * x = x * coe_fn i c) : algebra R S := algebra.mk i h sorry /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R : Type u_1} {S : Type u_2} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := ring_hom.to_algebra' i sorry theorem ring_hom.algebra_map_to_algebra {R : Type u_1} {S : Type u_2} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra_map R S = i := rfl namespace algebra /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule' {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x : A), r • 1 * x = r • x) (h₂ : ∀ (r : R) (x : A), x * r • 1 = r • x) : algebra R A := mk (ring_hom.mk (fun (r : R) => r • 1) sorry sorry sorry sorry) sorry sorry /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x y : A), r • x * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * r • y = r • (x * y)) : algebra R A := of_semimodule' sorry sorry theorem smul_def'' {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] (r : R) (x : A) : r • x = coe_fn (algebra_map R A) r * x := smul_def' r x /-- To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree, it suffices to check the `algebra_map`s agree. -/ -- We'll later use this to show `algebra ℤ M` is a subsingleton. theorem algebra_ext {R : Type u_1} [comm_semiring R] {A : Type u_2} [semiring A] (P : algebra R A) (Q : algebra R A) (w : ∀ (r : R), coe_fn (algebra_map R A) r = coe_fn (algebra_map R A) r) : P = Q := sorry protected instance to_semimodule {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] : semimodule R A := semimodule.mk sorry sorry -- from now on, we don't want to use the following instance anymore theorem smul_def {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] (r : R) (x : A) : r • x = coe_fn (algebra_map R A) r * x := smul_def' r x theorem algebra_map_eq_smul_one {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] (r : R) : coe_fn (algebra_map R A) r = r • 1 := Eq.trans (Eq.symm (mul_one (coe_fn (algebra_map R A) r))) (Eq.symm (smul_def r 1)) theorem commutes {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] (r : R) (x : A) : coe_fn (algebra_map R A) r * x = x * coe_fn (algebra_map R A) r := commutes' r x theorem left_comm {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] (r : R) (x : A) (y : A) : x * (coe_fn (algebra_map R A) r * y) = coe_fn (algebra_map R A) r * (x * y) := sorry @[simp] theorem mul_smul_comm {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] (s : R) (x : A) (y : A) : x * s • y = s • (x * y) := sorry @[simp] theorem smul_mul_assoc {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] (r : R) (x : A) (y : A) : r • x * y = r • (x * y) := sorry @[simp] theorem bit0_smul_one {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] {r : R} : bit0 r • 1 = r • bit0 1 := sorry @[simp] theorem bit0_smul_bit0 {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] {r : R} {a : A} : bit0 r • bit0 a = r • bit0 (bit0 a) := sorry @[simp] theorem bit0_smul_bit1 {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] {r : R} {a : A} : bit0 r • bit1 a = r • bit0 (bit1 a) := sorry @[simp] theorem bit1_smul_one {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] {r : R} : bit1 r • 1 = r • bit0 1 + 1 := sorry @[simp] theorem bit1_smul_bit0 {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] {r : R} {a : A} : bit1 r • bit0 a = r • bit0 (bit0 a) + bit0 a := sorry @[simp] theorem bit1_smul_bit1 {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] {r : R} {a : A} : bit1 r • bit1 a = r • bit0 (bit1 a) + bit1 a := sorry /-- The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`, packaged as an `R`-linear map. -/ protected def linear_map (R : Type u) (A : Type w) [comm_semiring R] [semiring A] [algebra R A] : linear_map R R A := linear_map.mk (ring_hom.to_fun (algebra_map R A)) sorry sorry @[simp] theorem linear_map_apply (R : Type u) (A : Type w) [comm_semiring R] [semiring A] [algebra R A] (r : R) : coe_fn (algebra.linear_map R A) r = coe_fn (algebra_map R A) r := rfl protected instance id (R : Type u) [comm_semiring R] : algebra R R := ring_hom.to_algebra (ring_hom.id R) namespace id @[simp] theorem map_eq_self {R : Type u} [comm_semiring R] (x : R) : coe_fn (algebra_map R R) x = x := rfl @[simp] theorem smul_eq_mul {R : Type u} [comm_semiring R] (x : R) (y : R) : x • y = x * y := rfl end id protected instance prod.algebra (R : Type u) (A : Type w) (B : Type u_1) [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] : algebra R (A × B) := mk (ring_hom.mk (ring_hom.to_fun (ring_hom.prod (algebra_map R A) (algebra_map R B))) sorry sorry sorry sorry) sorry sorry @[simp] theorem algebra_map_prod_apply {R : Type u} {A : Type w} {B : Type u_1} [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] (r : R) : coe_fn (algebra_map R (A × B)) r = (coe_fn (algebra_map R A) r, coe_fn (algebra_map R B) r) := rfl /-- Algebra over a subsemiring. -/ protected instance of_subsemiring {R : Type u} {A : Type w} [comm_semiring R] [semiring A] [algebra R A] (S : subsemiring R) : algebra (↥S) A := mk (ring_hom.mk (ring_hom.to_fun (ring_hom.comp (algebra_map R A) (subsemiring.subtype S))) sorry sorry sorry sorry) sorry sorry /-- Algebra over a subring. -/ protected instance of_subring {R : Type u_1} {A : Type u_2} [comm_ring R] [ring A] [algebra R A] (S : subring R) : algebra (↥S) A := mk (ring_hom.mk (ring_hom.to_fun (ring_hom.comp (algebra_map R A) (subring.subtype S))) sorry sorry sorry sorry) sorry sorry theorem algebra_map_of_subring {R : Type u_1} [comm_ring R] (S : subring R) : algebra_map (↥S) R = subring.subtype S := rfl theorem coe_algebra_map_of_subring {R : Type u_1} [comm_ring R] (S : subring R) : ⇑(algebra_map (↥S) R) = subtype.val := rfl theorem algebra_map_of_subring_apply {R : Type u_1} [comm_ring R] (S : subring R) (x : ↥S) : coe_fn (algebra_map (↥S) R) x = ↑x := rfl /-- Algebra over a set that is closed under the ring operations. -/ def of_is_subring {R : Type u_1} {A : Type u_2} [comm_ring R] [ring A] [algebra R A] (S : set R) [is_subring S] : algebra (↥S) A := algebra.of_subring (set.to_subring S) theorem is_subring_coe_algebra_map_hom {R : Type u_1} [comm_ring R] (S : set R) [is_subring S] : algebra_map (↥S) R = is_subring.subtype S := rfl theorem is_subring_coe_algebra_map {R : Type u_1} [comm_ring R] (S : set R) [is_subring S] : ⇑(algebra_map (↥S) R) = subtype.val := rfl theorem is_subring_algebra_map_apply {R : Type u_1} [comm_ring R] (S : set R) [is_subring S] (x : ↥S) : coe_fn (algebra_map (↥S) R) x = ↑x := rfl theorem set_range_subset {R : Type u_1} [comm_ring R] {T₁ : set R} {T₂ : set R} [is_subring T₁] (hyp : T₁ ⊆ T₂) : set.range ⇑(algebra_map (↥T₁) R) ⊆ T₂ := sorry /-- Explicit characterization of the submonoid map in the case of an algebra. `S` is made explicit to help with type inference -/ def algebra_map_submonoid {R : Type u} [comm_semiring R] (S : Type u_1) [semiring S] [algebra R S] (M : submonoid R) : submonoid S := submonoid.map (↑(algebra_map R S)) M theorem mem_algebra_map_submonoid_of_mem {R : Type u} {S : Type v} [comm_semiring R] [comm_semiring S] [algebra R S] {M : submonoid R} (x : ↥M) : coe_fn (algebra_map R S) ↑x ∈ algebra_map_submonoid S M := set.mem_image_of_mem (⇑(algebra_map R S)) (subtype.property x) /-- A `semiring` that is an `algebra` over a commutative ring carries a natural `ring` structure. -/ def semiring_to_ring (R : Type u) {A : Type w} [comm_ring R] [semiring A] [algebra R A] : ring A := ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry theorem mul_sub_algebra_map_commutes {R : Type u} {A : Type w} [comm_ring R] [ring A] [algebra R A] (x : A) (r : R) : x * (x - coe_fn (algebra_map R A) r) = (x - coe_fn (algebra_map R A) r) * x := sorry theorem mul_sub_algebra_map_pow_commutes {R : Type u} {A : Type w} [comm_ring R] [ring A] [algebra R A] (x : A) (r : R) (n : ℕ) : x * (x - coe_fn (algebra_map R A) r) ^ n = (x - coe_fn (algebra_map R A) r) ^ n * x := sorry end algebra namespace opposite protected instance algebra {R : Type u_1} {A : Type u_2} [comm_semiring R] [semiring A] [algebra R A] : algebra R (Aᵒᵖ) := algebra.mk (ring_hom.to_opposite (algebra_map R A) sorry) sorry sorry @[simp] theorem algebra_map_apply {R : Type u_1} {A : Type u_2} [comm_semiring R] [semiring A] [algebra R A] (c : R) : coe_fn (algebra_map R (Aᵒᵖ)) c = op (coe_fn (algebra_map R A) c) := rfl end opposite namespace module protected instance endomorphism_algebra (R : Type u) (M : Type v) [comm_semiring R] [add_comm_monoid M] [semimodule R M] : algebra R (linear_map R M M) := algebra.mk (ring_hom.mk (fun (r : R) => r • linear_map.id) sorry sorry sorry sorry) sorry sorry theorem algebra_map_End_eq_smul_id (R : Type u) (M : Type v) [comm_semiring R] [add_comm_monoid M] [semimodule R M] (a : R) : coe_fn (algebra_map R (End R M)) a = a • linear_map.id := rfl @[simp] theorem algebra_map_End_apply (R : Type u) (M : Type v) [comm_semiring R] [add_comm_monoid M] [semimodule R M] (a : R) (m : M) : coe_fn (coe_fn (algebra_map R (End R M)) a) m = a • m := rfl @[simp] theorem ker_algebra_map_End (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] (a : K) (ha : a ≠ 0) : linear_map.ker (coe_fn (algebra_map K (End K V)) a) = ⊥ := linear_map.ker_smul linear_map.id a ha end module protected instance matrix_algebra (n : Type u) (R : Type v) [DecidableEq n] [fintype n] [comm_semiring R] : algebra R (matrix n n R) := algebra.mk (ring_hom.mk (ring_hom.to_fun (matrix.scalar n)) sorry sorry sorry sorry) sorry sorry /-- Defining the homomorphism in the category R-Alg. -/ structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A →+* B where commutes' : ∀ (r : R), to_fun (coe_fn (algebra_map R A) r) = coe_fn (algebra_map R B) r namespace alg_hom protected instance has_coe_to_fun {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] : has_coe_to_fun (alg_hom R A B) := has_coe_to_fun.mk (fun (f : alg_hom R A B) => A → B) fun (f : alg_hom R A B) => to_fun f protected instance coe_ring_hom {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] : has_coe (alg_hom R A B) (A →+* B) := has_coe.mk to_ring_hom protected instance coe_monoid_hom {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] : has_coe (alg_hom R A B) (A →* B) := has_coe.mk fun (f : alg_hom R A B) => ↑↑f protected instance coe_add_monoid_hom {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] : has_coe (alg_hom R A B) (A →+ B) := has_coe.mk fun (f : alg_hom R A B) => ↑↑f @[simp] theorem coe_mk {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] {f : A → B} (h₁ : f 1 = 1) (h₂ : ∀ (x y : A), f (x * y) = f x * f y) (h₃ : f 0 = 0) (h₄ : ∀ (x y : A), f (x + y) = f x + f y) (h₅ : ∀ (r : R), f (coe_fn (algebra_map R A) r) = coe_fn (algebra_map R B) r) : ⇑(mk f h₁ h₂ h₃ h₄ h₅) = f := rfl @[simp] theorem coe_to_ring_hom {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (f : alg_hom R A B) : ⇑↑f = ⇑f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. theorem coe_to_monoid_hom {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (f : alg_hom R A B) : ⇑↑f = ⇑f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. theorem coe_to_add_monoid_hom {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (f : alg_hom R A B) : ⇑↑f = ⇑f := rfl theorem coe_fn_inj {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] {φ₁ : alg_hom R A B} {φ₂ : alg_hom R A B} (H : ⇑φ₁ = ⇑φ₂) : φ₁ = φ₂ := sorry theorem coe_ring_hom_injective {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] : function.injective coe := fun (φ₁ φ₂ : alg_hom R A B) (H : ↑φ₁ = ↑φ₂) => coe_fn_inj ((fun (this : ⇑↑φ₁ = ⇑↑φ₂) => this) (congr_arg coe_fn H)) theorem coe_monoid_hom_injective {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] : function.injective coe := function.injective.comp ring_hom.coe_monoid_hom_injective coe_ring_hom_injective theorem coe_add_monoid_hom_injective {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] : function.injective coe := function.injective.comp ring_hom.coe_add_monoid_hom_injective coe_ring_hom_injective protected theorem congr_fun {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] {φ₁ : alg_hom R A B} {φ₂ : alg_hom R A B} (H : φ₁ = φ₂) (x : A) : coe_fn φ₁ x = coe_fn φ₂ x := H ▸ rfl protected theorem congr_arg {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) {x : A} {y : A} (h : x = y) : coe_fn φ x = coe_fn φ y := h ▸ rfl theorem ext {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] {φ₁ : alg_hom R A B} {φ₂ : alg_hom R A B} (H : ∀ (x : A), coe_fn φ₁ x = coe_fn φ₂ x) : φ₁ = φ₂ := coe_fn_inj (funext H) theorem ext_iff {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] {φ₁ : alg_hom R A B} {φ₂ : alg_hom R A B} : φ₁ = φ₂ ↔ ∀ (x : A), coe_fn φ₁ x = coe_fn φ₂ x := { mp := alg_hom.congr_fun, mpr := ext } @[simp] theorem mk_coe {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] {f : alg_hom R A B} (h₁ : coe_fn f 1 = 1) (h₂ : ∀ (x y : A), coe_fn f (x * y) = coe_fn f x * coe_fn f y) (h₃ : coe_fn f 0 = 0) (h₄ : ∀ (x y : A), coe_fn f (x + y) = coe_fn f x + coe_fn f y) (h₅ : ∀ (r : R), coe_fn f (coe_fn (algebra_map R A) r) = coe_fn (algebra_map R B) r) : mk (⇑f) h₁ h₂ h₃ h₄ h₅ = f := ext fun (_x : A) => rfl @[simp] theorem commutes {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (r : R) : coe_fn φ (coe_fn (algebra_map R A) r) = coe_fn (algebra_map R B) r := commutes' φ r theorem comp_algebra_map {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) : ring_hom.comp (↑φ) (algebra_map R A) = algebra_map R B := ring_hom.ext (commutes φ) @[simp] theorem map_add {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (r : A) (s : A) : coe_fn φ (r + s) = coe_fn φ r + coe_fn φ s := ring_hom.map_add (to_ring_hom φ) r s @[simp] theorem map_zero {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) : coe_fn φ 0 = 0 := ring_hom.map_zero (to_ring_hom φ) @[simp] theorem map_mul {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (x : A) (y : A) : coe_fn φ (x * y) = coe_fn φ x * coe_fn φ y := ring_hom.map_mul (to_ring_hom φ) x y @[simp] theorem map_one {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) : coe_fn φ 1 = 1 := ring_hom.map_one (to_ring_hom φ) @[simp] theorem map_smul {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (r : R) (x : A) : coe_fn φ (r • x) = r • coe_fn φ x := sorry @[simp] theorem map_pow {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (x : A) (n : ℕ) : coe_fn φ (x ^ n) = coe_fn φ x ^ n := ring_hom.map_pow (to_ring_hom φ) x n theorem map_sum {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) {ι : Type u_1} (f : ι → A) (s : finset ι) : coe_fn φ (finset.sum s fun (x : ι) => f x) = finset.sum s fun (x : ι) => coe_fn φ (f x) := ring_hom.map_sum (to_ring_hom φ) f s theorem map_finsupp_sum {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) {α : Type u_1} [HasZero α] {ι : Type u_2} (f : ι →₀ α) (g : ι → α → A) : coe_fn φ (finsupp.sum f g) = finsupp.sum f fun (i : ι) (a : α) => coe_fn φ (g i a) := map_sum φ (fun (a : ι) => g a (coe_fn f a)) (finsupp.support f) @[simp] theorem map_nat_cast {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (n : ℕ) : coe_fn φ ↑n = ↑n := ring_hom.map_nat_cast (to_ring_hom φ) n @[simp] theorem map_bit0 {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (x : A) : coe_fn φ (bit0 x) = bit0 (coe_fn φ x) := ring_hom.map_bit0 (to_ring_hom φ) x @[simp] theorem map_bit1 {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (x : A) : coe_fn φ (bit1 x) = bit1 (coe_fn φ x) := ring_hom.map_bit1 (to_ring_hom φ) x /-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/ def mk' {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (f : A →+* B) (h : ∀ (c : R) (x : A), coe_fn f (c • x) = c • coe_fn f x) : alg_hom R A B := mk (⇑f) (ring_hom.map_one' f) (ring_hom.map_mul' f) (ring_hom.map_zero' f) (ring_hom.map_add' f) sorry @[simp] theorem coe_mk' {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (f : A →+* B) (h : ∀ (c : R) (x : A), coe_fn f (c • x) = c • coe_fn f x) : ⇑(mk' f h) = ⇑f := rfl /-- Identity map as an `alg_hom`. -/ protected def id (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : alg_hom R A A := mk (ring_hom.to_fun (ring_hom.id A)) sorry sorry sorry sorry sorry @[simp] theorem id_apply {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (p : A) : coe_fn (alg_hom.id R A) p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} [comm_semiring R] [semiring A] [semiring B] [semiring C] [algebra R A] [algebra R B] [algebra R C] (φ₁ : alg_hom R B C) (φ₂ : alg_hom R A B) : alg_hom R A C := mk (ring_hom.to_fun (ring_hom.comp (to_ring_hom φ₁) ↑φ₂)) sorry sorry sorry sorry sorry @[simp] theorem comp_apply {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} [comm_semiring R] [semiring A] [semiring B] [semiring C] [algebra R A] [algebra R B] [algebra R C] (φ₁ : alg_hom R B C) (φ₂ : alg_hom R A B) (p : A) : coe_fn (comp φ₁ φ₂) p = coe_fn φ₁ (coe_fn φ₂ p) := rfl @[simp] theorem comp_id {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) : comp φ (alg_hom.id R A) = φ := ext fun (x : A) => rfl @[simp] theorem id_comp {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) : comp (alg_hom.id R B) φ = φ := ext fun (x : A) => rfl theorem comp_assoc {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] [algebra R A] [algebra R B] [algebra R C] [algebra R D] (φ₁ : alg_hom R C D) (φ₂ : alg_hom R B C) (φ₃ : alg_hom R A B) : comp (comp φ₁ φ₂) φ₃ = comp φ₁ (comp φ₂ φ₃) := ext fun (x : A) => rfl /-- R-Alg ⥤ R-Mod -/ def to_linear_map {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) : linear_map R A B := linear_map.mk (⇑φ) (map_add φ) (map_smul φ) @[simp] theorem to_linear_map_apply {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (p : A) : coe_fn (to_linear_map φ) p = coe_fn φ p := rfl theorem to_linear_map_inj {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] {φ₁ : alg_hom R A B} {φ₂ : alg_hom R A B} (H : to_linear_map φ₁ = to_linear_map φ₂) : φ₁ = φ₂ := sorry @[simp] theorem comp_to_linear_map {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} [comm_semiring R] [semiring A] [semiring B] [semiring C] [algebra R A] [algebra R B] [algebra R C] (f : alg_hom R A B) (g : alg_hom R B C) : to_linear_map (comp g f) = linear_map.comp (to_linear_map g) (to_linear_map f) := rfl theorem map_prod {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [comm_semiring A] [comm_semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) {ι : Type u_1} (f : ι → A) (s : finset ι) : coe_fn φ (finset.prod s fun (x : ι) => f x) = finset.prod s fun (x : ι) => coe_fn φ (f x) := ring_hom.map_prod (to_ring_hom φ) f s theorem map_finsupp_prod {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [comm_semiring A] [comm_semiring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) {α : Type u_1} [HasZero α] {ι : Type u_2} (f : ι →₀ α) (g : ι → α → A) : coe_fn φ (finsupp.prod f g) = finsupp.prod f fun (i : ι) (a : α) => coe_fn φ (g i a) := map_prod φ (fun (a : ι) => g a (coe_fn f a)) (finsupp.support f) @[simp] theorem map_neg {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [ring A] [ring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (x : A) : coe_fn φ (-x) = -coe_fn φ x := ring_hom.map_neg (to_ring_hom φ) x @[simp] theorem map_sub {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [ring A] [ring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (x : A) (y : A) : coe_fn φ (x - y) = coe_fn φ x - coe_fn φ y := ring_hom.map_sub (to_ring_hom φ) x y @[simp] theorem map_int_cast {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [ring A] [ring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (n : ℤ) : coe_fn φ ↑n = ↑n := ring_hom.map_int_cast (to_ring_hom φ) n @[simp] theorem map_inv {R : Type u} {A : Type v} {B : Type w} [comm_ring R] [division_ring A] [division_ring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (x : A) : coe_fn φ (x⁻¹) = (coe_fn φ x⁻¹) := ring_hom.map_inv (to_ring_hom φ) x @[simp] theorem map_div {R : Type u} {A : Type v} {B : Type w} [comm_ring R] [division_ring A] [division_ring B] [algebra R A] [algebra R B] (φ : alg_hom R A B) (x : A) (y : A) : coe_fn φ (x / y) = coe_fn φ x / coe_fn φ y := ring_hom.map_div (to_ring_hom φ) x y theorem injective_iff {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_semiring R] [ring A] [semiring B] [algebra R A] [algebra R B] (f : alg_hom R A B) : function.injective ⇑f ↔ ∀ (x : A), coe_fn f x = 0 → x = 0 := ring_hom.injective_iff ↑f end alg_hom /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃+ B, A ≃+* B, A ≃ B, A ≃* B where commutes' : ∀ (r : R), to_fun (coe_fn (algebra_map R A) r) = coe_fn (algebra_map R B) r namespace alg_equiv protected instance has_coe_to_fun {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] : has_coe_to_fun (alg_equiv R A₁ A₂) := has_coe_to_fun.mk (fun (x : alg_equiv R A₁ A₂) => A₁ → A₂) to_fun theorem ext {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {f : alg_equiv R A₁ A₂} {g : alg_equiv R A₁ A₂} (h : ∀ (a : A₁), coe_fn f a = coe_fn g a) : f = g := sorry protected theorem congr_arg {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {f : alg_equiv R A₁ A₂} {x : A₁} {x' : A₁} : x = x' → coe_fn f x = coe_fn f x' := sorry protected theorem congr_fun {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {f : alg_equiv R A₁ A₂} {g : alg_equiv R A₁ A₂} (h : f = g) (x : A₁) : coe_fn f x = coe_fn g x := h ▸ rfl theorem ext_iff {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {f : alg_equiv R A₁ A₂} {g : alg_equiv R A₁ A₂} : f = g ↔ ∀ (x : A₁), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : A₁) => h ▸ rfl, mpr := ext } theorem coe_fun_injective {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] : function.injective fun (e : alg_equiv R A₁ A₂) => ⇑e := id fun (f g : alg_equiv R A₁ A₂) (w : (fun (e : alg_equiv R A₁ A₂) => ⇑e) f = (fun (e : alg_equiv R A₁ A₂) => ⇑e) g) => ext fun (a : A₁) => congr_fun w a protected instance has_coe_to_ring_equiv {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] : has_coe (alg_equiv R A₁ A₂) (A₁ ≃+* A₂) := has_coe.mk to_ring_equiv @[simp] theorem mk_apply {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {to_fun : A₁ → A₂} {inv_fun : A₂ → A₁} {left_inv : function.left_inverse inv_fun to_fun} {right_inv : function.right_inverse inv_fun to_fun} {map_mul : ∀ (x y : A₁), to_fun (x * y) = to_fun x * to_fun y} {map_add : ∀ (x y : A₁), to_fun (x + y) = to_fun x + to_fun y} {commutes : ∀ (r : R), to_fun (coe_fn (algebra_map R A₁) r) = coe_fn (algebra_map R A₂) r} {a : A₁} : coe_fn (mk to_fun inv_fun left_inv right_inv map_mul map_add commutes) a = to_fun a := rfl @[simp] theorem to_fun_apply {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {e : alg_equiv R A₁ A₂} {a : A₁} : to_fun e a = coe_fn e a := rfl @[simp] theorem coe_ring_equiv {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : ⇑↑e = ⇑e := rfl theorem coe_ring_equiv_injective {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] : function.injective fun (e : alg_equiv R A₁ A₂) => ↑e := id fun (f g : alg_equiv R A₁ A₂) (w : (fun (e : alg_equiv R A₁ A₂) => ↑e) f = (fun (e : alg_equiv R A₁ A₂) => ↑e) g) => ext fun (a : A₁) => congr_fun (congr_arg (fun (e : A₁ ≃+* A₂) => ⇑e) w) a @[simp] theorem map_add {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) (y : A₁) : coe_fn e (x + y) = coe_fn e x + coe_fn e y := add_equiv.map_add (to_add_equiv e) @[simp] theorem map_zero {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : coe_fn e 0 = 0 := add_equiv.map_zero (to_add_equiv e) @[simp] theorem map_mul {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) (y : A₁) : coe_fn e (x * y) = coe_fn e x * coe_fn e y := mul_equiv.map_mul (to_mul_equiv e) @[simp] theorem map_one {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : coe_fn e 1 = 1 := mul_equiv.map_one (to_mul_equiv e) @[simp] theorem commutes {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (r : R) : coe_fn e (coe_fn (algebra_map R A₁) r) = coe_fn (algebra_map R A₂) r := commutes' e theorem map_sum {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) {ι : Type u_1} (f : ι → A₁) (s : finset ι) : coe_fn e (finset.sum s fun (x : ι) => f x) = finset.sum s fun (x : ι) => coe_fn e (f x) := add_equiv.map_sum (to_add_equiv e) f s theorem map_finsupp_sum {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) {α : Type u_1} [HasZero α] {ι : Type u_2} (f : ι →₀ α) (g : ι → α → A₁) : coe_fn e (finsupp.sum f g) = finsupp.sum f fun (i : ι) (b : α) => coe_fn e (g i b) := map_sum e (fun (a : ι) => g a (coe_fn f a)) (finsupp.support f) /-- Interpret an algebra equivalence as an algebra homomorphism. This definition is included for symmetry with the other `to_*_hom` projections. The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/ def to_alg_hom {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : alg_hom R A₁ A₂ := alg_hom.mk (to_fun e) (map_one e) (map_mul' e) (map_zero e) (map_add' e) (commutes' e) protected instance has_coe_to_alg_hom {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] : has_coe (alg_equiv R A₁ A₂) (alg_hom R A₁ A₂) := has_coe.mk to_alg_hom @[simp] theorem to_alg_hom_eq_coe {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : to_alg_hom e = ↑e := rfl @[simp] theorem coe_alg_hom {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : ⇑↑e = ⇑e := rfl @[simp] theorem map_pow {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) (n : ℕ) : coe_fn e (x ^ n) = coe_fn e x ^ n := alg_hom.map_pow (to_alg_hom e) theorem injective {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : function.injective ⇑e := equiv.injective (to_equiv e) theorem surjective {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : function.surjective ⇑e := equiv.surjective (to_equiv e) theorem bijective {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : function.bijective ⇑e := equiv.bijective (to_equiv e) protected instance has_one {R : Type u} {A₁ : Type v} [comm_semiring R] [semiring A₁] [algebra R A₁] : HasOne (alg_equiv R A₁ A₁) := { one := mk (ring_equiv.to_fun 1) (ring_equiv.inv_fun 1) sorry sorry sorry sorry sorry } protected instance inhabited {R : Type u} {A₁ : Type v} [comm_semiring R] [semiring A₁] [algebra R A₁] : Inhabited (alg_equiv R A₁ A₁) := { default := 1 } /-- Algebra equivalences are reflexive. -/ def refl {R : Type u} {A₁ : Type v} [comm_semiring R] [semiring A₁] [algebra R A₁] : alg_equiv R A₁ A₁ := 1 @[simp] theorem coe_refl {R : Type u} {A₁ : Type v} [comm_semiring R] [semiring A₁] [algebra R A₁] : ↑refl = alg_hom.id R A₁ := alg_hom.ext fun (x : A₁) => rfl /-- Algebra equivalences are symmetric. -/ def symm {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : alg_equiv R A₂ A₁ := mk (ring_equiv.to_fun (ring_equiv.symm (to_ring_equiv e))) (ring_equiv.inv_fun (ring_equiv.symm (to_ring_equiv e))) sorry sorry sorry sorry sorry /-- See Note [custom simps projection] -/ def simps.inv_fun {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : A₂ → A₁ := ⇑(symm e) @[simp] theorem inv_fun_eq_symm {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {e : alg_equiv R A₁ A₂} : inv_fun e = ⇑(symm e) := rfl @[simp] theorem symm_symm {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {e : alg_equiv R A₁ A₂} : symm (symm e) = e := ext fun (a : A₁) => Eq.refl (coe_fn (symm (symm e)) a) /-- Algebra equivalences are transitive. -/ def trans {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] [algebra R A₁] [algebra R A₂] [algebra R A₃] (e₁ : alg_equiv R A₁ A₂) (e₂ : alg_equiv R A₂ A₃) : alg_equiv R A₁ A₃ := mk (ring_equiv.to_fun (ring_equiv.trans (to_ring_equiv e₁) (to_ring_equiv e₂))) (ring_equiv.inv_fun (ring_equiv.trans (to_ring_equiv e₁) (to_ring_equiv e₂))) sorry sorry sorry sorry sorry @[simp] theorem apply_symm_apply {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₂) : coe_fn e (coe_fn (symm e) x) = x := equiv.apply_symm_apply (to_equiv e) @[simp] theorem symm_apply_apply {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) : coe_fn (symm e) (coe_fn e x) = x := equiv.symm_apply_apply (to_equiv e) @[simp] theorem trans_apply {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] [algebra R A₁] [algebra R A₂] [algebra R A₃] (e₁ : alg_equiv R A₁ A₂) (e₂ : alg_equiv R A₂ A₃) (x : A₁) : coe_fn (trans e₁ e₂) x = coe_fn e₂ (coe_fn e₁ x) := rfl @[simp] theorem comp_symm {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : alg_hom.comp ↑e ↑(symm e) = alg_hom.id R A₂ := sorry @[simp] theorem symm_comp {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : alg_hom.comp ↑(symm e) ↑e = alg_hom.id R A₁ := sorry /-- If `A₁` is equivalent to `A₁'` and `A₂` is equivalent to `A₂'`, then the type of maps `A₁ →ₐ[R] A₂` is equivalent to the type of maps `A₁' →ₐ[R] A₂'`. -/ def arrow_congr {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {A₁' : Type u_1} {A₂' : Type u_2} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂'] (e₁ : alg_equiv R A₁ A₁') (e₂ : alg_equiv R A₂ A₂') : alg_hom R A₁ A₂ ≃ alg_hom R A₁' A₂' := equiv.mk (fun (f : alg_hom R A₁ A₂) => alg_hom.comp (alg_hom.comp (to_alg_hom e₂) f) (to_alg_hom (symm e₁))) (fun (f : alg_hom R A₁' A₂') => alg_hom.comp (alg_hom.comp (to_alg_hom (symm e₂)) f) (to_alg_hom e₁)) sorry sorry theorem arrow_congr_comp {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] [algebra R A₁] [algebra R A₂] [algebra R A₃] {A₁' : Type u_1} {A₂' : Type u_2} {A₃' : Type u_3} [semiring A₁'] [semiring A₂'] [semiring A₃'] [algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : alg_equiv R A₁ A₁') (e₂ : alg_equiv R A₂ A₂') (e₃ : alg_equiv R A₃ A₃') (f : alg_hom R A₁ A₂) (g : alg_hom R A₂ A₃) : coe_fn (arrow_congr e₁ e₃) (alg_hom.comp g f) = alg_hom.comp (coe_fn (arrow_congr e₂ e₃) g) (coe_fn (arrow_congr e₁ e₂) f) := sorry @[simp] theorem arrow_congr_refl {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] : arrow_congr refl refl = equiv.refl (alg_hom R A₁ A₂) := equiv.ext fun (x : alg_hom R A₁ A₂) => alg_hom.ext fun (x_1 : A₁) => Eq.refl (coe_fn (coe_fn (arrow_congr refl refl) x) x_1) @[simp] theorem arrow_congr_trans {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] [algebra R A₁] [algebra R A₂] [algebra R A₃] {A₁' : Type u_1} {A₂' : Type u_2} {A₃' : Type u_3} [semiring A₁'] [semiring A₂'] [semiring A₃'] [algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : alg_equiv R A₁ A₂) (e₁' : alg_equiv R A₁' A₂') (e₂ : alg_equiv R A₂ A₃) (e₂' : alg_equiv R A₂' A₃') : arrow_congr (trans e₁ e₂) (trans e₁' e₂') = equiv.trans (arrow_congr e₁ e₁') (arrow_congr e₂ e₂') := equiv.ext fun (x : alg_hom R A₁ A₁') => alg_hom.ext fun (x_1 : A₃) => Eq.refl (coe_fn (coe_fn (arrow_congr (trans e₁ e₂) (trans e₁' e₂')) x) x_1) @[simp] theorem arrow_congr_symm {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {A₁' : Type u_1} {A₂' : Type u_2} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂'] (e₁ : alg_equiv R A₁ A₁') (e₂ : alg_equiv R A₂ A₂') : equiv.symm (arrow_congr e₁ e₂) = arrow_congr (symm e₁) (symm e₂) := equiv.ext fun (x : alg_hom R A₁' A₂') => alg_hom.ext fun (x_1 : A₁) => Eq.refl (coe_fn (coe_fn (equiv.symm (arrow_congr e₁ e₂)) x) x_1) /-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/ def of_alg_hom {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (f : alg_hom R A₁ A₂) (g : alg_hom R A₂ A₁) (h₁ : alg_hom.comp f g = alg_hom.id R A₂) (h₂ : alg_hom.comp g f = alg_hom.id R A₁) : alg_equiv R A₁ A₂ := mk (alg_hom.to_fun f) ⇑g sorry sorry (alg_hom.map_mul' f) (alg_hom.map_add' f) (alg_hom.commutes' f) /-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/ def of_bijective {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (f : alg_hom R A₁ A₂) (hf : function.bijective ⇑f) : alg_equiv R A₁ A₂ := mk (ring_equiv.to_fun (ring_equiv.of_bijective (↑f) hf)) (ring_equiv.inv_fun (ring_equiv.of_bijective (↑f) hf)) sorry sorry sorry sorry (alg_hom.commutes' f) /-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/ def to_linear_equiv {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : linear_equiv R A₁ A₂ := linear_equiv.mk (to_fun e) sorry sorry (to_fun (symm e)) (left_inv e) (right_inv e) @[simp] theorem to_linear_equiv_apply {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) : coe_fn (to_linear_equiv e) x = coe_fn e x := rfl theorem to_linear_equiv_inj {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {e₁ : alg_equiv R A₁ A₂} {e₂ : alg_equiv R A₁ A₂} (H : to_linear_equiv e₁ = to_linear_equiv e₂) : e₁ = e₂ := sorry /-- Interpret an algebra equivalence as a linear map. -/ def to_linear_map {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : linear_map R A₁ A₂ := alg_hom.to_linear_map (to_alg_hom e) @[simp] theorem to_alg_hom_to_linear_map {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : alg_hom.to_linear_map ↑e = to_linear_map e := rfl @[simp] theorem to_linear_equiv_to_linear_map {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) : linear_equiv.to_linear_map (to_linear_equiv e) = to_linear_map e := rfl @[simp] theorem to_linear_map_apply {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) : coe_fn (to_linear_map e) x = coe_fn e x := rfl theorem to_linear_map_inj {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [semiring A₁] [semiring A₂] [algebra R A₁] [algebra R A₂] {e₁ : alg_equiv R A₁ A₂} {e₂ : alg_equiv R A₁ A₂} (H : to_linear_map e₁ = to_linear_map e₂) : e₁ = e₂ := sorry @[simp] theorem trans_to_linear_map {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] [algebra R A₁] [algebra R A₂] [algebra R A₃] (f : alg_equiv R A₁ A₂) (g : alg_equiv R A₂ A₃) : to_linear_map (trans f g) = linear_map.comp (to_linear_map g) (to_linear_map f) := rfl protected instance aut {R : Type u} {A₁ : Type v} [comm_semiring R] [semiring A₁] [algebra R A₁] : group (alg_equiv R A₁ A₁) := group.mk (fun (ϕ ψ : alg_equiv R A₁ A₁) => trans ψ ϕ) sorry 1 sorry sorry symm (div_inv_monoid.div._default (fun (ϕ ψ : alg_equiv R A₁ A₁) => trans ψ ϕ) sorry 1 sorry sorry symm) sorry theorem map_prod {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [comm_semiring A₁] [comm_semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) {ι : Type u_1} (f : ι → A₁) (s : finset ι) : coe_fn e (finset.prod s fun (x : ι) => f x) = finset.prod s fun (x : ι) => coe_fn e (f x) := alg_hom.map_prod (to_alg_hom e) f s theorem map_finsupp_prod {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_semiring R] [comm_semiring A₁] [comm_semiring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) {α : Type u_1} [HasZero α] {ι : Type u_2} (f : ι →₀ α) (g : ι → α → A₁) : coe_fn e (finsupp.prod f g) = finsupp.prod f fun (i : ι) (a : α) => coe_fn e (g i a) := alg_hom.map_finsupp_prod (to_alg_hom e) f g @[simp] theorem map_neg {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_ring R] [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) : coe_fn e (-x) = -coe_fn e x := alg_hom.map_neg (to_alg_hom e) x @[simp] theorem map_sub {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_ring R] [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) (y : A₁) : coe_fn e (x - y) = coe_fn e x - coe_fn e y := alg_hom.map_sub (to_alg_hom e) x y @[simp] theorem map_inv {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_ring R] [division_ring A₁] [division_ring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) : coe_fn e (x⁻¹) = (coe_fn e x⁻¹) := alg_hom.map_inv (to_alg_hom e) x @[simp] theorem map_div {R : Type u} {A₁ : Type v} {A₂ : Type w} [comm_ring R] [division_ring A₁] [division_ring A₂] [algebra R A₁] [algebra R A₂] (e : alg_equiv R A₁ A₂) (x : A₁) (y : A₁) : coe_fn e (x / y) = coe_fn e x / coe_fn e y := alg_hom.map_div (to_alg_hom e) x y end alg_equiv namespace matrix /-! ### `matrix` section Specialize `matrix.one_map` and `matrix.zero_map` to `alg_hom` and `alg_equiv`. TODO: there should be a way to avoid restating these for each `foo_hom`. -/ /-- A version of `matrix.one_map` where `f` is an `alg_hom`. -/ @[simp] theorem alg_hom_map_one {R : Type u_1} {A₁ : Type u_2} {A₂ : Type u_3} {n : Type u_4} [fintype n] [comm_semiring R] [semiring A₁] [algebra R A₁] [semiring A₂] [algebra R A₂] [DecidableEq n] (f : alg_hom R A₁ A₂) : map 1 ⇑f = 1 := one_map (alg_hom.map_zero f) (alg_hom.map_one f) /-- A version of `matrix.one_map` where `f` is an `alg_equiv`. -/ @[simp] theorem alg_equiv_map_one {R : Type u_1} {A₁ : Type u_2} {A₂ : Type u_3} {n : Type u_4} [fintype n] [comm_semiring R] [semiring A₁] [algebra R A₁] [semiring A₂] [algebra R A₂] [DecidableEq n] (f : alg_equiv R A₁ A₂) : map 1 ⇑f = 1 := one_map (alg_equiv.map_zero f) (alg_equiv.map_one f) /-- A version of `matrix.zero_map` where `f` is an `alg_hom`. -/ @[simp] theorem alg_hom_map_zero {R : Type u_1} {A₁ : Type u_2} {A₂ : Type u_3} {n : Type u_4} [fintype n] [comm_semiring R] [semiring A₁] [algebra R A₁] [semiring A₂] [algebra R A₂] (f : alg_hom R A₁ A₂) : map 0 ⇑f = 0 := map_zero (alg_hom.map_zero f) /-- A version of `matrix.zero_map` where `f` is an `alg_equiv`. -/ @[simp] theorem alg_equiv_map_zero {R : Type u_1} {A₁ : Type u_2} {A₂ : Type u_3} {n : Type u_4} [fintype n] [comm_semiring R] [semiring A₁] [algebra R A₁] [semiring A₂] [algebra R A₂] (f : alg_equiv R A₁ A₂) : map 0 ⇑f = 0 := map_zero (alg_equiv.map_zero f) end matrix namespace algebra /-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it when `algebra R S` and `algebra S A`. If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replaced with `is_scalar_tower`. -/ /- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and `algebra ?m_1 A -/ /- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the appropriate type classes -/ def comap (R : Type u) (S : Type v) (A : Type w) := A protected instance comap.inhabited (R : Type u) (S : Type v) (A : Type w) [h : Inhabited A] : Inhabited (comap R S A) := h protected instance comap.semiring (R : Type u) (S : Type v) (A : Type w) [h : semiring A] : semiring (comap R S A) := h protected instance comap.ring (R : Type u) (S : Type v) (A : Type w) [h : ring A] : ring (comap R S A) := h protected instance comap.comm_semiring (R : Type u) (S : Type v) (A : Type w) [h : comm_semiring A] : comm_semiring (comap R S A) := h protected instance comap.comm_ring (R : Type u) (S : Type v) (A : Type w) [h : comm_ring A] : comm_ring (comap R S A) := h protected instance comap.algebra' (R : Type u) (S : Type v) (A : Type w) [comm_semiring S] [semiring A] [h : algebra S A] : algebra S (comap R S A) := h /-- Identity homomorphism `A →ₐ[S] comap R S A`. -/ def comap.to_comap (R : Type u) (S : Type v) (A : Type w) [comm_semiring S] [semiring A] [algebra S A] : alg_hom S A (comap R S A) := alg_hom.id S A /-- Identity homomorphism `comap R S A →ₐ[S] A`. -/ def comap.of_comap (R : Type u) (S : Type v) (A : Type w) [comm_semiring S] [semiring A] [algebra S A] : alg_hom S (comap R S A) A := alg_hom.id S A /-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/ protected instance comap.algebra (R : Type u) (S : Type v) (A : Type w) [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] : algebra R (comap R S A) := mk (ring_hom.mk (ring_hom.to_fun (ring_hom.comp (algebra_map S A) (algebra_map R S))) sorry sorry sorry sorry) sorry sorry /-- Embedding of `S` into `comap R S A`. -/ def to_comap (R : Type u) (S : Type v) (A : Type w) [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] : alg_hom R S (comap R S A) := alg_hom.mk (ring_hom.to_fun (algebra_map S A)) sorry sorry sorry sorry sorry theorem to_comap_apply (R : Type u) (S : Type v) (A : Type w) [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] (x : S) : coe_fn (to_comap R S A) x = coe_fn (algebra_map S A) x := rfl end algebra namespace alg_hom /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] [algebra R S] [algebra S A] [algebra S B] (φ : alg_hom S A B) : alg_hom R (algebra.comap R S A) (algebra.comap R S B) := mk (to_fun φ) (map_one' φ) (map_mul' φ) (map_zero' φ) (map_add' φ) sorry end alg_hom namespace ring_hom /-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/ def to_nat_alg_hom {R : Type u_1} {S : Type u_2} [semiring R] [semiring S] [algebra ℕ R] [algebra ℕ S] (f : R →+* S) : alg_hom ℕ R S := alg_hom.mk (⇑f) (map_one' f) (map_mul' f) (map_zero' f) (map_add' f) sorry /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def to_int_alg_hom {R : Type u_1} {S : Type u_2} [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) : alg_hom ℤ R S := alg_hom.mk (to_fun f) sorry sorry sorry sorry sorry @[simp] theorem map_rat_algebra_map {R : Type u_1} {S : Type u_2} [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) (r : ℚ) : coe_fn f (coe_fn (algebra_map ℚ R) r) = coe_fn (algebra_map ℚ S) r := iff.mp ext_iff (subsingleton.elim (comp f (algebra_map ℚ R)) (algebra_map ℚ S)) r /-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. -/ def to_rat_alg_hom {R : Type u_1} {S : Type u_2} [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) : alg_hom ℚ R S := alg_hom.mk (to_fun f) sorry sorry sorry sorry (map_rat_algebra_map f) end ring_hom namespace rat protected instance algebra_rat {α : Type u_1} [division_ring α] [char_zero α] : algebra ℚ α := ring_hom.to_algebra' (cast_hom α) sorry end rat namespace algebra /-- `algebra_map` as an `alg_hom`. -/ def of_id (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : alg_hom R R A := alg_hom.mk (ring_hom.to_fun (algebra_map R A)) sorry sorry sorry sorry sorry theorem of_id_apply {R : Type u} (A : Type v) [comm_semiring R] [semiring A] [algebra R A] (r : R) : coe_fn (of_id R A) r = coe_fn (algebra_map R A) r := rfl /-- The multiplication in an algebra is a bilinear map. -/ def lmul (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : alg_hom R A (module.End R A) := alg_hom.mk (linear_map.to_fun ((fun (this : linear_map R A (linear_map R A A)) => this) (linear_map.mk₂ R Mul.mul sorry sorry sorry sorry))) sorry sorry sorry sorry sorry /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (R : Type u) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (r : A) : linear_map R A A := coe_fn (lmul R A) r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (R : Type u) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (r : A) : linear_map R A A := coe_fn (linear_map.flip (alg_hom.to_linear_map (lmul R A))) r /-- Simultaneous multiplication on the left and right is a linear map. -/ def lmul_left_right (R : Type u) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (vw : A × A) : linear_map R A A := linear_map.comp (lmul_right R (prod.snd vw)) (lmul_left R (prod.fst vw)) /-- The multiplication map on an algebra, as an `R`-linear map from `A ⊗[R] A` to `A`. -/ def lmul' (R : Type u) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] : linear_map R (tensor_product R A A) A := tensor_product.lift (alg_hom.to_linear_map (lmul R A)) @[simp] theorem lmul_apply {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (p : A) (q : A) : coe_fn (coe_fn (lmul R A) p) q = p * q := rfl @[simp] theorem lmul_left_apply {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (p : A) (q : A) : coe_fn (lmul_left R p) q = p * q := rfl @[simp] theorem lmul_right_apply {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (p : A) (q : A) : coe_fn (lmul_right R p) q = q * p := rfl @[simp] theorem lmul_left_right_apply {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (vw : A × A) (p : A) : coe_fn (lmul_left_right R vw) p = prod.fst vw * p * prod.snd vw := rfl @[simp] theorem lmul_left_one {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] : lmul_left R 1 = linear_map.id := sorry @[simp] theorem lmul_left_mul {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (a : A) (b : A) : lmul_left R (a * b) = linear_map.comp (lmul_left R a) (lmul_left R b) := sorry @[simp] theorem lmul_right_one {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] : lmul_right R 1 = linear_map.id := sorry @[simp] theorem lmul_right_mul {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (a : A) (b : A) : lmul_right R (a * b) = linear_map.comp (lmul_right R b) (lmul_right R a) := sorry @[simp] theorem lmul'_apply {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {x : A} {y : A} : coe_fn (lmul' R) (tensor_product.tmul R x y) = x * y := sorry protected instance linear_map.semimodule' (R : Type u) [comm_semiring R] (M : Type v) [add_comm_monoid M] [semimodule R M] (S : Type w) [comm_semiring S] [algebra R S] : semimodule S (linear_map R M S) := semimodule.mk sorry sorry end algebra /-- Semiring ⥤ ℕ-Alg -/ protected instance algebra_nat (R : Type u_1) [semiring R] : algebra ℕ R := algebra.mk (nat.cast_ring_hom R) nat.cast_commute sorry theorem span_nat_eq_add_group_closure (R : Type u_1) [semiring R] (s : set R) : submodule.to_add_submonoid (submodule.span ℕ s) = add_submonoid.closure s := sorry @[simp] theorem span_nat_eq (R : Type u_1) [semiring R] (s : add_submonoid R) : submodule.to_add_submonoid (submodule.span ℕ ↑s) = s := sorry /-- Ring ⥤ ℤ-Alg -/ protected instance algebra_int (R : Type u_1) [ring R] : algebra ℤ R := algebra.mk (int.cast_ring_hom R) int.cast_commute sorry protected instance int_algebra_subsingleton {S : Type u_2} [ring S] : subsingleton (algebra ℤ S) := subsingleton.intro fun (P Q : algebra ℤ S) => algebra.algebra_ext P Q fun (r : ℤ) => eq.mpr (id (Eq.trans ((fun (a a_1 : S) (e_1 : a = a_1) (ᾰ ᾰ_1 : S) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (coe_fn (algebra_map ℤ S) r) (↑r) (ring_hom.eq_int_cast (algebra_map ℤ S) r) (coe_fn (algebra_map ℤ S) r) (↑r) (ring_hom.eq_int_cast (algebra_map ℤ S) r)) (propext (eq_self_iff_true ↑r)))) trivial protected instance nat_algebra_subsingleton {S : Type u_2} [semiring S] : subsingleton (algebra ℕ S) := subsingleton.intro fun (P Q : algebra ℕ S) => algebra.algebra_ext P Q fun (r : ℕ) => eq.mpr (id (Eq.trans ((fun (a a_1 : S) (e_1 : a = a_1) (ᾰ ᾰ_1 : S) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (coe_fn (algebra_map ℕ S) r) (↑r) (ring_hom.eq_nat_cast (algebra_map ℕ S) r) (coe_fn (algebra_map ℕ S) r) (↑r) (ring_hom.eq_nat_cast (algebra_map ℕ S) r)) (propext (eq_self_iff_true ↑r)))) trivial theorem span_int_eq_add_group_closure {R : Type u_1} [ring R] (s : set R) : submodule.to_add_subgroup (submodule.span ℤ s) = add_subgroup.closure s := sorry @[simp] theorem span_int_eq {R : Type u_1} [ring R] (s : add_subgroup R) : submodule.to_add_subgroup (submodule.span ℤ ↑s) = s := eq.mpr (id (Eq._oldrec (Eq.refl (submodule.to_add_subgroup (submodule.span ℤ ↑s) = s)) (span_int_eq_add_group_closure ↑s))) (eq.mpr (id (Eq._oldrec (Eq.refl (add_subgroup.closure ↑s = s)) (add_subgroup.closure_eq s))) (Eq.refl s)) /-! The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra. We couldn't set this up back in `algebra.pi_instances` because this file imports it. -/ namespace pi protected instance algebra (I : Type u) (f : I → Type v) (α : Type u_1) {r : comm_semiring α} [s : (i : I) → semiring (f i)] [(i : I) → algebra α (f i)] : algebra α ((i : I) → f i) := algebra.mk (ring_hom.mk (ring_hom.to_fun (pi.ring_hom fun (i : I) => algebra_map α (f i))) sorry sorry sorry sorry) sorry sorry @[simp] theorem algebra_map_apply (I : Type u) (f : I → Type v) (α : Type u_1) {r : comm_semiring α} [s : (i : I) → semiring (f i)] [(i : I) → algebra α (f i)] (a : α) (i : I) : coe_fn (algebra_map α ((i : I) → f i)) a i = coe_fn (algebra_map α (f i)) a := rfl -- One could also build a `Π i, R i`-algebra structure on `Π i, A i`, -- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful. end pi theorem algebra_compatible_smul {R : Type u_1} [comm_semiring R] (A : Type u_2) [semiring A] [algebra R A] {M : Type u_3} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] (r : R) (m : M) : r • m = coe_fn (algebra_map R A) r • m := sorry @[simp] theorem algebra_map_smul {R : Type u_1} [comm_semiring R] (A : Type u_2) [semiring A] [algebra R A] {M : Type u_3} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] (r : R) (m : M) : coe_fn (algebra_map R A) r • m = r • m := Eq.symm (algebra_compatible_smul A r m) protected instance is_scalar_tower.to_smul_comm_class {R : Type u_1} [comm_semiring R] {A : Type u_2} [semiring A] [algebra R A] {M : Type u_3} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] : smul_comm_class R A M := smul_comm_class.mk fun (r : R) (a : A) (m : M) => eq.mpr (id (Eq._oldrec (Eq.refl (r • a • m = a • r • m)) (algebra_compatible_smul A r (a • m)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (algebra_map R A) r • a • m = a • r • m)) (smul_smul (coe_fn (algebra_map R A) r) a m))) (eq.mpr (id (Eq._oldrec (Eq.refl ((coe_fn (algebra_map R A) r * a) • m = a • r • m)) (algebra.commutes r a))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a * coe_fn (algebra_map R A) r) • m = a • r • m)) (mul_smul a (coe_fn (algebra_map R A) r) m))) (eq.mpr (id (Eq._oldrec (Eq.refl (a • coe_fn (algebra_map R A) r • m = a • r • m)) (Eq.symm (algebra_compatible_smul A r m)))) (Eq.refl (a • r • m)))))) protected instance is_scalar_tower.to_smul_comm_class' {R : Type u_1} [comm_semiring R] {A : Type u_2} [semiring A] [algebra R A] {M : Type u_3} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] : smul_comm_class A R M := smul_comm_class.symm R A M theorem smul_algebra_smul_comm {R : Type u_1} [comm_semiring R] {A : Type u_2} [semiring A] [algebra R A] {M : Type u_3} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] (r : R) (a : A) (m : M) : a • r • m = r • a • m := smul_comm a r m namespace linear_map protected instance coe_is_scalar_tower {R : Type u_1} [comm_semiring R] {A : Type u_2} [semiring A] [algebra R A] {M : Type u_3} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] {N : Type u_4} [add_comm_monoid N] [semimodule A N] [semimodule R N] [is_scalar_tower R A N] : has_coe (linear_map A M N) (linear_map R M N) := has_coe.mk (restrict_scalars R) @[simp] theorem coe_restrict_scalars_eq_coe (R : Type u_1) [comm_semiring R] {A : Type u_2} [semiring A] [algebra R A] {M : Type u_3} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] {N : Type u_4} [add_comm_monoid N] [semimodule A N] [semimodule R N] [is_scalar_tower R A N] (f : linear_map A M N) : ⇑(restrict_scalars R f) = ⇑f := rfl @[simp] theorem coe_coe_is_scalar_tower (R : Type u_1) [comm_semiring R] {A : Type u_2} [semiring A] [algebra R A] {M : Type u_3} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] {N : Type u_4} [add_comm_monoid N] [semimodule A N] [semimodule R N] [is_scalar_tower R A N] (f : linear_map A M N) : ⇑↑f = ⇑f := rfl /-- `A`-linearly coerce a `R`-linear map from `M` to `A` to a function, given an algebra `A` over a commutative semiring `R` and `M` a semimodule over `R`. -/ def lto_fun (R : Type u) (M : Type v) (A : Type w) [comm_semiring R] [add_comm_monoid M] [semimodule R M] [comm_ring A] [algebra R A] : linear_map A (linear_map R M A) (M → A) := mk to_fun sorry sorry end linear_map /- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then `S`-modules are also `R`-modules. -/ /-- Warning: use this type synonym judiciously! The preferred way of working with an `A`-module `M` as `R`-module (where `A` is an `R`-algebra), is by `[module R M] [module A M] [is_scalar_tower R A M]`. When `M` is a module over a ring `A`, and `A` is an algebra over `R`, then `M` inherits a module structure over `R`, provided as a type synonym `module.restrict_scalars R A M := M`. -/ def restrict_scalars (R : Type u_1) (A : Type u_2) (M : Type u_3) := M protected instance restrict_scalars.inhabited (R : Type u_1) (A : Type u_2) (M : Type u_3) [I : Inhabited M] : Inhabited (restrict_scalars R A M) := I protected instance restrict_scalars.add_comm_monoid (R : Type u_1) (A : Type u_2) (M : Type u_3) [I : add_comm_monoid M] : add_comm_monoid (restrict_scalars R A M) := I protected instance restrict_scalars.add_comm_group (R : Type u_1) (A : Type u_2) (M : Type u_3) [I : add_comm_group M] : add_comm_group (restrict_scalars R A M) := I protected instance restrict_scalars.module_orig (R : Type u_1) (A : Type u_2) (M : Type u_3) [semiring A] [add_comm_monoid M] [I : semimodule A M] : semimodule A (restrict_scalars R A M) := I /-- When `M` is a module over a ring `A`, and `A` is an algebra over `R`, then `M` inherits a module structure over `R`. The preferred way of setting this up is `[module R M] [module A M] [is_scalar_tower R A M]`. -/ protected instance restrict_scalars.semimodule (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule A M] : semimodule R (restrict_scalars R A M) := semimodule.mk sorry sorry theorem restrict_scalars_smul_def (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule A M] (c : R) (x : restrict_scalars R A M) : c • x = coe_fn (algebra_map R A) c • x := rfl protected instance restrict_scalars.is_scalar_tower (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule A M] : is_scalar_tower R A (restrict_scalars R A M) := is_scalar_tower.mk fun (r : R) (A_1 : A) (M_1 : restrict_scalars R A M) => eq.mpr (id (Eq._oldrec (Eq.refl ((r • A_1) • M_1 = r • A_1 • M_1)) (algebra.smul_def r A_1))) (eq.mpr (id (Eq._oldrec (Eq.refl ((coe_fn (algebra_map R A) r * A_1) • M_1 = r • A_1 • M_1)) (mul_smul (coe_fn (algebra_map R A) r) A_1 M_1))) (Eq.refl (coe_fn (algebra_map R A) r • A_1 • M_1))) protected instance submodule.restricted_module (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule A M] (V : submodule A M) : semimodule R ↥V := restrict_scalars.semimodule R A ↥V protected instance submodule.restricted_module_is_scalar_tower (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule A M] (V : submodule A M) : is_scalar_tower R A ↥V := restrict_scalars.is_scalar_tower R A ↥V namespace submodule /-- `V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars, corresponding to `V`, an `S`-submodule of the original `S`-module. -/ def restrict_scalars (R : Type u_1) {A : Type u_2} {M : Type u_3} [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] (V : submodule A M) : submodule R M := mk (carrier V) (zero_mem V) sorry sorry @[simp] theorem restrict_scalars_mem (R : Type u_1) {A : Type u_2} {M : Type u_3} [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] (V : submodule A M) (m : M) : m ∈ restrict_scalars R V ↔ m ∈ V := iff.refl (m ∈ restrict_scalars R V) theorem restrict_scalars_injective (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] : function.injective (restrict_scalars R) := fun (V₁ V₂ : submodule A M) (h : restrict_scalars R V₁ = restrict_scalars R V₂) => ext (eq.mpr (Eq.refl (∀ (x : M), x ∈ V₁ ↔ x ∈ V₂)) (iff.mp set.ext_iff (iff.mp ext'_iff h))) @[simp] theorem restrict_scalars_inj (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] {V₁ : submodule A M} {V₂ : submodule A M} : restrict_scalars R V₁ = restrict_scalars R V₂ ↔ V₁ = V₂ := { mp := fun (h : restrict_scalars R V₁ = restrict_scalars R V₂) => restrict_scalars_injective R A M h, mpr := congr_arg fun {V₁ : submodule A M} => restrict_scalars R V₁ } @[simp] theorem restrict_scalars_bot (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] : restrict_scalars R ⊥ = ⊥ := rfl @[simp] theorem restrict_scalars_top (R : Type u_1) (A : Type u_2) (M : Type u_3) [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] : restrict_scalars R ⊤ = ⊤ := rfl end submodule @[simp] theorem linear_map.ker_restrict_scalars (R : Type u_1) {A : Type u_2} {M : Type u_3} {N : Type u_4} [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] [add_comm_monoid N] [semimodule R N] [semimodule A N] [is_scalar_tower R A N] (f : linear_map A M N) : linear_map.ker (linear_map.restrict_scalars R f) = submodule.restrict_scalars R (linear_map.ker f) := rfl namespace linear_map /-! When `V` is an `R`-module and `W` is an `S`-module, where `S` is an algebra over `R`, then the collection of `R`-linear maps from `V` to `W` admits an `S`-module structure, given by multiplication in the target. -/ protected instance is_scalar_tower_extend_scalars (R : Type u_1) [comm_semiring R] (S : Type u_2) [semiring S] [algebra R S] (V : Type u_3) [add_comm_monoid V] [semimodule R V] (W : Type u_4) [add_comm_monoid W] [semimodule R W] [semimodule S W] [is_scalar_tower R S W] : is_scalar_tower R S (linear_map R V W) := sorry /-- When `f` is a linear map taking values in `S`, then `λb, f b • x` is a linear map. -/ def smul_algebra_right {R : Type u_1} [comm_semiring R] {S : Type u_2} [semiring S] [algebra R S] {V : Type u_3} [add_comm_monoid V] [semimodule R V] {W : Type u_4} [add_comm_monoid W] [semimodule R W] [semimodule S W] [is_scalar_tower R S W] (f : linear_map R V S) (x : W) : linear_map R V W := mk (fun (b : V) => coe_fn f b • x) sorry sorry @[simp] theorem smul_algebra_right_apply {R : Type u_1} [comm_semiring R] {S : Type u_2} [semiring S] [algebra R S] {V : Type u_3} [add_comm_monoid V] [semimodule R V] {W : Type u_4} [add_comm_monoid W] [semimodule R W] [semimodule S W] [is_scalar_tower R S W] (f : linear_map R V S) (x : W) (c : V) : coe_fn (smul_algebra_right f x) c = coe_fn f c • x := rfl end Mathlib
0763cbcd22abbd4db55897bfcae20a1e66922bb8
92b50235facfbc08dfe7f334827d47281471333b
/library/data/fin.lean
57f8dfd82f8cad358b97bf83243009cf0054d3e3
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
12,250
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Haitao Zhang, Leonardo de Moura Finite ordinal types. -/ import data.list.basic data.finset.basic data.fintype.card algebra.group open eq.ops nat function list finset fintype structure fin (n : nat) := (val : nat) (is_lt : val < n) definition less_than [reducible] := fin namespace fin attribute fin.val [coercion] section def_equal variable {n : nat} lemma eq_of_veq : ∀ {i j : fin n}, (val i) = j → i = j | (mk iv ilt) (mk jv jlt) := assume (veq : iv = jv), begin congruence, assumption end lemma veq_of_eq : ∀ {i j : fin n}, i = j → (val i) = j | (mk iv ilt) (mk jv jlt) := assume Peq, have veq : iv = jv, from fin.no_confusion Peq (λ Pe Pqe, Pe), veq lemma eq_iff_veq : ∀ {i j : fin n}, (val i) = j ↔ i = j := take i j, iff.intro eq_of_veq veq_of_eq definition val_inj := @eq_of_veq n end def_equal section open decidable protected definition has_decidable_eq [instance] (n : nat) : ∀ (i j : fin n), decidable (i = j) | (mk ival ilt) (mk jval jlt) := match nat.has_decidable_eq ival jval with | inl veq := inl (by substvars) | inr vne := inr (by intro h; injection h; contradiction) end end lemma dinj_lt (n : nat) : dinj (λ i, i < n) fin.mk := take a1 a2 Pa1 Pa2 Pmkeq, fin.no_confusion Pmkeq (λ Pe Pqe, Pe) lemma val_mk (n i : nat) (Plt : i < n) : fin.val (fin.mk i Plt) = i := rfl definition upto [reducible] (n : nat) : list (fin n) := dmap (λ i, i < n) fin.mk (list.upto n) lemma nodup_upto (n : nat) : nodup (upto n) := dmap_nodup_of_dinj (dinj_lt n) (list.nodup_upto n) lemma mem_upto (n : nat) : ∀ (i : fin n), i ∈ upto n := take i, fin.destruct i (take ival Piltn, assert Pin : ival ∈ list.upto n, from mem_upto_of_lt Piltn, mem_dmap Piltn Pin) lemma upto_zero : upto 0 = [] := by rewrite [↑upto, list.upto_nil, dmap_nil] lemma map_val_upto (n : nat) : map fin.val (upto n) = list.upto n := map_dmap_of_inv_of_pos (val_mk n) (@lt_of_mem_upto n) lemma length_upto (n : nat) : length (upto n) = n := calc length (upto n) = length (list.upto n) : (map_val_upto n ▸ length_map fin.val (upto n))⁻¹ ... = n : list.length_upto n definition is_fintype [instance] (n : nat) : fintype (fin n) := fintype.mk (upto n) (nodup_upto n) (mem_upto n) section pigeonhole open fintype lemma card_fin (n : nat) : card (fin n) = n := length_upto n theorem pigeonhole {n m : nat} (Pmltn : m < n) : ¬∃ f : fin n → fin m, injective f := assume Pex, absurd Pmltn (not_lt_of_ge (calc n = card (fin n) : card_fin ... ≤ card (fin m) : card_le_of_inj (fin n) (fin m) Pex ... = m : card_fin)) end pigeonhole definition zero (n : nat) : fin (succ n) := mk 0 !zero_lt_succ definition mk_mod [reducible] (n i : nat) : fin (succ n) := mk (i mod (succ n)) (mod_lt _ !zero_lt_succ) variable {n : nat} theorem val_lt : ∀ i : fin n, val i < n | (mk v h) := h lemma max_lt (i j : fin n) : max i j < n := max_lt (is_lt i) (is_lt j) definition lift : fin n → Π m, fin (n + m) | (mk v h) m := mk v (lt_add_of_lt_right h m) definition lift_succ (i : fin n) : fin (nat.succ n) := lift i 1 definition maxi [reducible] : fin (succ n) := mk n !lt_succ_self theorem val_lift : ∀ (i : fin n) (m : nat), val i = val (lift i m) | (mk v h) m := rfl lemma mk_succ_ne_zero {i : nat} : ∀ {P}, mk (succ i) P ≠ zero n := assume P Pe, absurd (veq_of_eq Pe) !succ_ne_zero lemma mk_mod_eq {i : fin (succ n)} : i = mk_mod n i := eq_of_veq begin rewrite [↑mk_mod, mod_eq_of_lt !is_lt] end lemma mk_mod_of_lt {i : nat} (Plt : i < succ n) : mk_mod n i = mk i Plt := begin esimp [mk_mod], congruence, exact mod_eq_of_lt Plt end section lift_lower lemma lift_zero : lift_succ (zero n) = zero (succ n) := rfl lemma ne_max_of_lt_max {i : fin (succ n)} : i < n → i ≠ maxi := by intro hlt he; substvars; exact absurd hlt (lt.irrefl n) lemma lt_max_of_ne_max {i : fin (succ n)} : i ≠ maxi → i < n := assume hne : i ≠ maxi, assert visn : val i < nat.succ n, from val_lt i, assert aux : val (@maxi n) = n, from rfl, assert vne : val i ≠ n, from assume he, have vivm : val i = val (@maxi n), from he ⬝ aux⁻¹, absurd (eq_of_veq vivm) hne, lt_of_le_of_ne (le_of_lt_succ visn) vne lemma lift_succ_ne_max {i : fin n} : lift_succ i ≠ maxi := begin cases i with v hlt, esimp [lift_succ, lift, max], intro he, injection he, substvars, exact absurd hlt (lt.irrefl v) end lemma lift_succ_inj : injective (@lift_succ n) := take i j, destruct i (destruct j (take iv ilt jv jlt Pmkeq, begin congruence, apply fin.no_confusion Pmkeq, intros, assumption end)) lemma lt_of_inj_of_max (f : fin (succ n) → fin (succ n)) : injective f → (f maxi = maxi) → ∀ i, i < n → f i < n := assume Pinj Peq, take i, assume Pilt, assert P1 : f i = f maxi → i = maxi, from assume Peq, Pinj i maxi Peq, have P : f i ≠ maxi, from begin rewrite -Peq, intro P2, apply absurd (P1 P2) (ne_max_of_lt_max Pilt) end, lt_max_of_ne_max P definition lift_fun : (fin n → fin n) → (fin (succ n) → fin (succ n)) := λ f i, dite (i = maxi) (λ Pe, maxi) (λ Pne, lift_succ (f (mk i (lt_max_of_ne_max Pne)))) definition lower_inj (f : fin (succ n) → fin (succ n)) (inj : injective f) : f maxi = maxi → fin n → fin n := assume Peq, take i, mk (f (lift_succ i)) (lt_of_inj_of_max f inj Peq (lift_succ i) (lt_max_of_ne_max lift_succ_ne_max)) lemma lift_fun_max {f : fin n → fin n} : lift_fun f maxi = maxi := begin rewrite [↑lift_fun, dif_pos rfl] end lemma lift_fun_of_ne_max {f : fin n → fin n} {i} (Pne : i ≠ maxi) : lift_fun f i = lift_succ (f (mk i (lt_max_of_ne_max Pne))) := begin rewrite [↑lift_fun, dif_neg Pne] end lemma lift_fun_eq {f : fin n → fin n} {i : fin n} : lift_fun f (lift_succ i) = lift_succ (f i) := begin rewrite [lift_fun_of_ne_max lift_succ_ne_max], congruence, congruence, rewrite [-eq_iff_veq], esimp, rewrite [↑lift_succ, -val_lift] end lemma lift_fun_of_inj {f : fin n → fin n} : injective f → injective (lift_fun f) := assume Pinj, take i j, assert Pdi : decidable (i = maxi), from _, assert Pdj : decidable (j = maxi), from _, begin cases Pdi with Pimax Pinmax, cases Pdj with Pjmax Pjnmax, substvars, intros, exact rfl, substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pjnmax], intro Plmax, apply absurd Plmax⁻¹ lift_succ_ne_max, cases Pdj with Pjmax Pjnmax, substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pinmax], intro Plmax, apply absurd Plmax lift_succ_ne_max, rewrite [lift_fun_of_ne_max Pinmax, lift_fun_of_ne_max Pjnmax], intro Peq, rewrite [-eq_iff_veq], exact veq_of_eq (Pinj (lift_succ_inj Peq)) end lemma lift_fun_inj : injective (@lift_fun n) := take f₁ f₂ Peq, funext (λ i, assert Peqi : lift_fun f₁ (lift_succ i) = lift_fun f₂ (lift_succ i), from congr_fun Peq _, begin revert Peqi, rewrite [*lift_fun_eq], apply lift_succ_inj end) lemma lower_inj_apply {f Pinj Pmax} (i : fin n) : val (lower_inj f Pinj Pmax i) = val (f (lift_succ i)) := by rewrite [↑lower_inj] end lift_lower section madd definition madd (i j : fin (succ n)) : fin (succ n) := mk ((i + j) mod (succ n)) (mod_lt _ !zero_lt_succ) definition minv : ∀ i : fin (succ n), fin (succ n) | (mk iv ilt) := mk ((succ n - iv) mod succ n) (mod_lt _ !zero_lt_succ) lemma val_madd : ∀ i j : fin (succ n), val (madd i j) = (i + j) mod (succ n) | (mk iv ilt) (mk jv jlt) := by esimp lemma madd_inj : ∀ {i : fin (succ n)}, injective (madd i) | (mk iv ilt) := take j₁ j₂, fin.destruct j₁ (fin.destruct j₂ (λ jv₁ jlt₁ jv₂ jlt₂, begin rewrite [↑madd, -eq_iff_veq], intro Peq, congruence, rewrite [-(mod_eq_of_lt jlt₁), -(mod_eq_of_lt jlt₂)], apply mod_eq_mod_of_add_mod_eq_add_mod_left Peq end)) lemma madd_mk_mod {i j : nat} : madd (mk_mod n i) (mk_mod n j) = mk_mod n (i+j) := eq_of_veq begin esimp [madd, mk_mod], rewrite [ mod_add_mod, add_mod_mod ] end lemma val_mod : ∀ i : fin (succ n), (val i) mod (succ n) = val i | (mk iv ilt) := by esimp; rewrite [(mod_eq_of_lt ilt)] lemma madd_comm (i j : fin (succ n)) : madd i j = madd j i := by apply eq_of_veq; rewrite [*val_madd, add.comm (val i)] lemma zero_madd (i : fin (succ n)) : madd (zero n) i = i := by apply eq_of_veq; rewrite [val_madd, ↑zero, nat.zero_add, mod_eq_of_lt (is_lt i)] lemma madd_zero (i : fin (succ n)) : madd i (zero n) = i := !madd_comm ▸ zero_madd i lemma madd_assoc (i j k : fin (succ n)) : madd (madd i j) k = madd i (madd j k) := by apply eq_of_veq; rewrite [*val_madd, mod_add_mod, add_mod_mod, add.assoc (val i)] lemma madd_left_inv : ∀ i : fin (succ n), madd (minv i) i = zero n | (mk iv ilt) := eq_of_veq (by rewrite [val_madd, ↑minv, ↑zero, mod_add_mod, sub_add_cancel (le_of_lt ilt), mod_self]) open algebra definition madd_is_comm_group [instance] : add_comm_group (fin (succ n)) := add_comm_group.mk madd madd_assoc (zero n) zero_madd madd_zero minv madd_left_inv madd_comm end madd definition pred : fin n → fin n | (mk v h) := mk (nat.pred v) (pre_lt_of_lt h) lemma val_pred : ∀ (i : fin n), val (pred i) = nat.pred (val i) | (mk v h) := rfl lemma pred_zero : pred (zero n) = zero n := rfl definition mk_pred (i : nat) (h : succ i < succ n) : fin n := mk i (lt_of_succ_lt_succ h) definition succ : fin n → fin (succ n) | (mk v h) := mk (nat.succ v) (succ_lt_succ h) lemma val_succ : ∀ (i : fin n), val (succ i) = nat.succ (val i) | (mk v h) := rfl lemma succ_max : fin.succ maxi = (@maxi (nat.succ n)) := rfl lemma lift_succ.comm : lift_succ ∘ (@succ n) = succ ∘ lift_succ := funext take i, eq_of_veq (begin rewrite [↑lift_succ, -val_lift, *val_succ, -val_lift] end) definition elim0 {C : fin 0 → Type} : Π i : fin 0, C i | (mk v h) := absurd h !not_lt_zero definition zero_succ_cases {C : fin (nat.succ n) → Type} : C (zero n) → (Π j : fin n, C (succ j)) → (Π k : fin (nat.succ n), C k) := begin intros CO CS k, induction k with [vk, pk], induction (nat.decidable_lt 0 vk) with [HT, HF], { show C (mk vk pk), from let vj := nat.pred vk in have HSv : vk = nat.succ vj, from eq.symm (succ_pred_of_pos HT), assert pj : vj < n, from lt_of_succ_lt_succ (eq.subst HSv pk), have HS : succ (mk vj pj) = mk vk pk, from val_inj (eq.symm HSv), eq.rec_on HS (CS (mk vj pj)) }, { show C (mk vk pk), from have HOv : vk = 0, from eq_zero_of_le_zero (le_of_not_gt HF), have HO : zero n = mk vk pk, from val_inj (eq.symm HOv), eq.rec_on HO CO } end theorem choice {C : fin n → Type} : (∀ i : fin n, nonempty (C i)) → nonempty (Π i : fin n, C i) := begin revert C, induction n with [n, IH], { intros C H, apply nonempty.intro, exact elim0 }, { intros C H, fapply nonempty.elim (H (zero n)), intro CO, fapply nonempty.elim (IH (λ i, C (succ i)) (λ i, H (succ i))), intro CS, apply nonempty.intro, exact zero_succ_cases CO CS } end section open list local postfix `+1`:100 := nat.succ lemma dmap_map_lift {n : nat} : ∀ l : list nat, (∀ i, i ∈ l → i < n) → dmap (λ i, i < n +1) mk l = map lift_succ (dmap (λ i, i < n) mk l) | [] := assume Plt, rfl | (i::l) := assume Plt, begin rewrite [@dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (lt_succ_of_lt (Plt i !mem_cons)), @dmap_cons_of_pos _ _ (λ i, i < n) _ _ _ (Plt i !mem_cons), map_cons], congruence, apply dmap_map_lift, intro j Pjinl, apply Plt, apply mem_cons_of_mem, assumption end lemma upto_succ (n : nat) : upto (n +1) = maxi :: map lift_succ (upto n) := begin rewrite [↑fin.upto, list.upto_succ, @dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (nat.self_lt_succ n)], congruence, apply dmap_map_lift, apply @list.lt_of_mem_upto end definition upto_step : ∀ {n : nat}, fin.upto (n +1) = (map succ (upto n))++[zero n] | 0 := rfl | (i +1) := begin rewrite [upto_succ i, map_cons, append_cons, succ_max, upto_succ, -lift_zero], congruence, rewrite [map_map, -lift_succ.comm, -map_map, -(map_singleton _ (zero i)), -map_append, -upto_step] end end end fin
612e32d417180cc67748b3189d7957d9fae77013
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/set/default_auto.lean
9f5e8ab36d1aa1f1e774a2002f0457a595b5cc2b
[]
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
188
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.finite import Mathlib.data.set.intervals.default import Mathlib.PostPort namespace Mathlib end Mathlib
d4c1c2cf83d5e5afcedaf8d5a1eba655fec9fd9b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/seq/parallel.lean
32ecf2e561c6f5c3b6b4e39fc34e4fbc8e14addd
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
12,119
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Parallel computation of a computable sequence of computations by a diagonal enumeration. The important theorems of this operation are proven as terminates_parallel and exists_of_mem_parallel. (This operation is nondeterministic in the sense that it does not honor sequence equivalence (irrelevance of computation time).) -/ import data.seq.wseq universes u v namespace computation open wseq variables {α : Type u} {β : Type v} def parallel.aux2 : list (computation α) → α ⊕ list (computation α) := list.foldr (λ c o, match o with | sum.inl a := sum.inl a | sum.inr ls := rmap (λ c', c' :: ls) (destruct c) end) (sum.inr []) def parallel.aux1 : list (computation α) × wseq (computation α) → α ⊕ list (computation α) × wseq (computation α) | (l, S) := rmap (λ l', match seq.destruct S with | none := (l', nil) | some (none, S') := (l', S') | some (some c, S') := (c::l', S') end) (parallel.aux2 l) /-- Parallel computation of an infinite stream of computations, taking the first result -/ def parallel (S : wseq (computation α)) : computation α := corec parallel.aux1 ([], S) theorem terminates_parallel.aux : ∀ {l : list (computation α)} {S c}, c ∈ l → terminates c → terminates (corec parallel.aux1 (l, S)) := begin have lem1 : ∀ l S, (∃ (a : α), parallel.aux2 l = sum.inl a) → terminates (corec parallel.aux1 (l, S)), { intros l S e, cases e with a e, have this : corec parallel.aux1 (l, S) = return a, { apply destruct_eq_ret, simp [parallel.aux1], rw e, simp [rmap] }, rw this, apply_instance }, intros l S c m T, revert l S, apply @terminates_rec_on _ _ c T _ _, { intros a l S m, apply lem1, induction l with c l IH generalizing m; simp at m, { contradiction }, cases m with e m, { rw ←e, simp [parallel.aux2], cases list.foldr parallel.aux2._match_1 (sum.inr list.nil) l with a' ls, exacts [⟨a', rfl⟩, ⟨a, rfl⟩] }, { cases IH m with a' e, simp [parallel.aux2], simp [parallel.aux2] at e, rw e, exact ⟨a', rfl⟩ } }, { intros s IH l S m, have H1 : ∀ l', parallel.aux2 l = sum.inr l' → s ∈ l', { induction l with c l IH' generalizing m; intros l' e'; simp at m, { contradiction }, cases m with e m; simp [parallel.aux2] at e', { rw ←e at e', cases list.foldr parallel.aux2._match_1 (sum.inr list.nil) l with a' ls; injection e' with e', rw ←e', simp }, { induction e : list.foldr parallel.aux2._match_1 (sum.inr list.nil) l with a' ls; rw e at e', { contradiction }, have := IH' m _ e, simp [parallel.aux2] at e', cases destruct c; injection e' with h', rw ←h', simp [this] } }, induction h : parallel.aux2 l with a l', { exact lem1 _ _ ⟨a, h⟩ }, { have H2 : corec parallel.aux1 (l, S) = think _, { apply destruct_eq_think, simp [parallel.aux1], rw h, simp [rmap] }, rw H2, apply @computation.think_terminates _ _ _, have := H1 _ h, rcases seq.destruct S with _ | ⟨_|c, S'⟩; simp [parallel.aux1]; apply IH; simp [this] } } end theorem terminates_parallel {S : wseq (computation α)} {c} (h : c ∈ S) [T : terminates c] : terminates (parallel S) := suffices ∀ n (l : list (computation α)) S c, c ∈ l ∨ some (some c) = seq.nth S n → terminates c → terminates (corec parallel.aux1 (l, S)), from let ⟨n, h⟩ := h in this n [] S c (or.inr h) T, begin intro n, induction n with n IH; intros l S c o T, { cases o with a a, { exact terminates_parallel.aux a T }, have H : seq.destruct S = some (some c, _), { unfold seq.destruct functor.map, rw ← a, simp }, induction h : parallel.aux2 l with a l'; have C : corec parallel.aux1 (l, S) = _, { apply destruct_eq_ret, simp [parallel.aux1], rw [h], simp [rmap] }, { rw C, resetI, apply_instance }, { apply destruct_eq_think, simp [parallel.aux1], rw [h, H], simp [rmap] }, { rw C, apply @computation.think_terminates _ _ _, apply terminates_parallel.aux _ T, simp } }, { cases o with a a, { exact terminates_parallel.aux a T }, induction h : parallel.aux2 l with a l'; have C : corec parallel.aux1 (l, S) = _, { apply destruct_eq_ret, simp [parallel.aux1], rw [h], simp [rmap] }, { rw C, resetI, apply_instance }, { apply destruct_eq_think, simp [parallel.aux1], rw [h], simp [rmap] }, { rw C, apply @computation.think_terminates _ _ _, have TT : ∀ l', terminates (corec parallel.aux1 (l', S.tail)), { intro, apply IH _ _ _ (or.inr _) T, rw a, cases S with f al, refl }, induction e : seq.nth S 0 with o, { have D : seq.destruct S = none, { dsimp [seq.destruct], rw e, refl }, rw D, simp [parallel.aux1], have TT := TT l', rwa [seq.destruct_eq_nil D, seq.tail_nil] at TT }, { have D : seq.destruct S = some (o, S.tail), { dsimp [seq.destruct], rw e, refl }, rw D, cases o with c; simp [parallel.aux1, TT] } } } end theorem exists_of_mem_parallel {S : wseq (computation α)} {a} (h : a ∈ parallel S) : ∃ c ∈ S, a ∈ c := suffices ∀ C, a ∈ C → ∀ (l : list (computation α)) S, corec parallel.aux1 (l, S) = C → ∃ c, (c ∈ l ∨ c ∈ S) ∧ a ∈ c, from let ⟨c, h1, h2⟩ := this _ h [] S rfl in ⟨c, h1.resolve_left id, h2⟩, begin let F : list (computation α) → α ⊕ list (computation α) → Prop, { intros l a, cases a with a l', exact ∃ c ∈ l, a ∈ c, exact ∀ a', (∃ c ∈ l', a' ∈ c) → (∃ c ∈ l, a' ∈ c) }, have lem1 : ∀ (l : list (computation α)), F l (parallel.aux2 l), { intro l, induction l with c l IH; simp [parallel.aux2], { intros a h, rcases h with ⟨c, hn, _⟩, exact false.elim hn }, { simp [parallel.aux2] at IH, cases list.foldr parallel.aux2._match_1 (sum.inr list.nil) l with a ls; simp [parallel.aux2], { rcases IH with ⟨c', cl, ac⟩, refine ⟨c', or.inr cl, ac⟩ }, { induction h : destruct c with a c'; simp [rmap], { refine ⟨c, list.mem_cons_self _ _, _⟩, rw destruct_eq_ret h, apply ret_mem }, { intros a' h, rcases h with ⟨d, dm, ad⟩, simp at dm, cases dm with e dl, { rw e at ad, refine ⟨c, list.mem_cons_self _ _, _⟩, rw destruct_eq_think h, exact think_mem ad }, { cases IH a' ⟨d, dl, ad⟩ with d dm, cases dm with dm ad, exact ⟨d, or.inr dm, ad⟩ } } } } }, intros C aC, refine mem_rec_on aC _ (λ C' IH, _); intros l S e; have e' := congr_arg destruct e; have := lem1 l; simp [parallel.aux1] at e'; cases parallel.aux2 l with a' l'; injection e' with h', { rw h' at this, rcases this with ⟨c, cl, ac⟩, exact ⟨c, or.inl cl, ac⟩ }, { induction e : seq.destruct S with a; rw e at h', { exact let ⟨d, o, ad⟩ := IH _ _ h', ⟨c, cl, ac⟩ := this a ⟨d, o.resolve_right (not_mem_nil _), ad⟩ in ⟨c, or.inl cl, ac⟩ }, { cases a with o S', cases o with c; simp [parallel.aux1] at h'; rcases IH _ _ h' with ⟨d, dl | dS', ad⟩, { exact let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩ in ⟨c, or.inl cl, ac⟩ }, { refine ⟨d, or.inr _, ad⟩, rw seq.destruct_eq_cons e, exact seq.mem_cons_of_mem _ dS' }, { simp at dl, cases dl with dc dl, { rw dc at ad, refine ⟨c, or.inr _, ad⟩, rw seq.destruct_eq_cons e, apply seq.mem_cons }, { exact let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩ in ⟨c, or.inl cl, ac⟩ } }, { refine ⟨d, or.inr _, ad⟩, rw seq.destruct_eq_cons e, exact seq.mem_cons_of_mem _ dS' } } } end theorem map_parallel (f : α → β) (S) : map f (parallel S) = parallel (S.map (map f)) := begin refine eq_of_bisim (λ c1 c2, ∃ l S, c1 = map f (corec parallel.aux1 (l, S)) ∧ c2 = corec parallel.aux1 (l.map (map f), S.map (map f))) _ ⟨[], S, rfl, rfl⟩, intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨l, S, rfl, rfl⟩ := begin clear _match, have : parallel.aux2 (l.map (map f)) = lmap f (rmap (list.map (map f)) (parallel.aux2 l)), { simp [parallel.aux2], induction l with c l IH; simp, rw [IH], cases list.foldr parallel.aux2._match_1 (sum.inr list.nil) l; simp [parallel.aux2], cases destruct c; simp }, simp [parallel.aux1], rw this, cases parallel.aux2 l with a l'; simp, apply S.cases_on _ (λ c S, _) (λ S, _); simp; simp [parallel.aux1]; exact ⟨_, _, rfl, rfl⟩ end end end theorem parallel_empty (S : wseq (computation α)) (h : S.head ~> none) : parallel S = empty _ := eq_empty_of_not_terminates $ λ ⟨⟨a, m⟩⟩, let ⟨c, cs, ac⟩ := exists_of_mem_parallel m, ⟨n, nm⟩ := exists_nth_of_mem cs, ⟨c', h'⟩ := head_some_of_nth_some nm in by injection h h' -- The reason this isn't trivial from exists_of_mem_parallel is because it eliminates to Sort def parallel_rec {S : wseq (computation α)} (C : α → Sort v) (H : ∀ s ∈ S, ∀ a ∈ s, C a) {a} (h : a ∈ parallel S) : C a := begin let T : wseq (computation (α × computation α)) := S.map (λ c, c.map (λ a, (a, c))), have : S = T.map (map (λ c, c.1)), { rw [←wseq.map_comp], refine (wseq.map_id _).symm.trans (congr_arg (λ f, wseq.map f S) _), funext c, dsimp [id, function.comp], rw [←map_comp], exact (map_id _).symm }, have pe := congr_arg parallel this, rw ←map_parallel at pe, have h' := h, rw pe at h', haveI : terminates (parallel T) := (terminates_map_iff _ _).1 ⟨⟨_, h'⟩⟩, induction e : get (parallel T) with a' c, have : a ∈ c ∧ c ∈ S, { rcases exists_of_mem_map h' with ⟨d, dT, cd⟩, rw get_eq_of_mem _ dT at e, cases e, dsimp at cd, cases cd, rcases exists_of_mem_parallel dT with ⟨d', dT', ad'⟩, rcases wseq.exists_of_mem_map dT' with ⟨c', cs', e'⟩, rw ←e' at ad', rcases exists_of_mem_map ad' with ⟨a', ac', e'⟩, injection e' with i1 i2, constructor, rwa [i1, i2] at ac', rwa i2 at cs' }, cases this with ac cs, apply H _ cs _ ac end theorem parallel_promises {S : wseq (computation α)} {a} (H : ∀ s ∈ S, s ~> a) : parallel S ~> a := λ a' ma', let ⟨c, cs, ac⟩ := exists_of_mem_parallel ma' in H _ cs ac theorem mem_parallel {S : wseq (computation α)} {a} (H : ∀ s ∈ S, s ~> a) {c} (cs : c ∈ S) (ac : a ∈ c) : a ∈ parallel S := by haveI := terminates_of_mem ac; haveI := terminates_parallel cs; exact mem_of_promises _ (parallel_promises H) theorem parallel_congr_lem {S T : wseq (computation α)} {a} (H : S.lift_rel equiv T) : (∀ s ∈ S, s ~> a) ↔ (∀ t ∈ T, t ~> a) := ⟨λ h1 t tT, let ⟨s, sS, se⟩ := wseq.exists_of_lift_rel_right H tT in (promises_congr se _).1 (h1 _ sS), λ h2 s sS, let ⟨t, tT, se⟩ := wseq.exists_of_lift_rel_left H sS in (promises_congr se _).2 (h2 _ tT)⟩ -- The parallel operation is only deterministic when all computation paths lead to the same value theorem parallel_congr_left {S T : wseq (computation α)} {a} (h1 : ∀ s ∈ S, s ~> a) (H : S.lift_rel equiv T) : parallel S ~ parallel T := let h2 := (parallel_congr_lem H).1 h1 in λ a', ⟨λ h, by have aa := parallel_promises h1 h; rw ←aa; rw ←aa at h; exact let ⟨s, sS, as⟩ := exists_of_mem_parallel h, ⟨t, tT, st⟩ := wseq.exists_of_lift_rel_left H sS, aT := (st _).1 as in mem_parallel h2 tT aT, λ h, by have aa := parallel_promises h2 h; rw ←aa; rw ←aa at h; exact let ⟨s, sS, as⟩ := exists_of_mem_parallel h, ⟨t, tT, st⟩ := wseq.exists_of_lift_rel_right H sS, aT := (st _).2 as in mem_parallel h1 tT aT⟩ theorem parallel_congr_right {S T : wseq (computation α)} {a} (h2 : ∀ t ∈ T, t ~> a) (H : S.lift_rel equiv T) : parallel S ~ parallel T := parallel_congr_left ((parallel_congr_lem H).2 h2) H end computation
e4ce2622ca8b5e5c59eab682901d8b031ed69d66
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/levelparsertest1.lean
12a726a3187d40a0fe9442e8a6ee046a31ae5747
[ "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
498
lean
import init.lean.parser.level open Lean open Lean.Parser def testParser (input : String) : IO Unit := do env ← mkEmptyEnvironment; levelPTables ← builtinLevelParsingTable.get; stx ← IO.ofExcept $ runParser env levelPTables input; IO.println stx def main (xs : List String) : IO Unit := do testParser "max 0 1"; testParser "(1)"; testParser "u"; testParser "(u)"; testParser "(u+1)"; testParser "(u+1+2)"; testParser "(max u v w)"; testParser "imax u v"; testParser "(max (u+1) v)"; pure ()
fa1065bc58cf3fc9aeb78e161c944ab1e9732d9c
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebra/lie/abelian.lean
268ad1112e4357d8b25cdf8548dde5024d726e34
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,931
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.of_associative import algebra.lie.ideal_operations /-! # Trivial Lie modules and Abelian Lie algebras The action of a Lie algebra `L` on a module `M` is trivial if `⁅x, m⁆ = 0` for all `x ∈ L` and `m ∈ M`. In the special case that `M = L` with the adjoint action, triviality corresponds to the concept of an Abelian Lie algebra. In this file we define these concepts and provide some related definitions and results. ## Main definitions * `lie_module.is_trivial` * `is_lie_abelian` * `commutative_ring_iff_abelian_lie_ring` * `lie_module.ker` * `lie_module.max_triv_submodule` * `lie_algebra.center` ## Tags lie algebra, abelian, commutative, center -/ universes u v w w₁ w₂ /-- A Lie (ring) module is trivial iff all brackets vanish. -/ class lie_module.is_trivial (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] : Prop := (trivial : ∀ (x : L) (m : M), ⁅x, m⁆ = 0) @[simp] lemma trivial_lie_zero (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] [lie_module.is_trivial L M] (x : L) (m : M) : ⁅x, m⁆ = 0 := lie_module.is_trivial.trivial x m /-- A Lie algebra is Abelian iff it is trivial as a Lie module over itself. -/ abbreviation is_lie_abelian (L : Type v) [has_bracket L L] [has_zero L] : Prop := lie_module.is_trivial L L instance lie_ideal.is_lie_abelian_of_trivial (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) [h : lie_module.is_trivial L I] : is_lie_abelian I := { trivial := λ x y, by apply h.trivial, } lemma function.injective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.injective f) (h₂ : is_lie_abelian L₂) : is_lie_abelian L₁ := { trivial := λ x y, by { apply h₁, rw [lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], } } lemma function.surjective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.surjective f) (h₂ : is_lie_abelian L₁) : is_lie_abelian L₂ := { trivial := λ x y, begin obtain ⟨u, hu⟩ := h₁ x, rw ← hu, obtain ⟨v, hv⟩ := h₁ y, rw ← hv, rw [← lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], end } lemma lie_abelian_iff_equiv_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] (e : L₁ ≃ₗ⁅R⁆ L₂) : is_lie_abelian L₁ ↔ is_lie_abelian L₂ := ⟨e.symm.injective.is_lie_abelian, e.injective.is_lie_abelian⟩ lemma commutative_ring_iff_abelian_lie_ring {A : Type v} [ring A] : is_commutative A (*) ↔ is_lie_abelian A := begin have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩, have h₂ : is_lie_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩, simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero], end lemma lie_algebra.is_lie_abelian_bot (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : is_lie_abelian (⊥ : lie_ideal R L) := ⟨begin rintros ⟨x, hx⟩ ⟨y, hy⟩, suffices : ⁅x, y⁆ = 0, { ext, simp only [this, lie_subalgebra.coe_bracket, submodule.coe_mk, submodule.coe_zero], }, change x ∈ (⊥ : lie_ideal R L) at hx, rw lie_submodule.mem_bot at hx, rw [hx, zero_lie], end⟩ section center variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] namespace lie_module /-- The kernel of the action of a Lie algebra `L` on a Lie module `M` as a Lie ideal in `L`. -/ protected def ker : lie_ideal R L := (to_endomorphism R L M).ker @[simp] protected lemma mem_ker (x : L) : x ∈ lie_module.ker R L M ↔ ∀ (m : M), ⁅x, m⁆ = 0 := begin dunfold lie_module.ker, simp only [lie_hom.mem_ker, linear_map.ext_iff, linear_map.zero_apply, to_endomorphism_apply_apply], end /-- The largest submodule of a Lie module `M` on which the Lie algebra `L` acts trivially. -/ def max_triv_submodule : lie_submodule R L M := { carrier := { m | ∀ (x : L), ⁅x, m⁆ = 0 }, zero_mem' := λ x, lie_zero x, add_mem' := λ x y hx hy z, by rw [lie_add, hx, hy, add_zero], smul_mem' := λ c x hx y, by rw [lie_smul, hx, smul_zero], lie_mem := λ x m hm y, by rw [hm, lie_zero], } @[simp] lemma mem_max_triv_submodule (m : M) : m ∈ max_triv_submodule R L M ↔ ∀ (x : L), ⁅x, m⁆ = 0 := iff.rfl instance : is_trivial L (max_triv_submodule R L M) := { trivial := λ x m, subtype.ext (m.property x), } lemma trivial_iff_le_maximal_trivial (N : lie_submodule R L M) : is_trivial L N ↔ N ≤ max_triv_submodule R L M := begin split, { rintros ⟨h⟩, intros m hm x, specialize h x ⟨m, hm⟩, rw subtype.ext_iff at h, exact h, }, { intros h, constructor, rintros x ⟨m, hm⟩, apply subtype.ext, apply h, exact hm, }, end lemma is_trivial_iff_max_triv_eq_top : is_trivial L M ↔ max_triv_submodule R L M = ⊤ := begin split, { rintros ⟨h⟩, ext, simp only [mem_max_triv_submodule, h, forall_const, true_iff, eq_self_iff_true], }, { intros h, constructor, intros x m, revert x, rw [← mem_max_triv_submodule R L M, h], exact lie_submodule.mem_top m, }, end variables {R L M N} /-- `max_triv_submodule` is functorial. -/ def max_triv_hom (f : M →ₗ⁅R,L⁆ N) : max_triv_submodule R L M →ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := λ m, ⟨f m, λ x, by { have h := congr_arg f (m.property x), rw [lie_module_hom.map_zero, lie_module_hom.map_lie] at h, exact h, }⟩, map_add' := λ m n, by simpa, map_smul' := λ t m, by simpa, map_lie' := λ x m, by simp, } @[norm_cast, simp] lemma coe_max_triv_hom_apply (f : M →ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_hom f m : N) = f m := rfl /-- The maximal trivial submodules of Lie-equivalent Lie modules are Lie-equivalent. -/ def max_triv_equiv (e : M ≃ₗ⁅R,L⁆ N) : max_triv_submodule R L M ≃ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := max_triv_hom (e : M →ₗ⁅R,L⁆ N), inv_fun := max_triv_hom (e.symm : N →ₗ⁅R,L⁆ M), left_inv := λ m, by { ext, simp, }, right_inv := λ n, by { ext, simp, }, .. max_triv_hom (e : M →ₗ⁅R,L⁆ N), } @[norm_cast, simp] lemma coe_max_triv_equiv_apply (e : M ≃ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_equiv e m : N) = e ↑m := rfl @[simp] lemma max_triv_equiv_of_refl_eq_refl : max_triv_equiv (lie_module_equiv.refl : M ≃ₗ⁅R,L⁆ M) = lie_module_equiv.refl := by { ext, simp only [coe_max_triv_equiv_apply, lie_module_equiv.refl_apply], } @[simp] lemma max_triv_equiv_of_equiv_symm_eq_symm (e : M ≃ₗ⁅R,L⁆ N) : (max_triv_equiv e).symm = max_triv_equiv e.symm := rfl /-- A linear map between two Lie modules is a morphism of Lie modules iff the Lie algebra action on it is trivial. -/ def max_triv_linear_map_equiv_lie_module_hom : (max_triv_submodule R L (M →ₗ[R] N)) ≃ₗ[R] (M →ₗ⁅R,L⁆ N) := { to_fun := λ f, { map_lie' := λ x m, by { have hf : ⁅x, f.val⁆ m = 0, { rw [f.property x, linear_map.zero_apply], }, rw [lie_hom.lie_apply, sub_eq_zero, ← linear_map.to_fun_eq_coe] at hf, exact hf.symm, }, ..f.val, }, map_add' := λ f g, by { ext, simp, }, map_smul' := λ F G, by { ext, simp, }, inv_fun := λ F, ⟨F, λ x, by { ext, simp, }⟩, left_inv := λ f, by simp, right_inv := λ F, by simp, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M → N) = f := by { ext, refl, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M → N) = f := rfl @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := by { ext, refl, } @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := rfl end lie_module namespace lie_algebra /-- The center of a Lie algebra is the set of elements that commute with everything. It can be viewed as the maximal trivial submodule of the Lie algebra as a Lie module over itself via the adjoint representation. -/ abbreviation center : lie_ideal R L := lie_module.max_triv_submodule R L L instance : is_lie_abelian (center R L) := infer_instance lemma center_eq_adjoint_kernel : center R L = lie_module.ker R L L := begin ext y, simp only [lie_module.mem_max_triv_submodule, lie_module.mem_ker, ← lie_skew _ y, neg_eq_zero], end lemma abelian_of_le_center (I : lie_ideal R L) (h : I ≤ center R L) : is_lie_abelian I := begin rw ← lie_module.trivial_iff_le_maximal_trivial R L L I at h, haveI := h, exact lie_ideal.is_lie_abelian_of_trivial R L I, end lemma is_lie_abelian_iff_center_eq_top : is_lie_abelian L ↔ center R L = ⊤ := lie_module.is_trivial_iff_max_triv_eq_top R L L end lie_algebra end center section ideal_operations open lie_submodule lie_subalgebra variables {R : Type u} {L : Type v} {M : Type w} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) @[simp] lemma lie_submodule.trivial_lie_oper_zero [lie_module.is_trivial L M] : ⁅I, N⁆ = ⊥ := begin suffices : ⁅I, N⁆ ≤ ⊥, { exact le_bot_iff.mp this, }, rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_le], rintros m ⟨x, n, h⟩, rw trivial_lie_zero at h, simp [← h], end lemma lie_submodule.lie_abelian_iff_lie_self_eq_bot : is_lie_abelian I ↔ ⁅I, I⁆ = ⊥ := begin simp only [_root_.eq_bot_iff, lie_ideal_oper_eq_span, lie_submodule.lie_span_le, lie_submodule.bot_coe, set.subset_singleton_iff, set.mem_set_of_eq, exists_imp_distrib], split; intros h, { intros z x y hz, rw [← hz, ← coe_bracket, coe_zero_iff_zero], apply h.trivial, }, { exact ⟨λ x y, by { rw ← coe_zero_iff_zero, apply h _ x y, refl, }⟩, }, end end ideal_operations
a19b5f7b73b723cc270c06fb602f1dcc5087f269
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/unit_interval.lean
28a1e9a3e9a69ddf6da576926660c32fc8824679
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
3,671
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison -/ import topology.instances.real import topology.algebra.field /-! # The unit interval, as a topological space Use `open_locale unit_interval` to turn on the notation `I := set.Icc (0 : ℝ) (1 : ℝ)`. We provide basic instances, as well as a custom tactic for discharging `0 ≤ x`, `0 ≤ 1 - x`, `x ≤ 1`, and `1 - x ≤ 1` when `x : I`. -/ noncomputable theory open_locale classical topological_space filter open set /-! ### The unit interval -/ /-- The unit interval `[0,1]` in ℝ. -/ abbreviation unit_interval : set ℝ := set.Icc 0 1 localized "notation `I` := unit_interval" in unit_interval namespace unit_interval lemma mem_iff_one_sub_mem {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := begin rw [mem_Icc, mem_Icc], split ; intro ; split ; linarith end instance has_zero : has_zero I := ⟨⟨0, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_zero : ((0 : I) : ℝ) = 0 := rfl instance has_one : has_one I := ⟨⟨1, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_one : ((1 : I) : ℝ) = 1 := rfl instance : nonempty I := ⟨0⟩ /-- Unit interval central symmetry. -/ def symm : I → I := λ t, ⟨1 - t.val, mem_iff_one_sub_mem.mp t.property⟩ localized "notation `σ` := unit_interval.symm" in unit_interval @[simp] lemma symm_zero : σ 0 = 1 := subtype.ext $ by simp [symm] @[simp] lemma symm_one : σ 1 = 0 := subtype.ext $ by simp [symm] @[continuity] lemma continuous_symm : continuous σ := by continuity! instance : connected_space I := subtype.connected_space ⟨nonempty_Icc.mpr zero_le_one, is_preconnected_Icc⟩ /-- Verify there is an instance for `compact_space I`. -/ example : compact_space I := by apply_instance lemma nonneg (x : I) : 0 ≤ (x : ℝ) := x.2.1 lemma one_minus_nonneg (x : I) : 0 ≤ 1 - (x : ℝ) := by simpa using x.2.2 lemma le_one (x : I) : (x : ℝ) ≤ 1 := x.2.2 lemma one_minus_le_one (x : I) : 1 - (x : ℝ) ≤ 1 := by simpa using x.2.1 end unit_interval namespace tactic.interactive /-- A tactic that solves `0 ≤ x`, `0 ≤ 1 - x`, `x ≤ 1`, and `1 - x ≤ 1` for `x : I`. -/ meta def unit_interval : tactic unit := `[apply unit_interval.nonneg] <|> `[apply unit_interval.one_minus_nonneg] <|> `[apply unit_interval.le_one] <|> `[apply unit_interval.one_minus_le_one] end tactic.interactive section variables {𝕜 : Type*} [linear_ordered_field 𝕜] [topological_space 𝕜] [topological_ring 𝕜] /-- The image of `[0,1]` under the homeomorphism `λ x, a * x + b` is `[b, a+b]`. -/ -- We only need the ordering on `𝕜` here to avoid talking about flipping the interval over. -- At the end of the day I only care about `ℝ`, so I'm hesitant to put work into generalizing. lemma affine_homeomorph_image_I (a b : 𝕜) (h : 0 < a) : affine_homeomorph a b h.ne.symm '' set.Icc 0 1 = set.Icc b (a + b) := by simp [h] /-- The affine homeomorphism from a nontrivial interval `[a,b]` to `[0,1]`. -/ def Icc_homeo_I (a b : 𝕜) (h : a < b) : set.Icc a b ≃ₜ set.Icc (0 : 𝕜) (1 : 𝕜) := begin let e := homeomorph.image (affine_homeomorph (b-a) a (sub_pos.mpr h).ne.symm) (set.Icc 0 1), refine (e.trans _).symm, apply homeomorph.set_congr, simp [sub_pos.mpr h], end @[simp] lemma Icc_homeo_I_apply_coe (a b : 𝕜) (h : a < b) (x : set.Icc a b) : ((Icc_homeo_I a b h) x : 𝕜) = (x - a) / (b - a) := rfl @[simp] lemma Icc_homeo_I_symm_apply_coe (a b : 𝕜) (h : a < b) (x : set.Icc (0 : 𝕜) (1 : 𝕜)) : ((Icc_homeo_I a b h).symm x : 𝕜) = (b - a) * x + a := rfl end
bc1f062a50744d8868d8942ce0f2c7ec986041c1
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/category/CommRing/basic.lean
cdc08c31c835d33062ef807c6f4ee53d6b82e74d
[ "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
6,420
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Yury Kudryashov -/ import algebra.category.Group import category_theory.fully_faithful import algebra.ring import data.int.basic /-! # Category instances for semiring, ring, comm_semiring, and comm_ring. We introduce the bundled categories: * `SemiRing` * `Ring` * `CommSemiRing` * `CommRing` along with the relevant forgetful functors between them. ## Implementation notes See the note [locally reducible category instances]. -/ universes u v open category_theory /-- The category of semirings. -/ def SemiRing : Type (u+1) := bundled semiring namespace SemiRing /-- Construct a bundled SemiRing from the underlying type and typeclass. -/ def of (R : Type u) [semiring R] : SemiRing := bundled.of R local attribute [reducible] SemiRing instance : has_coe_to_sort SemiRing := infer_instance -- short-circuit type class inference instance (R : SemiRing) : semiring R := R.str instance bundled_hom : bundled_hom @ring_hom := ⟨@ring_hom.to_fun, @ring_hom.id, @ring_hom.comp, @ring_hom.coe_inj⟩ instance : concrete_category SemiRing := infer_instance -- short-circuit type class inference instance has_forget_to_Mon : has_forget₂ SemiRing Mon := bundled_hom.mk_has_forget₂ @semiring.to_monoid (λ R₁ R₂, ring_hom.to_monoid_hom) (λ _ _ _, rfl) instance has_forget_to_AddCommMon : has_forget₂ SemiRing AddCommMon := -- can't use bundled_hom.mk_has_forget₂, since AddCommMon is an induced category { forget₂ := { obj := λ R, AddCommMon.of R, map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } } end SemiRing /-- The category of rings. -/ def Ring : Type (u+1) := induced_category SemiRing (bundled.map @ring.to_semiring) namespace Ring /-- Construct a bundled Ring from the underlying type and typeclass. -/ def of (R : Type u) [ring R] : Ring := bundled.of R local attribute [reducible] Ring instance : has_coe_to_sort Ring := infer_instance -- short-circuit type class inference instance (R : Ring) : ring R := R.str instance : concrete_category Ring := infer_instance -- short-circuit type class inference instance has_forget_to_SemiRing : has_forget₂ Ring SemiRing := infer_instance -- short-circuit type class inference instance has_forget_to_AddCommGroup : has_forget₂ Ring AddCommGroup := -- can't use bundled_hom.mk_has_forget₂, since AddCommGroup is an induced category { forget₂ := { obj := λ R, AddCommGroup.of R, map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } } end Ring /-- The category of commutative semirings. -/ def CommSemiRing : Type (u+1) := induced_category SemiRing (bundled.map comm_semiring.to_semiring) namespace CommSemiRing /-- Construct a bundled CommSemiRing from the underlying type and typeclass. -/ def of (R : Type u) [comm_semiring R] : CommSemiRing := bundled.of R local attribute [reducible] CommSemiRing instance : has_coe_to_sort CommSemiRing := infer_instance -- short-circuit type class inference instance (R : CommSemiRing) : comm_semiring R := R.str instance : concrete_category CommSemiRing := infer_instance -- short-circuit type class inference instance has_forget_to_SemiRing : has_forget₂ CommSemiRing SemiRing := infer_instance -- short-circuit type class inference /-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/ instance has_forget_to_CommMon : has_forget₂ CommSemiRing CommMon := has_forget₂.mk' (λ R : CommSemiRing, CommMon.of R) (λ R, rfl) (λ R₁ R₂ f, f.to_monoid_hom) (by tidy) end CommSemiRing /-- The category of commutative rings. -/ def CommRing : Type (u+1) := induced_category Ring (bundled.map comm_ring.to_ring) namespace CommRing /-- Construct a bundled CommRing from the underlying type and typeclass. -/ def of (R : Type u) [comm_ring R] : CommRing := bundled.of R local attribute [reducible] CommRing instance : has_coe_to_sort CommRing := infer_instance -- short-circuit type class inference instance (R : CommRing) : comm_ring R := R.str instance : concrete_category CommRing := infer_instance -- short-circuit type class inference instance has_forget_to_Ring : has_forget₂ CommRing Ring := infer_instance -- short-circuit type class inference /-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/ instance has_forget_to_CommSemiRing : has_forget₂ CommRing CommSemiRing := has_forget₂.mk' (λ R : CommRing, CommSemiRing.of R) (λ R, rfl) (λ R₁ R₂ f, f) (by tidy) end CommRing namespace ring_equiv variables {X Y : Type u} /-- Build an isomorphism in the category `Ring` from a `ring_equiv` between `ring`s. -/ @[simps] def to_Ring_iso [ring X] [ring Y] (e : X ≃+* Y) : Ring.of X ≅ Ring.of Y := { hom := e.to_ring_hom, inv := e.symm.to_ring_hom } /-- Build an isomorphism in the category `CommRing` from a `ring_equiv` between `comm_ring`s. -/ @[simps] def to_CommRing_iso [comm_ring X] [comm_ring Y] (e : X ≃+* Y) : CommRing.of X ≅ CommRing.of Y := { hom := e.to_ring_hom, inv := e.symm.to_ring_hom } end ring_equiv namespace category_theory.iso /-- Build a `ring_equiv` from an isomorphism in the category `Ring`. -/ def Ring_iso_to_ring_equiv {X Y : Ring.{u}} (i : X ≅ Y) : X ≃+* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_mul' := by tidy }. /-- Build a `ring_equiv` from an isomorphism in the category `CommRing`. -/ def CommRing_iso_to_ring_equiv {X Y : CommRing.{u}} (i : X ≅ Y) : X ≃+* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_mul' := by tidy }. end category_theory.iso /-- ring equivalences between `ring`s are the same as (isomorphic to) isomorphisms in `Ring`. -/ def ring_equiv_iso_Ring_iso {X Y : Type u} [ring X] [ring Y] : (X ≃+* Y) ≅ (Ring.of X ≅ Ring.of Y) := { hom := λ e, e.to_Ring_iso, inv := λ i, i.Ring_iso_to_ring_equiv, } /-- ring equivalences between `comm_ring`s are the same as (isomorphic to) isomorphisms in `CommRing`. -/ def ring_equiv_iso_CommRing_iso {X Y : Type u} [comm_ring X] [comm_ring Y] : (X ≃+* Y) ≅ (CommRing.of X ≅ CommRing.of Y) := { hom := λ e, e.to_CommRing_iso, inv := λ i, i.CommRing_iso_to_ring_equiv, }
ad9262a11c5d2ec1ce6ff780223bff75484aa60e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/finsupp/lattice.lean
9c84d5e819270a097a76475b8403d4c7843d4d4e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
4,248
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.finsupp.basic import algebra.ordered_group /-! # Lattice structure on finsupps This file provides instances of ordered structures on finsupps. -/ open_locale classical noncomputable theory variables {α : Type*} {β : Type*} [has_zero β] {μ : Type*} [canonically_ordered_add_monoid μ] variables {γ : Type*} [canonically_linear_ordered_add_monoid γ] namespace finsupp lemma le_def [partial_order β] {a b : α →₀ β} : a ≤ b ↔ ∀ (s : α), a s ≤ b s := by refl instance : order_bot (α →₀ μ) := { bot := 0, bot_le := by simp [finsupp.le_def, ← bot_eq_zero], .. finsupp.partial_order} instance [semilattice_inf β] : semilattice_inf (α →₀ β) := { inf := zip_with (⊓) inf_idem, inf_le_left := λ a b c, inf_le_left, inf_le_right := λ a b c, inf_le_right, le_inf := λ a b c h1 h2 s, le_inf (h1 s) (h2 s), ..finsupp.partial_order, } @[simp] lemma inf_apply [semilattice_inf β] {a : α} {f g : α →₀ β} : (f ⊓ g) a = f a ⊓ g a := rfl @[simp] lemma support_inf {f g : α →₀ γ} : (f ⊓ g).support = f.support ∩ g.support := begin ext, simp only [inf_apply, mem_support_iff, ne.def, finset.mem_union, finset.mem_filter, finset.mem_inter], rw [← decidable.not_or_iff_and_not, ← not_congr], rw inf_eq_min, unfold min, split_ifs; { try {apply or_iff_left_of_imp}, try {apply or_iff_right_of_imp}, intro con, rw con at h, revert h, simp, } end instance [semilattice_sup β] : semilattice_sup (α →₀ β) := { sup := zip_with (⊔) sup_idem, le_sup_left := λ a b c, le_sup_left, le_sup_right := λ a b c, le_sup_right, sup_le := λ a b c h1 h2 s, sup_le (h1 s) (h2 s), ..finsupp.partial_order, } @[simp] lemma sup_apply [semilattice_sup β] {a : α} {f g : α →₀ β} : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma support_sup {f g : α →₀ γ} : (f ⊔ g).support = f.support ∪ g.support := begin ext, simp only [finset.mem_union, mem_support_iff, sup_apply, ne.def, ← bot_eq_zero], rw sup_eq_bot_iff, tauto, end instance lattice [lattice β] : lattice (α →₀ β) := { .. finsupp.semilattice_inf, .. finsupp.semilattice_sup} instance semilattice_inf_bot : semilattice_inf_bot (α →₀ γ) := { ..finsupp.order_bot, ..finsupp.lattice} lemma of_multiset_strict_mono : strict_mono (@finsupp.of_multiset α) := begin unfold strict_mono, intros a b hab, rw lt_iff_le_and_ne at *, split, { rw finsupp.le_iff, intros s hs, repeat {rw finsupp.of_multiset_apply}, rw multiset.le_iff_count at hab, apply hab.left }, { have h := hab.right, contrapose h, simp at *, apply finsupp.equiv_multiset.symm.injective h } end lemma bot_eq_zero : (⊥ : α →₀ γ) = 0 := rfl lemma disjoint_iff {x y : α →₀ γ} : disjoint x y ↔ disjoint x.support y.support := begin unfold disjoint, repeat {rw le_bot_iff}, rw [finsupp.bot_eq_zero, ← finsupp.support_eq_empty, finsupp.support_inf], refl, end /-- The lattice of `finsupp`s to `ℕ` is order-isomorphic to that of `multiset`s. -/ def order_iso_multiset : (α →₀ ℕ) ≃o multiset α := ⟨finsupp.equiv_multiset, begin intros a b, unfold finsupp.equiv_multiset, dsimp, rw multiset.le_iff_count, simp only [finsupp.count_to_multiset], refl end ⟩ @[simp] lemma order_iso_multiset_apply {f : α →₀ ℕ} : order_iso_multiset f = f.to_multiset := rfl @[simp] lemma order_iso_multiset_symm_apply {s : multiset α} : order_iso_multiset.symm s = s.to_finsupp := by { conv_rhs { rw ← (rel_iso.apply_symm_apply order_iso_multiset) s}, simp } variable [partial_order β] /-- The order on `finsupp`s over a partial order embeds into the order on functions -/ def order_embedding_to_fun : (α →₀ β) ↪o (α → β) := ⟨⟨λ (f : α →₀ β) (a : α), f a, λ f g h, finsupp.ext (λ a, by { dsimp at h, rw h,} )⟩, λ a b, le_def⟩ @[simp] lemma order_embedding_to_fun_apply {f : α →₀ β} {a : α} : order_embedding_to_fun f a = f a := rfl lemma monotone_to_fun : monotone (finsupp.to_fun : (α →₀ β) → (α → β)) := λ f g h a, le_def.1 h a end finsupp
153dc668f3397a20eec2ebb0cf3e45655a70f316
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/sizeof6.lean
06496411f9e8f08483b0b41ed8c2fe8638e6a5c4
[ "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
147
lean
import Std inductive Foo where | mk (args : Std.PersistentArray Foo) #print Foo.mk.sizeOf_spec #print Foo._sizeOf_2_eq #print Foo._sizeOf_3_eq
7c6fd85dc9485ab71660ca47f382837f270413ec
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/ring_theory/discrete_valuation_ring.lean
9617c434c3429249568626c10febe6a12beec760
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
17,209
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import ring_theory.principal_ideal_domain import order.conditionally_complete_lattice import ring_theory.multiplicity import ring_theory.valuation.basic /-! # Discrete valuation rings This file defines discrete valuation rings (DVRs) and develops a basic interface for them. ## Important definitions There are various definitions of a DVR in the literature; we define a DVR to be a local PID which is not a field (the first definition in Wikipedia) and prove that this is equivalent to being a PID with a unique non-zero prime ideal (the definition in Serre's book "Local Fields"). Let R be an integral domain, assumed to be a principal ideal ring and a local ring. * `discrete_valuation_ring R` : a predicate expressing that R is a DVR ### Definitions * `add_val R : R → ℕ` : the additive valuation on a DVR (sending 0 to 0 rather than the mathematically correct +∞). TODO -- the multiplicative valuation, taking values in something like `with_zero (multiplicative ℤ)`? ## Implementation notes It's a theorem that an element of a DVR is a uniformizer if and only if it's irreducible. We do not hence define `uniformizer` at all, because we can use `irreducible` instead. ## Tags discrete valuation ring -/ open_locale classical universe u open ideal local_ring /-- An integral domain is a *discrete valuation ring* (DVR) if it's a local PID which is not a field. -/ class discrete_valuation_ring (R : Type u) [integral_domain R] extends is_principal_ideal_ring R, local_ring R : Prop := (not_a_field' : maximal_ideal R ≠ ⊥) namespace discrete_valuation_ring variables (R : Type u) [integral_domain R] [discrete_valuation_ring R] lemma not_a_field : maximal_ideal R ≠ ⊥ := not_a_field' variable {R} open principal_ideal_ring /-- An element of a DVR is irreducible iff it is a uniformizer, that is, generates the maximal ideal of R -/ theorem irreducible_iff_uniformizer (ϖ : R) : irreducible ϖ ↔ maximal_ideal R = ideal.span {ϖ} := ⟨λ hϖ, (eq_maximal_ideal (is_maximal_of_irreducible hϖ)).symm, begin intro h, have h2 : ¬(is_unit ϖ) := show ϖ ∈ maximal_ideal R, from h.symm ▸ submodule.mem_span_singleton_self ϖ, refine ⟨h2, _⟩, intros a b hab, by_contra h, push_neg at h, obtain ⟨ha : a ∈ maximal_ideal R, hb : b ∈ maximal_ideal R⟩ := h, rw h at ha hb, rw mem_span_singleton' at ha hb, rcases ha with ⟨a, rfl⟩, rcases hb with ⟨b, rfl⟩, rw (show a * ϖ * (b * ϖ) = ϖ * (ϖ * (a * b)), by ring) at hab, have h3 := eq_zero_of_mul_eq_self_right _ hab.symm, { apply not_a_field R, simp [h, h3] }, { intro hh, apply h2, refine is_unit_of_dvd_one ϖ _, use a * b, exact hh.symm } end⟩ variable (R) /-- Uniformisers exist in a DVR -/ theorem exists_irreducible : ∃ ϖ : R, irreducible ϖ := by {simp_rw [irreducible_iff_uniformizer], exact (is_principal_ideal_ring.principal $ maximal_ideal R).principal} /-- an integral domain is a DVR iff it's a PID with a unique non-zero prime ideal -/ theorem iff_pid_with_one_nonzero_prime (R : Type u) [integral_domain R] : discrete_valuation_ring R ↔ is_principal_ideal_ring R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ is_prime P := begin split, { intro RDVR, rcases id RDVR with ⟨RPID, Rlocal, Rnotafield⟩, split, assumption, resetI, use local_ring.maximal_ideal R, split, split, { assumption }, { apply_instance } , { rintro Q ⟨hQ1, hQ2⟩, obtain ⟨q, rfl⟩ := (is_principal_ideal_ring.principal Q).1, have hq : q ≠ 0, { rintro rfl, apply hQ1, simp }, erw span_singleton_prime hq at hQ2, replace hQ2 := irreducible_of_prime hQ2, rw irreducible_iff_uniformizer at hQ2, exact hQ2.symm } }, { rintro ⟨RPID, Punique⟩, haveI : local_ring R := local_of_unique_nonzero_prime R Punique, refine {not_a_field' := _}, rcases Punique with ⟨P, ⟨hP1, hP2⟩, hP3⟩, have hPM : P ≤ maximal_ideal R := le_maximal_ideal (hP2.1), intro h, rw [h, le_bot_iff] at hPM, exact hP1 hPM } end lemma associated_of_irreducible {a b : R} (ha : irreducible a) (hb : irreducible b) : associated a b := begin rw irreducible_iff_uniformizer at ha hb, rw [←span_singleton_eq_span_singleton, ←ha, hb], end end discrete_valuation_ring namespace discrete_valuation_ring variable (R : Type*) /-- Alternative characterisation of discrete valuation rings. -/ def has_unit_mul_pow_irreducible_factorization [integral_domain R] : Prop := ∃ p : R, irreducible p ∧ ∀ {x : R}, x ≠ 0 → ∃ (n : ℕ), associated (p ^ n) x namespace has_unit_mul_pow_irreducible_factorization variables {R} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) include hR lemma unique_irreducible ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) : associated p q := begin rcases hR with ⟨ϖ, hϖ, hR⟩, suffices : ∀ {p : R} (hp : irreducible p), associated p ϖ, { apply associated.trans (this hp) (this hq).symm, }, clear hp hq p q, intros p hp, obtain ⟨n, hn⟩ := hR hp.ne_zero, have : irreducible (ϖ ^ n) := irreducible_of_associated hn.symm hp, rcases lt_trichotomy n 1 with (H|rfl|H), { obtain rfl : n = 0, { clear hn this, revert H n, exact dec_trivial }, simpa only [not_irreducible_one, pow_zero] using this, }, { simpa only [pow_one] using hn.symm, }, { obtain ⟨n, rfl⟩ : ∃ k, n = 1 + k + 1 := nat.exists_eq_add_of_lt H, rw pow_succ at this, rcases this.2 _ _ rfl with H0|H0, { exact (hϖ.not_unit H0).elim, }, { rw [add_comm, pow_succ] at H0, exact (hϖ.not_unit (is_unit_of_mul_is_unit_left H0)).elim } } end /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a unique factorization domain. See `discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization`. -/ theorem to_unique_factorization_monoid : unique_factorization_monoid R := let p := classical.some hR in let spec := classical.some_spec hR in unique_factorization_monoid.of_exists_prime_factors $ λ x hx, begin use multiset.repeat p (classical.some (spec.2 hx)), split, { intros q hq, have hpq := multiset.eq_of_mem_repeat hq, rw hpq, refine ⟨spec.1.ne_zero, spec.1.not_unit, _⟩, intros a b h, by_cases ha : a = 0, { rw ha, simp only [true_or, dvd_zero], }, by_cases hb : b = 0, { rw hb, simp only [or_true, dvd_zero], }, obtain ⟨m, u, rfl⟩ := spec.2 ha, rw [mul_assoc, mul_left_comm, is_unit.dvd_mul_left _ _ _ (is_unit_unit _)] at h, rw is_unit.dvd_mul_right (is_unit_unit _), by_cases hm : m = 0, { simp only [hm, one_mul, pow_zero] at h ⊢, right, exact h }, left, obtain ⟨m, rfl⟩ := nat.exists_eq_succ_of_ne_zero hm, apply dvd_mul_of_dvd_left (dvd_refl _) _ }, { rw [multiset.prod_repeat], exact (classical.some_spec (spec.2 hx)), } end omit hR lemma of_ufd_of_unique_irreducible [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : has_unit_mul_pow_irreducible_factorization R := begin obtain ⟨p, hp⟩ := h₁, refine ⟨p, hp, _⟩, intros x hx, cases wf_dvd_monoid.exists_factors x hx with fx hfx, refine ⟨fx.card, _⟩, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, symmetry, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ q hq rfl, rw associates.mk_eq_mk_iff_associated, apply h₂ (hfx.1 _ hq) hp, end end has_unit_mul_pow_irreducible_factorization lemma aux_pid_of_ufd_of_unique_irreducible (R : Type u) [integral_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : is_principal_ideal_ring R := begin constructor, intro I, by_cases I0 : I = ⊥, { rw I0, use 0, simp only [set.singleton_zero, submodule.span_zero], }, obtain ⟨x, hxI, hx0⟩ : ∃ x ∈ I, x ≠ (0:R) := I.ne_bot_iff.mp I0, obtain ⟨p, hp, H⟩ := has_unit_mul_pow_irreducible_factorization.of_ufd_of_unique_irreducible h₁ h₂, have ex : ∃ n : ℕ, p ^ n ∈ I, { obtain ⟨n, u, rfl⟩ := H hx0, refine ⟨n, _⟩, simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hxI, }, constructor, use p ^ (nat.find ex), show I = ideal.span _, apply le_antisymm, { intros r hr, by_cases hr0 : r = 0, { simp only [hr0, submodule.zero_mem], }, obtain ⟨n, u, rfl⟩ := H hr0, simp only [mem_span_singleton, is_unit_unit, is_unit.dvd_mul_right], apply pow_dvd_pow, apply nat.find_min', simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hr, }, { erw submodule.span_singleton_le_iff_mem, exact nat.find_spec ex, }, end /-- A unique factorization domain with at least one irreducible element in which all irreducible elements are associated is a discrete valuation ring. -/ lemma of_ufd_of_unique_irreducible {R : Type u} [integral_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : discrete_valuation_ring R := begin rw iff_pid_with_one_nonzero_prime, haveI PID : is_principal_ideal_ring R := aux_pid_of_ufd_of_unique_irreducible R h₁ h₂, obtain ⟨p, hp⟩ := h₁, refine ⟨PID, ⟨ideal.span {p}, ⟨_, _⟩, _⟩⟩, { rw submodule.ne_bot_iff, refine ⟨p, ideal.mem_span_singleton.mpr (dvd_refl p), hp.ne_zero⟩, }, { rwa [ideal.span_singleton_prime hp.ne_zero, ← unique_factorization_monoid.irreducible_iff_prime], }, { intro I, rw ← submodule.is_principal.span_singleton_generator I, rintro ⟨I0, hI⟩, apply span_singleton_eq_span_singleton.mpr, apply h₂ _ hp, erw [ne.def, span_singleton_eq_bot] at I0, rwa [unique_factorization_monoid.irreducible_iff_prime, ← ideal.span_singleton_prime I0], }, end /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a discrete valuation ring. -/ lemma of_has_unit_mul_pow_irreducible_factorization {R : Type u} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) : discrete_valuation_ring R := begin letI : unique_factorization_monoid R := hR.to_unique_factorization_monoid, apply of_ufd_of_unique_irreducible _ hR.unique_irreducible, unfreezingI { obtain ⟨p, hp, H⟩ := hR, exact ⟨p, hp⟩, }, end section variables [integral_domain R] [discrete_valuation_ring R] variable {R} lemma associated_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ), associated x (ϖ ^ n) := begin have : wf_dvd_monoid R := is_noetherian_ring.wf_dvd_monoid, cases wf_dvd_monoid.exists_factors x hx with fx hfx, unfreezingI { use fx.card }, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ _ _ rfl, rw associates.mk_eq_mk_iff_associated, refine associated_of_irreducible _ _ hirr, apply hfx.1, assumption end lemma eq_unit_mul_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ) (u : units R), x = u * ϖ ^ n := begin obtain ⟨n, hn⟩ := associated_pow_irreducible hx hirr, obtain ⟨u, rfl⟩ := hn.symm, use [n, u], apply mul_comm, end open submodule.is_principal lemma ideal_eq_span_pow_irreducible {s : ideal R} (hs : s ≠ ⊥) {ϖ : R} (hirr : irreducible ϖ) : ∃ n : ℕ, s = ideal.span {ϖ ^ n} := begin have gen_ne_zero : generator s ≠ 0, { rw [ne.def, ← eq_bot_iff_generator_eq_zero], assumption }, rcases associated_pow_irreducible gen_ne_zero hirr with ⟨n, u, hnu⟩, use n, have : span _ = _ := span_singleton_generator s, rw [← this, ← hnu, span_singleton_eq_span_singleton], use u end lemma unit_mul_pow_congr_pow {p q : R} (hp : irreducible p) (hq : irreducible q) (u v : units R) (m n : ℕ) (h : ↑u * p ^ m = v * q ^ n) : m = n := begin have key : associated (multiset.repeat p m).prod (multiset.repeat q n).prod, { rw [multiset.prod_repeat, multiset.prod_repeat, associated], refine ⟨u * v⁻¹, _⟩, simp only [units.coe_mul], rw [mul_left_comm, ← mul_assoc, h, mul_right_comm, units.mul_inv, one_mul], }, have := multiset.card_eq_card_of_rel (unique_factorization_monoid.factors_unique _ _ key), { simpa only [multiset.card_repeat] }, all_goals { intros x hx, replace hx := multiset.eq_of_mem_repeat hx, unfreezingI { subst hx, assumption } }, end lemma unit_mul_pow_congr_unit {ϖ : R} (hirr : irreducible ϖ) (u v : units R) (m n : ℕ) (h : ↑u * ϖ ^ m = v * ϖ ^ n) : u = v := begin obtain rfl : m = n := unit_mul_pow_congr_pow hirr hirr u v m n h, rw ← sub_eq_zero at h, rw [← sub_mul, mul_eq_zero] at h, cases h, { rw sub_eq_zero at h, exact_mod_cast h }, { apply (hirr.ne_zero (pow_eq_zero h)).elim, } end /-! ## The additive valuation on a DVR -/ /-- The `ℕ`-valued additive valuation on a DVR (returns junk at `0` rather than `+∞`) -/ noncomputable def add_val (R : Type u) [integral_domain R] [discrete_valuation_ring R] : R → ℕ := λ r, if hr : r = 0 then 0 else classical.some (associated_pow_irreducible hr (classical.some_spec $ exists_irreducible R)) theorem add_val_spec {r : R} (hr : r ≠ 0) : let ϖ := classical.some (exists_irreducible R) in let n := classical.some (associated_pow_irreducible hr (classical.some_spec (exists_irreducible R))) in associated r (ϖ ^ n) := classical.some_spec (associated_pow_irreducible hr (classical.some_spec $ exists_irreducible R)) lemma add_val_def (r : R) (u : units R) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) (hr : r = u * ϖ ^ n) : add_val R r = n := begin subst hr, let ϖ₀ := classical.some (exists_irreducible R), have hϖ₀ : irreducible ϖ₀ := classical.some_spec (exists_irreducible R), have h0 : (u : R) * ϖ ^ n ≠ 0, { simp only [units.mul_right_eq_zero, ne.def, pow_ne_zero n hϖ.ne_zero, not_false_iff] }, unfold add_val, rw dif_neg h0, obtain ⟨v, hv⟩ := (add_val_spec h0).symm, rw mul_comm at hv, refine unit_mul_pow_congr_pow hϖ₀ hϖ _ u _ _ hv, end lemma add_val_def' (u : units R) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) : add_val R ((u : R) * ϖ ^ n) = n := add_val_def _ u hϖ n rfl @[simp] lemma add_val_zero : add_val R 0 = 0 := dif_pos rfl @[simp] lemma add_val_one : add_val R 1 = 0 := add_val_def 1 1 (classical.some_spec $ exists_irreducible R) 0 (by simp) @[simp] lemma add_val_uniformizer {ϖ : R} (hϖ : irreducible ϖ) : add_val R ϖ = 1 := add_val_def ϖ 1 hϖ 1 (by simp) @[simp] lemma add_val_mul {a b : R} (ha : a ≠ 0) (hb : b ≠ 0) : add_val R (a * b) = add_val R a + add_val R b := begin obtain ⟨ϖ, hϖ⟩ := exists_irreducible R, obtain ⟨m, u, rfl⟩ := eq_unit_mul_pow_irreducible ha hϖ, obtain ⟨n, v, rfl⟩ := eq_unit_mul_pow_irreducible hb hϖ, rw mul_mul_mul_comm, simp only [hϖ, add_val_def', ← pow_add, ← units.coe_mul], end lemma add_val_pow (a : R) (n : ℕ) : add_val R (a ^ n) = n * add_val R a := begin by_cases ha : a = 0, { cases nat.eq_zero_or_pos n with hn hn, { simp [ha, hn] }, { simp [ha, zero_pow hn] } }, induction n with d hd, { simp [ha] }, { rw [pow_succ, add_val_mul ha (pow_ne_zero _ ha), hd], ring} end lemma add_val_le_iff_dvd {a b : R} (ha : a ≠ 0) (hb : b ≠ 0) : add_val R a ≤ add_val R b ↔ a ∣ b := begin split, { obtain ⟨ϖ, hϖ⟩ := exists_irreducible R, obtain ⟨m, u, rfl⟩ := eq_unit_mul_pow_irreducible ha hϖ, obtain ⟨n, v, rfl⟩ := eq_unit_mul_pow_irreducible hb hϖ, rw [add_val_def' _ hϖ, add_val_def' _ hϖ, le_iff_exists_add], rintro ⟨q, rfl⟩, use ((v * u⁻¹ : units R) : R) * ϖ ^ q, rw [mul_mul_mul_comm, pow_add, units.coe_mul, mul_left_comm ↑u, units.mul_inv, mul_one] }, { rintro ⟨c, rfl⟩, rw add_val_mul ha (right_ne_zero_of_mul hb), simp only [zero_le, le_add_iff_nonneg_right] } end lemma add_val_add {a b : R} (ha : a ≠ 0) (hb : b ≠ 0) (hab : a + b ≠ 0) : min (add_val R a) (add_val R b) ≤ add_val R (a + b) := begin -- wlog is slow but I'm grateful it works. wlog h : add_val R a ≤ add_val R b := le_total (add_val R a) (add_val R b) using [a b, b a], rw [min_eq_left h, add_val_le_iff_dvd ha hab], rw add_val_le_iff_dvd ha hb at h, exact dvd_add_self_left.mpr h, end end end discrete_valuation_ring
ef4ff6e4bcdc4447c5b884f46cd91b2b1f540cc9
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/337.lean
dbf16d131a7922c5d354b2e5d542f175a9ecb8a0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,472
lean
section variable (G : Type 1) (T : Type 1) (EG : G → G → Type) (getCtx : T → G) inductive CtxSyntaxLayer where inductive TySyntaxLayer where | arrow : {Γ : G} → (A B : T) → EG Γ (getCtx A) → EG Γ (getCtx B) → TySyntaxLayer end section variable (G : Type 1) (T : Type 1) (Tm : Type 1) (EG : G → G → Type) (ET : T → T → Type) (getCtx : T → G) (getTy : Tm → T) (TAlgebra : TySyntaxLayer G T EG getCtx → T) inductive TmSyntaxLayer where | app : {Γ : G} → (A B : T) → (Actx : EG Γ (getCtx A)) → (Bctx : EG Γ (getCtx B)) → (f x : Tm) → ET (getTy f) (TAlgebra (TySyntaxLayer.arrow A B Actx Bctx)) → ET (getTy x) A → TmSyntaxLayer end structure Ty where ctx : Type ty : ctx → Type structure Tm where ty : Ty tm : ∀ {Γ}, ty.ty Γ def ECtx : Type → Type → Type := (PLift $ · = ·) def ETy : Ty → Ty → Type := (PLift $ · = ·) def ETm : Tm → Tm → Type := (PLift $ · = ·) def interpTyStep : TySyntaxLayer Type Ty ECtx Ty.ctx → Ty | TySyntaxLayer.arrow (Γ:=Γ) A B (PLift.up Actx) (PLift.up Bctx) => Ty.mk Γ (λ γ => A.ty (cast Actx γ) → B.ty (cast Bctx γ)) def interpTmStep : TmSyntaxLayer Type Ty Tm ECtx ETy Ty.ctx Tm.ty interpTyStep → Tm | TmSyntaxLayer.app (Γ:=Γ1) A B (PLift.up Actx) (PLift.up Bctx) { ty := fty , tm := ftm } x (PLift.up fTy) (PLift.up xTy) => sorry
0d28eab735e3a84fc2bc4fc6becf6f1a1c4b22b8
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/data/rbtree/basic.lean
8d62d804ba54abc24bb0326e4fcc58ca0a7b4669
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
6,872
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.ordering universes u v inductive rbnode (α : Type u) | leaf : rbnode | red_node (lchild : rbnode) (val : α) (rchild : rbnode) : rbnode | black_node (lchild : rbnode) (val : α) (rchild : rbnode) : rbnode namespace rbnode variables {α : Type u} {β : Type v} inductive color | red | black open color nat instance color.decidable_eq : decidable_eq color := λ a b, color.cases_on a (color.cases_on b (is_true rfl) (is_false (λ h, color.no_confusion h))) (color.cases_on b (is_false (λ h, color.no_confusion h)) (is_true rfl)) def depth (f : nat → nat → nat) : rbnode α → nat | leaf := 0 | (red_node l _ r) := succ (f (depth l) (depth r)) | (black_node l _ r) := succ (f (depth l) (depth r)) protected def min : rbnode α → option α | leaf := none | (red_node leaf v _) := some v | (black_node leaf v _) := some v | (red_node l v _) := min l | (black_node l v _) := min l protected def max : rbnode α → option α | leaf := none | (red_node _ v leaf) := some v | (black_node _ v leaf) := some v | (red_node _ v r) := max r | (black_node _ v r) := max r def fold (f : α → β → β) : rbnode α → β → β | leaf b := b | (red_node l v r) b := fold r (f v (fold l b)) | (black_node l v r) b := fold r (f v (fold l b)) def rev_fold (f : α → β → β) : rbnode α → β → β | leaf b := b | (red_node l v r) b := rev_fold l (f v (rev_fold r b)) | (black_node l v r) b := rev_fold l (f v (rev_fold r b)) def balance1 : rbnode α → α → rbnode α → α → rbnode α → rbnode α | (red_node l x r₁) y r₂ v t := red_node (black_node l x r₁) y (black_node r₂ v t) | l₁ y (red_node l₂ x r) v t := red_node (black_node l₁ y l₂) x (black_node r v t) | l y r v t := black_node (red_node l y r) v t def balance1_node : rbnode α → α → rbnode α → rbnode α | (red_node l x r) v t := balance1 l x r v t | (black_node l x r) v t := balance1 l x r v t | leaf v t := t /- dummy value -/ def balance2 : rbnode α → α → rbnode α → α → rbnode α → rbnode α | (red_node l x₁ r₁) y r₂ v t := red_node (black_node t v l) x₁ (black_node r₁ y r₂) | l₁ y (red_node l₂ x₂ r₂) v t := red_node (black_node t v l₁) y (black_node l₂ x₂ r₂) | l y r v t := black_node t v (red_node l y r) def balance2_node : rbnode α → α → rbnode α → rbnode α | (red_node l x r) v t := balance2 l x r v t | (black_node l x r) v t := balance2 l x r v t | leaf v t := t /- dummy -/ def get_color : rbnode α → color | (red_node _ _ _) := red | _ := black section insert variables (lt : α → α → Prop) [decidable_rel lt] def ins : rbnode α → α → rbnode α | leaf x := red_node leaf x leaf | (red_node a y b) x := match cmp_using lt x y with | ordering.lt := red_node (ins a x) y b | ordering.eq := red_node a x b | ordering.gt := red_node a y (ins b x) end | (black_node a y b) x := match cmp_using lt x y with | ordering.lt := if a.get_color = red then balance1_node (ins a x) y b else black_node (ins a x) y b | ordering.eq := black_node a x b | ordering.gt := if b.get_color = red then balance2_node (ins b x) y a else black_node a y (ins b x) end def mk_insert_result : color → rbnode α → rbnode α | red (red_node l v r) := black_node l v r | _ t := t def insert (t : rbnode α) (x : α) : rbnode α := mk_insert_result (get_color t) (ins lt t x) end insert section membership variable (lt : α → α → Prop) def mem : α → rbnode α → Prop | a leaf := false | a (red_node l v r) := mem a l ∨ (¬ lt a v ∧ ¬ lt v a) ∨ mem a r | a (black_node l v r) := mem a l ∨ (¬ lt a v ∧ ¬ lt v a) ∨ mem a r def mem_exact : α → rbnode α → Prop | a leaf := false | a (red_node l v r) := mem_exact a l ∨ a = v ∨ mem_exact a r | a (black_node l v r) := mem_exact a l ∨ a = v ∨ mem_exact a r variable [decidable_rel lt] def find : rbnode α → α → option α | leaf x := none | (red_node a y b) x := match cmp_using lt x y with | ordering.lt := find a x | ordering.eq := some y | ordering.gt := find b x end | (black_node a y b) x := match cmp_using lt x y with | ordering.lt := find a x | ordering.eq := some y | ordering.gt := find b x end end membership inductive well_formed (lt : α → α → Prop) : rbnode α → Prop | leaf_wff : well_formed leaf | insert_wff {n n' : rbnode α} {x : α} [decidable_rel lt] : well_formed n → n' = insert lt n x → well_formed n' end rbnode open rbnode set_option auto_param.check_exists false def rbtree (α : Type u) (lt : α → α → Prop . rbtree.default_lt) : Type u := {t : rbnode α // t.well_formed lt } def mk_rbtree (α : Type u) (lt : α → α → Prop . rbtree.default_lt) : rbtree α lt := ⟨leaf, well_formed.leaf_wff⟩ namespace rbtree variables {α : Type u} {β : Type v} {lt : α → α → Prop} protected def mem (a : α) (t : rbtree α lt) : Prop := rbnode.mem lt a t.val instance : has_mem α (rbtree α lt) := ⟨rbtree.mem⟩ def mem_exact (a : α) (t : rbtree α lt) : Prop := rbnode.mem_exact a t.val def depth (f : nat → nat → nat) (t : rbtree α lt) : nat := t.val.depth f def fold (f : α → β → β) : rbtree α lt → β → β | ⟨t, _⟩ b := t.fold f b def rev_fold (f : α → β → β) : rbtree α lt → β → β | ⟨t, _⟩ b := t.rev_fold f b def empty : rbtree α lt → bool | ⟨leaf, _⟩ := tt | _ := ff def to_list : rbtree α lt → list α | ⟨t, _⟩ := t.rev_fold (::) [] protected def min : rbtree α lt → option α | ⟨t, _⟩ := t.min protected def max : rbtree α lt → option α | ⟨t, _⟩ := t.max instance [has_repr α] : has_repr (rbtree α lt) := ⟨λ t, "rbtree_of " ++ repr t.to_list⟩ variables [decidable_rel lt] def insert : rbtree α lt → α → rbtree α lt | ⟨t, w⟩ x := ⟨t.insert lt x, well_formed.insert_wff w rfl⟩ def find : rbtree α lt → α → option α | ⟨t, _⟩ x := t.find lt x def contains (t : rbtree α lt) (a : α) : bool := (t.find a).is_some def from_list (l : list α) (lt : α → α → Prop . rbtree.default_lt) [decidable_rel lt] : rbtree α lt := l.foldl insert (mk_rbtree α lt) end rbtree def rbtree_of {α : Type u} (l : list α) (lt : α → α → Prop . rbtree.default_lt) [decidable_rel lt] : rbtree α lt := rbtree.from_list l lt
8a97391462f3b17866bb4bb98d55bf5747cc5c66
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/pairing_auto.lean
e08c9bed7cf25262d3322b3f14f957bc674acf7b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,135
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro Elegant pairing function. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.sqrt import Mathlib.data.set.lattice import Mathlib.PostPort universes u_1 u_2 namespace Mathlib namespace nat /-- Pairing function for the natural numbers. -/ def mkpair (a : ℕ) (b : ℕ) : ℕ := ite (a < b) (b * b + a) (a * a + a + b) /-- Unpairing function for the natural numbers. -/ def unpair (n : ℕ) : ℕ × ℕ := let s : ℕ := sqrt n; ite (n - s * s < s) (n - s * s, s) (s, n - s * s - s) @[simp] theorem mkpair_unpair (n : ℕ) : mkpair (prod.fst (unpair n)) (prod.snd (unpair n)) = n := sorry theorem mkpair_unpair' {n : ℕ} {a : ℕ} {b : ℕ} (H : unpair n = (a, b)) : mkpair a b = n := sorry @[simp] theorem unpair_mkpair (a : ℕ) (b : ℕ) : unpair (mkpair a b) = (a, b) := sorry theorem unpair_lt {n : ℕ} (n1 : 1 ≤ n) : prod.fst (unpair n) < n := sorry theorem unpair_le_left (n : ℕ) : prod.fst (unpair n) ≤ n := nat.cases_on n (idRhs (prod.fst (unpair 0) ≤ 0) (of_as_true trivial)) fun (n : ℕ) => idRhs (prod.fst (unpair (n + 1)) ≤ n + 1) (le_of_lt (unpair_lt (succ_pos n))) theorem le_mkpair_left (a : ℕ) (b : ℕ) : a ≤ mkpair a b := sorry theorem le_mkpair_right (a : ℕ) (b : ℕ) : b ≤ mkpair a b := sorry theorem unpair_le_right (n : ℕ) : prod.snd (unpair n) ≤ n := sorry theorem mkpair_lt_mkpair_left {a₁ : ℕ} {a₂ : ℕ} (b : ℕ) (h : a₁ < a₂) : mkpair a₁ b < mkpair a₂ b := sorry theorem mkpair_lt_mkpair_right (a : ℕ) {b₁ : ℕ} {b₂ : ℕ} (h : b₁ < b₂) : mkpair a b₁ < mkpair a b₂ := sorry end nat namespace set theorem Union_unpair_prod {α : Type u_1} {β : Type u_2} {s : ℕ → set α} {t : ℕ → set β} : (Union fun (n : ℕ) => set.prod (s (prod.fst (nat.unpair n))) (t (prod.snd (nat.unpair n)))) = set.prod (Union fun (n : ℕ) => s n) (Union fun (n : ℕ) => t n) := sorry end Mathlib
0e84edc9302110d48b16ff87c67e5b613a460758
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/set_theory/ordinal.lean
3d15090b3d770bfc039663681c2ac9ee6fccdb74
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
117,113
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Ordinal arithmetic. Ordinals are defined as equivalences of well-ordered sets by order isomorphism. -/ import order.order_iso set_theory.cardinal data.sum noncomputable theory open function cardinal local attribute [instance] classical.prop_decidable universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ≼o s := (init : ∀ a b, s b (to_order_embedding a) → ∃ a', to_order_embedding a' = b) local infix ` ≼i `:50 := initial_seg namespace initial_seg instance : has_coe (r ≼i s) (r ≼o s) := ⟨initial_seg.to_order_embedding⟩ @[simp] theorem coe_fn_mk (f : r ≼o s) (o) : (@initial_seg.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_order_embedding (f : r ≼i s) : (f.to_order_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ≼o s) : α → β) = f := rfl theorem init' (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b := f.init _ _ theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r ≼o s).ord'.2 (e.symm ▸ h)⟩, λ ⟨a', e, h⟩, e ▸ (f : r ≼o s).ord'.1 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃o s) : r ≼i s := ⟨f, λ a b h, ⟨f.symm b, order_iso.apply_inverse_apply f _⟩⟩ @[refl] protected def refl (r : α → α → Prop) : r ≼i r := ⟨order_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩ @[trans] protected def trans : r ≼i s → s ≼i t → r ≼i t | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ := ⟨f₁.trans f₂, λ a c h, begin simp at h ⊢, rcases o₂ _ _ h with ⟨b, rfl⟩, have h := f₂.ord'.2 h, rcases o₁ _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem of_iso_apply (f : r ≃o s) (x : α) : of_iso f x = f x := rfl @[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply : ∀ (f : r ≼i s) (g : s ≼i t) (a : α), (f.trans g) a = g (f a) | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ a := order_embedding.trans_apply _ _ _ theorem unique_of_extensional [is_extensional β s] : well_founded r → subsingleton (r ≼i s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : α → β) = g, { cases f, cases g, congr, exact order_embedding.eq_of_to_fun_eq this }, funext a, have := h a, induction this with a H IH, refine @is_extensional.ext _ s _ _ _ (λ x, ⟨λ h, _, λ h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r ≼o s).ord'.1 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r ≼o s).ord'.1 h' } end⟩ instance [is_well_order β s] : subsingleton (r ≼i s) := ⟨λ a, @subsingleton.elim _ (unique_of_extensional (@order_embedding.well_founded _ _ r s a (is_well_order.wf s))) a⟩ protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f | x := begin have := ((is_well_order.wf r).apply x), induction this with x _ IH, refine @is_extensional.ext _ r _ _ _ (λ y, _), simp only [g.init_iff, f.init_iff], split; intro h, { rcases h with ⟨a, rfl, b, rfl, h⟩, rwa IH _ h }, { exact ⟨f y, IH _ h, y, rfl, h⟩ } end def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃o s := by haveI := f.to_order_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.ord⟩ @[simp] theorem antisymm_to_fun [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl @[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f := order_iso.eq_of_to_fun_eq $ by dunfold initial_seg.antisymm; simp theorem eq_or_principal [is_well_order β s] (f : r ≼i s) : surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x := or_iff_not_imp_right.2 $ λ h b, acc.rec_on ((is_well_order.wf s).apply b) $ λ x H IH, not_forall_not.1 $ λ hn, h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (λ hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p := ⟨order_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s := ⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, by simp⟩, λ a b, by cases b; simp; exact λ _, ⟨_, rfl⟩⟩ @[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ≼o s := (top : β) (down : ∀ b, s b top ↔ ∃ a, to_order_embedding a = b) local infix ` ≺i `:50 := principal_seg namespace principal_seg instance : has_coe (r ≺i s) (r ≼o s) := ⟨principal_seg.to_order_embedding⟩ @[simp] theorem coe_fn_mk (f : r ≼o s) (t o) : (@principal_seg.mk _ _ r s f t o : α → β) = f := rfl @[simp] theorem coe_fn_to_order_embedding (f : r ≺i s) : (f.to_order_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≺i s) : ((f : r ≼o s) : α → β) = f := rfl theorem down' (f : r ≺i s) {b : β} : s b f.top ↔ ∃ a, f a = b := f.down _ theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.down'.2 ⟨_, rfl⟩ theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b := f.down'.1 $ trans h $ f.lt_top _ instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) := ⟨λ f, ⟨f.to_order_embedding, λ a b, f.init⟩⟩ @[simp] theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := initial_seg.init_iff f theorem irrefl (r : α → α → Prop) [is_well_order α r] (f : r ≺i r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end def lt_le [is_trans β s] (f : r ≺i s) (g : s ≼i t) : r ≺i t := ⟨@order_embedding.trans _ _ _ r s t f g, g f.top, λ a, by simp [g.init_iff, f.down', exists_and_distrib_left.symm, -exists_and_distrib_left, exists_swap]; refl⟩ @[simp] theorem lt_le_apply [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) := order_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl @[trans] protected def trans [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t := lt_le f g @[simp] theorem trans_apply [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl def equiv_lt [is_trans β s] [is_trans γ t] (f : r ≃o s) (g : s ≺i t) : r ≺i t := ⟨@order_embedding.trans _ _ _ r s t f g, g.top, λ c, by simp [g.down']; exact ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp [h]⟩, λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩ @[simp] theorem equiv_lt_apply [is_trans β s] [is_trans γ t] (f : r ≃o s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) := by delta equiv_lt; simp @[simp] theorem equiv_lt_top [is_trans β s] [is_trans γ t] (f : r ≃o s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl instance [is_well_order β s] : subsingleton (r ≺i s) := ⟨λ f g, begin have ef : (f : α → β) = g, { show ((f : r ≼i s) : α → β) = g, rw @subsingleton.elim _ _ (f : r ≼i s) g, refl }, have et : f.top = g.top, { refine @is_extensional.ext _ s _ _ _ (λ x, _), simp [f.down, g.down, ef] }, cases f, cases g, simp at ef et, have := order_embedding.eq_of_to_fun_eq ef; congr' end⟩ theorem top_eq [is_well_order β s] [is_well_order γ t] (e : r ≃o s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); simp /-- Any element of a well order yields a principal segment -/ def of_element {α : Type*} (r : α → α → Prop) [is_well_order α r] (a : α) : subrel r {b | r b a} ≺i r := ⟨subrel.order_embedding _ _, a, λ b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) [is_well_order α r] (a : α) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) [is_well_order α r] (a : α) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set β) (f : r ≺i s) (H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p := ⟨order_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩, f.down'.trans $ exists_congr $ λ a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl end principal_seg def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) : r ≺i s ⊕ r ≃o s := if h : surjective f then sum.inr (order_iso.of_surjective f h) else have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ @[simp] theorem initial_seg.lt_or_eq_apply_left [is_well_order β s] (f : r ≼i s) {g} (h : f.lt_or_eq = sum.inl g) (a : α) : g a = f a := begin unfold initial_seg.lt_or_eq at h, by_cases sj : surjective f; simp [sj] at h, {cases h}, {subst h, refl} end @[simp] theorem initial_seg.lt_or_eq_apply_right [is_well_order β s] (f : r ≼i s) {g} (h : f.lt_or_eq = sum.inr g) (a : α) : g a = f a := begin unfold initial_seg.lt_or_eq at h, by_cases sj : surjective f; simp [sj] at h, {subst g, simp}, {cases h} end def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp [f.lt_or_eq_apply_left h] }, { simp [f.lt_or_eq_apply_right h] } end namespace order_embedding def collapse_F [is_well_order β s] (f : r ≼o s) : Π a, {b // ¬ s (f a) b} := (order_embedding.well_founded f $ is_well_order.wf s).fix $ λ a IH, begin let S := {b | ∀ a h, s (IH a h).1 b}, have : f a ∈ S, from λ a' h, ((trichotomous _ _) .resolve_left $ λ h', (IH a' h).2 $ trans (f.ord'.1 h) h') .resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.ord'.1 h, exact ⟨(is_well_order.wf s).min S (set.ne_empty_of_mem this), (is_well_order.wf s).not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order β s] (f : r ≼o s) {a : α} : ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order β s] (f : r ≼o s) (a : α) {b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding. -/ def collapse [is_well_order β s] (f : r ≼o s) : r ≼i s := by haveI := order_embedding.is_well_order f; exact ⟨order_embedding.of_monotone (λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f), λ a b, by revert a; dsimp; exact acc.rec_on ((is_well_order.wf s).apply b) (λ b H IH a h, begin let S := {a | ¬ s (collapse_F f a).1 b}, have : S ≠ ∅ := set.ne_empty_of_mem (asymm h), existsi (is_well_order.wf r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_order.wf r).min_mem S this }, { refine collapse_F.not_lt f _ (λ a' h', _), by_contradiction hn, exact (is_well_order.wf r).not_lt_min S this hn h' } end)⟩ theorem collapse_apply [is_well_order β s] (f : r ≼o s) (a) : collapse f a = (collapse_F f a).1 := rfl end order_embedding section well_ordering_thm parameter {σ : Type*} private def partial_wo := Σ p : set σ, {r // is_well_order p r} private def partial_wo.le (x y : partial_wo) := ∃ f : x.2.1 ≼i y.2.1, ∀ x, (f x).1 = x.1 local infix ` ≤ `:50 := partial_wo.le private def partial_wo.is_refl : is_refl _ (≤) := ⟨λ a, ⟨initial_seg.refl _, λ x, rfl⟩⟩ local attribute [instance] partial_wo.is_refl private def partial_wo.trans {a b c} : a ≤ b → b ≤ c → a ≤ c | ⟨f, hf⟩ ⟨g, hg⟩ := ⟨f.trans g, λ a, by simp [hf, hg]⟩ private def sub_of_le {s t} : s ≤ t → s.1 ⊆ t.1 | ⟨f, hf⟩ x h := by have := (f ⟨x, h⟩).2; rwa [hf ⟨x, h⟩] at this private def agree_of_le {s t} : s ≤ t → ∀ {a b} sa sb ta tb, s.2.1 ⟨a, sa⟩ ⟨b, sb⟩ ↔ t.2.1 ⟨a, ta⟩ ⟨b, tb⟩ | ⟨f, hf⟩ a b sa sb ta tb := by rw [f.to_order_embedding.ord', show f.to_order_embedding ⟨a, sa⟩ = ⟨a, ta⟩, from subtype.eq (hf ⟨a, sa⟩), show f.to_order_embedding ⟨b, sb⟩ = ⟨b, tb⟩, from subtype.eq (hf ⟨b, sb⟩)] section parameters {c : set partial_wo} (hc : zorn.chain (≤) c) private def U := ⋃₀ ((λ x:partial_wo, x.1) '' c) private def R (x y : U) := ∃ a : partial_wo, a ∈ c ∧ ∃ (hx : x.1 ∈ a.1) (hy : y.1 ∈ a.1), a.2.1 ⟨_, hx⟩ ⟨_, hy⟩ private lemma mem_U {a} : a ∈ U ↔ ∃ s : partial_wo, s ∈ c ∧ a ∈ s.1 := by unfold U; simp [-sigma.exists] private lemma mem_U2 {a b} (au : a ∈ U) (bu : b ∈ U) : ∃ s : partial_wo, s ∈ c ∧ a ∈ s.1 ∧ b ∈ s.1 := let ⟨s, sc, as⟩ := mem_U.1 au, ⟨t, tc, bt⟩ := mem_U.1 bu, ⟨k, kc, ks, kt⟩ := hc.directed sc tc in ⟨k, kc, sub_of_le ks as, sub_of_le kt bt⟩ private lemma R_ex {s : partial_wo} (sc : s ∈ c) {a b : σ} (hb : b ∈ s.1) {au bu} : R ⟨a, au⟩ ⟨b, bu⟩ → ∃ ha, s.2.1 ⟨a, ha⟩ ⟨b, hb⟩ | ⟨t, tc, at', bt, h⟩ := match hc.total_of_refl sc tc with | or.inr hr := ⟨sub_of_le hr at', (agree_of_le hr _ _ _ _).1 h⟩ | or.inl hr@⟨f, hf⟩ := begin rw [← show (f ⟨b, hb⟩) = ⟨(subtype.mk b bu).val, bt⟩, from subtype.eq (hf _)] at h, rcases f.init_iff.1 h with ⟨⟨a', ha⟩, e, h'⟩, have : a' = a, { have := congr_arg subtype.val e, rwa hf at this }, subst a', exact ⟨_, h'⟩ end end private lemma R_iff {s : partial_wo} (sc : s ∈ c) {a b : σ} (ha hb) {au bu} : R ⟨a, au⟩ ⟨b, bu⟩ ↔ s.2.1 ⟨a, ha⟩ ⟨b, hb⟩ := ⟨λ h, let ⟨_, h⟩ := R_ex sc hb h in h, λ h, ⟨s, sc, ha, hb, h⟩⟩ private theorem wo : is_well_order U R := { trichotomous := λ ⟨a, au⟩ ⟨b, bu⟩, let ⟨s, sc, ha, hb⟩ := mem_U2 au bu in by haveI := s.2.2; exact (@trichotomous _ s.2.1 _ ⟨a, ha⟩ ⟨b, hb⟩).imp (R_iff hc sc _ _).2 (λ o, o.imp (λ h, by congr; injection h) (R_iff hc sc _ _).2), irrefl := λ ⟨a, au⟩ h, let ⟨s, sc, ha⟩ := mem_U.1 au in by haveI := s.2.2; exact irrefl _ ((R_iff hc sc _ ha).1 h), trans := λ ⟨a, au⟩ ⟨b, bu⟩ ⟨d, du⟩ ab bd, let ⟨s, sc, as, bs⟩ := mem_U2 au bu, ⟨t, tc, dt⟩ := mem_U.1 du, ⟨k, kc, ks, kt⟩ := hc.directed sc tc in begin simp only [R_iff hc kc, sub_of_le ks as, sub_of_le ks bs, sub_of_le kt dt] at ab bd ⊢, haveI := k.2.2, exact trans ab bd end, wf := ⟨λ ⟨a, au⟩, let ⟨s, sc, ha⟩ := mem_U.1 au in suffices ∀ (a : s.1) au, acc R ⟨a.1, au⟩, from this ⟨a, ha⟩ au, λ a, acc.rec_on ((@is_well_order.wf _ _ s.2.2).apply a) $ λ ⟨a, ha⟩ H IH au, ⟨_, λ ⟨b, hb⟩ h, let ⟨hb, h⟩ := R_ex sc ha h in IH ⟨b, hb⟩ h _⟩⟩ } theorem chain_ub : ∃ ub, ∀ a ∈ c, a ≤ ub := ⟨⟨U, R, wo⟩, λ s sc, ⟨⟨⟨⟨ λ a, ⟨a.1, mem_U.2 ⟨s, sc, a.2⟩⟩, λ a b h, by injection h with h; exact subtype.eq h⟩, λ a b, by cases a with a ha; cases b with b hb; exact (R_iff hc sc _ _).symm⟩, λ ⟨a, ha⟩ ⟨b, hb⟩ h, let ⟨bs, h'⟩ := R_ex sc ha h in ⟨⟨_, bs⟩, rfl⟩⟩, λ a, rfl⟩⟩ end theorem well_ordering_thm : ∃ r, is_well_order σ r := let ⟨m, MM⟩ := zorn.zorn (λ c, chain_ub) (λ a b c, partial_wo.trans) in by haveI := m.2.2; exact suffices hf : ∀ a, a ∈ m.1, from let f : σ ≃ m.1 := ⟨λ a, ⟨a, hf a⟩, λ a, a.1, λ a, rfl, λ ⟨a, ha⟩, rfl⟩ in ⟨order.preimage f m.2.1, @order_embedding.is_well_order _ _ _ _ ↑(order_iso.preimage f m.2.1) m.2.2⟩, λ a, classical.by_contradiction $ λ ha, let f : (insert a m.1 : set σ) ≃ (m.1 ⊕ unit) := ⟨λ x, if h : x.1 ∈ m.1 then sum.inl ⟨_, h⟩ else sum.inr ⟨⟩, λ x, sum.cases_on x (λ x, ⟨x.1, or.inr x.2⟩) (λ _, ⟨a, or.inl rfl⟩), λ x, match x with | ⟨_, or.inl rfl⟩ := by dsimp; rw [dif_neg ha] | ⟨x, or.inr h⟩ := by dsimp; rw [dif_pos h] end, λ x, by rcases x with ⟨x, h⟩ | ⟨⟨⟩⟩; dsimp; [rw [dif_pos h], rw [dif_neg ha]]⟩ in let r' := sum.lex m.2.1 (@empty_relation unit) in have r'wo : is_well_order _ r' := @sum.lex.is_well_order _ _ _ _ m.2.2 _, let m' : partial_wo := ⟨insert a m.1, order.preimage f r', @order_embedding.is_well_order _ _ _ _ ↑(order_iso.preimage f r') r'wo⟩ in let g : m.2.1 ≼i r' := ⟨⟨⟨sum.inl, λ a b, sum.inl.inj⟩, λ a b, by simp [r']⟩, λ a b h, begin rcases b with b | ⟨⟨⟩⟩; simp [r'] at h ⊢, { cases b, exact ⟨_, _, rfl⟩ }, { contradiction } end⟩ in ha (sub_of_le (MM m' ⟨g.trans (initial_seg.of_iso (order_iso.preimage f r').symm), λ x, rfl⟩) (or.inl rfl)) end well_ordering_thm structure Well_order : Type (u+1) := (α : Type u) (r : α → α → Prop) (wo : is_well_order α r) instance ordinal.is_equivalent : setoid Well_order := { r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃o s), iseqv := ⟨λ⟨α, r, _⟩, ⟨order_iso.refl _⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `ordinal.{u}` is the type of well orders in `Type u`, quotient by order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent namespace ordinal /-- The order type of a well order is an ordinal. -/ def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal := ⟦⟨α, r, wo⟩⟧ /-- The order type of an element inside a well order. -/ def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal := type (subrel r {b | r b a}) theorem type_def (r : α → α → Prop) [wo : is_well_order α r] : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl @[simp] theorem type_def' (r : α → α → Prop) [is_well_order α r] {wo} : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r = type s ↔ nonempty (r ≃o s) := quotient.eq @[elab_as_eliminator] theorem induction_on {C : ordinal → Prop} (o : ordinal) (H : ∀ α r [is_well_order α r], C (type r)) : C o := quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≤ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ protected def le (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, propext ⟨ λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩ instance : has_le ordinal := ⟨ordinal.le⟩ theorem type_le {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ def lt (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, by exactI propext ⟨ λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩ instance : has_lt ordinal := ⟨ordinal.lt⟩ @[simp] theorem type_lt {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r < type s ↔ nonempty (r ≺i s) := iff.rfl instance : partial_order ordinal := { le := (≤), lt := (<), le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl _⟩, λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩) (λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := λ x b, show x ≤ b → b ≤ x → x = b, from quotient.induction_on₂ x b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩, by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ } theorem typein_lt_type (r : α → α → Prop) [is_well_order α r] (a : α) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ @[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≺i s) : typein s f.top = type r := eq.symm $ quot.sound ⟨order_iso.of_surjective (order_embedding.cod_restrict _ f f.lt_top) (λ ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨order_iso.of_surjective (order_embedding.cod_restrict _ ((subrel.order_embedding _ _).trans f) (λ ⟨x, h⟩, by simpa using f.to_order_embedding.ord'.1 h)) (λ ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_order_embedding.ord'.2 h⟩, by simp⟩)⟩ @[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r] {a b : α} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, simpa [f', g'] }, rw ← this, exact f.top.2 end, λ h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : ∃ a, typein r a = o := induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, by simp⟩) h theorem typein_inj (r : α → α → Prop) [is_well_order α r] {a b} : typein r a = typein r b ↔ a = b := ⟨λ h, ((@trichotomous _ r _ a b) .resolve_left (λ hn, ne_of_lt ((typein_lt_typein r).2 hn) h)) .resolve_right (λ hn, ne_of_gt ((typein_lt_typein r).2 hn) h), congr_arg _⟩ /-- `enum r o h` is the `o`-th element of `α` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `α`. -/ def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α := quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $ λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (λ (H₂ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : ∀ {o e} (H : o < type r), @@eq.rec (λ (o : ordinal), o < type r → α) (λ (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this H₂).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice H₂)) end theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : s ≺i r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (order_iso.refl _) _ _ @[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α) {h : typein r a < type r} : enum r (typein r a) h = a := by simp [typein, enum_type (principal_seg.of_element r a)] @[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; simp theorem enum_lt {α β} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} [is_well_order α r] [is_well_order β s] [is_well_order γ t] (h₁ : type s < type r) (h₂ : type t < type r) : r (enum r (type s) h₁) (enum r (type t) h₂) ↔ type s < type t := by rw [← typein_lt_typein r, typein_enum, typein_enum] theorem wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ λ α r wo, by exactI suffices ∀ a, acc (<) (typein r a), from ⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩, λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), wf⟩ /-- The cardinal of an ordinal is the cardinal of any set with that order type. -/ def card (o : ordinal) : cardinal := quot.lift_on o (λ ⟨α, r, _⟩, mk α) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩ @[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] : card (type r) = mk α := rfl theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ instance : has_zero ordinal := ⟨⟦⟨ulift empty, empty_relation, by apply_instance⟩⟧⟩ theorem zero_eq_type_empty : 0 = @type empty empty_relation _ := quotient.sound ⟨⟨equiv.ulift, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_zero : card 0 = 0 := rfl theorem zero_le (o : ordinal) : 0 ≤ o := induction_on o $ λ α r _, ⟨⟨⟨embedding.of_not_nonempty $ λ ⟨⟨a⟩⟩, a.elim, λ ⟨a⟩, a.elim⟩, λ ⟨a⟩, a.elim⟩⟩ @[simp] theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] instance : has_one ordinal := ⟨⟦⟨ulift unit, empty_relation, by apply_instance⟩⟧⟩ theorem one_eq_type_unit : 1 = @type unit empty_relation _ := quotient.sound ⟨⟨equiv.ulift, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_one : card 1 = 1 := rfl instance : has_add ordinal.{u} := ⟨λo₁ o₂, quotient.lift_on₂ o₁ o₂ (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α ⊕ β, sum.lex r s, by exactI sum.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨order_iso.sum_lex_congr f g⟩⟩ @[simp] theorem type_add {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r + type s = type (sum.lex r s) := rfl /-- The ordinal successor is the smallest ordinal larger than `o`. It is defined as `o + 1`. -/ def succ (o : ordinal) : ordinal := o + 1 theorem succ_eq_add_one (o) : succ o = o + 1 := rfl theorem lt_succ_self (o : ordinal.{u}) : o < succ o := induction_on o $ λ α r _, ⟨begin resetI, cases e : initial_seg.lt_or_eq (@initial_seg.le_add α (ulift.{u 0} unit) r empty_relation) with f f, { exact f }, { have := (initial_seg.of_iso f).eq (initial_seg.le_add _ _) (f.symm (sum.inr ⟨()⟩)), simp at this, cases this } end⟩ theorem succ_pos (o : ordinal) : 0 < succ o := lt_of_le_of_lt (zero_le _) (lt_succ_self _) theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 := ne_of_gt $ succ_pos o theorem succ_le {a b : ordinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), induction_on a $ λ α r _, induction_on b $ λ β s _ ⟨⟨f, t, hf⟩⟩, begin resetI, refine ⟨⟨order_embedding.of_monotone (sum.rec _ _) (λ a b, _), λ a b, _⟩⟩, { exact f }, { exact λ _, t }, { rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { simpa using f.ord'.1 }, { simpa using (hf _).2 ⟨_, rfl⟩ }, { simp }, { simpa using false.elim } }, { rcases a with a|⟨⟨⟨⟩⟩⟩, { intro h, have := principal_seg.init ⟨f, t, hf⟩ h, simp at this, simp [this] }, { simp [(hf _).symm] {contextual := tt} } } end⟩ @[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl @[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 := by simp [succ] @[simp] theorem card_nat (n : ℕ) : card.{u} n = n := by induction n; simp * theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl instance : add_monoid ordinal.{u} := { add := (+), zero := 0, zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quot.sound ⟨⟨(equiv.symm $ (equiv.ulift.sum_congr (equiv.refl _)).trans (equiv.empty_sum _)), λ a b, show r a b ↔ sum.lex _ _ (sum.inr a) (sum.inr b), by simp⟩⟩, add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quot.sound ⟨⟨(equiv.symm $ ((equiv.refl _).sum_congr equiv.ulift).trans (equiv.sum_empty _)), λ a b, show r a b ↔ sum.lex _ _ (sum.inl a) (sum.inl b), by simp⟩⟩, add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨equiv.sum_assoc _ _ _, λ a b, by rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp⟩⟩ } theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) := (add_assoc _ _ _).symm @[simp] theorem succ_zero : succ 0 = 1 := zero_add _ theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem add_le_add_left {a b : ordinal} : a ≤ b → ∀ c, c + a ≤ c + b := induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s _, ⟨⟨⟨(embedding.refl _).sum_congr f, λ a b, by cases a with a a; cases b with b b; simp [fo]⟩, λ a b, begin cases b with b b, { simp [(⟨_, rfl⟩ : ∃ a, a=b)] }, cases a with a a; simp, exact fi _ _, end⟩⟩ theorem le_add_right (a b : ordinal) : a ≤ a + b := by simpa using add_le_add_left (zero_le b) a theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c := ⟨induction_on a $ λ α r _, induction_on b $ λ β₁ s₁ _, induction_on c $ λ β₂ s₂ _ ⟨f⟩, ⟨ by exactI have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a, by simpa using initial_seg.eq ((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a, have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin intro b, cases e : f (sum.inr b), { rw ← fl at e, have := f.inj e, contradiction }, { exact ⟨_, rfl⟩ } end, let g (b) := (this b).1 in have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2, ⟨⟨⟨g, λ x y h, by injection f.inj (by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩, λ a b, by simpa [fr] using @order_embedding.ord _ _ _ _ f.to_order_embedding (sum.inr a) (sum.inr b)⟩, λ a b, begin have nex : ¬ ∃ (a : α), f (sum.inl a) = sum.inr b := λ ⟨a, e⟩, by rw [fl] at e; injection e, simpa [fr, nex] using f.init (sum.inr a) (sum.inr b), end⟩⟩, λ h, add_le_add_left h _⟩ theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c := by simp [le_antisymm_iff, add_le_add_iff_left] /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. -/ def lift (o : ordinal.{u}) : ordinal.{max u v} := quotient.lift_on o (λ ⟨α, r, wo⟩, @type _ _ (@order_embedding.is_well_order _ _ (@equiv.ulift.{u v} α ⁻¹'o r) r (order_iso.preimage equiv.ulift.{u v} r) wo)) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(order_iso.preimage equiv.ulift r).trans $ f.trans (order_iso.preimage equiv.ulift s).symm⟩ theorem lift_type {α} (r : α → α → Prop) [is_well_order α r] : ∃ wo', lift (type r) = @type _ (@equiv.ulift.{u v} α ⁻¹'o r) wo' := ⟨_, rfl⟩ theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, induction_on a $ λ α r _, quotient.sound ⟨(order_iso.preimage equiv.ulift r).trans (order_iso.preimage equiv.ulift r).symm⟩ theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ λ α r _, quotient.sound ⟨order_iso.preimage equiv.ulift r⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : ordinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := induction_on a $ λ α r _, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans $ (order_iso.preimage equiv.ulift _).trans (order_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) ≤ lift.{v (max u w)} (type s) ↔ nonempty (r ≼i s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (order_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (order_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(initial_seg.of_iso (order_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (order_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) = lift.{v (max u w)} (type s) ↔ nonempty (r ≃o s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(order_iso.preimage equiv.ulift r).symm.trans $ f.trans (order_iso.preimage equiv.ulift s)⟩, λ ⟨f⟩, ⟨(order_iso.preimage equiv.ulift r).trans $ f.trans (order_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) < lift.{v (max u w)} (type s) ↔ nonempty (r ≺i s) := by haveI := @order_embedding.is_well_order _ _ (@equiv.ulift.{u (max v w)} α ⁻¹'o r) r (order_iso.preimage equiv.ulift.{u (max v w)} r) _; haveI := @order_embedding.is_well_order _ _ (@equiv.ulift.{v (max u w)} β ⁻¹'o s) s (order_iso.preimage equiv.ulift.{v (max u w)} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (order_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (order_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(f.equiv_lt (order_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (order_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b := induction_on a $ λ α r _, induction_on b $ λ β s _, by rw ← lift_umax; exactI lift_type_le @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans ⟨equiv.ulift.trans equiv.ulift.symm, λ a b, iff.rfl⟩⟩ theorem zero_eq_lift_type_empty : 0 = lift.{0 u} (@type empty empty_relation _) := by rw [← zero_eq_type_empty, lift_zero] @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans ⟨equiv.ulift.trans equiv.ulift.symm, λ a b, iff.rfl⟩⟩ theorem one_eq_lift_type_unit : 1 = lift.{0 u} (@type unit empty_relation _) := by rw [← one_eq_type_unit, lift_one] @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans (order_iso.sum_lex_congr (order_iso.preimage equiv.ulift _) (order_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := by unfold succ; simp @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ λ α r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≤ a.lift) : ∃ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in quotient.induction_on c (λ α, induction_on b $ λ β s _ e', begin resetI, dsimp at e', rw [← cardinal.lift_id'.{(max u v) u} (mk β), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := order_iso.preimage f s, haveI := g.to_order_embedding.is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≤ lift a) : ∃ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ /-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/ def omega : ordinal.{u} := lift $ @type ℕ (<) _ theorem card_omega : card omega = cardinal.omega := rfl @[simp] theorem lift_omega : lift omega = omega := lift_lift _ theorem type_le' {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼o s) := ⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩ theorem add_le_add_right {a b : ordinal} : a ≤ b → ∀ c, a + c ≤ b + c := induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s _, by exactI type_le'.2 ⟨⟨embedding.sum_congr f (embedding.refl _), λ a b, by cases a with a a; cases b with b b; simp [fo]⟩⟩ theorem le_add_left (a b : ordinal) : a ≤ b + a := by simpa using add_le_add_right (zero_le b) a theorem le_total (a b : ordinal) : a ≤ b ∨ b ≤ a := match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h; simp [h], end) h₁ h₂ end instance : decidable_linear_order ordinal := { le_total := le_total, decidable_le := classical.dec_rel _, ..ordinal.partial_order } theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c := by rw [← not_le, ← not_le, add_le_add_iff_left] theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c := le_imp_le_iff_lt_imp_lt.1 (λ h, add_le_add_right h _) @[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b := by rw [lt_succ, succ_le] @[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 succ_lt_succ theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b := by simp [le_antisymm_iff] theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b := by induction n; simp [*, -nat.cast_succ, (nat_cast_succ _).symm, add_succ, succ_inj] theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b := by simp [le_antisymm_iff, add_le_add_iff_right] @[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ h, begin refine le_antisymm (le_of_not_lt $ λ hn, ne_zero_iff_nonempty.2 _ h) (zero_le _), rw [← succ_le, succ_zero] at hn, cases hn with f, exact ⟨f ⟨()⟩⟩ end, λ e, by simp [e]⟩ @[simp] theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α := (not_congr (@card_eq_zero (type r))).symm.trans ne_zero_iff_nonempty @[simp] theorem type_eq_zero_iff_empty [is_well_order α r] : type r = 0 ↔ ¬ nonempty α := (not_iff_comm.1 type_ne_zero_iff_nonempty).symm instance : zero_ne_one_class ordinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ type_ne_zero_iff_nonempty.2 ⟨⟨()⟩⟩ } theorem zero_lt_one : (0 : ordinal) < 1 := by simp [lt_iff_le_and_ne, zero_le] /-- The ordinal predecessor of `o` is `o'` if `o = succ o'`, and `o` otherwise. -/ def pred (o : ordinal.{u}) : ordinal.{u} := if h : ∃ a, o = succ a then classical.some h else o @[simp] theorem pred_succ (o) : pred (succ o) = o := by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩; simpa [pred, h] using (succ_inj.1 $ classical.some_spec h).symm theorem pred_le_self (o) : pred o ≤ o := if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _) else by simp [pred, h] theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a := ⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e, λ h, dif_neg h⟩ theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a := iff.trans (by simp [le_antisymm_iff, pred_le_self]) (iff_not_comm.1 pred_eq_iff_not_succ).symm theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a := ⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp [e]⟩ theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o := ⟨lt_trans (lt_succ_self _), λ l, lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩ theorem lt_pred {a b} : a < pred b ↔ succ a < b := if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in by rw [e, pred_succ, succ_lt_succ] else by simpa [pred, h, succ_lt_of_not_succ] theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b := le_iff_le_iff_lt_iff_lt.2 lt_pred @[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) := ⟨λ ⟨a, h⟩, let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $ h.symm ▸ lt_succ_self _ in ⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩, λ ⟨a, h⟩, ⟨lift a, by simp [h]⟩⟩ @[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) := if h : ∃ a, o = succ a then by cases h with a e; simp [e] else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)] /-- A limit ordinal is an ordinal which is not zero and not a successor. -/ def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o theorem not_zero_is_limit : ¬ is_limit 0 | ⟨h, _⟩ := h rfl theorem not_succ_is_limit (o) : ¬ is_limit (succ o) | ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _)) theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a | ⟨a, e⟩ := not_succ_is_limit a (e ▸ h) theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o := ⟨lt_trans (lt_succ_self _), h.2 _⟩ theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a := le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a := ⟨λ h x l, le_trans (le_of_lt l) h, λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn, not_lt_of_le (H _ hn) (lt_succ_self _)⟩ theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x := by simpa [not_ball] using not_congr (@limit_le _ h a) @[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o := and_congr (not_congr $ by simpa using @lift_inj o 0) ⟨λ H a h, lift_lt.1 $ by simpa using H _ (lift_lt.2 h), λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in by rw [← e, ← lift_succ, lift_lt]; rw [← e, lift_lt] at h; exact H a' h⟩ theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o := lt_of_le_of_ne (zero_le _) h.1.symm theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o := by simpa using h.2 _ h.pos theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := h.pos | (n+1) := h.2 _ (is_limit.nat_lt n) theorem zero_or_succ_or_limit (o : ordinal) : o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o := if o0 : o = 0 then or.inl o0 else if h : ∃ a, o = succ a then or.inr (or.inl h) else or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ instance : is_well_order ordinal (<) := ⟨wf⟩ @[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*} (o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o)) (H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o := wf.fix (λ o IH, if o0 : o = 0 then by rw o0; exact H₁ else if h : ∃ a, o = succ a then by rw ← succ_pred_iff_is_succ.2 h; exact H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h) else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o @[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ := by rw [limit_rec_on, well_founded.fix_eq]; simp; refl set_option pp.proofs true @[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) : @limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) := begin have h : ∃ a, succ o = succ a := ⟨_, rfl⟩, rw [limit_rec_on, well_founded.fix_eq, dif_neg (succ_ne_zero o), dif_pos h], generalize : limit_rec_on._proof_2 (succ o) h = h₂, generalize : limit_rec_on._proof_3 (succ o) h = h₃, revert h₂ h₃, generalize e : pred (succ o) = o', intros, rw pred_succ at e, subst o', refl end @[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) : @limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) := by rw [limit_rec_on, well_founded.fix_eq, dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl /-- A normal ordinal function is a strictly increasing function which is order-continuous. -/ def is_normal (f : ordinal → ordinal) : Prop := (∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o → ∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2 theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} : a < f o ↔ ∃ b < o, a < f b := not_iff_not.1 $ by simpa using H.2 _ h a theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b := lt_iff_lt_of_strict_mono f $ λ a b, limit_rec_on b (not.elim (not_lt_of_le $ zero_le _)) (λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim (λ h, lt_trans (IH h) (H.1 _)) (λ e, e ▸ H.1 _)) (λ b l IH h, lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 (le_refl _) _ (l.2 _ h))) theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_iff theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b := by simp [le_antisymm_iff, H.le_iff] theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a := limit_rec_on a (zero_le _) (λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _)) (λ a l IH, (limit_le l).2 $ λ b h, le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h) theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop) (p0 : ∃ x, p x) (S) (H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} : f S ≤ o ↔ ∀ a, p a → f a ≤ o := ⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h, λ h, begin revert H₂, apply limit_rec_on S, { intro H₂, cases p0 with x px, have := le_zero.1 ((H₂ _).1 (zero_le _) _ px), rw this at px, exact h _ px }, { intros S _ H₂, rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩, exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) }, { intros S L _ H₂, apply (H.2 _ L _).2, intros a h', rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩, exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) } end⟩ theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal) (p0 : ∃ x, p x) (S) (H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} : f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o := (H.le_set (λ x, ∃ y, p y ∧ x = g y) (let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _ (λ o, (H₂ o).trans $ by repeat {simp <|> refine (forall_congr (λ _, _)).trans forall_swap})).trans (by repeat {simp <|> refine forall_swap.trans (forall_congr (λ _, _))}) theorem is_normal.refl : is_normal id := ⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩ theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) : is_normal (λ x, f (g x)) := ⟨λ x, H₁.lt_iff.2 (H₂.1 _), λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩ theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) : is_limit (f o) := ⟨ne_of_gt $ lt_of_le_of_lt (zero_le _) $ H.lt_iff.2 l.pos, λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩ theorem add_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c := ⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin resetI, suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l), { cases enum _ _ l with x x, { simpa using this (enum s 0 h.pos) }, { exact irrefl _ (this _) } }, intros x, rw [← typein_lt_typein (sum.lex r s), typein_enum], have := H _ (h.2 _ (typein_lt_type s x)), rw [add_succ, succ_le] at this, refine lt_of_le_of_lt (type_le'.2 ⟨order_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this, { rcases a with ⟨a | b, h⟩, { exact sum.inl a }, { exact sum.inr ⟨b, by simpa using h⟩ } }, { rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; simp } end) h H⟩ theorem add_is_normal (a : ordinal) : is_normal ((+) a) := ⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _), λ b l c, add_le_of_limit l⟩ theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) := (add_is_normal a).is_limit def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] : @principal_seg α ordinal.{u} r (<) := ⟨order_embedding.of_monotone (typein r) (λ a b, (typein_lt_typein r).2), type r, λ b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] : (typein.principal_seg r : α → ordinal) = typein r := rfl /-- The minimal element of a nonempty family of ordinals -/ def min {ι} (I : nonempty ι) (f : ι → ordinal) : ordinal := wf.min (set.range f) (let ⟨i⟩ := I in set.ne_empty_of_mem (set.mem_range_self i)) theorem min_eq {ι} (I) (f : ι → ordinal) : ∃ i, min I f = f i := let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩ theorem min_le {ι I} (f : ι → ordinal) (i) : min I f ≤ f i := le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i) theorem le_min {ι I} {f : ι → ordinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ /-- The minimal element of a nonempty set of ordinals -/ def omin (S : set ordinal.{u}) (H : ∃ x, x ∈ S) : ordinal.{u} := @min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val theorem omin_mem (S H) : omin S H ∈ S := let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in (show omin S H = i, from e).symm ▸ h theorem le_omin {S H a} : a ≤ omin S H ↔ ∀ i ∈ S, a ≤ i := le_min.trans set.set_coe.forall theorem omin_le {S H i} (h : i ∈ S) : omin S H ≤ i := le_omin.1 (le_refl _) _ h @[simp] theorem lift_min {ι} (I) (f : ι → ordinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{u v}, λ a b, lift_inj.1⟩, λ a b, lift_lt.symm⟩, λ a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ def univ := lift.{(u+1) v} (@type ordinal.{u} (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := ⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine λ b, induction_on b _, introsI β s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊢, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, intros α r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(order_iso.of_surjective (order_embedding.of_monotone _ _) _).symm⟩, { exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine λ a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.ord'.1 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, intros α r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal → ordinal) = lift.{u (max (u+1) v)} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ := by simp [univ_id] /-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/ def sub (a b : ordinal.{u}) : ordinal.{u} := omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩ instance : has_sub ordinal := ⟨sub⟩ theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) := omin_mem {o | a ≤ b+o} _ theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c := ⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _), λ h, omin_le h⟩ theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b := le_iff_le_iff_lt_iff_lt.1 sub_le theorem add_sub_cancel (a b : ordinal) : a + b - a = b := le_antisymm (sub_le.2 $ le_refl _) ((add_le_add_iff_left a).1 $ le_add_sub _ _) theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b := h ▸ add_sub_cancel _ _ theorem sub_le_self (a b : ordinal) : a - b ≤ a := sub_le.2 $ le_add_left _ _ theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a := le_antisymm begin rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l, { simp [e, h] }, { rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self }, { exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) } end (le_add_sub _ _) @[simp] theorem sub_zero (a : ordinal) : a - 0 = a := by simpa using add_sub_cancel 0 a @[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 := by rw ← le_zero; apply sub_le_self @[simp] theorem sub_self (a : ordinal) : a - a = 0 := by simpa using add_sub_cancel a 0 theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b := ⟨λ h, by simpa [h] using le_add_sub a b, λ h, by rwa [← le_zero, sub_le, add_zero]⟩ theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) := eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc] theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c := by rw [← sub_sub, add_sub_cancel] theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) := ⟨ne_of_gt $ lt_sub.2 $ by simp [h], λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩ @[simp] theorem one_add_omega : 1 + omega.{u} = omega := begin refine le_antisymm _ (le_add_left _ _), rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add], have : is_well_order unit empty_relation := by apply_instance, refine ⟨order_embedding.collapse (order_embedding.of_monotone _ _)⟩, { apply sum.rec, exact λ _, 0, exact nat.succ }, { intros a b, cases a; cases b; simp [empty_relation, nat.succ_pos, iff_true_intro nat.succ_lt_succ] }, end @[simp] theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o := by rw [← add_sub_cancel_of_le h, ← add_assoc, one_add_omega] instance : monoid ordinal.{u} := { mul := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨order_iso.prod_lex_congr g f⟩, one := 1, mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, eq.symm $ quotient.sound ⟨⟨equiv.prod_assoc _ _ _, λ a b, begin rcases a with ⟨⟨a₁, a₂⟩, a₃⟩, rcases b with ⟨⟨b₁, b₂⟩, b₃⟩, simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc] end⟩⟩, mul_one := λ a, induction_on a $ λ α r _, by exact quotient.sound ⟨⟨(equiv.ulift.prod_congr (equiv.refl _)).trans (equiv.unit_prod _), λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩; simp [prod.lex_def, empty_relation]⟩⟩, one_mul := λ a, induction_on a $ λ α r _, by exact quotient.sound ⟨⟨((equiv.refl _).prod_congr equiv.ulift).trans (equiv.prod_unit _), λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩; simp [prod.lex_def, empty_relation]⟩⟩ } @[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans (order_iso.prod_lex_congr (order_iso.preimage equiv.ulift _) (order_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem card_mul (a b) : card (a * b) = card a * card b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, mul_comm (mk β) (mk α) @[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 := induction_on a $ λ α _ _, by exactI type_eq_zero_iff_empty.2 (λ ⟨⟨⟨e⟩, _⟩⟩, e.elim) @[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 := induction_on a $ λ α _ _, by exactI type_eq_zero_iff_empty.2 (λ ⟨⟨_, ⟨e⟩⟩⟩, e.elim) theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quotient.sound ⟨⟨equiv.sum_prod_distrib _ _ _, λ a b, by rcases a with ⟨a₁|a₁, a₂⟩; rcases b with ⟨b₁|b₁, b₂⟩; simp [prod.lex_def]⟩⟩ @[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a := by simp [mul_add] @[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _ theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨order_embedding.of_monotone (λ a, (f a.1, a.2)) (λ a b h, _)⟩, clear_, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ _ (f.to_order_embedding.ord'.1 h') }, { exact prod.lex.right _ _ h' } end theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨order_embedding.of_monotone (λ a, (a.1, f a.2)) (λ a b h, _)⟩, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ _ h' }, { exact prod.lex.right _ _ (f.to_order_embedding.ord'.1 h') } end theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d := le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁) theorem mul_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c := ⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin resetI, suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l), { cases enum _ _ l with b a, exact irrefl _ (this _ _) }, intros a b, rw [← typein_lt_typein (prod.lex s r), typein_enum], have := H _ (h.2 _ (typein_lt_type s b)), rw [mul_succ] at this, have := lt_of_lt_of_le ((add_lt_add_iff_left _).2 (typein_lt_type _ a)) this, refine lt_of_le_of_lt (type_le'.2 ⟨order_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this, { rcases a with ⟨⟨b', a'⟩, h⟩, by_cases e : b = b', { refine sum.inr ⟨a', _⟩, subst e, cases h with _ _ _ _ h _ _ _ h, { exact (irrefl _ h).elim }, { exact h } }, { refine sum.inl (⟨b', _⟩, a'), cases h with _ _ _ _ h _ _ _ h, { exact h }, { exact (e rfl).elim } } }, { rcases a with ⟨⟨b₁, a₁⟩, h₁⟩, rcases b with ⟨⟨b₂, a₂⟩, h₂⟩, intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂, { substs b₁ b₂, simpa [prod.lex_def, @irrefl _ s _ b] using h }, { subst b₁, simp [e₂, prod.lex_def] at h ⊢, cases h₂; [exact asymm h h₂_h, exact e₂ rfl] }, { simp [e₁, e₂] }, { simpa [e₁, e₂, prod.lex_def] using h } } end) h H⟩ theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) := ⟨λ b, by rw mul_succ; simpa using (add_lt_add_iff_left (a*b)).2 h, λ b l c, mul_le_of_limit l⟩ theorem lt_mul_of_limit {a b c : ordinal.{u}} (h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' := by simpa [not_ball] using not_congr (@mul_le_of_limit b c a h) theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c := (mul_is_normal a0).lt_iff theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c := (mul_is_normal a0).le_iff theorem mul_lt_mul_of_pos_left {a b c : ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b := (mul_lt_mul_iff_left c0).2 h theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b := by simpa using mul_lt_mul_of_pos_left h₂ h₁ theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := by simpa only [pos_iff_ne_zero] using mul_pos theorem le_of_mul_le_mul_left {a b c : ordinal} (h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b := le_imp_le_iff_lt_imp_lt.2 (λ h', mul_lt_mul_of_pos_left h' h0) h theorem mul_left_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c := (mul_is_normal a0).inj theorem mul_is_limit {a b : ordinal} (a0 : 0 < a) : is_limit b → is_limit (a * b) := (mul_is_normal a0).is_limit theorem mul_is_limit_left {a b : ordinal} (l : is_limit a) (b0 : 0 < b) : is_limit (a * b) := begin rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb, { exact (lt_irrefl _).elim b0 }, { rw mul_succ, exact add_is_limit _ l }, { exact mul_is_limit l.pos lb } end /-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/ protected def div (a b : ordinal.{u}) : ordinal.{u} := if h : b = 0 then 0 else omin {o | a < b * succ o} ⟨a, succ_le.1 $ by simpa using mul_le_mul_right (succ a) (succ_le.2 (pos_iff_ne_zero.2 h))⟩ instance : has_div ordinal := ⟨ordinal.div⟩ @[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl def div_def (a) {b : ordinal} (h : b ≠ 0) : a / b = omin {o | a < b * succ o} _ := dif_neg h theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) := by rw div_def a h; exact omin_mem {o | a < b * succ o} _ theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b := by simpa using lt_mul_succ_div a h theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c := ⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h), λ h, by rw div_def a b0; exact omin_le h⟩ theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b := by rw [← not_le, div_le c0, not_lt] theorem le_div {a b c : ordinal} (c0 : c ≠ 0) : a ≤ b / c ↔ c * a ≤ b := begin apply limit_rec_on a, { simp [zero_le] }, { intros, rw [succ_le, lt_div c0] }, { simp [mul_le_of_limit, limit_le, -not_lt] {contextual := tt} } end theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) : a / b < c ↔ a < b * c := le_iff_le_iff_lt_iff_lt.1 $ le_div b0 theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c := if b0 : b = 0 then by simp [b0, zero_le] else (div_le b0).2 $ lt_of_le_of_lt h $ mul_lt_mul_of_pos_left (lt_succ_self _) (pos_iff_ne_zero.2 b0) theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b := le_imp_le_iff_lt_imp_lt.1 div_le_of_le_mul @[simp] theorem zero_div (a : ordinal) : 0 / a = 0 := le_zero.1 $ div_le_of_le_mul $ by simp theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a := if b0 : b = 0 then by simp [b0, zero_le] else (le_div b0).1 (le_refl _) theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b := begin apply le_antisymm, { apply (div_le b0).2, rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left], apply lt_mul_div_add _ b0 }, { rw [le_div b0, mul_add, add_le_add_iff_left], apply mul_div_le } end theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 := by rw [← le_zero, div_le $ pos_iff_ne_zero.1 $ lt_of_le_of_lt (zero_le _) h]; simpa using h @[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a := by simpa using mul_add_div a b0 0 @[simp] theorem div_one (a : ordinal) : a / 1 = a := by simpa using mul_div_cancel a one_ne_zero @[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 := by simpa using mul_div_cancel 1 h theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c := if a0 : a = 0 then by simp [a0] else eq_of_forall_ge_iff $ λ d, by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0] /-- Divisibility is defined by right multiplication: `a ∣ b` if there exists `c` such that `b = a * c`. -/ instance : has_dvd ordinal := ⟨λ a b, ∃ c, b = a * c⟩ theorem dvd_def {a b : ordinal} : a ∣ b ↔ ∃ c, b = a * c := iff.rfl theorem dvd_mul (a b : ordinal) : a ∣ a * b := ⟨_, rfl⟩ theorem dvd_trans : ∀ {a b c : ordinal}, a ∣ b → b ∣ c → a ∣ c | a _ _ ⟨b, rfl⟩ ⟨c, rfl⟩ := ⟨b * c, mul_assoc _ _ _⟩ theorem dvd_mul_of_dvd {a b : ordinal} (c) (h : a ∣ b) : a ∣ b * c := dvd_trans h (dvd_mul _ _) theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c) | a _ c ⟨b, rfl⟩ := ⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, λ ⟨d, e⟩, by rw [e, ← mul_add]; apply dvd_mul⟩ theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c := (dvd_add_iff h₁).2 theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩ theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 := ⟨λ ⟨h, e⟩, by simp [e], λ e, e.symm ▸ dvd_zero _⟩ theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩ theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b | a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0] theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b | a _ b0 ⟨b, rfl⟩ := by simpa using mul_le_mul_left a (one_le_iff_ne_zero.2 (λ h : b = 0, by simpa [h] using b0)) theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b := if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂) /-- `a % b` is the unique ordinal `o'` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩ theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl @[simp] theorem mod_zero (a : ordinal) : a % 0 = a := by simp [mod_def] theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a := by simp [mod_def, div_eq_zero_of_lt h] @[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 := by simp [mod_def] theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a := add_sub_cancel_of_le $ mul_div_le _ _ theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b := (add_lt_add_iff_left (b * (a / b))).1 $ by rw div_add_mod; exact lt_mul_div_add a h @[simp] theorem mod_self (a : ordinal) : a % a = 0 := if a0 : a = 0 then by simp [a0] else by simp [mod_def, a0] @[simp] theorem mod_one (a : ordinal) : a % 1 = 0 := by simp [mod_def] end ordinal namespace cardinal open ordinal /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. -/ def ord (c : cardinal) : ordinal := begin let ι := λ α, {r // is_well_order α r}, have : ∀ α, nonempty (ι α) := λ α, ⟨classical.indefinite_description _ well_ordering_thm⟩, let F := λ α, ordinal.min (this _) (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧), refine quot.lift_on c F _, suffices : ∀ {α β}, α ≈ β → F α ≤ F β, from λ α β h, le_antisymm (this h) (this (setoid.symm h)), intros α β h, cases h with f, refine ordinal.le_min.2 (λ i, _), haveI := @order_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(order_iso.preimage f i.1) i.2, rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from quot.sound ⟨order_iso.preimage f i.1⟩, exact ordinal.min_le (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩ end def ord_eq_min (α : Type u) : ord (mk α) = @ordinal.min _ _ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) := rfl theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r], ord (mk α) = @type α r wo := let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq _ ⟨classical.indefinite_description _ well_ordering_thm⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) in ⟨r, wo, h⟩ theorem ord_le_type (r : α → α → Prop) [is_well_order α r] : ord (mk α) ≤ ordinal.type r := @ordinal.min_le _ ⟨classical.indefinite_description _ well_ordering_thm⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩ theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card := quotient.induction_on c $ λ α, induction_on o $ λ β s _, let ⟨r, _, e⟩ := ord_eq α in begin resetI, simp, split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := order_embedding.preimage f s, haveI := order_embedding.is_well_order g, exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) } end theorem lt_ord {c o} : o < ord c ↔ o.card < c := by rw [← not_le, ← not_le, ord_le] @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ λ α, let ⟨r, _, e⟩ := ord_eq α in by simp [e] theorem ord_card_le (o : ordinal) : o.card.ord ≤ o := ord_le.2 (le_refl _) @[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ := by simp [ord_le] @[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ := by simp [lt_ord] @[simp] theorem ord_zero : ord 0 = 0 := le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _) @[simp] theorem ord_nat (n : ℕ) : ord n = n := le_antisymm (ord_le.2 $ by simp) $ begin induction n with n IH, { apply ordinal.zero_le }, { exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := eq_of_forall_ge_iff $ λ o, le_iff_le_iff_lt_iff_lt.2 $ begin split; intro h, { rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩, rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] }, { rw lt_ord at h, rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩, rw [← lift_card, lift_lt] at h, rwa [ordinal.lift_lt, lt_ord] } end def ord.order_embedding : @order_embedding cardinal ordinal (<) (<) := order_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2 @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal → ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ def univ := lift.{(u+1) v} (mk ordinal) theorem univ_id : univ.{u (u+1)} = mk ordinal := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{u (u+1)} c < univ.{u (u+1)} := by simpa [ord_le, succ_le] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{u (max (u+1) v)} c < univ.{u v} := by simpa [univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down'.1 (by simpa using h) with ⟨o', rfl⟩, simp, rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{u (u+1)} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down'.1 (by simpa) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{u (max (u+1) v)} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp [e.symm]⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩ end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl /-- The supremum of a family of ordinals -/ def sup {ι} (f : ι → ordinal) : ordinal := omin {c | ∀ i, f i ≤ c} ⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $ cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩ theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f := omin_mem {c | ∀ i, f i ≤ c} _ theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩ theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i := by simpa [not_forall] using not_congr (@sup_le _ f a) theorem is_normal.sup {f} (H : is_normal f) {ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) := eq_of_forall_ge_iff $ λ a, by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)]; simp [sup_le] /-- The supremum of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. (This is not a special case of `sup` over the subtype, because `{a // a < o} : Type (u+1)` and `sup` only works over families in `Type u`.) -/ def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} := match o, o.out, o.out_eq with | _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _)) end theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a := match o, o.out, o.out_eq, f : ∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}), bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with | _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI ⟨λ H i h, by simpa using H (enum r i h), λ H b, H _ _⟩ end theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) : bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) := eq_of_forall_ge_iff $ λ o, by rw [bsup_le, sup_le]; exact ⟨λ H b, H _ _, λ H i h, by simpa using H (enum r i h)⟩ theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f := bsup_le.1 (le_refl _) _ _ theorem is_normal.bsup {f} (H : is_normal f) {o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0), f (bsup o g) = bsup o (λ a h, f (g a h)) := induction_on o $ λ α r _ g h, by resetI; rw [bsup_type, H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type] /-- The ordinal exponential, defined by transfinite recursion. -/ def power (a b : ordinal) : ordinal := if a = 0 then 1 - b else limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b) instance : has_pow ordinal ordinal := ⟨power⟩ local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a := by simp [pow, power] @[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 := by rwa [zero_power', sub_eq_zero_iff_le, one_le_iff_ne_zero] @[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 := by by_cases a = 0; simp [pow, power, h] @[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a := if h : a = 0 then by subst a; simp [succ_ne_zero] else by simp [pow, power, h] theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b = bsup.{u u} b (λ c _, a ^ c) := by simp [pow, power, a0]; rw limit_rec_on_limit _ _ _ _ h; refl theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c := by rw [power_limit a0 h, bsup_le] theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) : a < b ^ c ↔ ∃ c' < c, a < b ^ c' := by rw [← not_iff_not, not_exists]; simp [power_le_of_limit b0 h] @[simp] theorem power_one (a : ordinal) : a ^ 1 = a := by rw [← succ_zero, power_succ]; simp @[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 := begin apply limit_rec_on a, {simp}, {simp}, refine λ b l IH, eq_of_forall_ge_iff (λ c, _), rw [power_le_of_limit one_ne_zero l], exact ⟨λ H, by simpa using H 0 l.pos, λ H b' h, by rwa IH _ h⟩, end theorem power_pos {a : ordinal} (b) (a0 : 0 < a) : 0 < a ^ b := begin have h0 : 0 < a ^ 0, {simp [zero_lt_one]}, apply limit_rec_on b, { exact h0 }, { intros b IH, rw [power_succ], exact mul_pos IH a0 }, { exact λ b l _, (lt_power_of_limit (pos_iff_ne_zero.1 a0) l).2 ⟨0, l.pos, h0⟩ }, end theorem power_ne_zero {a : ordinal} (b) (a0 : a ≠ 0) : a ^ b ≠ 0 := pos_iff_ne_zero.1 $ power_pos b $ pos_iff_ne_zero.2 a0 theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) := have a0 : 0 < a, from lt_trans zero_lt_one h, ⟨λ b, by simpa using (mul_lt_mul_iff_left (power_pos b a0)).2 h, λ b l c, power_le_of_limit (ne_of_gt a0) l⟩ theorem power_lt_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b < a ^ c ↔ b < c := (power_is_normal a1).lt_iff theorem power_le_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c := (power_is_normal a1).le_iff theorem power_right_inj {a b c : ordinal} (a1 : 1 < a) : a ^ b = a ^ c ↔ b = c := (power_is_normal a1).inj theorem power_is_limit {a b : ordinal} (a1 : 1 < a) : is_limit b → is_limit (a ^ b) := (power_is_normal a1).is_limit theorem power_is_limit_left {a b : ordinal} (l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) := begin rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l', { exact absurd e hb }, { rw power_succ, exact mul_is_limit (power_pos _ l.pos) l }, { exact power_is_limit l.one_lt l' } end theorem power_le_power_right {a b c : ordinal} (h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c := begin cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁, { exact (power_le_power_iff_right h₁).2 h₂ }, { subst a, simp } end theorem power_le_power_left {a b : ordinal} (c) (ab : a ≤ b) : a ^ c ≤ b ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, { subst c, simp }, { simp [c0, zero_le] } }, { apply limit_rec_on c, { simp }, { intros c IH, simpa using mul_le_mul IH ab }, { exact λ c l IH, (power_le_of_limit a0 l).2 (λ b' h, le_trans (IH _ h) (power_le_power_right (lt_of_lt_of_le (pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } } end theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b := (power_is_normal a1).le_self _ theorem power_lt_power_left_of_succ {a b c : ordinal} (ab : a < b) : a ^ succ c < b ^ succ c := by rw [power_succ, power_succ]; exact lt_of_le_of_lt (mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab) (mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (zero_le _) ab))) theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp [c0]}, have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le (pos_iff_ne_zero.2 c0) (le_add_left _ _)), simp [c0, this] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp }, apply limit_rec_on c, { simp }, { intros c IH, rw [add_succ, power_succ, IH, power_succ, mul_assoc] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans (add_is_normal b)).limit_le l).trans _), simp [IH] {contextual := tt}, exact (((mul_is_normal $ power_pos b (pos_iff_ne_zero.2 a0)).trans (power_is_normal a1)).limit_le l).symm } end theorem power_dvd_power (a) {b c : ordinal} (h : b ≤ c) : a ^ b ∣ a ^ c := by rw [← add_sub_cancel_of_le h, power_add]; apply dvd_mul theorem power_dvd_power_iff {a b c : ordinal} (a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c := ⟨λ h, le_of_not_lt $ λ hn, not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $ le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h, power_dvd_power _⟩ theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c := begin by_cases b0 : b = 0, {simp [b0]}, by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp [c0]}, simp [b0, c0, mul_ne_zero b0 c0] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp }, apply limit_rec_on c, { simp }, { intros c IH, rw [mul_succ, power_add, IH, power_succ] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans (mul_is_normal (pos_iff_ne_zero.2 b0))).limit_le l).trans _), simp [IH] {contextual := tt}, exact (power_le_of_limit (power_ne_zero _ a0) l).symm } end /-- The ordinal logarithm is the solution `u` to the equation `x = b ^ u * v + w` where `v < b` and `w < b`. -/ def log (b : ordinal) (x : ordinal) : ordinal := if h : 1 < b then pred $ omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩ else 0 @[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 := by simp [log, b1] theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x = pred (omin {o | x < b^o} (log._proof_1 b x b1)) := by simp [log, b1] @[simp] theorem log_zero (b : ordinal) : log b 0 = 0 := if b1 : 1 < b then by rw [log_def b1, ← le_zero, pred_le]; apply omin_le; simp [lt_trans zero_lt_one b1] else by simp [b1] theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) = omin {o | x < b^o} (log._proof_1 b x b1) := begin let t := omin {o | x < b^o} (log._proof_1 b x b1), have : x < b ^ t := omin_mem {o | x < b^o} _, rcases zero_or_succ_or_limit t with h|h|h, { refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim, simpa [h] }, { rw [show log b x = pred t, from log_def b1 x, succ_pred_iff_is_succ.2 h] }, { rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩, exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) } end theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) : x < b ^ succ (log b x) := begin cases lt_or_eq_of_le (zero_le x) with x0 x0, { rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ }, { subst x, apply power_pos _ (lt_trans zero_lt_one b1) } end theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) : b ^ log b x ≤ x := begin by_cases b0 : b = 0, { rw [b0, zero_power'], refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _), have := @omin_le {o | x < b^o} _ _ h, rwa ← succ_log_def b1 x0 at this }, { rw [← b1, one_power], exact one_le_iff_pos.2 x0 } end theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : c ≤ log b x ↔ b ^ c ≤ x := ⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0), λ h, le_of_not_lt $ λ hn, not_le_of_lt (lt_power_succ_log b1 x) $ le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩ theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : log b x < c ↔ x < b ^ c := le_iff_le_iff_lt_iff_lt.1 (le_log b1 x0) theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) : log b x ≤ log b y := if x0 : x = 0 then by simp [x0, zero_le] else have x0 : 0 < x, from pos_iff_ne_zero.2 x0, if b1 : 1 < b then (le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy else by simp [b1, zero_le] theorem log_le_self (b x : ordinal) : log b x ≤ x := if x0 : x = 0 then by simp [x0, zero_le] else if b1 : 1 < b then le_trans (le_power_self _ b1) (power_log_le b (pos_iff_ne_zero.2 x0)) else by simp [b1, zero_le] @[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n := by induction n with n IH; [simp, rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]] @[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n := by induction n with n IH; [simp, rw [nat.pow_succ, nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]] @[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n := by rw [← cardinal.ord_nat, ← cardinal.ord_nat, cardinal.ord_le_ord, cardinal.nat_cast_le] @[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 := @nat_cast_inj n 0 @[simp] theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 := not_congr nat_cast_eq_zero @[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n := by simpa using @nat_cast_lt 0 n @[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n := (_root_.le_total m n).elim (λ h, by rw [nat.sub_eq_zero_iff_le.2 h, sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl) (λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add, nat.add_sub_cancel' h, add_sub_cancel_of_le (nat_cast_le.2 h)]) @[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n := if n0 : n = 0 then by simp [n0] else have n0':_, from nat_cast_ne_zero.2 n0, le_antisymm (by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm]; apply nat.div_mul_le_self) (by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul, nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)]; apply nat.lt_succ_self) @[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n := by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add, add_comm, nat.mod_add_div] @[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o := ⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h, λ h, card_nat n ▸ card_le_card h⟩ @[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o := by rw [← succ_le, ← cardinal.succ_le, cardinal.nat_succ, nat_le_card]; refl @[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n := le_iff_le_iff_lt_iff_lt.1 nat_le_card @[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n := le_iff_le_iff_lt_iff_lt.2 nat_lt_card @[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n := by simp [le_antisymm_iff] @[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n := by rw [← card_eq_nat, card_type, mk_fin] @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n := by simp theorem fintype_card (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α := by rw [← card_eq_nat, card_type, fintype_card] end ordinal namespace cardinal open ordinal @[simp] theorem ord_omega : ord.{u} omega = ordinal.omega := le_antisymm (ord_le.2 $ le_refl _) $ le_of_forall_lt $ λ o h, begin rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩, rw [lt_ord, ← lift_card, ← lift_omega.{0 u}, lift_lt, ← typein_enum (<) h'], exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩ end @[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c := by rw [add_comm, ← card_ord c, ← card_one, ← card_add, one_add_of_omega_le]; rwa [← ord_omega, ord_le_ord] end cardinal namespace ordinal theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n := by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega := lt_omega.2 ⟨_, rfl⟩ theorem omega_pos : 0 < omega := nat_lt_omega 0 theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem omega_is_limit : is_limit omega := ⟨omega_ne_zero, λ o h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e]; exact nat_lt_omega (n+1)⟩ theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ H, le_of_forall_lt $ λ a h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e, ← succ_le]; exact H (n+1)⟩ theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := lt_of_le_of_ne (zero_le o) h.1.symm | (n+1) := h.2 _ (nat_lt_limit n) theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o := omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega := by rcases lt_omega.1 h with ⟨n, rfl⟩; clear h; induction n with n IH; simp * theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega end theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a := begin refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩, { refine (limit_le l).2 (λ x hx, le_of_lt _), rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero, mul_succ, add_le_of_limit omega_is_limit], intros b hb, rcases lt_omega.1 hb with ⟨n, rfl⟩, exact le_trans (add_le_add_right (mul_div_le _ _) _) (le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) }, { rcases h with ⟨a0, b, rfl⟩, refine mul_is_limit_left omega_is_limit (pos_iff_ne_zero.2 $ mt _ a0), intro e, simp [e] } end local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega end theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b := begin refine le_antisymm _ (le_add_left _ _), revert h, apply limit_rec_on b, { intro h, rw [power_zero, ← succ_zero, lt_succ, le_zero] at h, simp [h] }, { intros b _ h, rw [power_succ] at h, rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩, refine le_trans (add_le_add_right (le_of_lt ax) _) _, rw [power_succ, ← mul_add, add_omega xo] }, { intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩, refine (((add_is_normal a).trans (power_is_normal one_lt_omega)) .limit_le l).2 (λ y yb, _), let z := max x y, have := IH z (max_lt xb yb) (lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)), exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _) (le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) } end theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) : a + b < omega ^ c := by rwa [← add_omega_power h₁, add_lt_add_iff_left] theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c := by rw [← add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁] theorem add_absorp_iff {o : ordinal} (o0 : o > 0) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a := ⟨λ H, ⟨log omega o, begin refine ((lt_or_eq_of_le (power_log_le _ o0)) .resolve_left $ λ h, _).symm, have := H _ h, have := lt_power_succ_log one_lt_omega o, rw [power_succ, lt_mul_of_limit omega_is_limit] at this, rcases this with ⟨a, ao, h'⟩, rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao, revert h', apply not_lt_of_le, suffices e : omega ^ log omega o * ↑n + o = o, { simpa [e] using le_add_right (omega ^ log omega o * ↑n) o }, induction n with n IH, {simp}, simp [mul_add_one, this, IH] end⟩, λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩ theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a) (l : is_limit c) (IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c := le_antisymm ((mul_le_of_limit l).2 $ λ c' h, begin apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)), rw IH _ h, apply le_trans (add_le_add_left _ _), { rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) }, { rw ← ba, exact le_add_right _ _ } end) (mul_le_mul_right _ (le_add_right _ _)) theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := begin apply limit_rec_on c, { simp }, { intros c IH, rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] }, { intros c l IH, have := add_mul_limit_aux ba l IH, rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] } end theorem add_mul_limit {a b c : ordinal} (ba : b + a = a) (l : is_limit c) : (a + b) * c = a * c := add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba) theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega := le_antisymm ((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb)) (by simpa using mul_le_mul_right omega (one_le_iff_pos.2 a0)) theorem mul_lt_omega_power {a b c : ordinal} (c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c := if b0 : b = 0 then by simp [b0, power_pos _ omega_pos] else begin rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l, { exact (lt_irrefl _).elim c0 }, { rw power_succ at ha, rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt omega_is_limit).1 ha with ⟨n, hn, an⟩, refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _, rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)], exact mul_lt_omega hn hb }, { rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩, refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _, rw [← power_succ, power_lt_power_iff_right one_lt_omega], exact l.2 _ hx } end theorem mul_omega_dvd {a : ordinal} (a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b | _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha] theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) : a * omega ^ omega ^ b = omega ^ omega ^ b := begin by_cases b0 : b = 0, {simp [b0] at h ⊢, simp [mul_omega a0 h]}, refine le_antisymm _ (by simpa using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)), rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h with ⟨x, xb, ax⟩, refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _, rw [← power_add, add_omega_power xb] end theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega := le_antisymm ((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2 (λ b hb, le_of_lt (power_lt_omega h hb))) (le_power_self _ a1) theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : o % b ^ log b o < o := lt_of_lt_of_le (mod_lt _ $ power_ne_zero _ b0) (power_log_le _ $ pos_iff_ne_zero.2 o0) @[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0) {C : ordinal → Sort*} (H0 : C 0) (H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o) : ∀ o, C o | o := if o0 : o = 0 then by rw o0; exact H0 else have _, from CNF_aux b0 o0, H o o0 this (CNF_rec (o % b ^ log b o)) using_well_founded {dec_tac := `[assumption]} @[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 := by rw CNF_rec; simp; refl @[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) : @CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) := by rw CNF_rec; simp [o0] /-- The Cantor normal form of an ordinal is the list of coefficients in the base-`b` expansion of `o`. CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/ def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) := if b0 : b = 0 then [] else CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o @[simp] theorem zero_CNF (o) : CNF 0 o = [] := by rw CNF; simp @[simp] theorem CNF_zero (b) : CNF b 0 = [] := if b0 : b = 0 then by simp [b0] else by simp [CNF, b0] theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) := by simp [CNF, b0, o0] theorem one_CNF {o : ordinal} (o0 : o ≠ 0) : CNF 1 o = [(0, o)] := by rw [CNF_ne_zero one_ne_zero o0]; simp theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) : (CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o := CNF_rec b0 (by simp) (λ o o0 h IH, by simp [CNF_ne_zero b0 o0, IH, div_add_mod]) o theorem CNF_pairwise_aux (b := omega) (o) : (∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧ (CNF b o).pairwise (λ p q, q.1 < p.1) := begin by_cases b0 : b = 0, {simp [b0]}, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine CNF_rec b0 (by simp) _ o, intros o o0 H IH, cases IH with IH₁ IH₂, simp [CNF_ne_zero b0 o0, IH₁, IH₂, -prod.forall], refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩, { exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) }, { refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _), { rw pos_iff_ne_zero, intro e, rw e at m, simpa using m }, { exact mod_lt _ (power_ne_zero _ b0) } } }, { by_cases o0 : o = 0, {simp [o0]}, rw [← b1, one_CNF o0], simp } end theorem CNF_pairwise (b := omega) (o) : (CNF b o).pairwise (λ p q, prod.fst q < p.1) := (CNF_pairwise_aux _ _).2 theorem CNF_fst_le_log (b := omega) (o) : ∀ p ∈ CNF b o, prod.fst p ≤ log b o := (CNF_pairwise_aux _ _).1 theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o := le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _) theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) : ∀ p ∈ CNF b o, prod.snd p < b := begin have b0 := ne_of_gt (lt_trans zero_lt_one b1), refine CNF_rec b0 (by simp) _ o, intros o o0 H IH, simp [CNF_ne_zero b0 o0, iff_true_intro IH, -prod.forall], rw [div_lt (power_ne_zero _ b0), ← power_succ], exact lt_power_succ_log b1 _, end theorem CNF_sorted (b := omega) (o) : ((CNF b o).map prod.fst).sorted (>) := by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o /-- The next fixed point function, the least fixed point of the normal function `f` above `a`. -/ def nfp (f : ordinal → ordinal) (a : ordinal) := sup (λ n : ℕ, f^[n] a) theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a := le_sup _ n theorem le_nfp_self (f a) : a ≤ nfp f a := iterate_le_nfp f a 0 theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} : f b < nfp f a ↔ b < nfp f a := lt_sup.trans $ iff.trans (by exact ⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩, λ ⟨n, h⟩, ⟨n+1, by rw nat.iterate_succ'; exact H.lt_iff.2 h⟩⟩) lt_sup.symm theorem is_normal.nfp_le {f} (H : is_normal f) {a b} : nfp f a ≤ f b ↔ nfp f a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_nfp theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b} (ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b := sup_le.2 $ λ i, begin induction i with i IH generalizing a, {exact ab}, exact IH (le_trans (H.le_iff.2 ab) h), end theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a := begin refine le_antisymm _ (H.le_self _), cases le_or_lt (f a) a with aa aa, { rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) }, rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l, { refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1), simp [e, zero_le] }, { have : f b < nfp f a := H.lt_nfp.2 (by simp [e, lt_succ_self]), rw [e, lt_succ] at this, have ab : a ≤ b, { rw [← lt_succ, ← e], exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) }, refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this)) (le_trans this (le_of_lt _)), simp [e, lt_succ_self] }, { exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) } end theorem is_normal.le_nfp {f} (H : is_normal f) {a b} : f b ≤ nfp f a ↔ b ≤ nfp f a := ⟨le_trans (H.le_self _), λ h, by simpa [H.nfp_fp] using H.le_iff.2 h⟩ /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. -/ def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal := limit_rec_on o (nfp f 0) (λ a IH, nfp f (succ IH)) (λ a l, bsup.{u u} a) @[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := limit_rec_on_succ _ _ _ _ theorem deriv_limit (f) {o} : is_limit o → deriv f o = bsup.{u u} o (λ a _, deriv f a) := limit_rec_on_limit _ _ _ _ theorem deriv_is_normal (f) : is_normal (deriv f) := ⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self, λ o l a, by rw [deriv_limit _ l, bsup_le]⟩ theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o := begin apply limit_rec_on o; try {simp [H.nfp_fp]}, intros o l IH, rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1], apply eq_of_forall_ge_iff, simp [bsup_le, IH] {contextual := tt} end theorem is_normal.fp_iff_deriv {f} (H : is_normal f) {a} : f a ≤ a ↔ ∃ o, a = deriv f o := ⟨λ ha, begin suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o, from this a ((deriv_is_normal _).le_self _), intro o, apply limit_rec_on o, { intros h₁, refine ⟨0, le_antisymm h₁ _⟩, rw deriv_zero, exact H.nfp_le_fp (zero_le _) ha }, { intros o IH h₁, cases le_or_lt a (deriv f o), {exact IH h}, refine ⟨succ o, le_antisymm h₁ _⟩, rw deriv_succ, exact H.nfp_le_fp (succ_le.2 h) ha }, { intros o l IH h₁, cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩}, rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h, exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) } end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩ end ordinal namespace cardinal open ordinal theorem ord_is_limit {c} (co : omega ≤ c) : (ord c).is_limit := begin refine ⟨λ h, omega_ne_zero _, λ a, le_imp_le_iff_lt_imp_lt.1 _⟩, { rw [← ordinal.le_zero, ord_le] at h, simpa [le_zero] using le_trans co h }, { intro h, rw [ord_le] at h ⊢, rwa [← @add_one_of_omega_le (card a), ← card_succ], rw [← ord_le, ← le_succ_of_is_limit, ord_le], { exact le_trans co h }, { rw ord_omega, exact omega_is_limit } } end def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @order_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) -/ def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_order_embedding.ord'.symm @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b := aleph_idx.initial_seg.init _ _ def aleph_idx.order_iso : @order_iso cardinal.{u} ordinal.{u} (<) (<) := @order_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ λ ⟨o, e⟩, begin have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI α r _ h, let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)), apply not_le_of_gt (lt_succ_self s), have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.inj, simpa [left_inverse_inv_fun I (succ s)] using le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a)) (ordinal.enum r _ (h (succ s))), end @[simp] theorem aleph_idx.order_iso_coe : (aleph_idx.order_iso : cardinal → ordinal) = aleph_idx := by delta aleph_idx.order_iso; simp @[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.order_iso⟩ @[simp] theorem mk_cardinal : mk cardinal = univ.{u (u+1)} := by simpa [-type_cardinal] using congr_arg card type_cardinal def aleph'.order_iso := cardinal.aleph_idx.order_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁, etc. -/ def aleph' : ordinal → cardinal := aleph'.order_iso @[simp] theorem aleph'.order_iso_coe : (aleph'.order_iso : ordinal → cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := aleph'.order_iso.ord'.symm @[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c := by simpa using cardinal.aleph_idx.order_iso.to_equiv.inverse_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o := by simpa using cardinal.aleph_idx.order_iso.to_equiv.apply_inverse_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by rw [← le_zero, ← aleph'_aleph_idx 0, aleph'_le]; apply ordinal.zero_le @[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ := le_antisymm (cardinal.aleph_idx_le.1 $ by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx]; apply cardinal.lt_succ_self) (cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _) @[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n | 0 := by simp | (n+1) := show aleph' (ordinal.succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} : aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c := ⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h, λ h, begin rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l], intros x h', rw [← aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ @[simp] theorem aleph'_omega : aleph' ordinal.omega = omega := eq_of_forall_ge_iff $ λ c, begin simp [aleph'_le_of_limit omega_is_limit, omega_le, ordinal.lt_omega], exact forall_swap.trans (forall_congr $ λ n, by simp), end /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o) @[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := aleph'_lt.trans (ordinal.add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ := by rw [aleph, ordinal.add_succ, aleph'_succ]; refl @[simp] theorem aleph_zero : aleph 0 = omega := by simp [aleph] theorem omega_le_aleph' {o : ordinal} : omega ≤ aleph' o ↔ ordinal.omega ≤ o := by rw [← aleph'_omega, aleph'_le] theorem omega_le_aleph (o : ordinal) : omega ≤ aleph o := by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right theorem aleph_is_limit (o : ordinal) : is_limit (aleph o).ord := ord_is_limit $ omega_le_aleph _ theorem exists_aleph {c : cardinal} : omega ≤ c ↔ ∃ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ordinal.omega, by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx]; rwa [← omega_le_aleph', aleph'_aleph_idx]⟩, λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _, λ o l a, by simp [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ordinal.omega theorem mul_eq_self {c : cardinal} (h : omega ≤ c) : c * c = c := begin refine le_antisymm _ (by simpa using mul_le_mul_left c (le_trans (le_of_lt one_lt_omega) h)), refine acc.rec_on (cardinal.wf.apply c) (λ c _, quotient.induction_on c $ λ α IH ol, _) h, rcases ord_eq α with ⟨r, wo, e⟩, resetI, let := decidable_linear_order_of_STO' r, have : is_well_order α (<) := wo, let g : α × α → α := λ p, max p.1 p.2, let f : α × α ↪ ordinal × (α × α) := ⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), have : is_well_order _ s := (order_embedding.preimage _ _).is_well_order, suffices : type s ≤ type r, {exact card_le_card this}, refine le_of_forall_lt (λ o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _, { have : {q|s q p} ⊆ (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}), { intros q h, simp [s, order.preimage, prod.lex_def, typein_inj] at h, simpa using max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ ulift unit), { exact ⟨(set.embedding_of_subset this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr (equiv.punit_equiv_punit.trans equiv.ulift.symm)), apply @irrefl _ r }, cases lt_or_ge (card (typein (<) (g p)).succ) omega with qo qo, { exact lt_of_lt_of_le (mul_lt_omega qo qo) ol }, { suffices, {exact lt_of_le_of_lt (IH _ this qo) this}, rw ← lt_ord, apply (ord_is_limit ol).2, dsimp, rw e, apply typein_lt_type } end theorem mul_eq_max {a b : cardinal} (ha : omega ≤ a) (hb : omega ≤ b) : a * b = max a b := le_antisymm (mul_eq_self (le_trans ha (le_max_left a b)) ▸ mul_le_mul (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa using mul_le_mul_left a (le_trans (le_of_lt one_lt_omega) hb)) (by simpa using mul_le_mul_right b (le_trans (le_of_lt one_lt_omega) ha)) theorem add_eq_self {c : cardinal} (h : omega ≤ c) : c + c = c := le_antisymm (by simpa [mul_eq_self h, two_mul] using mul_le_mul_right c (le_trans (le_of_lt $ nat_lt_omega 2) h)) (le_add_left c c) theorem add_eq_max {a b : cardinal} (ha : omega ≤ a) : a + b = max a b := le_antisymm (add_eq_self (le_trans ha (le_max_left a b)) ▸ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (le_add_right _ _) (le_add_left _ _) end cardinal
f97ce34469776bc269a76868e41058f43d7590b0
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/algebra/basic.lean
61cdbaa5a976d0798aff1bb836fa869418294793
[ "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
63,869
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.module.basic import algebra.ring.aut import algebra.ring.ulift import algebra.module.ulift import linear_algebra.span import tactic.abel /-! # Algebras over commutative semirings In this file we define associative unital `algebra`s over commutative (semi)rings, algebra homomorphisms `alg_hom`, and algebra equivalences `alg_equiv`. `subalgebra`s are defined in `algebra.algebra.subalgebra`. For the category of `R`-algebras, denoted `Algebra R`, see the file `algebra/category/Algebra/basic.lean`. See the implementation notes for remarks about non-associative and non-unital algebras. ## Main definitions: * `algebra R A`: the algebra typeclass. * `alg_hom R A B`: the type of `R`-algebra morphisms from `A` to `B`. * `alg_equiv R A B`: the type of `R`-algebra isomorphisms between `A` to `B`. * `algebra_map R A : R →+* A`: the canonical map from `R` to `A`, as a `ring_hom`. This is the preferred spelling of this map. * `algebra.linear_map R A : R →ₗ[R] A`: the canonical map from `R` to `A`, as a `linear_map`. * `algebra.of_id R A : R →ₐ[R] A`: the canonical map from `R` to `A`, as n `alg_hom`. * Instances of `algebra` in this file: * `algebra.id` * `pi.algebra` * `prod.algebra` * `algebra_nat` * `algebra_int` * `algebra_rat` * `mul_opposite.algebra` * `module.End.algebra` ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. ## Implementation notes Given a commutative (semi)ring `R`, there are two ways to define an `R`-algebra structure on a (possibly noncommutative) (semi)ring `A`: * By endowing `A` with a morphism of rings `R →+* A` denoted `algebra_map R A` which lands in the center of `A`. * By requiring `A` be an `R`-module such that the action associates and commutes with multiplication as `r • (a₁ * a₂) = (r • a₁) * a₂ = a₁ * (r • a₂)`. We define `algebra R A` in a way that subsumes both definitions, by extending `has_smul R A` and requiring that this scalar action `r • x` must agree with left multiplication by the image of the structure morphism `algebra_map R A r * x`. As a result, there are two ways to talk about an `R`-algebra `A` when `A` is a semiring: 1. ```lean variables [comm_semiring R] [semiring A] variables [algebra R A] ``` 2. ```lean variables [comm_semiring R] [semiring A] variables [module R A] [smul_comm_class R A A] [is_scalar_tower R A A] ``` The first approach implies the second via typeclass search; so any lemma stated with the second set of arguments will automatically apply to the first set. Typeclass search does not know that the second approach implies the first, but this can be shown with: ```lean example {R A : Type*} [comm_semiring R] [semiring A] [module R A] [smul_comm_class R A A] [is_scalar_tower R A A] : algebra R A := algebra.of_module smul_mul_assoc mul_smul_comm ``` The advantage of the first approach is that `algebra_map R A` is available, and `alg_hom R A B` and `subalgebra R A` can be used. For concrete `R` and `A`, `algebra_map R A` is often definitionally convenient. The advantage of the second approach is that `comm_semiring R`, `semiring A`, and `module R A` can all be relaxed independently; for instance, this allows us to: * Replace `semiring A` with `non_unital_non_assoc_semiring A` in order to describe non-unital and/or non-associative algebras. * Replace `comm_semiring R` and `module R A` with `comm_group R'` and `distrib_mul_action R' A`, which when `R' = Rˣ` lets us talk about the "algebra-like" action of `Rˣ` on an `R`-algebra `A`. While `alg_hom R A B` cannot be used in the second approach, `non_unital_alg_hom R A B` still can. You should always use the first approach when working with associative unital algebras, and mimic the second approach only when you need to weaken a condition on either `R` or `A`. -/ universes u v w u₁ v₁ open_locale big_operators section prio -- We set this priority to 0 later in this file set_option extends_priority 200 /- control priority of `instance [algebra R A] : has_smul R A` -/ /-- An associative unital `R`-algebra is a semiring `A` equipped with a map into its center `R → A`. See the implementation notes in this file for discussion of the details of this definition. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_smul R A, R →+* A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) end prio /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ c x, i c * x = x * i c) : algebra R S := { smul := λ c x, i c * x, commutes' := h, smul_def' := λ c x, rfl, to_ring_hom := i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := i.to_algebra' $ λ _, mul_comm _ lemma ring_hom.algebra_map_to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : @algebra_map R S _ _ i.to_algebra = i := rfl namespace algebra variables {R : Type u} {S : Type v} {A : Type w} {B : Type*} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `module R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. See note [reducible non-instances]. -/ @[reducible] def of_module' [comm_semiring R] [semiring A] [module R A] (h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x) (h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul r₁ r₂ 1, commutes' := λ r x, by simp only [h₁, h₂], smul_def' := λ r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `module R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. See note [reducible non-instances]. -/ @[reducible] def of_module [comm_semiring R] [semiring A] [module R A] (h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A := of_module' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] variables [semiring A] [algebra R A] [semiring B] [algebra R B] /-- We keep this lemma private because it picks up the `algebra.to_has_smul` instance which we set to priority 0 shortly. See `smul_def` below for the public version. -/ private lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x /-- To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree, it suffices to check the `algebra_map`s agree. -/ -- We'll later use this to show `algebra ℤ M` is a subsingleton. @[ext] lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A) (w : ∀ (r : R), by { haveI := P, exact algebra_map R A r } = by { haveI := Q, exact algebra_map R A r }) : P = Q := begin unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ }, congr, { funext r a, replace w := congr_arg (λ s, s * a) (w r), simp only [←smul_def''] at w, apply w, }, { ext r, exact w r, }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, }, end @[priority 200] -- see Note [lower instance priority] instance to_module : module R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- From now on, we don't want to use the following instance anymore. -- Unfortunately, leaving it in place causes deterministic timeouts later in mathlib. attribute [instance, priority 0] algebra.to_has_smul lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 := calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm ... = r • 1 : (algebra.smul_def r 1).symm lemma algebra_map_eq_smul_one' : ⇑(algebra_map R A) = λ r, r • (1 : A) := funext algebra_map_eq_smul_one /-- `mul_comm` for `algebra`s when one element is from the base ring. -/ theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x /-- `mul_left_comm` for `algebra`s when one element is from the base ring. -/ theorem left_comm (x : A) (r : R) (y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] /-- `mul_right_comm` for `algebra`s when one element is from the base ring. -/ theorem right_comm (x : A) (r : R) (y : A) : (x * algebra_map R A r) * y = (x * y) * algebra_map R A r := by rw [mul_assoc, commutes, ←mul_assoc] instance _root_.is_scalar_tower.right : is_scalar_tower R A A := ⟨λ x y z, by rw [smul_eq_mul, smul_eq_mul, smul_def, smul_def, mul_assoc]⟩ /-- This is just a special case of the global `mul_smul_comm` lemma that requires less typeclass search (and was here first). -/ @[simp] protected lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := -- TODO: set up `is_scalar_tower.smul_comm_class` earlier so that we can actually prove this using -- `mul_smul_comm s x y`. by rw [smul_def, smul_def, left_comm] /-- This is just a special case of the global `smul_mul_assoc` lemma that requires less typeclass search (and was here first). -/ @[simp] protected lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := smul_mul_assoc r x y section variables {r : R} {a : A} @[simp] lemma bit0_smul_one : bit0 r • (1 : A) = bit0 (r • (1 : A)) := by simp [bit0, add_smul] lemma bit0_smul_one' : bit0 r • (1 : A) = r • 2 := by simp [bit0, add_smul, smul_add] @[simp] lemma bit0_smul_bit0 : bit0 r • bit0 a = r • (bit0 (bit0 a)) := by simp [bit0, add_smul, smul_add] @[simp] lemma bit0_smul_bit1 : bit0 r • bit1 a = r • (bit0 (bit1 a)) := by simp [bit0, add_smul, smul_add] @[simp] lemma bit1_smul_one : bit1 r • (1 : A) = bit1 (r • (1 : A)) := by simp [bit1, add_smul] lemma bit1_smul_one' : bit1 r • (1 : A) = r • 2 + 1 := by simp [bit1, bit0, add_smul, smul_add] @[simp] lemma bit1_smul_bit0 : bit1 r • bit0 a = r • (bit0 (bit0 a)) + bit0 a := by simp [bit1, add_smul, smul_add] @[simp] lemma bit1_smul_bit1 : bit1 r • bit1 a = r • (bit0 (bit1 a)) + bit1 a := by { simp only [bit0, bit1, add_smul, smul_add, one_smul], abel } end variables (R A) /-- The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`, packaged as an `R`-linear map. -/ protected def linear_map : R →ₗ[R] A := { map_smul' := λ x y, by simp [algebra.smul_def], ..algebra_map R A } @[simp] lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl lemma coe_linear_map : ⇑(algebra.linear_map R A) = algebra_map R A := rfl instance id : algebra R R := (ring_hom.id R).to_algebra variables {R A} namespace id @[simp] lemma map_eq_id : algebra_map R R = ring_hom.id _ := rfl lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl end id section punit instance _root_.punit.algebra : algebra R punit := { to_fun := λ x, punit.star, map_one' := rfl, map_mul' := λ _ _, rfl, map_zero' := rfl, map_add' := λ _ _, rfl, commutes' := λ _ _, rfl, smul_def' := λ _ _, rfl } @[simp] lemma algebra_map_punit (r : R) : algebra_map R punit r = punit.star := rfl end punit section ulift instance _root_.ulift.algebra : algebra R (ulift A) := { to_fun := λ r, ulift.up (algebra_map R A r), commutes' := λ r x, ulift.down_injective $ algebra.commutes r x.down, smul_def' := λ r x, ulift.down_injective $ algebra.smul_def' r x.down, .. ulift.module', .. (ulift.ring_equiv : ulift A ≃+* A).symm.to_ring_hom.comp (algebra_map R A) } lemma _root_.ulift.algebra_map_eq (r : R) : algebra_map R (ulift A) r = ulift.up (algebra_map R A r) := rfl @[simp] lemma _root_.ulift.down_algebra_map (r : R) : (algebra_map R (ulift A) r).down = algebra_map R A r := rfl end ulift section prod variables (R A B) instance _root_.prod.algebra : algebra R (A × B) := { commutes' := by { rintro r ⟨a, b⟩, dsimp, rw [commutes r a, commutes r b] }, smul_def' := by { rintro r ⟨a, b⟩, dsimp, rw [smul_def r a, smul_def r b] }, .. prod.module, .. ring_hom.prod (algebra_map R A) (algebra_map R B) } variables {R A B} @[simp] lemma algebra_map_prod_apply (r : R) : algebra_map R (A × B) r = (algebra_map R A r, algebra_map R B r) := rfl end prod /-- Algebra over a subsemiring. This builds upon `subsemiring.module`. -/ instance of_subsemiring (S : subsemiring R) : algebra S A := { smul := (•), commutes' := λ r x, algebra.commutes r x, smul_def' := λ r x, algebra.smul_def r x, .. (algebra_map R A).comp S.subtype } lemma algebra_map_of_subsemiring (S : subsemiring R) : (algebra_map S R : S →+* R) = subsemiring.subtype S := rfl lemma coe_algebra_map_of_subsemiring (S : subsemiring R) : (algebra_map S R : S → R) = subtype.val := rfl lemma algebra_map_of_subsemiring_apply (S : subsemiring R) (x : S) : algebra_map S R x = x := rfl /-- Algebra over a subring. This builds upon `subring.module`. -/ instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : subring R) : algebra S A := { smul := (•), .. algebra.of_subsemiring S.to_subsemiring, .. (algebra_map R A).comp S.subtype } lemma algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S →+* R) = subring.subtype S := rfl lemma coe_algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S → R) = subtype.val := rfl lemma algebra_map_of_subring_apply {R : Type*} [comm_ring R] (S : subring R) (x : S) : algebra_map S R x = x := rfl /-- Explicit characterization of the submonoid map in the case of an algebra. `S` is made explicit to help with type inference -/ def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S] (M : submonoid R) : (submonoid S) := submonoid.map (algebra_map R S : R →* S) M lemma mem_algebra_map_submonoid_of_mem {S : Type*} [semiring S] [algebra R S] {M : submonoid R} (x : M) : (algebra_map R S x) ∈ algebra_map_submonoid S M := set.mem_image_of_mem (algebra_map R S) x.2 end semiring section comm_semiring variables [comm_semiring R] lemma mul_sub_algebra_map_commutes [ring A] [algebra R A] (x : A) (r : R) : x * (x - algebra_map R A r) = (x - algebra_map R A r) * x := by rw [mul_sub, ←commutes, sub_mul] lemma mul_sub_algebra_map_pow_commutes [ring A] [algebra R A] (x : A) (r : R) (n : ℕ) : x * (x - algebra_map R A r) ^ n = (x - algebra_map R A r) ^ n * x := begin induction n with n ih, { simp }, { rw [pow_succ, ←mul_assoc, mul_sub_algebra_map_commutes, mul_assoc, ih, ←mul_assoc] } end end comm_semiring section ring variables [comm_ring R] variables (R) /-- A `semiring` that is an `algebra` over a commutative ring carries a natural `ring` structure. See note [reducible non-instances]. -/ @[reducible] def semiring_to_ring [semiring A] [algebra R A] : ring A := { ..module.add_comm_monoid_to_add_comm_group R, ..(infer_instance : semiring A) } end ring end algebra namespace mul_opposite variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R Aᵐᵒᵖ := { to_ring_hom := (algebra_map R A).to_opposite $ λ x y, algebra.commutes _ _, smul_def' := λ c x, unop_injective $ by { dsimp, simp only [op_mul, algebra.smul_def, algebra.commutes, op_unop] }, commutes' := λ r, mul_opposite.rec $ λ x, by dsimp; simp only [← op_mul, algebra.commutes], .. mul_opposite.has_smul A R } @[simp] lemma algebra_map_apply (c : R) : algebra_map R Aᵐᵒᵖ c = op (algebra_map R A c) := rfl end mul_opposite namespace module variables (R : Type u) (M : Type v) [comm_semiring R] [add_comm_monoid M] [module R M] instance : algebra R (module.End R M) := algebra.of_module smul_mul_assoc (λ r f g, (smul_comm r f g).symm) lemma algebra_map_End_eq_smul_id (a : R) : (algebra_map R (End R M)) a = a • linear_map.id := rfl @[simp] lemma algebra_map_End_apply (a : R) (m : M) : (algebra_map R (End R M)) a m = a • m := rfl @[simp] lemma ker_algebra_map_End (K : Type u) (V : Type v) [field K] [add_comm_group V] [module K V] (a : K) (ha : a ≠ 0) : ((algebra_map K (End K V)) a).ker = ⊥ := linear_map.ker_smul _ _ ha end module set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B /-- `alg_hom_class F R A B` asserts `F` is a type of bundled algebra homomorphisms from `A` to `B`. -/ class alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*) (B : out_param Type*) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom_class F A B := (commutes : ∀ (f : F) (r : R), f (algebra_map R A r) = algebra_map R B r) -- `R` becomes a metavariable but that's fine because it's an `out_param` attribute [nolint dangerous_instance] alg_hom_class.to_ring_hom_class attribute [simp] alg_hom_class.commutes namespace alg_hom_class variables {R : Type*} {A : Type*} {B : Type*} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] @[priority 100] -- see Note [lower instance priority] instance {F : Type*} [alg_hom_class F R A B] : linear_map_class F R A B := { map_smulₛₗ := λ f r x, by simp only [algebra.smul_def, map_mul, commutes, ring_hom.id_apply], ..‹alg_hom_class F R A B› } end alg_hom_class namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) (λ _, A → B) := ⟨alg_hom.to_fun⟩ initialize_simps_projections alg_hom (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : A →ₐ[R] B) : f.to_fun = f := rfl instance : alg_hom_class (A →ₐ[R] B) R A B := { coe := to_fun, coe_injective' := λ f g h, by { cases f, cases g, congr' }, map_add := map_add', map_zero := map_zero', map_mul := map_mul', map_one := map_one', commutes := λ f, f.commutes' } instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl -- make the coercion the simp-normal form @[simp] lemma to_ring_hom_eq_coe (f : A →ₐ[R] B) : f.to_ring_hom = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl @[simp, norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl @[simp, norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_injective : @function.injective (A →ₐ[R] B) (A → B) coe_fn := fun_like.coe_injective theorem coe_fn_inj {φ₁ φ₂ : A →ₐ[R] B} : (φ₁ : A → B) = φ₂ ↔ φ₁ = φ₂ := fun_like.coe_fn_eq theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_injective $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective protected lemma congr_fun {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x := fun_like.congr_fun H x protected lemma congr_arg (φ : A →ₐ[R] B) {x y : A} (h : x = y) : φ x = φ y := fun_like.congr_arg φ h @[ext] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := fun_like.ext _ _ H theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := fun_like.ext_iff @[simp] theorem mk_coe {f : A →ₐ[R] B} (h₁ h₂ h₃ h₄ h₅) : (⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := ext $ λ _, rfl @[simp] theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes protected lemma map_add (r s : A) : φ (r + s) = φ r + φ s := map_add _ _ _ protected lemma map_zero : φ 0 = 0 := map_zero _ protected lemma map_mul (x y) : φ (x * y) = φ x * φ y := map_mul _ _ _ protected lemma map_one : φ 1 = 1 := map_one _ protected lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := map_pow _ _ _ @[simp] protected lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := map_smul _ _ _ protected lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (∑ x in s, f x) = ∑ x in s, φ (f x) := map_sum _ _ _ protected lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) : φ (f.sum g) = f.sum (λ i a, φ (g i a)) := map_finsupp_sum _ _ _ protected lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) := map_bit0 _ _ protected lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) := map_bit1 _ _ /-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/ def mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : A →ₐ[R] B := { to_fun := f, commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, h, f.map_one], .. f } @[simp] lemma coe_mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : ⇑(mk' f h) = f := rfl section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } @[simp] lemma coe_id : ⇑(alg_hom.id R A) = id := rfl @[simp] lemma id_to_ring_hom : (alg_hom.id R A : A →+* A) = ring_hom.id _ := rfl end lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma coe_comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl lemma comp_to_ring_hom (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂ : A →+* C) = (φ₁ : B →+* C).comp ↑φ₂ := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ[R] B := { to_fun := φ, map_add' := map_add _, map_smul' := map_smul _ } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A →ₗ[R] B)) := λ φ₁ φ₂ h, ext $ linear_map.congr_fun h @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl @[simp] lemma to_linear_map_id : to_linear_map (alg_hom.id R A) = linear_map.id := linear_map.ext $ λ _, rfl /-- Promote a `linear_map` to an `alg_hom` by supplying proofs about the behavior on `1` and `*`. -/ @[simps] def of_linear_map (f : A →ₗ[R] B) (map_one : f 1 = 1) (map_mul : ∀ x y, f (x * y) = f x * f y) : A →ₐ[R] B := { to_fun := f, map_one' := map_one, map_mul' := map_mul, commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, f.map_smul, map_one], .. f.to_add_monoid_hom } @[simp] lemma of_linear_map_to_linear_map (map_one) (map_mul) : of_linear_map φ.to_linear_map map_one map_mul = φ := by { ext, refl } @[simp] lemma to_linear_map_of_linear_map (f : A →ₗ[R] B) (map_one) (map_mul) : to_linear_map (of_linear_map f map_one map_mul) = f := by { ext, refl } @[simp] lemma of_linear_map_id (map_one) (map_mul) : of_linear_map linear_map.id map_one map_mul = alg_hom.id R A := ext $ λ _, rfl lemma map_smul_of_tower {R'} [has_smul R' A] [has_smul R' B] [linear_map.compatible_smul A B R' R] (r : R') (x : A) : φ (r • x) = r • φ x := φ.to_linear_map.map_smul_of_tower r x lemma map_list_prod (s : list A) : φ s.prod = (s.map φ).prod := φ.to_ring_hom.map_list_prod s section prod /-- First projection as `alg_hom`. -/ def fst : A × B →ₐ[R] A := { commutes' := λ r, rfl, .. ring_hom.fst A B} /-- Second projection as `alg_hom`. -/ def snd : A × B →ₐ[R] B := { commutes' := λ r, rfl, .. ring_hom.snd A B} end prod lemma algebra_map_eq_apply (f : A →ₐ[R] B) {y : R} {x : A} (h : algebra_map R A y = x) : algebra_map R B y = f x := h ▸ (f.commutes _).symm end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) protected lemma map_multiset_prod (s : multiset A) : φ s.prod = (s.map φ).prod := map_multiset_prod _ _ protected lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (∏ x in s, f x) = ∏ x in s, φ (f x) := map_prod _ _ _ protected lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) : φ (f.prod g) = f.prod (λ i a, φ (g i a)) := map_finsupp_prod _ _ _ end comm_semiring section ring variables [comm_semiring R] [ring A] [ring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) protected lemma map_neg (x) : φ (-x) = -φ x := map_neg _ _ protected lemma map_sub (x y) : φ (x - y) = φ x - φ y := map_sub _ _ _ @[simp] lemma map_int_cast (n : ℤ) : φ n = n := φ.to_ring_hom.map_int_cast n end ring section division_ring variables [comm_semiring R] [division_ring A] [division_ring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) @[simp] lemma map_inv (x) : φ (x⁻¹) = (φ x)⁻¹ := φ.to_ring_hom.map_inv x @[simp] lemma map_div (x y) : φ (x / y) = φ x / φ y := φ.to_ring_hom.map_div x y end division_ring end alg_hom @[simp] lemma rat.smul_one_eq_coe {A : Type*} [division_ring A] [algebra ℚ A] (m : ℚ) : m • (1 : A) = ↑m := by rw [algebra.smul_def, mul_one, ring_hom.eq_rat_cast] set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' /-- `alg_equiv_class F R A B` states that `F` is a type of algebra structure preserving equivalences. You should extend this class when you extend `alg_equiv`. -/ class alg_equiv_class (F : Type*) (R A B : out_param Type*) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_equiv_class F A B := (commutes : ∀ (f : F) (r : R), f (algebra_map R A r) = algebra_map R B r) -- `R` becomes a metavariable but that's fine because it's an `out_param` attribute [nolint dangerous_instance] alg_equiv_class.to_ring_equiv_class namespace alg_equiv_class @[priority 100] -- See note [lower instance priority] instance to_alg_hom_class (F R A B : Type*) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] [h : alg_equiv_class F R A B] : alg_hom_class F R A B := { coe := coe_fn, coe_injective' := fun_like.coe_injective, map_zero := map_zero, map_one := map_one, .. h } end alg_equiv_class namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} section semiring variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] variables (e : A₁ ≃ₐ[R] A₂) instance : alg_equiv_class (A₁ ≃ₐ[R] A₂) R A₁ A₂ := { coe := to_fun, inv := inv_fun, coe_injective' := λ f g h₁ h₂, by { cases f, cases g, congr' }, map_add := map_add', map_mul := map_mul', commutes := commutes', left_inv := left_inv, right_inv := right_inv } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) (λ _, A₁ → A₂) := ⟨alg_equiv.to_fun⟩ @[ext] lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h protected lemma congr_arg {f : A₁ ≃ₐ[R] A₂} {x x' : A₁} : x = x' → f x = f x' := fun_like.congr_arg f protected lemma congr_fun {f g : A₁ ≃ₐ[R] A₂} (h : f = g) (x : A₁) : f x = g x := fun_like.congr_fun h x protected lemma ext_iff {f g : A₁ ≃ₐ[R] A₂} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) := fun_like.coe_injective instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩ @[simp] lemma coe_mk {to_fun inv_fun left_inv right_inv map_mul map_add commutes} : ⇑(⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) = to_fun := rfl @[simp] theorem mk_coe (e : A₁ ≃ₐ[R] A₂) (e' h₁ h₂ h₃ h₄ h₅) : (⟨e, e', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂) = e := ext $ λ _, rfl @[simp] lemma to_fun_eq_coe (e : A₁ ≃ₐ[R] A₂) : e.to_fun = e := rfl @[simp] lemma to_equiv_eq_coe : e.to_equiv = e := rfl @[simp] lemma to_ring_equiv_eq_coe : e.to_ring_equiv = e := rfl @[simp, norm_cast] lemma coe_ring_equiv : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl lemma coe_ring_equiv' : (e.to_ring_equiv : A₁ → A₂) = e := rfl lemma coe_ring_equiv_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ ≃+* A₂)) := λ e₁ e₂ h, ext $ ring_equiv.congr_fun h protected lemma map_add : ∀ x y, e (x + y) = e x + e y := map_add e protected lemma map_zero : e 0 = 0 := map_zero e protected lemma map_mul : ∀ x y, e (x * y) = (e x) * (e y) := map_mul e protected lemma map_one : e 1 = 1 := map_one e @[simp] lemma commutes : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r := e.commutes' @[simp] lemma map_smul (r : R) (x : A₁) : e (r • x) = r • e x := by simp only [algebra.smul_def, map_mul, commutes] lemma map_sum {ι : Type*} (f : ι → A₁) (s : finset ι) : e (∑ x in s, f x) = ∑ x in s, e (f x) := e.to_add_equiv.map_sum f s lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) : e (f.sum g) = f.sum (λ i b, e (g i b)) := e.map_sum _ _ /-- Interpret an algebra equivalence as an algebra homomorphism. This definition is included for symmetry with the other `to_*_hom` projections. The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/ def to_alg_hom : A₁ →ₐ[R] A₂ := { map_one' := e.map_one, map_zero' := e.map_zero, ..e } instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) := ⟨to_alg_hom⟩ @[simp] lemma to_alg_hom_eq_coe : e.to_alg_hom = e := rfl @[simp, norm_cast] lemma coe_alg_hom : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e := rfl lemma coe_alg_hom_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ →ₐ[R] A₂)) := λ e₁ e₂ h, ext $ alg_hom.congr_fun h /-- The two paths coercion can take to a `ring_hom` are equivalent -/ lemma coe_ring_hom_commutes : ((e : A₁ →ₐ[R] A₂) : A₁ →+* A₂) = ((e : A₁ ≃+* A₂) : A₁ →+* A₂) := rfl protected lemma map_pow : ∀ (x : A₁) (n : ℕ), e (x ^ n) = (e x) ^ n := map_pow _ protected lemma injective : function.injective e := equiv_like.injective e protected lemma surjective : function.surjective e := equiv_like.surjective e protected lemma bijective : function.bijective e := equiv_like.bijective e /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := {commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)} instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨refl⟩ @[simp] lemma refl_to_alg_hom : ↑(refl : A₁ ≃ₐ[R] A₁) = alg_hom.id R A₁ := rfl @[simp] lemma coe_refl : ⇑(refl : A₁ ≃ₐ[R] A₁) = id := rfl /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ := { commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } /-- See Note [custom simps projection] -/ def simps.symm_apply (e : A₁ ≃ₐ[R] A₂) : A₂ → A₁ := e.symm initialize_simps_projections alg_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm {e : A₁ ≃ₐ[R] A₂} : e.inv_fun = e.symm := rfl @[simp] lemma symm_symm (e : A₁ ≃ₐ[R] A₂) : e.symm.symm = e := by { ext, refl, } lemma symm_bijective : function.bijective (symm : (A₁ ≃ₐ[R] A₂) → (A₂ ≃ₐ[R] A₁)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (e : A₁ ≃ₐ[R] A₂) (f h₁ h₂ h₃ h₄ h₅) : (⟨f, e, h₁, h₂, h₃, h₄, h₅⟩ : A₂ ≃ₐ[R] A₁) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] theorem symm_mk (f f') (h₁ h₂ h₃ h₄ h₅) : (⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm = { to_fun := f', inv_fun := f, ..(⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm } := rfl @[simp] theorem refl_symm : (alg_equiv.refl : A₁ ≃ₐ[R] A₁).symm = alg_equiv.refl := rfl /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp] lemma symm_trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₃) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl @[simp] lemma coe_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[simp] lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl @[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ := by { ext, simp } @[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ := by { ext, simp } theorem left_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.left_inverse e.symm e := e.left_inv theorem right_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.right_inverse e.symm e := e.right_inv /-- If `A₁` is equivalent to `A₁'` and `A₂` is equivalent to `A₂'`, then the type of maps `A₁ →ₐ[R] A₂` is equivalent to the type of maps `A₁' →ₐ[R] A₂'`. -/ def arrow_congr {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (A₁ →ₐ[R] A₂) ≃ (A₁' →ₐ[R] A₂') := { to_fun := λ f, (e₂.to_alg_hom.comp f).comp e₁.symm.to_alg_hom, inv_fun := λ f, (e₂.symm.to_alg_hom.comp f).comp e₁.to_alg_hom, left_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, symm_comp], simp only [←alg_hom.comp_assoc, symm_comp, alg_hom.id_comp, alg_hom.comp_id] }, right_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, comp_symm], simp only [←alg_hom.comp_assoc, comp_symm, alg_hom.id_comp, alg_hom.comp_id] } } lemma arrow_congr_comp {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃'] [algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') (e₃ : A₃ ≃ₐ[R] A₃') (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [arrow_congr, equiv.coe_fn_mk, alg_hom.comp_apply], congr, exact (e₂.symm_apply_apply _).symm } @[simp] lemma arrow_congr_refl : arrow_congr alg_equiv.refl alg_equiv.refl = equiv.refl (A₁ →ₐ[R] A₂) := by { ext, refl } @[simp] lemma arrow_congr_trans {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃'] [algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₂) (e₁' : A₁' ≃ₐ[R] A₂') (e₂ : A₂ ≃ₐ[R] A₃) (e₂' : A₂' ≃ₐ[R] A₃') : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := by { ext, refl } @[simp] lemma arrow_congr_symm {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := by { ext, refl } /-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/ def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂) (h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ := { to_fun := f, inv_fun := g, left_inv := alg_hom.ext_iff.1 h₂, right_inv := alg_hom.ext_iff.1 h₁, ..f } lemma coe_alg_hom_of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : ↑(of_alg_hom f g h₁ h₂) = f := alg_hom.ext $ λ _, rfl @[simp] lemma of_alg_hom_coe_alg_hom (f : A₁ ≃ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : of_alg_hom ↑f g h₁ h₂ = f := ext $ λ _, rfl lemma of_alg_hom_symm (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : (of_alg_hom f g h₁ h₂).symm = of_alg_hom g f h₂ h₁ := rfl /-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/ noncomputable def of_bijective (f : A₁ →ₐ[R] A₂) (hf : function.bijective f) : A₁ ≃ₐ[R] A₂ := { .. ring_equiv.of_bijective (f : A₁ →+* A₂) hf, .. f } @[simp] lemma coe_of_bijective {f : A₁ →ₐ[R] A₂} {hf : function.bijective f} : (alg_equiv.of_bijective f hf : A₁ → A₂) = f := rfl lemma of_bijective_apply {f : A₁ →ₐ[R] A₂} {hf : function.bijective f} (a : A₁) : (alg_equiv.of_bijective f hf) a = f a := rfl /-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/ @[simps apply] def to_linear_equiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ := { to_fun := e, map_smul' := e.map_smul, inv_fun := e.symm, .. e } @[simp] lemma to_linear_equiv_refl : (alg_equiv.refl : A₁ ≃ₐ[R] A₁).to_linear_equiv = linear_equiv.refl R A₁ := rfl @[simp] lemma to_linear_equiv_symm (e : A₁ ≃ₐ[R] A₂) : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl @[simp] lemma to_linear_equiv_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := rfl theorem to_linear_equiv_injective : function.injective (to_linear_equiv : _ → (A₁ ≃ₗ[R] A₂)) := λ e₁ e₂ h, ext $ linear_equiv.congr_fun h /-- Interpret an algebra equivalence as a linear map. -/ def to_linear_map : A₁ →ₗ[R] A₂ := e.to_alg_hom.to_linear_map @[simp] lemma to_alg_hom_to_linear_map : (e : A₁ →ₐ[R] A₂).to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_equiv_to_linear_map : e.to_linear_equiv.to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_map_apply (x : A₁) : e.to_linear_map x = e x := rfl theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A₁ →ₗ[R] A₂)) := λ e₁ e₂ h, ext $ linear_map.congr_fun h @[simp] lemma trans_to_linear_map (f : A₁ ≃ₐ[R] A₂) (g : A₂ ≃ₐ[R] A₃) : (f.trans g).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl section of_linear_equiv variables (l : A₁ ≃ₗ[R] A₂) (map_mul : ∀ x y : A₁, l (x * y) = l x * l y) (commutes : ∀ r : R, l (algebra_map R A₁ r) = algebra_map R A₂ r) /-- Upgrade a linear equivalence to an algebra equivalence, given that it distributes over multiplication and action of scalars. -/ @[simps apply] def of_linear_equiv : A₁ ≃ₐ[R] A₂ := { to_fun := l, inv_fun := l.symm, map_mul' := map_mul, commutes' := commutes, ..l } @[simp] lemma of_linear_equiv_symm : (of_linear_equiv l map_mul commutes).symm = of_linear_equiv l.symm ((of_linear_equiv l map_mul commutes).symm.map_mul) ((of_linear_equiv l map_mul commutes).symm.commutes) := rfl @[simp] lemma of_linear_equiv_to_linear_equiv (map_mul) (commutes) : of_linear_equiv e.to_linear_equiv map_mul commutes = e := by { ext, refl } @[simp] lemma to_linear_equiv_of_linear_equiv : to_linear_equiv (of_linear_equiv l map_mul commutes) = l := by { ext, refl } end of_linear_equiv @[simps mul one {attrs := []}] instance aut : group (A₁ ≃ₐ[R] A₁) := { mul := λ ϕ ψ, ψ.trans ϕ, mul_assoc := λ ϕ ψ χ, rfl, one := refl, one_mul := λ ϕ, ext $ λ x, rfl, mul_one := λ ϕ, ext $ λ x, rfl, inv := symm, mul_left_inv := λ ϕ, ext $ symm_apply_apply ϕ } @[simp] lemma one_apply (x : A₁) : (1 : A₁ ≃ₐ[R] A₁) x = x := rfl @[simp] lemma mul_apply (e₁ e₂ : A₁ ≃ₐ[R] A₁) (x : A₁) : (e₁ * e₂) x = e₁ (e₂ x) := rfl /-- An algebra isomorphism induces a group isomorphism between automorphism groups -/ @[simps apply] def aut_congr (ϕ : A₁ ≃ₐ[R] A₂) : (A₁ ≃ₐ[R] A₁) ≃* (A₂ ≃ₐ[R] A₂) := { to_fun := λ ψ, ϕ.symm.trans (ψ.trans ϕ), inv_fun := λ ψ, ϕ.trans (ψ.trans ϕ.symm), left_inv := λ ψ, by { ext, simp_rw [trans_apply, symm_apply_apply] }, right_inv := λ ψ, by { ext, simp_rw [trans_apply, apply_symm_apply] }, map_mul' := λ ψ χ, by { ext, simp only [mul_apply, trans_apply, symm_apply_apply] } } @[simp] lemma aut_congr_refl : aut_congr (alg_equiv.refl) = mul_equiv.refl (A₁ ≃ₐ[R] A₁) := by { ext, refl } @[simp] lemma aut_congr_symm (ϕ : A₁ ≃ₐ[R] A₂) : (aut_congr ϕ).symm = aut_congr ϕ.symm := rfl @[simp] lemma aut_congr_trans (ϕ : A₁ ≃ₐ[R] A₂) (ψ : A₂ ≃ₐ[R] A₃) : (aut_congr ϕ).trans (aut_congr ψ) = aut_congr (ϕ.trans ψ) := rfl /-- The tautological action by `A₁ ≃ₐ[R] A₁` on `A₁`. This generalizes `function.End.apply_mul_action`. -/ instance apply_mul_semiring_action : mul_semiring_action (A₁ ≃ₐ[R] A₁) A₁ := { smul := ($), smul_zero := alg_equiv.map_zero, smul_add := alg_equiv.map_add, smul_one := alg_equiv.map_one, smul_mul := alg_equiv.map_mul, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : A₁ ≃ₐ[R] A₁) (a : A₁) : f • a = f a := rfl instance apply_has_faithful_smul : has_faithful_smul (A₁ ≃ₐ[R] A₁) A₁ := ⟨λ _ _, alg_equiv.ext⟩ instance apply_smul_comm_class : smul_comm_class R (A₁ ≃ₐ[R] A₁) A₁ := { smul_comm := λ r e a, (e.map_smul r a).symm } instance apply_smul_comm_class' : smul_comm_class (A₁ ≃ₐ[R] A₁) R A₁ := { smul_comm := λ e r a, (e.map_smul r a) } @[simp] lemma algebra_map_eq_apply (e : A₁ ≃ₐ[R] A₂) {y : R} {x : A₁} : (algebra_map R A₂ y = e x) ↔ (algebra_map R A₁ y = x) := ⟨λ h, by simpa using e.symm.to_alg_hom.algebra_map_eq_apply h, λ h, e.to_alg_hom.algebra_map_eq_apply h⟩ end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A₁] [comm_semiring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) lemma map_prod {ι : Type*} (f : ι → A₁) (s : finset ι) : e (∏ x in s, f x) = ∏ x in s, e (f x) := map_prod _ f s lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) : e (f.prod g) = f.prod (λ i a, e (g i a)) := map_finsupp_prod _ f g end comm_semiring section ring variables [comm_semiring R] [ring A₁] [ring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) protected lemma map_neg (x) : e (-x) = -e x := map_neg e x protected lemma map_sub (x y) : e (x - y) = e x - e y := map_sub e x y end ring section division_ring variables [comm_ring R] [division_ring A₁] [division_ring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) @[simp] lemma map_inv (x) : e (x⁻¹) = (e x)⁻¹ := e.to_alg_hom.map_inv x @[simp] lemma map_div (x y) : e (x / y) = e x / e y := e.to_alg_hom.map_div x y end division_ring end alg_equiv namespace mul_semiring_action variables {M G : Type*} (R A : Type*) [comm_semiring R] [semiring A] [algebra R A] section variables [monoid M] [mul_semiring_action M A] [smul_comm_class M R A] /-- Each element of the monoid defines a algebra homomorphism. This is a stronger version of `mul_semiring_action.to_ring_hom` and `distrib_mul_action.to_linear_map`. -/ @[simps] def to_alg_hom (m : M) : A →ₐ[R] A := alg_hom.mk' (mul_semiring_action.to_ring_hom _ _ m) (smul_comm _) theorem to_alg_hom_injective [has_faithful_smul M A] : function.injective (mul_semiring_action.to_alg_hom R A : M → A →ₐ[R] A) := λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_hom.ext_iff.1 h r end section variables [group G] [mul_semiring_action G A] [smul_comm_class G R A] /-- Each element of the group defines a algebra equivalence. This is a stronger version of `mul_semiring_action.to_ring_equiv` and `distrib_mul_action.to_linear_equiv`. -/ @[simps] def to_alg_equiv (g : G) : A ≃ₐ[R] A := { .. mul_semiring_action.to_ring_equiv _ _ g, .. mul_semiring_action.to_alg_hom R A g } theorem to_alg_equiv_injective [has_faithful_smul G A] : function.injective (mul_semiring_action.to_alg_equiv R A : G → A ≃ₐ[R] A) := λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_equiv.ext_iff.1 h r end end mul_semiring_action section nat variables {R : Type*} [semiring R] -- Lower the priority so that `algebra.id` is picked most of the time when working with -- `ℕ`-algebras. This is only an issue since `algebra.id` and `algebra_nat` are not yet defeq. -- TODO: fix this by adding an `of_nat` field to semirings. /-- Semiring ⥤ ℕ-Alg -/ @[priority 99] instance algebra_nat : algebra ℕ R := { commutes' := nat.cast_commute, smul_def' := λ _ _, nsmul_eq_mul _ _, to_ring_hom := nat.cast_ring_hom R } instance nat_algebra_subsingleton : subsingleton (algebra ℕ R) := ⟨λ P Q, by { ext, simp, }⟩ end nat namespace ring_hom variables {R S : Type*} /-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/ def to_nat_alg_hom [semiring R] [semiring S] (f : R →+* S) : R →ₐ[ℕ] S := { to_fun := f, commutes' := λ n, by simp, .. f } /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def to_int_alg_hom [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ n, by simp, .. f } -- note that `R`, `S` could be `semiring`s but this is useless mathematically speaking - -- a ℚ-algebra is a ring. furthermore, this change probably slows down elaboration. @[simp] lemma map_rat_algebra_map [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) (r : ℚ) : f (algebra_map ℚ R r) = algebra_map ℚ S r := ring_hom.ext_iff.1 (subsingleton.elim (f.comp (algebra_map ℚ R)) (algebra_map ℚ S)) r /-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. This actually yields an equivalence, see `ring_hom.equiv_rat_alg_hom`. -/ def to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) : R →ₐ[ℚ] S := { commutes' := f.map_rat_algebra_map, .. f } @[simp] lemma to_rat_alg_hom_to_ring_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) : ↑f.to_rat_alg_hom = f := ring_hom.ext $ λ x, rfl end ring_hom section variables {R S : Type*} @[simp] lemma alg_hom.to_ring_hom_to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →ₐ[ℚ] S) : (f : R →+* S).to_rat_alg_hom = f := alg_hom.ext $ λ x, rfl /-- The equivalence between `ring_hom` and `ℚ`-algebra homomorphisms. -/ @[simps] def ring_hom.equiv_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] : (R →+* S) ≃ (R →ₐ[ℚ] S) := { to_fun := ring_hom.to_rat_alg_hom, inv_fun := alg_hom.to_ring_hom, left_inv := ring_hom.to_rat_alg_hom_to_ring_hom, right_inv := alg_hom.to_ring_hom_to_rat_alg_hom, } end section rat instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α := (rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x @[simp] theorem algebra_map_rat_rat : algebra_map ℚ ℚ = ring_hom.id ℚ := subsingleton.elim _ _ -- TODO[gh-6025]: make this an instance once safe to do so lemma algebra_rat_subsingleton {α} [semiring α] : subsingleton (algebra ℚ α) := ⟨λ x y, algebra.algebra_ext x y $ ring_hom.congr_fun $ subsingleton.elim _ _⟩ end rat namespace algebra open module variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra section int variables (R : Type*) [ring R] -- Lower the priority so that `algebra.id` is picked most of the time when working with -- `ℤ`-algebras. This is only an issue since `algebra.id ℤ` and `algebra_int ℤ` are not yet defeq. -- TODO: fix this by adding an `of_int` field to rings. /-- Ring ⥤ ℤ-Alg -/ @[priority 99] instance algebra_int : algebra ℤ R := { commutes' := int.cast_commute, smul_def' := λ _ _, zsmul_eq_mul _ _, to_ring_hom := int.cast_ring_hom R } /-- A special case of `ring_hom.eq_int_cast'` that happens to be true definitionally -/ @[simp] lemma algebra_map_int_eq : algebra_map ℤ R = int.cast_ring_hom R := rfl variables {R} instance int_algebra_subsingleton : subsingleton (algebra ℤ R) := ⟨λ P Q, by { ext, simp, }⟩ end int namespace no_zero_smul_divisors variables {R A : Type*} open algebra /-- If `algebra_map R A` is injective and `A` has no zero divisors, `R`-multiples in `A` are zero only if one of the factors is zero. Cannot be an instance because there is no `injective (algebra_map R A)` typeclass. -/ lemma of_algebra_map_injective [comm_semiring R] [semiring A] [algebra R A] [no_zero_divisors A] (h : function.injective (algebra_map R A)) : no_zero_smul_divisors R A := ⟨λ c x hcx, (mul_eq_zero.mp ((smul_def c x).symm.trans hcx)).imp_left (map_eq_zero_iff (algebra_map R A) h).mp⟩ variables (R A) lemma algebra_map_injective [comm_ring R] [ring A] [nontrivial A] [algebra R A] [no_zero_smul_divisors R A] : function.injective (algebra_map R A) := suffices function.injective (λ (c : R), c • (1 : A)), by { convert this, ext, rw [algebra.smul_def, mul_one] }, smul_left_injective R one_ne_zero variables {R A} lemma iff_algebra_map_injective [comm_ring R] [ring A] [is_domain A] [algebra R A] : no_zero_smul_divisors R A ↔ function.injective (algebra_map R A) := ⟨@@no_zero_smul_divisors.algebra_map_injective R A _ _ _ _, no_zero_smul_divisors.of_algebra_map_injective⟩ @[priority 100] -- see note [lower instance priority] instance char_zero.no_zero_smul_divisors_nat [semiring R] [no_zero_divisors R] [char_zero R] : no_zero_smul_divisors ℕ R := no_zero_smul_divisors.of_algebra_map_injective $ (algebra_map ℕ R).injective_nat @[priority 100] -- see note [lower instance priority] instance char_zero.no_zero_smul_divisors_int [ring R] [no_zero_divisors R] [char_zero R] : no_zero_smul_divisors ℤ R := no_zero_smul_divisors.of_algebra_map_injective $ (algebra_map ℤ R).injective_int section field variables [field R] [semiring A] [algebra R A] @[priority 100] -- see note [lower instance priority] instance algebra.no_zero_smul_divisors [nontrivial A] [no_zero_divisors A] : no_zero_smul_divisors R A := no_zero_smul_divisors.of_algebra_map_injective (algebra_map R A).injective end field end no_zero_smul_divisors /-! The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra. We couldn't set this up back in `algebra.pi_instances` because this file imports it. -/ namespace pi variable {I : Type u} -- The indexing type variable {R : Type*} -- The scalar type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) variables (I f) instance algebra {r : comm_semiring R} [s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] : algebra R (Π i : I, f i) := { commutes' := λ a f, begin ext, simp [algebra.commutes], end, smul_def' := λ a f, begin ext, simp [algebra.smul_def], end, ..(pi.ring_hom (λ i, algebra_map R (f i)) : R →+* Π i : I, f i) } @[simp] lemma algebra_map_apply {r : comm_semiring R} [s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] (a : R) (i : I) : algebra_map R (Π i, f i) a i = algebra_map R (f i) a := rfl -- One could also build a `Π i, R i`-algebra structure on `Π i, A i`, -- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful. variables {I} (R) (f) /-- `function.eval` as an `alg_hom`. The name matches `pi.eval_ring_hom`, `pi.eval_monoid_hom`, etc. -/ @[simps] def eval_alg_hom {r : comm_semiring R} [Π i, semiring (f i)] [Π i, algebra R (f i)] (i : I) : (Π i, f i) →ₐ[R] f i := { to_fun := λ f, f i, commutes' := λ r, rfl, .. pi.eval_ring_hom f i} variables (A B : Type*) [comm_semiring R] [semiring B] [algebra R B] /-- `function.const` as an `alg_hom`. The name matches `pi.const_ring_hom`, `pi.const_monoid_hom`, etc. -/ @[simps] def const_alg_hom : B →ₐ[R] (A → B) := { to_fun := function.const _, commutes' := λ r, rfl, .. pi.const_ring_hom A B} /-- When `R` is commutative and permits an `algebra_map`, `pi.const_ring_hom` is equal to that map. -/ @[simp] lemma const_ring_hom_eq_algebra_map : const_ring_hom A R = algebra_map R (A → R) := rfl @[simp] lemma const_alg_hom_eq_algebra_of_id : const_alg_hom R A R = algebra.of_id R (A → R) := rfl end pi /-- A special case of `pi.algebra` for non-dependent types. Lean struggles to elaborate definitions elsewhere in the library without this, -/ instance function.algebra {R : Type*} (I : Type*) (A : Type*) [comm_semiring R] [semiring A] [algebra R A] : algebra R (I → A) := pi.algebra _ _ namespace alg_equiv /-- A family of algebra equivalences `Π j, (A₁ j ≃ₐ A₂ j)` generates a multiplicative equivalence between `Π j, A₁ j` and `Π j, A₂ j`. This is the `alg_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `alg_equiv.arrow_congr`. -/ @[simps apply] def Pi_congr_right {R ι : Type*} {A₁ A₂ : ι → Type*} [comm_semiring R] [Π i, semiring (A₁ i)] [Π i, semiring (A₂ i)] [Π i, algebra R (A₁ i)] [Π i, algebra R (A₂ i)] (e : Π i, A₁ i ≃ₐ[R] A₂ i) : (Π i, A₁ i) ≃ₐ[R] Π i, A₂ i := { to_fun := λ x j, e j (x j), inv_fun := λ x j, (e j).symm (x j), commutes' := λ r, by { ext i, simp }, .. @ring_equiv.Pi_congr_right ι A₁ A₂ _ _ (λ i, (e i).to_ring_equiv) } @[simp] lemma Pi_congr_right_refl {R ι : Type*} {A : ι → Type*} [comm_semiring R] [Π i, semiring (A i)] [Π i, algebra R (A i)] : Pi_congr_right (λ i, (alg_equiv.refl : A i ≃ₐ[R] A i)) = alg_equiv.refl := rfl @[simp] lemma Pi_congr_right_symm {R ι : Type*} {A₁ A₂ : ι → Type*} [comm_semiring R] [Π i, semiring (A₁ i)] [Π i, semiring (A₂ i)] [Π i, algebra R (A₁ i)] [Π i, algebra R (A₂ i)] (e : Π i, A₁ i ≃ₐ[R] A₂ i) : (Pi_congr_right e).symm = (Pi_congr_right $ λ i, (e i).symm) := rfl @[simp] lemma Pi_congr_right_trans {R ι : Type*} {A₁ A₂ A₃ : ι → Type*} [comm_semiring R] [Π i, semiring (A₁ i)] [Π i, semiring (A₂ i)] [Π i, semiring (A₃ i)] [Π i, algebra R (A₁ i)] [Π i, algebra R (A₂ i)] [Π i, algebra R (A₃ i)] (e₁ : Π i, A₁ i ≃ₐ[R] A₂ i) (e₂ : Π i, A₂ i ≃ₐ[R] A₃ i) : (Pi_congr_right e₁).trans (Pi_congr_right e₂) = (Pi_congr_right $ λ i, (e₁ i).trans (e₂ i)) := rfl end alg_equiv section is_scalar_tower variables {R : Type*} [comm_semiring R] variables (A : Type*) [semiring A] [algebra R A] variables {M : Type*} [add_comm_monoid M] [module A M] [module R M] [is_scalar_tower R A M] variables {N : Type*} [add_comm_monoid N] [module A N] [module R N] [is_scalar_tower R A N] lemma algebra_compatible_smul (r : R) (m : M) : r • m = ((algebra_map R A) r) • m := by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul] @[simp] lemma algebra_map_smul (r : R) (m : M) : ((algebra_map R A) r) • m = r • m := (algebra_compatible_smul A r m).symm lemma no_zero_smul_divisors.trans (R A M : Type*) [comm_ring R] [ring A] [is_domain A] [algebra R A] [add_comm_group M] [module R M] [module A M] [is_scalar_tower R A M] [no_zero_smul_divisors R A] [no_zero_smul_divisors A M] : no_zero_smul_divisors R M := begin refine ⟨λ r m h, _⟩, rw [algebra_compatible_smul A r m] at h, cases smul_eq_zero.1 h with H H, { have : function.injective (algebra_map R A) := no_zero_smul_divisors.iff_algebra_map_injective.1 infer_instance, left, exact (injective_iff_map_eq_zero _).1 this _ H }, { right, exact H } end variable {A} @[priority 100] -- see Note [lower instance priority] instance is_scalar_tower.to_smul_comm_class : smul_comm_class R A M := ⟨λ r a m, by rw [algebra_compatible_smul A r (a • m), smul_smul, algebra.commutes, mul_smul, ←algebra_compatible_smul]⟩ @[priority 100] -- see Note [lower instance priority] instance is_scalar_tower.to_smul_comm_class' : smul_comm_class A R M := smul_comm_class.symm _ _ _ lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a • r • m = r • a • m := smul_comm _ _ _ namespace linear_map instance coe_is_scalar_tower : has_coe (M →ₗ[A] N) (M →ₗ[R] N) := ⟨restrict_scalars R⟩ variables (R) {A M N} @[simp, norm_cast squash] lemma coe_restrict_scalars_eq_coe (f : M →ₗ[A] N) : (f.restrict_scalars R : M → N) = f := rfl @[simp, norm_cast squash] lemma coe_coe_is_scalar_tower (f : M →ₗ[A] N) : ((f : M →ₗ[R] N) : M → N) = f := rfl /-- `A`-linearly coerce a `R`-linear map from `M` to `A` to a function, given an algebra `A` over a commutative semiring `R` and `M` a module over `R`. -/ def lto_fun (R : Type u) (M : Type v) (A : Type w) [comm_semiring R] [add_comm_monoid M] [module R M] [comm_ring A] [algebra R A] : (M →ₗ[R] A) →ₗ[A] (M → A) := { to_fun := linear_map.to_fun, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } end linear_map end is_scalar_tower /-! TODO: The following lemmas no longer involve `algebra` at all, and could be moved closer to `algebra/module/submodule.lean`. Currently this is tricky because `ker`, `range`, `⊤`, and `⊥` are all defined in `linear_algebra/basic.lean`. -/ section module open module variables (R S M N : Type*) [semiring R] [semiring S] [has_smul R S] variables [add_comm_monoid M] [module R M] [module S M] [is_scalar_tower R S M] variables [add_comm_monoid N] [module R N] [module S N] [is_scalar_tower R S N] variables {S M N} @[simp] lemma linear_map.ker_restrict_scalars (f : M →ₗ[S] N) : (f.restrict_scalars R).ker = f.ker.restrict_scalars R := rfl end module namespace submodule variables (R A M : Type*) variables [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] variables [module R M] [module A M] [is_scalar_tower R A M] /-- If `A` is an `R`-algebra such that the induced morhpsim `R →+* A` is surjective, then the `R`-module generated by a set `X` equals the `A`-module generated by `X`. -/ lemma span_eq_restrict_scalars (X : set M) (hsur : function.surjective (algebra_map R A)) : span R X = restrict_scalars R (span A X) := begin apply (span_le_restrict_scalars R A X).antisymm (λ m hm, _), refine span_induction hm subset_span (zero_mem _) (λ _ _, add_mem) (λ a m hm, _), obtain ⟨r, rfl⟩ := hsur a, simpa [algebra_map_smul] using smul_mem _ r hm end end submodule namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {I : Type*} variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] /-- `R`-algebra homomorphism between the function spaces `I → A` and `I → B`, induced by an `R`-algebra homomorphism `f` between `A` and `B`. -/ @[simps] protected def comp_left (f : A →ₐ[R] B) (I : Type*) : (I → A) →ₐ[R] (I → B) := { to_fun := λ h, f ∘ h, commutes' := λ c, by { ext, exact f.commutes' c }, .. f.to_ring_hom.comp_left I } end alg_hom example {R A} [comm_semiring R] [semiring A] [module R A] [smul_comm_class R A A] [is_scalar_tower R A A] : algebra R A := algebra.of_module smul_mul_assoc mul_smul_comm
c457c8e009bb976b1e315fc60a14888d7d8f7902
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/add_torsor.lean
1f4ca2104496581a85434d4152b183ca872e7d81
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
13,754
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov. -/ import algebra.group.prod import algebra.group.type_tags import algebra.pi_instances import data.equiv.basic /-! # Torsors of additive group actions This file defines torsors of additive group actions. ## Notations The group elements are referred to as acting on points. This file defines the notation `+ᵥ` for adding a group element to a point and `-ᵥ` for subtracting two points to produce a group element. ## Implementation notes Affine spaces are the motivating example of torsors of additive group actions. It may be appropriate to refactor in terms of the general definition of group actions, via `to_additive`, when there is a use for multiplicative torsors (currently mathlib only develops the theory of group actions for multiplicative group actions). The variable `G` is an explicit rather than implicit argument to lemmas because otherwise the elaborator sometimes has problems inferring appropriate types and type class instances. ## References * https://en.wikipedia.org/wiki/Principal_homogeneous_space * https://en.wikipedia.org/wiki/Affine_space -/ /-- Type class for the `+ᵥ` notation. -/ class has_vadd (G : Type*) (P : Type*) := (vadd : G → P → P) /-- Type class for the `-ᵥ` notation. -/ class has_vsub (G : Type*) (P : Type*) := (vsub : P → P → G) infix ` +ᵥ `:65 := has_vadd.vadd infix ` -ᵥ `:65 := has_vsub.vsub section prio set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true /-- Type class for additive monoid actions. -/ class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P := (zero_vadd' : ∀ p : P, (0 : G) +ᵥ p = p) (vadd_assoc' : ∀ (g1 g2 : G) (p : P), g1 +ᵥ (g2 +ᵥ p) = (g1 + g2) +ᵥ p) /-- An `add_torsor G P` gives a structure to the nonempty type `P`, acted on by an `add_group G` with a transitive and free action given by the `+ᵥ` operation and a corresponding subtraction given by the `-ᵥ` operation. In the case of a vector space, it is an affine space. -/ class add_torsor (G : Type*) (P : Type*) [add_group G] extends add_action G P, has_vsub G P := [nonempty : nonempty P] (vsub_vadd' : ∀ (p1 p2 : P), (p1 -ᵥ p2 : G) +ᵥ p2 = p1) (vadd_vsub' : ∀ (g : G) (p : P), g +ᵥ p -ᵥ p = g) end prio /-- An `add_group G` is a torsor for itself. -/ instance add_group_is_add_torsor (G : Type*) [add_group G] : add_torsor G G := { vadd := has_add.add, vsub := has_sub.sub, zero_vadd' := zero_add, vadd_assoc' := λ a b c, (add_assoc a b c).symm, vsub_vadd' := sub_add_cancel, vadd_vsub' := add_sub_cancel } /-- Simplify addition for a torsor for an `add_group G` over itself. -/ @[simp] lemma vadd_eq_add (G : Type*) [add_group G] (g1 g2 : G) : g1 +ᵥ g2 = g1 + g2 := rfl /-- Simplify subtraction for a torsor for an `add_group G` over itself. -/ @[simp] lemma vsub_eq_sub (G : Type*) [add_group G] (g1 g2 : G) : g1 -ᵥ g2 = g1 - g2 := rfl namespace add_action section general variables (G : Type*) {P : Type*} [add_monoid G] [A : add_action G P] include A /-- Adding the zero group element to a point gives the same point. -/ @[simp] lemma zero_vadd (p : P) : (0 : G) +ᵥ p = p := zero_vadd' p /-- Adding two group elements to a point produces the same result as adding their sum. -/ lemma vadd_assoc (g1 g2 : G) (p : P) : g1 +ᵥ (g2 +ᵥ p) = (g1 + g2) +ᵥ p := vadd_assoc' g1 g2 p end general section comm variables (G : Type*) {P : Type*} [add_comm_monoid G] [A : add_action G P] include A /-- Adding two group elements to a point produces the same result in either order. -/ lemma vadd_comm (p : P) (g1 g2 : G) : g1 +ᵥ (g2 +ᵥ p) = g2 +ᵥ (g1 +ᵥ p) := by rw [vadd_assoc, vadd_assoc, add_comm] end comm section group variables {G : Type*} {P : Type*} [add_group G] [A : add_action G P] include A /-- If the same group element added to two points produces equal results, those points are equal. -/ lemma vadd_left_cancel {p1 p2 : P} (g : G) (h : g +ᵥ p1 = g +ᵥ p2) : p1 = p2 := begin have h2 : -g +ᵥ (g +ᵥ p1) = -g +ᵥ (g +ᵥ p2), { rw h }, rwa [vadd_assoc, vadd_assoc, add_left_neg, zero_vadd, zero_vadd] at h2 end @[simp] lemma vadd_left_cancel_iff {p₁ p₂ : P} (g : G) : g +ᵥ p₁ = g +ᵥ p₂ ↔ p₁ = p₂ := ⟨vadd_left_cancel g, λ h, h ▸ rfl⟩ end group end add_action namespace add_torsor open add_action section general variables (G : Type*) {P : Type*} [add_group G] [T : add_torsor G P] include T /-- Adding the result of subtracting from another point produces that point. -/ @[simp] lemma vsub_vadd (p1 p2 : P) : (p1 -ᵥ p2 : G) +ᵥ p2 = p1 := vsub_vadd' p1 p2 /-- Adding a group element then subtracting the original point produces that group element. -/ @[simp] lemma vadd_vsub (g : G) (p : P) : g +ᵥ p -ᵥ p = g := vadd_vsub' g p variable {G} /-- If the same point added to two group elements produces equal results, those group elements are equal. -/ lemma vadd_right_cancel {g1 g2 : G} (p : P) (h : g1 +ᵥ p = g2 +ᵥ p) : g1 = g2 := by rw [←vadd_vsub G g1, h, vadd_vsub] @[simp] lemma vadd_right_cancel_iff {g1 g2 : G} (p : P) : g1 +ᵥ p = g2 +ᵥ p ↔ g1 = g2 := ⟨vadd_right_cancel p, λ h, h ▸ rfl⟩ /-- Adding a group element to a point, then subtracting another point, produces the same result as subtracting the points then adding the group element. -/ lemma vadd_vsub_assoc (g : G) (p1 p2 : P) : g +ᵥ p1 -ᵥ p2 = g + (p1 -ᵥ p2) := begin apply vadd_right_cancel p2, rw [vsub_vadd, ←vadd_assoc, vsub_vadd] end variable (G) /-- Subtracting a point from itself produces 0. -/ @[simp] lemma vsub_self (p : P) : p -ᵥ p = (0 : G) := by rw [←zero_add (p -ᵥ p : G), ←vadd_vsub_assoc, vadd_vsub] /-- If subtracting two points produces 0, they are equal. -/ lemma eq_of_vsub_eq_zero {p1 p2 : P} (h : p1 -ᵥ p2 = (0 : G)) : p1 = p2 := by rw [←vsub_vadd G p1 p2, h, zero_vadd] /-- Subtracting two points produces 0 if and only if they are equal. -/ @[simp] lemma vsub_eq_zero_iff_eq {p1 p2 : P} : p1 -ᵥ p2 = (0 : G) ↔ p1 = p2 := iff.intro (eq_of_vsub_eq_zero G) (λ h, h ▸ vsub_self G _) /-- Cancellation adding the results of two subtractions. -/ @[simp] lemma vsub_add_vsub_cancel (p1 p2 p3 : P) : (p1 -ᵥ p2 : G) + (p2 -ᵥ p3) = (p1 -ᵥ p3) := begin apply vadd_right_cancel p3, rw [←vadd_assoc, vsub_vadd, vsub_vadd, vsub_vadd] end /-- Subtracting two points in the reverse order produces the negation of subtracting them. -/ @[simp] lemma neg_vsub_eq_vsub_rev (p1 p2 : P) : -(p1 -ᵥ p2) = (p2 -ᵥ p1 : G) := begin refine neg_eq_of_add_eq_zero (vadd_right_cancel p1 _), rw [vsub_add_vsub_cancel, vsub_self], end /-- Subtracting the result of adding a group element produces the same result as subtracting the points and subtracting that group element. -/ lemma vsub_vadd_eq_vsub_sub (p1 p2 : P) (g : G) : p1 -ᵥ (g +ᵥ p2) = (p1 -ᵥ p2) - g := by rw [←add_right_inj (p2 -ᵥ p1 : G), vsub_add_vsub_cancel, ←neg_vsub_eq_vsub_rev, vadd_vsub, ←add_sub_assoc, ←neg_vsub_eq_vsub_rev, neg_add_self, zero_sub] /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_right (p1 p2 p3 : P) : (p1 -ᵥ p3 : G) - (p2 -ᵥ p3) = (p1 -ᵥ p2) := by rw [←vsub_vadd_eq_vsub_sub, vsub_vadd] /-- The pairwise differences of a set of points. -/ def vsub_set (s : set P) : set G := {g | ∃ x ∈ s, ∃ y ∈ s, g = x -ᵥ y} /-- `vsub_set` of an empty set. -/ @[simp] lemma vsub_set_empty : vsub_set G (∅ : set P) = ∅ := begin rw set.eq_empty_iff_forall_not_mem, rintros g ⟨p, hp, hg⟩, exact hp end /-- Each pairwise difference is in the `vsub_set`. -/ lemma vsub_mem_vsub_set {p1 p2 : P} {s : set P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ vsub_set G s := ⟨p1, hp1, p2, hp2, rfl⟩ /-- `vsub_set` is contained in `vsub_set` of a larger set. -/ lemma vsub_set_mono {s1 s2 : set P} (h : s1 ⊆ s2) : vsub_set G s1 ⊆ vsub_set G s2 := begin rintros v ⟨p1, hp1, p2, hp2, hv⟩, exact ⟨p1, set.mem_of_mem_of_subset hp1 h, p2, set.mem_of_mem_of_subset hp2 h, hv⟩ end @[simp] lemma vadd_vsub_vadd_cancel_right (v₁ v₂ : G) (p : P) : ((v₁ +ᵥ p) -ᵥ (v₂ +ᵥ p) : G) = v₁ - v₂ := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, vsub_self, add_zero] /-- If the same point subtracted from two points produces equal results, those points are equal. -/ lemma vsub_left_cancel {p1 p2 p : P} (h : (p1 -ᵥ p : G) = p2 -ᵥ p) : p1 = p2 := by rwa [←sub_eq_zero, vsub_sub_vsub_cancel_right, vsub_eq_zero_iff_eq] at h /-- The same point subtracted from two points produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_left_cancel_iff {p1 p2 p : P} : (p1 -ᵥ p : G) = p2 -ᵥ p ↔ p1 = p2 := ⟨vsub_left_cancel _, λ h, h ▸ rfl⟩ /-- If subtracting two points from the same point produces equal results, those points are equal. -/ lemma vsub_right_cancel {p1 p2 p : P} (h : (p -ᵥ p1 : G) = p -ᵥ p2) : p1 = p2 := begin have h2 : (p -ᵥ p2 : G) +ᵥ p1 = (p -ᵥ p1 : G) +ᵥ p1, { rw h }, conv_rhs at h2 { rw [vsub_vadd, ←vsub_vadd G p p2], }, rwa vadd_left_cancel_iff at h2 end /-- Subtracting two points from the same point produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_right_cancel_iff {p1 p2 p : P} : (p -ᵥ p1 : G) = p -ᵥ p2 ↔ p1 = p2 := ⟨vsub_right_cancel _, λ h, h ▸ rfl⟩ end general section comm variables (G : Type*) {P : Type*} [add_comm_group G] [add_torsor G P] /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_left (p1 p2 p3 : P) : (p3 -ᵥ p2 : G) - (p3 -ᵥ p1) = (p1 -ᵥ p2) := by rw [sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm, vsub_add_vsub_cancel] @[simp] lemma vadd_vsub_vadd_cancel_left (v : G) (p1 p2 : P) : ((v +ᵥ p1) -ᵥ (v +ᵥ p2) : G) = p1 -ᵥ p2 := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub_cancel'] end comm end add_torsor namespace prod variables {G : Type*} {P : Type*} {G' : Type*} {P' : Type*} [add_group G] [add_group G'] [add_torsor G P] [add_torsor G' P'] instance : add_torsor (G × G') (P × P') := { vadd := λ v p, (v.1 +ᵥ p.1, v.2 +ᵥ p.2), zero_vadd' := λ p, by simp, vadd_assoc' := by simp [add_action.vadd_assoc], vsub := λ p₁ p₂, (p₁.1 -ᵥ p₂.1, p₁.2 -ᵥ p₂.2), nonempty := @prod.nonempty _ _ (add_torsor.nonempty G) (add_torsor.nonempty G'), vsub_vadd' := λ p₁ p₂, show (p₁.1 -ᵥ p₂.1 +ᵥ p₂.1, _) = p₁, by simp, vadd_vsub' := λ v p, show (v.1 +ᵥ p.1 -ᵥ p.1, v.2 +ᵥ p.2 -ᵥ p.2) =v, by simp } @[simp] lemma fst_vadd (v : G × G') (p : P × P') : (v +ᵥ p).1 = v.1 +ᵥ p.1 := rfl @[simp] lemma snd_vadd (v : G × G') (p : P × P') : (v +ᵥ p).2 = v.2 +ᵥ p.2 := rfl @[simp] lemma mk_vadd_mk (v : G) (v' : G') (p : P) (p' : P') : (v, v') +ᵥ (p, p') = (v +ᵥ p, v' +ᵥ p') := rfl @[simp] lemma fst_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').1 = p₁.1 -ᵥ p₂.1 := rfl @[simp] lemma snd_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').2 = p₁.2 -ᵥ p₂.2 := rfl @[simp] lemma mk_vsub_mk (p₁ p₂ : P) (p₁' p₂' : P') : ((p₁, p₁') -ᵥ (p₂, p₂') : G × G') = (p₁ -ᵥ p₂, p₁' -ᵥ p₂') := rfl end prod namespace pi universes u v w variables {I : Type u} {fg : I → Type v} [∀ i, add_group (fg i)] {fp : I → Type w} open add_action add_torsor /-- A product of `add_torsor`s is an `add_torsor`. -/ instance [T : ∀ i, add_torsor (fg i) (fp i)] : add_torsor (Π i, fg i) (Π i, fp i) := { vadd := λ g p, λ i, g i +ᵥ p i, zero_vadd' := λ p, funext $ λ i, zero_vadd (fg i) (p i), vadd_assoc' := λ g₁ g₂ p, funext $ λ i, vadd_assoc (fg i) (g₁ i) (g₂ i) (p i), vsub := λ p₁ p₂, λ i, p₁ i -ᵥ p₂ i, nonempty := ⟨λ i, classical.choice (T i).nonempty⟩, vsub_vadd' := λ p₁ p₂, funext $ λ i, vsub_vadd (fg i) (p₁ i) (p₂ i), vadd_vsub' := λ g p, funext $ λ i, vadd_vsub (fg i) (g i) (p i), } /-- Addition in a product of `add_torsor`s. -/ @[simp] lemma vadd_apply [T : ∀ i, add_torsor (fg i) (fp i)] (x : Π i, fg i) (y : Π i, fp i) {i : I} : (x +ᵥ y) i = x i +ᵥ y i := rfl end pi namespace equiv variables (G : Type*) {P : Type*} [add_group G] [add_torsor G P] open add_action add_torsor /-- `v ↦ v +ᵥ p` as an equivalence. -/ def vadd_const (p : P) : G ≃ P := { to_fun := λ v, v +ᵥ p, inv_fun := λ p', p' -ᵥ p, left_inv := λ v, vadd_vsub _ _ _, right_inv := λ p', vsub_vadd _ _ _ } @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const G p) = λ v, v+ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const G p).symm = λ p', p' -ᵥ p := rfl variables {G} (P) /-- The permutation given by `p ↦ v +ᵥ p`. -/ def const_vadd (v : G) : equiv.perm P := { to_fun := (+ᵥ) v, inv_fun := (+ᵥ) (-v), left_inv := λ p, by simp [vadd_assoc], right_inv := λ p, by simp [vadd_assoc] } @[simp] lemma coe_const_vadd (v : G) : ⇑(const_vadd P v) = (+ᵥ) v := rfl variable (G) @[simp] lemma const_vadd_zero : const_vadd P (0:G) = 1 := ext $ zero_vadd G variable {G} @[simp] lemma const_vadd_add (v₁ v₂ : G) : const_vadd P (v₁ + v₂) = const_vadd P v₁ * const_vadd P v₂ := ext $ λ p, (vadd_assoc G v₁ v₂ p).symm /-- `equiv.const_vadd` as a homomorphism from `multiplicative G` to `equiv.perm P` -/ def const_vadd_hom : multiplicative G →* equiv.perm P := { to_fun := λ v, const_vadd P v.to_add, map_one' := const_vadd_zero G P, map_mul' := const_vadd_add P } end equiv
f14967ae792f642dcc74c79c7550cf3b79e831e0
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/group/prod.lean
c10d86f822fde5bb781e8f6e656e41384299a194
[ "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
16,794
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 measure_theory.constructions.prod import measure_theory.group.measure /-! # Measure theory in the product of groups In this file we show properties about measure theory in products of measurable groups and properties of iterated integrals in measurable groups. These lemmas show the uniqueness of left invariant measures on measurable groups, up to scaling. In this file we follow the proof and refer to the book *Measure Theory* by Paul Halmos. The idea of the proof is to use the translation invariance of measures to prove `μ(F) = c * μ(E)` for two sets `E` and `F`, where `c` is a constant that does not depend on `μ`. Let `e` and `f` be the characteristic functions of `E` and `F`. Assume that `μ` and `ν` are left-invariant measures. Then the map `(x, y) ↦ (y * x, x⁻¹)` preserves the measure `μ.prod ν`, which means that ``` ∫ x, ∫ y, h x y ∂ν ∂μ = ∫ x, ∫ y, h (y * x) x⁻¹ ∂ν ∂μ ``` If we apply this to `h x y := e x * f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E)`, we can rewrite the RHS to `μ(F)`, and the LHS to `c * μ(E)`, where `c = c(ν)` does not depend on `μ`. Applying this to `μ` and to `ν` gives `μ (F) / μ (E) = ν (F) / ν (E)`, which is the uniqueness up to scalar multiplication. The proof in [Halmos] seems to contain an omission in §60 Th. A, see `measure_theory.measure_lintegral_div_measure`. -/ noncomputable theory open set (hiding prod_eq) function measure_theory filter (hiding map) open_locale classical ennreal pointwise measure_theory variables (G : Type*) [measurable_space G] variables [group G] [has_measurable_mul₂ G] variables (μ ν : measure G) [sigma_finite ν] [sigma_finite μ] {E : set G} /-- The map `(x, y) ↦ (x, xy)` as a `measurable_equiv`. This is a shear mapping. -/ @[to_additive "The map `(x, y) ↦ (x, x + y)` as a `measurable_equiv`. This is a shear mapping."] protected def measurable_equiv.shear_mul_right [has_measurable_inv G] : G × G ≃ᵐ G × G := { measurable_to_fun := measurable_fst.prod_mk measurable_mul, measurable_inv_fun := measurable_fst.prod_mk $ measurable_fst.inv.mul measurable_snd, .. equiv.prod_shear (equiv.refl _) equiv.mul_left } variables {G} namespace measure_theory open measure /-- A shear mapping preserves the measure `μ.prod ν`. This condition is part of the definition of a measurable group in [Halmos, §59]. There, the map in this lemma is called `S`. -/ @[to_additive map_prod_add_eq /-" An additive shear mapping preserves the measure `μ.prod ν`. "-/] lemma map_prod_mul_eq [is_mul_left_invariant ν] : map (λ z : G × G, (z.1, z.1 * z.2)) (μ.prod ν) = μ.prod ν := ((measure_preserving.id μ).skew_product measurable_mul (filter.eventually_of_forall $ map_mul_left_eq_self ν)).map_eq /-- The function we are mapping along is `SR` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_add_eq_swap /-" "-/] lemma map_prod_mul_eq_swap [is_mul_left_invariant μ] : map (λ z : G × G, (z.2, z.2 * z.1)) (μ.prod ν) = ν.prod μ := begin rw [← prod_swap], simp_rw [map_map (measurable_snd.prod_mk (measurable_snd.mul measurable_fst)) measurable_swap], exact map_prod_mul_eq ν μ end @[to_additive] lemma measurable_measure_mul_right (hE : measurable_set E) : measurable (λ x, μ ((λ y, y * x) ⁻¹' E)) := begin suffices : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' ((λ z : G × G, ((1 : G), z.1 * z.2)) ⁻¹' (univ ×ˢ E)))), { convert this, ext1 x, congr' 1 with y : 1, simp }, apply measurable_measure_prod_mk_right, exact measurable_const.prod_mk (measurable_fst.mul measurable_snd) (measurable_set.univ.prod hE) end variables [has_measurable_inv G] /-- The function we are mapping along is `S⁻¹` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq`. -/ @[to_additive map_prod_neg_add_eq "The function we are mapping along is `-S` in [Halmos, §59], where `S` is the map in `map_prod_add_eq`."] lemma map_prod_inv_mul_eq [is_mul_left_invariant ν] : map (λ z : G × G, (z.1, z.1⁻¹ * z.2)) (μ.prod ν) = μ.prod ν := (measurable_equiv.shear_mul_right G).map_apply_eq_iff_map_symm_apply_eq.mp $ map_prod_mul_eq μ ν @[to_additive] lemma quasi_measure_preserving_div [is_mul_right_invariant μ] : quasi_measure_preserving (λ (p : G × G), p.1 / p.2) (μ.prod μ) μ := begin refine quasi_measure_preserving.prod_of_left measurable_div _, simp_rw [div_eq_mul_inv], apply eventually_of_forall, refine λ y, ⟨measurable_mul_const y⁻¹, (map_mul_right_eq_self μ y⁻¹).absolutely_continuous⟩ end variables [is_mul_left_invariant μ] /-- The function we are mapping along is `S⁻¹R` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_neg_add_eq_swap "The function we are mapping along is `-S + R` in [Halmos, §59], where `S` is the map in `map_prod_add_eq` and `R` is `prod.swap`."] lemma map_prod_inv_mul_eq_swap : map (λ z : G × G, (z.2, z.2⁻¹ * z.1)) (μ.prod ν) = ν.prod μ := begin rw [← prod_swap], simp_rw [map_map (measurable_snd.prod_mk $ measurable_snd.inv.mul measurable_fst) measurable_swap], exact map_prod_inv_mul_eq ν μ end /-- The function we are mapping along is `S⁻¹RSR` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_add_neg_eq "The function we are mapping along is `-S + R + S + R ` in [Halmos, §59], where `S` is the map in `map_prod_add_eq` and `R` is `prod.swap`."] lemma map_prod_mul_inv_eq [is_mul_left_invariant ν] : map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod ν) = μ.prod ν := begin suffices : map ((λ z : G × G, (z.2, z.2⁻¹ * z.1)) ∘ (λ z : G × G, (z.2, z.2 * z.1))) (μ.prod ν) = μ.prod ν, { convert this, ext1 ⟨x, y⟩, simp }, simp_rw [← map_map (measurable_snd.prod_mk (measurable_snd.inv.mul measurable_fst)) (measurable_snd.prod_mk (measurable_snd.mul measurable_fst)), map_prod_mul_eq_swap μ ν, map_prod_inv_mul_eq_swap ν μ] end @[to_additive] lemma quasi_measure_preserving_inv : quasi_measure_preserving (has_inv.inv : G → G) μ μ := begin refine ⟨measurable_inv, absolutely_continuous.mk $ λ s hsm hμs, _⟩, rw [map_apply measurable_inv hsm, inv_preimage], have hf : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) := (measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv, suffices : map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod μ) (s⁻¹ ×ˢ s⁻¹) = 0, { simpa only [map_prod_mul_inv_eq μ μ, prod_prod, mul_eq_zero, or_self] using this }, have hsm' : measurable_set (s⁻¹ ×ˢ s⁻¹) := hsm.inv.prod hsm.inv, simp_rw [map_apply hf hsm', prod_apply_symm (hf hsm'), preimage_preimage, mk_preimage_prod, inv_preimage, inv_inv, measure_mono_null (inter_subset_right _ _) hμs, lintegral_zero] end @[to_additive] lemma map_inv_absolutely_continuous : map has_inv.inv μ ≪ μ := (quasi_measure_preserving_inv μ).absolutely_continuous @[to_additive] lemma measure_inv_null : μ E⁻¹ = 0 ↔ μ E = 0 := begin refine ⟨λ hE, _, (quasi_measure_preserving_inv μ).preimage_null⟩, convert (quasi_measure_preserving_inv μ).preimage_null hE, exact (inv_inv _).symm end @[to_additive] lemma absolutely_continuous_map_inv : μ ≪ map has_inv.inv μ := begin refine absolutely_continuous.mk (λ s hs, _), simp_rw [map_apply measurable_inv hs, inv_preimage, measure_inv_null, imp_self] end @[to_additive] lemma lintegral_lintegral_mul_inv [is_mul_left_invariant ν] (f : G → G → ℝ≥0∞) (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f (y * x) x⁻¹ ∂ν ∂μ = ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ := begin have h : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) := (measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv, have h2f : ae_measurable (uncurry $ λ x y, f (y * x) x⁻¹) (μ.prod ν), { apply hf.comp_measurable' h (map_prod_mul_inv_eq μ ν).absolutely_continuous }, simp_rw [lintegral_lintegral h2f, lintegral_lintegral hf], conv_rhs { rw [← map_prod_mul_inv_eq μ ν] }, symmetry, exact lintegral_map' (hf.mono' (map_prod_mul_inv_eq μ ν).absolutely_continuous) h.ae_measurable, end @[to_additive] lemma measure_mul_right_null (y : G) : μ ((λ x, x * y) ⁻¹' E) = 0 ↔ μ E = 0 := calc μ ((λ x, x * y) ⁻¹' E) = 0 ↔ μ ((λ x, y⁻¹ * x) ⁻¹' E⁻¹)⁻¹ = 0 : by simp_rw [← inv_preimage, preimage_preimage, mul_inv_rev, inv_inv] ... ↔ μ E = 0 : by simp only [measure_inv_null μ, measure_preimage_mul] @[to_additive] lemma measure_mul_right_ne_zero (h2E : μ E ≠ 0) (y : G) : μ ((λ x, x * y) ⁻¹' E) ≠ 0 := (not_iff_not_of_iff (measure_mul_right_null μ y)).mpr h2E @[to_additive] lemma quasi_measure_preserving_mul_right (g : G) : quasi_measure_preserving (λ h : G, h * g) μ μ := begin refine ⟨measurable_mul_const g, absolutely_continuous.mk $ λ s hs, _⟩, rw [map_apply (measurable_mul_const g) hs, measure_mul_right_null], exact id, end @[to_additive] lemma map_mul_right_absolutely_continuous (g : G) : map (* g) μ ≪ μ := (quasi_measure_preserving_mul_right μ g).absolutely_continuous @[to_additive] lemma absolutely_continuous_map_mul_right (g : G) : μ ≪ map (* g) μ := begin refine absolutely_continuous.mk (λ s hs, _), rw [map_apply (measurable_mul_const g) hs, measure_mul_right_null], exact id end @[to_additive] lemma quasi_measure_preserving_div_left (g : G) : quasi_measure_preserving (λ h : G, g / h) μ μ := begin refine ⟨measurable_const.div measurable_id, _⟩, simp_rw [div_eq_mul_inv], rw [← map_map (measurable_const_mul g) measurable_inv], refine ((map_inv_absolutely_continuous μ).map $ measurable_const_mul g).trans _, rw [map_mul_left_eq_self], end @[to_additive] lemma map_div_left_absolutely_continuous (g : G) : map (λ h, g / h) μ ≪ μ := (quasi_measure_preserving_div_left μ g).absolutely_continuous @[to_additive] lemma absolutely_continuous_map_div_left (g : G) : μ ≪ map (λ h, g / h) μ := begin simp_rw [div_eq_mul_inv], rw [← map_map (measurable_const_mul g) measurable_inv], conv_lhs { rw [← map_mul_left_eq_self μ g] }, exact (absolutely_continuous_map_inv μ).map (measurable_const_mul g) end /-- This is the computation performed in the proof of [Halmos, §60 Th. A]. -/ @[to_additive "This is the computation performed in the proof of [Halmos, §60 Th. A]."] lemma measure_mul_lintegral_eq [is_mul_left_invariant ν] (Em : measurable_set E) (f : G → ℝ≥0∞) (hf : measurable f) : μ E * ∫⁻ y, f y ∂ν = ∫⁻ x, ν ((λ z, z * x) ⁻¹' E) * f (x⁻¹) ∂μ := begin rw [← set_lintegral_one, ← lintegral_indicator _ Em, ← lintegral_lintegral_mul (measurable_const.indicator Em).ae_measurable hf.ae_measurable, ← lintegral_lintegral_mul_inv μ ν], swap, { exact (((measurable_const.indicator Em).comp measurable_fst).mul (hf.comp measurable_snd)).ae_measurable }, have mE : ∀ x : G, measurable (λ y, ((λ z, z * x) ⁻¹' E).indicator (λ z, (1 : ℝ≥0∞)) y) := λ x, measurable_const.indicator (measurable_mul_const _ Em), have : ∀ x y, E.indicator (λ (z : G), (1 : ℝ≥0∞)) (y * x) = ((λ z, z * x) ⁻¹' E).indicator (λ (b : G), 1) y, { intros x y, symmetry, convert indicator_comp_right (λ y, y * x), ext1 z, refl }, simp_rw [this, lintegral_mul_const _ (mE _), lintegral_indicator _ (measurable_mul_const _ Em), set_lintegral_one], end /-- Any two nonzero left-invariant measures are absolutely continuous w.r.t. each other. -/ @[to_additive /-" Any two nonzero left-invariant measures are absolutely continuous w.r.t. each other. "-/] lemma absolutely_continuous_of_is_mul_left_invariant [is_mul_left_invariant ν] (hν : ν ≠ 0) : μ ≪ ν := begin refine absolutely_continuous.mk (λ E Em hνE, _), have h1 := measure_mul_lintegral_eq μ ν Em 1 measurable_one, simp_rw [pi.one_apply, lintegral_one, mul_one, (measure_mul_right_null ν _).mpr hνE, lintegral_zero, mul_eq_zero, measure_univ_eq_zero.not.mpr hν, or_false] at h1, exact h1 end @[to_additive] lemma ae_measure_preimage_mul_right_lt_top [is_mul_left_invariant ν] (Em : measurable_set E) (hμE : μ E ≠ ∞) : ∀ᵐ x ∂μ, ν ((λ y, y * x) ⁻¹' E) < ∞ := begin refine ae_of_forall_measure_lt_top_ae_restrict' ν.inv _ _, intros A hA h2A h3A, simp only [ν.inv_apply] at h3A, apply ae_lt_top (measurable_measure_mul_right ν Em), have h1 := measure_mul_lintegral_eq μ ν Em (A⁻¹.indicator 1) (measurable_one.indicator hA.inv), rw [lintegral_indicator _ hA.inv] at h1, simp_rw [pi.one_apply, set_lintegral_one, ← image_inv, indicator_image inv_injective, image_inv, ← indicator_mul_right _ (λ x, ν ((λ y, y * x) ⁻¹' E)), function.comp, pi.one_apply, mul_one] at h1, rw [← lintegral_indicator _ hA, ← h1], exact ennreal.mul_ne_top hμE h3A.ne, end @[to_additive] lemma ae_measure_preimage_mul_right_lt_top_of_ne_zero [is_mul_left_invariant ν] (Em : measurable_set E) (h2E : ν E ≠ 0) (h3E : ν E ≠ ∞) : ∀ᵐ x ∂μ, ν ((λ y, y * x) ⁻¹' E) < ∞ := begin refine (ae_measure_preimage_mul_right_lt_top ν ν Em h3E).filter_mono _, refine (absolutely_continuous_of_is_mul_left_invariant μ ν _).ae_le, refine mt _ h2E, intro hν, rw [hν, measure.coe_zero, pi.zero_apply] end /-- A technical lemma relating two different measures. This is basically [Halmos, §60 Th. A]. Note that if `f` is the characteristic function of a measurable set `F` this states that `μ F = c * μ E` for a constant `c` that does not depend on `μ`. Note: There is a gap in the last step of the proof in [Halmos]. In the last line, the equality `g(x⁻¹)ν(Ex⁻¹) = f(x)` holds if we can prove that `0 < ν(Ex⁻¹) < ∞`. The first inequality follows from §59, Th. D, but the second inequality is not justified. We prove this inequality for almost all `x` in `measure_theory.ae_measure_preimage_mul_right_lt_top_of_ne_zero`. -/ @[to_additive "A technical lemma relating two different measures. This is basically [Halmos, §60 Th. A]. Note that if `f` is the characteristic function of a measurable set `F` this states that `μ F = c * μ E` for a constant `c` that does not depend on `μ`. Note: There is a gap in the last step of the proof in [Halmos]. In the last line, the equality `g(-x) + ν(E - x) = f(x)` holds if we can prove that `0 < ν(E - x) < ∞`. The first inequality follows from §59, Th. D, but the second inequality is not justified. We prove this inequality for almost all `x` in `measure_theory.ae_measure_preimage_add_right_lt_top_of_ne_zero`."] lemma measure_lintegral_div_measure [is_mul_left_invariant ν] (Em : measurable_set E) (h2E : ν E ≠ 0) (h3E : ν E ≠ ∞) (f : G → ℝ≥0∞) (hf : measurable f) : μ E * ∫⁻ y, f y⁻¹ / ν ((λ x, x * y⁻¹) ⁻¹' E) ∂ν = ∫⁻ x, f x ∂μ := begin set g := λ y, f y⁻¹ / ν ((λ x, x * y⁻¹) ⁻¹' E), have hg : measurable g := (hf.comp measurable_inv).div ((measurable_measure_mul_right ν Em).comp measurable_inv), simp_rw [measure_mul_lintegral_eq μ ν Em g hg, g, inv_inv], refine lintegral_congr_ae _, refine (ae_measure_preimage_mul_right_lt_top_of_ne_zero μ ν Em h2E h3E).mono (λ x hx , _), simp_rw [ennreal.mul_div_cancel' (measure_mul_right_ne_zero ν h2E _) hx.ne] end @[to_additive] lemma measure_mul_measure_eq [is_mul_left_invariant ν] {E F : set G} (hE : measurable_set E) (hF : measurable_set F) (h2E : ν E ≠ 0) (h3E : ν E ≠ ∞) : μ E * ν F = ν E * μ F := begin have h1 := measure_lintegral_div_measure ν ν hE h2E h3E (F.indicator (λ x, 1)) (measurable_const.indicator hF), have h2 := measure_lintegral_div_measure μ ν hE h2E h3E (F.indicator (λ x, 1)) (measurable_const.indicator hF), rw [lintegral_indicator _ hF, set_lintegral_one] at h1 h2, rw [← h1, mul_left_comm, h2], end /-- Left invariant Borel measures on a measurable group are unique (up to a scalar). -/ @[to_additive /-" Left invariant Borel measures on an additive measurable group are unique (up to a scalar). "-/] lemma measure_eq_div_smul [is_mul_left_invariant ν] (hE : measurable_set E) (h2E : ν E ≠ 0) (h3E : ν E ≠ ∞) : μ = (μ E / ν E) • ν := begin ext1 F hF, rw [smul_apply, smul_eq_mul, mul_comm, ← mul_div_assoc, mul_comm, measure_mul_measure_eq μ ν hE hF h2E h3E, mul_div_assoc, ennreal.mul_div_cancel' h2E h3E] end end measure_theory
e6cc130c28c14b6f51a0ecfa5aa9717ca1c541af
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/alternating_teest.lean
49c4c1f3b4d6e37acd4ea2d086364fe7e2c007b1
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
14,135
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.perm group_theory.order_of_element group_theory.quotient_group universes u v open finset is_subgroup equiv equiv.perm quotient_group instance {α β : Type*} [group α] [group β] [decidable_eq β] (f : α → β) [is_group_hom f] : decidable_pred (is_group_hom.ker f) := λ _, decidable_of_iff _ (is_group_hom.mem_ker f).symm def alternating (α : Type*) [decidable_eq α] [fintype α] : Type* := is_group_hom.ker (sign : perm α → units ℤ) /- not definitionally equal to `subtype.decidable_eq`, since `subtype.decidable_eq` does not reduce in the kernel -/ instance (α : Type*) [decidable_eq α] [fintype α] : decidable_eq (alternating α) := λ a b, decidable_of_iff (a.1 = b.1) (by cases a; cases b; simp [subtype.mk.inj_eq]) instance (α : Type*) [decidable_eq α] [fintype α] : fintype (alternating α) := set_fintype _ instance (α : Type*) [decidable_eq α] [fintype α] : group (alternating α) := by unfold alternating; apply_instance section classical local attribute [instance] classical.prop_decidable lemma card_alternating (α : Type*) [decidable_eq α] [fintype α] (h : 2 ≤ fintype.card α): fintype.card (alternating α) * 2 = (fintype.card α).fact := have (quotient_group.quotient (is_group_hom.ker (sign : perm α → units ℤ))) ≃ units ℤ, from quotient_ker_equiv_of_surjective _ (sign_surjective h), calc fintype.card (alternating α) * 2 = fintype.card (units ℤ × alternating α) : by rw [mul_comm, fintype.card_prod, fintype.card_units_int] ... = fintype.card (perm α) : fintype.card_congr (calc (units ℤ × alternating α) ≃ (quotient_group.quotient (is_group_hom.ker (sign : perm α → units ℤ)) × alternating α) : equiv.prod_congr this.symm (by refl) ... ≃ perm α : (group_equiv_quotient_times_subgroup _).symm) ... = (fintype.card α).fact : fintype.card_perm end classical local notation `A5` := alternating (fin 5) variables {α : Type*} [fintype α] [decidable_eq α] section local attribute [semireducible] reflected meta instance fin_reflect (n : ℕ) : has_reflect (fin n) := λ a, `(@fin.mk %%`(n) %%(nat.reflect a.1) (of_as_true %%`(_root_.trivial))) meta instance fin_fun.has_reflect : has_reflect (fin 5 → fin 5) := list.rec_on (quot.unquot (@univ (fin 5) _).1) (λ f, `(λ y : fin 5, y)) (λ x l ih f, let e := ih f in if f x = x then e else let ex := fin_reflect 5 x in let efx := fin_reflect 5 (f x) in if e = `(λ y : fin 5, y) then `(λ y : fin 5, ite.{1} (y = %%ex) (%%efx) y) else `(λ y : fin 5, ite.{1} (y = %%ex) (%%efx) ((%%e : fin 5 → fin 5) y))) meta instance : has_reflect (perm (fin 5)) := λ f, `(@equiv.mk.{1 1} (fin 5) (fin 5) %%(fin_fun.has_reflect f.to_fun) %%(fin_fun.has_reflect f.inv_fun) (of_as_true %%`(_root_.trivial)) (of_as_true %%`(_root_.trivial))) meta instance I1 : has_reflect (alternating (fin 5)) := λ f, `(@subtype.mk (perm (fin 5)) (is_group_hom.ker (sign : perm (fin 5) → units ℤ)) %%(@reflect (perm (fin 5)) f.1 (equiv.perm.has_reflect f.1)) ((is_group_hom.mem_ker sign).2 %%`(@eq.refl (units ℤ) 1))) meta instance multiset.has_reflect {α : Type} [reflected α] [has_reflect α] : has_reflect (multiset α) := λ s, let l : list α := quot.unquot s in `(@quotient.mk.{1} (list %%`(α)) _ %%`(l)) meta instance I2 (a : alternating (fin 5)) : has_reflect {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1} := λ b, `(@subtype.mk (alternating (fin 5) × alternating (fin 5)) (λ b, b.2 * %%`(a) * b.2⁻¹ = b.1) %%(prod.has_reflect _ _ b.1) (of_as_true %%`(_root_.trivial))) meta instance I3 (a : alternating (fin 5)) (m : reflected a) : reflected {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1} := `({b : alternating (fin 5) × alternating (fin 5) // b.2 * %%m * b.2⁻¹ = b.1}) meta instance I4 : has_reflect (Σ a : alternating (fin 5), multiset {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1}) := λ s, let ra : reflected s.1 := (I1 s.1) in `(let a : alternating (fin 5) := %%ra in @sigma.mk (alternating (fin 5)) (λ a, multiset {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1}) a %%(@multiset.has_reflect _ (I3 s.1 ra) (I2 s.1) s.2)) end def conjugacy_classes_A5_meta_aux : list (alternating (fin 5)) → multiset (Σ a : alternating (fin 5), multiset {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1}) | [] := 0 | (a :: l) := let m : Σ a : alternating (fin 5), multiset {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1} := ⟨a, quotient.lift_on (@univ (alternating (fin 5)) _).1 (λ l, (l.map (λ x, show {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1}, from ⟨(x * a * x⁻¹, x), rfl⟩)).pw_filter (λ x y, x.1.1 ≠ y.1.1)) sorry⟩ in have wf : (l.filter (λ x, x ∉ m.2.map (prod.fst ∘ subtype.val))).length < (a :: l : list _).length, from sorry, m :: conjugacy_classes_A5_meta_aux (l.filter (λ x, x ∉ m.2.map (prod.fst ∘ subtype.val))) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩], dec_tac := tactic.assumption} def conjugacy_classes_A52 : list A5 → multiset {s : finset A5 // ∀ (x∈s) (y∈s), is_conj x y} | [] := ∅ | (a::l) := let s : {s : finset A5 // ∀ (x∈s) (y∈s), is_conj x y} := ⟨(@univ A5 _).image (λ x, x * a * x⁻¹), λ x hx y hy, let ⟨m, _, hm⟩ := mem_image.1 hx in let ⟨n, _, hn⟩ := mem_image.1 hy in ⟨n * m⁻¹, by simp [hm.symm, mul_assoc, hn.symm]⟩⟩ in have wf : false, from sorry, s :: conjugacy_classes_A52 (l.filter (λ x, x ∉ s.1)) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, empty_wf⟩], dec_tac := tactic.assumption} -- def conjugacy_classes_A5_meta : multiset (Σ a : alternating (fin 5), multiset -- {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1}) := -- (quotient.mk ((conjugacy_classes_A5_meta_aux (quot.unquot univ.1)).map -- (λ a, ⟨a.1, (quotient.mk a.2)⟩))) #print nat.gcd open nat def gcd' : nat → nat → nat | 0 y := y | (succ x) y := have false, from sorry, gcd (y % succ x) (succ x) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, empty_wf⟩], dec_tac := tactic.assumption} example : gcd' 1 2 = 1 := rfl meta def exact_reflect {α : Sort*} [has_reflect α] (a : α) : tactic unit := tactic.exact `(a) @[irreducible] def conjugacy_classes_A5_aux : multiset (Σ a : alternating (fin 5), multiset {b : alternating (fin 5) × alternating (fin 5) // b.2 * a * b.2⁻¹ = b.1}) := by exact_reflect (conjugacy_classes_A5_meta_aux (quot.unquot univ.1)) example : conjugacy_classes_A5_aux = conjugacy_classes_A5_aux := dec_trivial def conjugacy_classes_A5_aux2 : multiset (multiset (alternating (fin 5))) := conjugacy_classes_A5_aux.map (λ s, s.2.map (λ b, b.1.1)) example : (quotient.lift_on (@univ A5 _).1 conjugacy_classes_A52 sorry).map (finset.card ∘ subtype.val) = {1,12,12,15,20} := dec_trivial lemma nodup_conjugacy_classes_A5_aux2_bind : (conjugacy_classes_A5_aux2.bind id).nodup := dec_trivial lemma nodup_conjugacy_classes_A5_aux2 : ∀ s : multiset (alternating (fin 5)), s ∈ conjugacy_classes_A5_aux2 → s.nodup := (multiset.nodup_bind.1 nodup_conjugacy_classes_A5_aux2_bind).1 def conjugacy_classes_A5 : finset (finset (alternating (fin 5))) := ⟨conjugacy_classes_A5_aux2.pmap finset.mk nodup_conjugacy_classes_A5_aux2, dec_trivial⟩ lemma nodup_conjugacy_classes_A5_bind : (conjugacy_classes_A5.1.bind finset.val).nodup := have conjugacy_classes_A5.1.bind finset.val = conjugacy_classes_A5_aux2.bind id, from multiset.ext.2 $ λ a, by rw [conjugacy_classes_A5, @multiset.count_bind A5, @multiset.count_bind A5, multiset.map_pmap, multiset.pmap_eq_map]; refl, by rw this; exact nodup_conjugacy_classes_A5_aux2_bind lemma is_conj_conjugacy_classes_A5 (s : finset A5) (h : s ∈ conjugacy_classes_A5) : ∀ x y ∈ s, is_conj x y := assume x y hx hy, begin simp only [conjugacy_classes_A5, finset.mem_def, multiset.mem_pmap, conjugacy_classes_A5_aux2] at h, rcases h with ⟨t, ht₁, ht₂⟩, rw [multiset.mem_map] at ht₁, rcases ht₁ with ⟨u, hu₁, hu₂⟩, have hx' : x ∈ multiset.map (λ (b : {b : A5 × A5 // b.2 * u.1 * b.2⁻¹ = b.1}), b.1.1) u.2, { simpa [ht₂.symm, hu₂] using hx }, have hy' : y ∈ multiset.map (λ (b : {b : A5 × A5 // b.2 * u.1 * b.2⁻¹ = b.1}), b.1.1) u.2, { simpa [ht₂.symm, hu₂] using hy }, cases multiset.mem_map.1 hx' with xc hxc, cases multiset.mem_map.1 hy' with yc hyc, exact is_conj_trans (is_conj_symm (show is_conj u.1 x, from hxc.2 ▸ ⟨_, xc.2⟩)) (hyc.2 ▸ ⟨_, yc.2⟩) end variables {G : Type u} [group G] [decidable_eq G] lemma normal_subgroup_eq_bind_conjugacy_classes (s : finset (finset G)) (h₁ : ∀ x, ∃ t ∈ s, x ∈ t) (h₂ : ∀ t ∈ s, ∀ x y ∈ t, is_conj x y) (I : finset G) [nI : normal_subgroup (↑I : set G)] : ∃ u ⊆ s, I = u.bind id := ⟨(s.powerset.filter (λ u : finset (finset G), u.bind id ⊆ I)).bind id, (λ x, by simp only [finset.subset_iff, mem_bind, mem_filter, exists_imp_distrib, mem_powerset, and_imp, id.def] {contextual := tt}; tauto), le_antisymm (λ x hxI, let ⟨t, ht₁, ht₂⟩ := h₁ x in mem_bind.2 ⟨t, mem_bind.2 ⟨(s.powerset.filter (λ u : finset (finset G), u.bind id ⊆ I)).bind id, mem_filter.2 ⟨mem_powerset.2 (λ u hu, let ⟨v, hv₁, hv₂⟩ := mem_bind.1 hu in mem_powerset.1 (mem_filter.1 hv₁).1 hv₂), λ y hy, let ⟨u, hu₁, hu₂⟩ := mem_bind.1 hy in let ⟨v, hv₁, hv₂⟩ := mem_bind.1 hu₁ in (mem_filter.1 hv₁).2 (mem_bind.2 ⟨u, hv₂, hu₂⟩)⟩, mem_bind.2 ⟨{t}, mem_filter.2 ⟨by simp [ht₁, finset.subset_iff], λ y hy, let ⟨u, hu₁, hu₂⟩ := mem_bind.1 hy in let ⟨z, hz⟩ := h₂ t ht₁ x y ht₂ (by simp * at *) in hz ▸ @normal_subgroup.normal G _ I.to_set nI _ hxI _⟩, by simp⟩⟩, ht₂⟩) (λ x, by simp only [finset.subset_iff, mem_bind, exists_imp_distrib, mem_filter, mem_powerset]; tauto)⟩ lemma simple_of_card_conjugacy_classes [fintype G] (s : finset (finset G)) (h₁ : ∀ x, ∃ t ∈ s, x ∈ t) (h₂ : ∀ t ∈ s, ∀ x y ∈ t, is_conj x y) (hs : (s.1.bind finset.val).nodup) (h₃ : ∀ t ≤ s.1.map finset.card, 1 ∈ t → t.sum ∣ fintype.card G → t.sum = 1 ∨ t.sum = fintype.card G) : simple_group G := by haveI := classical.dec; exact ⟨λ H iH, let I := (set.to_finset H) in have Ii : normal_subgroup (↑I : set G), by simpa using iH, let ⟨u, hu₁, hu₂⟩ := @normal_subgroup_eq_bind_conjugacy_classes G _ _ s h₁ h₂ I Ii in have hInd : ∀ (x : finset G), x ∈ u → ∀ (y : finset G), y ∈ u → x ≠ y → id x ∩ id y = ∅, from λ x hxu y hyu hxy, begin rw multiset.nodup_bind at hs, rw [← finset.disjoint_iff_inter_eq_empty, finset.disjoint_left], exact multiset.forall_of_pairwise (λ (a b : finset G) (h : multiset.disjoint a.1 b.1), multiset.disjoint.symm h) hs.2 x (hu₁ hxu) y (hu₁ hyu) hxy end, have hci : card I = u.sum finset.card, by rw [hu₂, card_bind hInd]; refl, have hu1 : (1 : G) ∈ u.bind id, by exactI hu₂ ▸ is_submonoid.one_mem (↑I : set G), let ⟨v, hv₁, hv₂⟩ := mem_bind.1 hu1 in have hv : v = finset.singleton (1 : G), from finset.ext.2 $ λ a, ⟨λ hav, mem_singleton.2 $ is_conj_one_right.1 (h₂ v (hu₁ hv₁) _ _ hv₂ hav), by simp [show (1 : G) ∈ v, from hv₂] {contextual := tt}⟩, have hci' : card I = 1 ∨ card I = fintype.card G, begin rw [hci], exact h₃ _ (multiset.map_le_map (show u.1 ≤ s.1, from (multiset.le_iff_subset u.2).2 hu₁)) (multiset.mem_map.2 ⟨finset.singleton 1, hv ▸ hv₁, rfl⟩) (calc u.sum finset.card = card I : hci.symm ... = fintype.card (↑I : set G) : (set.card_fintype_of_finset' I (by simp)).symm ... ∣ fintype.card G : by exactI card_subgroup_dvd_card _) end, hci'.elim (λ hci', or.inl (set.ext (λ x, let ⟨y, hy⟩ := finset.card_eq_one.1 hci' in by resetI; simp only [I, finset.ext, set.mem_to_finset, finset.mem_singleton] at hy; simp [is_subgroup.mem_trivial, hy, (hy 1).1 (is_submonoid.one_mem H)]))) (λ hci', or.inr $ suffices I = finset.univ, by simpa [I, set.ext_iff, finset.ext] using this, finset.eq_of_subset_of_card_le (λ _, by simp) (by rw hci'; refl))⟩ lemma card_A5 : fintype.card A5 = 60 := (nat.mul_right_inj (show 2 > 0, from dec_trivial)).1 $ have 2 ≤ fintype.card (fin 5), from dec_trivial, by rw [card_alternating _ this]; simp; refl lemma conjugacy_classes_A5_bind_eq_univ : conjugacy_classes_A5.bind (λ t, t) = univ := eq_of_subset_of_card_le (λ _, by simp) (calc card univ = 60 : card_A5 ... ≤ (conjugacy_classes_A5.1.bind finset.val).card : dec_trivial ... = (conjugacy_classes_A5.bind id).card : begin rw [finset.card_bind, multiset.card_bind], refl, { exact multiset.forall_of_pairwise (λ a b, by simp [finset.inter_comm]) (by simp only [finset.disjoint_iff_inter_eq_empty.symm, finset.disjoint_left]; exact (multiset.nodup_bind.1 nodup_conjugacy_classes_A5_bind).2) } end) lemma A5_simple : simple_group A5 := simple_of_card_conjugacy_classes conjugacy_classes_A5 (λ x, mem_bind.1 $ by rw [conjugacy_classes_A5_bind_eq_univ]; simp) is_conj_conjugacy_classes_A5 nodup_conjugacy_classes_A5_bind (by simp only [multiset.mem_powerset.symm, card_A5]; exact dec_trivial)
8c8a39f73a692157187e774bad12829056ba6b37
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/continued_fractions/computation/default.lean
c9d65d7eeb53f1a7fc69a0bc69844f82421e7a1a
[]
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
391
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.continued_fractions.computation.basic import Mathlib.algebra.continued_fractions.computation.translations import Mathlib.PostPort namespace Mathlib
877afe84712e14abe9df6123a7d38f58ba7d3c51
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/topology/algebra/uniform_ring.lean
8e97a613b9b01eb07ba68349d8b56407e932a866
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,648
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 Theory of topological rings with uniform structure. -/ import topology.algebra.group_completion import topology.algebra.ring open classical set filter topological_space add_comm_group open_locale classical noncomputable theory namespace uniform_space.completion open dense_inducing uniform_space function variables (α : Type*) [ring α] [uniform_space α] instance : has_one (completion α) := ⟨(1:α)⟩ instance : has_mul (completion α) := ⟨curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (coe ∘ uncurry (*))⟩ @[norm_cast] lemma coe_one : ((1 : α) : completion α) = 1 := rfl variables {α} [topological_ring α] @[norm_cast] lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b := ((dense_inducing_coe.prod dense_inducing_coe).extend_eq ((continuous_coe α).comp (@continuous_mul α _ _ _)) (a, b)).symm variables [uniform_add_group α] lemma continuous_mul : continuous (λ p : completion α × completion α, p.1 * p.2) := begin let m := (add_monoid_hom.mul : α →+ α →+ α).compr₂ to_compl, have : continuous (λ p : α × α, m p.1 p.2), from (continuous_coe α).comp continuous_mul, have di : dense_inducing (to_compl : α → completion α), from dense_inducing_coe, convert di.extend_Z_bilin di this, ext ⟨x, y⟩, refl end lemma continuous.mul {β : Type*} [topological_space β] {f g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) := continuous_mul.comp (hf.prod_mk hg : _) instance : ring (completion α) := { one_mul := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_const continuous_id) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, one_mul]), mul_one := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_id continuous_const) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, mul_one]), mul_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.mul continuous_fst (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]), left_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul continuous_fst (continuous.add (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))) (continuous.add (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]), right_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.add continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.add (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)) (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]), ..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α } /-- The map from a uniform ring to its completion, as a ring homomorphism. -/ def coe_ring_hom : α →+* completion α := ⟨coe, coe_one α, assume a b, coe_mul a b, coe_zero, assume a b, coe_add a b⟩ lemma continuous_coe_ring_hom : continuous (coe_ring_hom : α → completion α) := continuous_coe α universes u variables {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] (f : α →+* β) (hf : continuous f) /-- The completion extension as a ring morphism. -/ def extension_hom [complete_space β] [separated_space β] : completion α →+* β := have hf' : continuous (f : α →+ β), from hf, -- helping the elaborator have hf : uniform_continuous f, from uniform_continuous_of_continuous hf', { to_fun := completion.extension f, map_zero' := by rw [← coe_zero, extension_coe hf, f.map_zero], map_add' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add) ((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, f.map_add]), map_one' := by rw [← coe_one, extension_coe hf, f.map_one], map_mul' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_mul) ((continuous_extension.comp continuous_fst).mul (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, f.map_mul]) } instance top_ring_compl : topological_ring (completion α) := { continuous_add := continuous_add, continuous_mul := continuous_mul, continuous_neg := continuous_neg } /-- The completion map as a ring morphism. -/ def map_ring_hom (hf : continuous f) : completion α →+* completion β := extension_hom (coe_ring_hom.comp f) (continuous_coe_ring_hom.comp hf) variables (R : Type*) [comm_ring R] [uniform_space R] [uniform_add_group R] [topological_ring R] instance : comm_ring (completion R) := { mul_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_fst.mul continuous_snd) (continuous_snd.mul continuous_fst)) (assume a b, by rw [← coe_mul, ← coe_mul, mul_comm]), ..completion.ring } end uniform_space.completion namespace uniform_space variables {α : Type*} lemma ring_sep_rel (α) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) := setoid.ext $ assume x y, group_separation_rel x y lemma ring_sep_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = (⊥ : ideal α).closure.quotient := by rw [@ring_sep_rel α r]; refl /-- Given a topological ring `α` equipped with a uniform structure that makes subtraction uniformly continuous, get an equivalence between the separated quotient of `α` and the quotient ring corresponding to the closure of zero. -/ def sep_quot_equiv_ring_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) ≃ (⊥ : ideal α).closure.quotient := quotient.congr_right $ assume x y, group_separation_rel x y /- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/ instance comm_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : comm_ring (quotient (separation_setoid α)) := by rw ring_sep_quot α; apply_instance instance topological_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : topological_ring (quotient (separation_setoid α)) := begin convert topological_ring_quotient (⊥ : ideal α).closure; try {apply ring_sep_rel}, simp [uniform_space.comm_ring] end end uniform_space
e2ed24631b73c4c286fceaf735342effb2668c79
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/special_functions/complex/log_deriv.lean
75d63fafccf352e4c54c61b5ae1c6b7c4e634b8e
[ "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
6,351
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.complex.log import analysis.special_functions.exp_deriv /-! # Differentiability of the complex `log` function -/ noncomputable theory namespace complex open set filter open_locale real topological_space /-- `complex.exp` as a `local_homeomorph` with `source = {z | -π < im z < π}` and `target = {z | 0 < re z} ∪ {z | im z ≠ 0}`. This definition is used to prove that `complex.log` is complex differentiable at all points but the negative real semi-axis. -/ def exp_local_homeomorph : local_homeomorph ℂ ℂ := local_homeomorph.of_continuous_open { to_fun := exp, inv_fun := log, source := {z : ℂ | z.im ∈ Ioo (- π) π}, target := {z : ℂ | 0 < z.re} ∪ {z : ℂ | z.im ≠ 0}, map_source' := begin rintro ⟨x, y⟩ ⟨h₁ : -π < y, h₂ : y < π⟩, refine (not_or_of_imp $ λ hz, _).symm, obtain rfl : y = 0, { rw exp_im at hz, simpa [(real.exp_pos _).ne', real.sin_eq_zero_iff_of_lt_of_lt h₁ h₂] using hz }, rw [mem_set_of_eq, ← of_real_def, exp_of_real_re], exact real.exp_pos x end, map_target' := λ z h, suffices 0 ≤ z.re ∨ z.im ≠ 0, by simpa [log_im, neg_pi_lt_arg, (arg_le_pi _).lt_iff_ne, arg_eq_pi_iff, not_and_distrib], h.imp (λ h, le_of_lt h) id, left_inv' := λ x hx, log_exp hx.1 (le_of_lt hx.2), right_inv' := λ x hx, exp_log $ by { rintro rfl, simpa [lt_irrefl] using hx } } continuous_exp.continuous_on is_open_map_exp (is_open_Ioo.preimage continuous_im) lemma has_strict_deriv_at_log {x : ℂ} (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at log x⁻¹ x := have h0 : x ≠ 0, by { rintro rfl, simpa [lt_irrefl] using h }, exp_local_homeomorph.has_strict_deriv_at_symm h h0 $ by simpa [exp_log h0] using has_strict_deriv_at_exp (log x) lemma has_strict_fderiv_at_log_real {x : ℂ} (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_fderiv_at log (x⁻¹ • (1 : ℂ →L[ℝ] ℂ)) x := (has_strict_deriv_at_log h).complex_to_real_fderiv lemma cont_diff_at_log {x : ℂ} (h : 0 < x.re ∨ x.im ≠ 0) {n : with_top ℕ} : cont_diff_at ℂ n log x := exp_local_homeomorph.cont_diff_at_symm_deriv (exp_ne_zero $ log x) h (has_deriv_at_exp _) cont_diff_exp.cont_diff_at end complex section log_deriv open complex filter open_locale topological_space variables {α : Type*} [topological_space α] {E : Type*} [normed_group E] [normed_space ℂ E] lemma has_strict_fderiv_at.clog {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E} (h₁ : has_strict_fderiv_at f f' x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ t, log (f t)) ((f x)⁻¹ • f') x := (has_strict_deriv_at_log h₂).comp_has_strict_fderiv_at x h₁ lemma has_strict_deriv_at.clog {f : ℂ → ℂ} {f' x : ℂ} (h₁ : has_strict_deriv_at f f' x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ t, log (f t)) (f' / f x) x := by { rw div_eq_inv_mul, exact (has_strict_deriv_at_log h₂).comp x h₁ } lemma has_strict_deriv_at.clog_real {f : ℝ → ℂ} {x : ℝ} {f' : ℂ} (h₁ : has_strict_deriv_at f f' x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ t, log (f t)) (f' / f x) x := by simpa only [div_eq_inv_mul] using (has_strict_fderiv_at_log_real h₂).comp_has_strict_deriv_at x h₁ lemma has_fderiv_at.clog {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E} (h₁ : has_fderiv_at f f' x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ t, log (f t)) ((f x)⁻¹ • f') x := (has_strict_deriv_at_log h₂).has_deriv_at.comp_has_fderiv_at x h₁ lemma has_deriv_at.clog {f : ℂ → ℂ} {f' x : ℂ} (h₁ : has_deriv_at f f' x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ t, log (f t)) (f' / f x) x := by { rw div_eq_inv_mul, exact (has_strict_deriv_at_log h₂).has_deriv_at.comp x h₁ } lemma has_deriv_at.clog_real {f : ℝ → ℂ} {x : ℝ} {f' : ℂ} (h₁ : has_deriv_at f f' x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ t, log (f t)) (f' / f x) x := by simpa only [div_eq_inv_mul] using (has_strict_fderiv_at_log_real h₂).has_fderiv_at.comp_has_deriv_at x h₁ lemma differentiable_at.clog {f : E → ℂ} {x : E} (h₁ : differentiable_at ℂ f x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ t, log (f t)) x := (h₁.has_fderiv_at.clog h₂).differentiable_at lemma has_fderiv_within_at.clog {f : E → ℂ} {f' : E →L[ℂ] ℂ} {s : set E} {x : E} (h₁ : has_fderiv_within_at f f' s x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ t, log (f t)) ((f x)⁻¹ • f') s x := (has_strict_deriv_at_log h₂).has_deriv_at.comp_has_fderiv_within_at x h₁ lemma has_deriv_within_at.clog {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} (h₁ : has_deriv_within_at f f' s x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ t, log (f t)) (f' / f x) s x := by { rw div_eq_inv_mul, exact (has_strict_deriv_at_log h₂).has_deriv_at.comp_has_deriv_within_at x h₁ } lemma has_deriv_within_at.clog_real {f : ℝ → ℂ} {s : set ℝ} {x : ℝ} {f' : ℂ} (h₁ : has_deriv_within_at f f' s x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ t, log (f t)) (f' / f x) s x := by simpa only [div_eq_inv_mul] using (has_strict_fderiv_at_log_real h₂).has_fderiv_at.comp_has_deriv_within_at x h₁ lemma differentiable_within_at.clog {f : E → ℂ} {s : set E} {x : E} (h₁ : differentiable_within_at ℂ f s x) (h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ t, log (f t)) s x := (h₁.has_fderiv_within_at.clog h₂).differentiable_within_at lemma differentiable_on.clog {f : E → ℂ} {s : set E} (h₁ : differentiable_on ℂ f s) (h₂ : ∀ x ∈ s, 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_on ℂ (λ t, log (f t)) s := λ x hx, (h₁ x hx).clog (h₂ x hx) lemma differentiable.clog {f : E → ℂ} (h₁ : differentiable ℂ f) (h₂ : ∀ x, 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable ℂ (λ t, log (f t)) := λ x, (h₁ x).clog (h₂ x) end log_deriv
ba4874c59df08ef19f932e0b1daceaea2190a67c
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/polynomial/degree/basic.lean
ab8da6a509b430bbf375b04cfa4908d8c1934271
[ "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
34,939
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.coeff import data.nat.with_bot /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} section semiring variables [semiring R] {p q r : polynomial R} /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial R) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial R, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial R) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial R) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial R) := leading_coeff p = (1 : R) @[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : polynomial R) : monic p := subsingleton.elim _ _ lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : polynomial R} (hp : p.monic) : leading_coeff p = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial R) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial R) = 0 := rfl @[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : polynomial R} {n : ℕ} (hn : 0 < n) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : polynomial R} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := with_bot.gi_get_or_else_bot.gc.le_u_l _ lemma nat_degree_eq_of_degree_eq [semiring S] {q : polynomial S} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma le_nat_degree_of_mem_supp (a : ℕ) : a ∈ p.support → a ≤ nat_degree p:= le_nat_degree_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m := λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) := supp_subset_range (nat.lt_succ_self _) lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := mt $ λ h, by rw [nat_degree, h, option.get_or_else_coe] theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n := with_bot.get_or_else_bot_le_iff alias polynomial.nat_degree_le_iff_degree_le ↔ . . lemma nat_degree_le_nat_degree (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := with_bot.gi_get_or_else_bot.gc.monotone_l hpq @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial R) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial R) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := by rw [degree, support_monomial _ _ ha]; refl @[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree_monomial n ha] lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n := if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h) lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le } @[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha) @[simp] lemma nat_degree_monomial (i : ℕ) (r : R) (hr : r ≠ 0) : nat_degree (monomial i r) = i := by rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : polynomial R} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : polynomial R} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial R) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite (n < 1 + nat_degree p) I _ (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum_support (p : polynomial R) : p = ∑ i in p.support, monomial i (p.coeff i) := p.sum_single.symm lemma as_sum_support_C_mul_X_pow (p : polynomial R) : p = ∑ i in p.support, C (p.coeff i) * X^i := trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial] /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := finsupp.sum_of_support_subset _ (supp_subset_range w) _ $ λ n hn, h n /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ lemma sum_over_range [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) lemma as_sum_range' (p : polynomial R) (n : ℕ) (w : p.nat_degree < n) : p = ∑ i in range n, monomial i (coeff p i) := p.sum_single.symm.trans $ p.sum_over_range' (λ n, single_zero) _ w lemma as_sum_range (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) := p.sum_single.symm.trans $ p.sum_over_range $ λ n, single_zero lemma as_sum_range_C_mul_X_pow (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i := p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial] lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : ∃ a b, p = C a * X + C b := ⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩ theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial R) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R) theorem degree_X_le : degree (X : polynomial R) ≤ 1 := degree_monomial_le _ _ lemma nat_degree_X_le : (X : polynomial R).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le lemma support_C_mul_X_pow (c : R) (n : ℕ) : (C c * X ^ n).support ⊆ singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_single_subset end lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n := mem_singleton.1 $ support_C_mul_X_pow _ _ h lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 := begin rw ← card_singleton n, apply card_le_of_subset (support_C_mul_X_pow c n), end lemma card_supp_le_succ_nat_degree (p : polynomial R) : p.support.card ≤ p.nat_degree + 1 := begin rw ← finset.card_range (p.nat_degree + 1), exact finset.card_le_of_subset supp_subset_range_nat_degree_succ, end lemma le_degree_of_mem_supp (a : ℕ) : a ∈ p.support → ↑a ≤ degree p := le_degree_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 := by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty] lemma support_C_mul_X_pow_nonzero {c : R} {n : ℕ} (h : c ≠ 0) : (C c * X ^ n).support = singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_single_ne_zero h end end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_one : degree (1 : polynomial R) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial R) = 1 := degree_monomial _ one_ne_zero @[simp] lemma nat_degree_X : (X : polynomial R).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : polynomial R} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] lemma C_eq_int_cast (n : ℤ) : C (n : R) = n := (C : R →+* _).map_int_cast n @[simp] lemma degree_neg (p : polynomial R) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : polynomial R) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_int_cast, nat_degree_C] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : polynomial R) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : polynomial R) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : polynomial R} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin ext (_|n), { simp }, rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt], exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos), end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial R) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support := (p.mem_support_to_fun p.nat_degree).mpr ((not_congr leading_coeff_eq_zero).mpr H) lemma nat_degree_eq_support_max' (h : p ≠ 0) : p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) := begin apply le_antisymm, { apply finset.le_max', rw mem_support_iff_coeff_ne_zero, exact (not_congr leading_coeff_eq_zero).mpr h, }, { apply max'_le, refine le_nat_degree_of_mem_supp, }, end lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n := begin by_cases a0 : a = 0, { rw [a0, C_0, zero_mul, nat_degree_zero], exact nat.zero_le n, }, { rw nat_degree_eq_support_max', { simp_rw [support_C_mul_X_pow_nonzero a0, max'_singleton n], }, { intro, apply a0, rw [← C_inj, C_0], apply mul_X_pow_eq_zero ‹_›, }, }, end lemma nat_degree_C_mul_X_pow_of_nonzero {a : R} (n : ℕ) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := begin rw nat_degree_eq_support_max', { simp_rw [support_C_mul_X_pow_nonzero ha, max'_singleton n], }, { intro, apply ha, rw [← C_inj, C_0], exact mul_X_pow_eq_zero ‹_›, }, end lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial R) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset ι) (f : ι → polynomial R) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial R) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial R) : ∀ n, degree (p ^ n) ≤ n •ℕ (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree_C_mul_X_pow _ _ ha, C_mul_X_pow_eq_monomial], exact @finsupp.single_eq_same _ _ _ n a } end @[simp] lemma leading_coeff_monomial' (a : R) (n : ℕ) : leading_coeff (monomial n a) = a := by rw [← C_mul_X_pow_eq_monomial, leading_coeff_monomial] @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial R) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial R) := leading_coeff_C _ lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { rintro rfl, simpa [monic] using hp } lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { nontriviality R, exact hp.ne_zero } lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 := by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero } lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial R) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n •ℕ (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial R) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : R) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial R) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] theorem leading_coeff_mul_X_pow {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma nat_degree_mul_le {p q : polynomial R} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial R)) : (∀ p q : polynomial R, p = q) ∧ (∀ a b : R, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma zero_le_degree_iff {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := ⟨λ h0p hp0, absurd h0p (by rw [hp0, degree_zero]; exact dec_trivial), λ hp0, le_of_not_gt (λ h, by simp [gt, degree_eq_bot, *] at *)⟩ lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := by rw [← le_zero_iff_eq, nat_degree_le_iff_degree_le, with_bot.coe_zero] theorem degree_le_iff_coeff_zero (f : polynomial R) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem degree_lt_iff_coeff_zero (f : polynomial R) (n : ℕ) : degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 := begin refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩, simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ], exact λ h m, mt (h m), end lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nontrivial.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma nat_degree_pos_iff_degree_pos {p : polynomial R} : 0 < nat_degree p ↔ 0 < degree p := lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le lemma eq_C_of_nat_degree_le_zero {p : polynomial R} (h : nat_degree p ≤ 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h lemma eq_C_of_nat_degree_eq_zero {p : polynomial R} (h : nat_degree p = 0) : p = C (coeff p 0) := eq_C_of_nat_degree_le_zero h.le end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_X_pow (n : ℕ) : degree ((X : polynomial R) ^ n) = n := by rw [X_pow_eq_monomial, degree_monomial _ (@one_ne_zero R _ _)] theorem not_is_unit_X : ¬ is_unit (X : polynomial R) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { rw [← coeff_one_zero, ← hgf], simp } end nonzero_semiring section ring variables [ring R] {p q : polynomial R} lemma degree_sub_le (p q : polynomial R) : degree (p - q) ≤ max (degree p) (degree q) := degree_neg q ▸ degree_add_le p (-q) lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase _ _, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase _ _, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma nat_degree_X_sub_C_le {r : R} : (X - C r).nat_degree ≤ 1 := nat_degree_le_iff_degree_le.2 $ le_trans (degree_sub_le _ _) $ max_le degree_X_le $ le_trans degree_C_le $ with_bot.coe_le_coe.2 zero_le_one end ring section nonzero_ring variables [nontrivial R] [ring R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X R], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C (c : R) : next_coeff (X - C c) = - c := by simp [next_coeff_of_pos_nat_degree] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : polynomial R) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial R) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial R) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : polynomial R) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial R) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn a; exact dec_trivial) theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : polynomial R) ▸ X_pow_sub_C_ne_zero zero_lt_one r lemma nat_degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).nat_degree = n := by { apply nat_degree_eq_of_degree_eq_some, simp [degree_X_pow_sub_C hn], } end nonzero_ring section integral_domain variables [integral_domain R] {p q : polynomial R} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow (p : polynomial R) (n : ℕ) : degree (p ^ n) = n •ℕ (degree p) := by induction n; [simp only [pow_zero, degree_one, zero_nsmul], simp only [*, pow_succ, succ_nsmul, degree_mul]] @[simp] lemma leading_coeff_mul (p q : polynomial R) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_X_add_C (a b : R) (ha : a ≠ 0): leading_coeff (C a * X + C b) = a := begin rw [add_comm, leading_coeff_add_of_degree_lt], { simp }, { simpa [degree_C ha] using lt_of_le_of_lt degree_C_le (with_bot.coe_lt_coe.2 zero_lt_one)} end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` is an `integral_domain`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : polynomial R →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : polynomial R) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := leading_coeff_hom.map_pow p n end integral_domain end polynomial
d0978da2ee521ae5bf153e608edc26000491954c
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/derivation.lean
6c26455cd83f9e546fd576313a318fd9fc6628e7
[ "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
8,061
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import algebra.lie.basic import ring_theory.algebra_tower /-! # Derivations This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an `R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`. ## Notation The notation `⁅D1, D2⁆` is used for the commutator of two derivations. TODO: this file is just a stub to go on with some PRs in the geometry section. It only implements the definition of derivations in commutative algebra. This will soon change: as soon as bimodules will be there in mathlib I will change this file to take into account the non-commutative case. Any development on the theory of derivations is discouraged until the definitive definition of derivation will be implemented. -/ open algebra ring_hom /-- `D : derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz` equality. TODO: update this when bimodules are defined. -/ @[protect_proj] structure derivation (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] (M : Type*) [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] extends A →ₗ[R] M := (leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a) namespace derivation section variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] variables [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩ instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) := ⟨λ D, D.to_linear_map⟩ @[simp] lemma to_fun_eq_coe : D.to_fun = ⇑D := rfl @[simp, norm_cast] lemma coe_fn_coe (f : derivation R A M) : ⇑(f : A →ₗ[R] M) = f := rfl lemma coe_injective (H : ⇑D1 = D2) : D1 = D2 := by { cases D1, cases D2, congr', exact linear_map.coe_injective H } @[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 := coe_injective $ funext H @[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b @[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D @[simp] lemma map_smul : D (r • a) = r • D a := linear_map.map_smul D r a @[simp] lemma leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _ @[simp] lemma map_one_eq_zero : D 1 = 0 := begin have h : D 1 = D (1 * 1) := by rw mul_one, rw [leibniz D 1 1, one_smul] at h, exact eq_zero_of_left_cancel_add_self h, end @[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 := by rw [←mul_one r, ring_hom.map_mul, map_one, ←smul_def, map_smul, map_one_eq_zero, smul_zero] instance : has_zero (derivation R A M) := ⟨⟨(0 : A →ₗ[R] M), λ a b, by simp only [add_zero, linear_map.zero_apply, linear_map.to_fun_eq_coe, smul_zero]⟩⟩ instance : inhabited (derivation R A M) := ⟨0⟩ instance : add_comm_monoid (derivation R A M) := { add := λ D1 D2, ⟨D1 + D2, λ a b, by { simp only [leibniz, linear_map.add_apply, linear_map.to_fun_eq_coe, coe_fn_coe, smul_add], cc }⟩, add_assoc := λ D E F, ext $ λ a, add_assoc _ _ _, zero_add := λ D, ext $ λ a, zero_add _, add_zero := λ D, ext $ λ a, add_zero _, add_comm := λ D E, ext $ λ a, add_comm _ _, ..derivation.has_zero } @[simp] lemma add_apply : (D1 + D2) a = D1 a + D2 a := rfl @[priority 100] instance derivation.Rsemimodule : semimodule R (derivation R A M) := { smul := λ r D, ⟨r • D, λ a b, by simp only [linear_map.smul_apply, leibniz, linear_map.to_fun_eq_coe, smul_algebra_smul_comm, coe_fn_coe, smul_add, add_comm],⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul _ _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul _ _ } @[simp] lemma smul_to_linear_map_coe : ↑(r • D) = (r • D : A →ₗ[R] M) := rfl @[simp] lemma Rsmul_apply : (r • D) a = r • D a := rfl instance : semimodule A (derivation R A M) := { smul := λ a D, ⟨⟨λ b, a • D b, λ a1 a2, by rw [D.map_add, smul_add], λ a1 a2, by rw [D.map_smul, smul_algebra_smul_comm]⟩, λ b c, by { dsimp, simp only [smul_add, leibniz, smul_comm, add_comm] }⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul A _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul A _ } @[simp] lemma smul_apply : (a • D) b = a • D b := rfl instance : is_scalar_tower R A (derivation R A M) := ⟨λ x y z, ext (λ a, smul_assoc _ _ _)⟩ end section variables {R : Type*} [comm_ring R] variables {A : Type*} [comm_ring A] [algebra R A] section variables {M : Type*} [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) @[simp] lemma map_neg : D (-a) = -D a := linear_map.map_neg D a @[simp] lemma map_sub : D (a - b) = D a - D b := linear_map.map_sub D a b instance : add_comm_group (derivation R A M) := { neg := λ D, ⟨-D, λ a b, by simp only [linear_map.neg_apply, smul_neg, neg_add_rev, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, add_comm]⟩, add_left_neg := λ D, ext $ λ a, add_left_neg _, ..derivation.add_comm_monoid } end section lie_structures /-! # Lie structures -/ variables (D : derivation R A A) {D1 D2 : derivation R A A} (r : R) (a b : A) open ring_commutator /-- The commutator of derivations is again a derivation. -/ def commutator (D1 D2 : derivation R A A) : derivation R A A := ⟨⁅D1, D2⁆, λ a b, by {simp only [commutator, map_add, id.smul_eq_mul, linear_map.mul_app, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, linear_map.sub_apply], ring }⟩ instance : has_bracket (derivation R A A) := ⟨derivation.commutator⟩ @[simp] lemma commutator_coe_linear_map : ↑⁅D1, D2⁆ = (⁅D1, D2⁆ : A →ₗ[R] A) := rfl lemma commutator_apply : ⁅D1, D2⁆ a = D1 (D2 a) - D2 (D1 a) := rfl instance : lie_ring (derivation R A A) := { add_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring }, lie_add := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring }, lie_self := λ d, by { ext a, simp only [commutator_apply, add_apply, map_add], ring }, jacobi := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_sub], ring } } instance : lie_algebra R (derivation R A A) := { lie_smul := λ r d e, by { ext a, simp only [commutator_apply, map_smul, smul_sub, Rsmul_apply]}, ..derivation.Rsemimodule } end lie_structures end end derivation section comp_der namespace linear_map variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] variables {N : Type*} [add_cancel_comm_monoid N] [semimodule A N] [semimodule R N] variables [is_scalar_tower R A M] [is_scalar_tower R A N] /-- The composition of a linear map and a derivation is a derivation. -/ def comp_der (f : M →ₗ[A] N) (D : derivation R A M) : derivation R A N := { to_fun := λ a, f (D a), map_add' := λ a1 a2, by rw [D.map_add, f.map_add], map_smul' := λ r a, by rw [derivation.map_smul, map_smul_eq_smul_map], leibniz' := λ a b, by simp only [derivation.leibniz, linear_map.map_smul, linear_map.map_add, add_comm] } @[simp] lemma comp_der_apply (f : M →ₗ[A] N) (D : derivation R A M) (a : A) : f.comp_der D a = f (D a) := rfl end linear_map end comp_der
f1ab4d0002e3fc4f716f6ee6b2462a6a1b27b7d0
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/normed/group/basic.lean
3eba78c8551d9981b7810ae98c212f00178c04f9
[ "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
82,343
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, Yaël Dillies -/ import analysis.normed.group.seminorm import order.liminf_limsup import topology.algebra.uniform_group import topology.metric_space.algebra import topology.metric_space.isometry import topology.sequences /-! # Normed (semi)groups In this file we define 10 classes: * `has_norm`, `has_nnnorm`: auxiliary classes endowing a type `α` with a function `norm : α → ℝ` (notation: `‖x‖`) and `nnnorm : α → ℝ≥0` (notation: `‖x‖₊`), respectively; * `seminormed_..._group`: A seminormed (additive) (commutative) group is an (additive) (commutative) group with a norm and a compatible pseudometric space structure: `∀ x y, dist x y = ‖x / y‖` or `∀ x y, dist x y = ‖x - y‖`, depending on the group operation. * `normed_..._group`: A normed (additive) (commutative) group is an (additive) (commutative) group with a norm and a compatible metric space structure. We also prove basic properties of (semi)normed groups and provide some instances. ## Notes The current convention `dist x y = ‖x - y‖` means that the distance is invariant under right addition, but actions in mathlib are usually from the left. This means we might want to change it to `dist x y = ‖-x + y‖`. The normed group hierarchy would lend itself well to a mixin design (that is, having `seminormed_group` and `seminormed_add_group` not extend `group` and `add_group`), but we choose not to for performance concerns. ## Tags normed group -/ variables {𝓕 𝕜 α ι κ E F G : Type*} open filter function metric open_locale big_operators ennreal filter nnreal uniformity pointwise topological_space /-- Auxiliary class, endowing a type `E` with a function `norm : E → ℝ` with notation `‖x‖`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ @[notation_class] class has_norm (E : Type*) := (norm : E → ℝ) /-- Auxiliary class, endowing a type `α` with a function `nnnorm : α → ℝ≥0` with notation `‖x‖₊`. -/ @[notation_class] class has_nnnorm (E : Type*) := (nnnorm : E → ℝ≥0) export has_norm (norm) export has_nnnorm (nnnorm) notation `‖` e `‖` := norm e notation `‖` e `‖₊` := nnnorm e /-- A seminormed group is an additive group endowed with a norm for which `dist x y = ‖x - y‖` defines a pseudometric space structure. -/ class seminormed_add_group (E : Type*) extends has_norm E, add_group E, pseudo_metric_space E := (dist := λ x y, ‖x - y‖) (dist_eq : ∀ x y, dist x y = ‖x - y‖ . obviously) /-- A seminormed group is a group endowed with a norm for which `dist x y = ‖x / y‖` defines a pseudometric space structure. -/ @[to_additive] class seminormed_group (E : Type*) extends has_norm E, group E, pseudo_metric_space E := (dist := λ x y, ‖x / y‖) (dist_eq : ∀ x y, dist x y = ‖x / y‖ . obviously) /-- A normed group is an additive group endowed with a norm for which `dist x y = ‖x - y‖` defines a metric space structure. -/ class normed_add_group (E : Type*) extends has_norm E, add_group E, metric_space E := (dist := λ x y, ‖x - y‖) (dist_eq : ∀ x y, dist x y = ‖x - y‖ . obviously) /-- A normed group is a group endowed with a norm for which `dist x y = ‖x / y‖` defines a metric space structure. -/ @[to_additive] class normed_group (E : Type*) extends has_norm E, group E, metric_space E := (dist := λ x y, ‖x / y‖) (dist_eq : ∀ x y, dist x y = ‖x / y‖ . obviously) /-- A seminormed group is an additive group endowed with a norm for which `dist x y = ‖x - y‖` defines a pseudometric space structure. -/ class seminormed_add_comm_group (E : Type*) extends has_norm E, add_comm_group E, pseudo_metric_space E := (dist := λ x y, ‖x - y‖) (dist_eq : ∀ x y, dist x y = ‖x - y‖ . obviously) /-- A seminormed group is a group endowed with a norm for which `dist x y = ‖x / y‖` defines a pseudometric space structure. -/ @[to_additive] class seminormed_comm_group (E : Type*) extends has_norm E, comm_group E, pseudo_metric_space E := (dist := λ x y, ‖x / y‖) (dist_eq : ∀ x y, dist x y = ‖x / y‖ . obviously) /-- A normed group is an additive group endowed with a norm for which `dist x y = ‖x - y‖` defines a metric space structure. -/ class normed_add_comm_group (E : Type*) extends has_norm E, add_comm_group E, metric_space E := (dist := λ x y, ‖x - y‖) (dist_eq : ∀ x y, dist x y = ‖x - y‖ . obviously) /-- A normed group is a group endowed with a norm for which `dist x y = ‖x / y‖` defines a metric space structure. -/ @[to_additive] class normed_comm_group (E : Type*) extends has_norm E, comm_group E, metric_space E := (dist := λ x y, ‖x / y‖) (dist_eq : ∀ x y, dist x y = ‖x / y‖ . obviously) @[priority 100, to_additive] -- See note [lower instance priority] instance normed_group.to_seminormed_group [normed_group E] : seminormed_group E := { ..‹normed_group E› } @[priority 100, to_additive] -- See note [lower instance priority] instance normed_comm_group.to_seminormed_comm_group [normed_comm_group E] : seminormed_comm_group E := { ..‹normed_comm_group E› } @[priority 100, to_additive] -- See note [lower instance priority] instance seminormed_comm_group.to_seminormed_group [seminormed_comm_group E] : seminormed_group E := { ..‹seminormed_comm_group E› } @[priority 100, to_additive] -- See note [lower instance priority] instance normed_comm_group.to_normed_group [normed_comm_group E] : normed_group E := { ..‹normed_comm_group E› } /-- Construct a `normed_group` from a `seminormed_group` satisfying `∀ x, ‖x‖ = 0 → x = 1`. This avoids having to go back to the `(pseudo_)metric_space` level when declaring a `normed_group` instance as a special case of a more general `seminormed_group` instance. -/ @[to_additive "Construct a `normed_add_group` from a `seminormed_add_group` satisfying `∀ x, ‖x‖ = 0 → x = 0`. This avoids having to go back to the `(pseudo_)metric_space` level when declaring a `normed_add_group` instance as a special case of a more general `seminormed_add_group` instance.", reducible] -- See note [reducible non-instances] def normed_group.of_separation [seminormed_group E] (h : ∀ x : E, ‖x‖ = 0 → x = 1) : normed_group E := { to_metric_space := { eq_of_dist_eq_zero := λ x y hxy, div_eq_one.1 $ h _ $ by rwa ←‹seminormed_group E›.dist_eq }, ..‹seminormed_group E› } /-- Construct a `normed_comm_group` from a `seminormed_comm_group` satisfying `∀ x, ‖x‖ = 0 → x = 1`. This avoids having to go back to the `(pseudo_)metric_space` level when declaring a `normed_comm_group` instance as a special case of a more general `seminormed_comm_group` instance. -/ @[to_additive "Construct a `normed_add_comm_group` from a `seminormed_add_comm_group` satisfying `∀ x, ‖x‖ = 0 → x = 0`. This avoids having to go back to the `(pseudo_)metric_space` level when declaring a `normed_add_comm_group` instance as a special case of a more general `seminormed_add_comm_group` instance.", reducible] -- See note [reducible non-instances] def normed_comm_group.of_separation [seminormed_comm_group E] (h : ∀ x : E, ‖x‖ = 0 → x = 1) : normed_comm_group E := { ..‹seminormed_comm_group E›, ..normed_group.of_separation h } /-- Construct a seminormed group from a multiplication-invariant distance. -/ @[to_additive "Construct a seminormed group from a translation-invariant distance."] def seminormed_group.of_mul_dist [has_norm E] [group E] [pseudo_metric_space E] (h₁ : ∀ x : E, ‖x‖ = dist x 1) (h₂ : ∀ x y z : E, dist x y ≤ dist (x * z) (y * z)) : seminormed_group E := { dist_eq := λ x y, begin rw h₁, apply le_antisymm, { simpa only [div_eq_mul_inv, ← mul_right_inv y] using h₂ _ _ _ }, { simpa only [div_mul_cancel', one_mul] using h₂ (x/y) 1 y } end } /-- Construct a seminormed group from a multiplication-invariant pseudodistance. -/ @[to_additive "Construct a seminormed group from a translation-invariant pseudodistance."] def seminormed_group.of_mul_dist' [has_norm E] [group E] [pseudo_metric_space E] (h₁ : ∀ x : E, ‖x‖ = dist x 1) (h₂ : ∀ x y z : E, dist (x * z) (y * z) ≤ dist x y) : seminormed_group E := { dist_eq := λ x y, begin rw h₁, apply le_antisymm, { simpa only [div_mul_cancel', one_mul] using h₂ (x/y) 1 y }, { simpa only [div_eq_mul_inv, ← mul_right_inv y] using h₂ _ _ _ } end } /-- Construct a seminormed group from a multiplication-invariant pseudodistance. -/ @[to_additive "Construct a seminormed group from a translation-invariant pseudodistance."] def seminormed_comm_group.of_mul_dist [has_norm E] [comm_group E] [pseudo_metric_space E] (h₁ : ∀ x : E, ‖x‖ = dist x 1) (h₂ : ∀ x y z : E, dist x y ≤ dist (x * z) (y * z)) : seminormed_comm_group E := { ..seminormed_group.of_mul_dist h₁ h₂ } /-- Construct a seminormed group from a multiplication-invariant pseudodistance. -/ @[to_additive "Construct a seminormed group from a translation-invariant pseudodistance."] def seminormed_comm_group.of_mul_dist' [has_norm E] [comm_group E] [pseudo_metric_space E] (h₁ : ∀ x : E, ‖x‖ = dist x 1) (h₂ : ∀ x y z : E, dist (x * z) (y * z) ≤ dist x y) : seminormed_comm_group E := { ..seminormed_group.of_mul_dist' h₁ h₂ } /-- Construct a normed group from a multiplication-invariant distance. -/ @[to_additive "Construct a normed group from a translation-invariant distance."] def normed_group.of_mul_dist [has_norm E] [group E] [metric_space E] (h₁ : ∀ x : E, ‖x‖ = dist x 1) (h₂ : ∀ x y z : E, dist x y ≤ dist (x * z) (y * z)) : normed_group E := { ..seminormed_group.of_mul_dist h₁ h₂ } /-- Construct a normed group from a multiplication-invariant pseudodistance. -/ @[to_additive "Construct a normed group from a translation-invariant pseudodistance."] def normed_group.of_mul_dist' [has_norm E] [group E] [metric_space E] (h₁ : ∀ x : E, ‖x‖ = dist x 1) (h₂ : ∀ x y z : E, dist (x * z) (y * z) ≤ dist x y) : normed_group E := { ..seminormed_group.of_mul_dist' h₁ h₂ } /-- Construct a normed group from a multiplication-invariant pseudodistance. -/ @[to_additive "Construct a normed group from a translation-invariant pseudodistance."] def normed_comm_group.of_mul_dist [has_norm E] [comm_group E] [metric_space E] (h₁ : ∀ x : E, ‖x‖ = dist x 1) (h₂ : ∀ x y z : E, dist x y ≤ dist (x * z) (y * z)) : normed_comm_group E := { ..normed_group.of_mul_dist h₁ h₂ } /-- Construct a normed group from a multiplication-invariant pseudodistance. -/ @[to_additive "Construct a normed group from a translation-invariant pseudodistance."] def normed_comm_group.of_mul_dist' [has_norm E] [comm_group E] [metric_space E] (h₁ : ∀ x : E, ‖x‖ = dist x 1) (h₂ : ∀ x y z : E, dist (x * z) (y * z) ≤ dist x y) : normed_comm_group E := { ..normed_group.of_mul_dist' h₁ h₂ } set_option old_structure_cmd true /-- Construct a seminormed group from a seminorm, i.e., registering the pseudodistance and the pseudometric space structure from the seminorm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`). -/ @[to_additive "Construct a seminormed group from a seminorm, i.e., registering the pseudodistance* and the pseudometric space structure from the seminorm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`)."] def group_seminorm.to_seminormed_group [group E] (f : group_seminorm E) : seminormed_group E := { dist := λ x y, f (x / y), norm := f, dist_eq := λ x y, rfl, dist_self := λ x, by simp only [div_self', map_one_eq_zero], dist_triangle := le_map_div_add_map_div f, dist_comm := map_div_rev f } /-- Construct a seminormed group from a seminorm, i.e., registering the pseudodistance and the pseudometric space structure from the seminorm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`). -/ @[to_additive "Construct a seminormed group from a seminorm, i.e., registering the pseudodistance* and the pseudometric space structure from the seminorm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`)."] def group_seminorm.to_seminormed_comm_group [comm_group E] (f : group_seminorm E) : seminormed_comm_group E := { ..f.to_seminormed_group } /-- Construct a normed group from a norm, i.e., registering the distance and the metric space structure from the norm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`). -/ @[to_additive "Construct a normed group from a norm, i.e., registering the distance and the metric space structure from the norm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`)."] def group_norm.to_normed_group [group E] (f : group_norm E) : normed_group E := { eq_of_dist_eq_zero := λ x y h, div_eq_one.1 $ eq_one_of_map_eq_zero f h, ..f.to_group_seminorm.to_seminormed_group } /-- Construct a normed group from a norm, i.e., registering the distance and the metric space structure from the norm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`). -/ @[to_additive "Construct a normed group from a norm, i.e., registering the distance and the metric space structure from the norm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`)."] def group_norm.to_normed_comm_group [comm_group E] (f : group_norm E) : normed_comm_group E := { ..f.to_normed_group } instance : normed_add_comm_group punit := { norm := function.const _ 0, dist_eq := λ _ _, rfl, } @[simp] lemma punit.norm_eq_zero (r : punit) : ‖r‖ = 0 := rfl section seminormed_group variables [seminormed_group E] [seminormed_group F] [seminormed_group G] {s : set E} {a a₁ a₂ b b₁ b₂ : E} {r r₁ r₂ : ℝ} @[to_additive] lemma dist_eq_norm_div (a b : E) : dist a b = ‖a / b‖ := seminormed_group.dist_eq _ _ @[to_additive] lemma dist_eq_norm_div' (a b : E) : dist a b = ‖b / a‖ := by rw [dist_comm, dist_eq_norm_div] alias dist_eq_norm_sub ← dist_eq_norm alias dist_eq_norm_sub' ← dist_eq_norm' @[simp, to_additive] lemma dist_one_right (a : E) : dist a 1 = ‖a‖ := by rw [dist_eq_norm_div, div_one] @[simp, to_additive] lemma dist_one_left : dist (1 : E) = norm := funext $ λ a, by rw [dist_comm, dist_one_right] @[to_additive] lemma isometry.norm_map_of_map_one {f : E → F} (hi : isometry f) (h₁ : f 1 = 1) (x : E) : ‖f x‖ = ‖x‖ := by rw [←dist_one_right, ←h₁, hi.dist_eq, dist_one_right] @[to_additive tendsto_norm_cocompact_at_top] lemma tendsto_norm_cocompact_at_top' [proper_space E] : tendsto norm (cocompact E) at_top := by simpa only [dist_one_right] using tendsto_dist_right_cocompact_at_top (1 : E) @[to_additive] lemma norm_div_rev (a b : E) : ‖a / b‖ = ‖b / a‖ := by simpa only [dist_eq_norm_div] using dist_comm a b @[simp, to_additive norm_neg] lemma norm_inv' (a : E) : ‖a⁻¹‖ = ‖a‖ := by simpa using norm_div_rev 1 a @[simp, to_additive] lemma dist_mul_right (a₁ a₂ b : E) : dist (a₁ * b) (a₂ * b) = dist a₁ a₂ := by simp [dist_eq_norm_div] @[simp, to_additive] lemma dist_mul_self_right (a b : E) : dist b (a * b) = ‖a‖ := by rw [←dist_one_left, ←dist_mul_right 1 a b, one_mul] @[simp, to_additive] lemma dist_mul_self_left (a b : E) : dist (a * b) b = ‖a‖ := by rw [dist_comm, dist_mul_self_right] @[to_additive] lemma dist_div_right (a₁ a₂ b : E) : dist (a₁ / b) (a₂ / b) = dist a₁ a₂ := by simpa only [div_eq_mul_inv] using dist_mul_right _ _ _ @[simp, to_additive] lemma dist_div_eq_dist_mul_left (a b c : E) : dist (a / b) c = dist a (c * b) := by rw [←dist_mul_right _ _ b, div_mul_cancel'] @[simp, to_additive] lemma dist_div_eq_dist_mul_right (a b c : E) : dist a (b / c) = dist (a * c) b := by rw [←dist_mul_right _ _ c, div_mul_cancel'] /-- In a (semi)normed group, inversion `x ↦ x⁻¹` tends to infinity at infinity. TODO: use `bornology.cobounded` instead of `filter.comap has_norm.norm filter.at_top`. -/ @[to_additive "In a (semi)normed group, negation `x ↦ -x` tends to infinity at infinity. TODO: use `bornology.cobounded` instead of `filter.comap has_norm.norm filter.at_top`."] lemma filter.tendsto_inv_cobounded : tendsto (has_inv.inv : E → E) (comap norm at_top) (comap norm at_top) := by simpa only [norm_inv', tendsto_comap_iff, (∘)] using tendsto_comap /-- **Triangle inequality** for the norm. -/ @[to_additive norm_add_le "**Triangle inequality** for the norm."] lemma norm_mul_le' (a b : E) : ‖a * b‖ ≤ ‖a‖ + ‖b‖ := by simpa [dist_eq_norm_div] using dist_triangle a 1 b⁻¹ @[to_additive] lemma norm_mul_le_of_le (h₁ : ‖a₁‖ ≤ r₁) (h₂ : ‖a₂‖ ≤ r₂) : ‖a₁ * a₂‖ ≤ r₁ + r₂ := (norm_mul_le' a₁ a₂).trans $ add_le_add h₁ h₂ @[to_additive norm_add₃_le] lemma norm_mul₃_le (a b c : E) : ‖a * b * c‖ ≤ ‖a‖ + ‖b‖ + ‖c‖ := norm_mul_le_of_le (norm_mul_le' _ _) le_rfl @[simp, to_additive norm_nonneg] lemma norm_nonneg' (a : E) : 0 ≤ ‖a‖ := by { rw [←dist_one_right], exact dist_nonneg } section open tactic tactic.positivity /-- Extension for the `positivity` tactic: norms are nonnegative. -/ @[positivity] meta def _root_.tactic.positivity_norm : expr → tactic strictness | `(‖%%a‖) := nonnegative <$> mk_app ``norm_nonneg [a] <|> nonnegative <$> mk_app ``norm_nonneg' [a] | _ := failed end @[simp, to_additive norm_zero] lemma norm_one' : ‖(1 : E)‖ = 0 := by rw [←dist_one_right, dist_self] @[to_additive] lemma ne_one_of_norm_ne_zero : ‖a‖ ≠ 0 → a ≠ 1 := mt $ by { rintro rfl, exact norm_one' } @[nontriviality, to_additive norm_of_subsingleton] lemma norm_of_subsingleton' [subsingleton E] (a : E) : ‖a‖ = 0 := by rw [subsingleton.elim a 1, norm_one'] attribute [nontriviality] norm_of_subsingleton @[to_additive zero_lt_one_add_norm_sq] lemma zero_lt_one_add_norm_sq' (x : E) : 0 < 1 + ‖x‖^2 := by positivity @[to_additive] lemma norm_div_le (a b : E) : ‖a / b‖ ≤ ‖a‖ + ‖b‖ := by simpa [dist_eq_norm_div] using dist_triangle a 1 b @[to_additive] lemma norm_div_le_of_le {r₁ r₂ : ℝ} (H₁ : ‖a₁‖ ≤ r₁) (H₂ : ‖a₂‖ ≤ r₂) : ‖a₁ / a₂‖ ≤ r₁ + r₂ := (norm_div_le a₁ a₂).trans $ add_le_add H₁ H₂ @[to_additive] lemma dist_le_norm_mul_norm (a b : E) : dist a b ≤ ‖a‖ + ‖b‖ := by { rw dist_eq_norm_div, apply norm_div_le } @[to_additive abs_norm_sub_norm_le] lemma abs_norm_sub_norm_le' (a b : E) : |‖a‖ - ‖b‖| ≤ ‖a / b‖ := by simpa [dist_eq_norm_div] using abs_dist_sub_le a b 1 @[to_additive norm_sub_norm_le] lemma norm_sub_norm_le' (a b : E) : ‖a‖ - ‖b‖ ≤ ‖a / b‖ := (le_abs_self _).trans (abs_norm_sub_norm_le' a b) @[to_additive dist_norm_norm_le] lemma dist_norm_norm_le' (a b : E) : dist ‖a‖ ‖b‖ ≤ ‖a / b‖ := abs_norm_sub_norm_le' a b @[to_additive] lemma norm_le_norm_add_norm_div' (u v : E) : ‖u‖ ≤ ‖v‖ + ‖u / v‖ := by { rw add_comm, refine (norm_mul_le' _ _).trans_eq' _, rw div_mul_cancel' } @[to_additive] lemma norm_le_norm_add_norm_div (u v : E) : ‖v‖ ≤ ‖u‖ + ‖u / v‖ := by { rw norm_div_rev, exact norm_le_norm_add_norm_div' v u } alias norm_le_norm_add_norm_sub' ← norm_le_insert' alias norm_le_norm_add_norm_sub ← norm_le_insert @[to_additive] lemma norm_le_mul_norm_add (u v : E) : ‖u‖ ≤ ‖u * v‖ + ‖v‖ := calc ‖u‖ = ‖u * v / v‖ : by rw mul_div_cancel'' ... ≤ ‖u * v‖ + ‖v‖ : norm_div_le _ _ @[to_additive ball_eq] lemma ball_eq' (y : E) (ε : ℝ) : ball y ε = {x | ‖x / y‖ < ε} := set.ext $ λ a, by simp [dist_eq_norm_div] @[to_additive] lemma ball_one_eq (r : ℝ) : ball (1 : E) r = {x | ‖x‖ < r} := set.ext $ assume a, by simp @[to_additive mem_ball_iff_norm] lemma mem_ball_iff_norm'' : b ∈ ball a r ↔ ‖b / a‖ < r := by rw [mem_ball, dist_eq_norm_div] @[to_additive mem_ball_iff_norm'] lemma mem_ball_iff_norm''' : b ∈ ball a r ↔ ‖a / b‖ < r := by rw [mem_ball', dist_eq_norm_div] @[simp, to_additive] lemma mem_ball_one_iff : a ∈ ball (1 : E) r ↔ ‖a‖ < r := by rw [mem_ball, dist_one_right] @[to_additive mem_closed_ball_iff_norm] lemma mem_closed_ball_iff_norm'' : b ∈ closed_ball a r ↔ ‖b / a‖ ≤ r := by rw [mem_closed_ball, dist_eq_norm_div] @[simp, to_additive] lemma mem_closed_ball_one_iff : a ∈ closed_ball (1 : E) r ↔ ‖a‖ ≤ r := by rw [mem_closed_ball, dist_one_right] @[to_additive mem_closed_ball_iff_norm'] lemma mem_closed_ball_iff_norm''' : b ∈ closed_ball a r ↔ ‖a / b‖ ≤ r := by rw [mem_closed_ball', dist_eq_norm_div] @[to_additive norm_le_of_mem_closed_ball] lemma norm_le_of_mem_closed_ball' (h : b ∈ closed_ball a r) : ‖b‖ ≤ ‖a‖ + r := (norm_le_norm_add_norm_div' _ _).trans $ add_le_add_left (by rwa ←dist_eq_norm_div) _ @[to_additive norm_le_norm_add_const_of_dist_le] lemma norm_le_norm_add_const_of_dist_le' : dist a b ≤ r → ‖a‖ ≤ ‖b‖ + r := norm_le_of_mem_closed_ball' @[to_additive norm_lt_of_mem_ball] lemma norm_lt_of_mem_ball' (h : b ∈ ball a r) : ‖b‖ < ‖a‖ + r := (norm_le_norm_add_norm_div' _ _).trans_lt $ add_lt_add_left (by rwa ←dist_eq_norm_div) _ @[to_additive] lemma norm_div_sub_norm_div_le_norm_div (u v w : E) : ‖u / w‖ - ‖v / w‖ ≤ ‖u / v‖ := by simpa only [div_div_div_cancel_right'] using norm_sub_norm_le' (u / w) (v / w) @[to_additive bounded_iff_forall_norm_le] lemma bounded_iff_forall_norm_le' : bounded s ↔ ∃ C, ∀ x ∈ s, ‖x‖ ≤ C := by simpa only [set.subset_def, mem_closed_ball_one_iff] using bounded_iff_subset_ball (1 : E) alias bounded_iff_forall_norm_le' ↔ metric.bounded.exists_norm_le' _ alias bounded_iff_forall_norm_le ↔ metric.bounded.exists_norm_le _ attribute [to_additive metric.bounded.exists_norm_le] metric.bounded.exists_norm_le' @[to_additive metric.bounded.exists_pos_norm_le] lemma metric.bounded.exists_pos_norm_le' (hs : metric.bounded s) : ∃ R > 0, ∀ x ∈ s, ‖x‖ ≤ R := let ⟨R₀, hR₀⟩ := hs.exists_norm_le' in ⟨max R₀ 1, by positivity, λ x hx, (hR₀ x hx).trans $ le_max_left _ _⟩ @[simp, to_additive mem_sphere_iff_norm] lemma mem_sphere_iff_norm' : b ∈ sphere a r ↔ ‖b / a‖ = r := by simp [dist_eq_norm_div] @[simp, to_additive] lemma mem_sphere_one_iff_norm : a ∈ sphere (1 : E) r ↔ ‖a‖ = r := by simp [dist_eq_norm_div] @[simp, to_additive norm_eq_of_mem_sphere] lemma norm_eq_of_mem_sphere' (x : sphere (1:E) r) : ‖(x : E)‖ = r := mem_sphere_one_iff_norm.mp x.2 @[to_additive] lemma ne_one_of_mem_sphere (hr : r ≠ 0) (x : sphere (1 : E) r) : (x : E) ≠ 1 := ne_one_of_norm_ne_zero $ by rwa norm_eq_of_mem_sphere' x @[to_additive ne_zero_of_mem_unit_sphere] lemma ne_one_of_mem_unit_sphere (x : sphere (1 : E) 1) : (x:E) ≠ 1 := ne_one_of_mem_sphere one_ne_zero _ variables (E) /-- The norm of a seminormed group as a group seminorm. -/ @[to_additive "The norm of a seminormed group as an additive group seminorm."] def norm_group_seminorm : group_seminorm E := ⟨norm, norm_one', norm_mul_le', norm_inv'⟩ @[simp, to_additive] lemma coe_norm_group_seminorm : ⇑(norm_group_seminorm E) = norm := rfl variables {E} namespace isometric -- TODO This material is superseded by similar constructions such as -- `affine_isometry_equiv.const_vadd`; deduplicate /-- Multiplication `y ↦ y * x` as an `isometry`. -/ @[to_additive "Addition `y ↦ y + x` as an `isometry`"] protected def mul_right (x : E) : E ≃ᵢ E := { isometry_to_fun := isometry.of_dist_eq $ λ y z, dist_mul_right _ _ _, .. equiv.mul_right x } @[simp, to_additive] lemma mul_right_to_equiv (x : E) : (isometric.mul_right x).to_equiv = equiv.mul_right x := rfl @[simp, to_additive] lemma coe_mul_right (x : E) : (isometric.mul_right x : E → E) = λ y, y * x := rfl @[to_additive] lemma mul_right_apply (x y : E) : (isometric.mul_right x : E → E) y = y * x := rfl @[simp, to_additive] lemma mul_right_symm (x : E) : (isometric.mul_right x).symm = isometric.mul_right x⁻¹ := ext $ λ y, rfl end isometric @[to_additive] lemma normed_comm_group.tendsto_nhds_one {f : α → E} {l : filter α} : tendsto f l (𝓝 1) ↔ ∀ ε > 0, ∀ᶠ x in l, ‖ f x ‖ < ε := metric.tendsto_nhds.trans $ by simp only [dist_one_right] @[to_additive] lemma normed_comm_group.tendsto_nhds_nhds {f : E → F} {x : E} {y : F} : tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ‖x' / x‖ < δ → ‖f x' / y‖ < ε := by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm_div] @[to_additive] lemma normed_comm_group.cauchy_seq_iff [nonempty α] [semilattice_sup α] {u : α → E} : cauchy_seq u ↔ ∀ ε > 0, ∃ N, ∀ m, N ≤ m → ∀ n, N ≤ n → ‖u m / u n‖ < ε := by simp [metric.cauchy_seq_iff, dist_eq_norm_div] @[to_additive] lemma normed_comm_group.nhds_basis_norm_lt (x : E) : (𝓝 x).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {y | ‖y / x‖ < ε}) := by { simp_rw ← ball_eq', exact metric.nhds_basis_ball } @[to_additive] lemma normed_comm_group.nhds_one_basis_norm_lt : (𝓝 (1 : E)).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {y | ‖y‖ < ε}) := by { convert normed_comm_group.nhds_basis_norm_lt (1 : E), simp } @[to_additive] lemma normed_comm_group.uniformity_basis_dist : (𝓤 E).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p : E × E | ‖p.fst / p.snd‖ < ε}) := by { convert metric.uniformity_basis_dist, simp [dist_eq_norm_div] } open finset /-- A homomorphism `f` of seminormed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `‖f x‖ ≤ C * ‖x‖`. The analogous condition for a linear map of (semi)normed spaces is in `normed_space.operator_norm`. -/ @[to_additive "A homomorphism `f` of seminormed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `‖f x‖ ≤ C * ‖x‖`. The analogous condition for a linear map of (semi)normed spaces is in `normed_space.operator_norm`."] lemma monoid_hom_class.lipschitz_of_bound [monoid_hom_class 𝓕 E F] (f : 𝓕) (C : ℝ) (h : ∀ x, ‖f x‖ ≤ C * ‖x‖) : lipschitz_with (real.to_nnreal C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm_div, map_div] using h (x / y) @[to_additive] lemma lipschitz_on_with_iff_norm_div_le {f : E → F} {C : ℝ≥0} : lipschitz_on_with C f s ↔ ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → ‖f x / f y‖ ≤ C * ‖x / y‖ := by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm_div] alias lipschitz_on_with_iff_norm_div_le ↔ lipschitz_on_with.norm_div_le _ attribute [to_additive] lipschitz_on_with.norm_div_le @[to_additive] lemma lipschitz_on_with.norm_div_le_of_le {f : E → F} {C : ℝ≥0} (h : lipschitz_on_with C f s) (ha : a ∈ s) (hb : b ∈ s) (hr : ‖a / b‖ ≤ r) : ‖f a / f b‖ ≤ C * r := (h.norm_div_le ha hb).trans $ mul_le_mul_of_nonneg_left hr C.2 @[to_additive] lemma lipschitz_with_iff_norm_div_le {f : E → F} {C : ℝ≥0} : lipschitz_with C f ↔ ∀ x y, ‖f x / f y‖ ≤ C * ‖x / y‖ := by simp only [lipschitz_with_iff_dist_le_mul, dist_eq_norm_div] alias lipschitz_with_iff_norm_div_le ↔ lipschitz_with.norm_div_le _ attribute [to_additive] lipschitz_with.norm_div_le @[to_additive] lemma lipschitz_with.norm_div_le_of_le {f : E → F} {C : ℝ≥0} (h : lipschitz_with C f) (hr : ‖a / b‖ ≤ r) : ‖f a / f b‖ ≤ C * r := (h.norm_div_le _ _).trans $ mul_le_mul_of_nonneg_left hr C.2 /-- A homomorphism `f` of seminormed groups is continuous, if there exists a constant `C` such that for all `x`, one has `‖f x‖ ≤ C * ‖x‖`. -/ @[to_additive "A homomorphism `f` of seminormed groups is continuous, if there exists a constant `C` such that for all `x`, one has `‖f x‖ ≤ C * ‖x‖`"] lemma monoid_hom_class.continuous_of_bound [monoid_hom_class 𝓕 E F] (f : 𝓕) (C : ℝ) (h : ∀ x, ‖f x‖ ≤ C * ‖x‖) : continuous f := (monoid_hom_class.lipschitz_of_bound f C h).continuous @[to_additive] lemma monoid_hom_class.uniform_continuous_of_bound [monoid_hom_class 𝓕 E F] (f : 𝓕) (C : ℝ) (h : ∀x, ‖f x‖ ≤ C * ‖x‖) : uniform_continuous f := (monoid_hom_class.lipschitz_of_bound f C h).uniform_continuous @[to_additive is_compact.exists_bound_of_continuous_on] lemma is_compact.exists_bound_of_continuous_on' [topological_space α] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : ∃ C, ∀ x ∈ s, ‖f x‖ ≤ C := (bounded_iff_forall_norm_le'.1 (hs.image_of_continuous_on hf).bounded).imp $ λ C hC x hx, hC _ $ set.mem_image_of_mem _ hx @[to_additive] lemma monoid_hom_class.isometry_iff_norm [monoid_hom_class 𝓕 E F] (f : 𝓕) : isometry f ↔ ∀ x, ‖f x‖ = ‖x‖ := begin simp only [isometry_iff_dist_eq, dist_eq_norm_div, ←map_div], refine ⟨λ h x, _, λ h x y, h _⟩, simpa using h x 1, end alias monoid_hom_class.isometry_iff_norm ↔ _ monoid_hom_class.isometry_of_norm attribute [to_additive] monoid_hom_class.isometry_of_norm section nnnorm @[priority 100, to_additive] -- See note [lower instance priority] instance seminormed_group.to_has_nnnorm : has_nnnorm E := ⟨λ a, ⟨‖a‖, norm_nonneg' a⟩⟩ @[simp, norm_cast, to_additive coe_nnnorm] lemma coe_nnnorm' (a : E) : (‖a‖₊ : ℝ) = ‖a‖ := rfl @[simp, to_additive coe_comp_nnnorm] lemma coe_comp_nnnorm' : (coe : ℝ≥0 → ℝ) ∘ (nnnorm : E → ℝ≥0) = norm := rfl @[to_additive norm_to_nnreal] lemma norm_to_nnreal' : ‖a‖.to_nnreal = ‖a‖₊ := @real.to_nnreal_coe ‖a‖₊ @[to_additive] lemma nndist_eq_nnnorm_div (a b : E) : nndist a b = ‖a / b‖₊ := nnreal.eq $ dist_eq_norm_div _ _ alias nndist_eq_nnnorm_sub ← nndist_eq_nnnorm @[simp, to_additive nnnorm_zero] lemma nnnorm_one' : ‖(1 : E)‖₊ = 0 := nnreal.eq norm_one' @[to_additive] lemma ne_one_of_nnnorm_ne_zero {a : E} : ‖a‖₊ ≠ 0 → a ≠ 1 := mt $ by { rintro rfl, exact nnnorm_one' } @[to_additive nnnorm_add_le] lemma nnnorm_mul_le' (a b : E) : ‖a * b‖₊ ≤ ‖a‖₊ + ‖b‖₊ := nnreal.coe_le_coe.1 $ norm_mul_le' a b @[simp, to_additive nnnorm_neg] lemma nnnorm_inv' (a : E) : ‖a⁻¹‖₊ = ‖a‖₊ := nnreal.eq $ norm_inv' a @[to_additive] lemma nnnorm_div_le (a b : E) : ‖a / b‖₊ ≤ ‖a‖₊ + ‖b‖₊ := nnreal.coe_le_coe.1 $ norm_div_le _ _ @[to_additive nndist_nnnorm_nnnorm_le] lemma nndist_nnnorm_nnnorm_le' (a b : E) : nndist ‖a‖₊ ‖b‖₊ ≤ ‖a / b‖₊ := nnreal.coe_le_coe.1 $ dist_norm_norm_le' a b @[to_additive] lemma nnnorm_le_nnnorm_add_nnnorm_div (a b : E) : ‖b‖₊ ≤ ‖a‖₊ + ‖a / b‖₊ := norm_le_norm_add_norm_div _ _ @[to_additive] lemma nnnorm_le_nnnorm_add_nnnorm_div' (a b : E) : ‖a‖₊ ≤ ‖b‖₊ + ‖a / b‖₊ := norm_le_norm_add_norm_div' _ _ alias nnnorm_le_nnnorm_add_nnnorm_sub' ← nnnorm_le_insert' alias nnnorm_le_nnnorm_add_nnnorm_sub ← nnnorm_le_insert @[to_additive] lemma nnnorm_le_mul_nnnorm_add (a b : E) : ‖a‖₊ ≤ ‖a * b‖₊ + ‖b‖₊ := norm_le_mul_norm_add _ _ @[to_additive of_real_norm_eq_coe_nnnorm] lemma of_real_norm_eq_coe_nnnorm' (a : E) : ennreal.of_real ‖a‖ = ‖a‖₊ := ennreal.of_real_eq_coe_nnreal _ @[to_additive] lemma edist_eq_coe_nnnorm_div (a b : E) : edist a b = ‖a / b‖₊ := by rw [edist_dist, dist_eq_norm_div, of_real_norm_eq_coe_nnnorm'] @[to_additive edist_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm' (x : E) : edist x 1 = (‖x‖₊ : ℝ≥0∞) := by rw [edist_eq_coe_nnnorm_div, div_one] @[to_additive] lemma mem_emetric_ball_one_iff {r : ℝ≥0∞} : a ∈ emetric.ball (1 : E) r ↔ ↑‖a‖₊ < r := by rw [emetric.mem_ball, edist_eq_coe_nnnorm'] @[simp, to_additive] lemma edist_mul_right (a₁ a₂ b : E) : edist (a₁ * b) (a₂ * b) = edist a₁ a₂ := by simp [edist_dist] @[simp, to_additive] lemma edist_div_right (a₁ a₂ b : E) : edist (a₁ / b) (a₂ / b) = edist a₁ a₂ := by simpa only [div_eq_mul_inv] using edist_mul_right _ _ _ @[to_additive] lemma monoid_hom_class.lipschitz_of_bound_nnnorm [monoid_hom_class 𝓕 E F] (f : 𝓕) (C : ℝ≥0) (h : ∀ x, ‖f x‖₊ ≤ C * ‖x‖₊) : lipschitz_with C f := @real.to_nnreal_coe C ▸ monoid_hom_class.lipschitz_of_bound f C h @[to_additive] lemma monoid_hom_class.antilipschitz_of_bound [monoid_hom_class 𝓕 E F] (f : 𝓕) {K : ℝ≥0} (h : ∀ x, ‖x‖ ≤ K * ‖f x‖) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm_div, map_div] using h (x / y) @[to_additive] lemma monoid_hom_class.bound_of_antilipschitz [monoid_hom_class 𝓕 E F] (f : 𝓕) {K : ℝ≥0} (h : antilipschitz_with K f) (x) : ‖x‖ ≤ K * ‖f x‖ := by simpa only [dist_one_right, map_one] using h.le_mul_dist x 1 end nnnorm @[to_additive] lemma tendsto_iff_norm_tendsto_one {f : α → E} {a : filter α} {b : E} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ‖f e / b‖) a (𝓝 0) := by { convert tendsto_iff_dist_tendsto_zero, simp [dist_eq_norm_div] } @[to_additive] lemma tendsto_one_iff_norm_tendsto_one {f : α → E} {a : filter α} : tendsto f a (𝓝 1) ↔ tendsto (λ e, ‖f e‖) a (𝓝 0) := by { rw tendsto_iff_norm_tendsto_one, simp only [div_one] } @[to_additive] lemma comap_norm_nhds_one : comap norm (𝓝 0) = 𝓝 (1 : E) := by simpa only [dist_one_right] using nhds_comap_dist (1 : E) /-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `a` which tends to `0`, then `f` tends to `1`. In this pair of lemmas (`squeeze_one_norm'` and `squeeze_one_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.order`, the `'` version is phrased using "eventually" and the non-`'` version is phrased absolutely. -/ @[to_additive "Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `a` which tends to `0`, then `f` tends to `1`. In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.order`, the `'` version is phrased using \"eventually\" and the non-`'` version is phrased absolutely."] lemma squeeze_one_norm' {f : α → E} {a : α → ℝ} {t₀ : filter α} (h : ∀ᶠ n in t₀, ‖f n‖ ≤ a n) (h' : tendsto a t₀ (𝓝 0)) : tendsto f t₀ (𝓝 1) := tendsto_one_iff_norm_tendsto_one.2 $ squeeze_zero' (eventually_of_forall $ λ n, norm_nonneg' _) h h' /-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `a` which tends to `0`, then `f` tends to `1`. -/ @[to_additive "Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `a` which tends to `0`, then `f` tends to `0`."] lemma squeeze_one_norm {f : α → E} {a : α → ℝ} {t₀ : filter α} (h : ∀ n, ‖f n‖ ≤ a n) : tendsto a t₀ (𝓝 0) → tendsto f t₀ (𝓝 1) := squeeze_one_norm' $ eventually_of_forall h @[to_additive] lemma tendsto_norm_div_self (x : E) : tendsto (λ a, ‖a / x‖) (𝓝 x) (𝓝 0) := by simpa [dist_eq_norm_div] using tendsto_id.dist (tendsto_const_nhds : tendsto (λ a, (x:E)) (𝓝 x) _) @[to_additive tendsto_norm]lemma tendsto_norm' {x : E} : tendsto (λ a, ‖a‖) (𝓝 x) (𝓝 ‖x‖) := by simpa using tendsto_id.dist (tendsto_const_nhds : tendsto (λ a, (1:E)) _ _) @[to_additive] lemma tendsto_norm_one : tendsto (λ a : E, ‖a‖) (𝓝 1) (𝓝 0) := by simpa using tendsto_norm_div_self (1:E) @[continuity, to_additive continuous_norm] lemma continuous_norm' : continuous (λ a : E, ‖a‖) := by simpa using continuous_id.dist (continuous_const : continuous (λ a, (1:E))) @[continuity, to_additive continuous_nnnorm] lemma continuous_nnnorm' : continuous (λ a : E, ‖a‖₊) := continuous_norm'.subtype_mk _ @[to_additive lipschitz_with_one_norm] lemma lipschitz_with_one_norm' : lipschitz_with 1 (norm : E → ℝ) := by simpa only [dist_one_left] using lipschitz_with.dist_right (1 : E) @[to_additive lipschitz_with_one_nnnorm] lemma lipschitz_with_one_nnnorm' : lipschitz_with 1 (has_nnnorm.nnnorm : E → ℝ≥0) := lipschitz_with_one_norm' @[to_additive uniform_continuous_norm] lemma uniform_continuous_norm' : uniform_continuous (norm : E → ℝ) := lipschitz_with_one_norm'.uniform_continuous @[to_additive uniform_continuous_nnnorm] lemma uniform_continuous_nnnorm' : uniform_continuous (λ (a : E), ‖a‖₊) := uniform_continuous_norm'.subtype_mk _ @[to_additive] lemma mem_closure_one_iff_norm {x : E} : x ∈ closure ({1} : set E) ↔ ‖x‖ = 0 := by rw [←closed_ball_zero', mem_closed_ball_one_iff, (norm_nonneg' x).le_iff_eq] @[to_additive] lemma closure_one_eq : closure ({1} : set E) = {x | ‖x‖ = 0} := set.ext (λ x, mem_closure_one_iff_norm) /-- A helper lemma used to prove that the (scalar or usual) product of a function that tends to one and a bounded function tends to one. This lemma is formulated for any binary operation `op : E → F → G` with an estimate `‖op x y‖ ≤ A * ‖x‖ * ‖y‖` for some constant A instead of multiplication so that it can be applied to `(*)`, `flip (*)`, `(•)`, and `flip (•)`. -/ @[to_additive "A helper lemma used to prove that the (scalar or usual) product of a function that tends to zero and a bounded function tends to zero. This lemma is formulated for any binary operation `op : E → F → G` with an estimate `‖op x y‖ ≤ A * ‖x‖ * ‖y‖` for some constant A instead of multiplication so that it can be applied to `(*)`, `flip (*)`, `(•)`, and `flip (•)`."] lemma filter.tendsto.op_one_is_bounded_under_le' {f : α → E} {g : α → F} {l : filter α} (hf : tendsto f l (𝓝 1)) (hg : is_bounded_under (≤) l (norm ∘ g)) (op : E → F → G) (h_op : ∃ A, ∀ x y, ‖op x y‖ ≤ A * ‖x‖ * ‖y‖) : tendsto (λ x, op (f x) (g x)) l (𝓝 1) := begin cases h_op with A h_op, rcases hg with ⟨C, hC⟩, rw eventually_map at hC, rw normed_comm_group.tendsto_nhds_one at hf ⊢, intros ε ε₀, rcases exists_pos_mul_lt ε₀ (A * C) with ⟨δ, δ₀, hδ⟩, filter_upwards [hf δ δ₀, hC] with i hf hg, refine (h_op _ _).trans_lt _, cases le_total A 0 with hA hA, { exact (mul_nonpos_of_nonpos_of_nonneg (mul_nonpos_of_nonpos_of_nonneg hA $ norm_nonneg' _) $ norm_nonneg' _).trans_lt ε₀ }, calc A * ‖f i‖ * ‖g i‖ ≤ A * δ * C : mul_le_mul (mul_le_mul_of_nonneg_left hf.le hA) hg (norm_nonneg' _) (mul_nonneg hA δ₀.le) ... = A * C * δ : mul_right_comm _ _ _ ... < ε : hδ, end /-- A helper lemma used to prove that the (scalar or usual) product of a function that tends to one and a bounded function tends to one. This lemma is formulated for any binary operation `op : E → F → G` with an estimate `‖op x y‖ ≤ ‖x‖ * ‖y‖` instead of multiplication so that it can be applied to `(*)`, `flip (*)`, `(•)`, and `flip (•)`. -/ @[to_additive "A helper lemma used to prove that the (scalar or usual) product of a function that tends to zero and a bounded function tends to zero. This lemma is formulated for any binary operation `op : E → F → G` with an estimate `‖op x y‖ ≤ ‖x‖ * ‖y‖` instead of multiplication so that it can be applied to `(*)`, `flip (*)`, `(•)`, and `flip (•)`."] lemma filter.tendsto.op_one_is_bounded_under_le {f : α → E} {g : α → F} {l : filter α} (hf : tendsto f l (𝓝 1)) (hg : is_bounded_under (≤) l (norm ∘ g)) (op : E → F → G) (h_op : ∀ x y, ‖op x y‖ ≤ ‖x‖ * ‖y‖) : tendsto (λ x, op (f x) (g x)) l (𝓝 1) := hf.op_one_is_bounded_under_le' hg op ⟨1, λ x y, (one_mul (‖x‖)).symm ▸ h_op x y⟩ section variables {l : filter α} {f : α → E} @[to_additive filter.tendsto.norm] lemma filter.tendsto.norm' (h : tendsto f l (𝓝 a)) : tendsto (λ x, ‖f x‖) l (𝓝 ‖a‖) := tendsto_norm'.comp h @[to_additive filter.tendsto.nnnorm] lemma filter.tendsto.nnnorm' (h : tendsto f l (𝓝 a)) : tendsto (λ x, ‖f x‖₊) l (𝓝 (‖a‖₊)) := tendsto.comp continuous_nnnorm'.continuous_at h end section variables [topological_space α] {f : α → E} @[to_additive continuous.norm] lemma continuous.norm' : continuous f → continuous (λ x, ‖f x‖) := continuous_norm'.comp @[to_additive continuous.nnnorm] lemma continuous.nnnorm' : continuous f → continuous (λ x, ‖f x‖₊) := continuous_nnnorm'.comp @[to_additive continuous_at.norm] lemma continuous_at.norm' {a : α} (h : continuous_at f a) : continuous_at (λ x, ‖f x‖) a := h.norm' @[to_additive continuous_at.nnnorm] lemma continuous_at.nnnorm' {a : α} (h : continuous_at f a) : continuous_at (λ x, ‖f x‖₊) a := h.nnnorm' @[to_additive continuous_within_at.norm] lemma continuous_within_at.norm' {s : set α} {a : α} (h : continuous_within_at f s a) : continuous_within_at (λ x, ‖f x‖) s a := h.norm' @[to_additive continuous_within_at.nnnorm] lemma continuous_within_at.nnnorm' {s : set α} {a : α} (h : continuous_within_at f s a) : continuous_within_at (λ x, ‖f x‖₊) s a := h.nnnorm' @[to_additive continuous_on.norm] lemma continuous_on.norm' {s : set α} (h : continuous_on f s) : continuous_on (λ x, ‖f x‖) s := λ x hx, (h x hx).norm' @[to_additive continuous_on.nnnorm] lemma continuous_on.nnnorm' {s : set α} (h : continuous_on f s) : continuous_on (λ x, ‖f x‖₊) s := λ x hx, (h x hx).nnnorm' end /-- If `‖y‖ → ∞`, then we can assume `y ≠ x` for any fixed `x`. -/ @[to_additive eventually_ne_of_tendsto_norm_at_top "If `‖y‖→∞`, then we can assume `y≠x` for any fixed `x`"] lemma eventually_ne_of_tendsto_norm_at_top' {l : filter α} {f : α → E} (h : tendsto (λ y, ‖f y‖) l at_top) (x : E) : ∀ᶠ y in l, f y ≠ x := (h.eventually_ne_at_top _).mono $ λ x, ne_of_apply_ne norm @[to_additive] lemma seminormed_comm_group.mem_closure_iff : a ∈ closure s ↔ ∀ ε, 0 < ε → ∃ b ∈ s, ‖a / b‖ < ε := by simp [metric.mem_closure_iff, dist_eq_norm_div] @[to_additive norm_le_zero_iff'] lemma norm_le_zero_iff''' [t0_space E] {a : E} : ‖a‖ ≤ 0 ↔ a = 1 := begin letI : normed_group E := { to_metric_space := metric.of_t0_pseudo_metric_space E, ..‹seminormed_group E› }, rw [←dist_one_right, dist_le_zero], end @[to_additive norm_eq_zero'] lemma norm_eq_zero''' [t0_space E] {a : E} : ‖a‖ = 0 ↔ a = 1 := (norm_nonneg' a).le_iff_eq.symm.trans norm_le_zero_iff''' @[to_additive norm_pos_iff'] lemma norm_pos_iff''' [t0_space E] {a : E} : 0 < ‖a‖ ↔ a ≠ 1 := by rw [← not_le, norm_le_zero_iff'''] @[to_additive] lemma seminormed_group.tendsto_uniformly_on_one {f : ι → κ → G} {s : set κ} {l : filter ι} : tendsto_uniformly_on f 1 l s ↔ ∀ ε > 0, ∀ᶠ i in l, ∀ x ∈ s, ‖f i x‖ < ε := by simp_rw [tendsto_uniformly_on_iff, pi.one_apply, dist_one_left] @[to_additive] lemma seminormed_group.uniform_cauchy_seq_on_filter_iff_tendsto_uniformly_on_filter_one {f : ι → κ → G} {l : filter ι} {l' : filter κ} : uniform_cauchy_seq_on_filter f l l' ↔ tendsto_uniformly_on_filter (λ n : ι × ι, λ z, f n.fst z / f n.snd z) 1 (l ×ᶠ l) l' := begin refine ⟨λ hf u hu, _, λ hf u hu, _⟩, { obtain ⟨ε, hε, H⟩ := uniformity_basis_dist.mem_uniformity_iff.mp hu, refine (hf {p : G × G | dist p.fst p.snd < ε} $ dist_mem_uniformity hε).mono (λ x hx, H 1 (f x.fst.fst x.snd / f x.fst.snd x.snd) _), simpa [dist_eq_norm_div, norm_div_rev] using hx }, { obtain ⟨ε, hε, H⟩ := uniformity_basis_dist.mem_uniformity_iff.mp hu, refine (hf {p : G × G | dist p.fst p.snd < ε} $ dist_mem_uniformity hε).mono (λ x hx, H (f x.fst.fst x.snd) (f x.fst.snd x.snd) _), simpa [dist_eq_norm_div, norm_div_rev] using hx } end @[to_additive] lemma seminormed_group.uniform_cauchy_seq_on_iff_tendsto_uniformly_on_one {f : ι → κ → G} {s : set κ} {l : filter ι} : uniform_cauchy_seq_on f l s ↔ tendsto_uniformly_on (λ n : ι × ι, λ z, f n.fst z / f n.snd z) 1 (l ×ᶠ l) s := by rw [tendsto_uniformly_on_iff_tendsto_uniformly_on_filter, uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter, seminormed_group.uniform_cauchy_seq_on_filter_iff_tendsto_uniformly_on_filter_one] end seminormed_group section induced variables (E F) /-- A group homomorphism from a `group` to a `seminormed_group` induces a `seminormed_group` structure on the domain. -/ @[reducible, -- See note [reducible non-instances] to_additive "A group homomorphism from an `add_group` to a `seminormed_add_group` induces a `seminormed_add_group` structure on the domain."] def seminormed_group.induced [group E] [seminormed_group F] [monoid_hom_class 𝓕 E F] (f : 𝓕) : seminormed_group E := { norm := λ x, ‖f x‖, dist_eq := λ x y, by simpa only [map_div, ←dist_eq_norm_div], ..pseudo_metric_space.induced f _ } /-- A group homomorphism from a `comm_group` to a `seminormed_group` induces a `seminormed_comm_group` structure on the domain. -/ @[reducible, -- See note [reducible non-instances] to_additive "A group homomorphism from an `add_comm_group` to a `seminormed_add_group` induces a `seminormed_add_comm_group` structure on the domain."] def seminormed_comm_group.induced [comm_group E] [seminormed_group F] [monoid_hom_class 𝓕 E F] (f : 𝓕) : seminormed_comm_group E := { ..seminormed_group.induced E F f } /-- An injective group homomorphism from a `group` to a `normed_group` induces a `normed_group` structure on the domain. -/ @[reducible, -- See note [reducible non-instances]. to_additive "An injective group homomorphism from an `add_group` to a `normed_add_group` induces a `normed_add_group` structure on the domain."] def normed_group.induced [group E] [normed_group F] [monoid_hom_class 𝓕 E F] (f : 𝓕) (h : injective f) : normed_group E := { ..seminormed_group.induced E F f, ..metric_space.induced f h _ } /-- An injective group homomorphism from an `comm_group` to a `normed_group` induces a `normed_comm_group` structure on the domain. -/ @[reducible, -- See note [reducible non-instances]. to_additive "An injective group homomorphism from an `comm_group` to a `normed_comm_group` induces a `normed_comm_group` structure on the domain."] def normed_comm_group.induced [comm_group E] [normed_group F] [monoid_hom_class 𝓕 E F] (f : 𝓕) (h : injective f) : normed_comm_group E := { ..seminormed_group.induced E F f, ..metric_space.induced f h _ } end induced section seminormed_comm_group variables [seminormed_comm_group E] [seminormed_comm_group F] {a a₁ a₂ b b₁ b₂ : E} {r r₁ r₂ : ℝ} @[simp, to_additive] lemma dist_mul_left (a b₁ b₂ : E) : dist (a * b₁) (a * b₂) = dist b₁ b₂ := by simp [dist_eq_norm_div] @[to_additive] lemma dist_inv (x y : E) : dist x⁻¹ y = dist x y⁻¹ := by simp_rw [dist_eq_norm_div, ←norm_inv' (x⁻¹ / y), inv_div, div_inv_eq_mul, mul_comm] @[simp, to_additive] lemma dist_inv_inv (a b : E) : dist a⁻¹ b⁻¹ = dist a b := by rw [dist_inv, inv_inv] @[simp, to_additive] lemma dist_div_left (a b₁ b₂ : E) : dist (a / b₁) (a / b₂) = dist b₁ b₂ := by simp only [div_eq_mul_inv, dist_mul_left, dist_inv_inv] @[simp, to_additive] lemma dist_self_mul_right (a b : E) : dist a (a * b) = ‖b‖ := by rw [←dist_one_left, ←dist_mul_left a 1 b, mul_one] @[simp, to_additive] lemma dist_self_mul_left (a b : E) : dist (a * b) a = ‖b‖ := by rw [dist_comm, dist_self_mul_right] @[simp, to_additive] lemma dist_self_div_right (a b : E) : dist a (a / b) = ‖b‖ := by rw [div_eq_mul_inv, dist_self_mul_right, norm_inv'] @[simp, to_additive] lemma dist_self_div_left (a b : E) : dist (a / b) a = ‖b‖ := by rw [dist_comm, dist_self_div_right] @[to_additive] lemma dist_mul_mul_le (a₁ a₂ b₁ b₂ : E) : dist (a₁ * a₂) (b₁ * b₂) ≤ dist a₁ b₁ + dist a₂ b₂ := by simpa only [dist_mul_left, dist_mul_right] using dist_triangle (a₁ * a₂) (b₁ * a₂) (b₁ * b₂) @[to_additive] lemma dist_mul_mul_le_of_le (h₁ : dist a₁ b₁ ≤ r₁) (h₂ : dist a₂ b₂ ≤ r₂) : dist (a₁ * a₂) (b₁ * b₂) ≤ r₁ + r₂ := (dist_mul_mul_le a₁ a₂ b₁ b₂).trans $ add_le_add h₁ h₂ @[to_additive] lemma dist_div_div_le (a₁ a₂ b₁ b₂ : E) : dist (a₁ / a₂) (b₁ / b₂) ≤ dist a₁ b₁ + dist a₂ b₂ := by simpa only [div_eq_mul_inv, dist_inv_inv] using dist_mul_mul_le a₁ a₂⁻¹ b₁ b₂⁻¹ @[to_additive] lemma dist_div_div_le_of_le (h₁ : dist a₁ b₁ ≤ r₁) (h₂ : dist a₂ b₂ ≤ r₂) : dist (a₁ / a₂) (b₁ / b₂) ≤ r₁ + r₂ := (dist_div_div_le a₁ a₂ b₁ b₂).trans $ add_le_add h₁ h₂ @[to_additive] lemma abs_dist_sub_le_dist_mul_mul (a₁ a₂ b₁ b₂ : E) : |dist a₁ b₁ - dist a₂ b₂| ≤ dist (a₁ * a₂) (b₁ * b₂) := by simpa only [dist_mul_left, dist_mul_right, dist_comm b₂] using abs_dist_sub_le (a₁ * a₂) (b₁ * b₂) (b₁ * a₂) lemma norm_multiset_sum_le {E} [seminormed_add_comm_group E] (m : multiset E) : ‖m.sum‖ ≤ (m.map (λ x, ‖x‖)).sum := m.le_sum_of_subadditive norm norm_zero norm_add_le @[to_additive] lemma norm_multiset_prod_le (m : multiset E) : ‖m.prod‖ ≤ (m.map $ λ x, ‖x‖).sum := begin rw [←multiplicative.of_add_le, of_add_multiset_prod, multiset.map_map], refine multiset.le_prod_of_submultiplicative (multiplicative.of_add ∘ norm) _ (λ x y, _) _, { simp only [comp_app, norm_one', of_add_zero] }, { exact norm_mul_le' _ _ } end lemma norm_sum_le {E} [seminormed_add_comm_group E] (s : finset ι) (f : ι → E) : ‖∑ i in s, f i‖ ≤ ∑ i in s, ‖f i‖ := s.le_sum_of_subadditive norm norm_zero norm_add_le f @[to_additive] lemma norm_prod_le (s : finset ι) (f : ι → E) : ‖∏ i in s, f i‖ ≤ ∑ i in s, ‖f i‖ := begin rw [←multiplicative.of_add_le, of_add_sum], refine finset.le_prod_of_submultiplicative (multiplicative.of_add ∘ norm) _ (λ x y, _) _ _, { simp only [comp_app, norm_one', of_add_zero] }, { exact norm_mul_le' _ _ } end @[to_additive] lemma norm_prod_le_of_le (s : finset ι) {f : ι → E} {n : ι → ℝ} (h : ∀ b ∈ s, ‖f b‖ ≤ n b) : ‖∏ b in s, f b‖ ≤ ∑ b in s, n b := (norm_prod_le s f).trans $ finset.sum_le_sum h @[to_additive] lemma dist_prod_prod_le_of_le (s : finset ι) {f a : ι → E} {d : ι → ℝ} (h : ∀ b ∈ s, dist (f b) (a b) ≤ d b) : dist (∏ b in s, f b) (∏ b in s, a b) ≤ ∑ b in s, d b := by { simp only [dist_eq_norm_div, ← finset.prod_div_distrib] at *, exact norm_prod_le_of_le s h } @[to_additive] lemma dist_prod_prod_le (s : finset ι) (f a : ι → E) : dist (∏ b in s, f b) (∏ b in s, a b) ≤ ∑ b in s, dist (f b) (a b) := dist_prod_prod_le_of_le s $ λ _ _, le_rfl @[to_additive] lemma mul_mem_ball_iff_norm : a * b ∈ ball a r ↔ ‖b‖ < r := by rw [mem_ball_iff_norm'', mul_div_cancel'''] @[to_additive] lemma mul_mem_closed_ball_iff_norm : a * b ∈ closed_ball a r ↔ ‖b‖ ≤ r := by rw [mem_closed_ball_iff_norm'', mul_div_cancel'''] @[simp, to_additive] lemma preimage_mul_ball (a b : E) (r : ℝ) : ((*) b) ⁻¹' ball a r = ball (a / b) r := by { ext c, simp only [dist_eq_norm_div, set.mem_preimage, mem_ball, div_div_eq_mul_div, mul_comm] } @[simp, to_additive] lemma preimage_mul_closed_ball (a b : E) (r : ℝ) : ((*) b) ⁻¹' (closed_ball a r) = closed_ball (a / b) r := by { ext c, simp only [dist_eq_norm_div, set.mem_preimage, mem_closed_ball, div_div_eq_mul_div, mul_comm] } @[simp, to_additive] lemma preimage_mul_sphere (a b : E) (r : ℝ) : ((*) b) ⁻¹' sphere a r = sphere (a / b) r := by { ext c, simp only [set.mem_preimage, mem_sphere_iff_norm', div_div_eq_mul_div, mul_comm] } @[to_additive norm_nsmul_le] lemma norm_pow_le_mul_norm (n : ℕ) (a : E) : ‖a^n‖ ≤ n * ‖a‖ := begin induction n with n ih, { simp, }, simpa only [pow_succ', nat.cast_succ, add_mul, one_mul] using norm_mul_le_of_le ih le_rfl, end @[to_additive nnnorm_nsmul_le] lemma nnnorm_pow_le_mul_norm (n : ℕ) (a : E) : ‖a^n‖₊ ≤ n * ‖a‖₊ := by simpa only [← nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_nat_cast] using norm_pow_le_mul_norm n a @[to_additive] lemma pow_mem_closed_ball {n : ℕ} (h : a ∈ closed_ball b r) : a^n ∈ closed_ball (b^n) (n • r) := begin simp only [mem_closed_ball, dist_eq_norm_div, ← div_pow] at h ⊢, refine (norm_pow_le_mul_norm n (a / b)).trans _, simpa only [nsmul_eq_mul] using mul_le_mul_of_nonneg_left h n.cast_nonneg, end @[to_additive] lemma pow_mem_ball {n : ℕ} (hn : 0 < n) (h : a ∈ ball b r) : a^n ∈ ball (b^n) (n • r) := begin simp only [mem_ball, dist_eq_norm_div, ← div_pow] at h ⊢, refine lt_of_le_of_lt (norm_pow_le_mul_norm n (a / b)) _, replace hn : 0 < (n : ℝ), { norm_cast, assumption, }, rw nsmul_eq_mul, nlinarith, end @[simp, to_additive] lemma mul_mem_closed_ball_mul_iff {c : E} : a * c ∈ closed_ball (b * c) r ↔ a ∈ closed_ball b r := by simp only [mem_closed_ball, dist_eq_norm_div, mul_div_mul_right_eq_div] @[simp, to_additive] lemma mul_mem_ball_mul_iff {c : E} : a * c ∈ ball (b * c) r ↔ a ∈ ball b r := by simp only [mem_ball, dist_eq_norm_div, mul_div_mul_right_eq_div] @[to_additive] lemma smul_closed_ball'' : a • closed_ball b r = closed_ball (a • b) r := by { ext, simp [mem_closed_ball, set.mem_smul_set, dist_eq_norm_div, div_eq_inv_mul, ← eq_inv_mul_iff_mul_eq, mul_assoc], } @[to_additive] lemma smul_ball'' : a • ball b r = ball (a • b) r := by { ext, simp [mem_ball, set.mem_smul_set, dist_eq_norm_div, div_eq_inv_mul, ← eq_inv_mul_iff_mul_eq, mul_assoc], } namespace isometric /-- Multiplication `y ↦ x * y` as an `isometry`. -/ @[to_additive "Addition `y ↦ x + y` as an `isometry`"] protected def mul_left (x : E) : E ≃ᵢ E := { isometry_to_fun := isometry.of_dist_eq $ λ y z, dist_mul_left _ _ _, to_equiv := equiv.mul_left x } @[simp, to_additive] lemma mul_left_to_equiv (x : E) : (isometric.mul_left x).to_equiv = equiv.mul_left x := rfl @[simp, to_additive] lemma coe_mul_left (x : E) : ⇑(isometric.mul_left x) = (*) x := rfl @[simp, to_additive] lemma mul_left_symm (x : E) : (isometric.mul_left x).symm = isometric.mul_left x⁻¹ := ext $ λ y, rfl variables (E) /-- Inversion `x ↦ x⁻¹` as an `isometry`. -/ @[to_additive "Negation `x ↦ -x` as an `isometry`."] protected def inv : E ≃ᵢ E := { isometry_to_fun := isometry.of_dist_eq $ λ x y, dist_inv_inv _ _, to_equiv := equiv.inv E } variables {E} @[simp, to_additive] lemma inv_symm : (isometric.inv E).symm = isometric.inv E := rfl @[simp, to_additive] lemma inv_to_equiv : (isometric.inv E).to_equiv = equiv.inv E := rfl @[simp, to_additive] lemma coe_inv : ⇑(isometric.inv E) = has_inv.inv := rfl end isometric open finset @[to_additive] lemma controlled_prod_of_mem_closure {s : subgroup E} (hg : a ∈ closure (s : set E)) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ v : ℕ → E, tendsto (λ n, ∏ i in range (n+1), v i) at_top (𝓝 a) ∧ (∀ n, v n ∈ s) ∧ ‖v 0 / a‖ < b 0 ∧ ∀ n, 0 < n → ‖v n‖ < b n := begin obtain ⟨u : ℕ → E, u_in : ∀ n, u n ∈ s, lim_u : tendsto u at_top (𝓝 a)⟩ := mem_closure_iff_seq_limit.mp hg, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ∀ n ≥ n₀, ‖u n / a‖ < b 0, { have : {x | ‖x / a‖ < b 0} ∈ 𝓝 a, { simp_rw ← dist_eq_norm_div, exact metric.ball_mem_nhds _ (b_pos _) }, exact filter.tendsto_at_top'.mp lim_u _ this }, set z : ℕ → E := λ n, u (n + n₀), have lim_z : tendsto z at_top (𝓝 a) := lim_u.comp (tendsto_add_at_top_nat n₀), have mem_𝓤 : ∀ n, {p : E × E | ‖p.1 / p.2‖ < b (n + 1)} ∈ 𝓤 E := λ n, by simpa [← dist_eq_norm_div] using metric.dist_mem_uniformity (b_pos $ n+1), obtain ⟨φ : ℕ → ℕ, φ_extr : strict_mono φ, hφ : ∀ n, ‖z (φ $ n + 1) / z (φ n)‖ < b (n + 1)⟩ := lim_z.cauchy_seq.subseq_mem mem_𝓤, set w : ℕ → E := z ∘ φ, have hw : tendsto w at_top (𝓝 a), from lim_z.comp φ_extr.tendsto_at_top, set v : ℕ → E := λ i, if i = 0 then w 0 else w i / w (i - 1), refine ⟨v, tendsto.congr (finset.eq_prod_range_div' w) hw , _, hn₀ _ (n₀.le_add_left _), _⟩, { rintro ⟨⟩, { change w 0 ∈ s, apply u_in }, { apply s.div_mem ; apply u_in }, }, { intros l hl, obtain ⟨k, rfl⟩ : ∃ k, l = k+1, exact nat.exists_eq_succ_of_ne_zero hl.ne', apply hφ } end @[to_additive] lemma controlled_prod_of_mem_closure_range {j : E →* F} {b : F} (hb : b ∈ closure (j.range : set F)) {f : ℕ → ℝ} (b_pos : ∀ n, 0 < f n) : ∃ a : ℕ → E, tendsto (λ n, ∏ i in range (n + 1), j (a i)) at_top (𝓝 b) ∧ ‖j (a 0) / b‖ < f 0 ∧ ∀ n, 0 < n → ‖j (a n)‖ < f n := begin obtain ⟨v, sum_v, v_in, hv₀, hv_pos⟩ := controlled_prod_of_mem_closure hb b_pos, choose g hg using v_in, refine ⟨g, by simpa [← hg] using sum_v, by simpa [hg 0] using hv₀, λ n hn, by simpa [hg] using hv_pos n hn⟩, end @[to_additive] lemma nndist_mul_mul_le (a₁ a₂ b₁ b₂ : E) : nndist (a₁ * a₂) (b₁ * b₂) ≤ nndist a₁ b₁ + nndist a₂ b₂ := nnreal.coe_le_coe.1 $ dist_mul_mul_le a₁ a₂ b₁ b₂ @[to_additive] lemma edist_mul_mul_le (a₁ a₂ b₁ b₂ : E) : edist (a₁ * a₂) (b₁ * b₂) ≤ edist a₁ b₁ + edist a₂ b₂ := by { simp only [edist_nndist], norm_cast, apply nndist_mul_mul_le } @[simp, to_additive] lemma edist_mul_left (a b₁ b₂ : E) : edist (a * b₁) (a * b₂) = edist b₁ b₂ := by simp [edist_dist] @[to_additive] lemma edist_inv (a b : E) : edist a⁻¹ b = edist a b⁻¹ := by simp_rw [edist_dist, dist_inv] @[simp, to_additive] lemma edist_inv_inv (x y : E) : edist x⁻¹ y⁻¹ = edist x y := by rw [edist_inv, inv_inv] @[simp, to_additive] lemma edist_div_left (a b₁ b₂ : E) : edist (a / b₁) (a / b₂) = edist b₁ b₂ := by simp only [div_eq_mul_inv, edist_mul_left, edist_inv_inv] @[to_additive] lemma nnnorm_multiset_prod_le (m : multiset E) : ‖m.prod‖₊ ≤ (m.map (λ x, ‖x‖₊)).sum := nnreal.coe_le_coe.1 $ by { push_cast, rw multiset.map_map, exact norm_multiset_prod_le _ } @[to_additive] lemma nnnorm_prod_le (s : finset ι) (f : ι → E) : ‖∏ a in s, f a‖₊ ≤ ∑ a in s, ‖f a‖₊ := nnreal.coe_le_coe.1 $ by { push_cast, exact norm_prod_le _ _ } @[to_additive] lemma nnnorm_prod_le_of_le (s : finset ι) {f : ι → E} {n : ι → ℝ≥0} (h : ∀ b ∈ s, ‖f b‖₊ ≤ n b) : ‖∏ b in s, f b‖₊ ≤ ∑ b in s, n b := (norm_prod_le_of_le s h).trans_eq nnreal.coe_sum.symm namespace real instance : has_norm ℝ := { norm := λ r, |r| } @[simp] lemma norm_eq_abs (r : ℝ) : ‖r‖ = |r| := rfl instance : normed_add_comm_group ℝ := ⟨λ r y, rfl⟩ lemma norm_of_nonneg (hr : 0 ≤ r) : ‖r‖ = r := abs_of_nonneg hr lemma norm_of_nonpos (hr : r ≤ 0) : ‖r‖ = -r := abs_of_nonpos hr lemma le_norm_self (r : ℝ) : r ≤ ‖r‖ := le_abs_self r @[simp] lemma norm_coe_nat (n : ℕ) : ‖(n : ℝ)‖ = n := abs_of_nonneg n.cast_nonneg @[simp] lemma nnnorm_coe_nat (n : ℕ) : ‖(n : ℝ)‖₊ = n := nnreal.eq $ norm_coe_nat _ @[simp] lemma norm_two : ‖(2 : ℝ)‖ = 2 := abs_of_pos zero_lt_two @[simp] lemma nnnorm_two : ‖(2 : ℝ)‖₊ = 2 := nnreal.eq $ by simp lemma nnnorm_of_nonneg (hr : 0 ≤ r) : ‖r‖₊ = ⟨r, hr⟩ := nnreal.eq $ norm_of_nonneg hr @[simp] lemma nnnorm_abs (r : ℝ) : ‖(|r|)‖₊ = ‖r‖₊ := by simp [nnnorm] lemma ennnorm_eq_of_real (hr : 0 ≤ r) : (‖r‖₊ : ℝ≥0∞) = ennreal.of_real r := by { rw [← of_real_norm_eq_coe_nnnorm, norm_of_nonneg hr] } lemma ennnorm_eq_of_real_abs (r : ℝ) : (‖r‖₊ : ℝ≥0∞) = ennreal.of_real (|r|) := by rw [← real.nnnorm_abs r, real.ennnorm_eq_of_real (abs_nonneg _)] lemma to_nnreal_eq_nnnorm_of_nonneg (hr : 0 ≤ r) : r.to_nnreal = ‖r‖₊ := begin rw real.to_nnreal_of_nonneg hr, congr, rw [real.norm_eq_abs, abs_of_nonneg hr], end lemma of_real_le_ennnorm (r : ℝ) : ennreal.of_real r ≤ ‖r‖₊ := begin obtain hr | hr := le_total 0 r, { exact (real.ennnorm_eq_of_real hr).ge }, { rw [ennreal.of_real_eq_zero.2 hr], exact bot_le } end end real namespace lipschitz_with variables [pseudo_emetric_space α] {K Kf Kg : ℝ≥0} {f g : α → E} @[to_additive] lemma inv (hf : lipschitz_with K f) : lipschitz_with K (λ x, (f x)⁻¹) := λ x y, (edist_inv_inv _ _).trans_le $ hf x y @[to_additive add] lemma mul' (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x * g x) := λ x y, calc edist (f x * g x) (f y * g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_mul_mul_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm @[to_additive] lemma div (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x / g x) := by simpa only [div_eq_mul_inv] using hf.mul' hg.inv end lipschitz_with namespace antilipschitz_with variables [pseudo_emetric_space α] {K Kf Kg : ℝ≥0} {f g : α → E} @[to_additive] lemma mul_lipschitz_with (hf : antilipschitz_with Kf f) (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x * g x) := begin letI : pseudo_metric_space α := pseudo_emetric_space.to_pseudo_metric_space hf.edist_ne_top, refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], rw le_div_iff (nnreal.coe_pos.2 $ tsub_pos_iff_lt.2 hK), rw [mul_comm, nnreal.coe_sub hK.le, sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_mul_mul _ _ _ _), end @[to_additive] lemma mul_div_lipschitz_with (hf : antilipschitz_with Kf f) (hg : lipschitz_with Kg (g / f)) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ g := by simpa only [pi.div_apply, mul_div_cancel'_right] using hf.mul_lipschitz_with hg hK @[to_additive] lemma le_mul_norm_div {f : E → F} (hf : antilipschitz_with K f) (x y : E) : ‖x / y‖ ≤ K * ‖f x / f y‖ := by simp [← dist_eq_norm_div, hf.le_mul_dist x y] end antilipschitz_with @[priority 100, to_additive] -- See note [lower instance priority] instance seminormed_comm_group.to_has_lipschitz_mul : has_lipschitz_mul E := ⟨⟨1 + 1, lipschitz_with.prod_fst.mul' lipschitz_with.prod_snd⟩⟩ /-- A seminormed group is a uniform group, i.e., multiplication and division are uniformly continuous. -/ @[priority 100, to_additive "A seminormed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous."] -- See note [lower instance priority] instance seminormed_comm_group.to_uniform_group : uniform_group E := ⟨(lipschitz_with.prod_fst.div lipschitz_with.prod_snd).uniform_continuous⟩ -- short-circuit type class inference @[priority 100, to_additive] -- See note [lower instance priority] instance seminormed_comm_group.to_topological_group : topological_group E := infer_instance @[to_additive] lemma cauchy_seq_prod_of_eventually_eq {u v : ℕ → E} {N : ℕ} (huv : ∀ n ≥ N, u n = v n) (hv : cauchy_seq (λ n, ∏ k in range (n+1), v k)) : cauchy_seq (λ n, ∏ k in range (n + 1), u k) := begin let d : ℕ → E := λ n, ∏ k in range (n + 1), (u k / v k), rw show (λ n, ∏ k in range (n + 1), u k) = d * (λ n, ∏ k in range (n + 1), v k), by { ext n, simp [d] }, suffices : ∀ n ≥ N, d n = d N, { exact (tendsto_at_top_of_eventually_const this).cauchy_seq.mul hv }, intros n hn, dsimp [d], rw eventually_constant_prod _ hn, intros m hm, simp [huv m hm], end end seminormed_comm_group section normed_group variables [normed_group E] [normed_group F] {a b : E} @[simp, to_additive norm_eq_zero] lemma norm_eq_zero'' : ‖a‖ = 0 ↔ a = 1 := norm_eq_zero''' @[to_additive norm_ne_zero_iff] lemma norm_ne_zero_iff' : ‖a‖ ≠ 0 ↔ a ≠ 1 := norm_eq_zero''.not @[simp, to_additive norm_pos_iff] lemma norm_pos_iff'' : 0 < ‖a‖ ↔ a ≠ 1 := norm_pos_iff''' @[simp, to_additive norm_le_zero_iff] lemma norm_le_zero_iff'' : ‖a‖ ≤ 0 ↔ a = 1 := norm_le_zero_iff''' @[to_additive] lemma norm_div_eq_zero_iff : ‖a / b‖ = 0 ↔ a = b := by rw [norm_eq_zero'', div_eq_one] @[to_additive] lemma norm_div_pos_iff : 0 < ‖a / b‖ ↔ a ≠ b := by { rw [(norm_nonneg' _).lt_iff_ne, ne_comm], exact norm_div_eq_zero_iff.not } @[to_additive] lemma eq_of_norm_div_le_zero (h : ‖a / b‖ ≤ 0) : a = b := by rwa [←div_eq_one, ← norm_le_zero_iff''] alias norm_div_eq_zero_iff ↔ eq_of_norm_div_eq_zero _ attribute [to_additive] eq_of_norm_div_eq_zero @[simp, to_additive nnnorm_eq_zero] lemma nnnorm_eq_zero' : ‖a‖₊ = 0 ↔ a = 1 := by rw [← nnreal.coe_eq_zero, coe_nnnorm', norm_eq_zero''] @[to_additive nnnorm_ne_zero_iff] lemma nnnorm_ne_zero_iff' : ‖a‖₊ ≠ 0 ↔ a ≠ 1 := nnnorm_eq_zero'.not @[to_additive] lemma tendsto_norm_div_self_punctured_nhds (a : E) : tendsto (λ x, ‖x / a‖) (𝓝[≠] a) (𝓝[>] 0) := (tendsto_norm_div_self a).inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff''.2 $ div_ne_one.2 hx @[to_additive] lemma tendsto_norm_nhds_within_one : tendsto (norm : E → ℝ) (𝓝[≠] 1) (𝓝[>] 0) := tendsto_norm_one.inf $ tendsto_principal_principal.2 $ λ x, norm_pos_iff''.2 variables (E) /-- The norm of a normed group as a group norm. -/ @[to_additive "The norm of a normed group as an additive group norm."] def norm_group_norm : group_norm E := { eq_one_of_map_eq_zero' := λ _, norm_eq_zero''.1, ..norm_group_seminorm _ } @[simp] lemma coe_norm_group_norm : ⇑(norm_group_norm E) = norm := rfl end normed_group section normed_add_group variables [normed_add_group E] [topological_space α] {f : α → E} /-! Some relations with `has_compact_support` -/ lemma has_compact_support_norm_iff : has_compact_support (λ x, ‖f x‖) ↔ has_compact_support f := has_compact_support_comp_left $ λ x, norm_eq_zero alias has_compact_support_norm_iff ↔ _ has_compact_support.norm lemma continuous.bounded_above_of_compact_support (hf : continuous f) (h : has_compact_support f) : ∃ C, ∀ x, ‖f x‖ ≤ C := by simpa [bdd_above_def] using hf.norm.bdd_above_range_of_has_compact_support h.norm end normed_add_group /-! ### `ulift` -/ namespace ulift section has_norm variables [has_norm E] instance : has_norm (ulift E) := ⟨λ x, ‖x.down‖⟩ lemma norm_def (x : ulift E) : ‖x‖ = ‖x.down‖ := rfl @[simp] lemma norm_up (x : E) : ‖ulift.up x‖ = ‖x‖ := rfl @[simp] lemma norm_down (x : ulift E) : ‖x.down‖ = ‖x‖ := rfl end has_norm section has_nnnorm variables [has_nnnorm E] instance : has_nnnorm (ulift E) := ⟨λ x, ‖x.down‖₊⟩ lemma nnnorm_def (x : ulift E) : ‖x‖₊ = ‖x.down‖₊ := rfl @[simp] lemma nnnorm_up (x : E) : ‖ulift.up x‖₊ = ‖x‖₊ := rfl @[simp] lemma nnnorm_down (x : ulift E) : ‖x.down‖₊ = ‖x‖₊ := rfl end has_nnnorm @[to_additive] instance seminormed_group [seminormed_group E] : seminormed_group (ulift E) := seminormed_group.induced _ _ (⟨ulift.down, rfl, λ _ _, rfl⟩ : ulift E →* E) @[to_additive] instance seminormed_comm_group [seminormed_comm_group E] : seminormed_comm_group (ulift E) := seminormed_comm_group.induced _ _ (⟨ulift.down, rfl, λ _ _, rfl⟩ : ulift E →* E) @[to_additive] instance normed_group [normed_group E] : normed_group (ulift E) := normed_group.induced _ _ (⟨ulift.down, rfl, λ _ _, rfl⟩ : ulift E →* E) down_injective @[to_additive] instance normed_comm_group [normed_comm_group E] : normed_comm_group (ulift E) := normed_comm_group.induced _ _ (⟨ulift.down, rfl, λ _ _, rfl⟩ : ulift E →* E) down_injective end ulift /-! ### `additive`, `multiplicative` -/ section additive_multiplicative open additive multiplicative section has_norm variables [has_norm E] instance : has_norm (additive E) := ‹has_norm E› instance : has_norm (multiplicative E) := ‹has_norm E› @[simp] lemma norm_to_mul (x) : ‖(to_mul x : E)‖ = ‖x‖ := rfl @[simp] lemma norm_of_mul (x : E) : ‖of_mul x‖ = ‖x‖ := rfl @[simp] lemma norm_to_add (x) : ‖(to_add x : E)‖ = ‖x‖ := rfl @[simp] lemma norm_of_add (x : E) : ‖of_add x‖ = ‖x‖ := rfl end has_norm section has_nnnorm variables [has_nnnorm E] instance : has_nnnorm (additive E) := ‹has_nnnorm E› instance : has_nnnorm (multiplicative E) := ‹has_nnnorm E› @[simp] lemma nnnorm_to_mul (x) : ‖(to_mul x : E)‖₊ = ‖x‖₊ := rfl @[simp] lemma nnnorm_of_mul (x : E) : ‖of_mul x‖₊ = ‖x‖₊ := rfl @[simp] lemma nnnorm_to_add (x) : ‖(to_add x : E)‖₊ = ‖x‖₊ := rfl @[simp] lemma nnnorm_of_add (x : E) : ‖of_add x‖₊ = ‖x‖₊ := rfl end has_nnnorm instance [seminormed_group E] : seminormed_add_group (additive E) := { dist_eq := dist_eq_norm_div } instance [seminormed_add_group E] : seminormed_group (multiplicative E) := { dist_eq := dist_eq_norm_sub } instance [seminormed_comm_group E] : seminormed_add_comm_group (additive E) := { ..additive.seminormed_add_group } instance [seminormed_add_comm_group E] : seminormed_comm_group (multiplicative E) := { ..multiplicative.seminormed_group } instance [normed_group E] : normed_add_group (additive E) := { ..additive.seminormed_add_group } instance [normed_add_group E] : normed_group (multiplicative E) := { ..multiplicative.seminormed_group } instance [normed_comm_group E] : normed_add_comm_group (additive E) := { ..additive.seminormed_add_group } instance [normed_add_comm_group E] : normed_comm_group (multiplicative E) := { ..multiplicative.seminormed_group } end additive_multiplicative /-! ### Order dual -/ section order_dual open order_dual section has_norm variables [has_norm E] instance : has_norm Eᵒᵈ := ‹has_norm E› @[simp] lemma norm_to_dual (x : E) : ‖to_dual x‖ = ‖x‖ := rfl @[simp] lemma norm_of_dual (x : Eᵒᵈ) : ‖of_dual x‖ = ‖x‖ := rfl end has_norm section has_nnnorm variables [has_nnnorm E] instance : has_nnnorm Eᵒᵈ := ‹has_nnnorm E› @[simp] lemma nnnorm_to_dual (x : E) : ‖to_dual x‖₊ = ‖x‖₊ := rfl @[simp] lemma nnnorm_of_dual (x : Eᵒᵈ) : ‖of_dual x‖₊ = ‖x‖₊ := rfl end has_nnnorm @[priority 100, to_additive] -- See note [lower instance priority] instance [seminormed_group E] : seminormed_group Eᵒᵈ := ‹seminormed_group E› @[priority 100, to_additive] -- See note [lower instance priority] instance [seminormed_comm_group E] : seminormed_comm_group Eᵒᵈ := ‹seminormed_comm_group E› @[priority 100, to_additive] -- See note [lower instance priority] instance [normed_group E] : normed_group Eᵒᵈ := ‹normed_group E› @[priority 100, to_additive] -- See note [lower instance priority] instance [normed_comm_group E] : normed_comm_group Eᵒᵈ := ‹normed_comm_group E› end order_dual /-! ### Binary product of normed groups -/ section has_norm variables [has_norm E] [has_norm F] {x : E × F} {r : ℝ} instance : has_norm (E × F) := ⟨λ x, ‖x.1‖ ⊔ ‖x.2‖⟩ lemma prod.norm_def (x : E × F) : ‖x‖ = (max ‖x.1‖ ‖x.2‖) := rfl lemma norm_fst_le (x : E × F) : ‖x.1‖ ≤ ‖x‖ := le_max_left _ _ lemma norm_snd_le (x : E × F) : ‖x.2‖ ≤ ‖x‖ := le_max_right _ _ lemma norm_prod_le_iff : ‖x‖ ≤ r ↔ ‖x.1‖ ≤ r ∧ ‖x.2‖ ≤ r := max_le_iff end has_norm section seminormed_group variables [seminormed_group E] [seminormed_group F] /-- Product of seminormed groups, using the sup norm. -/ @[to_additive "Product of seminormed groups, using the sup norm."] instance : seminormed_group (E × F) := ⟨λ x y, by simp only [prod.norm_def, prod.dist_eq, dist_eq_norm_div, prod.fst_div, prod.snd_div]⟩ @[to_additive prod.nnnorm_def'] lemma prod.nnorm_def (x : E × F) : ‖x‖₊ = (max ‖x.1‖₊ ‖x.2‖₊) := rfl end seminormed_group /-- Product of seminormed groups, using the sup norm. -/ @[to_additive "Product of seminormed groups, using the sup norm."] instance [seminormed_comm_group E] [seminormed_comm_group F] : seminormed_comm_group (E × F) := { ..prod.seminormed_group } /-- Product of normed groups, using the sup norm. -/ @[to_additive "Product of normed groups, using the sup norm."] instance [normed_group E] [normed_group F] : normed_group (E × F) := { ..prod.seminormed_group } /-- Product of normed groups, using the sup norm. -/ @[to_additive "Product of normed groups, using the sup norm."] instance [normed_comm_group E] [normed_comm_group F] : normed_comm_group (E × F) := { ..prod.seminormed_group } /-! ### Finite product of normed groups -/ section pi variables {π : ι → Type*} [fintype ι] section seminormed_group variables [Π i, seminormed_group (π i)] [seminormed_group E] (f : Π i, π i) {x : Π i, π i} {r : ℝ} /-- Finite product of seminormed groups, using the sup norm. -/ @[to_additive "Finite product of seminormed groups, using the sup norm."] instance : seminormed_group (Π i, π i) := { norm := λ f, ↑(finset.univ.sup (λ b, ‖f b‖₊)), dist_eq := λ x y, congr_arg (coe : ℝ≥0 → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ λ a, show nndist (x a) (y a) = ‖x a / y a‖₊, from nndist_eq_nnnorm_div (x a) (y a) } @[to_additive pi.norm_def] lemma pi.norm_def' : ‖f‖ = ↑(finset.univ.sup (λ b, ‖f b‖₊)) := rfl @[to_additive pi.nnnorm_def] lemma pi.nnnorm_def' : ‖f‖₊ = finset.univ.sup (λ b, ‖f b‖₊) := subtype.eta _ _ /-- The seminorm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ @[to_additive pi_norm_le_iff_of_nonneg "The seminorm of an element in a product space is `≤ r` if and only if the norm of each component is."] lemma pi_norm_le_iff_of_nonneg' (hr : 0 ≤ r) : ‖x‖ ≤ r ↔ ∀ i, ‖x i‖ ≤ r := by simp only [←dist_one_right, dist_pi_le_iff hr, pi.one_apply] @[to_additive pi_nnnorm_le_iff] lemma pi_nnnorm_le_iff' {r : ℝ≥0} : ‖x‖₊ ≤ r ↔ ∀ i, ‖x i‖₊ ≤ r := pi_norm_le_iff_of_nonneg' r.coe_nonneg @[to_additive pi_norm_le_iff_of_nonempty] lemma pi_norm_le_iff_of_nonempty' [nonempty ι] : ‖f‖ ≤ r ↔ ∀ b, ‖f b‖ ≤ r := begin by_cases hr : 0 ≤ r, { exact pi_norm_le_iff_of_nonneg' hr }, { exact iff_of_false (λ h, hr $ (norm_nonneg' _).trans h) (λ h, hr $ (norm_nonneg' _).trans $ h $ classical.arbitrary _) } end /-- The seminorm of an element in a product space is `< r` if and only if the norm of each component is. -/ @[to_additive pi_norm_lt_iff "The seminorm of an element in a product space is `< r` if and only if the norm of each component is."] lemma pi_norm_lt_iff' (hr : 0 < r) : ‖x‖ < r ↔ ∀ i, ‖x i‖ < r := by simp only [←dist_one_right, dist_pi_lt_iff hr, pi.one_apply] @[to_additive pi_nnnorm_lt_iff] lemma pi_nnnorm_lt_iff' {r : ℝ≥0} (hr : 0 < r) : ‖x‖₊ < r ↔ ∀ i, ‖x i‖₊ < r := pi_norm_lt_iff' hr @[to_additive norm_le_pi_norm] lemma norm_le_pi_norm' (i : ι) : ‖f i‖ ≤ ‖f‖ := (pi_norm_le_iff_of_nonneg' $ norm_nonneg' _).1 le_rfl i @[to_additive nnnorm_le_pi_nnnorm] lemma nnnorm_le_pi_nnnorm' (i : ι) : ‖f i‖₊ ≤ ‖f‖₊ := norm_le_pi_norm' _ i @[to_additive pi_norm_const_le] lemma pi_norm_const_le' (a : E) : ‖(λ _ : ι, a)‖ ≤ ‖a‖ := (pi_norm_le_iff_of_nonneg' $ norm_nonneg' _).2 $ λ _, le_rfl @[to_additive pi_nnnorm_const_le] lemma pi_nnnorm_const_le' (a : E) : ‖(λ _ : ι, a)‖₊ ≤ ‖a‖₊ := pi_norm_const_le' _ @[simp, to_additive pi_norm_const] lemma pi_norm_const' [nonempty ι] (a : E) : ‖(λ i : ι, a)‖ = ‖a‖ := by simpa only [←dist_one_right] using dist_pi_const a 1 @[simp, to_additive pi_nnnorm_const] lemma pi_nnnorm_const' [nonempty ι] (a : E) : ‖(λ i : ι, a)‖₊ = ‖a‖₊ := nnreal.eq $ pi_norm_const' a /-- The $L^1$ norm is less than the $L^\infty$ norm scaled by the cardinality. -/ @[to_additive pi.sum_norm_apply_le_norm "The $L^1$ norm is less than the $L^\\infty$ norm scaled by the cardinality."] lemma pi.sum_norm_apply_le_norm' : ∑ i, ‖f i‖ ≤ fintype.card ι • ‖f‖ := finset.sum_le_card_nsmul _ _ _ $ λ i hi, norm_le_pi_norm' _ i /-- The $L^1$ norm is less than the $L^\infty$ norm scaled by the cardinality. -/ @[to_additive pi.sum_nnnorm_apply_le_nnnorm "The $L^1$ norm is less than the $L^\\infty$ norm scaled by the cardinality."] lemma pi.sum_nnnorm_apply_le_nnnorm' : ∑ i, ‖f i‖₊ ≤ fintype.card ι • ‖f‖₊ := nnreal.coe_sum.trans_le $ pi.sum_norm_apply_le_norm' _ end seminormed_group /-- Finite product of seminormed groups, using the sup norm. -/ @[to_additive "Finite product of seminormed groups, using the sup norm."] instance pi.seminormed_comm_group [Π i, seminormed_comm_group (π i)] : seminormed_comm_group (Π i, π i) := { ..pi.seminormed_group } /-- Finite product of normed groups, using the sup norm. -/ @[to_additive "Finite product of seminormed groups, using the sup norm."] instance pi.normed_group [Π i, normed_group (π i)] : normed_group (Π i, π i) := { ..pi.seminormed_group } /-- Finite product of normed groups, using the sup norm. -/ @[to_additive "Finite product of seminormed groups, using the sup norm."] instance pi.normed_comm_group [Π i, normed_comm_group (π i)] : normed_comm_group (Π i, π i) := { ..pi.seminormed_group } end pi /-! ### Subgroups of normed groups -/ namespace subgroup section seminormed_group variables [seminormed_group E] {s : subgroup E} /-- A subgroup of a seminormed group is also a seminormed group, with the restriction of the norm. -/ @[to_additive "A subgroup of a seminormed group is also a seminormed group, with the restriction of the norm."] instance seminormed_group : seminormed_group s := seminormed_group.induced _ _ s.subtype /-- If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. -/ @[simp, to_additive "If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`."] lemma coe_norm (x : s) : ‖x‖ = ‖(x : E)‖ := rfl /-- If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. This is a reversed version of the `simp` lemma `subgroup.coe_norm` for use by `norm_cast`. -/ @[norm_cast, to_additive "If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. This is a reversed version of the `simp` lemma `add_subgroup.coe_norm` for use by `norm_cast`."] lemma norm_coe {s : subgroup E} (x : s) : ‖(x : E)‖ = ‖x‖ := rfl end seminormed_group @[to_additive] instance seminormed_comm_group [seminormed_comm_group E] {s : subgroup E} : seminormed_comm_group s := seminormed_comm_group.induced _ _ s.subtype @[to_additive] instance normed_group [normed_group E] {s : subgroup E} : normed_group s := normed_group.induced _ _ s.subtype subtype.coe_injective @[to_additive] instance normed_comm_group [normed_comm_group E] {s : subgroup E} : normed_comm_group s := normed_comm_group.induced _ _ s.subtype subtype.coe_injective end subgroup /-! ### Submodules of normed groups -/ namespace submodule /-- A submodule of a seminormed group is also a seminormed group, with the restriction of the norm. -/ -- See note [implicit instance arguments] instance seminormed_add_comm_group {_ : ring 𝕜} [seminormed_add_comm_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : seminormed_add_comm_group s := seminormed_add_comm_group.induced _ _ s.subtype.to_add_monoid_hom /-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `s` is equal to its norm in `E`. -/ -- See note [implicit instance arguments]. @[simp] lemma coe_norm {_ : ring 𝕜} [seminormed_add_comm_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) : ‖x‖ = ‖(x : E)‖ := rfl /-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `E` is equal to its norm in `s`. This is a reversed version of the `simp` lemma `submodule.coe_norm` for use by `norm_cast`. -/ -- See note [implicit instance arguments]. @[norm_cast] lemma norm_coe {_ : ring 𝕜} [seminormed_add_comm_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) : ‖(x : E)‖ = ‖x‖ := rfl /-- A submodule of a normed group is also a normed group, with the restriction of the norm. -/ -- See note [implicit instance arguments]. instance {_ : ring 𝕜} [normed_add_comm_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_add_comm_group s := { ..submodule.seminormed_add_comm_group s } end submodule
bb705818ffda63ca5dcea46fcec5757c7fc5f447
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/Rpc/Deriving.lean
32e95ce67388d0627a7324a59e391513289012ac
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
5,712
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Elab.Command import Lean.Elab.Term import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util import Lean.Server.Rpc.Basic namespace Lean.Server.RpcEncodable open Meta Elab Command Term def isOptField (n : Name) : Bool := n.toString.endsWith "?" open Parser.Term private def deriveStructureInstance (indVal : InductiveVal) (params : Array Expr) (encInstBinders : Array (TSyntax ``bracketedBinder)) : TermElabM Command := do let fields := getStructureFieldsFlattened (← getEnv) indVal.name (includeSubobjectFields := false) trace[Elab.Deriving.RpcEncodable] "for structure {indVal.name} with params {params}" let mut fieldIds := #[] let mut fieldTys := #[] let mut encInits := #[] let mut decInits := #[] for fieldName in fields do let fid := mkIdent fieldName fieldIds := fieldIds.push fid if isOptField fieldName then fieldTys := fieldTys.push (← `(Option Json)) encInits := encInits.push (← `(structInstField| $fid:ident := ← (a.$fid).mapM rpcEncode)) decInits := decInits.push (← `(structInstField| $fid:ident := ← (a.$fid).mapM rpcDecode)) else fieldTys := fieldTys.push (← `(Json)) encInits := encInits.push (← `(structInstField| $fid:ident := ← rpcEncode a.$fid)) decInits := decInits.push (← `(structInstField| $fid:ident := ← rpcDecode a.$fid)) let paramIds ← params.mapM fun p => return mkIdent (← getFVarLocalDecl p).userName `(structure RpcEncodablePacket where $[($fieldIds : $fieldTys)]* deriving FromJson, ToJson variable $encInstBinders* in instance : RpcEncodable (@$(mkCIdent indVal.name) $paramIds*) := { rpcEncode := enc, rpcDecode := dec } where -- prevent inlining enc a := return toJson { $[$encInits],* : RpcEncodablePacket } dec j := do let a : RpcEncodablePacket ← fromJson? j return { $[$decInits],* } ) private def matchAltTerm := Lean.Parser.Term.matchAlt (rhsParser := Lean.Parser.termParser) instance : Coe (TSyntax ``matchAltTerm) (TSyntax ``Parser.Term.matchAlt) where coe s := ⟨s⟩ private def deriveInductiveInstance (indVal : InductiveVal) (params : Array Expr) (encInstBinders : Array (TSyntax ``bracketedBinder)) : TermElabM Command := do trace[Elab.Deriving.RpcEncodable] "for inductive {indVal.name} with params {params}" let st ← indVal.ctors.toArray.mapM fun ctorName => do let ctorTy ← instantiateForall (← getConstInfoCtor ctorName).type params forallTelescopeReducing ctorTy fun argVars _ => do let .str _ ctor := ctorName | throwError m!"constructor name not a string: {ctorName}" let ctorId := mkIdent ctor -- create the constructor let fieldStxs ← argVars.mapM fun arg => do let name := (← getFVarLocalDecl arg).userName `(bracketedBinderF| ($(mkIdent name) : Json)) let pktCtor ← `(Parser.Command.ctor| | $ctorId:ident $[$fieldStxs]* : RpcEncodablePacket) -- create encoder and decoder match arms let nms ← argVars.mapM fun _ => mkIdent <$> mkFreshBinderName let encArgs ← nms.mapM fun nm => `(← rpcEncode $nm) let encArm ← `(matchAltTerm| | .$ctorId $nms* => return toJson (.$ctorId $encArgs* : RpcEncodablePacket)) let decArgs ← nms.mapM fun nm => `(← rpcDecode $nm) let decArm ← `(matchAltTerm| | .$ctorId $nms* => return (.$ctorId $decArgs*)) return (pktCtor, encArm, decArm) let (ctors, st) := st.unzip let (encodes, decodes) := st.unzip -- helpers for type name syntax let paramIds ← params.mapM fun p => return mkIdent (← getFVarLocalDecl p).userName let typeId ← `(@$(mkIdent indVal.name) $paramIds*) `(inductive RpcEncodablePacket where $[$ctors:ctor]* deriving FromJson, ToJson variable $encInstBinders* in partial instance : RpcEncodable $typeId := { rpcEncode := enc, rpcDecode := dec } where enc x := have inst : RpcEncodable $typeId := { rpcEncode := enc, rpcDecode := dec } match x with $[$encodes:matchAlt]* dec j := do have inst : RpcEncodable $typeId := { rpcEncode := enc, rpcDecode := dec } let pkt : RpcEncodablePacket ← fromJson? j id <| match pkt with $[$decodes:matchAlt]* ) /-- Creates an `RpcEncodablePacket` for `typeName`. For structures, the packet is a structure with the same field names. For inductives, it mirrors the inductive structure with every field of every ctor replaced by `Json`. Then `RpcEncodable typeName` is instantiated using the `RpcEncodablePacket`. -/ private def deriveInstance (declNames : Array Name) : CommandElabM Bool := do let #[typeName] := declNames | return false let indVal ← getConstInfoInduct typeName if indVal.all.length ≠ 1 then throwError "mutually inductive types are not supported" if indVal.numIndices ≠ 0 then throwError "indexed inductive families are not supported" elabCommand <| ← liftTermElabM do forallTelescopeReducing indVal.type fun params _ => do let encInstBinders ← (← params.filterM (isType ·)).mapM fun p => do `(bracketedBinderF| [RpcEncodable $(mkIdent (← getFVarLocalDecl p).userName):ident]) if isStructure (← getEnv) typeName then deriveStructureInstance indVal params encInstBinders else deriveInductiveInstance indVal params encInstBinders return true initialize registerDerivingHandler ``RpcEncodable deriveInstance registerTraceClass `Elab.Deriving.RpcEncodable end Lean.Server.RpcEncodable
de238969b2a1a04291863d2bc7b365b73e5a683c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/list/join.lean
e46041af05a38d07f4cda847caef2d97c15bdf80
[ "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
6,001
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Floris van Doorn, Mario Carneiro -/ import data.list.big_operators /-! # Join of a list of lists This file proves basic properties of `list.join`, which concatenates a list of lists. It is defined in [`data.list.defs`](./defs). -/ variables {α β : Type*} namespace list attribute [simp] join @[simp] lemma join_nil : [([] : list α)].join = [] := rfl @[simp] lemma join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l :: L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] lemma join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] lemma join_concat (L : list (list α)) (l : list α) : join (L.concat l) = join L ++ l := by simp @[simp] lemma join_filter_empty_eq_ff [decidable_pred (λ l : list α, l.empty = ff)] : ∀ {L : list (list α)}, join (L.filter (λ l, l.empty = ff)) = L.join | [] := rfl | ([] :: L) := by simp [@join_filter_empty_eq_ff L] | ((a :: l) :: L) := by simp [@join_filter_empty_eq_ff L] @[simp] lemma join_filter_ne_nil [decidable_pred (λ l : list α, l ≠ [])] {L : list (list α)} : join (L.filter (λ l, l ≠ [])) = L.join := by simp [join_filter_empty_eq_ff, ← empty_iff_eq_nil] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } @[simp] lemma length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] lemma length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] @[simp] lemma bind_eq_nil {l : list α} {f : α → list β} : list.bind l f = [] ↔ ∀ x ∈ l, f x = [] := join_eq_nil.trans $ by simp only [mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end end list
5694921f52bb854c5a001b0520c4c917760a4a26
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/reduction/cpge_reduction_003_a.lean
7af6ea32372b203b649f944f92a93373f1d55e72
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
430
lean
import algebra.module.basic import algebra.module.linear_map import linear_algebra.basic import linear_algebra.prod import linear_algebra.projection import order.bounded_lattice theorem cpge_reduction_3_a (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M] [E : submodule R M] (u : linear_map R E E) (v : linear_map R E E) : (u.comp v) = (v.comp u) -> v '' u.ker ⊂ u.ker ∧ u '' v.ker ⊂ v.ker := sorry
560464e63c9f100fe10445e03fa6ec266e0ab567
f57749ca63d6416f807b770f67559503fdb21001
/library/algebra/group_bigops.lean
3c308ec836df098aa4b77836325784d00eea1cb5
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,870
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad Finite products on a monoid, and finite sums on an additive monoid. We have to be careful with dependencies. This theory imports files from finset and list, which import basic files from nat. Then nat imports this file to instantiate finite products and sums. -/ import .group .group_power data.list.basic data.list.perm data.finset.basic open algebra function binary quot subtype list finset namespace algebra variables {A B : Type} variable [deceqA : decidable_eq A] /- Prodl: product indexed by a list -/ section monoid variable [mB : monoid B] include mB definition mulf (f : A → B) : B → A → B := λ b a, b * f a definition Prodl (l : list A) (f : A → B) : B := list.foldl (mulf f) 1 l -- ∏ x ← l, f x notation `∏` binders `←` l, r:(scoped f, Prodl l f) := r private theorem foldl_const (f : A → B) : ∀ (l : list A) (b : B), foldl (mulf f) b l = b * foldl (mulf f) 1 l | [] b := by rewrite [*foldl_nil, mul_one] | (a::l) b := by rewrite [*foldl_cons, foldl_const, {foldl _ (mulf f 1 a) _}foldl_const, ↑mulf, one_mul, mul.assoc] theorem Prodl_nil (f : A → B) : Prodl [] f = 1 := rfl theorem Prodl_cons (f : A → B) (a : A) (l : list A) : Prodl (a::l) f = f a * Prodl l f := by rewrite [↑Prodl, foldl_cons, foldl_const, ↑mulf, one_mul] theorem Prodl_append : ∀ (l₁ l₂ : list A) (f : A → B), Prodl (l₁++l₂) f = Prodl l₁ f * Prodl l₂ f | [] l₂ f := by rewrite [append_nil_left, Prodl_nil, one_mul] | (a::l) l₂ f := by rewrite [append_cons, *Prodl_cons, Prodl_append, mul.assoc] section deceqA include deceqA theorem Prodl_insert_of_mem (f : A → B) {a : A} {l : list A} : a ∈ l → Prodl (insert a l) f = Prodl l f := assume ainl, by rewrite [insert_eq_of_mem ainl] theorem Prodl_insert_of_not_mem (f : A → B) {a : A} {l : list A} : a ∉ l → Prodl (insert a l) f = f a * Prodl l f := assume nainl, by rewrite [insert_eq_of_not_mem nainl, Prodl_cons] theorem Prodl_union {l₁ l₂ : list A} (f : A → B) (d : disjoint l₁ l₂) : Prodl (union l₁ l₂) f = Prodl l₁ f * Prodl l₂ f := by rewrite [union_eq_append d, Prodl_append] end deceqA theorem Prodl_one : ∀(l : list A), Prodl l (λ x, 1) = (1:B) | [] := rfl | (a::l) := by rewrite [Prodl_cons, Prodl_one, mul_one] lemma Prodl_singleton {a : A} {f : A → B} : Prodl [a] f = f a := !one_mul lemma Prodl_map {f : A → B} : ∀ {l : list A}, Prodl l f = Prodl (map f l) id | nil := by rewrite [map_nil] | (a::l) := begin rewrite [map_cons, Prodl_cons f, Prodl_cons id (f a), Prodl_map] end open nat lemma Prodl_eq_pow_of_const {f : A → B} : ∀ {l : list A} b, (∀ a, a ∈ l → f a = b) → Prodl l f = b ^ length l | nil := take b, assume Pconst, by rewrite [length_nil, {b^0}algebra.pow_zero] | (a::l) := take b, assume Pconst, assert Pconstl : ∀ a', a' ∈ l → f a' = b, from take a' Pa'in, Pconst a' (mem_cons_of_mem a Pa'in), by rewrite [Prodl_cons f, Pconst a !mem_cons, Prodl_eq_pow_of_const b Pconstl, length_cons, add_one, pow_succ' b] end monoid section comm_monoid variable [cmB : comm_monoid B] include cmB theorem Prodl_mul (l : list A) (f g : A → B) : Prodl l (λx, f x * g x) = Prodl l f * Prodl l g := list.induction_on l (by rewrite [*Prodl_nil, mul_one]) (take a l, assume IH, by rewrite [*Prodl_cons, IH, *mul.assoc, mul.left_comm (Prodl l f)]) end comm_monoid /- Prod: product indexed by a finset -/ section comm_monoid variable [cmB : comm_monoid B] include cmB theorem mulf_rcomm (f : A → B) : right_commutative (mulf f) := right_commutative_compose_right (@has_mul.mul B cmB) f (@mul.right_comm B cmB) theorem Prodl_eq_Prodl_of_perm (f : A → B) {l₁ l₂ : list A} : perm l₁ l₂ → Prodl l₁ f = Prodl l₂ f := λ p, perm.foldl_eq_of_perm (mulf_rcomm f) p 1 definition Prod (s : finset A) (f : A → B) : B := quot.lift_on s (λ l, Prodl (elt_of l) f) (λ l₁ l₂ p, Prodl_eq_Prodl_of_perm f p) -- ∏ x ∈ s, f x notation `∏` binders `∈` s, r:(scoped f, prod s f) := r theorem Prod_empty (f : A → B) : Prod ∅ f = 1 := Prodl_nil f theorem Prod_mul (s : finset A) (f g : A → B) : Prod s (λx, f x * g x) = Prod s f * Prod s g := quot.induction_on s (take u, !Prodl_mul) section deceqA include deceqA theorem Prod_insert_of_mem (f : A → B) {a : A} {s : finset A} : a ∈ s → Prod (insert a s) f = Prod s f := quot.induction_on s (λ l ainl, Prodl_insert_of_mem f ainl) theorem Prod_insert_of_not_mem (f : A → B) {a : A} {s : finset A} : a ∉ s → Prod (insert a s) f = f a * Prod s f := quot.induction_on s (λ l nainl, Prodl_insert_of_not_mem f nainl) theorem Prod_union (f : A → B) {s₁ s₂ : finset A} (disj : s₁ ∩ s₂ = ∅) : Prod (s₁ ∪ s₂) f = Prod s₁ f * Prod s₂ f := have H1 : disjoint s₁ s₂ → Prod (s₁ ∪ s₂) f = Prod s₁ f * Prod s₂ f, from quot.induction_on₂ s₁ s₂ (λ l₁ l₂ d, Prodl_union f d), H1 (disjoint_of_inter_eq_empty disj) theorem Prod_ext {s : finset A} {f g : A → B} : (∀{x}, x ∈ s → f x = g x) → Prod s f = Prod s g := finset.induction_on s (assume H, rfl) (take x s', assume H1 : x ∉ s', assume IH : (∀ {x : A}, x ∈ s' → f x = g x) → Prod s' f = Prod s' g, assume H2 : ∀{y}, y ∈ insert x s' → f y = g y, assert H3 : ∀y, y ∈ s' → f y = g y, from take y, assume H', H2 (mem_insert_of_mem _ H'), assert H4 : f x = g x, from H2 !mem_insert, by rewrite [Prod_insert_of_not_mem f H1, Prod_insert_of_not_mem g H1, IH H3, H4]) end deceqA theorem Prod_one (s : finset A) : Prod s (λ x, 1) = (1:B) := quot.induction_on s (take u, !Prodl_one) end comm_monoid section add_monoid variable [amB : add_monoid B] include amB local attribute add_monoid.to_monoid [trans-instance] definition Suml (l : list A) (f : A → B) : B := Prodl l f -- ∑ x ← l, f x notation `∑` binders `←` l, r:(scoped f, Suml l f) := r theorem Suml_nil (f : A → B) : Suml [] f = 0 := Prodl_nil f theorem Suml_cons (f : A → B) (a : A) (l : list A) : Suml (a::l) f = f a + Suml l f := Prodl_cons f a l theorem Suml_append (l₁ l₂ : list A) (f : A → B) : Suml (l₁++l₂) f = Suml l₁ f + Suml l₂ f := Prodl_append l₁ l₂ f section deceqA include deceqA theorem Suml_insert_of_mem (f : A → B) {a : A} {l : list A} (H : a ∈ l) : Suml (insert a l) f = Suml l f := Prodl_insert_of_mem f H theorem Suml_insert_of_not_mem (f : A → B) {a : A} {l : list A} (H : a ∉ l) : Suml (insert a l) f = f a + Suml l f := Prodl_insert_of_not_mem f H theorem Suml_union {l₁ l₂ : list A} (f : A → B) (d : disjoint l₁ l₂) : Suml (union l₁ l₂) f = Suml l₁ f + Suml l₂ f := Prodl_union f d end deceqA theorem Suml_zero (l : list A) : Suml l (λ x, 0) = (0:B) := Prodl_one l end add_monoid section add_comm_monoid variable [acmB : add_comm_monoid B] include acmB local attribute add_comm_monoid.to_comm_monoid [trans-instance] theorem Suml_add (l : list A) (f g : A → B) : Suml l (λx, f x + g x) = Suml l f + Suml l g := Prodl_mul l f g end add_comm_monoid /- Sum -/ section add_comm_monoid variable [acmB : add_comm_monoid B] include acmB local attribute add_comm_monoid.to_comm_monoid [trans-instance] definition Sum (s : finset A) (f : A → B) : B := Prod s f -- ∑ x ∈ s, f x notation `∑` binders `∈` s, r:(scoped f, Sum s f) := r theorem Sum_empty (f : A → B) : Sum ∅ f = 0 := Prod_empty f theorem Sum_add (s : finset A) (f g : A → B) : Sum s (λx, f x + g x) = Sum s f + Sum s g := Prod_mul s f g section deceqA include deceqA theorem Sum_insert_of_mem (f : A → B) {a : A} {s : finset A} (H : a ∈ s) : Sum (insert a s) f = Sum s f := Prod_insert_of_mem f H theorem Sum_insert_of_not_mem (f : A → B) {a : A} {s : finset A} (H : a ∉ s) : Sum (insert a s) f = f a + Sum s f := Prod_insert_of_not_mem f H theorem Sum_union (f : A → B) {s₁ s₂ : finset A} (disj : s₁ ∩ s₂ = ∅) : Sum (s₁ ∪ s₂) f = Sum s₁ f + Sum s₂ f := Prod_union f disj theorem Sum_ext {s : finset A} {f g : A → B} (H : ∀x, x ∈ s → f x = g x) : Sum s f = Sum s g := Prod_ext H end deceqA theorem Sum_zero (s : finset A) : Sum s (λ x, 0) = (0:B) := Prod_one s end add_comm_monoid end algebra
93a0fd19e96d81a4079fdaddffd76b2eb0689f1a
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/t4.lean
68c6fb3ff6786dc6b5078e6d262c95baca481f6d
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
210
lean
namespace foo definition f.{l} (A : Type.{l}) : Type.{l} := A check f.{1} end variable N : Type.{1} section parameter A : Type definition g (a : A) (B : Type) : A := a check g.{2} end check g.{2 3}
08813c592717d1551148c2fa1cec73a77c5dd719
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/algebra/category/adjoint.lean
fb858f2ae2efb88b4478835917aad5b9f324e51f
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,354
lean
-- Copyright (c) 2014 Floris van Doorn. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Floris van Doorn import .constructions open eq eq.ops category functor natural_transformation category.ops prod category.product namespace adjoint --representable functor definition foo (C : Category) : C ×c C ⇒ C ×c C := functor.id -- definition Hom (C : Category) : Cᵒᵖ ×c C ⇒ type := -- functor.mk (λ a, hom (pr1 a) (pr2 a)) -- (λ a b f h, pr2 f ∘ h ∘ pr1 f) -- (λ a, funext (λh, !id_left ⬝ !id_right)) -- (λ a b c g f, funext (λh, -- show (pr2 g ∘ pr2 f) ∘ h ∘ (pr1 f ∘ pr1 g) = pr2 g ∘ (pr2 f ∘ h ∘ pr1 f) ∘ pr1 g, from sorry)) --I'm lazy, waiting for automation to fill this variables (C D : Category) -- private definition aux_prod_cat [instance] : category (obD × obD) := prod_category (opposite.opposite D) D -- definition adjoint.{l} (F : C ⇒ D) (G : D ⇒ C) := -- --@natural_transformation _ Type.{l} (Dᵒᵖ ×c D) type_category.{l+1} (Hom D) (Hom D) -- sorry --(@functor.compose _ _ _ _ _ _ (Hom D) (@product.prod_functor _ _ _ _ _ _ (Dᵒᵖ) D sorry sorry)) --(Hom C ∘f sorry) --product.prod_functor (opposite.opposite_functor F) (functor.ID D) end adjoint
1d7f293e96a6b9c524b21f3666b6aa297eecd427
0533ebfa09b11cf8a29da118dd1b86b94949511e
/src/dirichlet_eta.lean
35e945b58703fe5cbc4c26e89fcb3c28b062e37d
[ "MIT" ]
permissive
wudcscheme/Lean-RH
89e9055aac68703876e750c23fb5327979a09822
870f78cc7c0715d03466d1211b0f032b425ec984
refs/heads/main
1,679,188,429,923
1,602,701,790,000
1,602,701,790,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,926
lean
/- ------------------------------------------------------------------------- -| | @project: riemann_hypothesis | | @file: dirichlet_eta.lean | | @author: Brandon H. Gomes and Alex Kontorovich | | @affil: Rutgers University | |- ------------------------------------------------------------------------- -/ import .complex import .riemann_zeta /-! -/ namespace riemann_hypothesis --——————————————————————————————————————————————————————————-- variables {ℂ : Type*} {ℝ : Type*} [has_lift_t nat ℝ] [has_lift_t ℝ ℂ] [preorder ℝ] [Algebra ℝ] [Algebra ℂ] (ℭ : Complex ℂ ℝ) namespace dirichlet_eta --———————————————————————————————————————————————————————————————-- open algebra /-- -/ def term_pair [has_lift_zero_same nat ℝ] [has_lift_lt_comm nat ℝ] (s n) := riemann_zeta.term ℭ.pow s (2 * n) - riemann_zeta.term ℭ.pow s (2 * n).succ namespace term_pair --———————————————————————————————————————————————————————————————————-- /-- -/ def riemann_zeta_bound (s) := ↑4 * ℭ.real_exp (ℭ.abs s) + ↑3 * ℭ.abs s namespace riemann_zeta_bound --——————————————————————————————————————————————————————————-- variables [has_zero_mul_is_zero ℝ] [has_nonneg_mul_nonneg_is_nonneg ℝ] [has_lt_add_of_le_of_pos ℝ] [has_lt_pos_mul_preserves_right ℝ] [has_lift_zero_same nat ℝ] [has_lift_one_same nat ℝ] [has_lift_add_comm nat ℝ] [has_lift_lt_comm nat ℝ] /-- -/ def positive (s) : 0 < riemann_zeta_bound ℭ s := begin refine has_lt_add_of_le_of_pos.lt _ (has_nonneg_mul_nonneg_is_nonneg.le (le_of_lt (nat.lift.succ_pos ℝ _)) (ℭ.abs_nonneg _)), let four_exponentials_are_positive := has_lt_pos_mul_preserves_right.lt (ℭ.real_explog.exp_positive _) (nat.lift.succ_pos ℝ _), rw has_zero_mul_is_zero.eq at four_exponentials_are_positive, refine four_exponentials_are_positive, end /-- -/ def abs_positive (ge_zero_to_abs : Π z, 0 ≤ z → ℭ.abs ↑z = z) (s) : 0 < ℭ.abs ↑(riemann_zeta_bound ℭ s) := begin rw ge_zero_to_abs _ (le_of_lt (positive ℭ _)), refine positive ℭ _, end end riemann_zeta_bound --————————————————————————————————————————————————————————————————-- /-- -/ def bounded_by_riemann_zeta [has_add_le_add ℝ] [has_inv_mul_reverse ℝ] [has_inv_mul_right_cancel_self ℝ] [has_inv_reverses_le ℝ] [has_le_nonneg_mul_preserves_left ℝ] [has_le_nonneg_mul_preserves_right ℝ] [has_le_pos_mul_preserves_left ℝ] [has_le_pos_mul_preserves_right ℝ] [has_left_add_distributivity ℝ] [has_left_sub_distributivity ℝ] [has_left_unit ℝ] [has_lt_add_of_le_of_pos ℝ] [has_lt_pos_mul_preserves_right ℝ] [has_mul_assoc ℝ] [has_nonneg_mul_nonneg_is_nonneg ℝ] [has_right_add_distributivity ℝ] [has_right_inv_pos_lt ℝ] [has_right_sub_distributivity ℝ] [has_right_unit ℝ] [has_squared_le_monotonic ℝ] [has_zero_mul_is_zero ℝ] [has_mul_zero_is_zero ℝ] [has_zero_right_add_cancel ℝ] [has_zero_sub_is_neg ℝ] [has_mul_pos ℝ] [has_inv_pos ℝ] [has_lift_add_comm nat ℝ] [has_lift_le_comm nat ℝ] [has_lift_lt_comm nat ℝ] [has_lift_ne_comm nat ℝ] [has_lift_sub_comm nat ℝ] [has_lift_one_same nat ℝ] [has_lift_zero_same nat ℝ] [has_add_sub_assoc ℂ] [has_inv_mul_left_cancel_self ℂ] [has_left_sub_distributivity ℂ] [has_left_unit ℂ] [has_mul_assoc ℂ] [has_right_sub_distributivity ℂ] [has_right_unit ℂ] [has_sub_add_sub_cancel ℂ] [has_sub_self_is_zero ℂ] [has_mul_zero_is_zero ℂ] [has_zero_right_add_cancel ℂ] [has_zero_sub_is_neg ℂ] [has_lift_sub_comm ℝ ℂ] (abs_mul : Π a b, ℭ.abs (a * b) = ℭ.abs (a) * ℭ.abs (b)) (abs_sub : Π a b, ℭ.abs (a - b) = ℭ.abs (b - a)) (abs_inv : Π z, ℭ.abs (z⁻¹) = (ℭ.abs z)⁻¹) (abs_add : Π a b, ℭ.abs (a + b) ≤ ℭ.abs a + ℭ.abs b) (ge_zero_to_abs : Π x, 0 ≤ x → ℭ.abs ↑x = x) (s n) : ℭ.abs (term_pair ℭ s n) ≤ riemann_zeta.term.on_reals ℭ.real_explog (1 + ℭ.real_part s) (2 * n) * riemann_zeta_bound ℭ s := begin rw [term_pair, riemann_zeta.term.on_reals], rw [riemann_zeta.term, riemann_zeta.term, riemann_zeta.term], rw [← has_zero_sub_is_neg.eq, ← has_zero_sub_is_neg.eq], rw ExpLog.pow_neg_exponent_inverts, rw ExpLog.pow_homomorphism, rw has_inv_mul_reverse.eq, rw ℭ.real_explog.pow_id_at_one _ (nat.lift.succ_pos ℝ _), rw Complex.pow_neg_exponent_inverts, rw Complex.pow_neg_exponent_inverts, rw inv_sub_inv_lemma' (ℭ.pow_nonzero _ _ _), rw abs_mul, rw abs_inv, rw Complex.abs_pow_is_real_pow, rw has_mul_assoc.eq, rw ← ExpLog.pow_neg_exponent_inverts, let K := (↑(2 * n).succ.succ : ℝ), have Kinv_ge_zero : K⁻¹ ≥ 0, { let ineq := has_right_inv_pos_lt.lt (nat.lift.succ_pos ℝ _) (nat.lift.zero_lt_one ℝ), rw [has_zero_mul_is_zero.eq, has_left_unit.eq] at ineq, refine le_of_lt ineq, }, let remove_abs := ge_zero_to_abs _ Kinv_ge_zero, refine has_le_pos_mul_preserves_left.le (ℭ.real_explog.pow_positivity _ (nat.lift.succ_pos ℝ _) _) _, rw [Complex.pow, Complex.pow], rw ← Complex.exp_homomorphism_inv, rw ← has_right_sub_distributivity.eq, rw ← has_lift_sub_comm.eq, rw ← ℭ.real_explog.log_homomorphism_inv (nat.lift.succ_pos ℝ _) (nat.lift.succ_pos ℝ _), rw ← Complex.pow, rw ℭ.pow_domain_irrel (↑((2 * n).succ) * (↑((2 * n).succ.succ))⁻¹) _ (1 - (↑(2 * n).succ.succ)⁻¹) _ _ (by rw mul_inv_add_one_lemma), refine le_trans _ (has_le_pos_mul_preserves_right.le (riemann_zeta_bound.positive _ _) (has_inv_reverses_le.le (le_of_lt (has_lift_lt_comm.lt (nat.lt_succ_self _))))), rw ← mul_inv_add_one_lemma, refine has_mul_pos.lt (nat.lift.succ_pos ℝ _) (has_inv_pos.lt (nat.lift.succ_pos ℝ _)), rw abs_sub, rw riemann_zeta_bound, rw has_left_add_distributivity.eq, refine le_trans (Complex.one_minus_pow_bound _ _ _ abs_mul abs_add _ _ _ _) _, rw two_is_lifted_two_lemma nat ℝ, refine nat.lift.succ_pos ℝ _, rw two_is_lifted_two_lemma nat ℝ, rw one_is_lifted_one_lemma nat ℝ, refine has_lift_le_comm.le (le_of_lt (nat.lt_succ_self _)), rw remove_abs, rw two_is_lifted_two_lemma nat ℝ, refine has_inv_reverses_le.le (has_lift_le_comm.le (nat.smallest_positive_even _)), rw remove_abs, rw ← has_left_add_distributivity.eq, rw four_is_lifted_four_lemma nat ℝ, rw ← two_mul_lemma, refine has_le_nonneg_mul_preserves_left.le Kinv_ge_zero (has_add_le_add.le (le_refl _) (has_le_nonneg_mul_preserves_right.le (ℭ.abs_nonneg _) _)), rw two_is_lifted_two_lemma nat ℝ, refine has_lift_le_comm.le (le_of_lt (nat.lt_succ_self _)), end end term_pair --—————————————————————————————————————————————————————————————————————————-- /-- -/ def partial_pairs [has_lift_lt_comm nat ℝ] [has_lift_zero_same nat ℝ] (s) := partial_sum (term_pair ℭ s) /-- -/ def partial_pairs.is_cauchy [has_add_le_add ℝ] [has_add_left_lt ℝ] [has_add_lt_add ℝ] [has_add_nonneg ℝ] [has_add_sub_assoc ℝ] [has_add_sub_exchange ℝ] [has_inv_mul_left_cancel_self ℝ] [has_inv_mul_reverse ℝ] [has_inv_mul_right_cancel_self ℝ] [has_inv_reverses_le ℝ] [has_inv_reverses_lt ℝ] [has_inv_right_mul_lt_pos ℝ] [has_le_add_of_nonneg_of_le ℝ] [has_le_nonneg_mul_preserves_left ℝ] [has_le_nonneg_mul_preserves_right ℝ] [has_le_pos_mul_preserves_left ℝ] [has_le_pos_mul_preserves_right ℝ] [has_le_sub_add_le ℝ] [has_left_add_distributivity ℝ] [has_left_mul_inv_lt_neg ℝ] [has_left_mul_inv_lt_pos ℝ] [has_left_sub_distributivity ℝ] [has_left_unit ℝ] [has_lt_add_of_le_of_pos ℝ] [has_lt_pos_mul_preserves_right ℝ] [has_lt_sub_neg ℝ] [has_mul_assoc ℝ] [has_nonneg_mul_nonneg_is_nonneg ℝ] [has_pos_mul_neg_is_neg ℝ] [has_right_add_distributivity ℝ] [has_right_inv_pos_lt ℝ] [has_right_sub_distributivity ℝ] [has_right_unit ℝ] [has_squared_le_monotonic ℝ] [has_sub_add_sub_cancel ℝ] [has_sub_self_is_zero ℝ] [has_sub_ne_zero_of_ne ℝ] [has_sub_sub ℝ] [has_zero_mul_is_zero ℝ] [has_mul_zero_is_zero ℝ] [has_zero_left_add_cancel ℝ] [has_zero_right_add_cancel ℝ] [has_zero_sub_is_neg ℝ] [has_mul_pos ℝ] [has_inv_pos ℝ] [has_sub_pos ℝ] [has_lift_zero_same nat ℝ] [has_lift_one_same nat ℝ] [has_lift_add_comm nat ℝ] [has_lift_mul_comm nat ℝ] [has_lift_sub_comm nat ℝ] [has_lift_le_comm nat ℝ] [has_lift_lt_comm nat ℝ] [has_lift_ne_comm nat ℝ] [has_add_sub_assoc ℂ] [has_inv_mul_left_cancel_self ℂ] [has_left_sub_distributivity ℂ] [has_left_unit ℂ] [has_mul_assoc ℂ] [has_right_sub_distributivity ℂ] [has_right_unit ℂ] [has_sub_add_sub_cancel ℂ] [has_sub_self_is_zero ℂ] [has_mul_zero_is_zero ℂ] [has_zero_right_add_cancel ℂ] [has_zero_sub_is_neg ℂ] [has_lift_zero_same ℝ ℂ] [has_lift_one_same ℝ ℂ] [has_lift_add_comm ℝ ℂ] [has_lift_sub_comm ℝ ℂ] [has_lift_mul_comm ℝ ℂ] [has_lift_inv_comm ℝ ℂ] (abs_zero abs_one) (abs_add : Π w z, ℭ.abs (w + z) ≤ ℭ.abs w + ℭ.abs z) (abs_sub : Π w z, ℭ.abs (w - z) = ℭ.abs (z - w)) (abs_mul : Π w z, ℭ.abs (w * z) = ℭ.abs w * ℭ.abs z) (abs_inv : Π z, ℭ.abs (z⁻¹) = (ℭ.abs z)⁻¹) (abs_ge_zero) (pos_to_absℝ abs_monoℝ) (half ceil) (s) (σpos : 0 < ℭ.real_part s) : is_cauchy ℭ.abs (partial_pairs ℭ s) := begin let one_plus_σ_gt_one := has_add_left_lt.lt _ _ 1 σpos, rw has_zero_right_add_cancel.eq at one_plus_σ_gt_one, have abs_zeroℝ : ℭ.abs ↑(0 : ℝ) = 0, rw has_lift_zero_same.eq, refine abs_zero, have abs_oneℝ : ℭ.abs ↑(1 : ℝ) = 1, rw has_lift_one_same.eq, refine abs_one, have abs_addℝ : Π x y : ℝ, ℭ.abs ↑(x + y) ≤ ℭ.abs ↑x + ℭ.abs ↑y, intros, rw has_lift_add_comm.eq, refine abs_add _ _, have abs_subℝ : Π x y : ℝ, ℭ.abs ↑(x - y) = ℭ.abs ↑(y - x), intros, rw [has_lift_sub_comm.eq, has_lift_sub_comm.eq], refine abs_sub _ _, have abs_mulℝ : Π x y : ℝ, ℭ.abs ↑(x * y) = ℭ.abs ↑x * ℭ.abs ↑y, intros, rw has_lift_mul_comm.eq, refine abs_mul _ _, have abs_invℝ : Π x : ℝ, ℭ.abs ↑(x⁻¹) = (ℭ.abs ↑x)⁻¹, intros, rw has_lift_inv_comm.eq, refine abs_inv _, refine is_cauchy.comparison _ pos_to_absℝ _ abs_zero abs_add abs_ge_zero _ _ (term_pair.bounded_by_riemann_zeta _ abs_mul abs_sub abs_inv abs_add pos_to_absℝ _) (is_cauchy.closed.partial_sum_right_mul _ abs_mulℝ _ _ (term_pair.riemann_zeta_bound.abs_positive _ pos_to_absℝ _) (is_cauchy.closed.scaled_sequence_partial_sum _ abs_monoℝ _ (riemann_zeta.term.on_reals.nonneg _ _) _ (nat.zero_lt_one_add _) (riemann_zeta.partial.on_reals.is_cauchy _ _ abs_zeroℝ abs_oneℝ abs_addℝ abs_subℝ abs_mulℝ abs_invℝ (λ _, abs_ge_zero _) pos_to_absℝ half ceil _ one_plus_σ_gt_one))), end end dirichlet_eta --—————————————————————————————————————————————————————————————————————-- end riemann_hypothesis --————————————————————————————————————————————————————————————————--
ba83dfd2524d5d486d71776ba596e1059d881b0c
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/algebra/ring.lean
8b5d89f91bb39e278e029876f3be631e58a4bea3
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
20,140
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 -/ import algebra.ring.prod import ring_theory.ideal.quotient import ring_theory.subring.basic import topology.algebra.group.basic /-! # Topological (semi)rings A topological (semi)ring is a (semi)ring equipped with a topology such that all operations are continuous. Besides this definition, this file proves that the topological closure of a subring (resp. an ideal) is a subring (resp. an ideal) and defines products and quotients of topological (semi)rings. ## Main Results - `subring.topological_closure`/`subsemiring.topological_closure`: the topological closure of a `subring`/`subsemiring` is itself a `sub(semi)ring`. - `prod.topological_semiring`/`prod.topological_ring`: The product of two topological (semi)rings. - `pi.topological_semiring`/`pi.topological_ring`: The arbitrary product of topological (semi)rings. - `ideal.closure`: The closure of an ideal is an ideal. - `topological_ring_quotient`: The quotient of a topological semiring by an ideal is a topological ring. -/ open classical set filter topological_space function open_locale classical topological_space filter section topological_semiring variables (α : Type*) /-- a topological semiring is a semiring `R` where addition and multiplication are continuous. We allow for non-unital and non-associative semirings as well. The `topological_semiring` class should *only* be instantiated in the presence of a `non_unital_non_assoc_semiring` instance; if there is an instance of `non_unital_non_assoc_ring`, then `topological_ring` should be used. Note: in the presence of `non_assoc_ring`, these classes are mathematically equivalent (see `topological_semiring.has_continuous_neg_of_mul` or `topological_semiring.to_topological_ring`). -/ class topological_semiring [topological_space α] [non_unital_non_assoc_semiring α] extends has_continuous_add α, has_continuous_mul α : Prop /-- A topological ring is a ring `R` where addition, multiplication and negation are continuous. If `R` is a (unital) ring, then continuity of negation can be derived from continuity of multiplication as it is multiplication with `-1`. (See `topological_semiring.has_continuous_neg_of_mul` and `topological_semiring.to_topological_add_group`) -/ class topological_ring [topological_space α] [non_unital_non_assoc_ring α] extends topological_semiring α, has_continuous_neg α : Prop variables {α} /-- If `R` is a ring with a continuous multiplication, then negation is continuous as well since it is just multiplication with `-1`. -/ lemma topological_semiring.has_continuous_neg_of_mul [topological_space α] [non_assoc_ring α] [has_continuous_mul α] : has_continuous_neg α := { continuous_neg := by simpa using (continuous_const.mul continuous_id : continuous (λ x : α, (-1) * x)) } /-- If `R` is a ring which is a topological semiring, then it is automatically a topological ring. This exists so that one can place a topological ring structure on `R` without explicitly proving `continuous_neg`. -/ lemma topological_semiring.to_topological_ring [topological_space α] [non_assoc_ring α] (h : topological_semiring α) : topological_ring α := { ..h, ..(by { haveI := h.to_has_continuous_mul, exact topological_semiring.has_continuous_neg_of_mul } : has_continuous_neg α) } @[priority 100] -- See note [lower instance priority] instance topological_ring.to_topological_add_group [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_add_group α := { ..topological_ring.to_topological_semiring.to_has_continuous_add, ..topological_ring.to_has_continuous_neg } @[priority 50] instance discrete_topology.topological_semiring [topological_space α] [non_unital_non_assoc_semiring α] [discrete_topology α] : topological_semiring α := ⟨⟩ @[priority 50] instance discrete_topology.topological_ring [topological_space α] [non_unital_non_assoc_ring α] [discrete_topology α] : topological_ring α := ⟨⟩ section variables [topological_space α] [semiring α] [topological_semiring α] namespace subsemiring instance (S : subsemiring α) : topological_semiring S := { ..S.to_submonoid.has_continuous_mul, ..S.to_add_submonoid.has_continuous_add } end subsemiring /-- The (topological-space) closure of a subsemiring of a topological semiring is itself a subsemiring. -/ def subsemiring.topological_closure (s : subsemiring α) : subsemiring α := { carrier := closure (s : set α), ..(s.to_submonoid.topological_closure), ..(s.to_add_submonoid.topological_closure ) } @[simp] lemma subsemiring.topological_closure_coe (s : subsemiring α) : (s.topological_closure : set α) = closure (s : set α) := rfl lemma subsemiring.le_topological_closure (s : subsemiring α) : s ≤ s.topological_closure := subset_closure lemma subsemiring.is_closed_topological_closure (s : subsemiring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subsemiring.topological_closure_minimal (s : subsemiring α) {t : subsemiring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subsemiring of a topological semiring is commutative, then so is its topological closure. -/ def subsemiring.comm_semiring_topological_closure [t2_space α] (s : subsemiring α) (hs : ∀ (x y : s), x * y = y * x) : comm_semiring s.topological_closure := { ..s.topological_closure.to_semiring, ..s.to_submonoid.comm_monoid_topological_closure hs } end section variables {β : Type*} [topological_space α] [topological_space β] /-- The product topology on the cartesian product of two topological semirings makes the product into a topological semiring. -/ instance [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] [topological_semiring α] [topological_semiring β] : topological_semiring (α × β) := {} /-- The product topology on the cartesian product of two topological rings makes the product into a topological ring. -/ instance [non_unital_non_assoc_ring α] [non_unital_non_assoc_ring β] [topological_ring α] [topological_ring β] : topological_ring (α × β) := {} end instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, non_unital_non_assoc_semiring (C b)] [Π b, topological_semiring (C b)] : topological_semiring (Π b, C b) := {} instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, non_unital_non_assoc_ring (C b)] [Π b, topological_ring (C b)] : topological_ring (Π b, C b) := {} section mul_opposite open mul_opposite instance [non_unital_non_assoc_semiring α] [topological_space α] [has_continuous_add α] : has_continuous_add αᵐᵒᵖ := { continuous_add := continuous_induced_rng.2 $ (@continuous_add α _ _ _).comp (continuous_unop.prod_map continuous_unop) } instance [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] : topological_semiring αᵐᵒᵖ := {} instance [non_unital_non_assoc_ring α] [topological_space α] [has_continuous_neg α] : has_continuous_neg αᵐᵒᵖ := { continuous_neg := continuous_induced_rng.2 $ (@continuous_neg α _ _ _).comp continuous_unop } instance [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_ring αᵐᵒᵖ := {} end mul_opposite section add_opposite open add_opposite instance [non_unital_non_assoc_semiring α] [topological_space α] [has_continuous_mul α] : has_continuous_mul αᵃᵒᵖ := { continuous_mul := by convert (continuous_op.comp $ (@continuous_mul α _ _ _).comp $ continuous_unop.prod_map continuous_unop) } instance [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] : topological_semiring αᵃᵒᵖ := {} instance [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_ring αᵃᵒᵖ := {} end add_opposite section variables {R : Type*} [non_unital_non_assoc_ring R] [topological_space R] lemma topological_ring.of_add_group_of_nhds_zero [topological_add_group R] (hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0) (hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) : topological_ring R := begin refine {..‹topological_add_group R›, ..}, have hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0), by simp, have hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) (𝓝 0), { rw ← nhds_prod_eq, convert continuous_add.tendsto ((0 : R), (0 : R)), rw zero_add }, rw continuous_iff_continuous_at, rintro ⟨x₀, y₀⟩, rw [continuous_at, nhds_prod_eq, hleft x₀, hleft y₀, hleft (x₀*y₀), filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λ (x : R), x + x₀ * y₀) ∘ (λ (p : R × R), p.1 + p.2) ∘ (λ (p : R × R), (p.1*y₀ + x₀*p.2, p.1*p.2))) ((𝓝 0) ×ᶠ (𝓝 0)) (map (λ (x : R), x + x₀ * y₀) $ 𝓝 0), { convert this using 1, { ext, simp only [comp_app, mul_add, add_mul], abel }, { simp only [add_comm] } }, refine tendsto_map.comp (hadd.comp (tendsto.prod_mk _ hmul)), exact hadd.comp (((hmul_right y₀).comp tendsto_fst).prod_mk ((hmul_left x₀).comp tendsto_snd)) end lemma topological_ring.of_nhds_zero (hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hneg : tendsto (λ x, -x : R → R) (𝓝 0) (𝓝 0)) (hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0) (hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) (hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0)) : topological_ring R := begin haveI := topological_add_group.of_comm_of_nhds_zero hadd hneg hleft, exact topological_ring.of_add_group_of_nhds_zero hmul hmul_left hmul_right end end variables {α} [topological_space α] section variables [non_unital_non_assoc_ring α] [topological_ring α] /-- In a topological semiring, the left-multiplication `add_monoid_hom` is continuous. -/ lemma mul_left_continuous (x : α) : continuous (add_monoid_hom.mul_left x) := continuous_const.mul continuous_id /-- In a topological semiring, the right-multiplication `add_monoid_hom` is continuous. -/ lemma mul_right_continuous (x : α) : continuous (add_monoid_hom.mul_right x) := continuous_id.mul continuous_const end variables [ring α] [topological_ring α] namespace subring instance (S : subring α) : topological_ring S := topological_semiring.to_topological_ring S.to_subsemiring.topological_semiring end subring /-- The (topological-space) closure of a subring of a topological ring is itself a subring. -/ def subring.topological_closure (S : subring α) : subring α := { carrier := closure (S : set α), ..S.to_submonoid.topological_closure, ..S.to_add_subgroup.topological_closure } lemma subring.le_topological_closure (s : subring α) : s ≤ s.topological_closure := subset_closure lemma subring.is_closed_topological_closure (s : subring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subring.topological_closure_minimal (s : subring α) {t : subring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subring of a topological ring is commutative, then so is its topological closure. -/ def subring.comm_ring_topological_closure [t2_space α] (s : subring α) (hs : ∀ (x y : s), x * y = y * x) : comm_ring s.topological_closure := { ..s.topological_closure.to_ring, ..s.to_submonoid.comm_monoid_topological_closure hs } end topological_semiring section topological_ring variables {α : Type*} [topological_space α] [ring α] [topological_ring α] /-- The closure of an ideal in a topological ring as an ideal. -/ def ideal.closure (S : ideal α) : ideal α := { carrier := closure S, smul_mem' := λ c x hx, map_mem_closure (mul_left_continuous _) hx $ λ a, S.mul_mem_left c, ..(add_submonoid.topological_closure S.to_add_submonoid) } @[simp] lemma ideal.coe_closure (S : ideal α) : (S.closure : set α) = closure S := rfl @[simp] lemma ideal.closure_eq_of_is_closed (S : ideal α) [hS : is_closed (S : set α)] : S.closure = S := ideal.ext $ set.ext_iff.mp hS.closure_eq end topological_ring section topological_ring variables {α : Type*} [topological_space α] [comm_ring α] (N : ideal α) open ideal.quotient instance topological_ring_quotient_topology : topological_space (α ⧸ N) := show topological_space (quotient _), by apply_instance -- note for the reader: in the following, `mk` is `ideal.quotient.mk`, the canonical map `R → R/I`. variable [topological_ring α] lemma quotient_ring.is_open_map_coe : is_open_map (mk N) := begin intros s s_op, change is_open (mk N ⁻¹' (mk N '' s)), rw quotient_ring_saturate, exact is_open_Union (λ ⟨n, _⟩, is_open_map_add_left n s s_op) end lemma quotient_ring.quotient_map_coe_coe : quotient_map (λ p : α × α, (mk N p.1, mk N p.2)) := is_open_map.to_quotient_map ((quotient_ring.is_open_map_coe N).prod (quotient_ring.is_open_map_coe N)) ((continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd)) (by rintro ⟨⟨x⟩, ⟨y⟩⟩; exact ⟨(x, y), rfl⟩) instance topological_ring_quotient : topological_ring (α ⧸ N) := topological_semiring.to_topological_ring { continuous_add := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst + p.snd)) := continuous_quot_mk.comp continuous_add, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont, continuous_mul := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont } end topological_ring /-! ### Lattice of ring topologies We define a type class `ring_topology α` which endows a ring `α` with a topology such that all ring operations are continuous. Ring topologies on a fixed ring `α` are ordered, by reverse inclusion. They form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. Any function `f : α → β` induces `coinduced f : topological_space α → ring_topology β`. -/ universes u v /-- A ring topology on a ring `α` is a topology for which addition, negation and multiplication are continuous. -/ @[ext] structure ring_topology (α : Type u) [ring α] extends topological_space α, topological_ring α : Type u namespace ring_topology variables {α : Type*} [ring α] instance inhabited {α : Type u} [ring α] : inhabited (ring_topology α) := ⟨{to_topological_space := ⊤, continuous_add := continuous_top, continuous_mul := continuous_top, continuous_neg := continuous_top}⟩ @[ext] lemma ext' {f g : ring_topology α} (h : f.is_open = g.is_open) : f = g := by { ext, rw h } /-- The ordering on ring topologies on the ring `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (ring_topology α) := partial_order.lift ring_topology.to_topological_space $ ext local notation `cont` := @continuous _ _ private def def_Inf (S : set (ring_topology α)) : ring_topology α := let Inf_S' := Inf (to_topological_space '' S) in { to_topological_space := Inf_S', continuous_add := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_add h_continuous_id, end, continuous_mul := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_mul h_continuous_id, end, continuous_neg := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_neg h, end } /-- Ring topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of ring topologies is the topology generated by all their open sets (which is a ring topology). The supremum of two ring topologies `s` and `t` is the infimum of the family of all ring topologies contained in the intersection of `s` and `t`. -/ instance : complete_semilattice_Inf (ring_topology α) := { Inf := def_Inf, Inf_le := λ S a haS, by { apply topological_space.complete_lattice.Inf_le, use [a, ⟨ haS, rfl⟩] }, le_Inf := begin intros S a hab, apply topological_space.complete_lattice.le_Inf, rintros _ ⟨b, hbS, rfl⟩, exact hab b hbS, end, ..ring_topology.partial_order } instance : complete_lattice (ring_topology α) := complete_lattice_of_complete_semilattice_Inf _ /-- Given `f : α → β` and a topology on `α`, the coinduced ring topology on `β` is the finest topology such that `f` is continuous and `β` is a topological ring. -/ def coinduced {α β : Type*} [t : topological_space α] [ring β] (f : α → β) : ring_topology β := Inf {b : ring_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space} lemma coinduced_continuous {α β : Type*} [t : topological_space α] [ring β] (f : α → β) : cont t (coinduced f).to_topological_space f := begin rw continuous_iff_coinduced_le, refine le_Inf _, rintros _ ⟨t', ht', rfl⟩, exact ht', end /-- The forgetful functor from ring topologies on `a` to additive group topologies on `a`. -/ def to_add_group_topology (t : ring_topology α) : add_group_topology α := { to_topological_space := t.to_topological_space, to_topological_add_group := @topological_ring.to_topological_add_group _ _ t.to_topological_space t.to_topological_ring } /-- The order embedding from ring topologies on `a` to additive group topologies on `a`. -/ def to_add_group_topology.order_embedding : order_embedding (ring_topology α) (add_group_topology α) := { to_fun := λ t, t.to_add_group_topology, inj' := begin intros t₁ t₂ h_eq, dsimp only at h_eq, ext, have h_t₁ : t₁.to_topological_space = t₁.to_add_group_topology.to_topological_space := rfl, rw [h_t₁, h_eq], refl, end, map_rel_iff' := begin intros t₁ t₂, rw [embedding.coe_fn_mk], have h_le : t₁ ≤ t₂ ↔ t₁.to_topological_space ≤ t₂.to_topological_space := by refl, rw h_le, refl, end } end ring_topology section absolute_value /-- Construct an absolute value on a semiring `T` from an absolute value on a semiring `R` and an injective ring homomorphism `f : T →+* R` -/ def absolute_value.comp {R S T : Type*} [semiring T] [semiring R] [ordered_semiring S] (v : absolute_value R S) {f : T →+* R} (hf : function.injective f) : absolute_value T S := { to_fun := v ∘ f, map_mul' := by simp only [function.comp_app, map_mul, eq_self_iff_true, forall_const], nonneg' := by simp only [v.nonneg, forall_const], eq_zero' := by simp only [map_eq_zero_iff f hf, v.eq_zero, forall_const, iff_self], add_le' := by simp only [function.comp_app, map_add, v.add_le, forall_const], } end absolute_value
9c350c800208e5295b0dd6802c05beaaa361a17d
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Lean/Compiler/IR/Borrow.lean
3dd885c60bdc484b7405cb924da3877589c28f56
[ "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
11,003
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.Compiler.ExportAttr import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.NormIds namespace Lean namespace IR namespace Borrow namespace OwnedSet abbrev Key := FunId × Index def beq : Key → Key → Bool | (f₁, x₁), (f₂, x₂) => f₁ == f₂ && x₁ == x₂ instance : BEq Key := ⟨beq⟩ def getHash : Key → USize | (f, x) => mixHash (hash f) (hash x) instance : Hashable Key := ⟨getHash⟩ end OwnedSet open OwnedSet (Key) in abbrev OwnedSet := Std.HashMap Key Unit def OwnedSet.insert (s : OwnedSet) (k : OwnedSet.Key) : OwnedSet := Std.HashMap.insert s k () def OwnedSet.contains (s : OwnedSet) (k : OwnedSet.Key) : Bool := Std.HashMap.contains s k /- We perform borrow inference in a block of mutually recursive functions. Join points are viewed as local functions, and are identified using their local id + the name of the surrounding function. We keep a mapping from function and joint points to parameters (`Array Param`). Recall that `Param` contains the field `borrow`. -/ namespace ParamMap inductive Key where | decl (name : FunId) | jp (name : FunId) (jpid : JoinPointId) deriving BEq def getHash : Key → USize | Key.decl n => hash n | Key.jp n id => mixHash (hash n) (hash id) instance : Hashable Key := ⟨getHash⟩ end ParamMap open ParamMap (Key) abbrev ParamMap := Std.HashMap Key (Array Param) def ParamMap.fmt (map : ParamMap) : Format := let fmts := map.fold (fun fmt k ps => let k := match k with | ParamMap.Key.decl n => format n | ParamMap.Key.jp n id => format n ++ ":" ++ format id fmt ++ Format.line ++ k ++ " -> " ++ formatParams ps) Format.nil "{" ++ (Format.nest 1 fmts) ++ "}" instance : ToFormat ParamMap := ⟨ParamMap.fmt⟩ instance : ToString ParamMap := ⟨fun m => Format.pretty (format m)⟩ namespace InitParamMap /- Mark parameters that take a reference as borrow -/ def initBorrow (ps : Array Param) : Array Param := ps.map $ fun p => { p with borrow := p.ty.isObj } /- We do perform borrow inference for constants marked as `export`. Reason: we current write wrappers in C++ for using exported functions. These wrappers use smart pointers such as `object_ref`. When writing a new wrapper we need to know whether an argument is a borrow inference or not. We can revise this decision when we implement code for generating the wrappers automatically. -/ def initBorrowIfNotExported (exported : Bool) (ps : Array Param) : Array Param := if exported then ps else initBorrow ps partial def visitFnBody (fnid : FunId) : FnBody → StateM ParamMap Unit | FnBody.jdecl j xs v b => do modify fun m => m.insert (ParamMap.Key.jp fnid j) (initBorrow xs) visitFnBody fnid v visitFnBody fnid b | FnBody.case _ _ _ alts => alts.forM fun alt => visitFnBody fnid alt.body | e => do unless e.isTerminal do let (instr, b) := e.split visitFnBody fnid b def visitDecls (env : Environment) (decls : Array Decl) : StateM ParamMap Unit := decls.forM fun decl => match decl with | Decl.fdecl f xs _ b => do let exported := isExport env f modify fun m => m.insert (ParamMap.Key.decl f) (initBorrowIfNotExported exported xs) visitFnBody f b | _ => pure () end InitParamMap def mkInitParamMap (env : Environment) (decls : Array Decl) : ParamMap := (InitParamMap.visitDecls env decls *> get).run' {} /- Apply the inferred borrow annotations stored at `ParamMap` to a block of mutually recursive functions. -/ namespace ApplyParamMap partial def visitFnBody (fn : FunId) (paramMap : ParamMap) : FnBody → FnBody | FnBody.jdecl j xs v b => let v := visitFnBody fn paramMap v let b := visitFnBody fn paramMap b match paramMap.find? (ParamMap.Key.jp fn j) with | some ys => FnBody.jdecl j ys v b | none => unreachable! | FnBody.case tid x xType alts => FnBody.case tid x xType $ alts.map $ fun alt => alt.modifyBody (visitFnBody fn paramMap) | e => if e.isTerminal then e else let (instr, b) := e.split let b := visitFnBody fn paramMap b instr.setBody b def visitDecls (decls : Array Decl) (paramMap : ParamMap) : Array Decl := decls.map fun decl => match decl with | Decl.fdecl f xs ty b => let b := visitFnBody f paramMap b match paramMap.find? (ParamMap.Key.decl f) with | some xs => Decl.fdecl f xs ty b | none => unreachable! | other => other end ApplyParamMap def applyParamMap (decls : Array Decl) (map : ParamMap) : Array Decl := -- dbgTrace ("applyParamMap " ++ toString map) $ fun _ => ApplyParamMap.visitDecls decls map structure BorrowInfCtx where env : Environment currFn : FunId := arbitrary -- Function being analyzed. paramSet : IndexSet := {} -- Set of all function parameters in scope. This is used to implement the heuristic at `ownArgsUsingParams` structure BorrowInfState where /- Set of variables that must be `owned`. -/ owned : OwnedSet := {} modified : Bool := false paramMap : ParamMap abbrev M := ReaderT BorrowInfCtx (StateM BorrowInfState) def getCurrFn : M FunId := do let ctx ← read pure ctx.currFn def markModified : M Unit := modify fun s => { s with modified := true } def ownVar (x : VarId) : M Unit := do -- dbgTrace ("ownVar " ++ toString x) $ fun _ => let currFn ← getCurrFn modify fun s => if s.owned.contains (currFn, x.idx) then s else { s with owned := s.owned.insert (currFn, x.idx), modified := true } def ownArg (x : Arg) : M Unit := match x with | Arg.var x => ownVar x | _ => pure () def ownArgs (xs : Array Arg) : M Unit := xs.forM ownArg def isOwned (x : VarId) : M Bool := do let currFn ← getCurrFn let s ← get pure $ s.owned.contains (currFn, x.idx) /- Updates `map[k]` using the current set of `owned` variables. -/ def updateParamMap (k : ParamMap.Key) : M Unit := do let currFn ← getCurrFn let s ← get match s.paramMap.find? k with | some ps => do let ps ← ps.mapM fun (p : Param) => do if !p.borrow then pure p else if (← isOwned p.x) then markModified pure { p with borrow := false } else pure p modify fun s => { s with paramMap := s.paramMap.insert k ps } | none => pure () def getParamInfo (k : ParamMap.Key) : M (Array Param) := do let s ← get match s.paramMap.find? k with | some ps => pure ps | none => match k with | ParamMap.Key.decl fn => do let ctx ← read match findEnvDecl ctx.env fn with | some decl => pure decl.params | none => unreachable! | _ => unreachable! /- For each ps[i], if ps[i] is owned, then mark xs[i] as owned. -/ def ownArgsUsingParams (xs : Array Arg) (ps : Array Param) : M Unit := xs.size.forM fun i => do let x := xs[i] let p := ps[i] unless p.borrow do ownArg x /- For each xs[i], if xs[i] is owned, then mark ps[i] as owned. We use this action to preserve tail calls. That is, if we have a tail call `f xs`, if the i-th parameter is borrowed, but `xs[i]` is owned we would have to insert a `dec xs[i]` after `f xs` and consequently "break" the tail call. -/ def ownParamsUsingArgs (xs : Array Arg) (ps : Array Param) : M Unit := xs.size.forM fun i => do let x := xs[i] let p := ps[i] match x with | Arg.var x => if (← isOwned x) then ownVar p.x | _ => pure () /- Mark `xs[i]` as owned if it is one of the parameters `ps`. We use this action to mark function parameters that are being "packed" inside constructors. This is a heuristic, and is not related with the effectiveness of the reset/reuse optimization. It is useful for code such as ``` def f (x y : obj) := let z := ctor_1 x y; ret z ``` -/ def ownArgsIfParam (xs : Array Arg) : M Unit := do let ctx ← read xs.forM fun x => do match x with | Arg.var x => if ctx.paramSet.contains x.idx then ownVar x | _ => pure () def collectExpr (z : VarId) : Expr → M Unit | Expr.reset _ x => ownVar z *> ownVar x | Expr.reuse x _ _ ys => ownVar z *> ownVar x *> ownArgsIfParam ys | Expr.ctor _ xs => ownVar z *> ownArgsIfParam xs | Expr.proj _ x => do if (← isOwned x) then ownVar z if (← isOwned z) then ownVar x | Expr.fap g xs => do let ps ← getParamInfo (ParamMap.Key.decl g) ownVar z *> ownArgsUsingParams xs ps | Expr.ap x ys => ownVar z *> ownVar x *> ownArgs ys | Expr.pap _ xs => ownVar z *> ownArgs xs | other => pure () def preserveTailCall (x : VarId) (v : Expr) (b : FnBody) : M Unit := do let ctx ← read match v, b with | (Expr.fap g ys), (FnBody.ret (Arg.var z)) => if ctx.currFn == g && x == z then -- dbgTrace ("preserveTailCall " ++ toString b) $ fun _ => do let ps ← getParamInfo (ParamMap.Key.decl g) ownParamsUsingArgs ys ps | _, _ => pure () def updateParamSet (ctx : BorrowInfCtx) (ps : Array Param) : BorrowInfCtx := { ctx with paramSet := ps.foldl (fun s p => s.insert p.x.idx) ctx.paramSet } partial def collectFnBody : FnBody → M Unit | FnBody.jdecl j ys v b => do withReader (fun ctx => updateParamSet ctx ys) (collectFnBody v) let ctx ← read updateParamMap (ParamMap.Key.jp ctx.currFn j) collectFnBody b | FnBody.vdecl x _ v b => collectFnBody b *> collectExpr x v *> preserveTailCall x v b | FnBody.jmp j ys => do let ctx ← read let ps ← getParamInfo (ParamMap.Key.jp ctx.currFn j) ownArgsUsingParams ys ps -- for making sure the join point can reuse ownParamsUsingArgs ys ps -- for making sure the tail call is preserved | FnBody.case _ _ _ alts => alts.forM fun alt => collectFnBody alt.body | e => do unless e.isTerminal do collectFnBody e.body partial def collectDecl : Decl → M Unit | Decl.fdecl f ys _ b => withReader (fun ctx => let ctx := updateParamSet ctx ys; { ctx with currFn := f }) do collectFnBody b updateParamMap (ParamMap.Key.decl f) | _ => pure () /- Keep executing `x` until it reaches a fixpoint -/ @[inline] partial def whileModifing (x : M Unit) : M Unit := do modify fun s => { s with modified := false } x let s ← get if s.modified then whileModifing x else pure () def collectDecls (decls : Array Decl) : M ParamMap := do whileModifing (decls.forM collectDecl) let s ← get pure s.paramMap def infer (env : Environment) (decls : Array Decl) : ParamMap := collectDecls decls { env := env } |>.run' { paramMap := mkInitParamMap env decls } end Borrow def inferBorrow (decls : Array Decl) : CompilerM (Array Decl) := do let env ← getEnv let paramMap := Borrow.infer env decls pure (Borrow.applyParamMap decls paramMap) end IR end Lean
4807109e41927a27e900021532d84c55a618b550
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Util/SCC.lean
63d89ca771b9ff264ec898655c37cb89ab5f5b31
[ "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
3,141
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.Data.HashMap namespace Lean.SCC /-! Very simple implementation of Tarjan's SCC algorithm. Performance is not a goal here since we use this module to compiler mutually recursive definitions, where each function (and nested let-rec) in the mutual block is a vertex. So, the graphs are small. -/ section variable (α : Type) [BEq α] [Hashable α] structure Data where index? : Option Nat := none lowlink? : Option Nat := none onStack : Bool := false structure State where stack : List α := [] nextIndex : Nat := 0 data : HashMap α Data := {} sccs : List (List α) := [] abbrev M := StateM (State α) end variable {α : Type} [BEq α] [Hashable α] private def getDataOf (a : α) : M α Data := do let s ← get match s.data.find? a with | some d => pure d | none => pure {} private def push (a : α) : M α Unit := modify fun s => { s with stack := a :: s.stack, nextIndex := s.nextIndex + 1, data := s.data.insert a { index? := s.nextIndex, lowlink? := s.nextIndex, onStack := true } } private def modifyDataOf (a : α) (f : Data → Data) : M α Unit := modify fun s => { s with data := match s.data.find? a with | none => s.data | some d => s.data.insert a (f d) } private def resetOnStack (a : α) : M α Unit := modifyDataOf a fun d => { d with onStack := false } private def updateLowLinkOf (a : α) (v : Option Nat) : M α Unit := modifyDataOf a fun d => { d with lowlink? := match d.lowlink?, v with | i, none => i | none, i => i | some i, some j => if i < j then i else j } private def addSCC (a : α) : M α Unit := do let rec add | [], newSCC => modify fun s => { s with stack := [], sccs := newSCC :: s.sccs } | b::bs, newSCC => do resetOnStack b; let newSCC := b::newSCC; if a != b then add bs newSCC else modify fun s => { s with stack := bs, sccs := newSCC :: s.sccs } add (← get).stack [] private partial def sccAux (successorsOf : α → List α) (a : α) : M α Unit := do push a (successorsOf a).forM fun b => do let bData ← getDataOf b; if bData.index?.isNone then -- `b` has not been visited yet sccAux successorsOf b; let bData ← getDataOf b; updateLowLinkOf a bData.lowlink? else if bData.onStack then do -- `b` is on the stack. So, it must be in the current SCC -- The edge `(a, b)` is pointing to an SCC already found and must be ignored updateLowLinkOf a bData.index? else pure () let aData ← getDataOf a; if aData.lowlink? == aData.index? then addSCC a def scc (vertices : List α) (successorsOf : α → List α) : List (List α) := let main : M α Unit := vertices.forM fun a => do let aData ← getDataOf a if aData.index?.isNone then sccAux successorsOf a let (_, s) := main.run {} s.sccs.reverse end Lean.SCC
d91677d443f0298a9e4813842e2d63ecf05af689
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/linear_algebra/matrix.lean
7ae4c6150919bb13bb32e56a08956fde6608dc3f
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,727
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Patrick Massot, Casper Putz -/ import linear_algebra.finite_dimensional import linear_algebra.nonsingular_inverse import linear_algebra.multilinear import linear_algebra.dual /-! # Linear maps and matrices This file defines the maps to send matrices to a linear map, and to send linear maps between modules with a finite bases to matrices. This defines a linear equivalence between linear maps between finite-dimensional vector spaces and matrices indexed by the respective bases. It also defines the trace of an endomorphism, and the determinant of a family of vectors with respect to some basis. Some results are proved about the linear map corresponding to a diagonal matrix (`range`, `ker` and `rank`). Some results are proved for determinants of block triangular matrices. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `linear_map.to_matrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`, the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `matrix κ ι R` * `matrix.to_lin`: the inverse of `linear_map.to_matrix` * `linear_map.to_matrix'`: the `R`-linear equivalence from `(n → R) →ₗ[R] (m → R)` to `matrix n m R` (with the standard basis on `n → R` and `m → R`) * `matrix.to_lin'`: the inverse of `linear_map.to_matrix'` * `alg_equiv_matrix`: given a basis indexed by `n`, the `R`-algebra equivalence between `R`-endomorphisms of `M` and `matrix n n R` * `matrix.trace`: the trace of a square matrix * `linear_map.trace`: the trace of an endomorphism * `is_basis.to_matrix`: the matrix whose columns are a given family of vectors in a given basis * `is_basis.to_matrix_equiv`: given a basis, the linear equivalence between families of vectors and matrices arising from `is_basis.to_matrix` * `is_basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map ## Tags linear_map, matrix, linear_equiv, diagonal, det, trace -/ noncomputable theory open linear_map matrix set submodule open_locale big_operators open_locale matrix universes u v w section to_matrix' variables {R : Type*} [comm_ring R] variables {l m n : Type*} [fintype l] [fintype m] [fintype n] instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) := by unfold matrix; apply_instance /-- `matrix.mul_vec M` is a linear map. -/ def matrix.mul_vec_lin (M : matrix m n R) : (n → R) →ₗ[R] (m → R) := { to_fun := M.mul_vec, map_add' := λ v w, funext (λ i, dot_product_add _ _ _), map_smul' := λ c v, funext (λ i, dot_product_smul _ _ _) } @[simp] lemma matrix.mul_vec_lin_apply (M : matrix m n R) (v : n → R) : matrix.mul_vec_lin M v = M.mul_vec v := rfl variables [decidable_eq n] @[simp] lemma matrix.mul_vec_std_basis (M : matrix m n R) (i j) : M.mul_vec (std_basis R (λ _, R) j 1) i = M i j := begin have : (∑ j', M i j' * if j = j' then 1 else 0) = M i j, { simp_rw [mul_boole, finset.sum_ite_eq, finset.mem_univ, if_true] }, convert this, ext, split_ifs with h; simp only [std_basis_apply], { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h), pi.zero_apply] } end /-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `matrix m n R`. -/ def linear_map.to_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R := { to_fun := λ f i j, f (std_basis R (λ _, R) j 1) i, inv_fun := matrix.mul_vec_lin, right_inv := λ M, by { ext i j, simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply] }, left_inv := λ f, begin apply (pi.is_basis_fun R n).ext, intro j, ext i, simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply] end, map_add' := λ f g, by { ext i j, simp only [pi.add_apply, linear_map.add_apply] }, map_smul' := λ c f, by { ext i j, simp only [pi.smul_apply, linear_map.smul_apply] } } /-- A `matrix m n R` is linearly equivalent to a linear map `(n → R) →ₗ[R] (m → R)`. -/ def matrix.to_lin' : matrix m n R ≃ₗ[R] ((n → R) →ₗ[R] (m → R)) := linear_map.to_matrix'.symm @[simp] lemma linear_map.to_matrix'_symm : (linear_map.to_matrix'.symm : matrix m n R ≃ₗ[R] _) = matrix.to_lin' := rfl @[simp] lemma matrix.to_lin'_symm : (matrix.to_lin'.symm : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] _) = linear_map.to_matrix' := rfl @[simp] lemma linear_map.to_matrix'_to_lin' (M : matrix m n R) : linear_map.to_matrix' (matrix.to_lin' M) = M := linear_map.to_matrix'.apply_symm_apply M @[simp] lemma matrix.to_lin'_to_matrix' (f : (n → R) →ₗ[R] (m → R)) : matrix.to_lin' (linear_map.to_matrix' f) = f := matrix.to_lin'.apply_symm_apply f @[simp] lemma linear_map.to_matrix'_apply (f : (n → R) →ₗ[R] (m → R)) (i j) : linear_map.to_matrix' f i j = f (λ j', if j' = j then 1 else 0) i := begin simp only [linear_map.to_matrix', linear_equiv.coe_mk], congr, ext j', split_ifs with h, { rw [h, std_basis_same] }, apply std_basis_ne _ _ _ _ h end @[simp] lemma matrix.to_lin'_apply (M : matrix m n R) (v : n → R) : matrix.to_lin' M v = M.mul_vec v := rfl @[simp] lemma matrix.to_lin'_one : matrix.to_lin' (1 : matrix n n R) = id := by { ext, simp [linear_map.one_apply, std_basis_apply] } @[simp] lemma linear_map.to_matrix'_id : (linear_map.to_matrix' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 := by { ext, rw [matrix.one_apply, linear_map.to_matrix'_apply, id_apply] } @[simp] lemma matrix.to_lin'_mul [decidable_eq m] (M : matrix l m R) (N : matrix m n R) : matrix.to_lin' (M ⬝ N) = (matrix.to_lin' M).comp (matrix.to_lin' N) := by { ext, simp } lemma linear_map.to_matrix'_comp [decidable_eq l] (f : (n → R) →ₗ[R] (m → R)) (g : (l → R) →ₗ[R] (n → R)) : (f.comp g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' := suffices (f.comp g) = (f.to_matrix' ⬝ g.to_matrix').to_lin', by rw [this, linear_map.to_matrix'_to_lin'], by rw [matrix.to_lin'_mul, matrix.to_lin'_to_matrix', matrix.to_lin'_to_matrix'] lemma linear_map.to_matrix'_mul [decidable_eq m] (f g : (m → R) →ₗ[R] (m → R)) : (f * g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' := linear_map.to_matrix'_comp f g /-- Linear maps `(n → R) →ₗ[R] (n → R)` are algebra equivalent to `matrix n n R`. -/ def linear_map.to_matrix_alg_equiv' : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] matrix n n R := alg_equiv.of_linear_equiv linear_map.to_matrix' linear_map.to_matrix'_mul (by simp [module.algebra_map_End_eq_smul_id]) /-- A `matrix n n R` is algebra equivalent to a linear map `(n → R) →ₗ[R] (n → R)`. -/ def matrix.to_lin_alg_equiv' : matrix n n R ≃ₐ[R] ((n → R) →ₗ[R] (n → R)) := linear_map.to_matrix_alg_equiv'.symm @[simp] lemma linear_map.to_matrix_alg_equiv'_symm : (linear_map.to_matrix_alg_equiv'.symm : matrix n n R ≃ₐ[R] _) = matrix.to_lin_alg_equiv' := rfl @[simp] lemma matrix.to_lin_alg_equiv'_symm : (matrix.to_lin_alg_equiv'.symm : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] _) = linear_map.to_matrix_alg_equiv' := rfl @[simp] lemma linear_map.to_matrix_alg_equiv'_to_lin_alg_equiv' (M : matrix n n R) : linear_map.to_matrix_alg_equiv' (matrix.to_lin_alg_equiv' M) = M := linear_map.to_matrix_alg_equiv'.apply_symm_apply M @[simp] lemma matrix.to_lin_alg_equiv'_to_matrix_alg_equiv' (f : (n → R) →ₗ[R] (n → R)) : matrix.to_lin_alg_equiv' (linear_map.to_matrix_alg_equiv' f) = f := matrix.to_lin_alg_equiv'.apply_symm_apply f @[simp] lemma linear_map.to_matrix_alg_equiv'_apply (f : (n → R) →ₗ[R] (n → R)) (i j) : linear_map.to_matrix_alg_equiv' f i j = f (λ j', if j' = j then 1 else 0) i := by simp [linear_map.to_matrix_alg_equiv'] @[simp] lemma matrix.to_lin_alg_equiv'_apply (M : matrix n n R) (v : n → R) : matrix.to_lin_alg_equiv' M v = M.mul_vec v := rfl @[simp] lemma matrix.to_lin_alg_equiv'_one : matrix.to_lin_alg_equiv' (1 : matrix n n R) = id := by { ext, simp [matrix.one_apply, std_basis_apply] } @[simp] lemma linear_map.to_matrix_alg_equiv'_id : (linear_map.to_matrix_alg_equiv' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 := by { ext, rw [matrix.one_apply, linear_map.to_matrix_alg_equiv'_apply, id_apply] } @[simp] lemma matrix.to_lin_alg_equiv'_mul (M N : matrix n n R) : matrix.to_lin_alg_equiv' (M ⬝ N) = (matrix.to_lin_alg_equiv' M).comp (matrix.to_lin_alg_equiv' N) := by { ext, simp } lemma linear_map.to_matrix_alg_equiv'_comp (f g : (n → R) →ₗ[R] (n → R)) : (f.comp g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' := suffices (f.comp g) = (f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv').to_lin_alg_equiv', by rw [this, linear_map.to_matrix_alg_equiv'_to_lin_alg_equiv'], by rw [matrix.to_lin_alg_equiv'_mul, matrix.to_lin_alg_equiv'_to_matrix_alg_equiv', matrix.to_lin_alg_equiv'_to_matrix_alg_equiv'] lemma linear_map.to_matrix_alg_equiv'_mul (f g : (n → R) →ₗ[R] (n → R)) : (f * g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' := linear_map.to_matrix_alg_equiv'_comp f g end to_matrix' section to_matrix variables {R : Type*} [comm_ring R] variables {l m n : Type*} [fintype l] [fintype m] [fintype n] [decidable_eq n] variables {M₁ M₂ : Type*} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] variables {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between linear maps `M₁ →ₗ M₂` and matrices over `R` indexed by the bases. -/ def linear_map.to_matrix : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix m n R := linear_equiv.trans (linear_equiv.arrow_congr hv₁.equiv_fun hv₂.equiv_fun) linear_map.to_matrix' /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between matrices over `R` indexed by the bases and linear maps `M₁ →ₗ M₂`. -/ def matrix.to_lin : matrix m n R ≃ₗ[R] (M₁ →ₗ[R] M₂) := (linear_map.to_matrix hv₁ hv₂).symm @[simp] lemma linear_map.to_matrix_symm : (linear_map.to_matrix hv₁ hv₂).symm = matrix.to_lin hv₁ hv₂ := rfl @[simp] lemma matrix.to_lin_symm : (matrix.to_lin hv₁ hv₂).symm = linear_map.to_matrix hv₁ hv₂ := rfl @[simp] lemma matrix.to_lin_to_matrix (f : M₁ →ₗ[R] M₂) : matrix.to_lin hv₁ hv₂ (linear_map.to_matrix hv₁ hv₂ f) = f := by rw [← matrix.to_lin_symm, linear_equiv.apply_symm_apply] @[simp] lemma linear_map.to_matrix_to_lin (M : matrix m n R) : linear_map.to_matrix hv₁ hv₂ (matrix.to_lin hv₁ hv₂ M) = M := by rw [← matrix.to_lin_symm, linear_equiv.symm_apply_apply] lemma linear_map.to_matrix_apply (f : M₁ →ₗ[R] M₂) (i : m) (j : n) : linear_map.to_matrix hv₁ hv₂ f i j = hv₂.equiv_fun (f (v₁ j)) i := begin rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_map.to_matrix'_apply, linear_equiv.arrow_congr_apply, is_basis.equiv_fun_symm_apply, finset.sum_eq_single j, if_pos rfl, one_smul], { intros j' _ hj', rw [if_neg hj', zero_smul] }, { intro hj, have := finset.mem_univ j, contradiction } end lemma linear_map.to_matrix_transpose_apply (f : M₁ →ₗ[R] M₂) (j : n) : (linear_map.to_matrix hv₁ hv₂ f)ᵀ j = hv₂.equiv_fun (f (v₁ j)) := funext $ λ i, f.to_matrix_apply _ _ i j lemma linear_map.to_matrix_apply' (f : M₁ →ₗ[R] M₂) (i : m) (j : n) : linear_map.to_matrix hv₁ hv₂ f i j = hv₂.repr (f (v₁ j)) i := linear_map.to_matrix_apply hv₁ hv₂ f i j lemma linear_map.to_matrix_transpose_apply' (f : M₁ →ₗ[R] M₂) (j : n) : (linear_map.to_matrix hv₁ hv₂ f)ᵀ j = hv₂.repr (f (v₁ j)) := linear_map.to_matrix_transpose_apply hv₁ hv₂ f j lemma matrix.to_lin_apply (M : matrix m n R) (v : M₁) : matrix.to_lin hv₁ hv₂ M v = ∑ j, M.mul_vec (hv₁.equiv_fun v) j • v₂ j := show hv₂.equiv_fun.symm (matrix.to_lin' M (hv₁.equiv_fun v)) = _, by rw [matrix.to_lin'_apply, hv₂.equiv_fun_symm_apply] @[simp] lemma matrix.to_lin_self (M : matrix m n R) (i : n) : matrix.to_lin hv₁ hv₂ M (v₁ i) = ∑ j, M j i • v₂ j := by simp only [matrix.to_lin_apply, matrix.mul_vec, dot_product, hv₁.equiv_fun_self, mul_boole, finset.sum_ite_eq, finset.mem_univ, if_true] /-- This will be a special case of `linear_map.to_matrix_id_eq_basis_to_matrix`. -/ lemma linear_map.to_matrix_id : linear_map.to_matrix hv₁ hv₁ id = 1 := begin ext i j, simp [linear_map.to_matrix_apply, is_basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm] end @[simp] lemma matrix.to_lin_one : matrix.to_lin hv₁ hv₁ 1 = id := by rw [← linear_map.to_matrix_id hv₁, matrix.to_lin_to_matrix] theorem linear_map.to_matrix_range [decidable_eq M₁] [decidable_eq M₂] (f : M₁ →ₗ[R] M₂) (k : m) (i : n) : linear_map.to_matrix hv₁.range hv₂.range f ⟨v₂ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ = linear_map.to_matrix hv₁ hv₂ f k i := by simp_rw [linear_map.to_matrix_apply, subtype.coe_mk, is_basis.equiv_fun_apply, hv₂.range_repr] variables {M₃ : Type*} [add_comm_group M₃] [module R M₃] {v₃ : l → M₃} (hv₃ : is_basis R v₃) lemma linear_map.to_matrix_comp [decidable_eq m] (f : M₂ →ₗ[R] M₃) (g : M₁ →ₗ[R] M₂) : linear_map.to_matrix hv₁ hv₃ (f.comp g) = linear_map.to_matrix hv₂ hv₃ f ⬝ linear_map.to_matrix hv₁ hv₂ g := by simp_rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_equiv.arrow_congr_comp _ hv₂.equiv_fun, linear_map.to_matrix'_comp] lemma linear_map.to_matrix_mul (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix hv₁ hv₁ (f * g) = linear_map.to_matrix hv₁ hv₁ f ⬝ linear_map.to_matrix hv₁ hv₁ g := by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl, linear_map.to_matrix_comp hv₁ hv₁ hv₁ f g] } lemma matrix.to_lin_mul [decidable_eq m] (A : matrix l m R) (B : matrix m n R) : matrix.to_lin hv₁ hv₃ (A ⬝ B) = (matrix.to_lin hv₂ hv₃ A).comp (matrix.to_lin hv₁ hv₂ B) := begin apply (linear_map.to_matrix hv₁ hv₃).injective, haveI : decidable_eq l := λ _ _, classical.prop_decidable _, rw linear_map.to_matrix_comp hv₁ hv₂ hv₃, repeat { rw linear_map.to_matrix_to_lin }, end /-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra equivalence between linear maps `M₁ →ₗ M₁` and square matrices over `R` indexed by the basis. -/ def linear_map.to_matrix_alg_equiv : (M₁ →ₗ[R] M₁) ≃ₐ[R] matrix n n R := alg_equiv.of_linear_equiv (linear_map.to_matrix hv₁ hv₁) (linear_map.to_matrix_mul hv₁) (by simp [module.algebra_map_End_eq_smul_id, linear_map.to_matrix_id]) /-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra equivalence between square matrices over `R` indexed by the basis and linear maps `M₁ →ₗ M₁`. -/ def matrix.to_lin_alg_equiv : matrix n n R ≃ₐ[R] (M₁ →ₗ[R] M₁) := (linear_map.to_matrix_alg_equiv hv₁).symm @[simp] lemma linear_map.to_matrix_alg_equiv_symm : (linear_map.to_matrix_alg_equiv hv₁).symm = matrix.to_lin_alg_equiv hv₁ := rfl @[simp] lemma matrix.to_lin_alg_equiv_symm : (matrix.to_lin_alg_equiv hv₁).symm = linear_map.to_matrix_alg_equiv hv₁ := rfl @[simp] lemma matrix.to_lin_alg_equiv_to_matrix_alg_equiv (f : M₁ →ₗ[R] M₁) : matrix.to_lin_alg_equiv hv₁ (linear_map.to_matrix_alg_equiv hv₁ f) = f := by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.apply_symm_apply] @[simp] lemma linear_map.to_matrix_alg_equiv_to_lin_alg_equiv (M : matrix n n R) : linear_map.to_matrix_alg_equiv hv₁ (matrix.to_lin_alg_equiv hv₁ M) = M := by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.symm_apply_apply] lemma linear_map.to_matrix_alg_equiv_apply (f : M₁ →ₗ[R] M₁) (i j : n) : linear_map.to_matrix_alg_equiv hv₁ f i j = hv₁.equiv_fun (f (v₁ j)) i := by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_apply] lemma linear_map.to_matrix_alg_equiv_transpose_apply (f : M₁ →ₗ[R] M₁) (j : n) : (linear_map.to_matrix_alg_equiv hv₁ f)ᵀ j = hv₁.equiv_fun (f (v₁ j)) := funext $ λ i, f.to_matrix_apply _ _ i j lemma linear_map.to_matrix_alg_equiv_apply' (f : M₁ →ₗ[R] M₁) (i j : n) : linear_map.to_matrix_alg_equiv hv₁ f i j = hv₁.repr (f (v₁ j)) i := linear_map.to_matrix_alg_equiv_apply hv₁ f i j lemma linear_map.to_matrix_alg_equiv_transpose_apply' (f : M₁ →ₗ[R] M₁) (j : n) : (linear_map.to_matrix_alg_equiv hv₁ f)ᵀ j = hv₁.repr (f (v₁ j)) := linear_map.to_matrix_alg_equiv_transpose_apply hv₁ f j lemma matrix.to_lin_alg_equiv_apply (M : matrix n n R) (v : M₁) : matrix.to_lin_alg_equiv hv₁ M v = ∑ j, M.mul_vec (hv₁.equiv_fun v) j • v₁ j := show hv₁.equiv_fun.symm (matrix.to_lin_alg_equiv' M (hv₁.equiv_fun v)) = _, by rw [matrix.to_lin_alg_equiv'_apply, hv₁.equiv_fun_symm_apply] @[simp] lemma matrix.to_lin_alg_equiv_self (M : matrix n n R) (i : n) : matrix.to_lin_alg_equiv hv₁ M (v₁ i) = ∑ j, M j i • v₁ j := by simp only [matrix.to_lin_alg_equiv_apply, matrix.mul_vec, dot_product, hv₁.equiv_fun_self, mul_boole, finset.sum_ite_eq, finset.mem_univ, if_true] lemma linear_map.to_matrix_alg_equiv_id : linear_map.to_matrix_alg_equiv hv₁ id = 1 := by simp_rw [linear_map.to_matrix_alg_equiv, alg_equiv.of_linear_equiv_apply, linear_map.to_matrix_id] @[simp] lemma matrix.to_lin_alg_equiv_one : matrix.to_lin_alg_equiv hv₁ 1 = id := by rw [← linear_map.to_matrix_alg_equiv_id hv₁, matrix.to_lin_alg_equiv_to_matrix_alg_equiv] theorem linear_map.to_matrix_alg_equiv_range [decidable_eq M₁] (f : M₁ →ₗ[R] M₁) (k i : n) : linear_map.to_matrix_alg_equiv hv₁.range f ⟨v₁ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ = linear_map.to_matrix_alg_equiv hv₁ f k i := by simp_rw [linear_map.to_matrix_alg_equiv_apply, subtype.coe_mk, is_basis.equiv_fun_apply, hv₁.range_repr] lemma linear_map.to_matrix_alg_equiv_comp (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix_alg_equiv hv₁ (f.comp g) = linear_map.to_matrix_alg_equiv hv₁ f ⬝ linear_map.to_matrix_alg_equiv hv₁ g := by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_comp hv₁ hv₁ hv₁ f g] lemma linear_map.to_matrix_alg_equiv_mul (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix_alg_equiv hv₁ (f * g) = linear_map.to_matrix_alg_equiv hv₁ f ⬝ linear_map.to_matrix_alg_equiv hv₁ g := by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl, linear_map.to_matrix_alg_equiv_comp hv₁ f g] } lemma matrix.to_lin_alg_equiv_mul (A B : matrix n n R) : matrix.to_lin_alg_equiv hv₁ (A ⬝ B) = (matrix.to_lin_alg_equiv hv₁ A).comp (matrix.to_lin_alg_equiv hv₁ B) := by convert matrix.to_lin_mul hv₁ hv₁ hv₁ A B end to_matrix section is_basis_to_matrix variables {ι ι' κ κ' : Type*} [fintype ι] [fintype ι'] [fintype κ] [fintype κ'] variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] open function matrix /-- From a basis `e : ι → M` and a family of vectors `v : ι' → M`, make the matrix whose columns are the vectors `v i` written in the basis `e`. -/ def is_basis.to_matrix {e : ι → M} (he : is_basis R e) (v : ι' → M) : matrix ι ι' R := λ i j, he.equiv_fun (v j) i variables {e : ι → M} (he : is_basis R e) (v : ι' → M) (i : ι) (j : ι') namespace is_basis lemma to_matrix_apply : he.to_matrix v i j = he.equiv_fun (v j) i := rfl lemma to_matrix_transpose_apply : (he.to_matrix v)ᵀ j = he.repr (v j) := funext $ (λ _, rfl) lemma to_matrix_eq_to_matrix_constr [decidable_eq ι] (v : ι → M) : he.to_matrix v = linear_map.to_matrix he he (he.constr v) := by { ext, simp [is_basis.to_matrix_apply, linear_map.to_matrix_apply] } @[simp] lemma to_matrix_self [decidable_eq ι] : he.to_matrix e = 1 := begin rw is_basis.to_matrix, ext i j, simp [is_basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm] end lemma to_matrix_update [decidable_eq ι'] (x : M) : he.to_matrix (function.update v j x) = matrix.update_column (he.to_matrix v) j (he.repr x) := begin ext i' k, rw [is_basis.to_matrix, matrix.update_column_apply, he.to_matrix_apply], split_ifs, { rw [h, update_same j x v, he.equiv_fun_apply] }, { rw update_noteq h }, end @[simp] lemma sum_to_matrix_smul_self : ∑ (i : ι), he.to_matrix v i j • e i = v j := begin conv_rhs { rw ← he.total_repr (v j) }, rw [finsupp.total_apply, finsupp.sum_fintype], { refl }, simp end @[simp] lemma to_lin_to_matrix [decidable_eq ι'] (hv : is_basis R v) : matrix.to_lin hv he (he.to_matrix v) = id := hv.ext (λ i, by rw [to_lin_self, id_apply, he.sum_to_matrix_smul_self]) /-- From a basis `e : ι → M`, build a linear equivalence between families of vectors `v : ι → M`, and matrices, making the matrix whose columns are the vectors `v i` written in the basis `e`. -/ def to_matrix_equiv {e : ι → M} (he : is_basis R e) : (ι → M) ≃ₗ[R] matrix ι ι R := { to_fun := he.to_matrix, map_add' := λ v w, begin ext i j, change _ = _ + _, simp [he.to_matrix_apply] end, map_smul' := begin intros c v, ext i j, simp [he.to_matrix_apply] end, inv_fun := λ m j, ∑ i, (m i j) • e i, left_inv := begin intro v, ext j, simp [he.to_matrix_apply, he.equiv_fun_total (v j)] end, right_inv := begin intros x, ext k l, simp [he.to_matrix_apply, he.equiv_fun.map_sum, he.equiv_fun.map_smul, fintype.sum_apply k (λ i, x i l • he.equiv_fun (e i)), he.equiv_fun_self] end } end is_basis section mul_linear_map_to_matrix variables {N : Type*} [add_comm_group N] [module R N] variables {b : ι → M} {b' : ι' → M} {c : κ → N} {c' : κ' → N} variables (hb : is_basis R b) (hb' : is_basis R b') (hc : is_basis R c) (hc' : is_basis R c') variables (f : M →ₗ[R] N) open linear_map @[simp] lemma is_basis_to_matrix_mul_linear_map_to_matrix [decidable_eq ι'] : hc.to_matrix c' ⬝ linear_map.to_matrix hb' hc' f = linear_map.to_matrix hb' hc f := (matrix.to_lin hb' hc).injective (by haveI := classical.dec_eq κ'; rw [to_lin_to_matrix, to_lin_mul hb' hc' hc, to_lin_to_matrix, hc.to_lin_to_matrix, id_comp]) @[simp] lemma linear_map_to_matrix_mul_is_basis_to_matrix [decidable_eq ι] [decidable_eq ι'] : linear_map.to_matrix hb' hc' f ⬝ hb'.to_matrix b = linear_map.to_matrix hb hc' f := (matrix.to_lin hb hc').injective (by rw [to_lin_to_matrix, to_lin_mul hb hb' hc', to_lin_to_matrix, hb'.to_lin_to_matrix, comp_id]) /-- A generalization of `linear_map.to_matrix_id`. -/ @[simp] lemma linear_map.to_matrix_id_eq_basis_to_matrix [decidable_eq ι] : linear_map.to_matrix hb hb' id = hb'.to_matrix b := by { haveI := classical.dec_eq ι', rw [← is_basis_to_matrix_mul_linear_map_to_matrix hb hb', to_matrix_id, matrix.mul_one] } /-- A generalization of `is_basis.to_matrix_self`, in the opposite direction. -/ @[simp] lemma is_basis.to_matrix_mul_to_matrix {ι'' : Type*} [fintype ι''] {b'' : ι'' → M} (hb'' : is_basis R b'') : hb.to_matrix b' ⬝ hb'.to_matrix b'' = hb.to_matrix b'' := begin haveI := classical.dec_eq ι, haveI := classical.dec_eq ι', haveI := classical.dec_eq ι'', rw [← linear_map.to_matrix_id_eq_basis_to_matrix hb' hb, ← linear_map.to_matrix_id_eq_basis_to_matrix hb'' hb', ← to_matrix_comp, id_comp, linear_map.to_matrix_id_eq_basis_to_matrix], end end mul_linear_map_to_matrix end is_basis_to_matrix open_locale matrix section det open linear_map matrix variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {M' : Type*} [add_comm_group M'] [module R M'] variables {ι : Type*} [decidable_eq ι] [fintype ι] {v : ι → M} {v' : ι → M'} lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (hv : is_basis R v) (hv' : is_basis R v') : is_unit (linear_map.to_matrix hv hv' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_map.to_matrix_comp hv hv' hv f.symm f).symm end /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {hv : is_basis R v} {hv' : is_basis R v'} (h : is_unit (linear_map.to_matrix hv hv' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := to_lin hv' hv (to_matrix hv hv' f)⁻¹, left_inv := λ x, calc to_lin hv' hv (to_matrix hv hv' f)⁻¹ (f x) = to_lin hv hv ((to_matrix hv hv' f)⁻¹ ⬝ to_matrix hv hv' f) x : by { rw [to_lin_mul hv hv' hv, to_lin_to_matrix, linear_map.comp_apply] } ... = x : by simp [h], right_inv := λ x, calc f (to_lin hv' hv (to_matrix hv hv' f)⁻¹ x) = to_lin hv' hv' (to_matrix hv hv' f ⬝ (to_matrix hv hv' f)⁻¹) x : by { rw [to_lin_mul hv' hv hv', linear_map.comp_apply, to_lin_to_matrix hv hv'] } ... = x : by simp [h], } variables {e : ι → M} (he : is_basis R e) /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def is_basis.det : alternating_map R M R ι := { to_fun := λ v, det (he.to_matrix v), map_add' := begin intros v i x y, simp only [he.to_matrix_update, linear_map.map_add], apply det_update_column_add end, map_smul' := begin intros u i c x, simp only [he.to_matrix_update, algebra.id.smul_eq_mul, map_smul_of_tower], apply det_update_column_smul end, map_eq_zero_of_eq' := begin intros v i j h hij, rw [←function.update_eq_self i v, h, ←det_transpose, he.to_matrix_update, ←update_row_transpose, ←he.to_matrix_transpose_apply], apply det_zero_of_row_eq hij, rw [update_row_ne hij.symm, update_row_self], end } lemma is_basis.det_apply (v : ι → M) : he.det v = det (he.to_matrix v) := rfl lemma is_basis.det_self : he.det e = 1 := by simp [he.det_apply] lemma is_basis.iff_det {v : ι → M} : is_basis R v ↔ is_unit (he.det v) := begin split, { intro hv, suffices : is_unit (linear_map.to_matrix he he (linear_equiv_of_is_basis he hv $ equiv.refl ι)).det, { rw [is_basis.det_apply, is_basis.to_matrix_eq_to_matrix_constr], exact this }, apply linear_equiv.is_unit_det }, { intro h, rw [is_basis.det_apply, is_basis.to_matrix_eq_to_matrix_constr] at h, convert linear_equiv.is_basis he (linear_equiv.of_is_unit_det h), ext i, exact (constr_basis he).symm }, end end det section transpose variables {K V₁ V₂ ι₁ ι₂ : Type*} [field K] [add_comm_group V₁] [vector_space K V₁] [add_comm_group V₂] [vector_space K V₂] [fintype ι₁] [fintype ι₂] [decidable_eq ι₁] [decidable_eq ι₂] {B₁ : ι₁ → V₁} (h₁ : is_basis K B₁) {B₂ : ι₂ → V₂} (h₂ : is_basis K B₂) @[simp] lemma linear_map.to_matrix_transpose (u : V₁ →ₗ[K] V₂) : linear_map.to_matrix h₂.dual_basis_is_basis h₁.dual_basis_is_basis (module.dual.transpose u) = (linear_map.to_matrix h₁ h₂ u)ᵀ := begin ext i j, simp only [linear_map.to_matrix_apply, module.dual.transpose_apply, h₁.dual_basis_equiv_fun, h₂.dual_basis_apply, matrix.transpose_apply, linear_map.comp_apply] end lemma linear_map.to_matrix_symm_transpose (M : matrix ι₁ ι₂ K) : (linear_map.to_matrix h₁.dual_basis_is_basis h₂.dual_basis_is_basis).symm Mᵀ = module.dual.transpose (matrix.to_lin h₂ h₁ M) := begin apply (linear_map.to_matrix h₁.dual_basis_is_basis h₂.dual_basis_is_basis).injective, rw [linear_equiv.apply_symm_apply], ext i j, simp only [linear_map.to_matrix_apply, module.dual.transpose_apply, h₂.dual_basis_equiv_fun, h₁.dual_basis_apply, matrix.transpose_apply, linear_map.comp_apply, if_true, matrix.to_lin_apply, linear_equiv.map_smul, mul_boole, algebra.id.smul_eq_mul, linear_equiv.map_sum, is_basis.equiv_fun_self, fintype.sum_apply, finset.sum_ite_eq', finset.sum_ite_eq, is_basis.equiv_fun_symm_apply, pi.smul_apply, matrix.to_lin_apply, matrix.mul_vec, matrix.dot_product, is_basis.equiv_fun_self, finset.mem_univ] end end transpose namespace matrix section trace variables {m : Type*} [fintype m] (n : Type*) [fintype n] variables (R : Type v) (M : Type w) [semiring R] [add_comm_monoid M] [semimodule R M] /-- The diagonal of a square matrix. -/ def diag : (matrix n n M) →ₗ[R] n → M := { to_fun := λ A i, A i i, map_add' := by { intros, ext, refl, }, map_smul' := by { intros, ext, refl, } } variables {n} {R} {M} @[simp] lemma diag_apply (A : matrix n n M) (i : n) : diag n R M A i = A i i := rfl @[simp] lemma diag_one [decidable_eq n] : diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_apply_eq] } @[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl variables (n) (R) (M) /-- The trace of a square matrix. -/ def trace : (matrix n n M) →ₗ[R] M := { to_fun := λ A, ∑ i, diag n R M A i, map_add' := by { intros, apply finset.sum_add_distrib, }, map_smul' := by { intros, simp [finset.smul_sum], } } variables {n} {R} {M} @[simp] lemma trace_diag (A : matrix n n M) : trace n R M A = ∑ i, diag n R M A i := rfl @[simp] lemma trace_one [decidable_eq n] : trace n R R 1 = fintype.card n := have h : trace n R R 1 = ∑ i, diag n R R 1 i := rfl, by simp_rw [h, diag_one, finset.sum_const, nsmul_one]; refl @[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl @[simp] lemma trace_transpose_mul (A : matrix m n R) (B : matrix n m R) : trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm lemma trace_mul_comm {S : Type v} [comm_ring S] (A : matrix m n S) (B : matrix n m S) : trace n S S (B ⬝ A) = trace m S S (A ⬝ B) := by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul] end trace section ring variables {n : Type*} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R] open linear_map matrix lemma proj_diagonal (i : n) (w : n → R) : (proj i).comp (to_lin' (diagonal w)) = (w i) • proj i := by ext j; simp [mul_vec_diagonal] lemma diagonal_comp_std_basis (w : n → R) (i : n) : (diagonal w).to_lin'.comp (std_basis R (λ_:n, R) i) = (w i) • std_basis R (λ_:n, R) i := begin ext j, simp_rw [linear_map.comp_apply, to_lin'_apply, mul_vec_diagonal, linear_map.smul_apply, pi.smul_apply, algebra.id.smul_eq_mul], by_cases i = j, { subst h }, { rw [std_basis_ne R (λ_:n, R) _ _ (ne.symm h), _root_.mul_zero, _root_.mul_zero] } end lemma diagonal_to_lin' (w : n → R) : (diagonal w).to_lin' = linear_map.pi (λi, w i • linear_map.proj i) := by ext v j; simp [mul_vec_diagonal] /-- An invertible matrix yields a linear equivalence from the free module to itself. -/ def to_linear_equiv (P : matrix n n R) (h : is_unit P) : (n → R) ≃ₗ[R] (n → R) := have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h, { inv_fun := P⁻¹.to_lin', left_inv := λ v, show (P⁻¹.to_lin'.comp P.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.nonsing_inv_mul h', matrix.to_lin'_one, linear_map.id_apply], right_inv := λ v, show (P.to_lin'.comp P⁻¹.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.mul_nonsing_inv h', matrix.to_lin'_one, linear_map.id_apply], ..P.to_lin' } @[simp] lemma to_linear_equiv_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv h) : module.End R (n → R)) = P.to_lin' := rfl @[simp] lemma to_linear_equiv_symm_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv h).symm : module.End R (n → R)) = P⁻¹.to_lin' := rfl end ring section vector_space variables {m n : Type*} [fintype m] [fintype n] variables {K : Type u} [field K] -- maybe try to relax the universe constraint open linear_map matrix lemma rank_vec_mul_vec {m n : Type u} [fintype m] [fintype n] [decidable_eq n] (w : m → K) (v : n → K) : rank (vec_mul_vec w v).to_lin' ≤ 1 := begin rw [vec_mul_vec_eq, to_lin'_mul], refine le_trans (rank_comp_le1 _ _) _, refine le_trans (rank_le_domain _) _, rw [dim_fun', ← cardinal.lift_eq_nat_iff.mpr (cardinal.fintype_card unit), cardinal.mk_unit], exact le_of_eq (cardinal.lift_one) end lemma ker_diagonal_to_lin' [decidable_eq m] (w : m → K) : ker (diagonal w).to_lin' = (⨆i∈{i | w i = 0 }, range (std_basis K (λi, K) i)) := begin rw [← comap_bot, ← infi_ker_proj], simp only [comap_infi, (ker_comp _ _).symm, proj_diagonal, ker_smul'], have : univ ⊆ {i : m | w i = 0} ∪ {i : m | w i = 0}ᶜ, { rw set.union_compl_self }, exact (supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) disjoint_compl_right this (finite.of_fintype _)).symm end lemma range_diagonal [decidable_eq m] (w : m → K) : (diagonal w).to_lin'.range = (⨆ i ∈ {i | w i ≠ 0}, (std_basis K (λi, K) i).range) := begin dsimp only [mem_set_of_eq], rw [← map_top, ← supr_range_std_basis, map_supr], congr, funext i, rw [← linear_map.range_comp, diagonal_comp_std_basis, ← range_smul'] end lemma rank_diagonal [decidable_eq m] [decidable_eq K] (w : m → K) : rank (diagonal w).to_lin' = fintype.card { i // w i ≠ 0 } := begin have hu : univ ⊆ {i : m | w i = 0}ᶜ ∪ {i : m | w i = 0}, { rw set.compl_union_self }, have hd : disjoint {i : m | w i ≠ 0} {i : m | w i = 0} := disjoint_compl_left, have h₁ := supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) hd hu (finite.of_fintype _), have h₂ := @infi_ker_proj_equiv K _ _ (λi:m, K) _ _ _ _ (by simp; apply_instance) hd hu, rw [rank, range_diagonal, h₁, ←@dim_fun' K], apply linear_equiv.dim_eq, apply h₂, end end vector_space section finite_dimensional variables {m n : Type*} [fintype m] [fintype n] variables {R : Type v} [field R] instance : finite_dimensional R (matrix m n R) := linear_equiv.finite_dimensional (linear_equiv.uncurry R m n).symm /-- The dimension of the space of finite dimensional matrices is the product of the number of rows and columns. -/ @[simp] lemma findim_matrix : finite_dimensional.findim R (matrix m n R) = fintype.card m * fintype.card n := by rw [@linear_equiv.findim_eq R (matrix m n R) _ _ _ _ _ _ (linear_equiv.uncurry R m n), finite_dimensional.findim_fintype_fun_eq_card, fintype.card_prod] end finite_dimensional section reindexing variables {l m n : Type*} [fintype l] [fintype m] [fintype n] variables {l' m' n' : Type*} [fintype l'] [fintype m'] [fintype n'] variables {R : Type v} /-- The natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence. -/ def reindex (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n R ≃ matrix m' n' R := { to_fun := λ M i j, M (eₘ.symm i) (eₙ.symm j), inv_fun := λ M i j, M (eₘ i) (eₙ j), left_inv := λ M, by simp, right_inv := λ M, by simp, } @[simp] lemma reindex_apply (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : reindex eₘ eₙ M = λ i j, M (eₘ.symm i) (eₙ.symm j) := rfl @[simp] lemma reindex_symm_apply (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) : (reindex eₘ eₙ).symm M = λ i j, M (eₘ i) (eₙ j) := rfl @[simp] lemma reindex_refl_refl (A : matrix m n R) : (reindex (equiv.refl _) (equiv.refl _) A) = A := by { ext, simp only [reindex_apply, equiv.refl_symm, equiv.refl_apply] } /-- The natural map that reindexes a matrix's rows and columns with equivalent types is a linear equivalence. -/ def reindex_linear_equiv [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n R ≃ₗ[R] matrix m' n' R := { map_add' := λ M N, rfl, map_smul' := λ M N, rfl, ..(reindex eₘ eₙ)} @[simp] lemma coe_reindex_linear_equiv [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : reindex_linear_equiv eₘ eₙ M = λ i j, M (eₘ.symm i) (eₙ.symm j) := rfl lemma reindex_linear_equiv_apply [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) (i j) : reindex_linear_equiv eₘ eₙ M i j = M (eₘ.symm i) (eₙ.symm j) := rfl @[simp] lemma coe_reindex_linear_equiv_symm [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) : (reindex_linear_equiv eₘ eₙ).symm M = λ i j, M (eₘ i) (eₙ j) := rfl lemma reindex_linear_equiv_symm_apply [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) (i j) : (reindex_linear_equiv eₘ eₙ).symm M i j = M (eₘ i) (eₙ j) := rfl @[simp] lemma reindex_linear_equiv_refl_refl [semiring R] (A : matrix m n R) : (reindex_linear_equiv (equiv.refl _) (equiv.refl _) A) = A := reindex_refl_refl A lemma reindex_mul [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (eₗ : l ≃ l') (M : matrix m n R) (N : matrix n l R) : (reindex_linear_equiv eₘ eₙ M) ⬝ (reindex_linear_equiv eₙ eₗ N) = reindex_linear_equiv eₘ eₗ (M ⬝ N) := begin ext i j, dsimp only [matrix.mul, matrix.dot_product], rw [←finset.univ_map_equiv_to_embedding eₙ, finset.sum_map finset.univ eₙ.to_embedding], simp, end /-- For square matrices, the natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence of algebras. -/ def reindex_alg_equiv [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) : matrix m m R ≃ₐ[R] matrix n n R := { map_mul' := λ M N, by simp only [reindex_mul, linear_equiv.to_fun_eq_coe, mul_eq_mul], commutes' := λ r, by { ext, simp [algebra_map, algebra.to_ring_hom], by_cases h : i = j; simp [h], }, ..(reindex_linear_equiv e e) } @[simp] lemma coe_reindex_alg_equiv [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) (M : matrix m m R) : reindex_alg_equiv e M = λ i j, M (e.symm i) (e.symm j) := rfl @[simp] lemma reindex_alg_equiv_apply [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) (M : matrix m m R) (i j) : reindex_alg_equiv e M i j = M (e.symm i) (e.symm j) := rfl @[simp] lemma coe_reindex_alg_equiv_symm [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) (M : matrix n n R) : (reindex_alg_equiv e).symm M = λ i j, M (e i) (e j) := rfl @[simp] lemma reindex_alg_equiv_symm_apply [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) (M : matrix n n R) (i j): (reindex_alg_equiv e).symm M i j = M (e i) (e j) := rfl @[simp] lemma reindex_alg_equiv_refl [comm_semiring R] [decidable_eq m] (A : matrix m m R) : (reindex_alg_equiv (equiv.refl m) A) = A := reindex_linear_equiv_refl_refl A lemma reindex_transpose (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : (reindex eₘ eₙ M)ᵀ = (reindex eₙ eₘ Mᵀ) := rfl /-- `simp` version of `det_reindex_self` `det_reindex_self` is not a good simp lemma because `reindex_apply` fires before. So we have this lemma to continue from there. -/ @[simp] lemma det_reindex_self' [decidable_eq m] [decidable_eq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (λ i j, A (e.symm i) (e.symm j)) = det A := begin rw [det_apply', det_apply'], apply finset.sum_bij' (λ σ _, equiv.perm_congr e.symm σ) _ _ (λ σ _, equiv.perm_congr e σ), { intros σ _, ext, simp only [equiv.symm_symm, equiv.perm_congr_apply, equiv.apply_symm_apply] }, { intros σ _, ext, simp only [equiv.symm_symm, equiv.perm_congr_apply, equiv.symm_apply_apply] }, { intros σ _, apply finset.mem_univ }, { intros σ _, apply finset.mem_univ }, intros σ _, simp_rw [equiv.perm_congr_apply, equiv.symm_symm], congr, { convert (equiv.perm.sign_perm_congr e.symm σ).symm }, apply finset.prod_bij' (λ i _, e.symm i) _ _ (λ i _, e i), { intros, simp_rw equiv.apply_symm_apply }, { intros, simp_rw equiv.symm_apply_apply }, { intros, apply finset.mem_univ }, { intros, apply finset.mem_univ }, { intros, simp_rw equiv.apply_symm_apply }, end /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ lemma det_reindex_self [decidable_eq m] [decidable_eq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A := det_reindex_self' e A /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ lemma det_reindex_linear_equiv_self [decidable_eq m] [decidable_eq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (reindex_linear_equiv e e A) = det A := det_reindex_self' e A /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ lemma det_reindex_alg_equiv [decidable_eq m] [decidable_eq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (reindex_alg_equiv e A) = det A := det_reindex_self' e A end reindexing end matrix namespace linear_map open_locale matrix /-- The trace of an endomorphism given a basis. -/ def trace_aux (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) : (M →ₗ[R] M) →ₗ[R] R := (matrix.trace ι R R).comp $ linear_map.to_matrix hb hb @[simp] lemma trace_aux_def (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) (f : M →ₗ[R] M) : trace_aux R hb f = matrix.trace ι R R (linear_map.to_matrix hb hb f) := rfl theorem trace_aux_eq' (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) {κ : Type w} [decidable_eq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) : trace_aux R hb = trace_aux R hc := linear_map.ext $ λ f, calc matrix.trace ι R R (linear_map.to_matrix hb hb f) = matrix.trace ι R R (linear_map.to_matrix hb hb ((linear_map.id.comp f).comp linear_map.id)) : by rw [linear_map.id_comp, linear_map.comp_id] ... = matrix.trace ι R R (linear_map.to_matrix hc hb linear_map.id ⬝ linear_map.to_matrix hc hc f ⬝ linear_map.to_matrix hb hc linear_map.id) : by rw [linear_map.to_matrix_comp _ hc, linear_map.to_matrix_comp _ hc] ... = matrix.trace κ R R (linear_map.to_matrix hc hc f ⬝ linear_map.to_matrix hb hc linear_map.id ⬝ linear_map.to_matrix hc hb linear_map.id) : by rw [matrix.mul_assoc, matrix.trace_mul_comm] ... = matrix.trace κ R R (linear_map.to_matrix hc hc ((f.comp linear_map.id).comp linear_map.id)) : by rw [linear_map.to_matrix_comp _ hb, linear_map.to_matrix_comp _ hc] ... = matrix.trace κ R R (linear_map.to_matrix hc hc f) : by rw [linear_map.comp_id, linear_map.comp_id] open_locale classical theorem trace_aux_range (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) : trace_aux R hb.range = trace_aux R hb := linear_map.ext $ λ f, if H : 0 = 1 then eq_of_zero_eq_one H _ _ else begin haveI : nontrivial R := ⟨⟨0, 1, H⟩⟩, change ∑ i : set.range b, _ = ∑ i : ι, _, simp_rw [matrix.diag_apply], symmetry, convert (equiv.of_injective _ hb.injective).sum_comp _, ext i, exact (linear_map.to_matrix_range hb hb f i i).symm end /-- where `ι` and `κ` can reside in different universes -/ theorem trace_aux_eq (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type*} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) {κ : Type*} [decidable_eq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) : trace_aux R hb = trace_aux R hc := calc trace_aux R hb = trace_aux R hb.range : by rw trace_aux_range R hb ... = trace_aux R hc.range : trace_aux_eq' _ _ _ ... = trace_aux R hc : by rw trace_aux_range R hc /-- Trace of an endomorphism independent of basis. -/ def trace (R : Type u) [comm_ring R] (M : Type v) [add_comm_group M] [module R M] : (M →ₗ[R] M) →ₗ[R] R := if H : ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M) then trace_aux R (classical.some_spec H) else 0 theorem trace_eq_matrix_trace (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [fintype ι] [decidable_eq ι] {b : ι → M} (hb : is_basis R b) (f : M →ₗ[R] M) : trace R M f = matrix.trace ι R R (linear_map.to_matrix hb hb f) := have ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M), from ⟨finset.univ.image b, by { rw [finset.coe_image, finset.coe_univ, set.image_univ], exact hb.range }⟩, by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq } theorem trace_mul_comm (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] (f g : M →ₗ[R] M) : trace R M (f * g) = trace R M (g * f) := if H : ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M) then let ⟨s, hb⟩ := H in by { simp_rw [trace_eq_matrix_trace R hb, linear_map.to_matrix_mul], apply matrix.trace_mul_comm } else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply] section finite_dimensional variables {K : Type*} [field K] variables {V : Type*} [add_comm_group V] [vector_space K V] [finite_dimensional K V] variables {W : Type*} [add_comm_group W] [vector_space K W] [finite_dimensional K W] instance : finite_dimensional K (V →ₗ[K] W) := begin classical, cases finite_dimensional.exists_is_basis_finset K V with bV hbV, cases finite_dimensional.exists_is_basis_finset K W with bW hbW, apply linear_equiv.finite_dimensional (linear_map.to_matrix hbV hbW).symm, end /-- The dimension of the space of linear transformations is the product of the dimensions of the domain and codomain. -/ @[simp] lemma findim_linear_map : finite_dimensional.findim K (V →ₗ[K] W) = (finite_dimensional.findim K V) * (finite_dimensional.findim K W) := begin classical, cases finite_dimensional.exists_is_basis_finset K V with bV hbV, cases finite_dimensional.exists_is_basis_finset K W with bW hbW, rw [linear_equiv.findim_eq (linear_map.to_matrix hbV hbW), matrix.findim_matrix, finite_dimensional.findim_eq_card_basis hbV, finite_dimensional.findim_eq_card_basis hbW, mul_comm], end end finite_dimensional end linear_map /-- The natural equivalence between linear endomorphisms of finite free modules and square matrices is compatible with the algebra structures. -/ def alg_equiv_matrix' {R : Type v} [comm_ring R] {n : Type*} [fintype n] [decidable_eq n] : module.End R (n → R) ≃ₐ[R] matrix n n R := { map_mul' := linear_map.to_matrix'_comp, map_add' := linear_map.to_matrix'.map_add, commutes' := λ r, by { change (r • (linear_map.id : module.End R _)).to_matrix' = r • 1, rw ←linear_map.to_matrix'_id, refl, }, ..linear_map.to_matrix' } /-- A linear equivalence of two modules induces an equivalence of algebras of their endomorphisms. -/ def linear_equiv.alg_conj {R : Type v} [comm_ring R] {M₁ M₂ : Type*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] (e : M₁ ≃ₗ[R] M₂) : module.End R M₁ ≃ₐ[R] module.End R M₂ := { map_mul' := λ f g, by apply e.arrow_congr_comp, map_add' := e.conj.map_add, commutes' := λ r, by { change e.conj (r • linear_map.id) = r • linear_map.id, rw [linear_equiv.map_smul, linear_equiv.conj_id], }, ..e.conj } /-- A basis of a module induces an equivalence of algebras from the endomorphisms of the module to square matrices. -/ def alg_equiv_matrix {R : Type v} {M : Type w} {n : Type*} [fintype n] [comm_ring R] [add_comm_group M] [module R M] [decidable_eq n] {b : n → M} (h : is_basis R b) : module.End R M ≃ₐ[R] matrix n n R := h.equiv_fun.alg_conj.trans alg_equiv_matrix' section variables {R : Type v} [semiring R] {n : Type w} [fintype n] @[simp] lemma matrix.dot_product_std_basis_eq_mul [decidable_eq n] (v : n → R) (c : R) (i : n) : matrix.dot_product v (linear_map.std_basis R (λ _, R) i c) = v i * c := begin rw [matrix.dot_product, finset.sum_eq_single i, linear_map.std_basis_same], exact λ _ _ hb, by rw [linear_map.std_basis_ne _ _ _ _ hb, mul_zero], exact λ hi, false.elim (hi $ finset.mem_univ _) end @[simp] lemma matrix.dot_product_std_basis_one [decidable_eq n] (v : n → R) (i : n) : matrix.dot_product v (linear_map.std_basis R (λ _, R) i 1) = v i := by rw [matrix.dot_product_std_basis_eq_mul, mul_one] lemma matrix.dot_product_eq (v w : n → R) (h : ∀ u, matrix.dot_product v u = matrix.dot_product w u) : v = w := begin funext x, classical, rw [← matrix.dot_product_std_basis_one v x, ← matrix.dot_product_std_basis_one w x, h], end lemma matrix.dot_product_eq_iff {v w : n → R} : (∀ u, matrix.dot_product v u = matrix.dot_product w u) ↔ v = w := ⟨λ h, matrix.dot_product_eq v w h, λ h _, h ▸ rfl⟩ lemma matrix.dot_product_eq_zero (v : n → R) (h : ∀ w, matrix.dot_product v w = 0) : v = 0 := matrix.dot_product_eq _ _ $ λ u, (h u).symm ▸ (zero_dot_product u).symm lemma matrix.dot_product_eq_zero_iff {v : n → R} : (∀ w, matrix.dot_product v w = 0) ↔ v = 0 := ⟨λ h, matrix.dot_product_eq_zero v h, λ h w, h.symm ▸ zero_dot_product w⟩ end namespace matrix variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m] variables {R : Type v} [comm_ring R] lemma det_to_block (M : matrix m m R) (p : m → Prop) [decidable_pred p] : M.det = (matrix.from_blocks (to_block M p p) (to_block M p (λ j, ¬p j)) (to_block M (λ j, ¬p j) p) (to_block M (λ j, ¬p j) (λ j, ¬p j))).det := begin rw ← matrix.det_reindex_self (equiv.sum_compl p).symm M, rw [det_apply', det_apply'], congr, ext σ, congr, ext, generalize hy : σ x = y, cases x; cases y; simp only [matrix.reindex_apply, to_block_apply, equiv.symm_symm, equiv.sum_compl_apply_inr, equiv.sum_compl_apply_inl, from_blocks_apply₁₁, from_blocks_apply₁₂, from_blocks_apply₂₁, from_blocks_apply₂₂], end lemma det_to_square_block (M : matrix m m R) {n : nat} (b : m → fin n) (k : fin n) : (to_square_block M b k).det = (to_square_block_prop M (λ i, b i = k)).det := by simp lemma det_to_square_block' (M : matrix m m R) (b : m → ℕ) (k : ℕ) : (to_square_block' M b k).det = (to_square_block_prop M (λ i, b i = k)).det := by simp lemma two_block_triangular_det (M : matrix m m R) (p : m → Prop) [decidable_pred p] (h : ∀ i (h1 : ¬p i) j (h2 : p j), M i j = 0) : M.det = (to_square_block_prop M p).det * (to_square_block_prop M (λ i, ¬p i)).det := begin rw det_to_block M p, convert upper_two_block_triangular_det (to_block M p p) (to_block M p (λ j, ¬p j)) (to_block M (λ j, ¬p j) (λ j, ¬p j)), ext, exact h ↑i i.2 ↑j j.2 end lemma equiv_block_det (M : matrix m m R) {p q : m → Prop} [decidable_pred p] [decidable_pred q] (e : ∀x, q x ↔ p x) : (to_square_block_prop M p).det = (to_square_block_prop M q).det := by convert matrix.det_reindex_self (equiv.subtype_equiv_right e) (to_square_block_prop M q) lemma to_square_block_det'' (M : matrix m m R) {n : nat} (b : m → fin n) (k : fin n) : (to_square_block M b k).det = (to_square_block' M (λ i, ↑(b i)) ↑k).det := begin rw [to_square_block_def', to_square_block_def], apply equiv_block_det, intro x, apply (fin.ext_iff _ _).symm end /-- Let `b` map rows and columns of a square matrix `M` to `n` blocks. Then `block_triangular_matrix' M n b` says the matrix is block triangular. -/ def block_triangular_matrix' {o : Type*} [fintype o] (M : matrix o o R) {n : ℕ} (b : o → fin n) : Prop := ∀ i j, b j < b i → M i j = 0 lemma upper_two_block_triangular' {m n : Type*} [fintype m] [fintype n] (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : block_triangular_matrix' (from_blocks A B 0 D) (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) := begin intros k1 k2 hk12, have h0 : ∀ (k : m ⊕ n), sum.elim (λ i, (0 : fin 2)) (λ j, 1) k = 0 → ∃ i, k = sum.inl i, { simp }, have h1 : ∀ (k : m ⊕ n), sum.elim (λ i, (0 : fin 2)) (λ j, 1) k = 1 → ∃ j, k = sum.inr j, { simp }, set mk1 := (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) k1 with hmk1, set mk2 := (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) k2 with hmk2, fin_cases mk1; fin_cases mk2; rw [h, h_1] at hk12, { exact absurd hk12 (nat.not_lt_zero 0) }, { exact absurd hk12 (nat.not_lt_zero 1) }, { rw hmk1 at h, obtain ⟨i, hi⟩ := h1 k1 h, rw hmk2 at h_1, obtain ⟨j, hj⟩ := h0 k2 h_1, rw [hi, hj], simp }, { exact absurd hk12 (irrefl 1) } end /-- Let `b` map rows and columns of a square matrix `M` to blocks indexed by `ℕ`s. Then `block_triangular_matrix M n b` says the matrix is block triangular. -/ def block_triangular_matrix {o : Type*} [fintype o] (M : matrix o o R) (b : o → ℕ) : Prop := ∀ i j, b j < b i → M i j = 0 lemma upper_two_block_triangular {m n : Type*} [fintype m] [fintype n] (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : block_triangular_matrix (from_blocks A B 0 D) (sum.elim (λ i, 0) (λ j, 1)) := begin intros k1 k2 hk12, have h01 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 0 ∨ sum.elim (λ i, 0) (λ j, 1) k = 1, { simp }, have h0 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 0 → ∃ i, k = sum.inl i, { simp }, have h1 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 1 → ∃ j, k = sum.inr j, { simp }, cases (h01 k1) with hk1 hk1; cases (h01 k2) with hk2 hk2; rw [hk1, hk2] at hk12, { exact absurd hk12 (nat.not_lt_zero 0) }, { exact absurd hk12 (nat.not_lt_zero 1) }, { obtain ⟨i, hi⟩ := h1 k1 hk1, obtain ⟨j, hj⟩ := h0 k2 hk2, rw [hi, hj], simp }, { exact absurd hk12 (irrefl 1) } end lemma det_of_block_triangular_matrix (M : matrix m m R) (b : m → ℕ) (h : block_triangular_matrix M b) : ∀ (n : ℕ) (hn : ∀ i, b i < n), M.det = ∏ k in finset.range n, (to_square_block' M b k).det := begin intros n hn, tactic.unfreeze_local_instances, induction n with n hi generalizing m M b, { rw finset.prod_range_zero, apply det_eq_one_of_card_eq_zero, apply fintype.card_eq_zero_iff.mpr, intro i, exact nat.not_lt_zero (b i) (hn i) }, { rw finset.prod_range_succ, have h2 : (M.to_square_block_prop (λ (i : m), b i = n.succ)).det = (M.to_square_block' b n.succ).det, { dunfold to_square_block', dunfold to_square_block_prop, refl }, rw two_block_triangular_det M (λ i, ¬(b i = n)), { rw mul_comm, apply congr (congr_arg has_mul.mul _), { let m' := {a // ¬b a = n }, let b' := (λ (i : m'), b ↑i), have h' : block_triangular_matrix (M.to_square_block_prop (λ (i : m), ¬b i = n)) b', { intros i j, apply h ↑i ↑j }, have hni : ∀ (i : {a // ¬b a = n}), b' i < n, { exact λ i, (ne.le_iff_lt i.property).mp (nat.lt_succ_iff.mp (hn ↑i)) }, have h1 := hi (M.to_square_block_prop (λ (i : m), ¬b i = n)) b' h' hni, rw ←fin.prod_univ_eq_prod_range at h1 ⊢, convert h1, ext k, simp only [to_square_block_def', to_square_block_def], let he : {a // b' a = ↑k} ≃ {a // b a = ↑k}, { have hc : ∀ (i : m), (λ a, b a = ↑k) i → (λ a, ¬b a = n) i, { intros i hbi, rw hbi, exact ne_of_lt (fin.is_lt k) }, exact equiv.subtype_subtype_equiv_subtype hc }, exact matrix.det_reindex_self he (λ (i j : {a // b' a = ↑k}), M ↑i ↑j) }, { rw det_to_square_block' M b n, have hh : ∀ a, b a = n ↔ ¬(λ (i : m), ¬b i = n) a, { intro i, simp only [not_not] }, exact equiv_block_det M hh }}, { intros i hi j hj, apply (h i), simp only [not_not] at hi, rw hi, exact (ne.le_iff_lt hj).mp (nat.lt_succ_iff.mp (hn j)) }} end lemma det_of_block_triangular_matrix'' (M : matrix m m R) (b : m → ℕ) (h : block_triangular_matrix M b) : M.det = ∏ k in finset.image b finset.univ, (to_square_block' M b k).det := begin let n : ℕ := (Sup (finset.image b finset.univ : set ℕ)).succ, have hn : ∀ i, b i < n, { have hbi : ∀ i, b i ∈ finset.image b finset.univ, { simp }, intro i, dsimp only [n], apply nat.lt_succ_iff.mpr, exact le_cSup (finset.bdd_above _) (hbi i) }, rw det_of_block_triangular_matrix M b h n hn, refine (finset.prod_subset _ _).symm, { intros a ha, apply finset.mem_range.mpr, obtain ⟨i, ⟨hi, hbi⟩⟩ := finset.mem_image.mp ha, rw ←hbi, exact hn i }, { intros k hk hbk, apply det_eq_one_of_card_eq_zero, apply fintype.card_eq_zero_iff.mpr, simp only [subtype.forall], intros a hba, apply hbk, apply finset.mem_image.mpr, use a, exact ⟨finset.mem_univ a, hba⟩ } end lemma det_of_block_triangular_matrix' (M : matrix m m R) {n : ℕ} (b : m → fin n) (h : block_triangular_matrix' M b) : M.det = ∏ (k : fin n), (to_square_block M b k).det := begin let b2 : m → ℕ := λ i, ↑(b i), simp_rw to_square_block_det'', rw fin.prod_univ_eq_prod_range (λ (k : ℕ), (M.to_square_block' b2 k).det) n, apply det_of_block_triangular_matrix, { intros i j hij, exact h i j (fin.coe_fin_lt.mp hij) }, { intro i, exact fin.is_lt (b i) } end lemma det_of_upper_triangular {n : ℕ} (M : matrix (fin n) (fin n) R) (h : ∀ (i j : fin n), j < i → M i j = 0) : M.det = ∏ i : (fin n), M i i := begin convert det_of_block_triangular_matrix' M id h, ext i, have h2 : ∀ (j : {a // id a = i}), j = ⟨i, rfl⟩ := λ (j : {a // id a = i}), subtype.ext j.property, haveI : unique {a // id a = i} := ⟨⟨⟨i, rfl⟩⟩, h2⟩, simp [h2 (default {a // id a = i})] end lemma det_of_lower_triangular {n : ℕ} (M : matrix (fin n) (fin n) R) (h : ∀ (i j : fin n), i < j → M i j = 0) : M.det = ∏ i : (fin n), M i i := begin rw ← det_transpose, exact det_of_upper_triangular _ (λ (i j : fin n) (hji : j < i), h j i hji) end end matrix
829c58bb6ff890eb2a9671d39c3459d9bb5b5427
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0103/S0103.lean
7361dcf3a011eb06e2077814574ce2dfa8003252
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,165
lean
/- M1F 2017-18 Sheet 1 Question 2 to 4 solutions. Author : Kevin Buzzard This file should work with any version of lean -- whether you installed it yourself or are running the version on https://leanprover.github.io/live/latest/ -/ -- We probably need the "law of the excluded middle" for this question -- every -- proposition is either true or false! Don't even ask me to explain what the -- other options are, but Lean does not come with this axiom by default (blame -- the computer scientists) and mathematicians have to add it themselves. -- It's easy to add though. "em" for excluded middle. axiom em (X : Prop) : X ∨ ¬ X variables P Q R S : Prop -- A "Prop" is a proposition, that is, a true/false statement. -- Sheet 1 Q3. Prove one result and delete the other. -- theorem m1f_sheet01_q03_is_T (HP : P) (HnQ : ¬ Q) (HnR : ¬ R) (HS : S) : (R → S) → (P → Q) := theorem m1f_sheet01_q03_is_F (HP : P) (HnQ : ¬ Q) (HnR : ¬ R) (HS : S) : ¬ ((R → S) → (P → Q)) := begin intro H, have HRS : R → S, intro HR, contradiction, have HPQ : P → Q, exact H HRS, have HQ : Q, exact HPQ HP, -- now we have Q and not Q contradiction, end
ff260a15c42217ee3bfb6d23ed477855da8c28cd
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/introduction/unnamed_266.lean
a1cffc1fcb8bc1f1d33c4dca266d0a2c7dbd6962
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
143
lean
import data.nat.parity tactic open nat -- BEGIN example : ∀ m n : nat, even n → even (m * n) := by intros; simp * with parity_simps -- END
26dc9557d9b6cd1ae6afd9690f61f5776c2e7054
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/set_theory/ordinal_notation.lean
3adbb35589c0c1ae9d51d799e3dae1e10c6676c6
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
35,268
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import set_theory.ordinal_arithmetic /-! # Ordinal notations constructive ordinal arithmetic for ordinals `< ε₀`. -/ open ordinal open_locale ordinal -- get notation for `ω` /-- Recursive definition of an ordinal notation. `zero` denotes the ordinal 0, and `oadd e n a` is intended to refer to `ω^e * n + a`. For this to be valid Cantor normal form, we must have the exponents decrease to the right, but we can't state this condition until we've defined `repr`, so it is a separate definition `NF`. -/ @[derive decidable_eq] inductive onote : Type | zero : onote | oadd : onote → ℕ+ → onote → onote namespace onote /-- Notation for 0 -/ instance : has_zero onote := ⟨zero⟩ @[simp] theorem zero_def : zero = 0 := rfl instance : inhabited onote := ⟨0⟩ /-- Notation for 1 -/ instance : has_one onote := ⟨oadd 0 1 0⟩ /-- Notation for ω -/ def omega : onote := oadd 1 1 0 /-- The ordinal denoted by a notation -/ @[simp] noncomputable def repr : onote → ordinal.{0} | 0 := 0 | (oadd e n a) := ω ^ repr e * n + repr a /-- Auxiliary definition to print an ordinal notation -/ def to_string_aux1 (e : onote) (n : ℕ) (s : string) : string := if e = 0 then _root_.to_string n else (if e = 1 then "ω" else "ω^(" ++ s ++ ")") ++ if n = 1 then "" else "*" ++ _root_.to_string n /-- Print an ordinal notation -/ def to_string : onote → string | zero := "0" | (oadd e n 0) := to_string_aux1 e n (to_string e) | (oadd e n a) := to_string_aux1 e n (to_string e) ++ " + " ++ to_string a /-- Print an ordinal notation -/ def repr' : onote → string | zero := "0" | (oadd e n a) := "(oadd " ++ repr' e ++ " " ++ _root_.to_string (n:ℕ) ++ " " ++ repr' a ++ ")" instance : has_to_string onote := ⟨to_string⟩ instance : has_repr onote := ⟨repr'⟩ instance : preorder onote := { le := λ x y, repr x ≤ repr y, lt := λ x y, repr x < repr y, le_refl := λ a, @le_refl ordinal _ _, le_trans := λ a b c, @le_trans ordinal _ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ } theorem lt_def {x y : onote} : x < y ↔ repr x < repr y := iff.rfl theorem le_def {x y : onote} : x ≤ y ↔ repr x ≤ repr y := iff.rfl /-- Convert a `nat` into an ordinal -/ @[simp] def of_nat : ℕ → onote | 0 := 0 | (nat.succ n) := oadd 0 n.succ_pnat 0 @[simp] theorem of_nat_one : of_nat 1 = 1 := rfl @[simp] theorem repr_of_nat (n : ℕ) : repr (of_nat n) = n := by cases n; simp @[simp] theorem repr_one : repr 1 = 1 := by simpa using repr_of_nat 1 theorem omega_le_oadd (e n a) : ω ^ repr e ≤ repr (oadd e n a) := begin unfold repr, refine le_trans _ (le_add_right _ _), simpa using (mul_le_mul_iff_left $ power_pos (repr e) omega_pos).2 (nat_cast_le.2 n.2) end theorem oadd_pos (e n a) : 0 < oadd e n a := @lt_of_lt_of_le _ _ _ _ _ (power_pos _ omega_pos) (omega_le_oadd _ _ _) /-- Compare ordinal notations -/ def cmp : onote → onote → ordering | 0 0 := ordering.eq | _ 0 := ordering.gt | 0 _ := ordering.lt | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) := (cmp e₁ e₂).or_else $ (_root_.cmp (n₁:ℕ) n₂).or_else (cmp a₁ a₂) theorem eq_of_cmp_eq : ∀ {o₁ o₂}, cmp o₁ o₂ = ordering.eq → o₁ = o₂ | 0 0 h := rfl | (oadd e n a) 0 h := by injection h | 0 (oadd e n a) h := by injection h | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h := begin revert h, simp [cmp], cases h₁ : cmp e₁ e₂; intro h; try {cases h}, have := eq_of_cmp_eq h₁, subst e₂, revert h, cases h₂ : _root_.cmp (n₁:ℕ) n₂; intro h; try {cases h}, have := eq_of_cmp_eq h, subst a₂, rw [_root_.cmp, cmp_using_eq_eq] at h₂, have := subtype.eq (eq_of_incomp h₂), subst n₂, simp end theorem zero_lt_one : (0 : onote) < 1 := by rw [lt_def, repr, repr_one]; exact zero_lt_one /-- `NF_below o b` says that `o` is a normal form ordinal notation satisfying `repr o < ω ^ b`. -/ inductive NF_below : onote → ordinal.{0} → Prop | zero {b} : NF_below 0 b | oadd' {e n a eb b} : NF_below e eb → NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b /-- A normal form ordinal notation has the form ω ^ a₁ * n₁ + ω ^ a₂ * n₂ + ... ω ^ aₖ * nₖ where `a₁ > a₂ > ... > aₖ` and all the `aᵢ` are also in normal form. We will essentially only be interested in normal form ordinal notations, but to avoid complicating the algorithms we define everything over general ordinal notations and only prove correctness with normal form as an invariant. -/ @[class, pp_nodot] def NF (o : onote) := Exists (NF_below o) instance NF.zero : NF 0 := ⟨0, NF_below.zero⟩ theorem NF_below.oadd {e n a b} : NF e → NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b | ⟨eb, h⟩ := NF_below.oadd' h theorem NF_below.fst {e n a b} (h : NF_below (oadd e n a) b) : NF e := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact ⟨_, h₁⟩ theorem NF.fst {e n a} : NF (oadd e n a) → NF e | ⟨b, h⟩ := h.fst theorem NF_below.snd {e n a b} (h : NF_below (oadd e n a) b) : NF_below a (repr e) := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₂ theorem NF.snd' {e n a} : NF (oadd e n a) → NF_below a (repr e) | ⟨b, h⟩ := h.snd theorem NF.snd {e n a} (h : NF (oadd e n a)) : NF a := ⟨_, h.snd'⟩ theorem NF.oadd {e a} (h₁ : NF e) (n) (h₂ : NF_below a (repr e)) : NF (oadd e n a) := ⟨_, NF_below.oadd h₁ h₂ (ordinal.lt_succ_self _)⟩ instance NF.oadd_zero (e n) [h : NF e] : NF (oadd e n 0) := h.oadd _ NF_below.zero theorem NF_below.lt {e n a b} (h : NF_below (oadd e n a) b) : repr e < b := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₃ theorem NF_below_zero : ∀ {o}, NF_below o 0 ↔ o = 0 | 0 := ⟨λ _, rfl, λ _, NF_below.zero⟩ | (oadd e n a) := ⟨λ h, (not_le_of_lt h.lt).elim (ordinal.zero_le _), λ e, e.symm ▸ NF_below.zero⟩ theorem NF.zero_of_zero {e n a} (h : NF (oadd e n a)) (e0 : e = 0) : a = 0 := by simpa [e0, NF_below_zero] using h.snd' theorem NF_below.repr_lt {o b} (h : NF_below o b) : repr o < ω ^ b := begin induction h with _ e n a eb b h₁ h₂ h₃ _ IH, { exact power_pos _ omega_pos }, { rw repr, refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 IH) _, rw ← mul_succ, refine le_trans (mul_le_mul_left _ $ ordinal.succ_le.2 $ nat_lt_omega _) _, rw ← power_succ, exact power_le_power_right omega_pos (ordinal.succ_le.2 h₃) } end theorem NF_below.mono {o b₁ b₂} (bb : b₁ ≤ b₂) (h : NF_below o b₁) : NF_below o b₂ := begin induction h with _ e n a eb b h₁ h₂ h₃ _ IH; constructor, exacts [h₁, h₂, lt_of_lt_of_le h₃ bb] end theorem NF.below_of_lt {e n a b} (H : repr e < b) : NF (oadd e n a) → NF_below (oadd e n a) b | ⟨b', h⟩ := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact NF_below.oadd' h₁ h₂ H theorem NF.below_of_lt' : ∀ {o b}, repr o < ω ^ b → NF o → NF_below o b | 0 b H _ := NF_below.zero | (oadd e n a) b H h := h.below_of_lt $ (power_lt_power_iff_right one_lt_omega).1 $ (lt_of_le_of_lt (omega_le_oadd _ _ _) H) theorem NF_below_of_nat : ∀ n, NF_below (of_nat n) 1 | 0 := NF_below.zero | (nat.succ n) := NF_below.oadd NF.zero NF_below.zero ordinal.zero_lt_one instance NF_of_nat (n) : NF (of_nat n) := ⟨_, NF_below_of_nat n⟩ instance NF_one : NF 1 := by rw ← of_nat_one; apply_instance theorem oadd_lt_oadd_1 {e₁ n₁ o₁ e₂ n₂ o₂} (h₁ : NF (oadd e₁ n₁ o₁)) (h : e₁ < e₂) : oadd e₁ n₁ o₁ < oadd e₂ n₂ o₂ := @lt_of_lt_of_le _ _ _ _ _ ((h₁.below_of_lt h).repr_lt) (omega_le_oadd _ _ _) theorem oadd_lt_oadd_2 {e o₁ o₂ : onote} {n₁ n₂ : ℕ+} (h₁ : NF (oadd e n₁ o₁)) (h : (n₁:ℕ) < n₂) : oadd e n₁ o₁ < oadd e n₂ o₂ := begin simp [lt_def], refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 h₁.snd'.repr_lt) (le_trans _ (le_add_right _ _)), rwa [← mul_succ, mul_le_mul_iff_left (power_pos _ omega_pos), ordinal.succ_le, nat_cast_lt] end theorem oadd_lt_oadd_3 {e n a₁ a₂} (h : a₁ < a₂) : oadd e n a₁ < oadd e n a₂ := begin rw lt_def, unfold repr, exact (ordinal.add_lt_add_iff_left _).2 h end theorem cmp_compares : ∀ (a b : onote) [NF a] [NF b], (cmp a b).compares a b | 0 0 h₁ h₂ := rfl | (oadd e n a) 0 h₁ h₂ := oadd_pos _ _ _ | 0 (oadd e n a) h₁ h₂ := oadd_pos _ _ _ | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h₁ h₂ := begin rw cmp, have IHe := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂, case ordering.lt { exact oadd_lt_oadd_1 h₁ IHe }, case ordering.gt { exact oadd_lt_oadd_1 h₂ IHe }, change e₁ = e₂ at IHe, subst IHe, unfold _root_.cmp, cases nh : cmp_using (<) (n₁:ℕ) n₂, case ordering.lt { rw cmp_using_eq_lt at nh, exact oadd_lt_oadd_2 h₁ nh }, case ordering.gt { rw cmp_using_eq_gt at nh, exact oadd_lt_oadd_2 h₂ nh }, rw cmp_using_eq_eq at nh, have := subtype.eq (eq_of_incomp nh), subst n₂, have IHa := @cmp_compares _ _ h₁.snd h₂.snd, cases cmp a₁ a₂, case ordering.lt { exact oadd_lt_oadd_3 IHa }, case ordering.gt { exact oadd_lt_oadd_3 IHa }, change a₁ = a₂ at IHa, subst IHa, exact rfl end theorem repr_inj {a b} [NF a] [NF b] : repr a = repr b ↔ a = b := ⟨match cmp a b, cmp_compares a b with | ordering.lt, (h : repr a < repr b), e := (ne_of_lt h e).elim | ordering.gt, (h : repr a > repr b), e := (ne_of_gt h e).elim | ordering.eq, h, e := h end, congr_arg _⟩ theorem NF.of_dvd_omega_power {b e n a} (h : NF (oadd e n a)) (d : ω ^ b ∣ repr (oadd e n a)) : b ≤ repr e ∧ ω ^ b ∣ repr a := begin have := mt repr_inj.1 (λ h, by injection h : oadd e n a ≠ 0), have L := le_of_not_lt (λ l, not_le_of_lt (h.below_of_lt l).repr_lt (le_of_dvd this d)), simp at d, exact ⟨L, (dvd_add_iff $ dvd_mul_of_dvd_left (power_dvd_power _ L) _).1 d⟩ end theorem NF.of_dvd_omega {e n a} (h : NF (oadd e n a)) : ω ∣ repr (oadd e n a) → repr e ≠ 0 ∧ ω ∣ repr a := by rw [← power_one ω, ← one_le_iff_ne_zero]; exact h.of_dvd_omega_power /-- `top_below b o` asserts that the largest exponent in `o`, if it exists, is less than `b`. This is an auxiliary definition for decidability of `NF`. -/ def top_below (b) : onote → Prop | 0 := true | (oadd e n a) := cmp e b = ordering.lt instance decidable_top_below : decidable_rel top_below := by intros b o; cases o; delta top_below; apply_instance theorem NF_below_iff_top_below {b} [NF b] : ∀ {o}, NF_below o (repr b) ↔ NF o ∧ top_below b o | 0 := ⟨λ h, ⟨⟨_, h⟩, trivial⟩, λ _, NF_below.zero⟩ | (oadd e n a) := ⟨λ h, ⟨⟨_, h⟩, (@cmp_compares _ b h.fst _).eq_lt.2 h.lt⟩, λ ⟨h₁, h₂⟩, h₁.below_of_lt $ (@cmp_compares _ b h₁.fst _).eq_lt.1 h₂⟩ instance decidable_NF : decidable_pred NF | 0 := is_true NF.zero | (oadd e n a) := begin have := decidable_NF e, have := decidable_NF a, resetI, apply decidable_of_iff (NF e ∧ NF a ∧ top_below e a), abstract { rw ← and_congr_right (λ h, @NF_below_iff_top_below _ h _), exact ⟨λ ⟨h₁, h₂⟩, NF.oadd h₁ n h₂, λ h, ⟨h.fst, h.snd'⟩⟩ }, end /-- Addition of ordinal notations (correct only for normal input) -/ def add : onote → onote → onote | 0 o := o | (oadd e n a) o := match add a o with | 0 := oadd e n 0 | o'@(oadd e' n' a') := match cmp e e' with | ordering.lt := o' | ordering.eq := oadd e (n + n') a' | ordering.gt := oadd e n o' end end instance : has_add onote := ⟨add⟩ @[simp] theorem zero_add (o : onote) : 0 + o = o := rfl theorem oadd_add (e n a o) : oadd e n a + o = add._match_1 e n (a + o) := rfl /-- Subtraction of ordinal notations (correct only for normal input) -/ def sub : onote → onote → onote | 0 o := 0 | o 0 := o | o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := match cmp e₁ e₂ with | ordering.lt := 0 | ordering.gt := o₁ | ordering.eq := match (n₁:ℕ) - n₂ with | 0 := if n₁ = n₂ then sub a₁ a₂ else 0 | (nat.succ k) := oadd e₁ k.succ_pnat a₁ end end instance : has_sub onote := ⟨sub⟩ theorem add_NF_below {b} : ∀ {o₁ o₂}, NF_below o₁ b → NF_below o₂ b → NF_below (o₁ + o₂) b | 0 o h₁ h₂ := h₂ | (oadd e n a) o h₁ h₂ := begin have h' := add_NF_below (h₁.snd.mono $ le_of_lt h₁.lt) h₂, simp [oadd_add], cases a + o with e' n' a', { exact NF_below.oadd h₁.fst NF_below.zero h₁.lt }, simp [add], have := @cmp_compares _ _ h₁.fst h'.fst, cases cmp e e'; simp [add], { exact h' }, { simp at this, subst e', exact NF_below.oadd h'.fst h'.snd h'.lt }, { exact NF_below.oadd h₁.fst (NF.below_of_lt this ⟨_, h'⟩) h₁.lt } end instance add_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ + o₂) | ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := (b₁.le_total b₂).elim (λ h, ⟨b₂, add_NF_below (h₁.mono h) h₂⟩) (λ h, ⟨b₁, add_NF_below h₁ (h₂.mono h)⟩) @[simp] theorem repr_add : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ + o₂) = repr o₁ + repr o₂ | 0 o h₁ h₂ := by simp | (oadd e n a) o h₁ h₂ := begin haveI := h₁.snd, have h' := repr_add a o, conv at h' in (_+o) {simp [(+)]}, have nf := onote.add_NF a o, conv at nf in (_+o) {simp [(+)]}, conv in (_+o) {simp [(+), add]}, cases add a o with e' n' a'; simp [add, h'.symm, add_assoc], have := h₁.fst, haveI := nf.fst, have ee := cmp_compares e e', cases cmp e e'; simp [add], { rw [← add_assoc, @add_absorp _ (repr e') (ω ^ repr e' * (n':ℕ))], { have := (h₁.below_of_lt ee).repr_lt, unfold repr at this, exact lt_of_le_of_lt (le_add_right _ _) this }, { simpa using (mul_le_mul_iff_left $ power_pos (repr e') omega_pos).2 (nat_cast_le.2 n'.pos) } }, { change e = e' at ee, substI e', rw [← add_assoc, ← ordinal.mul_add, ← nat.cast_add] } end theorem sub_NF_below : ∀ {o₁ o₂ b}, NF_below o₁ b → NF o₂ → NF_below (o₁ - o₂) b | 0 o b h₁ h₂ := by cases o; exact NF_below.zero | (oadd e n a) 0 b h₁ h₂ := h₁ | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) b h₁ h₂ := begin have h' := sub_NF_below h₁.snd h₂.snd, simp [has_sub.sub, sub] at h' ⊢, have := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂; simp [sub], { apply NF_below.zero }, { simp at this, subst e₂, cases mn : (n₁:ℕ) - n₂; simp [sub], { by_cases en : n₁ = n₂; simp [en], { exact h'.mono (le_of_lt h₁.lt) }, { exact NF_below.zero } }, { exact NF_below.oadd h₁.fst h₁.snd h₁.lt } }, { exact h₁ } end instance sub_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ - o₂) | ⟨b₁, h₁⟩ h₂ := ⟨b₁, sub_NF_below h₁ h₂⟩ @[simp] theorem repr_sub : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ - o₂) = repr o₁ - repr o₂ | 0 o h₁ h₂ := by cases o; exact (ordinal.zero_sub _).symm | (oadd e n a) 0 h₁ h₂ := (ordinal.sub_zero _).symm | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin haveI := h₁.snd, haveI := h₂.snd, have h' := repr_sub a₁ a₂, conv at h' in (a₁-a₂) {simp [has_sub.sub]}, have nf := onote.sub_NF a₁ a₂, conv at nf in (a₁-a₂) {simp [has_sub.sub]}, conv in (_-oadd _ _ _) {simp [has_sub.sub, sub]}, have ee := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂, { rw [sub_eq_zero_iff_le.2], {refl}, exact le_of_lt (oadd_lt_oadd_1 h₁ ee) }, { change e₁ = e₂ at ee, substI e₂, unfold sub._match_1, cases mn : (n₁:ℕ) - n₂; dsimp only [sub._match_2], { by_cases en : n₁ = n₂, { simp [en], rwa [add_sub_add_cancel] }, { simp [en, -repr], exact (sub_eq_zero_iff_le.2 $ le_of_lt $ oadd_lt_oadd_2 h₁ $ lt_of_le_of_ne (nat.sub_eq_zero_iff_le.1 mn) (mt pnat.eq en)).symm } }, { simp [nat.succ_pnat, -nat.cast_succ], rw [(nat.sub_eq_iff_eq_add $ le_of_lt $ nat.lt_of_sub_eq_succ mn).1 mn, add_comm, nat.cast_add, ordinal.mul_add, add_assoc, add_sub_add_cancel], refine (ordinal.sub_eq_of_add_eq $ add_absorp h₂.snd'.repr_lt $ le_trans _ (le_add_right _ _)).symm, simpa using mul_le_mul_left _ (nat_cast_le.2 $ nat.succ_pos _) } }, { exact (ordinal.sub_eq_of_add_eq $ add_absorp (h₂.below_of_lt ee).repr_lt $ omega_le_oadd _ _ _).symm } end /-- Multiplication of ordinal notations (correct only for normal input) -/ def mul : onote → onote → onote | 0 _ := 0 | _ 0 := 0 | o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else oadd (e₁ + e₂) n₂ (mul o₁ a₂) instance : has_mul onote := ⟨mul⟩ @[simp] theorem zero_mul (o : onote) : 0 * o = 0 := by cases o; refl @[simp] theorem mul_zero (o : onote) : o * 0 = 0 := by cases o; refl theorem oadd_mul (e₁ n₁ a₁ e₂ n₂ a₂) : oadd e₁ n₁ a₁ * oadd e₂ n₂ a₂ = if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else oadd (e₁ + e₂) n₂ (oadd e₁ n₁ a₁ * a₂) := rfl theorem oadd_mul_NF_below {e₁ n₁ a₁ b₁} (h₁ : NF_below (oadd e₁ n₁ a₁) b₁) : ∀ {o₂ b₂}, NF_below o₂ b₂ → NF_below (oadd e₁ n₁ a₁ * o₂) (repr e₁ + b₂) | 0 b₂ h₂ := NF_below.zero | (oadd e₂ n₂ a₂) b₂ h₂ := begin have IH := oadd_mul_NF_below h₂.snd, by_cases e0 : e₂ = 0; simp [e0, oadd_mul], { apply NF_below.oadd h₁.fst h₁.snd, simpa using (add_lt_add_iff_left (repr e₁)).2 (lt_of_le_of_lt (ordinal.zero_le _) h₂.lt) }, { haveI := h₁.fst, haveI := h₂.fst, apply NF_below.oadd, apply_instance, { rwa repr_add }, { rw [repr_add, ordinal.add_lt_add_iff_left], exact h₂.lt } } end instance mul_NF : ∀ o₁ o₂ [NF o₁] [NF o₂], NF (o₁ * o₂) | 0 o h₁ h₂ := by cases o; exact NF.zero | (oadd e n a) o ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ := ⟨_, oadd_mul_NF_below hb₁ hb₂⟩ @[simp] theorem repr_mul : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ * o₂) = repr o₁ * repr o₂ | 0 o h₁ h₂ := by cases o; exact (ordinal.zero_mul _).symm | (oadd e₁ n₁ a₁) 0 h₁ h₂ := (ordinal.mul_zero _).symm | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin have IH : repr (mul _ _) = _ := @repr_mul _ _ h₁ h₂.snd, conv {to_lhs, simp [(*)]}, have ao : repr a₁ + ω ^ repr e₁ * (n₁:ℕ) = ω ^ repr e₁ * (n₁:ℕ), { apply add_absorp h₁.snd'.repr_lt, simpa using (mul_le_mul_iff_left $ power_pos _ omega_pos).2 (nat_cast_le.2 n₁.2) }, by_cases e0 : e₂ = 0; simp [e0, mul], { cases nat.exists_eq_succ_of_ne_zero n₂.ne_zero with x xe, simp [h₂.zero_of_zero e0, xe, -nat.cast_succ], rw [← nat_cast_succ x, add_mul_succ _ ao, mul_assoc] }, { haveI := h₁.fst, haveI := h₂.fst, simp [IH, repr_add, power_add, ordinal.mul_add], rw ← mul_assoc, congr' 2, have := mt repr_inj.1 e0, rw [add_mul_limit ao (power_is_limit_left omega_is_limit this), mul_assoc, mul_omega_dvd (nat_cast_pos.2 n₁.pos) (nat_lt_omega _)], simpa using power_dvd_power ω (one_le_iff_ne_zero.2 this) }, end /-- Calculate division and remainder of `o` mod ω. `split' o = (a, n)` means `o = ω * a + n`. -/ def split' : onote → onote × ℕ | 0 := (0, 0) | (oadd e n a) := if e = 0 then (0, n) else let (a', m) := split' a in (oadd (e - 1) n a', m) /-- Calculate division and remainder of `o` mod ω. `split o = (a, n)` means `o = a + n`, where `ω ∣ a`. -/ def split : onote → onote × ℕ | 0 := (0, 0) | (oadd e n a) := if e = 0 then (0, n) else let (a', m) := split a in (oadd e n a', m) /-- `scale x o` is the ordinal notation for `ω ^ x * o`. -/ def scale (x : onote) : onote → onote | 0 := 0 | (oadd e n a) := oadd (x + e) n (scale a) /-- `mul_nat o n` is the ordinal notation for `o * n`. -/ def mul_nat : onote → ℕ → onote | 0 m := 0 | _ 0 := 0 | (oadd e n a) (m+1) := oadd e (n * m.succ_pnat) a /-- Auxiliary definition to compute the ordinal notation for the ordinal exponentiation in `power` -/ def power_aux (e a0 a : onote) : ℕ → ℕ → onote | _ 0 := 0 | 0 (m+1) := oadd e m.succ_pnat 0 | (k+1) m := scale (e + mul_nat a0 k) a + power_aux k m /-- `power o₁ o₂` calculates the ordinal notation for the ordinal exponential `o₁ ^ o₂`. -/ def power (o₁ o₂ : onote) : onote := match split o₁ with | (0, 0) := if o₂ = 0 then 1 else 0 | (0, 1) := 1 | (0, m+1) := let (b', k) := split' o₂ in oadd b' (@has_pow.pow ℕ+ _ _ m.succ_pnat k) 0 | (a@(oadd a0 _ _), m) := match split o₂ with | (b, 0) := oadd (a0 * b) 1 0 | (b, k+1) := let eb := a0*b in scale (eb + mul_nat a0 k) a + power_aux eb a0 (mul_nat a m) k m end end instance : has_pow onote onote := ⟨power⟩ theorem power_def (o₁ o₂ : onote) : o₁ ^ o₂ = power._match_1 o₂ (split o₁) := rfl theorem split_eq_scale_split' : ∀ {o o' m} [NF o], split' o = (o', m) → split o = (scale 1 o', m) | 0 o' m h p := by injection p; substs o' m; refl | (oadd e n a) o' m h p := begin by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢, { rcases p with ⟨rfl, rfl⟩, exact ⟨rfl, rfl⟩ }, { revert p, cases h' : split' a with a' m', haveI := h.fst, haveI := h.snd, simp [split_eq_scale_split' h', split, split'], have : 1 + (e - 1) = e, { refine repr_inj.1 _, simp, have := mt repr_inj.1 e0, exact add_sub_cancel_of_le (one_le_iff_ne_zero.2 this) }, intros, substs o' m, simp [scale, this] } end theorem NF_repr_split' : ∀ {o o' m} [NF o], split' o = (o', m) → NF o' ∧ repr o = ω * repr o' + m | 0 o' m h p := by injection p; substs o' m; simp [NF.zero] | (oadd e n a) o' m h p := begin by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢, { rcases p with ⟨rfl, rfl⟩, simp [h.zero_of_zero e0, NF.zero] }, { revert p, cases h' : split' a with a' m', haveI := h.fst, haveI := h.snd, cases NF_repr_split' h' with IH₁ IH₂, simp [IH₂, split'], intros, substs o' m, have : ω ^ repr e = ω ^ (1 : ordinal.{0}) * ω ^ (repr e - 1), { have := mt repr_inj.1 e0, rw [← power_add, add_sub_cancel_of_le (one_le_iff_ne_zero.2 this)] }, refine ⟨NF.oadd (by apply_instance) _ _, _⟩, { simp at this ⊢, refine IH₁.below_of_lt' ((mul_lt_mul_iff_left omega_pos).1 $ lt_of_le_of_lt (le_add_right _ m') _), rw [← this, ← IH₂], exact h.snd'.repr_lt }, { rw this, simp [ordinal.mul_add, mul_assoc, add_assoc] } } end theorem scale_eq_mul (x) [NF x] : ∀ o [NF o], scale x o = oadd x 1 0 * o | 0 h := rfl | (oadd e n a) h := begin simp [(*)], simp [mul, scale], haveI := h.snd, by_cases e0 : e = 0, { rw scale_eq_mul, simp [e0, h.zero_of_zero, show x + 0 = x, from repr_inj.1 (by simp)] }, { simp [e0, scale_eq_mul, (*)] } end instance NF_scale (x) [NF x] (o) [NF o] : NF (scale x o) := by rw scale_eq_mul; apply_instance @[simp] theorem repr_scale (x) [NF x] (o) [NF o] : repr (scale x o) = ω ^ repr x * repr o := by simp [scale_eq_mul] theorem NF_repr_split {o o' m} [NF o] (h : split o = (o', m)) : NF o' ∧ repr o = repr o' + m := begin cases e : split' o with a n, cases NF_repr_split' e with s₁ s₂, resetI, rw split_eq_scale_split' e at h, injection h, substs o' n, simp [repr_scale, s₂.symm], apply_instance end theorem split_dvd {o o' m} [NF o] (h : split o = (o', m)) : ω ∣ repr o' := begin cases e : split' o with a n, rw split_eq_scale_split' e at h, injection h, subst o', cases NF_repr_split' e, resetI, simp end theorem split_add_lt {o e n a m} [NF o] (h : split o = (oadd e n a, m)) : repr a + m < ω ^ repr e := begin cases NF_repr_split h with h₁ h₂, cases h₁.of_dvd_omega (split_dvd h) with e0 d, have := h₁.fst, have := h₁.snd, refine add_lt_omega_power h₁.snd'.repr_lt (lt_of_lt_of_le (nat_lt_omega _) _), simpa using power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0), end @[simp] theorem mul_nat_eq_mul (n o) : mul_nat o n = o * of_nat n := by cases o; cases n; refl instance NF_mul_nat (o) [NF o] (n) : NF (mul_nat o n) := by simp; apply_instance instance NF_power_aux (e a0 a) [NF e] [NF a0] [NF a] : ∀ k m, NF (power_aux e a0 a k m) | k 0 := by cases k; exact NF.zero | 0 (m+1) := NF.oadd_zero _ _ | (k+1) (m+1) := by haveI := NF_power_aux k; simp [power_aux, nat.succ_ne_zero]; apply_instance instance NF_power (o₁ o₂) [NF o₁] [NF o₂] : NF (o₁ ^ o₂) := begin cases e₁ : split o₁ with a m, have na := (NF_repr_split e₁).1, cases e₂ : split' o₂ with b' k, haveI := (NF_repr_split' e₂).1, casesI a with a0 n a', { cases m with m, { by_cases o₂ = 0; simp [pow, power, *]; apply_instance }, { by_cases m = 0; simp [pow, power, -monoid.pow_eq_has_pow, *]; apply_instance } }, { simp [pow, power, e₁, e₂, split_eq_scale_split' e₂], have := na.fst, cases k with k; simp [succ_eq_add_one, power]; resetI; apply_instance } end theorem scale_power_aux (e a0 a : onote) [NF e] [NF a0] [NF a] : ∀ k m, repr (power_aux e a0 a k m) = ω ^ repr e * repr (power_aux 0 a0 a k m) | 0 m := by cases m; simp [power_aux] | (k+1) m := by by_cases m = 0; simp [h, power_aux, ordinal.mul_add, power_add, mul_assoc, scale_power_aux] theorem repr_power_aux₁ {e a} [Ne : NF e] [Na : NF a] {a' : ordinal} (e0 : repr e ≠ 0) (h : a' < ω ^ repr e) (aa : repr a = a') (n : ℕ+) : (ω ^ repr e * (n:ℕ) + a') ^ ω = (ω ^ repr e) ^ ω := begin subst aa, have No := Ne.oadd n (Na.below_of_lt' h), have := omega_le_oadd e n a, unfold repr at this, refine le_antisymm _ (power_le_power_left _ this), apply (power_le_of_limit (ne_of_gt $ lt_of_lt_of_le (power_pos _ omega_pos) this) omega_is_limit).2, intros b l, have := (No.below_of_lt (lt_succ_self _)).repr_lt, unfold repr at this, apply le_trans (power_le_power_left b $ le_of_lt this), rw [← power_mul, ← power_mul], apply power_le_power_right omega_pos, cases le_or_lt ω (repr e) with h h, { apply le_trans (mul_le_mul_left _ $ le_of_lt $ lt_succ_self _), rw [succ, add_mul_succ _ (one_add_of_omega_le h), ← succ, succ_le, mul_lt_mul_iff_left (ordinal.pos_iff_ne_zero.2 e0)], exact omega_is_limit.2 _ l }, { refine le_trans (le_of_lt $ mul_lt_omega (omega_is_limit.2 _ h) l) _, simpa using mul_le_mul_right ω (one_le_iff_ne_zero.2 e0) } end section local infixr ^ := @pow ordinal.{0} ordinal ordinal.has_pow theorem repr_power_aux₂ {a0 a'} [N0 : NF a0] [Na' : NF a'] (m : ℕ) (d : ω ∣ repr a') (e0 : repr a0 ≠ 0) (h : repr a' + m < ω ^ repr a0) (n : ℕ+) (k : ℕ) : let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m) in (k ≠ 0 → R < (ω ^ repr a0) ^ succ k) ∧ (ω ^ repr a0) ^ k * (ω ^ repr a0 * (n:ℕ) + repr a') + R = (ω ^ repr a0 * (n:ℕ) + repr a' + m) ^ succ k := begin intro, haveI No : NF (oadd a0 n a') := N0.oadd n (Na'.below_of_lt' $ lt_of_le_of_lt (le_add_right _ _) h), induction k with k IH, {cases m; simp [power_aux, R]}, rename R R', let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m), let ω0 := ω ^ repr a0, let α' := ω0 * n + repr a', change (k ≠ 0 → R < ω0 ^ succ k) ∧ ω0 ^ k * α' + R = (α' + m) ^ succ k at IH, have RR : R' = ω0 ^ k * (α' * m) + R, { by_cases m = 0; simp [h, R', power_aux, R, power_mul], { cases k; simp [power_aux] }, { refl } }, have α0 : 0 < α', {simpa [α', lt_def, repr] using oadd_pos a0 n a'}, have ω00 : 0 < ω0 ^ k := power_pos _ (power_pos _ omega_pos), have Rl : R < ω ^ (repr a0 * succ ↑k), { by_cases k0 : k = 0, { simp [k0], refine lt_of_lt_of_le _ (power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0)), cases m with m; simp [k0, R, power_aux, omega_pos], rw [← nat.cast_succ], apply nat_lt_omega }, { rw power_mul, exact IH.1 k0 } }, refine ⟨λ_, _, _⟩, { rw [RR, ← power_mul _ _ (succ k.succ)], have e0 := ordinal.pos_iff_ne_zero.2 e0, have rr0 := lt_of_lt_of_le e0 (le_add_left _ _), apply add_lt_omega_power, { simp [power_mul, ω0, power_add, mul_assoc], rw [mul_lt_mul_iff_left ω00, ← ordinal.power_add], have := (No.below_of_lt _).repr_lt, unfold repr at this, refine mul_lt_omega_power rr0 this (nat_lt_omega _), simpa using (add_lt_add_iff_left (repr a0)).2 e0 }, { refine lt_of_lt_of_le Rl (power_le_power_right omega_pos $ mul_le_mul_left _ $ succ_le_succ.2 $ nat_cast_le.2 $ le_of_lt k.lt_succ_self) } }, refine calc ω0 ^ k.succ * α' + R' = ω0 ^ succ k * α' + (ω0 ^ k * α' * m + R) : by rw [nat_cast_succ, RR, ← mul_assoc] ... = (ω0 ^ k * α' + R) * α' + (ω0 ^ k * α' + R) * m : _ ... = (α' + m) ^ succ k.succ : by rw [← ordinal.mul_add, ← nat_cast_succ, power_succ, IH.2], congr' 1, { have αd : ω ∣ α' := dvd_add (dvd_mul_of_dvd_left (by simpa using power_dvd_power ω (one_le_iff_ne_zero.2 e0)) _) d, rw [ordinal.mul_add (ω0 ^ k), add_assoc, ← mul_assoc, ← power_succ, add_mul_limit _ (is_limit_iff_omega_dvd.2 ⟨ne_of_gt α0, αd⟩), mul_assoc, @mul_omega_dvd n (nat_cast_pos.2 n.pos) (nat_lt_omega _) _ αd], apply @add_absorp _ (repr a0 * succ k), { refine add_lt_omega_power _ Rl, rw [power_mul, power_succ, mul_lt_mul_iff_left ω00], exact No.snd'.repr_lt }, { have := mul_le_mul_left (ω0 ^ succ k) (one_le_iff_pos.2 $ nat_cast_pos.2 n.pos), rw power_mul, simpa [-power_succ] } }, { cases m, { have : R = 0, {cases k; simp [R, power_aux]}, simp [this] }, { rw [← nat_cast_succ, add_mul_succ], apply add_absorp Rl, rw [power_mul, power_succ], apply ordinal.mul_le_mul_left, simpa [α', repr] using omega_le_oadd a0 n a' } } end end theorem repr_power (o₁ o₂) [NF o₁] [NF o₂] : repr (o₁ ^ o₂) = repr o₁ ^ repr o₂ := begin cases e₁ : split o₁ with a m, cases NF_repr_split e₁ with N₁ r₁, cases a with a0 n a', { cases m with m, { by_cases o₂ = 0; simp [power_def, power, e₁, h, r₁], have := mt repr_inj.1 h, rw zero_power this }, { cases e₂ : split' o₂ with b' k, cases NF_repr_split' e₂ with _ r₂, by_cases m = 0; simp [power_def, power, e₁, h, r₁, e₂, r₂, -nat.cast_succ], rw [power_add, power_mul, power_omega _ (nat_lt_omega _)], simpa using nat_cast_lt.2 (nat.succ_lt_succ $ pos_iff_ne_zero.2 h) } }, { haveI := N₁.fst, haveI := N₁.snd, cases N₁.of_dvd_omega (split_dvd e₁) with a00 ad, have al := split_add_lt e₁, have aa : repr (a' + of_nat m) = repr a' + m, {simp}, cases e₂ : split' o₂ with b' k, cases NF_repr_split' e₂ with _ r₂, simp [power_def, power, e₁, r₁, split_eq_scale_split' e₂], cases k with k; resetI, { simp [power, r₂, power_mul, repr_power_aux₁ a00 al aa, add_assoc] }, { simp [succ_eq_add_one, power, r₂, power_add, power_mul, mul_assoc, add_assoc], rw [repr_power_aux₁ a00 al aa, scale_power_aux], simp [power_mul], rw [← ordinal.mul_add, ← add_assoc (ω ^ repr a0 * (n:ℕ))], congr' 1, rw [← power_succ], exact (repr_power_aux₂ _ ad a00 al _ _).2 } } end end onote /-- The type of normal ordinal notations. (It would have been nicer to define this right in the inductive type, but `NF o` requires `repr` which requires `onote`, so all these things would have to be defined at once, which messes up the VM representation.) -/ def nonote := {o : onote // o.NF} instance : decidable_eq nonote := by unfold nonote; apply_instance namespace nonote open onote instance NF (o : nonote) : NF o.1 := o.2 /-- Construct a `nonote` from an ordinal notation (and infer normality) -/ def mk (o : onote) [h : NF o] : nonote := ⟨o, h⟩ /-- The ordinal represented by an ordinal notation. (This function is noncomputable because ordinal arithmetic is noncomputable. In computational applications `nonote` can be used exclusively without reference to `ordinal`, but this function allows for correctness results to be stated.) -/ noncomputable def repr (o : nonote) : ordinal := o.1.repr instance : has_to_string nonote := ⟨λ x, x.1.to_string⟩ instance : has_repr nonote := ⟨λ x, x.1.repr'⟩ instance : preorder nonote := { le := λ x y, repr x ≤ repr y, lt := λ x y, repr x < repr y, le_refl := λ a, @le_refl ordinal _ _, le_trans := λ a b c, @le_trans ordinal _ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ } instance : has_zero nonote := ⟨⟨0, NF.zero⟩⟩ instance : inhabited nonote := ⟨0⟩ /-- Convert a natural number to an ordinal notation -/ def of_nat (n : ℕ) : nonote := ⟨of_nat n, _, NF_below_of_nat _⟩ /-- Compare ordinal notations -/ def cmp (a b : nonote) : ordering := cmp a.1 b.1 theorem cmp_compares : ∀ a b : nonote, (cmp a b).compares a b | ⟨a, ha⟩ ⟨b, hb⟩ := begin resetI, dsimp [cmp], have := onote.cmp_compares a b, cases onote.cmp a b; try {exact this}, exact subtype.mk_eq_mk.2 this end instance : linear_order nonote := linear_order_of_compares cmp cmp_compares /-- Asserts that `repr a < ω ^ repr b`. Used in `nonote.rec_on` -/ def below (a b : nonote) : Prop := NF_below a.1 (repr b) /-- The `oadd` pseudo-constructor for `nonote` -/ def oadd (e : nonote) (n : ℕ+) (a : nonote) (h : below a e) : nonote := ⟨_, NF.oadd e.2 n h⟩ /-- This is a recursor-like theorem for `nonote` suggesting an inductive definition, which can't actually be defined this way due to conflicting dependencies. -/ @[elab_as_eliminator] def rec_on {C : nonote → Sort*} (o : nonote) (H0 : C 0) (H1 : ∀ e n a h, C e → C a → C (oadd e n a h)) : C o := begin cases o with o h, induction o with e n a IHe IHa, { exact H0 }, { exact H1 ⟨e, h.fst⟩ n ⟨a, h.snd⟩ h.snd' (IHe _) (IHa _) } end /-- Addition of ordinal notations -/ instance : has_add nonote := ⟨λ x y, mk (x.1 + y.1)⟩ theorem repr_add (a b) : repr (a + b) = repr a + repr b := onote.repr_add a.1 b.1 /-- Subtraction of ordinal notations -/ instance : has_sub nonote := ⟨λ x y, mk (x.1 - y.1)⟩ theorem repr_sub (a b) : repr (a - b) = repr a - repr b := onote.repr_sub a.1 b.1 /-- Multiplication of ordinal notations -/ instance : has_mul nonote := ⟨λ x y, mk (x.1 * y.1)⟩ theorem repr_mul (a b) : repr (a * b) = repr a * repr b := onote.repr_mul a.1 b.1 /-- Exponentiation of ordinal notations -/ def power (x y : nonote) := mk (x.1.power y.1) theorem repr_power (a b) : repr (power a b) = (repr a).power (repr b) := onote.repr_power a.1 b.1 end nonote
e4bfc1d9ab18a1d80c62f2522ccea681151e2142
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/connected.lean
1b2c248568291d34ff33ad874055414c298d8d24
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,728
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.shapes.pullbacks import category_theory.limits.shapes.equalizers import category_theory.limits.preserves.basic import category_theory.is_connected /-! # Connected limits A connected limit is a limit whose shape is a connected category. We give examples of connected categories, and prove that the functor given by `(X × -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X × -)`. -/ noncomputable theory universes v₁ v₂ u₁ u₂ open category_theory category_theory.category category_theory.limits namespace category_theory section examples instance wide_pullback_shape_connected (J : Type v₁) : is_connected (wide_pullback_shape J) := begin apply is_connected.of_induct, introv hp t, cases j, { exact hp }, { rwa t (wide_pullback_shape.hom.term j) } end instance wide_pushout_shape_connected (J : Type v₁) : is_connected (wide_pushout_shape J) := begin apply is_connected.of_induct, introv hp t, cases j, { exact hp }, { rwa ← t (wide_pushout_shape.hom.init j) } end instance parallel_pair_inhabited : inhabited walking_parallel_pair := ⟨walking_parallel_pair.one⟩ instance parallel_pair_connected : is_connected (walking_parallel_pair) := begin apply is_connected.of_induct, introv _ t, cases j, { rwa t walking_parallel_pair_hom.left }, { assumption } end end examples local attribute [tidy] tactic.case_bash variables {C : Type u₂} [category.{v₂} C] variables [has_binary_products C] variables {J : Type v₂} [small_category J] namespace prod_preserves_connected_limits /-- (Impl). The obvious natural transformation from (X × K -) to K. -/ @[simps] def γ₂ {K : J ⥤ C} (X : C) : K ⋙ prod.functor.obj X ⟶ K := { app := λ Y, limits.prod.snd } /-- (Impl). The obvious natural transformation from (X × K -) to X -/ @[simps] def γ₁ {K : J ⥤ C} (X : C) : K ⋙ prod.functor.obj X ⟶ (functor.const J).obj X := { app := λ Y, limits.prod.fst } /-- (Impl). Given a cone for (X × K -), produce a cone for K using the natural transformation `γ₂` -/ @[simps] def forget_cone {X : C} {K : J ⥤ C} (s : cone (K ⋙ prod.functor.obj X)) : cone K := { X := s.X, π := s.π ≫ γ₂ X } end prod_preserves_connected_limits open prod_preserves_connected_limits /-- The functor `(X × -)` preserves any connected limit. Note that this functor does not preserve the two most obvious disconnected limits - that is, `(X × -)` does not preserve products or terminal object, eg `(X ⨯ A) ⨯ (X ⨯ B)` is not isomorphic to `X ⨯ (A ⨯ B)` and `X ⨯ 1` is not isomorphic to `1`. -/ noncomputable def prod_preserves_connected_limits [is_connected J] (X : C) : preserves_limits_of_shape J (prod.functor.obj X) := { preserves_limit := λ K, { preserves := λ c l, { lift := λ s, prod.lift (s.π.app (classical.arbitrary _) ≫ limits.prod.fst) (l.lift (forget_cone s)), fac' := λ s j, begin apply prod.hom_ext, { erw [assoc, limit.map_π, comp_id, limit.lift_π], exact (nat_trans_from_is_connected (s.π ≫ γ₁ X) j (classical.arbitrary _)).symm }, { simp [← l.fac (forget_cone s) j] } end, uniq' := λ s m L, begin apply prod.hom_ext, { erw [limit.lift_π, ← L (classical.arbitrary J), assoc, limit.map_π, comp_id], refl }, { rw limit.lift_π, apply l.uniq (forget_cone s), intro j, simp [← L j] } end } } } end category_theory
5c6bffd828923eb1fba224abe4f04805e4199f06
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/alias2.lean
896025fb36c8710b682e8456d3850255cba05b85
[ "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
173
lean
-- namespace foo definition t := true end foo open foo namespace bla definition t := false check foo.t -- <<< must print foo.t : Prop instead of t : Prop end bla
a7ff3382ca0c36952b89f30c1498821e10ab6a49
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/584a.lean
ae895fe26956c7c6c67e81c61289e7fd1d4370b3
[ "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
332
lean
universe variables u variables (A : Type u) [H : inhabited A] (x : A) include H definition foo := x #check foo -- A and x are explicit variables {A x} definition foo' := x #check @foo' -- A is explicit, x is implicit open nat #check foo nat 10 definition test : foo' = (10:nat) := rfl set_option pp.implicit true #print test
9e98114a72941f97ab893c53546fbd6a2def786d
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/meta/expr.lean
f36e33d6b491bd561eae5e0df596860db9c554c6
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
5,099
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis Additional non-tactic operations on expr and related types -/ namespace name meta def deinternalize_field : name → name | (name.mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) -- Pops the top `n` prefixes from the given name. meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest def from_components : list string → name := from_components_aux name.anonymous -- `name`s can contain numeral pieces, which are not legal names -- when typed/passed directly to the parser. We turn an arbitrary -- name into a legal identifier name. meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n end name namespace level meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff end level namespace expr open tactic protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat meta def is_meta_var : expr → bool | (mvar _ _ _) := tt | e := ff meta def is_sort : expr → bool | (sort _) := tt | e := ff meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_meta_var then insert e' es else es) meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg end expr namespace environment meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) meta def is_structure_like (env : environment) (n : name) : option (nat × name) := do guardb (env.is_inductive n), d ← (env.get n).to_option, [intro] ← pure (env.constructors_of n) | none, guard (env.inductive_num_indices n = 0), some (env.inductive_num_params n, intro) meta def is_structure (env : environment) (n : name) : bool := option.is_some $ do (nparams, intro) ← env.is_structure_like n, di ← (env.get intro).to_option, expr.pi x _ _ _ ← nparams.iterate (λ e : option expr, do expr.pi _ _ _ body ← e | none, some body) (some di.type) | none, env.is_projection (n ++ x.deinternalize_field) end environment
98096d2b9a97f25d5b0119117bb160e4a575175b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/lie/submodule.lean
1e0712ff9e520e8aebe5bd84a92f84e65b9b40cb
[ "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
33,604
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.subalgebra import ring_theory.noetherian /-! # Lie submodules of a Lie algebra In this file we define Lie submodules and Lie ideals, we construct the lattice structure on Lie submodules and we use it to define various important operations, notably the Lie span of a subset of a Lie module. ## Main definitions * `lie_submodule` * `lie_submodule.well_founded_of_noetherian` * `lie_submodule.lie_span` * `lie_submodule.map` * `lie_submodule.comap` * `lie_ideal` * `lie_ideal.map` * `lie_ideal.comap` ## Tags lie algebra, lie submodule, lie ideal, lattice structure -/ universes u v w w₁ w₂ section lie_submodule variables (R : Type u) (L : Type v) (M : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] set_option old_structure_cmd true /-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie module. -/ structure lie_submodule extends submodule R M := (lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → ⁅x, m⁆ ∈ carrier) attribute [nolint doc_blame] lie_submodule.to_submodule namespace lie_submodule variables {R L M} (N N' : lie_submodule R L M) /-- The zero module is a Lie submodule of any Lie module. -/ instance : has_zero (lie_submodule R L M) := ⟨{ lie_mem := λ x m h, by { rw ((submodule.mem_bot R).1 h), apply lie_zero, }, ..(0 : submodule R M)}⟩ instance : inhabited (lie_submodule R L M) := ⟨0⟩ instance coe_submodule : has_coe (lie_submodule R L M) (submodule R M) := ⟨to_submodule⟩ @[norm_cast] lemma coe_to_submodule : ((N : submodule R M) : set M) = N := rfl instance has_mem : has_mem M (lie_submodule R L M) := ⟨λ x N, x ∈ (N : set M)⟩ @[simp] lemma mem_carrier {x : M} : x ∈ N.carrier ↔ x ∈ (N : set M) := iff.rfl @[simp] lemma mem_mk_iff (S : set M) (h₁ h₂ h₃ h₄) {x : M} : x ∈ (⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) ↔ x ∈ S := iff.rfl @[simp] lemma mem_coe_submodule {x : M} : x ∈ (N : submodule R M) ↔ x ∈ N := iff.rfl lemma mem_coe {x : M} : x ∈ (N : set M) ↔ x ∈ N := iff.rfl @[simp] lemma zero_mem : (0 : M) ∈ N := (N : submodule R M).zero_mem @[simp] lemma coe_to_set_mk (S : set M) (h₁ h₂ h₃ h₄) : ((⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) : set M) = S := rfl @[simp] lemma coe_to_submodule_mk (p : submodule R M) (h) : (({lie_mem := h, ..p} : lie_submodule R L M) : submodule R M) = p := by { cases p, refl, } lemma coe_submodule_injective : function.injective (to_submodule : lie_submodule R L M → submodule R M) := λ x y h, by { cases x, cases y, congr, injection h } @[ext] lemma ext (h : ∀ m, m ∈ N ↔ m ∈ N') : N = N' := coe_submodule_injective $ set_like.ext h @[simp] lemma coe_to_submodule_eq_iff : (N : submodule R M) = (N' : submodule R M) ↔ N = N' := coe_submodule_injective.eq_iff /-- Copy of a lie_submodule with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (s : set M) (hs : s = ↑N) : lie_submodule R L M := { carrier := s, zero_mem' := hs.symm ▸ N.zero_mem', add_mem' := hs.symm ▸ N.add_mem', smul_mem' := hs.symm ▸ N.smul_mem', lie_mem := hs.symm ▸ N.lie_mem, } @[simp] lemma coe_copy (S : lie_submodule R L M) (s : set M) (hs : s = ↑S) : (S.copy s hs : set M) = s := rfl lemma copy_eq (S : lie_submodule R L M) (s : set M) (hs : s = ↑S) : S.copy s hs = S := coe_submodule_injective (set_like.coe_injective hs) instance : lie_ring_module L N := { bracket := λ (x : L) (m : N), ⟨⁅x, m.val⁆, N.lie_mem m.property⟩, add_lie := by { intros x y m, apply set_coe.ext, apply add_lie, }, lie_add := by { intros x m n, apply set_coe.ext, apply lie_add, }, leibniz_lie := by { intros x y m, apply set_coe.ext, apply leibniz_lie, }, } instance : lie_module R L N := { lie_smul := by { intros t x y, apply set_coe.ext, apply lie_smul, }, smul_lie := by { intros t x y, apply set_coe.ext, apply smul_lie, }, } @[simp, norm_cast] lemma coe_zero : ((0 : N) : M) = (0 : M) := rfl @[simp, norm_cast] lemma coe_add (m m' : N) : (↑(m + m') : M) = (m : M) + (m' : M) := rfl @[simp, norm_cast] lemma coe_neg (m : N) : (↑(-m) : M) = -(m : M) := rfl @[simp, norm_cast] lemma coe_sub (m m' : N) : (↑(m - m') : M) = (m : M) - (m' : M) := rfl @[simp, norm_cast] lemma coe_smul (t : R) (m : N) : (↑(t • m) : M) = t • (m : M) := rfl @[simp, norm_cast] lemma coe_bracket (x : L) (m : N) : (↑⁅x, m⁆ : M) = ⁅x, ↑m⁆ := rfl end lie_submodule section lie_ideal variables (L) /-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/ abbreviation lie_ideal := lie_submodule R L L lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I := by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, } /-- An ideal of a Lie algebra is a Lie subalgebra. -/ def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L := { lie_mem' := by { intros x y hx hy, apply lie_mem_right, exact hy, }, ..I.to_submodule, } instance : has_coe (lie_ideal R L) (lie_subalgebra R L) := ⟨λ I, lie_ideal_subalgebra R L I⟩ @[norm_cast] lemma lie_ideal.coe_to_subalgebra (I : lie_ideal R L) : ((I : lie_subalgebra R L) : set L) = I := rfl @[norm_cast] lemma lie_ideal.coe_to_lie_subalgebra_to_submodule (I : lie_ideal R L) : ((I : lie_subalgebra R L) : submodule R L) = I := rfl end lie_ideal variables {R M} lemma submodule.exists_lie_submodule_coe_eq_iff (p : submodule R M) : (∃ (N : lie_submodule R L M), ↑N = p) ↔ ∀ (x : L) (m : M), m ∈ p → ⁅x, m⁆ ∈ p := begin split, { rintros ⟨N, rfl⟩, exact N.lie_mem, }, { intros h, use { lie_mem := h, ..p }, exact lie_submodule.coe_to_submodule_mk p _, }, end namespace lie_subalgebra variables {L} /-- Given a Lie subalgebra `K ⊆ L`, if we view `L` as a `K`-module by restriction, it contains a distinguished Lie submodule for the action of `K`, namely `K` itself. -/ def to_lie_submodule (K : lie_subalgebra R L) : lie_submodule R K L := { lie_mem := λ x y hy, K.lie_mem x.property hy, .. (K : submodule R L) } @[simp] lemma coe_to_lie_submodule (K : lie_subalgebra R L) : (K.to_lie_submodule : submodule R L) = K := by { rcases K with ⟨⟨⟩⟩, refl, } @[simp] lemma mem_to_lie_submodule {K : lie_subalgebra R L} (x : L) : x ∈ K.to_lie_submodule ↔ x ∈ K := iff.rfl lemma exists_lie_ideal_coe_eq_iff (K : lie_subalgebra R L) : (∃ (I : lie_ideal R L), ↑I = K) ↔ ∀ (x y : L), y ∈ K → ⁅x, y⁆ ∈ K := begin simp only [← coe_to_submodule_eq_iff, lie_ideal.coe_to_lie_subalgebra_to_submodule, submodule.exists_lie_submodule_coe_eq_iff L], exact iff.rfl, end lemma exists_nested_lie_ideal_coe_eq_iff {K K' : lie_subalgebra R L} (h : K ≤ K') : (∃ (I : lie_ideal R K'), ↑I = of_le h) ↔ ∀ (x y : L), x ∈ K' → y ∈ K → ⁅x, y⁆ ∈ K := begin simp only [exists_lie_ideal_coe_eq_iff, coe_bracket, mem_of_le], split, { intros h' x y hx hy, exact h' ⟨x, hx⟩ ⟨y, h hy⟩ hy, }, { rintros h' ⟨x, hx⟩ ⟨y, hy⟩ hy', exact h' x y hx hy', }, end end lie_subalgebra end lie_submodule namespace lie_submodule variables {R : Type u} {L : Type v} {M : Type w} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) section lattice_structure open set lemma coe_injective : function.injective (coe : lie_submodule R L M → set M) := set_like.coe_injective.comp coe_submodule_injective instance : partial_order (lie_submodule R L M) := { le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq. ..partial_order.lift (coe : lie_submodule R L M → set M) coe_injective } lemma le_def : N ≤ N' ↔ (N : set M) ⊆ N' := iff.rfl @[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (N : submodule R M) ≤ N' ↔ N ≤ N' := iff.rfl instance : has_bot (lie_submodule R L M) := ⟨0⟩ @[simp] lemma bot_coe : ((⊥ : lie_submodule R L M) : set M) = {0} := rfl @[simp] lemma bot_coe_submodule : ((⊥ : lie_submodule R L M) : submodule R M) = ⊥ := rfl @[simp] lemma mem_bot (x : M) : x ∈ (⊥ : lie_submodule R L M) ↔ x = 0 := mem_singleton_iff instance : has_top (lie_submodule R L M) := ⟨{ lie_mem := λ x m h, mem_univ ⁅x, m⁆, ..(⊤ : submodule R M) }⟩ @[simp] lemma top_coe : ((⊤ : lie_submodule R L M) : set M) = univ := rfl @[simp] lemma top_coe_submodule : ((⊤ : lie_submodule R L M) : submodule R M) = ⊤ := rfl @[simp] lemma mem_top (x : M) : x ∈ (⊤ : lie_submodule R L M) := mem_univ x instance : has_inf (lie_submodule R L M) := ⟨λ N N', { lie_mem := λ x m h, mem_inter (N.lie_mem h.1) (N'.lie_mem h.2), ..(N ⊓ N' : submodule R M) }⟩ instance : has_Inf (lie_submodule R L M) := ⟨λ S, { lie_mem := λ x m h, by { simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib] at *, intros N hN, apply N.lie_mem (h N hN), }, ..Inf {(s : submodule R M) | s ∈ S} }⟩ @[simp] theorem inf_coe : (↑(N ⊓ N') : set M) = N ∩ N' := rfl @[simp] lemma Inf_coe_to_submodule (S : set (lie_submodule R L M)) : (↑(Inf S) : submodule R M) = Inf {(s : submodule R M) | s ∈ S} := rfl @[simp] lemma Inf_coe (S : set (lie_submodule R L M)) : (↑(Inf S) : set M) = ⋂ s ∈ S, (s : set M) := begin rw [← lie_submodule.coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe], ext m, simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib], end lemma Inf_glb (S : set (lie_submodule R L M)) : is_glb S (Inf S) := begin have h : ∀ (N N' : lie_submodule R L M), (N : set M) ≤ N' ↔ N ≤ N', { intros, refl }, apply is_glb.of_image h, simp only [Inf_coe], exact is_glb_binfi end /-- The set of Lie submodules of a Lie module form a complete lattice. We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions than we would otherwise obtain from `complete_lattice_of_Inf`. -/ instance : complete_lattice (lie_submodule R L M) := { bot := ⊥, bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', }, top := ⊤, le_top := λ _ _ _, trivial, inf := (⊓), le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩, inf_le_left := λ _ _ _, and.left, inf_le_right := λ _ _ _, and.right, ..complete_lattice_of_Inf _ Inf_glb } instance : add_comm_monoid (lie_submodule R L M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm, } @[simp] lemma add_eq_sup : N + N' = N ⊔ N' := rfl @[norm_cast, simp] lemma sup_coe_to_submodule : (↑(N ⊔ N') : submodule R M) = (N : submodule R M) ⊔ (N' : submodule R M) := begin have aux : ∀ (x : L) m, m ∈ (N ⊔ N' : submodule R M) → ⁅x,m⁆ ∈ (N ⊔ N' : submodule R M), { simp only [submodule.mem_sup], rintro x m ⟨y, hy, z, hz, rfl⟩, refine ⟨⁅x, y⁆, N.lie_mem hy, ⁅x, z⁆, N'.lie_mem hz, (lie_add _ _ _).symm⟩ }, refine le_antisymm (Inf_le ⟨{ lie_mem := aux, ..(N ⊔ N' : submodule R M) }, _⟩) _, { simp only [exists_prop, and_true, mem_set_of_eq, eq_self_iff_true, coe_to_submodule_mk, ← coe_submodule_le_coe_submodule, and_self, le_sup_left, le_sup_right] }, { simp, }, end @[norm_cast, simp] lemma inf_coe_to_submodule : (↑(N ⊓ N') : submodule R M) = (N : submodule R M) ⊓ (N' : submodule R M) := rfl @[simp] lemma mem_inf (x : M) : x ∈ N ⊓ N' ↔ x ∈ N ∧ x ∈ N' := by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule, submodule.mem_inf] lemma mem_sup (x : M) : x ∈ N ⊔ N' ↔ ∃ (y ∈ N) (z ∈ N'), y + z = x := by { rw [← mem_coe_submodule, sup_coe_to_submodule, submodule.mem_sup], exact iff.rfl, } lemma eq_bot_iff : N = ⊥ ↔ ∀ (m : M), m ∈ N → m = 0 := by { rw eq_bot_iff, exact iff.rfl, } -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_bot : subsingleton (lie_submodule R L ↥(⊥ : lie_submodule R L M)) := begin apply subsingleton_of_bot_eq_top, ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx, simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot], end instance : is_modular_lattice (lie_submodule R L M) := { sup_inf_le_assoc_of_le := λ N₁ N₂ N₃, by { simp only [← coe_submodule_le_coe_submodule, sup_coe_to_submodule, inf_coe_to_submodule], exact is_modular_lattice.sup_inf_le_assoc_of_le ↑N₂, }, } variables (R L M) lemma well_founded_of_noetherian [is_noetherian R M] : well_founded ((>) : lie_submodule R L M → lie_submodule R L M → Prop) := begin let f : ((>) : lie_submodule R L M → lie_submodule R L M → Prop) →r ((>) : submodule R M → submodule R M → Prop) := { to_fun := coe, map_rel' := λ N N' h, h, }, apply f.well_founded, rw ← is_noetherian_iff_well_founded, apply_instance, end @[simp] lemma subsingleton_iff : subsingleton (lie_submodule R L M) ↔ subsingleton M := have h : subsingleton (lie_submodule R L M) ↔ subsingleton (submodule R M), { rw [← subsingleton_iff_bot_eq_top, ← subsingleton_iff_bot_eq_top, ← coe_to_submodule_eq_iff, top_coe_submodule, bot_coe_submodule], }, h.trans $ submodule.subsingleton_iff R @[simp] lemma nontrivial_iff : nontrivial (lie_submodule R L M) ↔ nontrivial M := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R L M).trans not_nontrivial_iff_subsingleton.symm) instance [nontrivial M] : nontrivial (lie_submodule R L M) := (nontrivial_iff R L M).mpr ‹_› variables {R L M} section inclusion_maps /-- The inclusion of a Lie submodule into its ambient space is a morphism of Lie modules. -/ def incl : N →ₗ⁅R,L⁆ M := { map_lie' := λ x m, rfl, ..submodule.subtype (N : submodule R M) } @[simp] lemma incl_apply (m : N) : N.incl m = m := rfl lemma incl_eq_val : (N.incl : N → M) = subtype.val := rfl variables {N N'} (h : N ≤ N') /-- Given two nested Lie submodules `N ⊆ N'`, the inclusion `N ↪ N'` is a morphism of Lie modules.-/ def hom_of_le : N →ₗ⁅R,L⁆ N' := { map_lie' := λ x m, rfl, ..submodule.of_le h } @[simp] lemma coe_hom_of_le (m : N) : (hom_of_le h m : M) = m := rfl lemma hom_of_le_apply (m : N) : hom_of_le h m = ⟨m.1, h m.2⟩ := rfl lemma hom_of_le_injective : function.injective (hom_of_le h) := λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe, subtype.val_eq_coe] end inclusion_maps section lie_span variables (R L) (s : set M) /-- The `lie_span` of a set `s ⊆ M` is the smallest Lie submodule of `M` that contains `s`. -/ def lie_span : lie_submodule R L M := Inf {N | s ⊆ N} variables {R L s} lemma mem_lie_span {x : M} : x ∈ lie_span R L s ↔ ∀ N : lie_submodule R L M, s ⊆ N → x ∈ N := by { change x ∈ (lie_span R L s : set M) ↔ _, erw Inf_coe, exact mem_bInter_iff, } lemma subset_lie_span : s ⊆ lie_span R L s := by { intros m hm, erw mem_lie_span, intros N hN, exact hN hm, } lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s := by { rw submodule.span_le, apply subset_lie_span, } lemma lie_span_le {N} : lie_span R L s ≤ N ↔ s ⊆ N := begin split, { exact subset.trans subset_lie_span, }, { intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, }, end lemma lie_span_mono {t : set M} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t := by { rw lie_span_le, exact subset.trans h subset_lie_span, } lemma lie_span_eq : lie_span R L (N : set M) = N := le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span lemma coe_lie_span_submodule_eq_iff {p : submodule R M} : (lie_span R L (p : set M) : submodule R M) = p ↔ ∃ (N : lie_submodule R L M), ↑N = p := begin rw p.exists_lie_submodule_coe_eq_iff L, split; intros h, { intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), }, { rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], }, end variables (R L M) /-- `lie_span` forms a Galois insertion with the coercion from `lie_submodule` to `set`. -/ protected def gi : galois_insertion (lie_span R L : set M → lie_submodule R L M) coe := { choice := λ s _, lie_span R L s, gc := λ s t, lie_span_le, le_l_u := λ s, subset_lie_span, choice_eq := λ s h, rfl } @[simp] lemma span_empty : lie_span R L (∅ : set M) = ⊥ := (lie_submodule.gi R L M).gc.l_bot @[simp] lemma span_univ : lie_span R L (set.univ : set M) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span variables {M} lemma span_union (s t : set M) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t := (lie_submodule.gi R L M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) := (lie_submodule.gi R L M).gc.l_supr end lie_span end lattice_structure end lie_submodule section lie_submodule_map_and_comap variables {R : Type u} {L : Type v} {L' : Type w₂} {M : Type w} {M' : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group M'] [module R M'] [lie_ring_module L M'] [lie_module R L M'] namespace lie_submodule variables (f : M →ₗ⁅R,L⁆ M') (N N₂ : lie_submodule R L M) (N' : lie_submodule R L M') /-- A morphism of Lie modules `f : M → M'` pushes forward Lie submodules of `M` to Lie submodules of `M'`. -/ def map : lie_submodule R L M' := { lie_mem := λ x m' h, by { rcases h with ⟨m, hm, hfm⟩, use ⁅x, m⁆, split, { apply N.lie_mem hm, }, { norm_cast at hfm, simp [hfm], }, }, ..(N : submodule R M).map (f : M →ₗ[R] M') } /-- A morphism of Lie modules `f : M → M'` pulls back Lie submodules of `M'` to Lie submodules of `M`. -/ def comap : lie_submodule R L M := { lie_mem := λ x m h, by { suffices : ⁅x, f m⁆ ∈ N', { simp [this], }, apply N'.lie_mem h, }, ..(N' : submodule R M').comap (f : M →ₗ[R] M') } variables {f N N₂ N'} lemma map_le_iff_le_comap : map f N ≤ N' ↔ N ≤ comap f N' := set.image_subset_iff variables (f) lemma gc_map_comap : galois_connection (map f) (comap f) := λ N N', map_le_iff_le_comap variables {f} @[simp] lemma map_sup : (N ⊔ N₂).map f = N.map f ⊔ N₂.map f := (gc_map_comap f).l_sup lemma mem_map (m' : M') : m' ∈ N.map f ↔ ∃ m, m ∈ N ∧ f m = m' := submodule.mem_map @[simp] lemma mem_comap {m : M} : m ∈ comap f N' ↔ f m ∈ N' := iff.rfl end lie_submodule namespace lie_ideal variables (f : L →ₗ⁅R⁆ L') (I I₂ : lie_ideal R L) (J : lie_ideal R L') @[simp] lemma top_coe_lie_subalgebra : ((⊤ : lie_ideal R L) : lie_subalgebra R L) = ⊤ := rfl /-- A morphism of Lie algebras `f : L → L'` pushes forward Lie ideals of `L` to Lie ideals of `L'`. Note that unlike `lie_submodule.map`, we must take the `lie_span` of the image. Mathematically this is because although `f` makes `L'` into a Lie module over `L`, in general the `L` submodules of `L'` are not the same as the ideals of `L'`. -/ def map : lie_ideal R L' := lie_submodule.lie_span R L' $ (I : submodule R L).map (f : L →ₗ[R] L') /-- A morphism of Lie algebras `f : L → L'` pulls back Lie ideals of `L'` to Lie ideals of `L`. Note that `f` makes `L'` into a Lie module over `L` (turning `f` into a morphism of Lie modules) and so this is a special case of `lie_submodule.comap` but we do not exploit this fact. -/ def comap : lie_ideal R L := { lie_mem := λ x y h, by { suffices : ⁅f x, f y⁆ ∈ J, { simp [this], }, apply J.lie_mem h, }, ..(J : submodule R L').comap (f : L →ₗ[R] L') } @[simp] lemma map_coe_submodule (h : ↑(map f I) = f '' I) : (map f I : submodule R L') = (I : submodule R L).map (f : L →ₗ[R] L') := by { rw [set_like.ext'_iff, lie_submodule.coe_to_submodule, h, submodule.map_coe], refl, } @[simp] lemma comap_coe_submodule : (comap f J : submodule R L) = (J : submodule R L').comap (f : L →ₗ[R] L') := rfl lemma map_le : map f I ≤ J ↔ f '' I ⊆ J := lie_submodule.lie_span_le variables {f I I₂ J} lemma mem_map {x : L} (hx : x ∈ I) : f x ∈ map f I := by { apply lie_submodule.subset_lie_span, use x, exact ⟨hx, rfl⟩, } @[simp] lemma mem_comap {x : L} : x ∈ comap f J ↔ f x ∈ J := iff.rfl lemma map_le_iff_le_comap : map f I ≤ J ↔ I ≤ comap f J := by { rw map_le, exact set.image_subset_iff, } variables (f) lemma gc_map_comap : galois_connection (map f) (comap f) := λ I I', map_le_iff_le_comap variables {f} @[simp] lemma map_sup : (I ⊔ I₂).map f = I.map f ⊔ I₂.map f := (gc_map_comap f).l_sup lemma map_comap_le : map f (comap f J) ≤ J := by { rw map_le_iff_le_comap, apply le_refl _, } /-- See also `lie_ideal.map_comap_eq`. -/ lemma comap_map_le : I ≤ comap f (map f I) := by { rw ← map_le_iff_le_comap, apply le_refl _, } @[mono] lemma map_mono : monotone (map f) := λ I₁ I₂ h, by { rw lie_submodule.le_def at h, apply lie_submodule.lie_span_mono (set.image_subset ⇑f h), } @[mono] lemma comap_mono : monotone (comap f) := λ J₁ J₂ h, by { rw lie_submodule.le_def at h ⊢, exact set.preimage_mono h, } lemma map_of_image (h : f '' I = J) : I.map f = J := begin apply le_antisymm, { erw [lie_submodule.lie_span_le, submodule.map_coe, h], }, { rw [lie_submodule.le_def, ← h], exact lie_submodule.subset_lie_span, }, end /-- Note that this is not a special case of `lie_submodule.subsingleton_of_bot`. Indeed, given `I : lie_ideal R L`, in general the two lattices `lie_ideal R I` and `lie_submodule R L I` are different (though the latter does naturally inject into the former). In other words, in general, ideals of `I`, regarded as a Lie algebra in its own right, are not the same as ideals of `L` contained in `I`. -/ -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_bot : subsingleton (lie_ideal R ↥(⊥ : lie_ideal R L)) := begin apply subsingleton_of_bot_eq_top, ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx, simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot], end end lie_ideal namespace lie_hom variables (f : L →ₗ⁅R⁆ L') (I : lie_ideal R L) (J : lie_ideal R L') /-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/ def ker : lie_ideal R L := lie_ideal.comap f ⊥ /-- The range of a morphism of Lie algebras as an ideal in the codomain. -/ def ideal_range : lie_ideal R L' := lie_submodule.lie_span R L' f.range lemma ideal_range_eq_lie_span_range : f.ideal_range = lie_submodule.lie_span R L' f.range := rfl lemma ideal_range_eq_map : f.ideal_range = lie_ideal.map f ⊤ := by { ext, simp only [ideal_range, range_eq_map], refl } /-- The condition that the image of a morphism of Lie algebras is an ideal. -/ def is_ideal_morphism : Prop := (f.ideal_range : lie_subalgebra R L') = f.range @[simp] lemma is_ideal_morphism_def : f.is_ideal_morphism ↔ (f.ideal_range : lie_subalgebra R L') = f.range := iff.rfl lemma is_ideal_morphism_iff : f.is_ideal_morphism ↔ ∀ (x : L') (y : L), ∃ (z : L), ⁅x, f y⁆ = f z := begin simp only [is_ideal_morphism_def, ideal_range_eq_lie_span_range, ← lie_subalgebra.coe_to_submodule_eq_iff, ← f.range.coe_to_submodule, lie_ideal.coe_to_lie_subalgebra_to_submodule, lie_submodule.coe_lie_span_submodule_eq_iff, lie_subalgebra.mem_coe_submodule, mem_range, exists_imp_distrib, submodule.exists_lie_submodule_coe_eq_iff], split, { intros h x y, obtain ⟨z, hz⟩ := h x (f y) y rfl, use z, exact hz.symm, }, { intros h x y z hz, obtain ⟨w, hw⟩ := h x z, use w, rw [← hw, hz], }, end lemma range_subset_ideal_range : (f.range : set L') ⊆ f.ideal_range := lie_submodule.subset_lie_span lemma map_le_ideal_range : I.map f ≤ f.ideal_range := begin rw f.ideal_range_eq_map, exact lie_ideal.map_mono le_top, end lemma ker_le_comap : f.ker ≤ J.comap f := lie_ideal.comap_mono bot_le @[simp] lemma ker_coe_submodule : (ker f : submodule R L) = (f : L →ₗ[R] L').ker := rfl @[simp] lemma mem_ker {x : L} : x ∈ ker f ↔ f x = 0 := show x ∈ (f.ker : submodule R L) ↔ _, by simp only [ker_coe_submodule, linear_map.mem_ker, coe_to_linear_map] lemma mem_ideal_range {x : L} : f x ∈ ideal_range f := begin rw ideal_range_eq_map, exact lie_ideal.mem_map (lie_submodule.mem_top x) end @[simp] lemma mem_ideal_range_iff (h : is_ideal_morphism f) {y : L'} : y ∈ ideal_range f ↔ ∃ (x : L), f x = y := begin rw f.is_ideal_morphism_def at h, rw [← lie_submodule.mem_coe, ← lie_ideal.coe_to_subalgebra, h, f.range_coe, set.mem_range], end lemma le_ker_iff : I ≤ f.ker ↔ ∀ x, x ∈ I → f x = 0 := begin split; intros h x hx, { specialize h hx, rw mem_ker at h, exact h, }, { rw mem_ker, apply h x hx, }, end lemma ker_eq_bot : f.ker = ⊥ ↔ function.injective f := by rw [← lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule, linear_map.ker_eq_bot, coe_to_linear_map] @[simp] lemma range_coe_submodule : (f.range : submodule R L') = (f : L →ₗ[R] L').range := rfl lemma range_eq_top : f.range = ⊤ ↔ function.surjective f := begin rw [← lie_subalgebra.coe_to_submodule_eq_iff, range_coe_submodule, lie_subalgebra.top_coe_submodule], exact linear_map.range_eq_top, end @[simp] lemma ideal_range_eq_top_of_surjective (h : function.surjective f) : f.ideal_range = ⊤ := begin rw ← f.range_eq_top at h, rw [ideal_range_eq_lie_span_range, h, ← lie_subalgebra.coe_to_submodule, ← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule, lie_subalgebra.top_coe_submodule, lie_submodule.coe_lie_span_submodule_eq_iff], use ⊤, exact lie_submodule.top_coe_submodule, end lemma is_ideal_morphism_of_surjective (h : function.surjective f) : f.is_ideal_morphism := by rw [is_ideal_morphism_def, f.ideal_range_eq_top_of_surjective h, f.range_eq_top.mpr h, lie_ideal.top_coe_lie_subalgebra] end lie_hom namespace lie_ideal variables {f : L →ₗ⁅R⁆ L'} {I : lie_ideal R L} {J : lie_ideal R L'} @[simp] lemma map_eq_bot_iff : I.map f = ⊥ ↔ I ≤ f.ker := by { rw ← le_bot_iff, exact lie_ideal.map_le_iff_le_comap } lemma coe_map_of_surjective (h : function.surjective f) : (I.map f : submodule R L') = (I : submodule R L).map (f : L →ₗ[R] L') := begin let J : lie_ideal R L' := { lie_mem := λ x y hy, begin have hy' : ∃ (x : L), x ∈ I ∧ f x = y, { simpa [hy], }, obtain ⟨z₂, hz₂, rfl⟩ := hy', obtain ⟨z₁, rfl⟩ := h x, simp only [lie_hom.coe_to_linear_map, set_like.mem_coe, set.mem_image, lie_submodule.mem_coe_submodule, submodule.mem_carrier, submodule.map_coe], use ⁅z₁, z₂⁆, exact ⟨I.lie_mem hz₂, f.map_lie z₁ z₂⟩, end, ..(I : submodule R L).map (f : L →ₗ[R] L'), }, erw lie_submodule.coe_lie_span_submodule_eq_iff, use J, apply lie_submodule.coe_to_submodule_mk, end lemma mem_map_of_surjective {y : L'} (h₁ : function.surjective f) (h₂ : y ∈ I.map f) : ∃ (x : I), f x = y := begin rw [← lie_submodule.mem_coe_submodule, coe_map_of_surjective h₁, submodule.mem_map] at h₂, obtain ⟨x, hx, rfl⟩ := h₂, use ⟨x, hx⟩, refl, end lemma bot_of_map_eq_bot {I : lie_ideal R L} (h₁ : function.injective f) (h₂ : I.map f = ⊥) : I = ⊥ := begin rw ← f.ker_eq_bot at h₁, change comap f ⊥ = ⊥ at h₁, rw [eq_bot_iff, map_le_iff_le_comap, h₁] at h₂, rw eq_bot_iff, exact h₂, end /-- Given two nested Lie ideals `I₁ ⊆ I₂`, the inclusion `I₁ ↪ I₂` is a morphism of Lie algebras. -/ def hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) : I₁ →ₗ⁅R⁆ I₂ := { map_lie' := λ x y, rfl, ..submodule.of_le h, } @[simp] lemma coe_hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) : (hom_of_le h x : L) = x := rfl lemma hom_of_le_apply {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) : hom_of_le h x = ⟨x.1, h x.2⟩ := rfl lemma hom_of_le_injective {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) : function.injective (hom_of_le h) := λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe, subtype.val_eq_coe] @[simp] lemma map_sup_ker_eq_map : lie_ideal.map f (I ⊔ f.ker) = lie_ideal.map f I := begin suffices : lie_ideal.map f (I ⊔ f.ker) ≤ lie_ideal.map f I, { exact le_antisymm this (lie_ideal.map_mono le_sup_left), }, apply lie_submodule.lie_span_mono, rintros x ⟨y, hy₁, hy₂⟩, rw ← hy₂, erw lie_submodule.mem_sup at hy₁, obtain ⟨z₁, hz₁, z₂, hz₂, hy⟩ := hy₁, rw ← hy, rw [f.coe_to_linear_map, f.map_add, f.mem_ker.mp hz₂, add_zero], exact ⟨z₁, hz₁, rfl⟩, end @[simp] lemma map_comap_eq (h : f.is_ideal_morphism) : map f (comap f J) = f.ideal_range ⊓ J := begin apply le_antisymm, { rw le_inf_iff, exact ⟨f.map_le_ideal_range _, map_comap_le⟩, }, { rw f.is_ideal_morphism_def at h, rw [lie_submodule.le_def, lie_submodule.inf_coe, ← coe_to_subalgebra, h], rintros y ⟨⟨x, h₁⟩, h₂⟩, rw ← h₁ at h₂ ⊢, exact mem_map h₂, }, end @[simp] lemma comap_map_eq (h : ↑(map f I) = f '' I) : comap f (map f I) = I ⊔ f.ker := by rw [← lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, I.map_coe_submodule f h, lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, submodule.comap_map_eq] variables (f I J) /-- Regarding an ideal `I` as a subalgebra, the inclusion map into its ambient space is a morphism of Lie algebras. -/ def incl : I →ₗ⁅R⁆ L := (I : lie_subalgebra R L).incl @[simp] lemma incl_range : I.incl.range = I := (I : lie_subalgebra R L).incl_range @[simp] lemma incl_apply (x : I) : I.incl x = x := rfl @[simp] lemma incl_coe : (I.incl : I →ₗ[R] L) = (I : submodule R L).subtype := rfl @[simp] lemma comap_incl_self : comap I.incl I = ⊤ := by { rw ← lie_submodule.coe_to_submodule_eq_iff, exact submodule.comap_subtype_self _, } @[simp] lemma ker_incl : I.incl.ker = ⊥ := by rw [← lie_submodule.coe_to_submodule_eq_iff, I.incl.ker_coe_submodule, lie_submodule.bot_coe_submodule, incl_coe, submodule.ker_subtype] @[simp] lemma incl_ideal_range : I.incl.ideal_range = I := begin rw [lie_hom.ideal_range_eq_lie_span_range, ← lie_subalgebra.coe_to_submodule, ← lie_submodule.coe_to_submodule_eq_iff, incl_range, coe_to_lie_subalgebra_to_submodule, lie_submodule.coe_lie_span_submodule_eq_iff], use I, end lemma incl_is_ideal_morphism : I.incl.is_ideal_morphism := begin rw [I.incl.is_ideal_morphism_def, incl_ideal_range], exact (I : lie_subalgebra R L).incl_range.symm, end end lie_ideal end lie_submodule_map_and_comap namespace lie_module_hom variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] variables (f : M →ₗ⁅R,L⁆ N) /-- The range of a morphism of Lie modules `f : M → N` is a Lie submodule of `N`. See Note [range copy pattern]. -/ def range : lie_submodule R L N := (lie_submodule.map f ⊤).copy (set.range f) set.image_univ.symm @[simp] lemma coe_range : (f.range : set N) = set.range f := rfl @[simp] lemma coe_submodule_range : (f.range : submodule R N) = (f : M →ₗ[R] N).range := rfl @[simp] lemma mem_range (n : N) : n ∈ f.range ↔ ∃ m, f m = n := iff.rfl lemma map_top : lie_submodule.map f ⊤ = f.range := by { ext, simp [lie_submodule.mem_map], } end lie_module_hom section top_equiv_self variables {R : Type u} {L : Type v} variables [comm_ring R] [lie_ring L] [lie_algebra R L] /-- The natural equivalence between the 'top' Lie subalgebra and the enclosing Lie algebra. -/ def lie_subalgebra.top_equiv_self : (⊤ : lie_subalgebra R L) ≃ₗ⁅R⁆ L := { inv_fun := λ x, ⟨x, set.mem_univ x⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, rfl, ..(⊤ : lie_subalgebra R L).incl, } @[simp] lemma lie_subalgebra.top_equiv_self_apply (x : (⊤ : lie_subalgebra R L)) : lie_subalgebra.top_equiv_self x = x := rfl /-- The natural equivalence between the 'top' Lie ideal and the enclosing Lie algebra. -/ def lie_ideal.top_equiv_self : (⊤ : lie_ideal R L) ≃ₗ⁅R⁆ L := lie_subalgebra.top_equiv_self @[simp] lemma lie_ideal.top_equiv_self_apply (x : (⊤ : lie_ideal R L)) : lie_ideal.top_equiv_self x = x := rfl end top_equiv_self
53c88f57d94752931077e3dae46b759d79d4b5ba
e83ddc62e2c86805ddf581443a41b664d72a40d5
/proofs/pigeonhole.lean
c8939f3f40f712dbc4871e74b60d5878459e24f6
[]
no_license
mdickinson/snippets
fcc3accedfd54389ea7c43af2309170128925e9b
9df4b78b1468aa5eaa7fe1ecc1c2e028e06b37de
refs/heads/master
1,661,582,598,170
1,643,576,064,000
1,643,576,064,000
150,001,812
3
3
null
null
null
null
UTF-8
Lean
false
false
8,626
lean
/- Attempt to prove some form of the pigeonhole principle in Lean. We prove two different versions; the first says that for any map f : fin n → ℕ with n ≥ 1, there's an element x of fin n such that f x ≥ m / n. The second says that for any map f : fin m → fin n, again with n ≥ 1, there's an element y of fin n such that the preimage of y has at least m/n elements. -/ /- Definitions of partial summation (up to a given m) and summation on fin n. -/ def partial_sum {n : ℕ} (m : ℕ) (m_le_n : m ≤ n) (f : fin n → ℕ) : ℕ := begin induction m with k ind_hyp, exact 0, exact ind_hyp (nat.le_of_succ_le m_le_n) + f ⟨k, m_le_n⟩, end def sum_of {n : ℕ} (f : fin n → ℕ) : ℕ := partial_sum n (nat.le_refl n) f /- Lemmas to help with unwinding the recursive partial_sum definition. -/ lemma partial_sum_zero {n : ℕ} (f : fin n → ℕ) : partial_sum 0 (nat.zero_le n) f = 0 := rfl lemma partial_sum_succ {n : ℕ} (m : ℕ) (succ_m_le_n : nat.succ m ≤ n) (f) : partial_sum (nat.succ m) succ_m_le_n f = partial_sum m (nat.le_of_succ_le succ_m_le_n) f + f ⟨ m, succ_m_le_n ⟩ := by rw partial_sum; refl /- Basic properties of partial_sum. -/ lemma partial_sum_eq {n m : ℕ} (m_le_n : m ≤ n) (f : fin n → ℕ) (g : fin n → ℕ) : (∀ x, f x = g x) → partial_sum m m_le_n f = partial_sum m m_le_n g := begin intro f_eq_g, induction m with k ind_hyp, refl, -- base case repeat {rw partial_sum_succ}, rw ind_hyp (nat.le_of_succ_le m_le_n), rw f_eq_g end lemma partial_sum_of_zero {n m : ℕ} (m_le_n : m ≤ n) : partial_sum m m_le_n (λ x, 0) = 0 := begin induction m with k ind_hyp, refl, -- base case repeat {rw partial_sum_succ}, rw ind_hyp (nat.le_of_succ_le m_le_n) end lemma partial_sum_of_add {n : ℕ} (m : ℕ) (m_le_n : m ≤ n) (f : fin n → ℕ) (g : fin n → ℕ) : partial_sum m m_le_n (λ x, f x + g x) = partial_sum m m_le_n f + partial_sum m m_le_n g := begin induction m with k ind_hyp, refl, -- base case repeat {rw partial_sum_succ}, rw ind_hyp (nat.le_of_succ_le m_le_n), simp, end lemma partial_sum_of_one {n m : ℕ} (m_le_n : m ≤ n) : partial_sum m m_le_n (λ x, 1) = m := begin induction m with k ind_hyp, refl, -- base case repeat {rw partial_sum_succ}, rw ind_hyp (nat.le_of_succ_le m_le_n) end lemma partial_sum_of_indicator {n : ℕ} (m : ℕ) (m_le_n : m ≤ n) (x : fin n) : partial_sum m m_le_n (λ y, if x = y then 1 else 0) = if x.val < m then 1 else 0 := begin induction m with k ind_hyp, refl, -- base case repeat {rw partial_sum_succ}, rw ind_hyp (nat.le_of_succ_le m_le_n), have take_vals : ite (x = (⟨k, m_le_n⟩ : fin n)) 1 0 = ite (x.val = k) 1 0, { cases nat.decidable_eq x.val k with x_ne_k x_eq_k, rw [if_neg, if_neg], exact x_ne_k, apply fin.ne_of_vne, exact x_ne_k, rw [if_pos, if_pos], exact x_eq_k, apply fin.eq_of_veq, exact x_eq_k, }, rw take_vals, cases lt_trichotomy x.val k with hlt heq_hgt, { -- x < k rw [if_pos, if_neg, if_pos], exact nat.lt_succ_of_lt hlt, exact ne_of_lt hlt, exact hlt }, cases heq_hgt with heq hgt, { -- x = k rw [if_neg, if_pos, if_pos]; rw heq, apply nat.lt_succ_self, apply nat.lt_irrefl }, { -- x > k rw [if_neg, if_neg, if_neg], intro lt_succ, have x_le_k : x.val ≤ k, { apply nat.le_of_lt_succ lt_succ, }, revert hgt, apply not_lt_of_ge, apply x_le_k, intro x_eq_k, revert hgt, rw x_eq_k, apply nat.lt_irrefl, apply not_lt_of_lt, apply hgt } end /- Helper for the induction step -/ lemma pigeonhole_ind_step {m S fm fx : ℕ} : 0 < m → S ≤ m * fx → nat.succ m * fm < S + fm → S + fm ≤ nat.succ m * fx := begin change nat.succ m with m + 1, intros m_pos ind_hyp h2, rw [add_mul, one_mul], apply add_le_add ind_hyp, apply le_of_mul_le_mul_left _ m_pos, apply le_trans _ ind_hyp, rw ← nat.add_le_add_iff_le_right fm, rw [add_mul, one_mul] at h2, exact nat.le_of_lt h2 end /- Version of the target statement for partial_sum, proved by induction -/ lemma pigeonhole_partial {n m : ℕ} (f : fin n → ℕ) : 1 ≤ m → ∀ (m_le_n : m ≤ n), exists x, partial_sum m m_le_n f ≤ m * f x := begin intro m_ge_1, induction m_ge_1 with k k_ge_1 induction_hypothesis, { -- base case m = 1 intro n_ge_1, existsi (⟨0, n_ge_1⟩ : fin n), rw partial_sum_succ, change 0 + f ⟨0, n_ge_1⟩ ≤ 1 * f ⟨0, n_ge_1⟩, simp, }, { -- induction step intro k_lt_n, -- either f k works, or it doesn't let top : fin n := ⟨ k, k_lt_n ⟩, cases nat.lt_or_ge (nat.succ k * f top) (partial_sum (nat.succ k) k_lt_n f) with top_not_ok top_ok, { -- top doesn't work; use the induction hypothesis cases induction_hypothesis (nat.le_of_succ_le k_lt_n) with x x_ok, existsi x, apply pigeonhole_ind_step k_ge_1 x_ok top_not_ok }, { -- top works! use it existsi top, exact top_ok } } end /- The main statement then follows immediately. -/ theorem pigeonhole_principle {n : ℕ} (n_pos : 1 ≤ n) (f : fin n → ℕ) : exists x : fin n, sum_of f ≤ n * f x := by apply pigeonhole_partial _ n_pos /- Alternative formulation: given a function f : fin m → fin n, there should be an element x of fin n whose preimage has at least m / n elements. But that means we need some way to count the size of the preimage. -/ lemma sum_of_indicator {n : ℕ} (fx : fin n) : sum_of (λ (y : fin n), if fx = y then 1 else 0) = 1 := begin rw sum_of, rw partial_sum_of_indicator n (nat.le_refl n) fx, rw if_pos, cases fx, exact fx_is_lt end lemma sum_of_zero {n : ℕ} : sum_of (λ x : fin n, 0) = 0 := partial_sum_of_zero _ lemma sum_of_add {n : ℕ} (f g : fin n → ℕ) : sum_of (λ x, f x + g x) = sum_of f + sum_of g := partial_sum_of_add _ _ _ _ lemma sum_of_one {n : ℕ} : sum_of (λ x : fin n, 1) = n := partial_sum_of_one _ lemma sum_of_equality {n : ℕ} (f g : fin n → ℕ) : (∀ x, f x = g x) → sum_of f = sum_of g := partial_sum_eq _ _ _ lemma partial_order_of_summation {m n k : ℕ} (k_le_m : k ≤ m) (f : fin m → fin n → nat) : partial_sum k k_le_m (λ x, sum_of (λ y, f x y)) = sum_of (λ y, partial_sum k k_le_m (λ x, f x y)) := begin induction k with k ind_hyp, { rw partial_sum_zero, apply sum_of_zero.symm }, { rename k_le_m succ_k_le_m, rw partial_sum_succ, have rhs : sum_of (λ y : fin n, partial_sum (nat.succ k) succ_k_le_m (λ x : fin m, f x y)) = sum_of (λ y : fin n, partial_sum k (nat.le_of_succ_le succ_k_le_m) (λ x : fin m, f x y) + f ⟨ k, _ ⟩ y), { apply sum_of_equality, intro y, rw partial_sum_succ }, rw rhs, rw ind_hyp (nat.le_of_succ_le succ_k_le_m), rw sum_of_add } end theorem order_of_summation {m n : ℕ} (f : fin m → fin n → nat) : sum_of (λ x : fin m, sum_of (λ y : fin n, f x y)) = sum_of (λ y : fin n, sum_of (λ x : fin m, f x y)) := begin apply partial_order_of_summation end /- the sizes of the preimages sum to the size of the domain -/ def preimage_size {m n : ℕ} (f : fin m → fin n) (y : fin n) : ℕ := sum_of (λ x, if f x = y then 1 else 0) lemma sum_of_preimage_size {m n : ℕ} (f : fin m → fin n) : sum_of (preimage_size f) = m := begin change sum_of (λ y, sum_of (λ x, if f x = y then 1 else 0)) = m, rw order_of_summation, have h : sum_of (λ (x : fin m), sum_of (λ (y : fin n), ite (f x = y) 1 0)) = sum_of (λ (x : fin m), 1), { apply sum_of_equality, intro x, apply sum_of_indicator }, rewrite h, apply sum_of_one end theorem pigeonhole_principle_bis {m n : ℕ} (n_pos : 1 ≤ n) (f : fin m → fin n) : exists y : fin n, m ≤ n * preimage_size f y := begin have preimage_sum := sum_of_preimage_size f, have pp1 := pigeonhole_principle n_pos (λ y : fin n, preimage_size f y), rw preimage_sum at pp1, exact pp1 end