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
2f3e373a312b299abe27e4e0e16a7d1b287145a8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/sigma/basic.lean
33637892d9fc49afa204e4b6c41637616489fa84
[ "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
10,130
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 meta.univs import tactic.lint import tactic.ext import logic.function.basic /-! # Sigma types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves basic results about sigma types. A sigma type is a dependent pair type. Like `α × β` but where the type of the second component depends on the first component. This can be seen as a generalization of the sum type `α ⊕ β`: * `α ⊕ β` is made of stuff which is either of type `α` or `β`. * Given `α : ι → Type*`, `sigma α` is made of stuff which is of type `α i` for some `i : ι`. One effectively recovers a type isomorphic to `α ⊕ β` by taking a `ι` with exactly two elements. See `equiv.sum_equiv_sigma_bool`. `Σ x, A x` is notation for `sigma A` (note the difference with the big operator `∑`). `Σ x y z ..., A x y z ...` is notation for `Σ x, Σ y, Σ z, ..., A x y z ...`. Here we have `α : Type*`, `β : α → Type*`, `γ : Π a : α, β a → Type*`, ..., `A : Π (a : α) (b : β a) (c : γ a b) ..., Type*` with `x : α` `y : β x`, `z : γ x y`, ... ## Notes The definition of `sigma` takes values in `Type*`. This effectively forbids `Prop`- valued sigma types. To that effect, we have `psigma`, which takes value in `Sort*` and carries a more complicated universe signature in consequence. -/ section sigma variables {α α₁ α₂ : Type*} {β : α → Type*} {β₁ : α₁ → Type*} {β₂ : α₂ → Type*} namespace sigma instance [inhabited α] [inhabited (β default)] : inhabited (sigma β) := ⟨⟨default, default⟩⟩ instance [h₁ : decidable_eq α] [h₂ : ∀a, decidable_eq (β a)] : decidable_eq (sigma β) | ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, is_true (eq.refl a) := match b₁, b₂, h₂ a b₁ b₂ with | _, _, is_true (eq.refl b) := is_true rfl | b₁, b₂, is_false n := is_false (assume h, sigma.no_confusion h (λe₁ e₂, n $ eq_of_heq e₂)) end | a₁, _, a₂, _, is_false n := is_false (assume h, sigma.no_confusion h (λe₁ e₂, n e₁)) end @[simp, nolint simp_nf] -- sometimes the built-in injectivity support does not work theorem mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : sigma.mk a₁ b₁ = ⟨a₂, b₂⟩ ↔ (a₁ = a₂ ∧ b₁ == b₂) := by simp @[simp] theorem eta : ∀ x : Σ a, β a, sigma.mk x.1 x.2 = x | ⟨i, x⟩ := rfl @[ext] lemma ext {x₀ x₁ : sigma β} (h₀ : x₀.1 = x₁.1) (h₁ : x₀.2 == x₁.2) : x₀ = x₁ := by { cases x₀, cases x₁, cases h₀, cases h₁, refl } lemma ext_iff {x₀ x₁ : sigma β} : x₀ = x₁ ↔ x₀.1 = x₁.1 ∧ x₀.2 == x₁.2 := by { cases x₀, cases x₁, exact sigma.mk.inj_iff } /-- A specialized ext lemma for equality of sigma types over an indexed subtype. -/ @[ext] lemma subtype_ext {β : Type*} {p : α → β → Prop} : ∀ {x₀ x₁ : Σ a, subtype (p a)}, x₀.fst = x₁.fst → (x₀.snd : β) = x₁.snd → x₀ = x₁ | ⟨a₀, b₀, hb₀⟩ ⟨a₁, b₁, hb₁⟩ rfl rfl := rfl lemma subtype_ext_iff {β : Type*} {p : α → β → Prop} {x₀ x₁ : Σ a, subtype (p a)} : x₀ = x₁ ↔ x₀.fst = x₁.fst ∧ (x₀.snd : β) = x₁.snd := ⟨λ h, h ▸ ⟨rfl, rfl⟩, λ ⟨h₁, h₂⟩, subtype_ext h₁ h₂⟩ @[simp] theorem «forall» {p : (Σ a, β a) → Prop} : (∀ x, p x) ↔ (∀ a b, p ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem «exists» {p : (Σ a, β a) → Prop} : (∃ x, p x) ↔ (∃ a b, p ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ /-- Map the left and right components of a sigma -/ def map (f₁ : α₁ → α₂) (f₂ : Πa, β₁ a → β₂ (f₁ a)) (x : sigma β₁) : sigma β₂ := ⟨f₁ x.1, f₂ x.1 x.2⟩ end sigma lemma sigma_mk_injective {i : α} : function.injective (@sigma.mk α β i) | _ _ rfl := rfl lemma function.injective.sigma_map {f₁ : α₁ → α₂} {f₂ : Πa, β₁ a → β₂ (f₁ a)} (h₁ : function.injective f₁) (h₂ : ∀ a, function.injective (f₂ a)) : function.injective (sigma.map f₁ f₂) | ⟨i, x⟩ ⟨j, y⟩ h := begin obtain rfl : i = j, from h₁ (sigma.mk.inj_iff.mp h).1, obtain rfl : x = y, from h₂ i (sigma_mk_injective h), refl end lemma function.injective.of_sigma_map {f₁ : α₁ → α₂} {f₂ : Πa, β₁ a → β₂ (f₁ a)} (h : function.injective (sigma.map f₁ f₂)) (a : α₁) : function.injective (f₂ a) := λ x y hxy, sigma_mk_injective $ @h ⟨a, x⟩ ⟨a, y⟩ (sigma.ext rfl (heq_iff_eq.2 hxy)) lemma function.injective.sigma_map_iff {f₁ : α₁ → α₂} {f₂ : Πa, β₁ a → β₂ (f₁ a)} (h₁ : function.injective f₁) : function.injective (sigma.map f₁ f₂) ↔ ∀ a, function.injective (f₂ a) := ⟨λ h, h.of_sigma_map, h₁.sigma_map⟩ lemma function.surjective.sigma_map {f₁ : α₁ → α₂} {f₂ : Πa, β₁ a → β₂ (f₁ a)} (h₁ : function.surjective f₁) (h₂ : ∀ a, function.surjective (f₂ a)) : function.surjective (sigma.map f₁ f₂) := begin simp only [function.surjective, sigma.forall, h₁.forall], exact λ i, (h₂ _).forall.2 (λ x, ⟨⟨i, x⟩, rfl⟩) end /-- Interpret a function on `Σ x : α, β x` as a dependent function with two arguments. This also exists as an `equiv` as `equiv.Pi_curry γ`. -/ def sigma.curry {γ : Π a, β a → Type*} (f : Π x : sigma β, γ x.1 x.2) (x : α) (y : β x) : γ x y := f ⟨x,y⟩ /-- Interpret a dependent function with two arguments as a function on `Σ x : α, β x`. This also exists as an `equiv` as `(equiv.Pi_curry γ).symm`. -/ def sigma.uncurry {γ : Π a, β a → Type*} (f : Π x (y : β x), γ x y) (x : sigma β) : γ x.1 x.2 := f x.1 x.2 @[simp] lemma sigma.uncurry_curry {γ : Π a, β a → Type*} (f : Π x : sigma β, γ x.1 x.2) : sigma.uncurry (sigma.curry f) = f := funext $ λ ⟨i, j⟩, rfl @[simp] lemma sigma.curry_uncurry {γ : Π a, β a → Type*} (f : Π x (y : β x), γ x y) : sigma.curry (sigma.uncurry f) = f := rfl /-- Convert a product type to a Σ-type. -/ def prod.to_sigma {α β} (p : α × β) : Σ _ : α, β := ⟨p.1, p.2⟩ @[simp] lemma prod.fst_comp_to_sigma {α β} : sigma.fst ∘ @prod.to_sigma α β = prod.fst := rfl @[simp] lemma prod.fst_to_sigma {α β} (x : α × β) : (prod.to_sigma x).fst = x.fst := rfl @[simp] lemma prod.snd_to_sigma {α β} (x : α × β) : (prod.to_sigma x).snd = x.snd := rfl @[simp] lemma prod.to_sigma_mk {α β} (x : α) (y : β) : (x, y).to_sigma = ⟨x, y⟩ := rfl -- we generate this manually as `@[derive has_reflect]` fails @[instance] protected meta def {u v} sigma.reflect [reflected_univ.{u}] [reflected_univ.{v}] {α : Type u} (β : α → Type v) [reflected _ α] [reflected _ β] [hα : has_reflect α] [hβ : Π i, has_reflect (β i)] : has_reflect (Σ a, β a) := λ ⟨a, b⟩, (by reflect_name : reflected _ @sigma.mk.{u v}).subst₄ `(α) `(β) `(a) `(b) end sigma section psigma variables {α : Sort*} {β : α → Sort*} namespace psigma /-- Nondependent eliminator for `psigma`. -/ def elim {γ} (f : ∀ a, β a → γ) (a : psigma β) : γ := psigma.cases_on a f @[simp] theorem elim_val {γ} (f : ∀ a, β a → γ) (a b) : psigma.elim f ⟨a, b⟩ = f a b := rfl instance [inhabited α] [inhabited (β default)] : inhabited (psigma β) := ⟨⟨default, default⟩⟩ instance [h₁ : decidable_eq α] [h₂ : ∀a, decidable_eq (β a)] : decidable_eq (psigma β) | ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, is_true (eq.refl a) := match b₁, b₂, h₂ a b₁ b₂ with | _, _, is_true (eq.refl b) := is_true rfl | b₁, b₂, is_false n := is_false (assume h, psigma.no_confusion h (λe₁ e₂, n $ eq_of_heq e₂)) end | a₁, _, a₂, _, is_false n := is_false (assume h, psigma.no_confusion h (λe₁ e₂, n e₁)) end theorem mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : @psigma.mk α β a₁ b₁ = @psigma.mk α β a₂ b₂ ↔ (a₁ = a₂ ∧ b₁ == b₂) := iff.intro psigma.mk.inj $ assume ⟨h₁, h₂⟩, match a₁, a₂, b₁, b₂, h₁, h₂ with _, _, _, _, eq.refl a, heq.refl b := rfl end @[ext] lemma ext {x₀ x₁ : psigma β} (h₀ : x₀.1 = x₁.1) (h₁ : x₀.2 == x₁.2) : x₀ = x₁ := by { cases x₀, cases x₁, cases h₀, cases h₁, refl } lemma ext_iff {x₀ x₁ : psigma β} : x₀ = x₁ ↔ x₀.1 = x₁.1 ∧ x₀.2 == x₁.2 := by { cases x₀, cases x₁, exact psigma.mk.inj_iff } @[simp] theorem «forall» {p : (Σ' a, β a) → Prop} : (∀ x, p x) ↔ (∀ a b, p ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem «exists» {p : (Σ' a, β a) → Prop} : (∃ x, p x) ↔ (∃ a b, p ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ /-- A specialized ext lemma for equality of psigma types over an indexed subtype. -/ @[ext] lemma subtype_ext {β : Sort*} {p : α → β → Prop} : ∀ {x₀ x₁ : Σ' a, subtype (p a)}, x₀.fst = x₁.fst → (x₀.snd : β) = x₁.snd → x₀ = x₁ | ⟨a₀, b₀, hb₀⟩ ⟨a₁, b₁, hb₁⟩ rfl rfl := rfl lemma subtype_ext_iff {β : Sort*} {p : α → β → Prop} {x₀ x₁ : Σ' a, subtype (p a)} : x₀ = x₁ ↔ x₀.fst = x₁.fst ∧ (x₀.snd : β) = x₁.snd := ⟨λ h, h ▸ ⟨rfl, rfl⟩, λ ⟨h₁, h₂⟩, subtype_ext h₁ h₂⟩ variables {α₁ : Sort*} {α₂ : Sort*} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} /-- Map the left and right components of a sigma -/ def map (f₁ : α₁ → α₂) (f₂ : Πa, β₁ a → β₂ (f₁ a)) : psigma β₁ → psigma β₂ | ⟨a, b⟩ := ⟨f₁ a, f₂ a b⟩ end psigma end psigma
6b953e4e3d1ac928069bd1ac5a35a7c704553128
43d840497673d50aaf1058dc851b1edc51d1ab11
/src/solutions/friday/topology.lean
1578801f24e8e508a8eb4c102b1c96f1f7c39626
[]
permissive
dhruva-divate/lftcm2020
6606bc857204fbfd8ab92812060c0e5114f67e0d
d2e1a31a4ad280eadef1d0ae6a89920b7345c823
refs/heads/master
1,668,432,237,346
1,594,377,206,000
1,594,377,206,000
278,630,020
0
0
MIT
1,594,384,713,000
1,594,384,712,000
null
UTF-8
Lean
false
false
15,667
lean
import topology.metric_space.basic open_locale classical filter topological_space namespace lftcm open filter set /-! # Filters ## Definition of filters -/ def principal {α : Type*} (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := begin -- sorry tauto, -- sorry end, sets_of_superset := begin -- sorry intros U V hU hUV, tauto, -- sorry end, inter_sets := begin -- sorry rintros U V hU hV, intros x xs, split ; tauto, -- sorry end} def at_top : filter ℕ := { sets := {s | ∃ a, ∀ b, a ≤ b → b ∈ s}, univ_sets := begin -- sorry use 42, finish, -- sorry end, sets_of_superset := begin -- sorry rintros U V ⟨N, hN⟩ hUV, use N, tauto, -- sorry end, inter_sets := begin -- sorry rintros U V ⟨N, hN⟩ ⟨N', hN'⟩, use max N N', intros b hb, rw max_le_iff at hb, split ; tauto, -- sorry end} -- The next exercise is slightly more tricky, you should probably keep it for later def nhds (x : ℝ) : filter ℝ := { sets := {s | ∃ ε > 0, Ioo (x - ε) (x + ε) ⊆ s}, univ_sets := begin -- sorry use 42⁻¹, split, norm_num, tauto, -- sorry end, sets_of_superset := begin -- sorry rintros U V ⟨ε, hε⟩ hUV, use ε, tauto, -- sorry end, inter_sets := begin -- sorry rintros U V ⟨ε, hε, hU⟩ ⟨ε', hε', hV⟩, use [min ε ε', lt_min hε hε'], intros b hb, rw mem_Ioo at hb, split, { apply hU, split ; linarith [min_le_left ε ε'] }, { apply hV, split ; linarith [min_le_right ε ε'] }, -- sorry end} /- The filter axiom are also available as standalone lemmas where the filter argument is implicit Compare -/ #check @filter.sets_of_superset #check @mem_sets_of_superset -- And analogously: #check @inter_mem_sets /-! ## Definition of "tends to" -/ -- We'll practive using tendsto by reproving the composition lemma `tendsto.comp` from mathlib -- Let's first use the concrete definition recorded by `tendsto_def` #check @tendsto_def #check @preimage_comp example {α β γ : Type*} {A : filter α} {B : filter β} {C : filter γ} {f : α → β} {g : β → γ} (hf : tendsto f A B) (hg : tendsto g B C) : tendsto (g ∘ f) A C := begin -- sorry rw tendsto_def at *, intros U U_in, rw preimage_comp, apply hf, apply hg, assumption, -- sorry end -- Now let's get functorial (same statement as above, different proof packaging). example {α β γ : Type*} {A : filter α} {B : filter β} {C : filter γ} {f : α → β} {g : β → γ} (hf : tendsto f A B) (hg : tendsto g B C) : tendsto (g ∘ f) A C := begin calc map (g ∘ f) A = map g (map f A) : _ ... ≤ map g B : _ ... ≤ C : _, -- sorry { apply map_map }, { exact map_mono hf /- or simply: mono -/ }, { exact hg } -- sorry end /- Let's now focus on the pull-back operation `filter.comap` which takes `f : X → Y` and a filter `G` on `Y` and returns a filter on `X`. -/ #check @mem_comap_sets -- this is by definition, the proof is `iff.rfl` -- It also help to record a special case of one implication: #check @preimage_mem_comap -- The following exercise, which reproves `comap_ne_bot_iff` can start using #check @forall_sets_nonempty_iff_ne_bot example {α β : Type*} {f : filter β} {m : α → β} : comap m f ≠ ⊥ ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin -- sorry rw ← forall_sets_nonempty_iff_ne_bot, split ; intro h, { intros t t_in, exact h (m ⁻¹' t) ⟨t, t_in, subset.refl _⟩, }, { rintros s ⟨u, u_in, hu⟩, cases h u u_in with x hx, exact ⟨x, hu hx⟩ }, -- sorry end /-! ## Properties holding eventually -/ /-- The next exercise only needs the definition of filters and the fact that `∀ᶠ x in f, p x` is a notation for `{x | p x} ∈ f`. It is called `eventually_and` in mathlib, and won't be needed below. For instance, applied to `α = ℕ` and the `at_top` filter above, it says that, given two predicates `p` and `q` on natural numbers, p n and q n for n large enough if and only if p n holds for n large enough and q n holds for n large enough. -/ example {α : Type*} {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := begin -- sorry split, { intro h, split, { apply mem_sets_of_superset h, intros x x_in, exact x_in.1 }, { apply mem_sets_of_superset h, intros x x_in, exact x_in.2 } }, { intros h, exact f.inter_sets h.1 h.2, }, -- sorry end /-! ## Topological spaces -/ section -- This is how we can talk about two topological spaces X and Y variables {X Y : Type*} [topological_space X] [topological_space Y] /- Given a topological space `X` and some `A : set X`, we have the usual zoo of predicates `is_open A`, `is_closed A`, `is_connected A`, `compact A` (and some more) There are also additional type classes referring to properties of `X` itself, like `compact_space X` or `connected_space X` -/ /-- We can talk about continuous functions from `X` to `Y` -/ example (f : X → Y) : continuous f ↔ ∀ V, is_open V → is_open (f ⁻¹' V) := iff.rfl /- Each point `x` of a topological space has a neighborhood filter `𝓝 x` made of sets containing an open set containing `x`. It is always a proper filter, as recorded by `nhds_ne_bot` Asking for continuity is the same as asking for continuity at each point the right-hand side below is known as `continuous_at f x` -/ example (f : X → Y) : continuous f ↔ ∀ x, tendsto f (𝓝 x) (𝓝 (f x)) := continuous_iff_continuous_at /- The topological structure also brings operations on sets. To each `A : set X`, we can associate `closure A`, `interior A` and `frontier A`. We'll focus on `closure A`. It is defined as the intersection of closed sets containing `A` but we can characterize it in terms of neighborhoods. The most concrete version is `mem_closure_iff_nhds : a ∈ closure A ↔ ∀ B ∈ 𝓝 a, (B ∩ A).nonempty` We'll pratice by reproving the slightly more abstract `mem_closure_iff_comap_ne_bot`. First let's review sets and subtypes. Fix a type `X` and recall that `A : set X` is not a type a priori, but Lean coerces automatically when needed to the type `↥A` whose terms are build of a term `x : X` and a proof of `x ∈ A`. In the other direction, inhabitants of `↥A` can be coerced to `X` automatically. This inclusion coercion map is called `coe : A → X` and `coe a` is also denoted by `↑a`. Now assume `X` is a topological space, and let's understand the closure of A in terms of `coe` and the neighborhood filter. In the next exercise, you can use `simp_rw` instead of `rw` to rewrite inside a quantifier -/ #check nonempty_inter_iff_exists_right example {A : set X} {x : X} : x ∈ closure A ↔ comap (coe : A → X) (𝓝 x) ≠ ⊥ := begin -- sorry simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, nonempty_inter_iff_exists_right], -- sorry end /- In elementary contexts, the main property of `closure A` is that a converging sequence `u : ℕ → X` such that `∀ n, u n ∈ A` has its limit in `closure A`. Note we don't need all the full sequence to be in `A`, it's enough to ask it for `n` large enough, ie. `∀ᶠ n in at_top, u n ∈ A`. Also there is no reason to use sequences only, we can use any map and any source filter. We hence have the important `mem_closure_of_tendsto` : ∀ {f : β → X} {F : filter β} {a : X} {A : set X}, F ≠ ⊥ → tendsto f F (𝓝 a) → (∀ᶠ x in F, f x ∈ A) → a ∈ closure A If `A` is known to be closed then we can replace `closure A` by `A`, this is `mem_of_closed_of_tendsto`. -/ /- We need one last piece of filter technology: bases. By definition, each neighborhood of a point `x` contains an *open* neighborhood of `x`. Hence we can often restrict our attention to such neighborhoods. The general definition recording such a situation is: `has_basis` (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t) You can now inspect three examples of how bases allow to restrict attention to certain elements of a filter. -/ #check @has_basis.mem_iff #check @has_basis.tendsto_left_iff #check @has_basis.tendsto_right_iff -- We'll use the following bases: #check @nhds_basis_opens' #check @closed_nhds_basis /-- Our main goal is now to prove the basic theorem which allows extension by continuity. From Bourbaki's general topology book, I.8.5, Theorem 1 (taking only the non-trivial implication): Let `X` be a topological space, `A` a dense subset of `X`, `f : A → Y` a mapping of `A` into a regular space `Y`. If, for each `x` in `X`, `f(y)` tends to a limit in `Y` when `y` tends to `x` while remaining in `A` then there exists a continuous extension `φ` of `f` to `X`. The regularity assumption on `Y` ensures that each point of `Y` has a basis of *closed* neighborhoods, this is `closed_nhds_basis`. It also ensures that `Y` is Hausdorff so limits in `Y` are unique, this is `tendsto_nhds_unique`. mathlib contains a refinement of the above lemma, `dense_inducing.continuous_at_extend`, but we'll stick to Bourbaki's version here. Remember that, given `A : set X`, `↥A` is the subtype associated to `A`, and Lean will automatically insert that funny up arrow when needed. And the (inclusion) coercion map is `coe : A → X`. The assumption "tends to `x` while remaining in `A`" corresponds to the pull-back filter `comap coe (𝓝 x)`. Let's prove first an auxilliary lemma, extracted to simplify the context (in particular we don't need Y to be a topological space here). -/ lemma aux {X Y A : Type*} [topological_space X] {c : A → X} {f : A → Y} {x : X} {F : filter Y} (h : tendsto f (comap c (𝓝 x)) F) {V' : set Y} (V'_in : V' ∈ F) : ∃ V ∈ 𝓝 x, is_open V ∧ c ⁻¹' V ⊆ f ⁻¹' V' := begin -- sorry simpa [and_assoc] using ((nhds_basis_opens' x).comap c).tendsto_left_iff.mp h V' V'_in -- sorry end /-- Let's now turn to the main proof of the extension by continuity theorem. When Lean needs a topology on `↥A` it will use the induced topology, thanks to the instance `subtype.topological_space`. This all happens automatically. The only relevant lemma is `nhds_induced coe : ∀ a : ↥A, 𝓝 a = comap coe (𝓝 ↑a)` (this is actually a general lemma about induced topologies). The proof outline is: The main assumption and the axiom of choice give a function `φ` such that `∀ x, tendsto f (comap coe $ 𝓝 x) (𝓝 (φ x))` (because `Y` is Hausdorff, `φ` is entirely determined, but we won't need that until we try to prove that `φ` indeed extends `f`). Let's first prove `φ` is continuous. Fix any `x : X`. Since `Y` is regular, it suffices to check that for every *closed* neighborhood `V'` of `φ x`, `φ ⁻¹' V' ∈ 𝓝 x`. The limit assumption gives (through the auxilliary lemma above) some `V ∈ 𝓝 x` such `is_open V ∧ coe ⁻¹' V ⊆ f ⁻¹' V'`. Since `V ∈ 𝓝 x`, it suffices to prove `V ⊆ φ ⁻¹' V'`, ie `∀ y ∈ V, φ y ∈ V'`. Let's fix `y` in `V`. Because `V` is *open*, it is a neighborhood of `y`. In particular `coe ⁻¹' V ∈ comap coe (𝓝 y)` and a fortiori `f ⁻¹' V' ∈ comap coe (𝓝 y)`. In addition `comap coe $ 𝓝 y ≠ ⊥` because `A` is dense. Because we know `tendsto f (comap coe $ 𝓝 y) (𝓝 (φ y))` this implies `φ y ∈ closure V'` and, since `V'` is closed, we have proved `φ y ∈ V'`. It remains to prove that `φ` extends `f`. This is were continuity of `f` enters the discussion, together with the fact that `Y` is Hausdorff. -/ example [regular_space Y] {A : set X} (hA : ∀ x, x ∈ closure A) {f : A → Y} (f_cont : continuous f) (hf : ∀ x : X, ∃ c : Y, tendsto f (comap coe $ 𝓝 x) $ 𝓝 c) : ∃ φ : X → Y, continuous φ ∧ ∀ a : A, φ a = f a := begin -- sorry choose φ hφ using hf, use φ, split, { rw continuous_iff_continuous_at, intros x, suffices : ∀ V' ∈ 𝓝 (φ x), is_closed V' → φ ⁻¹' V' ∈ 𝓝 x, by simpa [continuous_at, (closed_nhds_basis _).tendsto_right_iff], intros V' V'_in V'_closed, obtain ⟨V, V_in, V_op, hV⟩ : ∃ V ∈ 𝓝 x, is_open V ∧ coe ⁻¹' V ⊆ f ⁻¹' V', { exact aux (hφ x) V'_in }, suffices : ∀ y ∈ V, φ y ∈ V', from mem_sets_of_superset V_in this, intros y y_in, have hVx : V ∈ 𝓝 y := mem_nhds_sets V_op y_in, apply mem_of_closed_of_tendsto _ (hφ y) V'_closed, { exact mem_sets_of_superset (preimage_mem_comap hVx) hV }, { simpa [mem_closure_iff_comap_ne_bot] using hA y } }, { intros a, have lim : tendsto f (𝓝 a) (𝓝 $ φ a), by simpa [nhds_induced] using hφ a, exact tendsto_nhds_unique nhds_ne_bot lim f_cont.continuous_at }, -- sorry end end /-! ## Metric spaces -/ /-- We now leave general topology and turn to metric spaces. The distance function is denoted by `dist`. A slight difficulty here is that, as in Bourbaki, many results you may expect to see stated for metric spaces are stated for uniform spaces, a more general notion that also includes topological groups. In this tutorial we will avoid uniform spaces for simplicity. We will prove that continuous functions from a compact metric space to a metric space are uniformly continuous. mathlib has a much more general version (about functions between uniform spaces...). The lemma `metric.uniform_continuous_iff` allows to translate the general definition of uniform continuity to the ε-δ definition that works for metric spaces only. So let's fix `ε > 0` and start looking for `δ`. We will deduce Heine-Cantor from the fact that a real value continuous function on a nonempty compact set reaches its infimum. There are several ways to state that, but here we recommend `compact.exists_forall_le`. Let `φ : X × X → ℝ := λ p, dist (f p.1) (f p.2)` and let `K := { p : X × X | ε ≤ φ p }`. Observe `φ` is continuous by assumption on `f` and using `continuous_dist`. And `K` is closed using `is_closed_le` hence compact since `X` is compact. Then we discuss two possibilities using `eq_empty_or_nonempty`. If `K` is empty then we are clearly done (we can set `δ = 1` for instance). So let's assume `K` is not empty, and choose `(x₀, x₁)` attaining the infimum of `φ` on `K`. We can then set `δ = dist x₀ x₁` and check everything works. -/ example {X : Type*} [metric_space X] [compact_space X] {Y : Type*} [metric_space Y] {f : X → Y} (hf : continuous f) : uniform_continuous f := begin -- sorry rw metric.uniform_continuous_iff, intros ε ε_pos, let φ : X × X → ℝ := λ p, dist (f p.1) (f p.2), have φ_cont : continuous φ := continuous_dist.comp (hf.prod_map hf), let K := { p : X × X | ε ≤ φ p }, have K_closed : is_closed K := is_closed_le continuous_const φ_cont, have K_cpct : compact K := K_closed.compact, cases eq_empty_or_nonempty K with hK hK, { use [1, by norm_num], intros x y hxy, have : (x, y) ∉ K, by simp [hK], simpa [K] }, { rcases K_cpct.exists_forall_le hK continuous_dist.continuous_on with ⟨⟨x₀, x₁⟩, xx_in, H⟩, use dist x₀ x₁, split, { change _ < _, rw dist_pos, intro h, have : ε ≤ 0, by simpa [*] using xx_in, linarith }, { intros x x', contrapose!, intros hxx', linarith [H (x, x') hxx'] } }, -- sorry end end lftcm
4b7b25231333b9777568867ee5bc076fc9dc683e
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/quaternion.lean
89f29d218d274875f7cb5e29becdc748e21c8924
[ "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
22,404
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import tactic.ring_exp import algebra.algebra.basic import algebra.opposites import data.equiv.ring /-! # Quaternions In this file we define quaternions `ℍ[R]` over a commutative ring `R`, and define some algebraic structures on `ℍ[R]`. ## Main definitions * `quaternion_algebra R a b`, `ℍ[R, a, b]` : [quaternion algebra](https://en.wikipedia.org/wiki/Quaternion_algebra) with coefficients `a`, `b` * `quaternion R`, `ℍ[R]` : the space of quaternions, a.k.a. `quaternion_algebra R (-1) (-1)`; * `quaternion.norm_sq` : square of the norm of a quaternion; * `quaternion.conj` : conjugate of a quaternion; We also define the following algebraic structures on `ℍ[R]`: * `ring ℍ[R, a, b]` and `algebra R ℍ[R, a, b]` : for any commutative ring `R`; * `ring ℍ[R]` and `algebra R ℍ[R]` : for any commutative ring `R`; * `domain ℍ[R]` : for a linear ordered commutative ring `R`; * `division_algebra ℍ[R]` : for a linear ordered field `R`. ## Notation The following notation is available with `open_locale quaternion`. * `ℍ[R, c₁, c₂]` : `quaternion_algebra R c₁ c₂` * `ℍ[R]` : quaternions over `R`. ## Implementation notes We define quaternions over any ring `R`, not just `ℝ` to be able to deal with, e.g., integer or rational quaternions without using real numbers. In particular, all definitions in this file are computable. ## Tags quaternion -/ /-- Quaternion algebra over a type with fixed coefficients $a=i^2$ and $b=j^2$. Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/ @[nolint unused_arguments, ext] structure quaternion_algebra (R : Type*) (a b : R) := mk {} :: (re : R) (im_i : R) (im_j : R) (im_k : R) localized "notation `ℍ[` R`,` a`,` b `]` := quaternion_algebra R a b" in quaternion namespace quaternion_algebra @[simp] lemma mk.eta {R : Type*} {c₁ c₂} : ∀ a : ℍ[R, c₁, c₂], mk a.1 a.2 a.3 a.4 = a | ⟨a₁, a₂, a₃, a₄⟩ := rfl variables {R : Type*} [comm_ring R] {c₁ c₂ : R} (r x y z : R) (a b c : ℍ[R, c₁, c₂]) instance : has_coe_t R (ℍ[R, c₁, c₂]) := ⟨λ x, ⟨x, 0, 0, 0⟩⟩ @[simp] lemma coe_re : (x : ℍ[R, c₁, c₂]).re = x := rfl @[simp] lemma coe_im_i : (x : ℍ[R, c₁, c₂]).im_i = 0 := rfl @[simp] lemma coe_im_j : (x : ℍ[R, c₁, c₂]).im_j = 0 := rfl @[simp] lemma coe_im_k : (x : ℍ[R, c₁, c₂]).im_k = 0 := rfl lemma coe_injective : function.injective (coe : R → ℍ[R, c₁, c₂]) := λ x y h, congr_arg re h @[simp] lemma coe_inj {x y : R} : (x : ℍ[R, c₁, c₂]) = y ↔ x = y := coe_injective.eq_iff @[simps] instance : has_zero ℍ[R, c₁, c₂] := ⟨⟨0, 0, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_zero : ((0 : R) : ℍ[R, c₁, c₂]) = 0 := rfl instance : inhabited ℍ[R, c₁, c₂] := ⟨0⟩ @[simps] instance : has_one ℍ[R, c₁, c₂] := ⟨⟨1, 0, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_one : ((1 : R) : ℍ[R, c₁, c₂]) = 1 := rfl @[simps] instance : has_add ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4⟩⟩ @[simp] lemma mk_add_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) + mk b₁ b₂ b₃ b₄ = mk (a₁ + b₁) (a₂ + b₂) (a₃ + b₃) (a₄ + b₄) := rfl @[simps] instance : has_neg ℍ[R, c₁, c₂] := ⟨λ a, ⟨-a.1, -a.2, -a.3, -a.4⟩⟩ @[simp] lemma neg_mk (a₁ a₂ a₃ a₄ : R) : -(mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) = ⟨-a₁, -a₂, -a₃, -a₄⟩ := rfl @[simps] instance : has_sub ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 - b.1, a.2 - b.2, a.3 - b.3, a.4 - b.4⟩⟩ @[simp] lemma mk_sub_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) - mk b₁ b₂ b₃ b₄ = mk (a₁ - b₁) (a₂ - b₂) (a₃ - b₃) (a₄ - b₄) := rfl /-- Multiplication is given by * `1 * x = x * 1 = x`; * `i * i = c₁`; * `j * j = c₂`; * `i * j = k`, `j * i = -k`; * `k * k = -c₁ * c₂`; * `i * k = c₁ * j`, `k * i = `-c₁ * j`; * `j * k = -c₂ * i`, `k * j = c₂ * i`. -/ @[simps] instance : has_mul ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 * b.1 + c₁ * a.2 * b.2 + c₂ * a.3 * b.3 - c₁ * c₂ * a.4 * b.4, a.1 * b.2 + a.2 * b.1 - c₂ * a.3 * b.4 + c₂ * a.4 * b.3, a.1 * b.3 + c₁ * a.2 * b.4 + a.3 * b.1 - c₁ * a.4 * b.2, a.1 * b.4 + a.2 * b.3 - a.3 * b.2 + a.4 * b.1⟩⟩ @[simp] lemma mk_mul_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) * mk b₁ b₂ b₃ b₄ = ⟨a₁ * b₁ + c₁ * a₂ * b₂ + c₂ * a₃ * b₃ - c₁ * c₂ * a₄ * b₄, a₁ * b₂ + a₂ * b₁ - c₂ * a₃ * b₄ + c₂ * a₄ * b₃, a₁ * b₃ + c₁ * a₂ * b₄ + a₃ * b₁ - c₁ * a₄ * b₂, a₁ * b₄ + a₂ * b₃ - a₃ * b₂ + a₄ * b₁⟩ := rfl instance : ring ℍ[R, c₁, c₂] := by refine_struct { add := (+), zero := (0 : ℍ[R, c₁, c₂]), neg := has_neg.neg, sub := has_sub.sub, mul := (*), one := 1, nsmul := @nsmul_rec _ ⟨(0 : ℍ[R, c₁, c₂])⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨(0 : ℍ[R, c₁, c₂])⟩ ⟨(+)⟩ ⟨has_neg.neg⟩, npow := @npow_rec _ ⟨(1 : ℍ[R, c₁, c₂])⟩ ⟨(*)⟩ }; intros; try { refl }; ext; simp; ring_exp instance : algebra R ℍ[R, c₁, c₂] := { smul := λ r a, ⟨r * a.1, r * a.2, r * a.3, r * a.4⟩, to_fun := coe, map_one' := rfl, map_zero' := rfl, map_mul' := λ x y, by ext; simp, map_add' := λ x y, by ext; simp, smul_def' := λ r x, by ext; simp, commutes' := λ r x, by ext; simp [mul_comm] } @[simp] lemma smul_re : (r • a).re = r • a.re := rfl @[simp] lemma smul_im_i : (r • a).im_i = r • a.im_i := rfl @[simp] lemma smul_im_j : (r • a).im_j = r • a.im_j := rfl @[simp] lemma smul_im_k : (r • a).im_k = r • a.im_k := rfl @[simp] lemma smul_mk (re im_i im_j im_k : R) : r • (⟨re, im_i, im_j, im_k⟩ : ℍ[R, c₁, c₂]) = ⟨r • re, r • im_i, r • im_j, r • im_k⟩ := rfl lemma algebra_map_eq (r : R) : algebra_map R ℍ[R,c₁,c₂] r = ⟨r, 0, 0, 0⟩ := rfl section variables (R c₁ c₂) /-- `quaternion_algebra.re` as a `linear_map`-/ @[simps] def re_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := re, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_i` as a `linear_map`-/ @[simps] def im_i_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_i, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_j` as a `linear_map`-/ @[simps] def im_j_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_j, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_k` as a `linear_map`-/ @[simps] def im_k_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_k, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } end @[norm_cast, simp] lemma coe_add : ((x + y : R) : ℍ[R, c₁, c₂]) = x + y := (algebra_map R ℍ[R, c₁, c₂]).map_add x y @[norm_cast, simp] lemma coe_sub : ((x - y : R) : ℍ[R, c₁, c₂]) = x - y := (algebra_map R ℍ[R, c₁, c₂]).map_sub x y @[norm_cast, simp] lemma coe_neg : ((-x : R) : ℍ[R, c₁, c₂]) = -x := (algebra_map R ℍ[R, c₁, c₂]).map_neg x @[norm_cast, simp] lemma coe_mul : ((x * y : R) : ℍ[R, c₁, c₂]) = x * y := (algebra_map R ℍ[R, c₁, c₂]).map_mul x y lemma coe_commutes : ↑r * a = a * r := algebra.commutes r a lemma coe_commute : commute ↑r a := coe_commutes r a lemma coe_mul_eq_smul : ↑r * a = r • a := (algebra.smul_def r a).symm lemma mul_coe_eq_smul : a * r = r • a := by rw [← coe_commutes, coe_mul_eq_smul] @[norm_cast, simp] lemma coe_algebra_map : ⇑(algebra_map R ℍ[R, c₁, c₂]) = coe := rfl lemma smul_coe : x • (y : ℍ[R, c₁, c₂]) = ↑(x * y) := by rw [coe_mul, coe_mul_eq_smul] /-- Quaternion conjugate. -/ def conj : ℍ[R, c₁, c₂] ≃ₗ[R] ℍ[R, c₁, c₂] := linear_equiv.of_involutive { to_fun := λ a, ⟨a.1, -a.2, -a.3, -a.4⟩, map_add' := λ a b, by ext; simp [neg_add], map_smul' := λ r a, by ext; simp } $ λ a, by simp @[simp] lemma re_conj : (conj a).re = a.re := rfl @[simp] lemma im_i_conj : (conj a).im_i = - a.im_i := rfl @[simp] lemma im_j_conj : (conj a).im_j = - a.im_j := rfl @[simp] lemma im_k_conj : (conj a).im_k = - a.im_k := rfl @[simp] lemma conj_mk (a₁ a₂ a₃ a₄ : R) : conj (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) = ⟨a₁, -a₂, -a₃, -a₄⟩ := rfl @[simp] lemma conj_conj : a.conj.conj = a := ext _ _ rfl (neg_neg _) (neg_neg _) (neg_neg _) lemma conj_add : (a + b).conj = a.conj + b.conj := conj.map_add a b @[simp] lemma conj_mul : (a * b).conj = b.conj * a.conj := by ext; simp; ring_exp lemma conj_conj_mul : (a.conj * b).conj = b.conj * a := by rw [conj_mul, conj_conj] lemma conj_mul_conj : (a * b.conj).conj = b * a.conj := by rw [conj_mul, conj_conj] lemma self_add_conj' : a + a.conj = ↑(2 * a.re) := by ext; simp [two_mul] lemma self_add_conj : a + a.conj = 2 * a.re := by simp only [self_add_conj', two_mul, coe_add] lemma conj_add_self' : a.conj + a = ↑(2 * a.re) := by rw [add_comm, self_add_conj'] lemma conj_add_self : a.conj + a = 2 * a.re := by rw [add_comm, self_add_conj] lemma conj_eq_two_re_sub : a.conj = ↑(2 * a.re) - a := eq_sub_iff_add_eq.2 a.conj_add_self' lemma commute_conj_self : commute a.conj a := begin rw [a.conj_eq_two_re_sub], exact (coe_commute (2 * a.re) a).sub_left (commute.refl a) end lemma commute_self_conj : commute a a.conj := a.commute_conj_self.symm lemma commute_conj_conj {a b : ℍ[R, c₁, c₂]} (h : commute a b) : commute a.conj b.conj := calc a.conj * b.conj = (b * a).conj : (conj_mul b a).symm ... = (a * b).conj : by rw h.eq ... = b.conj * a.conj : conj_mul a b @[simp] lemma conj_coe : conj (x : ℍ[R, c₁, c₂]) = x := by ext; simp lemma conj_smul : conj (r • a) = r • conj a := conj.map_smul r a @[simp] lemma conj_one : conj (1 : ℍ[R, c₁, c₂]) = 1 := conj_coe 1 lemma eq_re_of_eq_coe {a : ℍ[R, c₁, c₂]} {x : R} (h : a = x) : a = a.re := by rw [h, coe_re] lemma eq_re_iff_mem_range_coe {a : ℍ[R, c₁, c₂]} : a = a.re ↔ a ∈ set.range (coe : R → ℍ[R, c₁, c₂]) := ⟨λ h, ⟨a.re, h.symm⟩, λ ⟨x, h⟩, eq_re_of_eq_coe h.symm⟩ @[simp] lemma conj_fixed {R : Type*} [comm_ring R] [no_zero_divisors R] [char_zero R] {c₁ c₂ : R} {a : ℍ[R, c₁, c₂]} : conj a = a ↔ a = a.re := by simp [ext_iff, neg_eq_iff_add_eq_zero, add_self_eq_zero] -- Can't use `rw ← conj_fixed` in the proof without additional assumptions lemma conj_mul_eq_coe : conj a * a = (conj a * a).re := by ext; simp; ring_exp lemma mul_conj_eq_coe : a * conj a = (a * conj a).re := by { rw a.commute_self_conj.eq, exact a.conj_mul_eq_coe } lemma conj_zero : conj (0 : ℍ[R, c₁, c₂]) = 0 := conj.map_zero lemma conj_neg : (-a).conj = -a.conj := (conj : ℍ[R, c₁, c₂] ≃ₗ[R] _).map_neg a lemma conj_sub : (a - b).conj = a.conj - b.conj := (conj : ℍ[R, c₁, c₂] ≃ₗ[R] _).map_sub a b instance : star_ring ℍ[R, c₁, c₂] := { star := conj, star_involutive := conj_conj, star_add := conj_add, star_mul := conj_mul } @[simp] lemma star_def (a : ℍ[R, c₁, c₂]) : star a = conj a := rfl open opposite /-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/ def conj_ae : ℍ[R, c₁, c₂] ≃ₐ[R] (ℍ[R, c₁, c₂]ᵒᵖ) := { to_fun := op ∘ conj, inv_fun := conj ∘ unop, map_mul' := λ x y, by simp, commutes' := λ r, by simp, .. conj.to_add_equiv.trans op_add_equiv } @[simp] lemma coe_conj_ae : ⇑(conj_ae : ℍ[R, c₁, c₂] ≃ₐ[R] _) = op ∘ conj := rfl end quaternion_algebra /-- Space of quaternions over a type. Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/ def quaternion (R : Type*) [has_one R] [has_neg R] := quaternion_algebra R (-1) (-1) localized "notation `ℍ[` R `]` := quaternion R" in quaternion namespace quaternion variables {R : Type*} [comm_ring R] (r x y z : R) (a b c : ℍ[R]) export quaternion_algebra (re im_i im_j im_k) instance : has_coe_t R ℍ[R] := quaternion_algebra.has_coe_t instance : ring ℍ[R] := quaternion_algebra.ring instance : inhabited ℍ[R] := quaternion_algebra.inhabited instance : algebra R ℍ[R] := quaternion_algebra.algebra instance : star_ring ℍ[R] := quaternion_algebra.star_ring @[ext] lemma ext : a.re = b.re → a.im_i = b.im_i → a.im_j = b.im_j → a.im_k = b.im_k → a = b := quaternion_algebra.ext a b lemma ext_iff {a b : ℍ[R]} : a = b ↔ a.re = b.re ∧ a.im_i = b.im_i ∧ a.im_j = b.im_j ∧ a.im_k = b.im_k := quaternion_algebra.ext_iff a b @[simp, norm_cast] lemma coe_re : (x : ℍ[R]).re = x := rfl @[simp, norm_cast] lemma coe_im_i : (x : ℍ[R]).im_i = 0 := rfl @[simp, norm_cast] lemma coe_im_j : (x : ℍ[R]).im_j = 0 := rfl @[simp, norm_cast] lemma coe_im_k : (x : ℍ[R]).im_k = 0 := rfl @[simp] lemma zero_re : (0 : ℍ[R]).re = 0 := rfl @[simp] lemma zero_im_i : (0 : ℍ[R]).im_i = 0 := rfl @[simp] lemma zero_im_j : (0 : ℍ[R]).im_j = 0 := rfl @[simp] lemma zero_im_k : (0 : ℍ[R]).im_k = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : R) : ℍ[R]) = 0 := rfl @[simp] lemma one_re : (1 : ℍ[R]).re = 1 := rfl @[simp] lemma one_im_i : (1 : ℍ[R]).im_i = 0 := rfl @[simp] lemma one_im_j : (1 : ℍ[R]).im_j = 0 := rfl @[simp] lemma one_im_k : (1 : ℍ[R]).im_k = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : R) : ℍ[R]) = 1 := rfl @[simp] lemma add_re : (a + b).re = a.re + b.re := rfl @[simp] lemma add_im_i : (a + b).im_i = a.im_i + b.im_i := rfl @[simp] lemma add_im_j : (a + b).im_j = a.im_j + b.im_j := rfl @[simp] lemma add_im_k : (a + b).im_k = a.im_k + b.im_k := rfl @[simp, norm_cast] lemma coe_add : ((x + y : R) : ℍ[R]) = x + y := quaternion_algebra.coe_add x y @[simp] lemma neg_re : (-a).re = -a.re := rfl @[simp] lemma neg_im_i : (-a).im_i = -a.im_i := rfl @[simp] lemma neg_im_j : (-a).im_j = -a.im_j := rfl @[simp] lemma neg_im_k : (-a).im_k = -a.im_k := rfl @[simp, norm_cast] lemma coe_neg : ((-x : R) : ℍ[R]) = -x := quaternion_algebra.coe_neg x @[simp] lemma sub_re : (a - b).re = a.re - b.re := rfl @[simp] lemma sub_im_i : (a - b).im_i = a.im_i - b.im_i := rfl @[simp] lemma sub_im_j : (a - b).im_j = a.im_j - b.im_j := rfl @[simp] lemma sub_im_k : (a - b).im_k = a.im_k - b.im_k := rfl @[simp, norm_cast] lemma coe_sub : ((x - y : R) : ℍ[R]) = x - y := quaternion_algebra.coe_sub x y @[simp] lemma mul_re : (a * b).re = a.re * b.re - a.im_i * b.im_i - a.im_j * b.im_j - a.im_k * b.im_k := (quaternion_algebra.has_mul_mul_re a b).trans $ by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_i : (a * b).im_i = a.re * b.im_i + a.im_i * b.re + a.im_j * b.im_k - a.im_k * b.im_j := (quaternion_algebra.has_mul_mul_im_i a b).trans $ by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_j : (a * b).im_j = a.re * b.im_j - a.im_i * b.im_k + a.im_j * b.re + a.im_k * b.im_i := (quaternion_algebra.has_mul_mul_im_j a b).trans $ by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_k : (a * b).im_k = a.re * b.im_k + a.im_i * b.im_j - a.im_j * b.im_i + a.im_k * b.re := (quaternion_algebra.has_mul_mul_im_k a b).trans $ by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg] @[simp, norm_cast] lemma coe_mul : ((x * y : R) : ℍ[R]) = x * y := quaternion_algebra.coe_mul x y lemma coe_injective : function.injective (coe : R → ℍ[R]) := quaternion_algebra.coe_injective @[simp] lemma coe_inj {x y : R} : (x : ℍ[R]) = y ↔ x = y := coe_injective.eq_iff @[simp] lemma smul_re : (r • a).re = r • a.re := rfl @[simp] lemma smul_im_i : (r • a).im_i = r • a.im_i := rfl @[simp] lemma smul_im_j : (r • a).im_j = r • a.im_j := rfl @[simp] lemma smul_im_k : (r • a).im_k = r • a.im_k := rfl lemma coe_commutes : ↑r * a = a * r := quaternion_algebra.coe_commutes r a lemma coe_commute : commute ↑r a := quaternion_algebra.coe_commute r a lemma coe_mul_eq_smul : ↑r * a = r • a := quaternion_algebra.coe_mul_eq_smul r a lemma mul_coe_eq_smul : a * r = r • a := quaternion_algebra.mul_coe_eq_smul r a @[simp] lemma algebra_map_def : ⇑(algebra_map R ℍ[R]) = coe := rfl lemma smul_coe : x • (y : ℍ[R]) = ↑(x * y) := quaternion_algebra.smul_coe x y /-- Quaternion conjugate. -/ def conj : ℍ[R] ≃ₗ[R] ℍ[R] := quaternion_algebra.conj @[simp] lemma conj_re : a.conj.re = a.re := rfl @[simp] lemma conj_im_i : a.conj.im_i = - a.im_i := rfl @[simp] lemma conj_im_j : a.conj.im_j = - a.im_j := rfl @[simp] lemma conj_im_k : a.conj.im_k = - a.im_k := rfl @[simp] lemma conj_conj : a.conj.conj = a := a.conj_conj @[simp] lemma conj_add : (a + b).conj = a.conj + b.conj := a.conj_add b @[simp] lemma conj_mul : (a * b).conj = b.conj * a.conj := a.conj_mul b lemma conj_conj_mul : (a.conj * b).conj = b.conj * a := a.conj_conj_mul b lemma conj_mul_conj : (a * b.conj).conj = b * a.conj := a.conj_mul_conj b lemma self_add_conj' : a + a.conj = ↑(2 * a.re) := a.self_add_conj' lemma self_add_conj : a + a.conj = 2 * a.re := a.self_add_conj lemma conj_add_self' : a.conj + a = ↑(2 * a.re) := a.conj_add_self' lemma conj_add_self : a.conj + a = 2 * a.re := a.conj_add_self lemma conj_eq_two_re_sub : a.conj = ↑(2 * a.re) - a := a.conj_eq_two_re_sub lemma commute_conj_self : commute a.conj a := a.commute_conj_self lemma commute_self_conj : commute a a.conj := a.commute_self_conj lemma commute_conj_conj {a b : ℍ[R]} (h : commute a b) : commute a.conj b.conj := quaternion_algebra.commute_conj_conj h alias commute_conj_conj ← commute.quaternion_conj @[simp] lemma conj_coe : conj (x : ℍ[R]) = x := quaternion_algebra.conj_coe x @[simp] lemma conj_smul : conj (r • a) = r • conj a := a.conj_smul r @[simp] lemma conj_one : conj (1 : ℍ[R]) = 1 := conj_coe 1 lemma eq_re_of_eq_coe {a : ℍ[R]} {x : R} (h : a = x) : a = a.re := quaternion_algebra.eq_re_of_eq_coe h lemma eq_re_iff_mem_range_coe {a : ℍ[R]} : a = a.re ↔ a ∈ set.range (coe : R → ℍ[R]) := quaternion_algebra.eq_re_iff_mem_range_coe @[simp] lemma conj_fixed {R : Type*} [comm_ring R] [no_zero_divisors R] [char_zero R] {a : ℍ[R]} : conj a = a ↔ a = a.re := quaternion_algebra.conj_fixed lemma conj_mul_eq_coe : conj a * a = (conj a * a).re := a.conj_mul_eq_coe lemma mul_conj_eq_coe : a * conj a = (a * conj a).re := a.mul_conj_eq_coe @[simp] lemma conj_zero : conj (0:ℍ[R]) = 0 := quaternion_algebra.conj_zero @[simp] lemma conj_neg : (-a).conj = -a.conj := a.conj_neg @[simp] lemma conj_sub : (a - b).conj = a.conj - b.conj := a.conj_sub b open opposite /-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/ def conj_ae : ℍ[R] ≃ₐ[R] (ℍ[R]ᵒᵖ) := quaternion_algebra.conj_ae @[simp] lemma coe_conj_ae : ⇑(conj_ae : ℍ[R] ≃ₐ[R] ℍ[R]ᵒᵖ) = op ∘ conj := rfl /-- Square of the norm. -/ def norm_sq : monoid_with_zero_hom ℍ[R] R := { to_fun := λ a, (a * a.conj).re, map_zero' := by rw [conj_zero, zero_mul, zero_re], map_one' := by rw [conj_one, one_mul, one_re], map_mul' := λ x y, coe_injective $ by conv_lhs { rw [← mul_conj_eq_coe, conj_mul, mul_assoc, ← mul_assoc y, y.mul_conj_eq_coe, coe_commutes, ← mul_assoc, x.mul_conj_eq_coe, ← coe_mul] } } lemma norm_sq_def : norm_sq a = (a * a.conj).re := rfl lemma norm_sq_def' : norm_sq a = a.1^2 + a.2^2 + a.3^2 + a.4^2 := by simp only [norm_sq_def, sq, ← neg_mul_eq_mul_neg, sub_neg_eq_add, mul_re, conj_re, conj_im_i, conj_im_j, conj_im_k] lemma norm_sq_coe : norm_sq (x : ℍ[R]) = x^2 := by rw [norm_sq_def, conj_coe, ← coe_mul, coe_re, sq] @[simp] lemma norm_sq_neg : norm_sq (-a) = norm_sq a := by simp only [norm_sq_def, conj_neg, neg_mul_neg] lemma self_mul_conj : a * a.conj = norm_sq a := by rw [mul_conj_eq_coe, norm_sq_def] lemma conj_mul_self : a.conj * a = norm_sq a := by rw [← a.commute_self_conj.eq, self_mul_conj] lemma coe_norm_sq_add : (norm_sq (a + b) : ℍ[R]) = norm_sq a + a * b.conj + b * a.conj + norm_sq b := by simp [← self_mul_conj, mul_add, add_mul, add_assoc] end quaternion namespace quaternion variables {R : Type*} section linear_ordered_comm_ring variables [linear_ordered_comm_ring R] {a : ℍ[R]} @[simp] lemma norm_sq_eq_zero : norm_sq a = 0 ↔ a = 0 := begin refine ⟨λ h, _, λ h, h.symm ▸ norm_sq.map_zero⟩, rw [norm_sq_def', add_eq_zero_iff', add_eq_zero_iff', add_eq_zero_iff'] at h, exact ext a 0 (pow_eq_zero h.1.1.1) (pow_eq_zero h.1.1.2) (pow_eq_zero h.1.2) (pow_eq_zero h.2), all_goals { apply_rules [sq_nonneg, add_nonneg] } end lemma norm_sq_ne_zero : norm_sq a ≠ 0 ↔ a ≠ 0 := not_congr norm_sq_eq_zero @[simp] lemma norm_sq_nonneg : 0 ≤ norm_sq a := by { rw norm_sq_def', apply_rules [sq_nonneg, add_nonneg] } @[simp] lemma norm_sq_le_zero : norm_sq a ≤ 0 ↔ a = 0 := by simpa only [le_antisymm_iff, norm_sq_nonneg, and_true] using @norm_sq_eq_zero _ _ a instance : nontrivial ℍ[R] := { exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩, } instance : is_domain ℍ[R] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b hab, have norm_sq a * norm_sq b = 0, by rwa [← norm_sq.map_mul, norm_sq_eq_zero], (eq_zero_or_eq_zero_of_mul_eq_zero this).imp norm_sq_eq_zero.1 norm_sq_eq_zero.1, ..quaternion.nontrivial, } end linear_ordered_comm_ring section field variables [linear_ordered_field R] (a b : ℍ[R]) @[simps { attrs := [] }]instance : has_inv ℍ[R] := ⟨λ a, (norm_sq a)⁻¹ • a.conj⟩ instance : division_ring ℍ[R] := { inv := has_inv.inv, inv_zero := by rw [has_inv_inv, conj_zero, smul_zero], mul_inv_cancel := λ a ha, by rw [has_inv_inv, algebra.mul_smul_comm, self_mul_conj, smul_coe, inv_mul_cancel (norm_sq_ne_zero.2 ha), coe_one], .. quaternion.nontrivial, .. quaternion.ring } @[simp] lemma norm_sq_inv : norm_sq a⁻¹ = (norm_sq a)⁻¹ := monoid_with_zero_hom.map_inv norm_sq _ @[simp] lemma norm_sq_div : norm_sq (a / b) = norm_sq a / norm_sq b := monoid_with_zero_hom.map_div norm_sq a b end field end quaternion
47cc8cac05606958f583b6ef593cf79c9a95fa00
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/continuous_function/polynomial.lean
a9c7142e3f834ea43bd3801ea547a8fccf5dfa23
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,292
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.algebra.polynomial import topology.continuous_function.algebra import topology.unit_interval /-! # Constructions relating polynomial functions and continuous functions. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `polynomial.to_continuous_map_on p X`: for `X : set R`, interprets a polynomial `p` as a bundled continuous function in `C(X, R)`. * `polynomial.to_continuous_map_on_alg_hom`: the same, as an `R`-algebra homomorphism. * `polynomial_functions (X : set R) : subalgebra R C(X, R)`: polynomial functions as a subalgebra. * `polynomial_functions_separates_points (X : set R) : (polynomial_functions X).separates_points`: the polynomial functions separate points. -/ variables {R : Type*} open_locale polynomial namespace polynomial section variables [semiring R] [topological_space R] [topological_semiring R] /-- Every polynomial with coefficients in a topological semiring gives a (bundled) continuous function. -/ @[simps] def to_continuous_map (p : R[X]) : C(R, R) := ⟨λ x : R, p.eval x, by continuity⟩ /-- A polynomial as a continuous function, with domain restricted to some subset of the semiring of coefficients. (This is particularly useful when restricting to compact sets, e.g. `[0,1]`.) -/ @[simps] def to_continuous_map_on (p : R[X]) (X : set R) : C(X, R) := ⟨λ x : X, p.to_continuous_map x, by continuity⟩ -- TODO some lemmas about when `to_continuous_map_on` is injective? end section variables {α : Type*} [topological_space α] [comm_semiring R] [topological_space R] [topological_semiring R] @[simp] lemma aeval_continuous_map_apply (g : R[X]) (f : C(α, R)) (x : α) : ((polynomial.aeval f) g) x = g.eval (f x) := begin apply polynomial.induction_on' g, { intros p q hp hq, simp [hp, hq], }, { intros n a, simp [pi.pow_apply], }, end end section noncomputable theory variables [comm_semiring R] [topological_space R] [topological_semiring R] /-- The algebra map from `R[X]` to continuous functions `C(R, R)`. -/ @[simps] def to_continuous_map_alg_hom : R[X] →ₐ[R] C(R, R) := { to_fun := λ p, p.to_continuous_map, map_zero' := by { ext, simp, }, map_add' := by { intros, ext, simp, }, map_one' := by { ext, simp, }, map_mul' := by { intros, ext, simp, }, commutes' := by { intros, ext, simp [algebra.algebra_map_eq_smul_one], }, } /-- The algebra map from `R[X]` to continuous functions `C(X, R)`, for any subset `X` of `R`. -/ @[simps] def to_continuous_map_on_alg_hom (X : set R) : R[X] →ₐ[R] C(X, R) := { to_fun := λ p, p.to_continuous_map_on X, map_zero' := by { ext, simp, }, map_add' := by { intros, ext, simp, }, map_one' := by { ext, simp, }, map_mul' := by { intros, ext, simp, }, commutes' := by { intros, ext, simp [algebra.algebra_map_eq_smul_one], }, } end end polynomial section variables [comm_semiring R] [topological_space R] [topological_semiring R] /-- The subalgebra of polynomial functions in `C(X, R)`, for `X` a subset of some topological semiring `R`. -/ def polynomial_functions (X : set R) : subalgebra R C(X, R) := (⊤ : subalgebra R R[X]).map (polynomial.to_continuous_map_on_alg_hom X) @[simp] lemma polynomial_functions_coe (X : set R) : (polynomial_functions X : set C(X, R)) = set.range (polynomial.to_continuous_map_on_alg_hom X) := by { ext, simp [polynomial_functions], } -- TODO: -- if `f : R → R` is an affine equivalence, then pulling back along `f` -- induces a normed algebra isomorphism between `polynomial_functions X` and -- `polynomial_functions (f ⁻¹' X)`, intertwining the pullback along `f` of `C(R, R)` to itself. lemma polynomial_functions_separates_points (X : set R) : (polynomial_functions X).separates_points := λ x y h, begin -- We use `polynomial.X`, then clean up. refine ⟨_, ⟨⟨_, ⟨⟨polynomial.X, ⟨algebra.mem_top, rfl⟩⟩, rfl⟩⟩, _⟩⟩, dsimp, simp only [polynomial.eval_X], exact (λ h', h (subtype.ext h')), end open_locale unit_interval open continuous_map /-- The preimage of polynomials on `[0,1]` under the pullback map by `x ↦ (b-a) * x + a` is the polynomials on `[a,b]`. -/ lemma polynomial_functions.comap_comp_right_alg_hom_Icc_homeo_I (a b : ℝ) (h : a < b) : (polynomial_functions I).comap (comp_right_alg_hom ℝ ℝ (Icc_homeo_I a b h).symm.to_continuous_map) = polynomial_functions (set.Icc a b) := begin ext f, fsplit, { rintro ⟨p, ⟨-,w⟩⟩, rw fun_like.ext_iff at w, dsimp at w, let q := p.comp ((b - a)⁻¹ • polynomial.X + polynomial.C (-a * (b-a)⁻¹)), refine ⟨q, ⟨_, _⟩⟩, { simp, }, { ext x, simp only [neg_mul, ring_hom.map_neg, ring_hom.map_mul, alg_hom.coe_to_ring_hom, polynomial.eval_X, polynomial.eval_neg, polynomial.eval_C, polynomial.eval_smul, smul_eq_mul, polynomial.eval_mul, polynomial.eval_add, polynomial.coe_aeval_eq_eval, polynomial.eval_comp, polynomial.to_continuous_map_on_alg_hom_apply, polynomial.to_continuous_map_on_apply, polynomial.to_continuous_map_apply], convert w ⟨_, _⟩; clear w, { -- why does `comm_ring.add` appear here!? change x = (Icc_homeo_I a b h).symm ⟨_ + _, _⟩, ext, simp only [Icc_homeo_I_symm_apply_coe, subtype.coe_mk], replace h : b - a ≠ 0 := sub_ne_zero_of_ne h.ne.symm, simp only [mul_add], field_simp, ring, }, { change _ + _ ∈ I, rw [mul_comm (b-a)⁻¹, ←neg_mul, ←add_mul, ←sub_eq_add_neg], have w₁ : 0 < (b-a)⁻¹ := inv_pos.mpr (sub_pos.mpr h), have w₂ : 0 ≤ (x : ℝ) - a := sub_nonneg.mpr x.2.1, have w₃ : (x : ℝ) - a ≤ b - a := sub_le_sub_right x.2.2 a, fsplit, { exact mul_nonneg w₂ (le_of_lt w₁), }, { rw [←div_eq_mul_inv, div_le_one (sub_pos.mpr h)], exact w₃, }, }, }, }, { rintro ⟨p, ⟨-,rfl⟩⟩, let q := p.comp ((b - a) • polynomial.X + polynomial.C a), refine ⟨q, ⟨_, _⟩⟩, { simp, }, { ext x, simp [mul_comm], }, }, end end
15e40dec0a6173ef72edce04018ba1e9112e83cf
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/10a_Properties/00_intro.lean
10e2c0ba9fab2f5848e90ac9c5340a96c69340fd
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
8,149
lean
/- A predicate is a "proposition with parameters." For example, a predicate, fromCharlottesville(p) has a parameter, p, and asserts that p (for some value of p) is from Charlottesville. In Lean, we represent a predicate as a function that takes one or more more arguments and reduces to a proposition, and generally to one that is "about" the arguments that were given. So, speaking informally, for example, fromCharlottesville(Kevin) could be read as the proposition "Kevin is from Cville". fromCharlottesville(Mary) is a different proposition, "Mary is from Cville." A predicate thus gives rise to a whole family of propositions, one for each possible combination of argument values. Not every proposition derived by applying a predicate to one or more arguments will be true. Rather, the predicate in effect "picks out" the argument values for which the corresponding proposition is true, and thereby identifies them as having a property of interest, such as the property of "being from Cville." -/ /- Consider a predicate called even(n): that, for any given natural number value of n, asserts that n is even. Given a specific value for n, say 3, this predicate would reduce to the proposition (even 3), a proposition that asserts that 3 is even. Of course 3 isn't even, so (even 3) is false; but (even 4), on the other hand, is true, as long as even(n) is properly defined to express the property of being even. The key idea is this: the numbers that have the property are exactly the numbers for which the corresponding propositions are true. The predicate "picks out" the set of numbers with the given property. -/ /- Here's one way to define an evenness predicate. It uses the existential quantifier, ∃, which we study in detail in the next unit. You can read this as saying n is even if there exists an m such that 2 * m = n. -/ def isEven (n :ℕ) : Prop := ∃ m : nat, 2 * m = n /- Note: isEven isn't a proposition, it's a property! -/ #check isEven /- On the other hand, (isEven 6) is a proposition, namely the proposition that there is some value, m, such that 2 * m = n. -/ #reduce isEven 6 /- We can even prove it. -/ example : isEven 6 := begin unfold isEven, apply exists.intro 3, apply rfl, end /- We define a predicate as a function that takes one or more arguments and that returns a proposition that, in general, involves those values. Consider the following simple example: a predicate that expresses the property of a natural number of "being equal to zero." We write this predicate as a function that takes a natural number, n, and returns the proposition that that number is equal to zero. Here's such a predicate/function. -/ def isZero (n : ℕ): Prop := (0 = n) def nil (n : ℕ) : Prop := false def allN (n : ℕ) := true example : allN 8 := true.intro example : ¬ (nil 8) := begin assume p, exact false.elim p, end /- First, let's check the type of the isZero predicate. -/ #check isZero /- The type of isZero is ℕ → Prop. It is absolutely clear that a predicate is not a proposition, but is instead a function that takes one or more values as arguments (here just one) that that reduces to a proposition. In general, such a proposition is "about" those values. It asserts that they have some particular property. Such a proposition need not be true, and will not be true if the arguments do not have the property in question. For example, (isZero 3) is false. On the other hand, (isZero 0) is true. -/ example : isZero 0 := rfl example : ¬(isZero 3) := λ zeq3, nat.no_confusion zeq3 example : ¬(isZero 1) := begin assume zeq1, exact nat.no_confusion zeq1 end /- Think carefully about what kind of value this predicate/function returns when applied to a particular argument value, e.g., 3. The result is a proposition, in particular, a proposition about 3, namely one that asserts that 0 = 3. To be clear, isZero is a predicate: a function from a ℕ-valued argument to Prop. By contrast, (isZero 3) is a proposition. Look at the types of the following expressions. -/ #check isZero 0 -- a proposition #check isZero 1 -- a proposition #check isZero 2 -- a proposition /- Now look at the specific propositions that this predicate/function returns when applied to particular arguments. Study this until it's clear to you that applying a predicate to an argument returns a proposition about that value. -/ #reduce isZero 0 -- the proposition 0 = 0 #reduce isZero 1 -- the proposition 0 = 1 #reduce isZero 2 -- the proposition 0 = 2 /- We can rewrite this function into an equivalent form in the usual way, to make the type of the predicate clear as a function type. The type of isZero is ℕ → Prop. -/ def isZero' : ℕ → Prop := λ n, 0 = n /- Again, you can think of a predicate as specifying a *property* of its argument: in this case the property of "being equal to zero". Argument values for which the corresponding propositions are true have the given property, and those for which the corresponding proposition is false, do not have the property. -/ -- 0 has the isZero property theorem zeqz : isZero 0 := eq.refl 0 -- 1 does not have this property theorem oneeqz : ¬(isZero 1) := begin unfold isZero, assume eq, exact nat.no_confusion eq, end /- A predicate basically asserts that the value given as its argument has some property. Not every value has a given property (e.g., 3 does not have the property of being even). In general a given predicate is not true for every value of its argument(s). EXERCISE: What are other properties of natural numbers that could be expressed as predicates? -/ def isMultOf8: ℕ → Prop := λ n : nat, ∃ m : nat, 8 * m = n def nIsMultOfm: ℕ → ℕ → Prop := λ n m, ∃ k, n = k * m example : isMultOf8 64 := begin unfold isMultOf8, apply exists.intro 8, apply rfl, end example : nIsMultOfm 64 8 := begin unfold nIsMultOfm, apply exists.intro 8, apply rfl, end /- EXERCISE: Define a predicate that is true for every natural number. -/ /- EXERCISE: Define a predicate that is false for every natural number. -/ def is_absorbed_by_zero(n: ℕ): Prop := n * 0 = 0 def equals_self_plus_one(n: ℕ): Prop := n = n + 1 /- EXAMPLE: Thank goodness it's the weekend. Below we define a new datatype, day, with the names of the seven days of the week as values. Given this datatype, specify the property of being a weekend day. -/ inductive day : Type | Monday : day | Tuesday : day | Wednesday | Thursday | Friday | Saturday | Sunday #check day.Tuesday open day -- no longer need to day. prefix #check Tuesday -- Answer def isWeekend : day → Prop := λ d, d = Saturday ∨ d = Sunday -- EXERCISE: Show Saturday's a weekend day theorem satIsWeekend: isWeekend Saturday := begin unfold isWeekend, -- unfold tactic apply or.intro_left,-- backwards reasoning apply rfl , -- finally, equality end /- EXERCISE: Express the property, of natural numbers, of being a perfect square. For example, 9 is a perfect square, because 3 is a natural number such that 3 * 3 = 9. By contrast, 12 is not a perfect square, as there does not exist a natural number that squares to 12. State and prove the proposition that 9 is a perfect square. -/ -- Answer def isASquare: ℕ → Prop := λ n, exists m, n = m ^ 2 theorem isPS9 : isASquare 9 := begin unfold isASquare, exact exists.intro 3 (eq.refl 9) end /- As a final important concept that we just introduce in this section, we note that we can think of a predicate as specifying a set of values: the set of values for which the predicate (corresponding proposition) is true. For example, the predicate, isZero(n), specifies the set containing only the natural number, zero. A predicate, isEven(n), could specify the set of even natural numbers. Etc. We explore this idea in more depth in the unit on sets to come shortly. EXERCISE: Think of a few more properties that you could specify as predicates. What are the domains of values on which your properties are defined? What sets do your predicates define? -/
7a144f07193fe5f8f6bd69bdcec6dc8c2270c431
2458d2338218c0b15eedf43e540c16f2d3b90991
/lean/tutorial.lean
eceaf93ee2954910812b728fd6edbaca1ea76745
[]
no_license
oraoto/learn
b5e3ebac8e15501540f7ffb857ea687997eee28d
df0454b3ff1bccb010c953fade68fe150e2af7ad
refs/heads/master
1,620,399,134,829
1,510,128,332,000
1,510,128,332,000
109,945,736
1
0
null
null
null
null
UTF-8
Lean
false
false
213
lean
#check "hello, world" inductive mynat: Type | zero: mynat | succ: mynat -> mynat def add: mynat -> mynat -> mynat | m mynat.zero := m | m (mynat.succ n) := mynat.succ (add m n) #check add mynat.zero mynat.zero
f815d6d62022f1618a55ac6ab4640e1b74a96c5e
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/newfrontend3.lean
61bd2481b026b0660424b8f0f165c039c43e9650
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
760
lean
-- structure S := (g {α} : α → α) def f (h : Nat → ({α : Type} → α → α) × Bool) : Nat := (h 0).1 1 def tst : Nat := f fun n => (fun x => x, true) theorem ex : id (Nat → Nat) := by { intro; assumption } def g (i j k : Nat) (a : Array Nat) (h₁ : i < k) (h₂ : k < j) (h₃ : j < a.size) : Nat := let vj := a.get ⟨j, h₃⟩; let vi := a.get ⟨i, Nat.ltTrans h₁ (Nat.ltTrans h₂ h₃)⟩; vi + vj set_option pp.all true in #print g #check g.proof_1 theorem ex1 {p q r s : Prop} : p ∧ q ∧ r ∧ s → r ∧ s ∧ q ∧ p := fun ⟨hp, hq, hr, hs⟩ => ⟨hr, hs, hq, hp⟩ theorem ex2 {p q r s : Prop} : p ∧ q ∧ r ∧ s → r ∧ s ∧ q ∧ p := by intro ⟨hp, hq, hr, hs⟩ exact ⟨hr, hs, hq, hp⟩
2b7cfdfccb55937e29e27d592888a52d8317d3cb
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/tactic.lean
475343a7c22e60e05b5ea99db8e9fcbd6ea77ff7
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
457
lean
-- vim: ts=2 sw=0 sts=-1 et ai tw=70 open tactic open tactic.interactive open interactive (parse) open interactive.types (texpr) open lean.parser -- Convert a goal ∀ a b : t, p a b -- To a λ expr of form λ a b : t, p a b -- Fails if current goal has incorrect form meta def goal_to_lambda2 : tactic expr := do expr.pi a _ ta (expr.pi b _ tb p) ← target, return (expr.lam a binder_info.default ta (expr.lam b binder_info.default tb p))
a76f42756a44a7dbc905221f01c617fc7140426b
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/category_theory/limits/shapes/finite_limits.lean
b3d5f420df89f57af6256eb0dc4a0be40b18287c
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
1,833
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 category_theory.limits.shapes.products import category_theory.discrete_category import data.fintype universes v u open category_theory namespace category_theory.limits /-- A category with a `fintype` of objects, and a `fintype` for each morphism space. -/ class fin_category (J : Type v) [small_category J] := (decidable_eq_obj : decidable_eq J . tactic.apply_instance) (fintype_obj : fintype J . tactic.apply_instance) (decidable_eq_hom : Π (j j' : J), decidable_eq (j ⟶ j') . tactic.apply_instance) (fintype_hom : Π (j j' : J), fintype (j ⟶ j') . tactic.apply_instance) attribute [instance] fin_category.decidable_eq_obj fin_category.fintype_obj fin_category.decidable_eq_hom fin_category.fintype_hom -- We need a `decidable_eq` instance here to construct `fintype` on the morphism spaces. instance fin_category_discrete_of_decidable_fintype (J : Type v) [fintype J] [decidable_eq J] : fin_category (discrete J) := { } variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 class has_finite_limits := (has_limits_of_shape : Π (J : Type v) [small_category J] [fin_category J], has_limits_of_shape.{v} J C) class has_finite_colimits := (has_colimits_of_shape : Π (J : Type v) [small_category J] [fin_category J], has_colimits_of_shape.{v} J C) attribute [instance] has_finite_limits.has_limits_of_shape has_finite_colimits.has_colimits_of_shape instance [has_limits.{v} C] : has_finite_limits.{v} C := { has_limits_of_shape := λ J _ _, by { resetI, apply_instance } } instance [has_colimits.{v} C] : has_finite_colimits.{v} C := { has_colimits_of_shape := λ J _ _, by { resetI, apply_instance } } end category_theory.limits
3848cad5181c11fd0d02737fb298a7fcd2adc8d5
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/inaccessible.lean
146fdaea7f6ec537885d51b05bec1223a1e2805b
[ "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
3,380
lean
universe variables u v inductive imf {A : Type u} {B : Type v} (f : A → B) : B → Type (max 1 u v) | mk : ∀ (a : A), imf (f a) definition inv_1 {A : Type u} {B : Type v} (f : A → B) : ∀ (b : B), imf f b → A | .(f a) (imf.mk .f a) := a definition inv_2 {A : Type u} {B : Type v} (f : A → B) : ∀ (b : B), imf f b → A | ._ (imf.mk ._ a) := a definition mk {A : Type u} {B : Type v} {f : A → B} (a : A) := imf.mk f a definition inv_3 {A : Type u} {B : Type v} (f : A → B) : ∀ (b : B), imf f b → A | .(f a) (mk a) := a -- Error, mk is not a constructor definition inv_4 {A : Type u} {B : Type v} (f : A → B) : ∀ (b : B), imf f b → A | .(f a) (.mk a) := a -- Error, we cannot use inaccessible annotation around functions in applications attribute [pattern] mk definition inv_5 {A : Type u} {B : Type v} (f : A → B) : ∀ (b : B), imf f b → A | .(f a) (mk a) := a definition inv_6 {A : Type u} {B : Type v} (f : A → B) : ∀ (b : B), imf f b → A | (f a) (mk a) := a -- Error, 'a' is being "declared" twice in the pattern definition inv_7 {A : Type u} {B : Type v} (f : A → B) : ∀ (b : B), imf f b → A | (f a) (mk b) := a -- Typing error, it would also fail when compiling the pattern definition g_1 : nat → nat → nat | a a := a -- Error, 'a' is being "declared" twice definition g_2 (a : nat) : nat → nat → nat | a b := a example (a b c : nat) : g_2 a b c = b := rfl inductive vec1 (A : Type u) : nat → Type (max 1 u) | nil : vec1 0 | cons : ∀ n, A → vec1 n → vec1 (n+1) section open vec1 definition map_1 {A : Type u} (f : A → A → A) : Π {n}, vec1 A n → vec1 A n → vec1 A n | 0 (nil .A) (nil .A) := nil A | (n+1) (cons .n h₁ v₁) (cons .n h₂ v₂) := cons n (f h₁ h₂) (map_1 v₁ v₂) definition map_2 {A : Type u} (f : A → A → A) : Π {n}, vec1 A n → vec1 A n → vec1 A n | 0 (nil ._) (nil ._) := nil A | (n+1) (cons ._ h₁ v₁) (cons ._ h₂ v₂) := cons n (f h₁ h₂) (map_2 v₁ v₂) /- In map_3, we use the inaccessible terms to avoid pattern/matching on the first argument -/ definition map_3 {A : Type u} (f : A → A → A) : Π {n}, vec1 A n → vec1 A n → vec1 A n | ._ (nil ._) (nil ._) := nil A | ._ (cons n h₁ v₁) (cons .n h₂ v₂) := cons n (f h₁ h₂) (map_3 v₁ v₂) end inductive vec2 (A : Type u) : nat → Type (max 1 u) | nil {} : vec2 0 | cons : ∀ {n}, A → vec2 n → vec2 (n+1) section open vec2 definition map_4 {A : Type u} (f : A → A → A) : Π {n}, vec2 A n → vec2 A n → vec2 A n | 0 nil nil := nil | (n+1) (cons h₁ v₁) (cons h₂ v₂) := cons (f h₁ h₂) (map_4 v₁ v₂) definition map_5 {A : Type u} (f : A → A → A) : Π {n}, vec2 A n → vec2 A n → vec2 A n | ._ nil nil := nil | ._ (@cons .A n h₁ v₁) (cons h₂ v₂) := cons (f h₁ h₂) (map_5 v₁ v₂) /- The following variant will be rejected by the new equation compiler. In Lean2, the second equation is accepted because unassigned metavariables occurring in patterns become new variables. This feature is too hackish. -/ definition map_6 {A : Type u} (f : A → A → A) : Π {n}, vec2 A n → vec2 A n → vec2 A n | ._ nil nil := nil | ._ (cons h₁ v₁) (cons h₂ v₂) := cons (f h₁ h₂) (map_6 v₁ v₂) end
b5331b5b77047192104bfad0359e111c5d2e248c
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/decomposition/unsigned_hahn.lean
7e5a0cc3538dee05e1abce70098d586aec21218a
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
8,853
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import measure_theory.measure_space /-! # Unsigned Hahn decomposition theorem This file proves the unsigned version of the Hahn decomposition theorem. ## Main statements * `hahn_decomposition` : Given two finite measures `μ` and `ν`, there exists a measurable set `s` such that any measurable set `t` included in `s` satisfies `ν t ≤ μ t`, and any measurable set `u` included in the complement of `s` satisfies `μ u ≤ ν u`. ## Tags Hahn decomposition -/ open set filter open_locale classical topological_space ennreal namespace measure_theory variables {α : Type*} [measurable_space α] {μ ν : measure α} -- suddenly this is necessary?! private lemma aux {m : ℕ} {γ d : ℝ} (h : γ - (1 / 2) ^ m < d) : γ - 2 * (1 / 2) ^ m + (1 / 2) ^ m ≤ d := by linarith /-- **Hahn decomposition theorem** -/ lemma hahn_decomposition [finite_measure μ] [finite_measure ν] : ∃s, measurable_set s ∧ (∀t, measurable_set t → t ⊆ s → ν t ≤ μ t) ∧ (∀t, measurable_set t → t ⊆ sᶜ → μ t ≤ ν t) := begin let d : set α → ℝ := λs, ((μ s).to_nnreal : ℝ) - (ν s).to_nnreal, let c : set ℝ := d '' {s | measurable_set s }, let γ : ℝ := Sup c, have hμ : ∀s, μ s < ∞ := measure_lt_top μ, have hν : ∀s, ν s < ∞ := measure_lt_top ν, have to_nnreal_μ : ∀s, ((μ s).to_nnreal : ℝ≥0∞) = μ s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hμ _), have to_nnreal_ν : ∀s, ((ν s).to_nnreal : ℝ≥0∞) = ν s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hν _), have d_empty : d ∅ = 0, { simp [d], rw [measure_empty, measure_empty], simp }, have d_split : ∀s t, measurable_set s → measurable_set t → d s = d (s \ t) + d (s ∩ t), { assume s t hs ht, simp only [d], rw [measure_eq_inter_diff hs ht, measure_eq_inter_diff hs ht, ennreal.to_nnreal_add (hμ _) (hμ _), ennreal.to_nnreal_add (hν _) (hν _), nnreal.coe_add, nnreal.coe_add], simp only [sub_eq_add_neg, neg_add], ac_refl }, have d_Union : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → monotone s → tendsto (λn, d (s n)) at_top (𝓝 (d (⋃n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ∞ _).comp $ tendsto_measure_Union hs hm), exact hμ _, exact hν _ }, have d_Inter : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → (∀n m, n ≤ m → s m ⊆ s n) → tendsto (λn, d (s n)) at_top (𝓝 (d (⋂n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ∞ _).comp $ tendsto_measure_Inter hs hm _), exact hμ _, exact ⟨0, hμ _⟩, exact hν _, exact ⟨0, hν _⟩ }, have bdd_c : bdd_above c, { use (μ univ).to_nnreal, rintros r ⟨s, hs, rfl⟩, refine le_trans (sub_le_self _ $ nnreal.coe_nonneg _) _, rw [nnreal.coe_le_coe, ← ennreal.coe_le_coe, to_nnreal_μ, to_nnreal_μ], exact measure_mono (subset_univ _) }, have c_nonempty : c.nonempty := nonempty.image _ ⟨_, measurable_set.empty⟩, have d_le_γ : ∀s, measurable_set s → d s ≤ γ := assume s hs, le_cSup bdd_c ⟨s, hs, rfl⟩, have : ∀n:ℕ, ∃s : set α, measurable_set s ∧ γ - (1/2)^n < d s, { assume n, have : γ - (1/2)^n < γ := sub_lt_self γ (pow_pos (half_pos zero_lt_one) n), rcases exists_lt_of_lt_cSup c_nonempty this with ⟨r, ⟨s, hs, rfl⟩, hlt⟩, exact ⟨s, hs, hlt⟩ }, rcases classical.axiom_of_choice this with ⟨e, he⟩, change ℕ → set α at e, have he₁ : ∀n, measurable_set (e n) := assume n, (he n).1, have he₂ : ∀n, γ - (1/2)^n < d (e n) := assume n, (he n).2, let f : ℕ → ℕ → set α := λn m, (finset.Ico n (m + 1)).inf e, have hf : ∀n m, measurable_set (f n m), { assume n m, simp only [f, finset.inf_eq_infi], exact measurable_set.bInter (countable_encodable _) (assume i _, he₁ _) }, have f_subset_f : ∀{a b c d}, a ≤ b → c ≤ d → f a d ⊆ f b c, { assume a b c d hab hcd, dsimp only [f], rw [finset.inf_eq_infi, finset.inf_eq_infi], refine bInter_subset_bInter_left _, simp, rintros j ⟨hbj, hjc⟩, exact ⟨le_trans hab hbj, lt_of_lt_of_le hjc $ add_le_add_right hcd 1⟩ }, have f_succ : ∀n m, n ≤ m → f n (m + 1) = f n m ∩ e (m + 1), { assume n m hnm, have : n ≤ m + 1 := le_of_lt (nat.succ_le_succ hnm), simp only [f], rw [finset.Ico.succ_top this, finset.inf_insert, set.inter_comm], refl }, have le_d_f : ∀n m, m ≤ n → γ - 2 * ((1 / 2) ^ m) + (1 / 2) ^ n ≤ d (f m n), { assume n m h, refine nat.le_induction _ _ n h, { have := he₂ m, simp only [f], rw [finset.Ico.succ_singleton, finset.inf_singleton], exact aux this }, { assume n (hmn : m ≤ n) ih, have : γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n + 1)) ≤ γ + d (f m (n + 1)), { calc γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n+1)) ≤ γ + (γ - 2 * (1 / 2)^m + ((1 / 2) ^ n - (1/2)^(n+1))) : begin refine add_le_add_left (add_le_add_left _ _) γ, simp only [pow_add, pow_one, le_sub_iff_add_le], linarith end ... = (γ - (1 / 2)^(n+1)) + (γ - 2 * (1 / 2)^m + (1 / 2)^n) : by simp only [sub_eq_add_neg]; ac_refl ... ≤ d (e (n + 1)) + d (f m n) : add_le_add (le_of_lt $ he₂ _) ih ... ≤ d (e (n + 1)) + d (f m n \ e (n + 1)) + d (f m (n + 1)) : by rw [f_succ _ _ hmn, d_split (f m n) (e (n + 1)) (hf _ _) (he₁ _), add_assoc] ... = d (e (n + 1) ∪ f m n) + d (f m (n + 1)) : begin rw [d_split (e (n + 1) ∪ f m n) (e (n + 1)), union_diff_left, union_inter_cancel_left], ac_refl, exact (he₁ _).union (hf _ _), exact (he₁ _) end ... ≤ γ + d (f m (n + 1)) : add_le_add_right (d_le_γ _ $ (he₁ _).union (hf _ _)) _ }, exact (add_le_add_iff_left γ).1 this } }, let s := ⋃ m, ⋂n, f m n, have γ_le_d_s : γ ≤ d s, { have hγ : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 γ), { suffices : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 (γ - 2 * 0)), { simpa }, exact (tendsto_const_nhds.sub $ tendsto_const_nhds.mul $ tendsto_pow_at_top_nhds_0_of_lt_1 (le_of_lt $ half_pos $ zero_lt_one) (half_lt_self zero_lt_one)) }, have hd : tendsto (λm, d (⋂n, f m n)) at_top (𝓝 (d (⋃ m, ⋂ n, f m n))), { refine d_Union _ _ _, { assume n, exact measurable_set.Inter (assume m, hf _ _) }, { exact assume n m hnm, subset_Inter (assume i, subset.trans (Inter_subset (f n) i) $ f_subset_f hnm $ le_refl _) } }, refine le_of_tendsto_of_tendsto' hγ hd (assume m, _), have : tendsto (λn, d (f m n)) at_top (𝓝 (d (⋂ n, f m n))), { refine d_Inter _ _ _, { assume n, exact hf _ _ }, { assume n m hnm, exact f_subset_f (le_refl _) hnm } }, refine ge_of_tendsto this (eventually_at_top.2 ⟨m, assume n hmn, _⟩), change γ - 2 * (1 / 2) ^ m ≤ d (f m n), refine le_trans _ (le_d_f _ _ hmn), exact le_add_of_le_of_nonneg (le_refl _) (pow_nonneg (le_of_lt $ half_pos $ zero_lt_one) _) }, have hs : measurable_set s := measurable_set.Union (assume n, measurable_set.Inter (assume m, hf _ _)), refine ⟨s, hs, _, _⟩, { assume t ht hts, have : 0 ≤ d t := ((add_le_add_iff_left γ).1 $ calc γ + 0 ≤ d s : by rw [add_zero]; exact γ_le_d_s ... = d (s \ t) + d t : by rw [d_split _ _ hs ht, inter_eq_self_of_subset_right hts] ... ≤ γ + d t : add_le_add (d_le_γ _ (hs.diff ht)) (le_refl _)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe], simpa only [d, le_sub_iff_add_le, zero_add] using this }, { assume t ht hts, have : d t ≤ 0, exact ((add_le_add_iff_left γ).1 $ calc γ + d t ≤ d s + d t : add_le_add γ_le_d_s (le_refl _) ... = d (s ∪ t) : begin rw [d_split _ _ (hs.union ht) ht, union_diff_right, union_inter_cancel_right, diff_eq_self.2], exact assume a ⟨hat, has⟩, hts hat has end ... ≤ γ + 0 : by rw [add_zero]; exact d_le_γ _ (hs.union ht)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe], simpa only [d, sub_le_iff_le_add, zero_add] using this } end end measure_theory
95d9b3f7554d50c43e9b110aa1ba5a78e21d314b
82e44445c70db0f03e30d7be725775f122d72f3e
/src/order/boolean_algebra.lean
b112479c29f03986128407b5a1b99e535317d0f8
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
32,794
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, Bryan Gin-ge Chen -/ import order.bounded_lattice /-! # (Generalized) Boolean algebras A Boolean algebra is a bounded distributive lattice with a complement operator. Boolean algebras generalize the (classical) logic of propositions and the lattice of subsets of a set. Generalized Boolean algebras may be less familiar, but they are essentially Boolean algebras which do not necessarily have a top element (`⊤`) (and hence not all elements may have complements). One example in mathlib is `finset α`, the type of all finite subsets of an arbitrary (not-necessarily-finite) type `α`. `generalized_boolean_algebra α` is defined to be a distributive lattice with bottom (`⊥`) admitting a *relative* complement operator, written using "set difference" notation as `x \ y` (`sdiff x y`). For convenience, the `boolean_algebra` type class is defined to extend `generalized_boolean_algebra` so that it is also bundled with a `\` operator. (A terminological point: `x \ y` is the complement of `y` relative to the interval `[⊥, x]`. We do not yet have relative complements for arbitrary intervals, as we do not even have lattice intervals.) ## Main declarations * `has_compl`: a type class for the complement operator * `generalized_boolean_algebra`: a type class for generalized Boolean algebras * `boolean_algebra.core`: a type class with the minimal assumptions for a Boolean algebras * `boolean_algebra`: the main type class for Boolean algebras; it extends both `generalized_boolean_algebra` and `boolean_algebra.core`. An instance of `boolean_algebra` can be obtained from one of `boolean_algebra.core` using `boolean_algebra.of_core`. * `Prop.boolean_algebra`: the Boolean algebra instance on `Prop` ## Implementation notes The `sup_inf_sdiff` and `inf_inf_sdiff` axioms for the relative complement operator in `generalized_boolean_algebra` are taken from [Wikipedia](https://en.wikipedia.org/wiki/Boolean_algebra_(structure)#Generalizations). [Stone's paper introducing generalized Boolean algebras][Stone1935] does not define a relative complement operator `a \ b` for all `a`, `b`. Instead, the postulates there amount to an assumption that for all `a, b : α` where `a ≤ b`, the equations `x ⊔ a = b` and `x ⊓ a = ⊥` have a solution `x`. `disjoint.sdiff_unique` proves that this `x` is in fact `b \ a`. ## Notations * `xᶜ` is notation for `compl x` * `x \ y` is notation for `sdiff x y`. ## References * <https://en.wikipedia.org/wiki/Boolean_algebra_(structure)#Generalizations> * [*Postulates for Boolean Algebras and Generalized Boolean Algebras*, M.H. Stone][Stone1935] * [*Lattice Theory: Foundation*, George Grätzer][Gratzer2011] ## Tags generalized Boolean algebras, Boolean algebras, lattices, sdiff, compl -/ set_option old_structure_cmd true universes u v variables {α : Type u} {w x y z : α} /-! ### Generalized Boolean algebras Some of the lemmas in this section are from: * [*Lattice Theory: Foundation*, George Grätzer][Gratzer2011] * <https://ncatlab.org/nlab/show/relative+complement> * <https://people.math.gatech.edu/~mccuan/courses/4317/symmetricdifference.pdf> -/ export has_sdiff (sdiff) /-- A generalized Boolean algebra is a distributive lattice with `⊥` and a relative complement operation `\` (called `sdiff`, after "set difference") satisfying `(a ⊓ b) ⊔ (a \ b) = a` and `(a ⊓ b) ⊓ (a \ b) = b`, i.e. `a \ b` is the complement of `b` in `a`. This is a generalization of Boolean algebras which applies to `finset α` for arbitrary (not-necessarily-`fintype`) `α`. -/ class generalized_boolean_algebra (α : Type u) extends semilattice_sup_bot α, semilattice_inf_bot α, distrib_lattice α, has_sdiff α := (sup_inf_sdiff : ∀a b:α, (a ⊓ b) ⊔ (a \ b) = a) (inf_inf_sdiff : ∀a b:α, (a ⊓ b) ⊓ (a \ b) = ⊥) -- We might want a `is_compl_of` predicate (for relative complements) generalizing `is_compl`, -- however we'd need another type class for lattices with bot, and all the API for that. section generalized_boolean_algebra variables [generalized_boolean_algebra α] @[simp] theorem sup_inf_sdiff (x y : α) : (x ⊓ y) ⊔ (x \ y) = x := generalized_boolean_algebra.sup_inf_sdiff _ _ @[simp] theorem inf_inf_sdiff (x y : α) : (x ⊓ y) ⊓ (x \ y) = ⊥ := generalized_boolean_algebra.inf_inf_sdiff _ _ @[simp] theorem sup_sdiff_inf (x y : α) : (x \ y) ⊔ (x ⊓ y) = x := by rw [sup_comm, sup_inf_sdiff] @[simp] theorem inf_sdiff_inf (x y : α) : (x \ y) ⊓ (x ⊓ y) = ⊥ := by rw [inf_comm, inf_inf_sdiff] theorem disjoint_inf_sdiff : disjoint (x ⊓ y) (x \ y) := (inf_inf_sdiff x y).le -- TODO: in distributive lattices, relative complements are unique when they exist theorem sdiff_unique (s : (x ⊓ y) ⊔ z = x) (i : (x ⊓ y) ⊓ z = ⊥) : x \ y = z := begin conv_rhs at s { rw [←sup_inf_sdiff x y, sup_comm] }, rw sup_comm at s, conv_rhs at i { rw [←inf_inf_sdiff x y, inf_comm] }, rw inf_comm at i, exact (eq_of_inf_eq_sup_eq i s).symm, end theorem sdiff_symm (hy : y ≤ x) (hz : z ≤ x) (H : x \ y = z) : x \ z = y := have hyi : x ⊓ y = y := inf_eq_right.2 hy, have hzi : x ⊓ z = z := inf_eq_right.2 hz, eq_of_inf_eq_sup_eq (begin have ixy := inf_inf_sdiff x y, rw [H, hyi] at ixy, have ixz := inf_inf_sdiff x z, rwa [hzi, inf_comm, ←ixy] at ixz, end) (begin have sxz := sup_inf_sdiff x z, rw [hzi, sup_comm] at sxz, rw sxz, symmetry, have sxy := sup_inf_sdiff x y, rwa [H, hyi] at sxy, end) lemma sdiff_le : x \ y ≤ x := calc x \ y ≤ (x ⊓ y) ⊔ (x \ y) : le_sup_right ... = x : sup_inf_sdiff x y @[simp] lemma bot_sdiff : ⊥ \ x = ⊥ := le_bot_iff.1 sdiff_le lemma inf_sdiff_right : x ⊓ (x \ y) = x \ y := by rw [inf_of_le_right (@sdiff_le _ x y _)] lemma inf_sdiff_left : (x \ y) ⊓ x = x \ y := by rw [inf_comm, inf_sdiff_right] -- cf. `is_compl_top_bot` @[simp] lemma sdiff_self : x \ x = ⊥ := by rw [←inf_inf_sdiff, inf_idem, inf_of_le_right (@sdiff_le _ x x _)] @[simp] theorem sup_sdiff_self_right : x ⊔ (y \ x) = x ⊔ y := calc x ⊔ (y \ x) = (x ⊔ (x ⊓ y)) ⊔ (y \ x) : by rw sup_inf_self ... = x ⊔ ((y ⊓ x) ⊔ (y \ x)) : by ac_refl ... = x ⊔ y : by rw sup_inf_sdiff @[simp] theorem sup_sdiff_self_left : (y \ x) ⊔ x = y ⊔ x := by rw [sup_comm, sup_sdiff_self_right, sup_comm] lemma sup_sdiff_symm : x ⊔ (y \ x) = y ⊔ (x \ y) := by rw [sup_sdiff_self_right, sup_sdiff_self_right, sup_comm] lemma sup_sdiff_of_le (h : x ≤ y) : x ⊔ (y \ x) = y := by conv_rhs { rw [←sup_inf_sdiff y x, inf_eq_right.2 h] } @[simp] lemma sup_sdiff_left : x ⊔ (x \ y) = x := by { rw sup_eq_left, exact sdiff_le } lemma sup_sdiff_right : (x \ y) ⊔ x = x := by rw [sup_comm, sup_sdiff_left] @[simp] lemma sdiff_inf_sdiff : x \ y ⊓ (y \ x) = ⊥ := eq.symm $ calc ⊥ = (x ⊓ y) ⊓ (x \ y) : by rw inf_inf_sdiff ... = (x ⊓ (y ⊓ x ⊔ y \ x)) ⊓ (x \ y) : by rw sup_inf_sdiff ... = (x ⊓ (y ⊓ x) ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by rw inf_sup_left ... = (y ⊓ (x ⊓ x) ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by ac_refl ... = (y ⊓ x ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by rw inf_idem ... = (x ⊓ y ⊓ (x \ y)) ⊔ (x ⊓ (y \ x) ⊓ (x \ y)) : by rw [inf_sup_right, @inf_comm _ _ x y] ... = x ⊓ (y \ x) ⊓ (x \ y) : by rw [inf_inf_sdiff, bot_sup_eq] ... = x ⊓ (x \ y) ⊓ (y \ x) : by ac_refl ... = (x \ y) ⊓ (y \ x) : by rw inf_sdiff_right lemma disjoint_sdiff_sdiff : disjoint (x \ y) (y \ x) := sdiff_inf_sdiff.le theorem le_sup_sdiff : y ≤ x ⊔ (y \ x) := by { rw [sup_sdiff_self_right], exact le_sup_right } theorem le_sdiff_sup : y ≤ (y \ x) ⊔ x := by { rw [sup_comm], exact le_sup_sdiff } @[simp] theorem inf_sdiff_self_right : x ⊓ (y \ x) = ⊥ := calc x ⊓ (y \ x) = ((x ⊓ y) ⊔ (x \ y)) ⊓ (y \ x) : by rw sup_inf_sdiff ... = (x ⊓ y) ⊓ (y \ x) ⊔ (x \ y) ⊓ (y \ x) : by rw inf_sup_right ... = ⊥ : by rw [@inf_comm _ _ x y, inf_inf_sdiff, sdiff_inf_sdiff, bot_sup_eq] @[simp] theorem inf_sdiff_self_left : (y \ x) ⊓ x = ⊥ := by rw [inf_comm, inf_sdiff_self_right] theorem disjoint_sdiff_self_left : disjoint (y \ x) x := inf_sdiff_self_left.le theorem disjoint_sdiff_self_right : disjoint x (y \ x) := inf_sdiff_self_right.le lemma disjoint.disjoint_sdiff_left (h : disjoint x y) : disjoint (x \ z) y := h.mono_left sdiff_le lemma disjoint.disjoint_sdiff_right (h : disjoint x y) : disjoint x (y \ z) := h.mono_right sdiff_le /- TODO: if we had a typeclass for distributive lattices with `⊥`, we could make an alternative constructor for `generalized_boolean_algebra` using `disjoint x (y \ x)` and `x ⊔ (y \ x) = y` as axioms. -/ theorem disjoint.sdiff_eq_of_sup_eq (hi : disjoint x z) (hs : x ⊔ z = y) : y \ x = z := have h : y ⊓ x = x := inf_eq_right.2 $ le_sup_left.trans hs.le, sdiff_unique (by rw [h, hs]) (by rw [h, hi.eq_bot]) lemma disjoint.sup_sdiff_cancel_left (h : disjoint x y) : (x ⊔ y) \ x = y := h.sdiff_eq_of_sup_eq rfl lemma disjoint.sup_sdiff_cancel_right (h : disjoint x y) : (x ⊔ y) \ y = x := h.symm.sdiff_eq_of_sup_eq sup_comm protected theorem disjoint.sdiff_unique (hd : disjoint x z) (hz : z ≤ y) (hs : y ≤ x ⊔ z) : y \ x = z := sdiff_unique (begin rw ←inf_eq_right at hs, rwa [sup_inf_right, inf_sup_right, @sup_comm _ _ x, inf_sup_self, inf_comm, @sup_comm _ _ z, hs, sup_eq_left], end) (by rw [inf_assoc, hd.eq_bot, inf_bot_eq]) -- cf. `is_compl.disjoint_left_iff` and `is_compl.disjoint_right_iff` lemma disjoint_sdiff_iff_le (hz : z ≤ y) (hx : x ≤ y) : disjoint z (y \ x) ↔ z ≤ x := ⟨λ H, le_of_inf_le_sup_le (le_trans H bot_le) (begin rw sup_sdiff_of_le hx, refine le_trans (sup_le_sup_left sdiff_le z) _, rw sup_eq_right.2 hz, end), λ H, disjoint_sdiff_self_right.mono_left H⟩ -- cf. `is_compl.le_left_iff` and `is_compl.le_right_iff` lemma le_iff_disjoint_sdiff (hz : z ≤ y) (hx : x ≤ y) : z ≤ x ↔ disjoint z (y \ x) := (disjoint_sdiff_iff_le hz hx).symm -- cf. `is_compl.inf_left_eq_bot_iff` and `is_compl.inf_right_eq_bot_iff` lemma inf_sdiff_eq_bot_iff (hz : z ≤ y) (hx : x ≤ y) : z ⊓ (y \ x) = ⊥ ↔ z ≤ x := by { rw ←disjoint_iff, exact disjoint_sdiff_iff_le hz hx } -- cf. `is_compl.left_le_iff` and `is_compl.right_le_iff` lemma le_iff_eq_sup_sdiff (hz : z ≤ y) (hx : x ≤ y) : x ≤ z ↔ y = z ⊔ (y \ x) := ⟨λ H, begin apply le_antisymm, { conv_lhs { rw ←sup_inf_sdiff y x, }, apply sup_le_sup_right, rwa inf_eq_right.2 hx, }, { apply le_trans, { apply sup_le_sup_right hz, }, { rw sup_sdiff_left, } } end, λ H, begin conv_lhs at H { rw ←sup_sdiff_of_le hx, }, refine le_of_inf_le_sup_le _ H.le, rw inf_sdiff_self_right, exact bot_le, end⟩ -- cf. `set.union_diff_cancel'` lemma sup_sdiff_cancel' (hx : x ≤ z) (hz : z ≤ y) : z ⊔ (y \ x) = y := ((le_iff_eq_sup_sdiff hz (hx.trans hz)).1 hx).symm -- cf. `is_compl.sup_inf` lemma sdiff_sup : y \ (x ⊔ z) = (y \ x) ⊓ (y \ z) := sdiff_unique (calc y ⊓ (x ⊔ z) ⊔ y \ x ⊓ (y \ z) = (y ⊓ (x ⊔ z) ⊔ y \ x) ⊓ (y ⊓ (x ⊔ z) ⊔ (y \ z)) : by rw sup_inf_left ... = (y ⊓ x ⊔ y ⊓ z ⊔ y \ x) ⊓ (y ⊓ x ⊔ y ⊓ z ⊔ (y \ z)) : by rw @inf_sup_left _ _ y ... = (y ⊓ z ⊔ (y ⊓ x ⊔ y \ x)) ⊓ (y ⊓ x ⊔ (y ⊓ z ⊔ (y \ z))) : by ac_refl ... = (y ⊓ z ⊔ y) ⊓ (y ⊓ x ⊔ y) : by rw [sup_inf_sdiff, sup_inf_sdiff] ... = (y ⊔ y ⊓ z) ⊓ (y ⊔ y ⊓ x) : by ac_refl ... = y : by rw [sup_inf_self, sup_inf_self, inf_idem]) (calc y ⊓ (x ⊔ z) ⊓ ((y \ x) ⊓ (y \ z)) = (y ⊓ x ⊔ y ⊓ z) ⊓ ((y \ x) ⊓ (y \ z)) : by rw inf_sup_left ... = ((y ⊓ x) ⊓ ((y \ x) ⊓ (y \ z))) ⊔ ((y ⊓ z) ⊓ ((y \ x) ⊓ (y \ z))) : by rw inf_sup_right ... = ((y ⊓ x) ⊓ (y \ x) ⊓ (y \ z)) ⊔ ((y \ x) ⊓ ((y \ z) ⊓ (y ⊓ z))) : by ac_refl ... = ⊥ : by rw [inf_inf_sdiff, bot_inf_eq, bot_sup_eq, @inf_comm _ _ (y \ z), inf_inf_sdiff, inf_bot_eq]) -- cf. `is_compl.inf_sup` lemma sdiff_inf : y \ (x ⊓ z) = y \ x ⊔ y \ z := sdiff_unique (calc y ⊓ (x ⊓ z) ⊔ (y \ x ⊔ y \ z) = (z ⊓ (y ⊓ x)) ⊔ (y \ x ⊔ y \ z) : by ac_refl ... = (z ⊔ (y \ x ⊔ y \ z)) ⊓ ((y ⊓ x) ⊔ (y \ x ⊔ y \ z)) : by rw sup_inf_right ... = (y \ x ⊔ (y \ z ⊔ z)) ⊓ (y ⊓ x ⊔ (y \ x ⊔ y \ z)) : by ac_refl ... = (y ⊔ z) ⊓ ((y ⊓ x) ⊔ (y \ x ⊔ y \ z)) : by rw [sup_sdiff_self_left, ←sup_assoc, sup_sdiff_right] ... = (y ⊔ z) ⊓ y : by rw [←sup_assoc, sup_inf_sdiff, sup_sdiff_left] ... = y : by rw [inf_comm, inf_sup_self]) (calc y ⊓ (x ⊓ z) ⊓ ((y \ x) ⊔ (y \ z)) = (y ⊓ (x ⊓ z) ⊓ (y \ x)) ⊔ (y ⊓ (x ⊓ z) ⊓ (y \ z)) : by rw inf_sup_left ... = z ⊓ (y ⊓ x ⊓ (y \ x)) ⊔ z ⊓ (y ⊓ x) ⊓ (y \ z) : by ac_refl ... = z ⊓ (y ⊓ x) ⊓ (y \ z) : by rw [inf_inf_sdiff, inf_bot_eq, bot_sup_eq] ... = x ⊓ ((y ⊓ z) ⊓ (y \ z)) : by ac_refl ... = ⊥ : by rw [inf_inf_sdiff, inf_bot_eq]) @[simp] lemma sdiff_inf_self_right : y \ (x ⊓ y) = y \ x := by rw [sdiff_inf, sdiff_self, sup_bot_eq] @[simp] lemma sdiff_inf_self_left : y \ (y ⊓ x) = y \ x := by rw [inf_comm, sdiff_inf_self_right] lemma sdiff_eq_sdiff_iff_inf_eq_inf : y \ x = y \ z ↔ y ⊓ x = y ⊓ z := ⟨λ h, eq_of_inf_eq_sup_eq (by rw [inf_inf_sdiff, h, inf_inf_sdiff]) (by rw [sup_inf_sdiff, h, sup_inf_sdiff]), λ h, by rw [←sdiff_inf_self_right, ←@sdiff_inf_self_right _ z y, inf_comm, h, inf_comm]⟩ theorem disjoint.sdiff_eq_left (h : disjoint x y) : x \ y = x := by conv_rhs { rw [←sup_inf_sdiff x y, h.eq_bot, bot_sup_eq] } theorem disjoint.sdiff_eq_right (h : disjoint x y) : y \ x = y := h.symm.sdiff_eq_left -- cf. `is_compl_bot_top` @[simp] theorem sdiff_bot : x \ ⊥ = x := disjoint_bot_right.sdiff_eq_left theorem sdiff_eq_self_iff_disjoint : x \ y = x ↔ disjoint y x := calc x \ y = x ↔ x \ y = x \ ⊥ : by rw sdiff_bot ... ↔ x ⊓ y = x ⊓ ⊥ : sdiff_eq_sdiff_iff_inf_eq_inf ... ↔ disjoint y x : by rw [inf_bot_eq, inf_comm, disjoint_iff] theorem sdiff_eq_self_iff_disjoint' : x \ y = x ↔ disjoint x y := by rw [sdiff_eq_self_iff_disjoint, disjoint.comm] lemma sdiff_lt (hx : y ≤ x) (hy : y ≠ ⊥) : x \ y < x := begin refine sdiff_le.lt_of_ne (λ h, hy _), rw [sdiff_eq_self_iff_disjoint', disjoint_iff] at h, rw [←h, inf_eq_right.mpr hx], end -- cf. `is_compl.antimono` lemma sdiff_le_sdiff_self (h : z ≤ x) : w \ x ≤ w \ z := le_of_inf_le_sup_le (calc (w \ x) ⊓ (w ⊓ z) ≤ (w \ x) ⊓ (w ⊓ x) : inf_le_inf le_rfl (inf_le_inf le_rfl h) ... = ⊥ : by rw [inf_comm, inf_inf_sdiff] ... ≤ (w \ z) ⊓ (w ⊓ z) : bot_le) (calc w \ x ⊔ (w ⊓ z) ≤ w \ x ⊔ (w ⊓ x) : sup_le_sup le_rfl (inf_le_inf le_rfl h) ... ≤ w : by rw [sup_comm, sup_inf_sdiff] ... = (w \ z) ⊔ (w ⊓ z) : by rw [sup_comm, sup_inf_sdiff]) lemma sdiff_le_iff : y \ x ≤ z ↔ y ≤ x ⊔ z := ⟨λ h, le_of_inf_le_sup_le (le_of_eq (calc y ⊓ (y \ x) = y \ x : inf_sdiff_right ... = (x ⊓ (y \ x)) ⊔ (z ⊓ (y \ x)) : by rw [inf_eq_right.2 h, inf_sdiff_self_right, bot_sup_eq] ... = (x ⊔ z) ⊓ (y \ x) : inf_sup_right.symm)) (calc y ⊔ y \ x = y : sup_sdiff_left ... ≤ y ⊔ (x ⊔ z) : le_sup_left ... = ((y \ x) ⊔ x) ⊔ z : by rw [←sup_assoc, ←@sup_sdiff_self_left _ x y] ... = x ⊔ z ⊔ y \ x : by ac_refl), λ h, le_of_inf_le_sup_le (calc y \ x ⊓ x = ⊥ : inf_sdiff_self_left ... ≤ z ⊓ x : bot_le) (calc y \ x ⊔ x = y ⊔ x : sup_sdiff_self_left ... ≤ (x ⊔ z) ⊔ x : sup_le_sup_right h x ... ≤ z ⊔ x : by rw [sup_assoc, sup_comm, sup_assoc, sup_idem])⟩ lemma sdiff_eq_bot_iff : y \ x = ⊥ ↔ y ≤ x := by rw [←le_bot_iff, sdiff_le_iff, sup_bot_eq] lemma sdiff_le_comm : x \ y ≤ z ↔ x \ z ≤ y := by rw [sdiff_le_iff, sup_comm, sdiff_le_iff] lemma sdiff_le_self_sdiff (h : w ≤ y) : w \ x ≤ y \ x := le_of_inf_le_sup_le (calc (w \ x) ⊓ (w ⊓ x) = ⊥ : by rw [inf_comm, inf_inf_sdiff] ... ≤ (y \ x) ⊓ (w ⊓ x) : bot_le) (calc w \ x ⊔ (w ⊓ x) = w : by rw [sup_comm, sup_inf_sdiff] ... ≤ (y ⊓ (y \ x)) ⊔ w : le_sup_right ... = (y ⊓ (y \ x)) ⊔ (y ⊓ w) : by rw inf_eq_right.2 h ... = y ⊓ ((y \ x) ⊔ w) : by rw inf_sup_left ... = ((y \ x) ⊔ (y ⊓ x)) ⊓ ((y \ x) ⊔ w) : by rw [@sup_comm _ _ (y \ x) (y ⊓ x), sup_inf_sdiff] ... = (y \ x) ⊔ ((y ⊓ x) ⊓ w) : by rw ←sup_inf_left ... = (y \ x) ⊔ ((w ⊓ y) ⊓ x) : by ac_refl ... = (y \ x) ⊔ (w ⊓ x) : by rw inf_eq_left.2 h) theorem sdiff_le_sdiff (h₁ : w ≤ y) (h₂ : z ≤ x) : w \ x ≤ y \ z := calc w \ x ≤ w \ z : sdiff_le_sdiff_self h₂ ... ≤ y \ z : sdiff_le_self_sdiff h₁ lemma sup_inf_inf_sdiff : (x ⊓ y) ⊓ z ⊔ (y \ z) = (x ⊓ y) ⊔ (y \ z) := calc (x ⊓ y) ⊓ z ⊔ (y \ z) = x ⊓ (y ⊓ z) ⊔ (y \ z) : by rw inf_assoc ... = (x ⊔ (y \ z)) ⊓ y : by rw [sup_inf_right, sup_inf_sdiff] ... = (x ⊓ y) ⊔ (y \ z) : by rw [inf_sup_right, inf_sdiff_left] @[simp] lemma inf_sdiff_sup_left : (x \ z) ⊓ (x ⊔ y) = x \ z := by rw [inf_sup_left, inf_sdiff_left, sup_inf_self] @[simp] lemma inf_sdiff_sup_right : (x \ z) ⊓ (y ⊔ x) = x \ z := by rw [sup_comm, inf_sdiff_sup_left] lemma sdiff_sdiff_right : x \ (y \ z) = (x \ y) ⊔ (x ⊓ y ⊓ z) := begin rw [sup_comm, inf_comm, ←inf_assoc, sup_inf_inf_sdiff], apply sdiff_unique, { calc x ⊓ (y \ z) ⊔ (z ⊓ x ⊔ x \ y) = (x ⊔ (z ⊓ x ⊔ x \ y)) ⊓ (y \ z ⊔ (z ⊓ x ⊔ x \ y)) : by rw sup_inf_right ... = (x ⊔ x ⊓ z ⊔ x \ y) ⊓ (y \ z ⊔ (x ⊓ z ⊔ x \ y)) : by ac_refl ... = x ⊓ (y \ z ⊔ x ⊓ z ⊔ x \ y) : by rw [sup_inf_self, sup_sdiff_left, ←sup_assoc] ... = x ⊓ (y \ z ⊓ (z ⊔ y) ⊔ x ⊓ (z ⊔ y) ⊔ x \ y) : by rw [sup_inf_left, sup_sdiff_self_left, inf_sup_right, @sup_comm _ _ y] ... = x ⊓ (y \ z ⊔ (x ⊓ z ⊔ x ⊓ y) ⊔ x \ y) : by rw [inf_sdiff_sup_right, @inf_sup_left _ _ x z y] ... = x ⊓ (y \ z ⊔ (x ⊓ z ⊔ (x ⊓ y ⊔ x \ y))) : by ac_refl ... = x ⊓ (y \ z ⊔ (x ⊔ x ⊓ z)) : by rw [sup_inf_sdiff, @sup_comm _ _ (x ⊓ z)] ... = x : by rw [sup_inf_self, sup_comm, inf_sup_self] }, { calc x ⊓ (y \ z) ⊓ (z ⊓ x ⊔ x \ y) = x ⊓ (y \ z) ⊓ (z ⊓ x) ⊔ x ⊓ (y \ z) ⊓ (x \ y) : by rw inf_sup_left ... = x ⊓ (y \ z ⊓ z ⊓ x) ⊔ x ⊓ (y \ z) ⊓ (x \ y) : by ac_refl ... = x ⊓ (y \ z) ⊓ (x \ y) : by rw [inf_sdiff_self_left, bot_inf_eq, inf_bot_eq, bot_sup_eq] ... = x ⊓ (y \ z ⊓ y) ⊓ (x \ y) : by conv_lhs { rw ←inf_sdiff_left } ... = x ⊓ (y \ z ⊓ (y ⊓ (x \ y))) : by ac_refl ... = ⊥ : by rw [inf_sdiff_self_right, inf_bot_eq, inf_bot_eq] } end lemma sdiff_sdiff_right' : x \ (y \ z) = (x \ y) ⊔ (x ⊓ z) := calc x \ (y \ z) = (x \ y) ⊔ (x ⊓ y ⊓ z) : sdiff_sdiff_right ... = z ⊓ x ⊓ y ⊔ (x \ y) : by ac_refl ... = (x \ y) ⊔ (x ⊓ z) : by rw [sup_inf_inf_sdiff, sup_comm, inf_comm] @[simp] lemma sdiff_sdiff_right_self : x \ (x \ y) = x ⊓ y := by rw [sdiff_sdiff_right, inf_idem, sdiff_self, bot_sup_eq] lemma sdiff_sdiff_eq_self (h : y ≤ x) : x \ (x \ y) = y := by rw [sdiff_sdiff_right_self, inf_of_le_right h] lemma sdiff_sdiff_left : (x \ y) \ z = x \ (y ⊔ z) := begin rw sdiff_sup, apply sdiff_unique, { rw [←inf_sup_left, sup_sdiff_self_right, inf_sdiff_sup_right] }, { rw [inf_assoc, @inf_comm _ _ z, inf_assoc, inf_sdiff_self_left, inf_bot_eq, inf_bot_eq] } end lemma sdiff_sdiff_left' : (x \ y) \ z = (x \ y) ⊓ (x \ z) := by rw [sdiff_sdiff_left, sdiff_sup] lemma sdiff_sdiff_comm : (x \ y) \ z = (x \ z) \ y := by rw [sdiff_sdiff_left, sup_comm, sdiff_sdiff_left] @[simp] lemma sdiff_idem : x \ y \ y = x \ y := by rw [sdiff_sdiff_left, sup_idem] @[simp] lemma sdiff_sdiff_self : x \ y \ x = ⊥ := by rw [sdiff_sdiff_comm, sdiff_self, bot_sdiff] lemma sdiff_sdiff_sup_sdiff : z \ (x \ y ⊔ y \ x) = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) := calc z \ (x \ y ⊔ y \ x) = (z \ x ⊔ z ⊓ x ⊓ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by rw [sdiff_sup, sdiff_sdiff_right, sdiff_sdiff_right] ... = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by rw [sup_inf_left, sup_comm, sup_inf_sdiff] ... = z ⊓ (z \ x ⊔ y) ⊓ (z ⊓ (z \ y ⊔ x)) : by rw [sup_inf_left, @sup_comm _ _ (z \ y), sup_inf_sdiff] ... = z ⊓ z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) : by ac_refl ... = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) : by rw inf_idem lemma sdiff_sdiff_sup_sdiff' : z \ (x \ y ⊔ y \ x) = z ⊓ x ⊓ y ⊔ ((z \ x) ⊓ (z \ y)) := calc z \ (x \ y ⊔ y \ x) = z \ (x \ y) ⊓ (z \ (y \ x)) : sdiff_sup ... = (z \ x ⊔ z ⊓ x ⊓ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by rw [sdiff_sdiff_right, sdiff_sdiff_right] ... = (z \ x ⊔ z ⊓ y ⊓ x) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by ac_refl ... = (z \ x) ⊓ (z \ y) ⊔ z ⊓ y ⊓ x : sup_inf_right.symm ... = z ⊓ x ⊓ y ⊔ ((z \ x) ⊓ (z \ y)) : by ac_refl lemma sup_sdiff : (x ⊔ y) \ z = (x \ z) ⊔ (y \ z) := sdiff_unique (calc (x ⊔ y) ⊓ z ⊔ (x \ z ⊔ y \ z) = (x ⊓ z ⊔ y ⊓ z) ⊔ (x \ z ⊔ y \ z) : by rw inf_sup_right ... = x ⊓ z ⊔ x \ z ⊔ y \ z ⊔ y ⊓ z : by ac_refl ... = x ⊔ (y ⊓ z ⊔ y \ z) : by rw [sup_inf_sdiff, sup_assoc, @sup_comm _ _ (y \ z)] ... = x ⊔ y : by rw sup_inf_sdiff) (calc (x ⊔ y) ⊓ z ⊓ (x \ z ⊔ y \ z) = (x ⊓ z ⊔ y ⊓ z) ⊓ (x \ z ⊔ y \ z) : by rw inf_sup_right ... = (x ⊓ z ⊔ y ⊓ z) ⊓ (x \ z) ⊔ ((x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z)) : by rw [@inf_sup_left _ _ (x ⊓ z ⊔ y ⊓ z)] ... = (y ⊓ z ⊓ (x \ z)) ⊔ ((x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z)) : by rw [inf_sup_right, inf_inf_sdiff, bot_sup_eq] ... = (x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z) : by rw [inf_assoc, inf_sdiff_self_right, inf_bot_eq, bot_sup_eq] ... = x ⊓ z ⊓ (y \ z) : by rw [inf_sup_right, inf_inf_sdiff, sup_bot_eq] ... = ⊥ : by rw [inf_assoc, inf_sdiff_self_right, inf_bot_eq]) lemma sup_sdiff_right_self : (x ⊔ y) \ y = x \ y := by rw [sup_sdiff, sdiff_self, sup_bot_eq] lemma sup_sdiff_left_self : (x ⊔ y) \ x = y \ x := by rw [sup_comm, sup_sdiff_right_self] lemma inf_sdiff : (x ⊓ y) \ z = (x \ z) ⊓ (y \ z) := sdiff_unique (calc (x ⊓ y) ⊓ z ⊔ ((x \ z) ⊓ (y \ z)) = ((x ⊓ y) ⊓ z ⊔ (x \ z)) ⊓ ((x ⊓ y) ⊓ z ⊔ (y \ z)) : by rw [sup_inf_left] ... = (x ⊓ y ⊓ (z ⊔ x) ⊔ x \ z) ⊓ (x ⊓ y ⊓ z ⊔ y \ z) : by rw [sup_inf_right, sup_sdiff_self_right, inf_sup_right, inf_sdiff_sup_right] ... = (y ⊓ (x ⊓ (x ⊔ z)) ⊔ x \ z) ⊓ (x ⊓ y ⊓ z ⊔ y \ z) : by ac_refl ... = ((y ⊓ x) ⊔ (x \ z)) ⊓ ((x ⊓ y) ⊔ (y \ z)) : by rw [inf_sup_self, sup_inf_inf_sdiff] ... = (x ⊓ y) ⊔ ((x \ z) ⊓ (y \ z)) : by rw [@inf_comm _ _ y, sup_inf_left] ... = x ⊓ y : sup_eq_left.2 (inf_le_inf sdiff_le sdiff_le)) (calc (x ⊓ y) ⊓ z ⊓ ((x \ z) ⊓ (y \ z)) = x ⊓ y ⊓ (z ⊓ (x \ z)) ⊓ (y \ z) : by ac_refl ... = ⊥ : by rw [inf_sdiff_self_right, inf_bot_eq, bot_inf_eq]) lemma inf_sdiff_assoc : (x ⊓ y) \ z = x ⊓ (y \ z) := sdiff_unique (calc x ⊓ y ⊓ z ⊔ x ⊓ (y \ z) = x ⊓ (y ⊓ z) ⊔ x ⊓ (y \ z) : by rw inf_assoc ... = x ⊓ ((y ⊓ z) ⊔ y \ z) : inf_sup_left.symm ... = x ⊓ y : by rw sup_inf_sdiff) (calc x ⊓ y ⊓ z ⊓ (x ⊓ (y \ z)) = x ⊓ x ⊓ ((y ⊓ z) ⊓ (y \ z)) : by ac_refl ... = ⊥ : by rw [inf_inf_sdiff, inf_bot_eq]) lemma sup_eq_sdiff_sup_sdiff_sup_inf : x ⊔ y = (x \ y) ⊔ (y \ x) ⊔ (x ⊓ y) := eq.symm $ calc (x \ y) ⊔ (y \ x) ⊔ (x ⊓ y) = ((x \ y) ⊔ (y \ x) ⊔ x) ⊓ ((x \ y) ⊔ (y \ x) ⊔ y) : by rw sup_inf_left ... = ((x \ y) ⊔ x ⊔ (y \ x)) ⊓ ((x \ y) ⊔ ((y \ x) ⊔ y)) : by ac_refl ... = (x ⊔ (y \ x)) ⊓ ((x \ y) ⊔ y) : by rw [sup_sdiff_right, sup_sdiff_right] ... = x ⊔ y : by rw [sup_sdiff_self_right, sup_sdiff_self_left, inf_idem] instance pi.generalized_boolean_algebra {α : Type u} {β : Type v} [generalized_boolean_algebra β] : generalized_boolean_algebra (α → β) := by pi_instance end generalized_boolean_algebra /-! ### Boolean algebras -/ /-- Set / lattice complement -/ @[notation_class] class has_compl (α : Type*) := (compl : α → α) export has_compl (compl) postfix `ᶜ`:(max+1) := compl /-- This class contains the core axioms of a Boolean algebra. The `boolean_algebra` class extends both this class and `generalized_boolean_algebra`, see Note [forgetful inheritance]. -/ class boolean_algebra.core (α : Type u) extends bounded_distrib_lattice α, has_compl α := (inf_compl_le_bot : ∀x:α, x ⊓ xᶜ ≤ ⊥) (top_le_sup_compl : ∀x:α, ⊤ ≤ x ⊔ xᶜ) section boolean_algebra_core variables [boolean_algebra.core α] @[simp] theorem inf_compl_eq_bot : x ⊓ xᶜ = ⊥ := bot_unique $ boolean_algebra.core.inf_compl_le_bot x @[simp] theorem compl_inf_eq_bot : xᶜ ⊓ x = ⊥ := eq.trans inf_comm inf_compl_eq_bot @[simp] theorem sup_compl_eq_top : x ⊔ xᶜ = ⊤ := top_unique $ boolean_algebra.core.top_le_sup_compl x @[simp] theorem compl_sup_eq_top : xᶜ ⊔ x = ⊤ := eq.trans sup_comm sup_compl_eq_top theorem is_compl_compl : is_compl x xᶜ := is_compl.of_eq inf_compl_eq_bot sup_compl_eq_top theorem is_compl.eq_compl (h : is_compl x y) : x = yᶜ := h.left_unique is_compl_compl.symm theorem is_compl.compl_eq (h : is_compl x y) : xᶜ = y := (h.right_unique is_compl_compl).symm theorem eq_compl_iff_is_compl : x = yᶜ ↔ is_compl x y := ⟨λ h, by { rw h, exact is_compl_compl.symm }, is_compl.eq_compl⟩ theorem compl_eq_iff_is_compl : xᶜ = y ↔ is_compl x y := ⟨λ h, by { rw ←h, exact is_compl_compl }, is_compl.compl_eq⟩ theorem disjoint_compl_right : disjoint x xᶜ := is_compl_compl.disjoint theorem disjoint_compl_left : disjoint xᶜ x := disjoint_compl_right.symm theorem compl_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : xᶜ = y := (is_compl.of_eq i s).compl_eq @[simp] theorem compl_top : ⊤ᶜ = (⊥:α) := is_compl_top_bot.compl_eq @[simp] theorem compl_bot : ⊥ᶜ = (⊤:α) := is_compl_bot_top.compl_eq @[simp] theorem compl_compl (x : α) : xᶜᶜ = x := is_compl_compl.symm.compl_eq @[simp] theorem compl_involutive : function.involutive (compl : α → α) := compl_compl theorem compl_bijective : function.bijective (compl : α → α) := compl_involutive.bijective theorem compl_injective : function.injective (compl : α → α) := compl_involutive.injective @[simp] theorem compl_inj_iff : xᶜ = yᶜ ↔ x = y := compl_injective.eq_iff theorem is_compl.compl_eq_iff (h : is_compl x y) : zᶜ = y ↔ z = x := h.compl_eq ▸ compl_inj_iff @[simp] theorem compl_eq_top : xᶜ = ⊤ ↔ x = ⊥ := is_compl_bot_top.compl_eq_iff @[simp] theorem compl_eq_bot : xᶜ = ⊥ ↔ x = ⊤ := is_compl_top_bot.compl_eq_iff @[simp] theorem compl_inf : (x ⊓ y)ᶜ = xᶜ ⊔ yᶜ := (is_compl_compl.inf_sup is_compl_compl).compl_eq @[simp] theorem compl_sup : (x ⊔ y)ᶜ = xᶜ ⊓ yᶜ := (is_compl_compl.sup_inf is_compl_compl).compl_eq theorem compl_le_compl (h : y ≤ x) : xᶜ ≤ yᶜ := is_compl_compl.antimono is_compl_compl h @[simp] theorem compl_le_compl_iff_le : yᶜ ≤ xᶜ ↔ x ≤ y := ⟨assume h, by have h := compl_le_compl h; simp at h; assumption, compl_le_compl⟩ theorem le_compl_of_le_compl (h : y ≤ xᶜ) : x ≤ yᶜ := by simpa only [compl_compl] using compl_le_compl h theorem compl_le_of_compl_le (h : yᶜ ≤ x) : xᶜ ≤ y := by simpa only [compl_compl] using compl_le_compl h theorem le_compl_iff_le_compl : y ≤ xᶜ ↔ x ≤ yᶜ := ⟨le_compl_of_le_compl, le_compl_of_le_compl⟩ theorem compl_le_iff_compl_le : xᶜ ≤ y ↔ yᶜ ≤ x := ⟨compl_le_of_compl_le, compl_le_of_compl_le⟩ namespace boolean_algebra @[priority 100] instance : is_complemented α := ⟨λ x, ⟨xᶜ, is_compl_compl⟩⟩ end boolean_algebra end boolean_algebra_core /-- A Boolean algebra is a bounded distributive lattice with a complement operator `ᶜ` such that `x ⊓ xᶜ = ⊥` and `x ⊔ xᶜ = ⊤`. For convenience, it must also provide a set difference operation `\` satisfying `x \ y = x ⊓ yᶜ`. This is a generalization of (classical) logic of propositions, or the powerset lattice. -/ -- Lean complains about metavariables in the type if the universe is not specified class boolean_algebra (α : Type u) extends generalized_boolean_algebra α, boolean_algebra.core α := (sdiff_eq : ∀x y:α, x \ y = x ⊓ yᶜ) -- TODO: is there a way to automatically fill in the proofs of sup_inf_sdiff and inf_inf_sdiff given -- everything in `boolean_algebra.core` and `sdiff_eq`? The following doesn't work: -- (sup_inf_sdiff := λ a b, by rw [sdiff_eq, ←inf_sup_left, sup_compl_eq_top, inf_top_eq]) /-- Create a `boolean_algebra` instance from a `boolean_algebra.core` instance, defining `x \ y` to be `x ⊓ yᶜ`. For some types, it may be more convenient to create the `boolean_algebra` instance by hand in order to have a simpler `sdiff` operation. -/ def boolean_algebra.of_core (B : boolean_algebra.core α) : boolean_algebra α := { sdiff := λ x y, x ⊓ yᶜ, sdiff_eq := λ _ _, rfl, sup_inf_sdiff := λ a b, by rw [←inf_sup_left, sup_compl_eq_top, inf_top_eq], inf_inf_sdiff := λ a b, by rw [inf_left_right_swap, @inf_assoc _ _ a, compl_inf_eq_bot, inf_bot_eq, bot_inf_eq], ..B } section boolean_algebra variables [boolean_algebra α] theorem sdiff_eq : x \ y = x ⊓ yᶜ := boolean_algebra.sdiff_eq x y theorem sdiff_compl : x \ yᶜ = x ⊓ y := by rw [sdiff_eq, compl_compl] theorem top_sdiff : ⊤ \ x = xᶜ := by rw [sdiff_eq, top_inf_eq] @[simp] theorem sdiff_top : x \ ⊤ = ⊥ := by rw [sdiff_eq, compl_top, inf_bot_eq] end boolean_algebra instance Prop.boolean_algebra : boolean_algebra Prop := boolean_algebra.of_core { compl := not, inf_compl_le_bot := λ p ⟨Hp, Hpc⟩, Hpc Hp, top_le_sup_compl := λ p H, classical.em p, .. Prop.bounded_distrib_lattice } instance pi.boolean_algebra {ι : Type u} {α : ι → Type v} [∀ i, boolean_algebra (α i)] : boolean_algebra (Π i, α i) := by refine_struct { sdiff := λ x y i, x i \ y i, compl := λ x i, (x i)ᶜ, .. pi.bounded_lattice }; tactic.pi_instance_derive_field
b0793bf7e3ba2e6728c6f13907d1acbca9e0b8e1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/100-theorems-list/42_inverse_triangle_sum.lean
063c4d35bf0b77454c59cffc805154377ddcc52f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,103
lean
/- Copyright (c) 2020. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jalex Stark, Yury Kudryashov -/ import algebra.big_operators.basic import data.real.basic /-! # Sum of the Reciprocals of the Triangular Numbers This file proves Theorem 42 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). We interpret “triangular numbers” as naturals of the form $\frac{k(k+1)}{2}$ for natural `k`. We prove that the sum of the reciprocals of the first `n` triangular numbers is $2 - \frac2n$. ## Tags discrete_sum -/ open_locale big_operators open finset /-- **Sum of the Reciprocals of the Triangular Numbers** -/ lemma inverse_triangle_sum : ∀ n, ∑ k in range n, (2 : ℚ) / (k * (k + 1)) = if n = 0 then 0 else 2 - (2 : ℚ) / n := begin refine sum_range_induction _ _ (if_pos rfl) _, rintro (_|n), { rw [if_neg, if_pos]; norm_num }, simp_rw [if_neg (nat.succ_ne_zero _), nat.succ_eq_add_one], have A : (n + 1 + 1 : ℚ) ≠ 0, by { norm_cast, norm_num }, push_cast, field_simp [nat.cast_add_one_ne_zero], ring end
50125dbb38c92b6be011ea90dca410506161bf80
c9c1a27957d84c115a545c9f93aeaaa780279709
/src/LTL.lean
4f615ff9bdeadd2bb1b1e79928ca9f3f0f59d5c3
[]
no_license
loganrjmurphy/lean-temporal
320475197f39afbea7e29b7de6cdd183e3f7c5de
40c6ad1502fc4168dffe9f34ad2d2043d53af174
refs/heads/main
1,672,925,416,469
1,605,106,081,000
1,605,106,081,000
311,688,877
4
0
null
null
null
null
UTF-8
Lean
false
false
3,633
lean
import data.stream tactic open stream tactic namespace LTL variable AP : Type inductive formula | T : formula | atom : AP → formula | conj : formula → formula → formula | neg : formula → formula | next : formula → formula | until : formula → formula → formula local infix ` & ` : 70 := formula.conj local notation ` ∼` Φ : 100:= formula.neg Φ local notation ` ●` Φ : 100:= formula.next Φ local infixr ` 𝒰 ` : 80 := formula.until namespace formula def disj (φ ψ : formula AP) :formula AP := ∼ (∼φ & ∼ψ) local infix ` ⅋ ` :60 := formula.disj _ def impl (φ ψ : formula AP) : formula AP:= ∼φ ⅋ ψ local infix ` ⇒` : 50 := formula.impl _ def bimpl (φ ψ : formula AP) : formula AP := φ ⇒ ψ & ψ ⇒ φ local infix ` ⇔ ` : 50 := formula.bimpl _ def eventually (φ : formula AP) : formula AP := formula.T 𝒰 φ local notation ` ◆` := formula.eventually _ def always (φ : formula AP) : formula AP := ∼◆∼φ local notation ` ◾` :=formula.always _ def inf_word : Type := stream (set AP) local notation σ[i..] := stream.drop i σ namespace sat def sat : inf_word AP → formula AP → Prop | _ formula.T := true | σ (formula.atom a) := a ∈ σ 0 | σ (formula.conj φ ψ) := (sat σ φ) ∧ (sat σ ψ) | σ (∼ φ) := ¬ (sat σ φ) | σ (● φ) := sat (σ[1..]) φ | σ (φ 𝒰 ψ) := ∃ j, sat (σ[j..]) ψ ∧ ∀ i, i < j → sat (σ[i..]) φ notation σ ` ⊨ ` φ := sat _ σ φ def disj (φ ψ : formula AP) (σ : inf_word AP) : (σ ⊨ φ ⅋ ψ) ↔ (σ ⊨ φ) ∨ (σ ⊨ ψ) := begin rw disj, repeat {rw sat}, rw [not_and, not_not,imp_iff_not_or, not_not], end def impl (φ ψ : formula AP) (σ : inf_word AP) : (σ ⊨ φ ⇒ ψ) ↔ (σ ⊨ φ) → (σ ⊨ ψ) := by { rw [impl,disj, sat, imp_iff_not_or]} def eventually (φ : formula AP) (σ : inf_word AP) : (σ ⊨ ◆φ) ↔ ∃ j, σ[j..] ⊨ φ := begin rw eventually, rw sat, split, { rintros ⟨w,H1,H2⟩, use w, exact H1 }, { rintros ⟨w,H⟩, use w, split, {exact H}, {intros, trivial}} end def always (φ : formula AP) (σ : inf_word AP) : (σ ⊨ ◾ φ) ↔ ∀ i, σ[i..] ⊨ φ := begin rw always, rw [sat, sat.eventually, not_exists], split, {intros H i, replace H := H i, rwa [sat, not_not] at H}, {intros H i, rw sat, rw not_not, apply H i} end def always_eventually (φ : formula AP) (σ : inf_word AP) : (σ ⊨ ◾(◆φ)) ↔ ∀ i, ∃ j, j ≥ i ∧ (σ[j..] ⊨ φ):= begin rw always, split, { intros H i, replace H := H i, rw eventually at H, cases H with k H, rw drop_drop at H, use (k+i), split, {rw [ge_iff_le,le_add_iff_nonneg_left], apply zero_le}, exact H}, { intros H i, replace H := H i, rcases H with ⟨k,H1,H2⟩, rw eventually, use (k-i), rw drop_drop, rwa nat.sub_add_cancel H1,} end def eventually_always (φ : formula AP) (σ : inf_word AP) : (σ ⊨ ◆(◾φ)) ↔ ∃ i, ∀ j, j ≥ i → (σ[j..] ⊨ φ):= begin rw eventually, split, { rintros ⟨k,H⟩, rw always at H, use k, intros j H', replace H := H (j-k), rw drop_drop at H, rwa nat.sub_add_cancel H' at H}, { rintros ⟨k,H1⟩, use k,rw always, intro i, replace H1 := H1 (i+k), rw drop_drop, apply H1, rw [ge_iff_le, le_add_iff_nonneg_left], apply zero_le} end def equiv (φ ψ : formula AP) : Prop := {σ | σ ⊨ φ } = {σ | σ ⊨ ψ} notation φ ≡ ψ := equiv _ φ ψ end sat end formula end LTL
f3a1585db4f881e703eefb031a7853218fd88567
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/degree/trailing_degree.lean
8a9e87a396e9307553d02ae98f1a850ffa8353eb
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,892
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.degree.definitions /-! # Trailing degree of univariate polynomials ## Main definitions * `trailing_degree p`: the multiplicity of `X` in the polynomial `p` * `nat_trailing_degree`: a variant of `trailing_degree` that takes values in the natural numbers * `trailing_coeff`: the coefficient at index `nat_trailing_degree p` Converts most results about `degree`, `nat_degree` and `leading_coeff` to results about the bottom end of a polynomial -/ noncomputable theory open function polynomial finsupp finset open_locale big_operators classical polynomial 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 : R[X]} /-- `trailing_degree p` is the multiplicity of `x` in the polynomial `p`, i.e. the smallest `X`-exponent in `p`. `trailing_degree p = some n` when `p ≠ 0` and `n` is the smallest power of `X` that appears in `p`, otherwise `trailing_degree 0 = ⊤`. -/ def trailing_degree (p : R[X]) : with_top ℕ := p.support.inf some lemma trailing_degree_lt_wf : well_founded (λp q : R[X], trailing_degree p < trailing_degree q) := inv_image.wf trailing_degree (with_top.well_founded_lt nat.lt_wf) /-- `nat_trailing_degree p` forces `trailing_degree p` to `ℕ`, by defining `nat_trailing_degree ⊤ = 0`. -/ def nat_trailing_degree (p : R[X]) : ℕ := (trailing_degree p).get_or_else 0 /-- `trailing_coeff p` gives the coefficient of the smallest power of `X` in `p`-/ def trailing_coeff (p : R[X]) : R := coeff p (nat_trailing_degree p) /-- a polynomial is `monic_at` if its trailing coefficient is 1 -/ def trailing_monic (p : R[X]) := trailing_coeff p = (1 : R) lemma trailing_monic.def : trailing_monic p ↔ trailing_coeff p = 1 := iff.rfl instance trailing_monic.decidable [decidable_eq R] : decidable (trailing_monic p) := by unfold trailing_monic; apply_instance @[simp] lemma trailing_monic.trailing_coeff {p : R[X]} (hp : p.trailing_monic) : trailing_coeff p = 1 := hp @[simp] lemma trailing_degree_zero : trailing_degree (0 : R[X]) = ⊤ := rfl @[simp] lemma trailing_coeff_zero : trailing_coeff (0 : R[X]) = 0 := rfl @[simp] lemma nat_trailing_degree_zero : nat_trailing_degree (0 : R[X]) = 0 := rfl lemma trailing_degree_eq_top : trailing_degree p = ⊤ ↔ p = 0 := ⟨λ h, by rw [trailing_degree, ← min_eq_inf_with_top] at h; exact support_eq_empty.1 (min_eq_none.1 h), λ h, by simp [h]⟩ lemma trailing_degree_eq_nat_trailing_degree (hp : p ≠ 0) : trailing_degree p = (nat_trailing_degree p : with_top ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt trailing_degree_eq_top.1 hp)) in have hn : trailing_degree p = some n := not_not.1 hn, by rw [nat_trailing_degree, hn]; refl lemma trailing_degree_eq_iff_nat_trailing_degree_eq {p : R[X]} {n : ℕ} (hp : p ≠ 0) : p.trailing_degree = n ↔ p.nat_trailing_degree = n := by rw [trailing_degree_eq_nat_trailing_degree hp, with_top.coe_eq_coe] lemma trailing_degree_eq_iff_nat_trailing_degree_eq_of_pos {p : R[X]} {n : ℕ} (hn : 0 < n) : p.trailing_degree = n ↔ p.nat_trailing_degree = n := begin split, { intro H, rwa ← trailing_degree_eq_iff_nat_trailing_degree_eq, rintro rfl, rw trailing_degree_zero at H, exact option.no_confusion H }, { intro H, rwa trailing_degree_eq_iff_nat_trailing_degree_eq, rintro rfl, rw nat_trailing_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_trailing_degree_eq_of_trailing_degree_eq_some {p : R[X]} {n : ℕ} (h : trailing_degree p = n) : nat_trailing_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_trailing_degree p : with_top ℕ) = n, by rwa [← trailing_degree_eq_nat_trailing_degree hp0] @[simp] lemma nat_trailing_degree_le_trailing_degree : ↑(nat_trailing_degree p) ≤ trailing_degree p := begin by_cases hp : p = 0, { rw [hp, trailing_degree_zero], exact le_top }, rw [trailing_degree_eq_nat_trailing_degree hp], exact le_rfl end lemma nat_trailing_degree_eq_of_trailing_degree_eq [semiring S] {q : S[X]} (h : trailing_degree p = trailing_degree q) : nat_trailing_degree p = nat_trailing_degree q := by unfold nat_trailing_degree; rw h lemma le_trailing_degree_of_ne_zero (h : coeff p n ≠ 0) : trailing_degree p ≤ n := show @has_le.le (with_top ℕ) _ (p.support.inf some : with_top ℕ) (some n : with_top ℕ), from finset.inf_le (mem_support_iff.2 h) lemma nat_trailing_degree_le_of_ne_zero (h : coeff p n ≠ 0) : nat_trailing_degree p ≤ n := begin rw [← with_top.coe_le_coe, ← trailing_degree_eq_nat_trailing_degree], { exact le_trailing_degree_of_ne_zero h, }, { assume h, subst h, exact h rfl } end lemma trailing_degree_le_trailing_degree (h : coeff q (nat_trailing_degree p) ≠ 0) : trailing_degree q ≤ trailing_degree p := begin by_cases hp : p = 0, { rw hp, exact le_top }, { rw trailing_degree_eq_nat_trailing_degree hp, exact le_trailing_degree_of_ne_zero h } end lemma trailing_degree_ne_of_nat_trailing_degree_ne {n : ℕ} : p.nat_trailing_degree ≠ n → trailing_degree p ≠ n := mt $ λ h, by rw [nat_trailing_degree, h, option.get_or_else_coe] theorem nat_trailing_degree_le_of_trailing_degree_le {n : ℕ} {hp : p ≠ 0} (H : (n : with_top ℕ) ≤ trailing_degree p) : n ≤ nat_trailing_degree p := begin rw trailing_degree_eq_nat_trailing_degree hp at H, exact with_top.coe_le_coe.mp H, end lemma nat_trailing_degree_le_nat_trailing_degree {hq : q ≠ 0} (hpq : p.trailing_degree ≤ q.trailing_degree) : p.nat_trailing_degree ≤ q.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, nat_trailing_degree_zero], exact zero_le _ }, rwa [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, with_top.coe_le_coe] at hpq end @[simp] lemma trailing_degree_monomial (ha : a ≠ 0) : trailing_degree (monomial n a) = n := by rw [trailing_degree, support_monomial _ _ ha, inf_singleton, with_top.some_eq_coe] lemma nat_trailing_degree_monomial (ha : a ≠ 0) : nat_trailing_degree (monomial n a) = n := by rw [nat_trailing_degree, trailing_degree_monomial ha]; refl lemma nat_trailing_degree_monomial_le : nat_trailing_degree (monomial n a) ≤ n := if ha : a = 0 then by simp [ha] else (nat_trailing_degree_monomial ha).le lemma le_trailing_degree_monomial : ↑n ≤ trailing_degree (monomial n a) := if ha : a = 0 then by simp [ha] else (trailing_degree_monomial ha).ge @[simp] lemma trailing_degree_C (ha : a ≠ 0) : trailing_degree (C a) = (0 : with_top ℕ) := trailing_degree_monomial ha lemma le_trailing_degree_C : (0 : with_top ℕ) ≤ trailing_degree (C a) := le_trailing_degree_monomial lemma trailing_degree_one_le : (0 : with_top ℕ) ≤ trailing_degree (1 : R[X]) := by rw [← C_1]; exact le_trailing_degree_C @[simp] lemma nat_trailing_degree_C (a : R) : nat_trailing_degree (C a) = 0 := nonpos_iff_eq_zero.1 nat_trailing_degree_monomial_le @[simp] lemma nat_trailing_degree_one : nat_trailing_degree (1 : R[X]) = 0 := nat_trailing_degree_C 1 @[simp] lemma nat_trailing_degree_nat_cast (n : ℕ) : nat_trailing_degree (n : R[X]) = 0 := by simp only [←C_eq_nat_cast, nat_trailing_degree_C] @[simp] lemma trailing_degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : trailing_degree (C a * X ^ n) = n := by rw [C_mul_X_pow_eq_monomial, trailing_degree_monomial ha] lemma le_trailing_degree_C_mul_X_pow (n : ℕ) (a : R) : (n : with_top ℕ) ≤ trailing_degree (C a * X ^ n) := by { rw C_mul_X_pow_eq_monomial, exact le_trailing_degree_monomial } lemma coeff_eq_zero_of_trailing_degree_lt (h : (n : with_top ℕ) < trailing_degree p) : coeff p n = 0 := not_not.1 (mt le_trailing_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_lt_nat_trailing_degree {p : R[X]} {n : ℕ} (h : n < p.nat_trailing_degree) : p.coeff n = 0 := begin apply coeff_eq_zero_of_trailing_degree_lt, by_cases hp : p = 0, { rw [hp, trailing_degree_zero], exact with_top.coe_lt_top n, }, { rwa [trailing_degree_eq_nat_trailing_degree hp, with_top.coe_lt_coe] }, end @[simp] lemma coeff_nat_trailing_degree_pred_eq_zero {p : R[X]} {hp : (0 : with_top ℕ) < nat_trailing_degree p} : p.coeff (p.nat_trailing_degree - 1) = 0 := coeff_eq_zero_of_lt_nat_trailing_degree $ nat.sub_lt ((with_top.zero_lt_coe (nat_trailing_degree p)).mp hp) nat.one_pos theorem le_trailing_degree_X_pow (n : ℕ) : (n : with_top ℕ) ≤ trailing_degree (X^n : R[X]) := by simpa only [C_1, one_mul] using le_trailing_degree_C_mul_X_pow n (1:R) theorem le_trailing_degree_X : (1 : with_top ℕ) ≤ trailing_degree (X : R[X]) := le_trailing_degree_monomial lemma nat_trailing_degree_X_le : (X : R[X]).nat_trailing_degree ≤ 1 := nat_trailing_degree_monomial_le @[simp] lemma trailing_coeff_eq_zero : trailing_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_min (trailing_degree_eq_nat_trailing_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma trailing_coeff_nonzero_iff_nonzero : trailing_coeff p ≠ 0 ↔ p ≠ 0 := not_congr trailing_coeff_eq_zero lemma nat_trailing_degree_mem_support_of_nonzero : p ≠ 0 → nat_trailing_degree p ∈ p.support := (mem_support_iff.mpr ∘ trailing_coeff_nonzero_iff_nonzero.mpr) lemma nat_trailing_degree_le_of_mem_supp (a : ℕ) : a ∈ p.support → nat_trailing_degree p ≤ a:= nat_trailing_degree_le_of_ne_zero ∘ mem_support_iff.mp lemma nat_trailing_degree_eq_support_min' (h : p ≠ 0) : nat_trailing_degree p = p.support.min' (nonempty_support_iff.mpr h) := begin apply le_antisymm, { apply le_min', intros y hy, exact nat_trailing_degree_le_of_mem_supp y hy }, { apply finset.min'_le, exact mem_support_iff.mpr (trailing_coeff_nonzero_iff_nonzero.mpr h), }, end lemma nat_trailing_degree_le_nat_degree (p : R[X]) : p.nat_trailing_degree ≤ p.nat_degree := begin by_cases hp : p = 0, { rw [hp, nat_degree_zero, nat_trailing_degree_zero] }, { exact le_nat_degree_of_ne_zero (mt trailing_coeff_eq_zero.mp hp) }, end lemma nat_trailing_degree_mul_X_pow {p : R[X]} (hp : p ≠ 0) (n : ℕ) : (p * X ^ n).nat_trailing_degree = p.nat_trailing_degree + n := begin apply le_antisymm, { refine nat_trailing_degree_le_of_ne_zero (λ h, mt trailing_coeff_eq_zero.mp hp _), rwa [trailing_coeff, ←coeff_mul_X_pow] }, { rw [nat_trailing_degree_eq_support_min' (λ h, hp (mul_X_pow_eq_zero h)), finset.le_min'_iff], intros y hy, have key : n ≤ y, { rw [mem_support_iff, coeff_mul_X_pow'] at hy, exact by_contra (λ h, hy (if_neg h)) }, rw [mem_support_iff, coeff_mul_X_pow', if_pos key] at hy, exact (le_tsub_iff_right key).mp (nat_trailing_degree_le_of_ne_zero hy) }, end end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma trailing_degree_one : trailing_degree (1 : R[X]) = (0 : with_top ℕ) := trailing_degree_C one_ne_zero @[simp] lemma trailing_degree_X : trailing_degree (X : R[X]) = 1 := trailing_degree_monomial one_ne_zero @[simp] lemma nat_trailing_degree_X : (X : R[X]).nat_trailing_degree = 1 := nat_trailing_degree_monomial one_ne_zero end nonzero_semiring section ring variables [ring R] @[simp] lemma trailing_degree_neg (p : R[X]) : trailing_degree (-p) = trailing_degree p := by unfold trailing_degree; rw support_neg @[simp] lemma nat_trailing_degree_neg (p : R[X]) : nat_trailing_degree (-p) = nat_trailing_degree p := by simp [nat_trailing_degree] @[simp] lemma nat_trailing_degree_int_cast (n : ℤ) : nat_trailing_degree (n : R[X]) = 0 := by simp only [←C_eq_int_cast, nat_trailing_degree_C] end ring section semiring variables [semiring R] /-- The second-lowest coefficient, or 0 for constants -/ def next_coeff_up (p : R[X]) : R := if p.nat_trailing_degree = 0 then 0 else p.coeff (p.nat_trailing_degree + 1) @[simp] lemma next_coeff_up_C_eq_zero (c : R) : next_coeff_up (C c) = 0 := by { rw next_coeff_up, simp } lemma next_coeff_up_of_pos_nat_trailing_degree (p : R[X]) (hp : 0 < p.nat_trailing_degree) : next_coeff_up p = p.coeff (p.nat_trailing_degree + 1) := by { rw [next_coeff_up, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : R[X]} {ι : Type*} lemma coeff_nat_trailing_degree_eq_zero_of_trailing_degree_lt (h : trailing_degree p < trailing_degree q) : coeff q (nat_trailing_degree p) = 0 := coeff_eq_zero_of_trailing_degree_lt $ nat_trailing_degree_le_trailing_degree.trans_lt h lemma ne_zero_of_trailing_degree_lt {n : with_top ℕ} (h : trailing_degree p < n) : p ≠ 0 := λ h₀, h.not_le (by simp [h₀]) end semiring end polynomial
cc96255aeb9fc06d0f046dcf93ead05f34011472
ac92829298855d39b757cf1fddca8f058436f027
/hott/hit/prop_trunc.hlean
092fdaa560c5f244f9adc3f14242c937ac3c897c
[ "Apache-2.0" ]
permissive
avigad/lean2
7af27190b9697b69a13268a133c1d3c8df85d2cf
34dbd6c3ae612186b8f0f80d12fbf5ae7a059ec9
refs/heads/master
1,592,027,477,851
1,500,732,234,000
1,500,732,234,000
75,484,066
0
0
null
1,480,781,056,000
1,480,781,056,000
null
UTF-8
Lean
false
false
15,621
hlean
import types.trunc hit.colimit homotopy.connectedness open eq is_trunc unit quotient seq_colim pi nat equiv sum algebra is_conn function /- In this file we define the propositional truncation, which, given (X : Type) has constructors * tr : X → trunc X * is_prop_trunc : is_prop (trunc X) and with a recursor which recurses to any family of mere propositions. The construction uses a "one step truncation" of X, with two constructors: * tr : X → one_step_tr X * tr_eq : Π(a b : X), tr a = tr b This is like a truncation, but taking out the recursive part. Martin Escardo calls this construction the generalized circle, since the one step truncation of the unit type is the circle. Then we can repeat this n times: A 0 = X, A (n + 1) = one_step_tr (A n) We have a map f {n : ℕ} : A n → A (n + 1) := tr Then trunc is defined as the sequential colimit of (A, f). Both the one step truncation and the sequential colimit can be defined as a quotient, which is a primitive HIT in Lean. Here, with a quotient, we mean the following HIT: Given {X : Type} (R : X → X → Type) we have the constructors * class_of : X → quotient R * eq_of_rel : Π{a a' : X}, R a a' → a = a' See the comment below for a sketch of the proof that (trunc A) is actually a mere proposition. -/ /- definition of "one step truncation" in terms of quotients -/ namespace one_step_tr section parameters {A : Type} variables (a a' : A) protected definition R (a a' : A) : Type₀ := unit parameter (A) definition one_step_tr : Type := quotient R parameter {A} definition tr : one_step_tr := class_of R a definition tr_eq : tr a = tr a' := eq_of_rel _ star protected definition rec {P : one_step_tr → Type} (Pt : Π(a : A), P (tr a)) (Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') (x : one_step_tr) : P x := begin fapply (quotient.rec_on x), { intro a, apply Pt}, { intro a a' H, cases H, apply Pe} end protected definition rec_on [reducible] {P : one_step_tr → Type} (x : one_step_tr) (Pt : Π(a : A), P (tr a)) (Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') : P x := rec Pt Pe x protected definition elim {P : Type} (Pt : A → P) (Pe : Π(a a' : A), Pt a = Pt a') (x : one_step_tr) : P := rec Pt (λa a', pathover_of_eq _ (Pe a a')) x protected definition elim_on [reducible] {P : Type} (x : one_step_tr) (Pt : A → P) (Pe : Π(a a' : A), Pt a = Pt a') : P := elim Pt Pe x theorem rec_tr_eq {P : one_step_tr → Type} (Pt : Π(a : A), P (tr a)) (Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') (a a' : A) : apd (rec Pt Pe) (tr_eq a a') = Pe a a' := !rec_eq_of_rel theorem elim_tr_eq {P : Type} (Pt : A → P) (Pe : Π(a a' : A), Pt a = Pt a') (a a' : A) : ap (elim Pt Pe) (tr_eq a a') = Pe a a' := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (tr_eq a a')), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_tr_eq], end end definition n_step_tr [reducible] (A : Type) (n : ℕ) : Type := nat.rec_on n A (λn' A', one_step_tr A') end one_step_tr attribute one_step_tr.rec one_step_tr.elim [recursor 5] [unfold 5] attribute one_step_tr.rec_on one_step_tr.elim_on [unfold 2] attribute one_step_tr.tr [constructor] namespace one_step_tr /- Theorems about the one-step truncation -/ open homotopy trunc prod theorem tr_eq_ne_idp {A : Type} (a : A) : tr_eq a a ≠ idp := begin intro p, have H2 : Π{X : Type₁} {x : X} {q : x = x}, q = idp, from λX x q, calc q = ap (one_step_tr.elim (λa, x) (λa b, q)) (tr_eq a a) : elim_tr_eq ... = ap (one_step_tr.elim (λa, x) (λa b, q)) (refl (one_step_tr.tr a)) : by rewrite p ... = idp : idp, exact bool.eq_bnot_ne_idp H2 end theorem tr_eq_ne_ap_tr {A : Type} {a b : A} (p : a = b) : tr_eq a b ≠ ap tr p := by induction p; apply tr_eq_ne_idp theorem not_inhabited_set_trunc_one_step_tr (A : Type) : ¬(trunc 1 (one_step_tr A) × is_set (trunc 1 (one_step_tr A))) := begin intro H, induction H with x H, refine trunc.elim_on x _, clear x, intro x, induction x, { have q : trunc -1 ((tr_eq a a) = idp), begin refine to_fun !tr_eq_tr_equiv _, refine @is_prop.elim _ _ _ _, apply is_trunc_equiv_closed, apply tr_eq_tr_equiv end, refine trunc.elim_on q _, clear q, intro p, exact !tr_eq_ne_idp p}, { apply is_prop.elim} end theorem not_is_conn_one_step_tr (A : Type) : ¬is_conn 1 (one_step_tr A) := λH, not_inhabited_set_trunc_one_step_tr A (!center, _) theorem is_prop_trunc_one_step_tr (A : Type) : is_prop (trunc 0 (one_step_tr A)) := begin apply is_prop.mk, intro x y, refine trunc.rec_on x _, refine trunc.rec_on y _, clear x y, intro y x, induction x, { induction y, { exact ap trunc.tr !tr_eq}, { apply is_prop.elimo}}, { apply is_prop.elimo} end local attribute is_prop_trunc_one_step_tr [instance] theorem trunc_0_one_step_tr_equiv (A : Type) : trunc 0 (one_step_tr A) ≃ ∥ A ∥ := begin apply equiv_of_is_prop, { intro x, refine trunc.rec _ x, clear x, intro x, induction x, { exact trunc.tr a}, { apply is_prop.elim}}, { intro x, refine trunc.rec _ x, clear x, intro a, exact trunc.tr (tr a)}, end definition one_step_tr_functor [unfold 4] {A B : Type} (f : A → B) (x : one_step_tr A) : one_step_tr B := begin induction x, { exact tr (f a)}, { apply tr_eq} end definition one_step_tr_universal_property [constructor] (A B : Type) : (one_step_tr A → B) ≃ Σ(f : A → B), Π(x y : A), f x = f y := begin fapply equiv.MK, { intro f, fconstructor, intro a, exact f (tr a), intros, exact ap f !tr_eq}, { intro v a, induction v with f p, induction a, exact f a, apply p}, { intro v, induction v with f p, esimp, apply ap (sigma.mk _), apply eq_of_homotopy2, intro a a', apply elim_tr_eq}, { intro f, esimp, apply eq_of_homotopy, intro a, induction a, reflexivity, apply eq_pathover, apply hdeg_square, rewrite [▸*,elim_tr_eq]}, end end one_step_tr open one_step_tr namespace prop_trunc namespace hide section parameter {X : Type} /- basic constructors -/ definition A [reducible] (n : ℕ) : Type := nat.rec_on n X (λn' X', one_step_tr X') definition f [reducible] ⦃n : ℕ⦄ (a : A n) : A (succ n) := tr a definition f_eq [reducible] {n : ℕ} (a a' : A n) : f a = f a' := tr_eq a a' definition truncX [reducible] : Type := @seq_colim A f definition i [reducible] {n : ℕ} (a : A n) : truncX := inclusion f a definition g [reducible] {n : ℕ} (a : A n) : i (f a) = i a := glue f a /- defining the normal recursor is easy -/ definition rec {P : truncX → Type} [Pt : Πx, is_prop (P x)] (H : Π(a : X), P (@i 0 a)) (x : truncX) : P x := begin induction x, { induction n with n IH, { exact H a}, { induction a, { exact !g⁻¹ ▸ IH a}, { apply is_prop.elimo}}}, { apply is_prop.elimo} end /- The main effort is to prove that truncX is a mere proposition. We prove Π(a b : truncX), a = b first by induction on a, using the induction principle we just proven and then by induction on b On the point level we need to construct (1) a : A n, b : A m ⊢ p a b : i a = i b On the path level (for the induction on b) we need to show that (2) a : A n, b : A m ⊢ p a (f b) ⬝ g b = p a b The path level for a is automatic, since (Πb, a = b) is a mere proposition Thanks to Egbert Rijke for pointing this out For (1) we distinguish the cases n ≤ m and n ≥ m, and we prove that the two constructions coincide for n = m For (2) we distinguish the cases n ≤ m and n > m During the proof we heavily use induction on inequalities. (n ≤ m), or (le n m), is defined as an inductive family: inductive le (n : ℕ) : ℕ → Type₀ := | refl : le n n | step : Π {m}, le n m → le n (succ m) -/ /- point operations -/ definition fr [reducible] [unfold 2] (n : ℕ) (a : X) : A n := begin induction n with n x, { exact a}, { exact f x}, end /- path operations -/ definition i_fr [unfold 2] (n : ℕ) (a : X) : i (fr n a) = @i 0 a := begin induction n with n p, { reflexivity}, { exact g (fr n a) ⬝ p}, end definition eq_same {n : ℕ} (a a' : A n) : i a = i a' := calc i a = i (f a) : g ... = i (f a') : ap i (f_eq a a') ... = i a' : g definition eq_constructors {n : ℕ} (a : X) (b : A n) : @i 0 a = i b := calc i a = i (fr n a) : i_fr ... = i b : eq_same /- 2-dimensional path operations -/ theorem ap_i_ap_f {n : ℕ} {a a' : A n} (p : a = a') : !g⁻¹ ⬝ ap i (ap !f p) ⬝ !g = ap i p := by induction p; apply con.left_inv theorem ap_i_eq_ap_i_same {n : ℕ} {a a' : A n} (p q : a = a') : ap i p = ap i q := @(is_weakly_constant_ap i) eq_same a a' p q theorem ap_f_eq_f {n : ℕ} (a a' : A n) : !g⁻¹ ⬝ ap i (f_eq (f a) (f a')) ⬝ !g = ap i (f_eq a a') := ap _ !ap_i_eq_ap_i_same ⬝ !ap_i_ap_f theorem eq_same_f {n : ℕ} (a a' : A n) : (g a)⁻¹ ⬝ eq_same (f a) (f a') ⬝ g a' = eq_same a a' := begin esimp [eq_same], apply (ap (λx, _ ⬝ x ⬝ _)), apply (ap_f_eq_f a a'), end theorem eq_constructors_comp {n : ℕ} (a : X) (b : A n) : eq_constructors a (f b) ⬝ g b = eq_constructors a b := begin rewrite [↑eq_constructors,▸*,↓fr n a,↓i_fr n a,con_inv,+con.assoc], apply ap (λx, _ ⬝ x), rewrite -con.assoc, exact !eq_same_f end theorem is_prop_truncX : is_prop truncX := begin apply is_prop_of_imp_is_contr, intro a, refine @rec _ _ _ a, clear a, intro a, fapply is_contr.mk, exact @i 0 a, intro b, induction b with n b n b, { apply eq_constructors}, { apply (equiv.to_inv !eq_pathover_equiv_r), apply eq_constructors_comp} end end end hide end prop_trunc namespace prop_trunc open hide definition ptrunc.{u} (A : Type.{u}) : Type.{u} := @truncX A definition ptr {A : Type} : A → ptrunc A := @i A 0 definition is_prop_trunc (A : Type) : is_prop (ptrunc A) := is_prop_truncX protected definition ptrunc.rec {A : Type} {P : ptrunc A → Type} [Pt : Π(x : ptrunc A), is_prop (P x)] (H : Π(a : A), P (ptr a)) : Π(x : ptrunc A), P x := @rec A P Pt H example {A : Type} {P : ptrunc A → Type} [Pt : Πaa, is_prop (P aa)] (H : Πa, P (ptr a)) (a : A) : (ptrunc.rec H) (ptr a) = H a := by reflexivity open sigma prod -- the constructed truncation is equivalent to the "standard" propositional truncation -- (called _root_.trunc -1 below) open trunc attribute is_prop_trunc [instance] definition ptrunc_equiv_trunc (A : Type) : ptrunc A ≃ trunc -1 A := begin fapply equiv.MK, { intro x, induction x using ptrunc.rec with a, exact tr a}, { intro x, refine trunc.rec _ x, intro a, exact ptr a}, { intro x, induction x with a, reflexivity}, { intro x, induction x using ptrunc.rec with a, reflexivity} end -- some other recursors we get from this construction: definition trunc.elim2 {A P : Type} (h : Π{n}, n_step_tr A n → P) (coh : Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a) (x : ptrunc A) : P := begin induction x, { exact h a}, { apply coh} end definition trunc.rec2 {A : Type} {P : truncX → Type} (h : Π{n} (a : n_step_tr A n), P (i a)) (coh : Π(n : ℕ) (a : n_step_tr A n), h (f a) =[g a] h a) (x : ptrunc A) : P x := begin induction x, { exact h a}, { apply coh} end definition elim2_equiv [constructor] (A P : Type) : (ptrunc A → P) ≃ Σ(h : Π{n}, n_step_tr A n → P), Π(n : ℕ) (a : n_step_tr A n), @h (succ n) (one_step_tr.tr a) = h a := begin fapply equiv.MK, { intro h, fconstructor, { intro n a, refine h (i a)}, { intro n a, exact ap h (g a)}}, { intro x a, induction x with h p, induction a, exact h a, apply p}, { intro x, induction x with h p, fapply sigma_eq, { reflexivity}, { esimp, apply pathover_idp_of_eq, apply eq_of_homotopy2, intro n a, xrewrite elim_glue}}, { intro h, apply eq_of_homotopy, intro a, esimp, induction a, esimp, apply eq_pathover, apply hdeg_square, esimp, rewrite elim_glue} end open sigma.ops definition conditionally_constant_equiv {A P : Type} (k : A → P) : (Σ(g : ptrunc A → P), Πa, g (ptr a) = k a) ≃ Σ(h : Π{n}, n_step_tr A n → P), (Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a) × (Πa, @h 0 a = k a) := calc (Σ(g : ptrunc A → P), Πa, g (ptr a) = k a) ≃ Σ(v : Σ(h : Π{n}, n_step_tr A n → P), Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a), Πa, (v.1) 0 a = k a : sigma_equiv_sigma !elim2_equiv (λg, equiv.rfl) ... ≃ Σ(h : Π{n}, n_step_tr A n → P) (p : Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a), Πa, @h 0 a = k a : sigma_assoc_equiv ... ≃ Σ(h : Π{n}, n_step_tr A n → P), (Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a) × (Πa, @h 0 a = k a) : sigma_equiv_sigma_right (λa, !equiv_prod) definition cocone_of_is_collapsible {A : Type} (f : A → A) (p : Πa a', f a = f a') (n : ℕ) (x : n_step_tr A n) : A := begin apply f, induction n with n h, { exact x}, { apply to_inv !one_step_tr_universal_property ⟨f, p⟩, exact one_step_tr_functor h x} end definition has_split_support_of_is_collapsible {A : Type} (f : A → A) (p : Πa a', f a = f a') : ptrunc A → A := begin fapply to_inv !elim2_equiv, fconstructor, { exact cocone_of_is_collapsible f p}, { intro n a, apply p} end end prop_trunc open prop_trunc trunc -- Corollaries for the actual truncation. namespace is_trunc local attribute is_prop_trunc_one_step_tr [instance] definition prop_trunc.elim_set [unfold 6] {A : Type} {P : Type} [is_set P] (f : A → P) (p : Πa a', f a = f a') (x : trunc -1 A) : P := begin have y : trunc 0 (one_step_tr A), by induction x; exact trunc.tr (one_step_tr.tr a), induction y with y, induction y, { exact f a}, { exact p a a'} end definition prop_trunc.elim_set_tr {A : Type} {P : Type} {H : is_set P} (f : A → P) (p : Πa a', f a = f a') (a : A) : prop_trunc.elim_set f p (tr a) = f a := by reflexivity open sigma local attribute prop_trunc.elim_set [recursor 6] definition total_image.elim_set [unfold 8] {A B : Type} {f : A → B} {C : Type} [is_set C] (g : A → C) (h : Πa a', f a = f a' → g a = g a') (x : total_image f) : C := begin induction x with b v, induction v using prop_trunc.elim_set with x x x', { induction x with a p, exact g a }, { induction x with a p, induction x' with a' p', induction p', exact h _ _ p } end definition total_image.rec [unfold 7] {A B : Type} {f : A → B} {C : total_image f → Type} [H : Πx, is_prop (C x)] (g : Πa, C ⟨f a, image.mk a idp⟩) (x : total_image f) : C x := begin induction x with b v, refine @image.rec _ _ _ _ _ (λv, H ⟨b, v⟩) _ v, intro a p, induction p, exact g a end end is_trunc
5332f38cf84ad5e55ba6a7681265d661f95948b1
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/polynomial/big_operators.lean
8e6070ab374b4bca5488429cabb4e33a0202b2e8
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,909
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark. -/ import data.polynomial.monic import tactic.linarith /-! # Lemmas for the interaction between polynomials and `∑` and `∏`. Recall that `∑` and `∏` are notation for `finset.sum` and `finset.prod` respectively. ## Main results - `polynomial.nat_degree_prod_of_monic` : the degree of a product of monic polynomials is the product of degrees. We prove this only for `[comm_semiring R]`, but it ought to be true for `[semiring R]` and `list.prod`. - `polynomial.nat_degree_prod` : for polynomials over an integral domain, the degree of the product is the sum of degrees. - `polynomial.leading_coeff_prod` : for polynomials over an integral domain, the leading coefficient is the product of leading coefficients. - `polynomial.prod_X_sub_C_coeff_card_pred` carries most of the content for computing the second coefficient of the characteristic polynomial. -/ open finset open_locale big_operators universes u w variables {R : Type u} {ι : Type w} namespace polynomial variable (s : finset ι) section comm_semiring variables [comm_semiring R] (f : ι → polynomial R) lemma nat_degree_prod_le : (∏ i in s, f i).nat_degree ≤ ∑ i in s, (f i).nat_degree := begin classical, induction s using finset.induction with a s ha hs, { simp }, rw [prod_insert ha, sum_insert ha], transitivity (f a).nat_degree + (∏ x in s, f x).nat_degree, apply polynomial.nat_degree_mul_le, linarith, end /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients, provided that this product is nonzero. See `polynomial.leading_coeff_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma leading_coeff_prod' (h : ∏ i in s, (f i).leading_coeff ≠ 0) : (∏ i in s, f i).leading_coeff = ∏ i in s, (f i).leading_coeff := begin classical, revert h, induction s using finset.induction with a s ha hs, { simp }, repeat { rw prod_insert ha }, intro h, rw polynomial.leading_coeff_mul'; { rwa hs, apply right_ne_zero_of_mul h }, end /-- The degree of a product of polynomials is equal to the sum of the degrees, provided that the product of leading coefficients is nonzero. See `polynomial.nat_degree_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma nat_degree_prod' (h : ∏ i in s, (f i).leading_coeff ≠ 0) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := begin classical, revert h, induction s using finset.induction with a s ha hs, { simp }, rw [prod_insert ha, prod_insert ha, sum_insert ha], intro h, rw polynomial.nat_degree_mul', rw hs, apply right_ne_zero_of_mul h, rwa polynomial.leading_coeff_prod', apply right_ne_zero_of_mul h, end lemma nat_degree_prod_of_monic [nontrivial R] (h : ∀ i ∈ s, (f i).monic) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := begin apply nat_degree_prod', suffices : ∏ i in s, (f i).leading_coeff = 1, { rw this, simp }, rw prod_eq_one, intros, apply h, assumption, end lemma coeff_zero_prod : (∏ i in s, f i).coeff 0 = ∏ i in s, (f i).coeff 0 := begin classical, induction s using finset.induction with a s ha hs, { simp only [coeff_one_zero, prod_empty] }, { simp only [ha, hs, mul_coeff_zero, not_false_iff, prod_insert] } end end comm_semiring section comm_ring variables [comm_ring R] open monic -- Eventually this can be generalized with Vieta's formulas -- plus the connection between roots and factorization. lemma prod_X_sub_C_next_coeff [nontrivial R] {s : finset ι} (f : ι → R) : next_coeff ∏ i in s, (X - C (f i)) = -∑ i in s, f i := by { rw next_coeff_prod; { simp [monic_X_sub_C] } } lemma prod_X_sub_C_coeff_card_pred [nontrivial R] (s : finset ι) (f : ι → R) (hs : 0 < s.card) : (∏ i in s, (X - C (f i))).coeff (s.card - 1) = - ∑ i in s, f i := begin convert prod_X_sub_C_next_coeff (by assumption), rw next_coeff, split_ifs, { rw nat_degree_prod_of_monic at h, swap, { intros, apply monic_X_sub_C }, rw sum_eq_zero_iff at h, simp_rw nat_degree_X_sub_C at h, contrapose! h, norm_num, exact multiset.card_pos_iff_exists_mem.mp hs }, congr, rw nat_degree_prod_of_monic; { simp [nat_degree_X_sub_C, monic_X_sub_C] }, end end comm_ring section no_zero_divisors variables [comm_ring R] [no_zero_divisors R] (f : ι → polynomial R) /-- The degree of a product of polynomials is equal to the sum of the degrees. See `polynomial.nat_degree_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma nat_degree_prod [nontrivial R] (h : ∀ i ∈ s, f i ≠ 0) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := begin apply nat_degree_prod', rw prod_ne_zero_iff, intros x hx, simp [h x hx], end /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is ⊥. -/ lemma degree_prod [nontrivial R] : (∏ i in s, f i).degree = ∑ i in s, (f i).degree := begin classical, induction s using finset.induction with a s ha hs, { simp }, { rw [prod_insert ha, sum_insert ha, degree_mul, hs] }, end /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients. See `polynomial.leading_coeff_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma leading_coeff_prod : (∏ i in s, f i).leading_coeff = ∏ i in s, (f i).leading_coeff := by { rw ← leading_coeff_hom_apply, apply monoid_hom.map_prod } end no_zero_divisors end polynomial
f9af94192dc5050bd7d63ac9fe6d884087e491ca
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/tc.lean
ef0c30913bafa662d517c52caf5f25c08766e96e
[ "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
4,816
lean
/-! # A Certified Type Checker In this example, we build a certified type checker for a simple expression language. Remark: this example is based on an example in the book [Certified Programming with Dependent Types](http://adam.chlipala.net/cpdt/) by Adam Chlipala. -/ inductive Expr where | nat : Nat → Expr | plus : Expr → Expr → Expr | bool : Bool → Expr | and : Expr → Expr → Expr /-! We define a simple language of types using the inductive datatype `Ty`, and its typing rules using the inductive predicate `HasType`. -/ inductive Ty where | nat | bool deriving DecidableEq inductive HasType : Expr → Ty → Prop | nat : HasType (.nat v) .nat | plus : HasType a .nat → HasType b .nat → HasType (.plus a b) .nat | bool : HasType (.bool v) .bool | and : HasType a .bool → HasType b .bool → HasType (.and a b) .bool /-! We can easily show that if `e` has type `t₁` and type `t₂`, then `t₁` and `t₂` must be equal by using the the `cases` tactic. This tactic creates a new subgoal for every constructor, and automatically discharges unreachable cases. The tactic combinator `tac₁ <;> tac₂` applies `tac₂` to each subgoal produced by `tac₁`. Then, the tactic `rfl` is used to close all produced goals using reflexivity. -/ theorem HasType.det (h₁ : HasType e t₁) (h₂ : HasType e t₂) : t₁ = t₂ := by cases h₁ <;> cases h₂ <;> rfl /-! The inductive type `Maybe p` has two contructors: `found a h` and `unknown`. The former contains an element `a : α` and a proof that `a` satisfies the predicate `p`. The constructor `unknown` is used to encode "failure". -/ inductive Maybe (p : α → Prop) where | found : (a : α) → p a → Maybe p | unknown /-! We define a notation for `Maybe` that is similar to the builtin notation for the Lean builtin type `Subtype`. -/ notation "{{ " x " | " p " }}" => Maybe (fun x => p) /-! The function `Expr.typeCheck e` returns a type `ty` and a proof that `e` has type `ty`, or `unknown`. Recall that, `def Expr.typeCheck ...` in Lean is notation for `namespace Expr def typeCheck ... end Expr`. The term `.found .nat .nat` is sugar for `Maybe.found Ty.nat HasType.nat`. Lean can infer the namespaces using the expected types. -/ def Expr.typeCheck (e : Expr) : {{ ty | HasType e ty }} := match e with | nat .. => .found .nat .nat | bool .. => .found .bool .bool | plus a b => match a.typeCheck, b.typeCheck with | .found .nat h₁, .found .nat h₂ => .found .nat (.plus h₁ h₂) | _, _ => .unknown | and a b => match a.typeCheck, b.typeCheck with | .found .bool h₁, .found .bool h₂ => .found .bool (.and h₁ h₂) | _, _ => .unknown theorem Expr.typeCheck_correct (h₁ : HasType e ty) (h₂ : e.typeCheck ≠ .unknown) : e.typeCheck = .found ty h := by revert h₂ cases typeCheck e with | found ty' h' => intro; have := HasType.det h₁ h'; subst this; rfl | unknown => intros; contradiction /-! Now, we prove that if `Expr.typeCheck e` returns `Maybe.unknown`, then forall `ty`, `HasType e ty` does not hold. The notation `e.typeCheck` is sugar for `Expr.typeCheck e`. Lean can infer this because we explicitly said that `e` has type `Expr`. The proof is by induction on `e` and case analysis. The tactic `rename_i` is used to to rename "inaccessible" variables. We say a variable is inaccessible if it is introduced by a tactic (e.g., `cases`) or has been shadowed by another variable introduced by the user. Note that the tactic `simp [typeCheck]` is applied to all goal generated by the `induction` tactic, and closes the cases corresponding to the constructors `Expr.nat` and `Expr.bool`. -/ theorem Expr.typeCheck_complete {e : Expr} : e.typeCheck = .unknown → ¬ HasType e ty := by induction e with simp [typeCheck] | plus a b iha ihb => split next => intros; contradiction next ra rb hnp => -- Recall that `hnp` is a hypothesis generated by the `split` tactic -- that asserts the previous case was not taken intro h ht cases ht with | plus h₁ h₂ => exact hnp h₁ h₂ (typeCheck_correct h₁ (iha · h₁)) (typeCheck_correct h₂ (ihb · h₂)) | and a b iha ihb => split next => intros; contradiction next ra rb hnp => intro h ht cases ht with | and h₁ h₂ => exact hnp h₁ h₂ (typeCheck_correct h₁ (iha · h₁)) (typeCheck_correct h₂ (ihb · h₂)) /-! Finally, we show that type checking for `e` can be decided using `Expr.typeCheck`. -/ instance (e : Expr) (t : Ty) : Decidable (HasType e t) := match h' : e.typeCheck with | .found t' ht' => if heq : t = t' then isTrue (heq ▸ ht') else isFalse fun ht => heq (HasType.det ht ht') | .unknown => isFalse (Expr.typeCheck_complete h')
a59e0bd2b842ed4de7272e8fce7eb6a23e0a9ebd
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Deriving/FromToJson.lean
08905d93f11054a6bcf4ca850781f69d338efc79
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
9,318
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Dany Fabian -/ import Lean.Meta.Transform import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util import Lean.Data.Json.FromToJson namespace Lean.Elab.Deriving.FromToJson open Lean.Elab.Command open Lean.Json open Lean.Parser.Term open Lean.Meta def mkJsonField (n : Name) : Bool × Syntax := let s := n.toString let s₁ := s.dropRightWhile (· == '?') (s != s₁, Syntax.mkStrLit s₁) def mkToJsonInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if declNames.size == 1 then if (← isStructure (← getEnv) declNames[0]) then let cmds ← liftTermElabM none <| do let ctx ← mkContext "toJson" declNames[0] let header ← mkHeader ctx ``ToJson 1 ctx.typeInfos[0] let fields := getStructureFieldsFlattened (← getEnv) declNames[0] (includeSubobjectFields := false) let fields : Array Syntax ← fields.mapM fun field => do let (isOptField, nm) ← mkJsonField field if isOptField then `(opt $nm $(mkIdent <| header.targetNames[0] ++ field)) else `([($nm, toJson $(mkIdent <| header.targetNames[0] ++ field))]) let cmd ← `(private def $(mkIdent ctx.auxFunNames[0]):ident $header.binders:explicitBinder* := mkObj <| List.join [$fields,*]) return #[cmd] ++ (← mkInstanceCmds ctx ``ToJson declNames) cmds.forM elabCommand return true else let indVal ← getConstInfoInduct declNames[0] let cmds ← liftTermElabM none <| do let ctx ← mkContext "toJson" declNames[0] let toJsonFuncId := mkIdent ctx.auxFunNames[0] -- Return syntax to JSONify `id`, either via `ToJson` or recursively -- if `id`'s type is the type we're deriving for. let mkToJson (id : Syntax) (type : Expr) : TermElabM Syntax := do if type.isAppOf indVal.name then `($toJsonFuncId:ident $id:ident) else `(toJson $id:ident) let header ← mkHeader ctx ``ToJson 1 ctx.typeInfos[0] let discrs ← mkDiscrs header indVal let alts ← mkAlts indVal fun ctor args userNames => do match args, userNames with | #[], _ => `(toJson $(quote ctor.name.getString!)) | #[(x, t)], none => `(mkObj [($(quote ctor.name.getString!), $(← mkToJson x t))]) | xs, none => let xs ← xs.mapM fun (x, t) => mkToJson x t `(mkObj [($(quote ctor.name.getString!), Json.arr #[$[$xs:term],*])]) | xs, some userNames => let xs ← xs.mapIdxM fun idx (x, t) => do `(($(quote userNames[idx].getString!), $(← mkToJson x t))) `(mkObj [($(quote ctor.name.getString!), mkObj [$[$xs:term],*])]) let mut auxCmd ← `(match $[$discrs],* with $alts:matchAlt*) if ctx.usePartial then let letDecls ← mkLocalInstanceLetDecls ctx ``ToJson header.argNames auxCmd ← mkLet letDecls auxCmd auxCmd ← `(private partial def $toJsonFuncId:ident $header.binders:explicitBinder* := $auxCmd) else auxCmd ← `(private def $toJsonFuncId:ident $header.binders:explicitBinder* := $auxCmd) return #[auxCmd] ++ (← mkInstanceCmds ctx ``ToJson declNames) cmds.forM elabCommand return true else return false where mkAlts (indVal : InductiveVal) (rhs : ConstructorVal → Array (Syntax × Expr) → (Option $ Array Name) → TermElabM Syntax) : TermElabM (Array Syntax) := do indVal.ctors.toArray.mapM fun ctor => do let ctorInfo ← getConstInfoCtor ctor forallTelescopeReducing ctorInfo.type fun xs type => do let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.numIndices] do patterns := patterns.push (← `(_)) let mut ctorArgs := #[] -- add `_` for inductive parameters, they are inaccessible for i in [:indVal.numParams] do ctorArgs := ctorArgs.push (← `(_)) -- bound constructor arguments and their types let mut binders := #[] let mut userNames := #[] for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i] let localDecl ← getLocalDecl x.fvarId! if !localDecl.userName.hasMacroScopes then userNames := userNames.push localDecl.userName let a := mkIdent (← mkFreshUserName `a) binders := binders.push (a, localDecl.type) ctorArgs := ctorArgs.push a patterns := patterns.push (← `(@$(mkIdent ctorInfo.name):ident $ctorArgs:term*)) let rhs ← rhs ctorInfo binders (if userNames.size == binders.size then some userNames else none) `(matchAltExpr| | $[$patterns:term],* => $rhs:term) def mkFromJsonInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if declNames.size == 1 then if (← isStructure (← getEnv) declNames[0]) then let cmds ← liftTermElabM none <| do let ctx ← mkContext "fromJson" declNames[0] let header ← mkHeader ctx ``FromJson 0 ctx.typeInfos[0] let fields := getStructureFieldsFlattened (← getEnv) declNames[0] (includeSubobjectFields := false) let jsonFields := fields.map (Prod.snd ∘ mkJsonField) let fields := fields.map mkIdent let cmd ← `(private def $(mkIdent ctx.auxFunNames[0]):ident $header.binders:explicitBinder* (j : Json) : Except String $(← mkInductiveApp ctx.typeInfos[0] header.argNames) := do $[let $fields:ident ← getObjValAs? j _ $jsonFields]* return { $[$fields:ident := $(id fields)]* }) return #[cmd] ++ (← mkInstanceCmds ctx ``FromJson declNames) cmds.forM elabCommand return true else let indVal ← getConstInfoInduct declNames[0] let cmds ← liftTermElabM none <| do let ctx ← mkContext "fromJson" declNames[0] let header ← mkHeader ctx ``FromJson 0 ctx.typeInfos[0] let fromJsonFuncId := mkIdent ctx.auxFunNames[0] let discrs ← mkDiscrs header indVal let alts ← mkAlts indVal fromJsonFuncId let mut auxCmd ← alts.foldrM (fun xs x => `(Except.orElseLazy $xs (fun _ => $x))) (←`(Except.error "no inductive constructor matched")) if ctx.usePartial then let letDecls ← mkLocalInstanceLetDecls ctx ``FromJson header.argNames auxCmd ← mkLet letDecls auxCmd -- FromJson is not structurally recursive even non-nested recursive inductives, -- so we also use `partial` then. if ctx.usePartial || indVal.isRec then auxCmd ← `( private partial def $fromJsonFuncId:ident $header.binders:explicitBinder* (json : Json) : Except String $(← mkInductiveApp ctx.typeInfos[0] header.argNames) := $auxCmd) else auxCmd ← `( private def $fromJsonFuncId:ident $header.binders:explicitBinder* (json : Json) : Except String $(← mkInductiveApp ctx.typeInfos[0] header.argNames) := $auxCmd) return #[auxCmd] ++ (← mkInstanceCmds ctx ``FromJson declNames) cmds.forM elabCommand return true else return false where mkAlts (indVal : InductiveVal) (fromJsonFuncId : Syntax) : TermElabM (Array Syntax) := do let alts ← indVal.ctors.toArray.mapM fun ctor => do let ctorInfo ← getConstInfoCtor ctor forallTelescopeReducing ctorInfo.type fun xs type => do let mut binders := #[] let mut userNames := #[] for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i] let localDecl ← getLocalDecl x.fvarId! if !localDecl.userName.hasMacroScopes then userNames := userNames.push localDecl.userName let a := mkIdent (← mkFreshUserName `a) binders := binders.push (a, localDecl.type) -- Return syntax to parse `id`, either via `FromJson` or recursively -- if `id`'s type is the type we're deriving for. let mkFromJson (idx : Nat) (type : Expr) : TermElabM Syntax := if type.isAppOf indVal.name then `(Lean.Parser.Term.doExpr| $fromJsonFuncId:ident jsons[$(quote idx)]) else `(Lean.Parser.Term.doExpr| fromJson? jsons[$(quote idx)]) let identNames := binders.map Prod.fst let fromJsons ← binders.mapIdxM fun idx (_, type) => mkFromJson idx type let userNamesOpt ← if binders.size == userNames.size then `(some #[$[$(userNames.map quote):ident],*]) else `(none) let stx ← `((Json.parseTagged json $(quote ctor.getString!) $(quote ctorInfo.numFields) $(quote userNamesOpt)).bind (fun jsons => do $[let $identNames:ident ← $fromJsons]* return $(mkIdent ctor):ident $identNames*)) (stx, ctorInfo.numFields) -- the smaller cases, especially the ones without fields are likely faster let alts := alts.qsort (fun (_, x) (_, y) => x < y) alts.map Prod.fst builtin_initialize registerBuiltinDerivingHandler ``ToJson mkToJsonInstanceHandler registerBuiltinDerivingHandler ``FromJson mkFromJsonInstanceHandler end Lean.Elab.Deriving.FromToJson
3b5566b888b4b92e07058802d9b9808f210b96e8
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/normed_space/hahn_banach.lean
4b7d6b1532fbe4ab8c5a7cd737142d0342afed0d
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
7,178
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth -/ import analysis.convex.cone import analysis.normed_space.extend /-! # Hahn-Banach theorem In this file we prove a version of Hahn-Banach theorem for continuous linear functions on normed spaces over `ℝ` and `ℂ`. In order to state and prove its corollaries uniformly, we prove the statements for a field `𝕜` satisfying `is_R_or_C 𝕜`. In this setting, `exists_dual_vector` states that, for any nonzero `x`, there exists a continuous linear form `g` of norm `1` with `g x = ∥x∥` (where the norm has to be interpreted as an element of `𝕜`). -/ universes u v /-- The norm of `x` as an element of `𝕜` (a normed algebra over `ℝ`). This is needed in particular to state equalities of the form `g x = norm' 𝕜 x` when `g` is a linear function. For the concrete cases of `ℝ` and `ℂ`, this is just `∥x∥` and `↑∥x∥`, respectively. -/ noncomputable def norm' (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [semi_normed_algebra ℝ 𝕜] {E : Type*} [semi_normed_group E] (x : E) : 𝕜 := algebra_map ℝ 𝕜 ∥x∥ lemma norm'_def (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [semi_normed_algebra ℝ 𝕜] {E : Type*} [semi_normed_group E] (x : E) : norm' 𝕜 x = (algebra_map ℝ 𝕜 ∥x∥) := rfl lemma norm_norm' (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [semi_normed_algebra ℝ 𝕜] (A : Type*) [semi_normed_group A] (x : A) : ∥norm' 𝕜 x∥ = ∥x∥ := by rw [norm'_def, norm_algebra_map_eq, norm_norm] @[simp] lemma norm'_eq_zero_iff (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [semi_normed_algebra ℝ 𝕜] (A : Type*) [normed_group A] (x : A) : norm' 𝕜 x = 0 ↔ x = 0 := by simp [norm', ← norm_eq_zero, norm_algebra_map_eq] namespace real variables {E : Type*} [semi_normed_group E] [semi_normed_space ℝ E] /-- Hahn-Banach theorem for continuous linear functions over `ℝ`. -/ theorem exists_extension_norm_eq (p : subspace ℝ E) (f : p →L[ℝ] ℝ) : ∃ g : E →L[ℝ] ℝ, (∀ x : p, g x = f x) ∧ ∥g∥ = ∥f∥ := begin rcases exists_extension_of_le_sublinear ⟨p, f⟩ (λ x, ∥f∥ * ∥x∥) (λ c hc x, by simp only [norm_smul c x, real.norm_eq_abs, abs_of_pos hc, mul_left_comm]) (λ x y, _) (λ x, le_trans (le_abs_self _) (f.le_op_norm _)) with ⟨g, g_eq, g_le⟩, set g' := g.mk_continuous (∥f∥) (λ x, abs_le.2 ⟨neg_le.1 $ g.map_neg x ▸ norm_neg x ▸ g_le (-x), g_le x⟩), { refine ⟨g', g_eq, _⟩, { apply le_antisymm (g.mk_continuous_norm_le (norm_nonneg f) _), refine f.op_norm_le_bound (norm_nonneg _) (λ x, _), dsimp at g_eq, rw ← g_eq, apply g'.le_op_norm } }, { simp only [← mul_add], exact mul_le_mul_of_nonneg_left (norm_add_le x y) (norm_nonneg f) } end end real section is_R_or_C open is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] {F : Type*} [semi_normed_group F] [semi_normed_space 𝕜 F] /-- Hahn-Banach theorem for continuous linear functions over `𝕜` satisyfing `is_R_or_C 𝕜`. -/ theorem exists_extension_norm_eq (p : subspace 𝕜 F) (f : p →L[𝕜] 𝕜) : ∃ g : F →L[𝕜] 𝕜, (∀ x : p, g x = f x) ∧ ∥g∥ = ∥f∥ := begin letI : module ℝ F := restrict_scalars.module ℝ 𝕜 F, letI : is_scalar_tower ℝ 𝕜 F := restrict_scalars.is_scalar_tower _ _ _, letI : semi_normed_space ℝ F := semi_normed_space.restrict_scalars _ 𝕜 _, -- Let `fr: p →L[ℝ] ℝ` be the real part of `f`. let fr := re_clm.comp (f.restrict_scalars ℝ), have fr_apply : ∀ x, fr x = re (f x), by { assume x, refl }, -- Use the real version to get a norm-preserving extension of `fr`, which -- we'll call `g : F →L[ℝ] ℝ`. rcases real.exists_extension_norm_eq (p.restrict_scalars ℝ) fr with ⟨g, ⟨hextends, hnormeq⟩⟩, -- Now `g` can be extended to the `F →L[𝕜] 𝕜` we need. refine ⟨g.extend_to_𝕜, _⟩, -- It is an extension of `f`. have h : ∀ x : p, g.extend_to_𝕜 x = f x, { assume x, rw [continuous_linear_map.extend_to_𝕜_apply, ←submodule.coe_smul, hextends, hextends], have : (fr x : 𝕜) - I * ↑(fr (I • x)) = (re (f x) : 𝕜) - (I : 𝕜) * (re (f ((I : 𝕜) • x))), by refl, rw this, apply ext, { simp only [add_zero, algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im', zero_mul, of_real_re, eq_self_iff_true, sub_zero, mul_neg_eq_neg_mul_symm, of_real_neg, mul_re, mul_zero, sub_neg_eq_add, continuous_linear_map.map_smul] }, { simp only [algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im', zero_mul, of_real_re, mul_neg_eq_neg_mul_symm, mul_im, zero_add, of_real_neg, mul_re, sub_neg_eq_add, continuous_linear_map.map_smul] } }, -- And we derive the equality of the norms by bounding on both sides. refine ⟨h, le_antisymm _ _⟩, { calc ∥g.extend_to_𝕜∥ ≤ ∥g∥ : g.extend_to_𝕜.op_norm_le_bound g.op_norm_nonneg (norm_bound _) ... = ∥fr∥ : hnormeq ... ≤ ∥re_clm∥ * ∥f∥ : continuous_linear_map.op_norm_comp_le _ _ ... = ∥f∥ : by rw [re_clm_norm, one_mul] }, { exact f.op_norm_le_bound g.extend_to_𝕜.op_norm_nonneg (λ x, h x ▸ g.extend_to_𝕜.le_op_norm x) } end end is_R_or_C section dual_vector variables (𝕜 : Type v) [is_R_or_C 𝕜] variables {E : Type u} [normed_group E] [normed_space 𝕜 E] open continuous_linear_equiv submodule open_locale classical lemma coord_norm' (x : E) (h : x ≠ 0) : ∥norm' 𝕜 x • coord 𝕜 x h∥ = 1 := by rw [norm_smul, norm_norm', coord_norm, mul_inv_cancel (mt norm_eq_zero.mp h)] /-- Corollary of Hahn-Banach. Given a nonzero element `x` of a normed space, there exists an element of the dual space, of norm `1`, whose value on `x` is `∥x∥`. -/ theorem exists_dual_vector (x : E) (h : x ≠ 0) : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g x = norm' 𝕜 x := begin let p : submodule 𝕜 E := 𝕜 ∙ x, let f := norm' 𝕜 x • coord 𝕜 x h, obtain ⟨g, hg⟩ := exists_extension_norm_eq p f, refine ⟨g, _, _⟩, { rw [hg.2, coord_norm'] }, { calc g x = g (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw coe_mk ... = (norm' 𝕜 x • coord 𝕜 x h) (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw ← hg.1 ... = norm' 𝕜 x : by simp } end /-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, and choosing the dual element arbitrarily when `x = 0`. -/ theorem exists_dual_vector' [nontrivial E] (x : E) : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g x = norm' 𝕜 x := begin by_cases hx : x = 0, { obtain ⟨y, hy⟩ := exists_ne (0 : E), obtain ⟨g, hg⟩ : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g y = norm' 𝕜 y := exists_dual_vector 𝕜 y hy, refine ⟨g, hg.left, _⟩, rw [norm'_def, hx, norm_zero, ring_hom.map_zero, continuous_linear_map.map_zero] }, { exact exists_dual_vector 𝕜 x hx } end end dual_vector
46573e0ee09cf94cf91bd489561d55ac13439cfc
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Structure.lean
f7e5e4aab7743de6d2a854223961a96cb13c04b8
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
8,287
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 Helper functions for retrieving structure information. -/ import Lean.Environment import Lean.ProjFns namespace Lean structure StructureFieldInfo where fieldName : Name projFn : Name subobject? : Option Name -- It is `some parentStructName` if it is a subobject, and `parentStructName` is the name of the parent structure binderInfo : BinderInfo inferMod : Bool -- true if user used the `{}` when declaring the field deriving Inhabited, Repr def StructureFieldInfo.lt (i₁ i₂ : StructureFieldInfo) : Bool := Name.quickLt i₁.fieldName i₂.fieldName structure StructureInfo where structName : Name fieldNames : Array Name := #[] -- sorted by field position in the structure fieldInfo : Array StructureFieldInfo := #[] -- sorted by `fieldName` deriving Inhabited def StructureInfo.lt (i₁ i₂ : StructureInfo) : Bool := Name.quickLt i₁.structName i₂.structName /-- Auxiliary state for structures defined in the current module. -/ private structure StructureState where map : Std.PersistentHashMap Name StructureInfo := {} deriving Inhabited builtin_initialize structureExt : SimplePersistentEnvExtension StructureInfo StructureState ← registerSimplePersistentEnvExtension { name := `structExt addImportedFn := fun _ => {} addEntryFn := fun s e => { s with map := s.map.insert e.structName e } toArrayFn := fun es => es.toArray.qsort StructureInfo.lt } structure StructureDescr where structName : Name fields : Array StructureFieldInfo -- Should use the order the field appear in the constructor. deriving Inhabited def registerStructure (env : Environment) (e : StructureDescr) : Environment := structureExt.addEntry env { structName := e.structName fieldNames := e.fields.map fun e => e.fieldName fieldInfo := e.fields.qsort StructureFieldInfo.lt } def getStructureInfo? (env : Environment) (structName : Name) : Option StructureInfo := match env.getModuleIdxFor? structName with | some modIdx => structureExt.getModuleEntries env modIdx |>.binSearch { structName } StructureInfo.lt | none => structureExt.getState env |>.map.find? structName def getStructureCtor (env : Environment) (constName : Name) : ConstructorVal := match env.find? constName with | some (ConstantInfo.inductInfo { isRec := false, ctors := [ctorName], .. }) => match env.find? ctorName with | some (ConstantInfo.ctorInfo val) => val | _ => panic! "ill-formed environment" | _ => panic! "structure expected" /-- Get direct field names for the given structure. -/ def getStructureFields (env : Environment) (structName : Name) : Array Name := if let some info := getStructureInfo? env structName then info.fieldNames else panic! "structure expected" def getFieldInfo? (env : Environment) (structName : Name) (fieldName : Name) : Option StructureFieldInfo := if let some info := getStructureInfo? env structName then info.fieldInfo.binSearch { fieldName := fieldName, projFn := arbitrary, subobject? := none, binderInfo := arbitrary, inferMod := false } StructureFieldInfo.lt else none /-- If `fieldName` represents the relation to a parent structure `S`, return `S` -/ def isSubobjectField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if let some fieldInfo := getFieldInfo? env structName fieldName then fieldInfo.subobject? else none /-- Return immediate parent structures -/ def getParentStructures (env : Environment) (structName : Name) : Array Name := let fieldNames := getStructureFields env structName; fieldNames.foldl (init := #[]) fun acc fieldName => match isSubobjectField? env structName fieldName with | some parentStructName => acc.push parentStructName | none => acc /-- Return all parent structures -/ partial def getAllParentStructures (env : Environment) (structName : Name) : Array Name := visit structName |>.run #[] |>.2 where visit (structName : Name) : StateT (Array Name) Id Unit := do for p in getParentStructures env structName do modify fun s => s.push p visit p /-- `findField? env S fname`. If `fname` is defined in a parent `S'` of `S`, return `S'` -/ partial def findField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if (getStructureFields env structName).contains fieldName then some structName else getParentStructures env structName |>.findSome? fun parentStructName => findField? env parentStructName fieldName private partial def getStructureFieldsFlattenedAux (env : Environment) (structName : Name) (fullNames : Array Name) (includeSubobjectFields : Bool) : Array Name := (getStructureFields env structName).foldl (init := fullNames) fun fullNames fieldName => match isSubobjectField? env structName fieldName with | some parentStructName => let fullNames := if includeSubobjectFields then fullNames.push fieldName else fullNames getStructureFieldsFlattenedAux env parentStructName fullNames includeSubobjectFields | none => fullNames.push fieldName def getStructureFieldsFlattened (env : Environment) (structName : Name) (includeSubobjectFields := true) : Array Name := getStructureFieldsFlattenedAux env structName #[] includeSubobjectFields /-- Return true if `constName` is the name of an inductive datatype created using the `structure` or `class` commands. We perform the check by testing whether auxiliary projection functions have been created. -/ def isStructure (env : Environment) (constName : Name) : Bool := getStructureInfo? env constName |>.isSome def getProjFnForField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if let some fieldInfo := getFieldInfo? env structName fieldName then some fieldInfo.projFn else none def mkDefaultFnOfProjFn (projFn : Name) : Name := projFn ++ `_default def getDefaultFnForField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if let some projName := getProjFnForField? env structName fieldName then let defFn := mkDefaultFnOfProjFn projName if env.contains defFn then defFn else none else -- Check if we have a default function for a default values overriden by substructure. let defFn := mkDefaultFnOfProjFn (structName ++ fieldName) if env.contains defFn then defFn else none partial def getPathToBaseStructureAux (env : Environment) (baseStructName : Name) (structName : Name) (path : List Name) : Option (List Name) := if baseStructName == structName then some path.reverse else let fieldNames := getStructureFields env structName; fieldNames.findSome? fun fieldName => match isSubobjectField? env structName fieldName with | none => none | some parentStructName => match getProjFnForField? env structName fieldName with | none => none | some projFn => getPathToBaseStructureAux env baseStructName parentStructName (projFn :: path) /-- If `baseStructName` is an ancestor structure for `structName`, then return a sequence of projection functions to go from `structName` to `baseStructName`. -/ def getPathToBaseStructure? (env : Environment) (baseStructName : Name) (structName : Name) : Option (List Name) := getPathToBaseStructureAux env baseStructName structName [] /-- Return true iff `constName` is the a non-recursive inductive datatype that has only one constructor. -/ def isStructureLike (env : Environment) (constName : Name) : Bool := match env.find? constName with | some (ConstantInfo.inductInfo { isRec := false, ctors := [ctor], numIndices := 0, .. }) => true | _ => false /-- Return number of fields for a structure-like type -/ def getStructureLikeNumFields (env : Environment) (constName : Name) : Nat := match env.find? constName with | some (ConstantInfo.inductInfo { isRec := false, ctors := [ctor], numIndices := 0, .. }) => match env.find? ctor with | some (ConstantInfo.ctorInfo { numFields := n, .. }) => n | _ => 0 | _ => 0 end Lean
8a85596de534de754b742ef9eae943019d5c626f
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/valuation/basic.lean
16891ee601c63d88186fbad1aea9a90da5dbb50c
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,975
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Johan Commelin, Patrick Massot -/ import algebra.order.with_zero import algebra.group_power import ring_theory.ideal.operations import algebra.punit_instances /-! # The basics of valuation theory. The basic theory of valuations (non-archimedean norms) on a commutative ring, following T. Wedhorn's unpublished notes “Adic Spaces” ([wedhorn_adic]). The definition of a valuation we use here is Definition 1.22 of [wedhorn_adic]. A valuation on a ring `R` is a monoid homomorphism `v` to a linearly ordered commutative monoid with zero, that in addition satisfies the following two axioms: * `v 0 = 0` * `∀ x y, v (x + y) ≤ max (v x) (v y)` `valuation R Γ₀`is the type of valuations `R → Γ₀`, with a coercion to the underlying function. If `v` is a valuation from `R` to `Γ₀` then the induced group homomorphism `units(R) → Γ₀` is called `unit_map v`. The equivalence "relation" `is_equiv v₁ v₂ : Prop` defined in 1.27 of [wedhorn_adic] is not strictly speaking a relation, because `v₁ : valuation R Γ₁` and `v₂ : valuation R Γ₂` might not have the same type. This corresponds in ZFC to the set-theoretic difficulty that the class of all valuations (as `Γ₀` varies) on a ring `R` is not a set. The "relation" is however reflexive, symmetric and transitive in the obvious sense. Note that we use 1.27(iii) of [wedhorn_adic] as the definition of equivalence. The support of a valuation `v : valuation R Γ₀` is `supp v`. If `J` is an ideal of `R` with `h : J ⊆ supp v` then the induced valuation on R / J = `ideal.quotient J` is `on_quot v h`. ## Main definitions * `valuation R Γ₀`, the type of valuations on `R` with values in `Γ₀` * `valuation.is_equiv`, the heterogeneous equivalence relation on valuations * `valuation.supp`, the support of a valuation * `add_valuation R Γ₀`, the type of additive valuations on `R` with values in a linearly ordered additive commutative group with a top element, `Γ₀`. ## Implementation Details `add_valuation R Γ₀` is implemented as `valuation R (multiplicative (order_dual Γ₀))`. -/ open_locale classical big_operators noncomputable theory open function ideal variables {R : Type*} -- This will be a ring, assumed commutative in some sections section variables (R) (Γ₀ : Type*) [linear_ordered_comm_monoid_with_zero Γ₀] [ring R] /-- The type of `Γ₀`-valued valuations on `R`. -/ @[nolint has_inhabited_instance] structure valuation extends monoid_with_zero_hom R Γ₀ := (map_add' : ∀ x y, to_fun (x + y) ≤ max (to_fun x) (to_fun y)) /-- The `monoid_with_zero_hom` underlying a valuation. -/ add_decl_doc valuation.to_monoid_with_zero_hom end namespace valuation variables {Γ₀ : Type*} variables {Γ'₀ : Type*} variables {Γ''₀ : Type*} [linear_ordered_comm_monoid_with_zero Γ''₀] section basic variables (R) (Γ₀) [ring R] section monoid variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] /-- A valuation is coerced to the underlying function `R → Γ₀`. -/ instance : has_coe_to_fun (valuation R Γ₀) := { F := λ _, R → Γ₀, coe := λ v, v.to_monoid_with_zero_hom.to_fun } /-- A valuation is coerced to a monoid morphism R → Γ₀. -/ instance : has_coe (valuation R Γ₀) (monoid_with_zero_hom R Γ₀) := ⟨valuation.to_monoid_with_zero_hom⟩ variables {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp, norm_cast] lemma coe_coe : ((v : monoid_with_zero_hom R Γ₀) : R → Γ₀) = v := rfl @[simp] lemma map_zero : v 0 = 0 := v.map_zero' @[simp] lemma map_one : v 1 = 1 := v.map_one' @[simp] lemma map_mul : ∀ x y, v (x * y) = v x * v y := v.map_mul' @[simp] lemma map_add : ∀ x y, v (x + y) ≤ max (v x) (v y) := v.map_add' lemma map_add_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x + y) ≤ g := le_trans (v.map_add x y) $ max_le hx hy lemma map_add_lt {x y g} (hx : v x < g) (hy : v y < g) : v (x + y) < g := lt_of_le_of_lt (v.map_add x y) $ max_lt hx hy lemma map_sum_le {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, v (f i) ≤ g) : v (∑ i in s, f i) ≤ g := begin refine finset.induction_on s (λ _, trans_rel_right (≤) v.map_zero zero_le') (λ a s has ih hf, _) hf, rw finset.forall_mem_insert at hf, rw finset.sum_insert has, exact v.map_add_le hf.1 (ih hf.2) end lemma map_sum_lt {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ 0) (hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g := begin refine finset.induction_on s (λ _, trans_rel_right (<) v.map_zero (zero_lt_iff.2 hg)) (λ a s has ih hf, _) hf, rw finset.forall_mem_insert at hf, rw finset.sum_insert has, exact v.map_add_lt hf.1 (ih hf.2) end lemma map_sum_lt' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : 0 < g) (hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g := v.map_sum_lt (ne_of_gt hg) hf @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = (v x)^n := v.to_monoid_with_zero_hom.to_monoid_hom.map_pow @[ext] lemma ext {v₁ v₂ : valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := by { rcases v₁ with ⟨⟨⟩⟩, rcases v₂ with ⟨⟨⟩⟩, congr, funext r, exact h r } lemma ext_iff {v₁ v₂ : valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := ⟨λ h r, congr_arg _ h, ext⟩ -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is a valuation on a division ring then `v(x) = 0` iff `x = 0`. -/ @[simp] lemma zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x = 0 ↔ x = 0 := v.to_monoid_with_zero_hom.map_eq_zero lemma ne_zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x ≠ 0 ↔ x ≠ 0 := v.to_monoid_with_zero_hom.map_ne_zero theorem unit_map_eq (u : units R) : (units.map (v : R →* Γ₀) u : Γ₀) = v u := rfl /-- A ring homomorphism `S → R` induces a map `valuation R Γ₀ → valuation S Γ₀`. -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : valuation R Γ₀) : valuation S Γ₀ := { to_fun := v ∘ f, map_add' := λ x y, by simp only [comp_app, map_add, f.map_add], .. v.to_monoid_with_zero_hom.comp f.to_monoid_with_zero_hom, } @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := ext $ λ r, rfl lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := ext $ λ r, rfl /-- A `≤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `valuation R Γ₀ → valuation R Γ'₀`. -/ def map (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (v : valuation R Γ₀) : valuation R Γ'₀ := { to_fun := f ∘ v, map_add' := λ r s, calc f (v (r + s)) ≤ f (max (v r) (v s)) : hf (v.map_add r s) ... = max (f (v r)) (f (v s)) : hf.map_max, .. monoid_with_zero_hom.comp f v.to_monoid_with_zero_hom } /-- Two valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/ def is_equiv (v₁ : valuation R Γ₀) (v₂ : valuation R Γ'₀) : Prop := ∀ r s, v₁ r ≤ v₁ s ↔ v₂ r ≤ v₂ s end monoid section group variables [linear_ordered_comm_group_with_zero Γ₀] {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp] lemma map_inv {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x⁻¹ = (v x)⁻¹ := v.to_monoid_with_zero_hom.map_inv x lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = (v x)⁻¹ := v.to_monoid_with_zero_hom.to_monoid_hom.map_units_inv x @[simp] lemma map_neg (x : R) : v (-x) = v x := v.to_monoid_with_zero_hom.to_monoid_hom.map_neg x lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) := v.to_monoid_with_zero_hom.to_monoid_hom.map_sub_swap x y lemma map_sub (x y : R) : v (x - y) ≤ max (v x) (v y) := calc v (x - y) = v (x + -y) : by rw [sub_eq_add_neg] ... ≤ max (v x) (v $ -y) : v.map_add _ _ ... = max (v x) (v y) : by rw map_neg lemma map_sub_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x - y) ≤ g := begin rw sub_eq_add_neg, exact v.map_add_le hx (le_trans (le_of_eq (v.map_neg y)) hy) end lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = max (v x) (v y) := begin suffices : ¬v (x + y) < max (v x) (v y), from or_iff_not_imp_right.1 (le_iff_eq_or_lt.1 (v.map_add x y)) this, intro h', wlog vyx : v y < v x using x y, { apply lt_or_gt_of_ne h.symm }, { rw max_eq_left_of_lt vyx at h', apply lt_irrefl (v x), calc v x = v ((x+y) - y) : by simp ... ≤ max (v $ x + y) (v y) : map_sub _ _ _ ... < v x : max_lt h' vyx }, { apply this h.symm, rwa [add_comm, max_comm] at h' } end lemma map_eq_of_sub_lt (h : v (y - x) < v x) : v y = v x := begin have := valuation.map_add_of_distinct_val v (ne_of_gt h).symm, rw max_eq_right (le_of_lt h) at this, simpa using this end /-- The subgroup of elements whose valuation is less than a certain unit.-/ def lt_add_subgroup (v : valuation R Γ₀) (γ : units Γ₀) : add_subgroup R := { carrier := {x | v x < γ}, zero_mem' := by { have h := units.ne_zero γ, contrapose! h, simpa using h }, add_mem' := λ x y x_in y_in, lt_of_le_of_lt (v.map_add x y) (max_lt x_in y_in), neg_mem' := λ x x_in, by rwa [set.mem_set_of_eq, map_neg] } end group end basic -- end of section namespace is_equiv variables [ring R] variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] variables {v : valuation R Γ₀} variables {v₁ : valuation R Γ₀} {v₂ : valuation R Γ'₀} {v₃ : valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := λ _ _, iff.refl _ @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := λ _ _, iff.symm (h _ _) @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := λ _ _, iff.trans (h₁₂ _ _) (h₂₃ _ _) lemma of_eq {v' : valuation R Γ₀} (h : v = v') : v.is_equiv v' := by { subst h } lemma map {v' : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f hf).is_equiv (v'.map f hf) := let H : strict_mono f := hf.strict_mono_of_injective inf in λ r s, calc f (v r) ≤ f (v s) ↔ v r ≤ v s : by rw H.le_iff_le ... ↔ v' r ≤ v' s : h r s ... ↔ f (v' r) ≤ f (v' s) : by rw H.le_iff_le /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := λ r s, h (f r) (f s) lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := by simpa only [le_antisymm_iff] using and_congr (h r s) (h s r) lemma ne_zero (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ 0 ↔ v₂ r ≠ 0 := begin have : v₁ r ≠ v₁ 0 ↔ v₂ r ≠ v₂ 0 := not_iff_not_of_iff h.val_eq, rwa [v₁.map_zero, v₂.map_zero] at this, end end is_equiv -- end of namespace section lemma is_equiv_of_map_strict_mono [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] [ring R] {v : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (H : strict_mono f) : is_equiv (v.map f (H.monotone)) v := λ x y, ⟨H.le_iff_le.mp, λ h, H.monotone h⟩ lemma is_equiv_of_val_le_one [linear_ordered_comm_group_with_zero Γ₀] [linear_ordered_comm_group_with_zero Γ'₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) (v' : valuation K Γ'₀) (h : ∀ {x:K}, v x ≤ 1 ↔ v' x ≤ 1) : v.is_equiv v' := begin intros x y, by_cases hy : y = 0, { simp [hy, zero_iff], }, rw show y = 1 * y, by rw one_mul, rw [← (inv_mul_cancel_right₀ hy x)], iterate 2 {rw [v.map_mul _ y, v'.map_mul _ y]}, rw [v.map_one, v'.map_one], split; intro H, { apply mul_le_mul_right', replace hy := v.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h at H, }, { apply mul_le_mul_right', replace hy := v'.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h, }, end end section supp variables [comm_ring R] variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] variables (v : valuation R Γ₀) /-- The support of a valuation `v : R → Γ₀` is the ideal of `R` where `v` vanishes. -/ def supp : ideal R := { carrier := {x | v x = 0}, zero_mem' := map_zero v, add_mem' := λ x y hx hy, le_zero_iff.mp $ calc v (x + y) ≤ max (v x) (v y) : v.map_add x y ... ≤ 0 : max_le (le_zero_iff.mpr hx) (le_zero_iff.mpr hy), smul_mem' := λ c x hx, calc v (c * x) = v c * v x : map_mul v c x ... = v c * 0 : congr_arg _ hx ... = 0 : mul_zero _ } @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = 0 := iff.rfl -- @[simp] lemma mem_supp_iff' (x : R) : x ∈ (supp v : set R) ↔ v x = 0 := iff.rfl /-- The support of a valuation is a prime ideal. -/ instance [nontrivial Γ₀] [no_zero_divisors Γ₀] : ideal.is_prime (supp v) := ⟨λ (h : v.supp = ⊤), one_ne_zero $ show (1 : Γ₀) = 0, from calc 1 = v 1 : v.map_one.symm ... = 0 : show (1:R) ∈ supp v, by { rw h, trivial }, λ x y hxy, begin show v x = 0 ∨ v y = 0, change v (x * y) = 0 at hxy, rw [v.map_mul x y] at hxy, exact eq_zero_or_eq_zero_of_mul_eq_zero hxy end⟩ lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := begin have aux : ∀ a s, v s = 0 → v (a + s) ≤ v a, { intros a' s' h', refine le_trans (v.map_add a' s') (max_le (le_refl _) _), simp [h'], }, apply le_antisymm (aux a s h), calc v a = v (a + s + -s) : by simp ... ≤ v (a + s) : aux (a + s) (-s) (by rwa ←ideal.neg_mem_iff at h) end /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := λ q, quotient.lift_on' q v $ λ a b h, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : valuation J.quotient Γ₀ := { to_fun := v.on_quot_val hJ, map_zero' := v.map_zero, map_one' := v.map_one, map_mul' := λ xbar ybar, quotient.ind₂' v.map_mul xbar ybar, map_add' := λ xbar ybar, quotient.ind₂' v.map_add xbar ybar } @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := ext $ λ r, begin refine @quotient.lift_on_mk _ _ (J.quotient_rel) v (λ a b h, _) _, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) end lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := ideal.ext $ λ x, begin rw [mem_supp_iff, ideal.mem_comap, mem_supp_iff], refl, end lemma self_le_supp_comap (J : ideal R) (v : valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := by { rw [comap_supp, ← ideal.map_le_iff_le_comap], simp } @[simp] lemma comap_on_quot_eq (J : ideal R) (v : valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := ext $ by { rintro ⟨x⟩, refl } /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := begin apply le_antisymm, { rintro ⟨x⟩ hx, apply ideal.subset_span, exact ⟨x, hx, rfl⟩ }, { rw ideal.map_le_iff_le_comap, intros x hx, exact hx } end lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := by { rw supp_quot, exact ideal.map_quotient_self _ } end supp -- end of section end valuation section add_monoid variables (R) [ring R] (Γ₀ : Type*) [linear_ordered_add_comm_monoid_with_top Γ₀] /-- The type of `Γ₀`-valued additive valuations on `R`. -/ @[nolint has_inhabited_instance] def add_valuation := valuation R (multiplicative (order_dual Γ₀)) end add_monoid namespace add_valuation variables {Γ₀ : Type*} {Γ'₀ : Type*} section basic section monoid variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables (R) (Γ₀) [ring R] /-- A valuation is coerced to the underlying function `R → Γ₀`. -/ instance : has_coe_to_fun (add_valuation R Γ₀) := { F := λ _, R → Γ₀, coe := λ v, v.to_monoid_with_zero_hom.to_fun } variables {R} {Γ₀} (v : add_valuation R Γ₀) {x y z : R} section variables (f : R → Γ₀) (h0 : f 0 = ⊤) (h1 : f 1 = 0) variables (hadd : ∀ x y, min (f x) (f y) ≤ f (x + y)) (hmul : ∀ x y, f (x * y) = f x + f y) /-- An alternate constructor of `add_valuation`, that doesn't reference `multiplicative (order_dual Γ₀)` -/ def of : add_valuation R Γ₀ := { to_fun := f, map_one' := h1, map_zero' := h0, map_add' := hadd, map_mul' := hmul } variables {h0} {h1} {hadd} {hmul} {r : R} @[simp] theorem of_apply : (of f h0 h1 hadd hmul) r = f r := rfl end @[simp] lemma map_zero : v 0 = ⊤ := v.map_zero @[simp] lemma map_one : v 1 = 0 := v.map_one @[simp] lemma map_mul : ∀ x y, v (x * y) = v x + v y := v.map_mul @[simp] lemma map_add : ∀ x y, min (v x) (v y) ≤ v (x + y) := v.map_add lemma map_le_add {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x + y) := v.map_add_le hx hy lemma map_lt_add {x y g} (hx : g < v x) (hy : g < v y) : g < v (x + y) := v.map_add_lt hx hy lemma map_le_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, g ≤ v (f i)) : g ≤ v (∑ i in s, f i) := v.map_sum_le hf lemma map_lt_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ ⊤) (hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt hg hf lemma map_lt_sum' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g < ⊤) (hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt' hg hf @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = n • (v x) := v.map_pow @[ext] lemma ext {v₁ v₂ : add_valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := valuation.ext h lemma ext_iff {v₁ v₂ : add_valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := valuation.ext_iff -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is an additive valuation on a division ring then `v(x) = ⊤` iff `x = 0`. -/ @[simp] lemma top_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x = ⊤ ↔ x = 0 := v.zero_iff lemma ne_top_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x ≠ ⊤ ↔ x ≠ 0 := v.ne_zero_iff /-- A ring homomorphism `S → R` induces a map `add_valuation R Γ₀ → add_valuation S Γ₀`. -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : add_valuation R Γ₀) : add_valuation S Γ₀ := v.comap f @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := v.comap_id lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := v.comap_comp f g /-- A `≤`-preserving, `⊤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `add_valuation R Γ₀ → add_valuation R Γ'₀`. -/ def map (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (v : add_valuation R Γ₀) : add_valuation R Γ'₀ := v.map { to_fun := f, map_mul' := f.map_add, map_one' := f.map_zero, map_zero' := ht } (λ x y h, hf h) /-- Two additive valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/ def is_equiv (v₁ : add_valuation R Γ₀) (v₂ : add_valuation R Γ'₀) : Prop := v₁.is_equiv v₂ end monoid section group variables [linear_ordered_add_comm_group_with_top Γ₀] [ring R] (v : add_valuation R Γ₀) {x y z : R} @[simp] lemma map_inv {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x⁻¹ = - (v x) := v.map_inv lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = - (v x) := v.map_units_inv x @[simp] lemma map_neg (x : R) : v (-x) = v x := v.map_neg x lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) := v.map_sub_swap x y lemma map_sub (x y : R) : min (v x) (v y) ≤ v (x - y) := v.map_sub x y lemma map_le_sub {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x - y) := v.map_sub_le hx hy lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = min (v x) (v y) := v.map_add_of_distinct_val h lemma map_eq_of_lt_sub (h : v x < v (y - x)) : v y = v x := v.map_eq_of_sub_lt h end group end basic namespace is_equiv variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables [ring R] variables {Γ''₀ : Type*} [linear_ordered_add_comm_monoid_with_top Γ''₀] variables {v : add_valuation R Γ₀} variables {v₁ : add_valuation R Γ₀} {v₂ : add_valuation R Γ'₀} {v₃ : add_valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := valuation.is_equiv.refl @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := h.symm @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := h₁₂.trans h₂₃ lemma of_eq {v' : add_valuation R Γ₀} (h : v = v') : v.is_equiv v' := valuation.is_equiv.of_eq h lemma map {v' : add_valuation R Γ₀} (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f ht hf).is_equiv (v'.map f ht hf) := h.map { to_fun := f, map_mul' := f.map_add, map_one' := f.map_zero, map_zero' := ht } (λ x y h, hf h) inf /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := h.comap f lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := h.val_eq lemma ne_top (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ ⊤ ↔ v₂ r ≠ ⊤ := h.ne_zero end is_equiv section supp variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables [comm_ring R] variables (v : add_valuation R Γ₀) /-- The support of an additive valuation `v : R → Γ₀` is the ideal of `R` where `v x = ⊤` -/ def supp : ideal R := v.supp @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = ⊤ := v.mem_supp_iff x lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := v.map_add_supp a h /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := v.on_quot_val hJ /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : add_valuation J.quotient Γ₀ := v.on_quot hJ @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := v.on_quot_comap_eq hJ lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := v.comap_supp f lemma self_le_supp_comap (J : ideal R) (v : add_valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := v.self_le_supp_comap J @[simp] lemma comap_on_quot_eq (J : ideal R) (v : add_valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := v.comap_on_quot_eq J /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := v.supp_quot hJ lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := v.supp_quot_supp end supp -- end of section attribute [irreducible] add_valuation end add_valuation
08c7d98458302c47568f8232d9f541554813930f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/free_monoid.lean
d910494df0201ec32b172f32cd4f43ca468f6838
[ "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
4,985
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Yury Kudryashov -/ import data.equiv.basic import data.list.basic import algebra.star.basic /-! # Free monoid over a given alphabet ## Main definitions * `free_monoid α`: free monoid over alphabet `α`; defined as a synonym for `list α` with multiplication given by `(++)`. * `free_monoid.of`: embedding `α → free_monoid α` sending each element `x` to `[x]`; * `free_monoid.lift`: natural equivalence between `α → M` and `free_monoid α →* M` * `free_monoid.map`: embedding of `α → β` into `free_monoid α →* free_monoid β` given by `list.map`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {M : Type*} [monoid M] {N : Type*} [monoid N] /-- Free monoid over a given alphabet. -/ @[to_additive "Free nonabelian additive monoid over a given alphabet"] def free_monoid (α) := list α namespace free_monoid @[to_additive] instance : monoid (free_monoid α) := { one := [], mul := λ x y, (x ++ y : list α), mul_one := by intros; apply list.append_nil, one_mul := by intros; refl, mul_assoc := by intros; apply list.append_assoc } @[to_additive] instance : inhabited (free_monoid α) := ⟨1⟩ @[to_additive] lemma one_def : (1 : free_monoid α) = [] := rfl @[to_additive] lemma mul_def (xs ys : list α) : (xs * ys : free_monoid α) = (xs ++ ys : list α) := rfl /-- Embeds an element of `α` into `free_monoid α` as a singleton list. -/ @[to_additive "Embeds an element of `α` into `free_add_monoid α` as a singleton list." ] def of (x : α) : free_monoid α := [x] @[to_additive] lemma of_def (x : α) : of x = [x] := rfl @[to_additive] lemma of_injective : function.injective (@of α) := λ a b, list.head_eq_of_cons_eq /-- Recursor for `free_monoid` using `1` and `of x * xs` instead of `[]` and `x :: xs`. -/ @[to_additive "Recursor for `free_add_monoid` using `0` and `of x + xs` instead of `[]` and `x :: xs`."] def rec_on {C : free_monoid α → Sort*} (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : C xs := list.rec_on xs h0 ih attribute [elab_as_eliminator] rec_on free_add_monoid.rec_on @[to_additive] lemma hom_eq ⦃f g : free_monoid α →* M⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := monoid_hom.ext $ λ l, rec_on l (f.map_one.trans g.map_one.symm) $ λ x xs hxs, by simp only [h, hxs, monoid_hom.map_mul] attribute [ext] hom_eq free_add_monoid.hom_eq /-- Equivalence between maps `α → M` and monoid homomorphisms `free_monoid α →* M`. -/ @[to_additive "Equivalence between maps `α → A` and additive monoid homomorphisms `free_add_monoid α →+ A`."] def lift : (α → M) ≃ (free_monoid α →* M) := { to_fun := λ f, ⟨λ l, (l.map f).prod, rfl, λ l₁ l₂, by simp only [mul_def, list.map_append, list.prod_append]⟩, inv_fun := λ f x, f (of x), left_inv := λ f, funext $ λ x, one_mul (f x), right_inv := λ f, hom_eq $ λ x, one_mul (f (of x)) } @[simp, to_additive] lemma lift_symm_apply (f : free_monoid α →* M) : lift.symm f = f ∘ of := rfl @[to_additive] lemma lift_apply (f : α → M) (l : free_monoid α) : lift f l = (l.map f).prod := rfl @[to_additive] lemma lift_comp_of (f : α → M) : (lift f) ∘ of = f := lift.symm_apply_apply f @[simp, to_additive] lemma lift_eval_of (f : α → M) (x : α) : lift f (of x) = f x := congr_fun (lift_comp_of f) x @[simp, to_additive] lemma lift_restrict (f : free_monoid α →* M) : lift (f ∘ of) = f := lift.apply_symm_apply f @[to_additive] lemma comp_lift (g : M →* N) (f : α → M) : g.comp (lift f) = lift (g ∘ f) := by { ext, simp } @[to_additive] lemma hom_map_lift (g : M →* N) (f : α → M) (x : free_monoid α) : g (lift f x) = lift (g ∘ f) x := monoid_hom.ext_iff.1 (comp_lift g f) x /-- The unique monoid homomorphism `free_monoid α →* free_monoid β` that sends each `of x` to `of (f x)`. -/ @[to_additive "The unique additive monoid homomorphism `free_add_monoid α →+ free_add_monoid β` that sends each `of x` to `of (f x)`."] def map (f : α → β) : free_monoid α →* free_monoid β := { to_fun := list.map f, map_one' := rfl, map_mul' := λ l₁ l₂, list.map_append _ _ _ } @[simp, to_additive] lemma map_of (f : α → β) (x : α) : map f (of x) = of (f x) := rfl @[to_additive] lemma lift_of_comp_eq_map (f : α → β) : lift (λ x, of (f x)) = map f := hom_eq $ λ x, rfl @[to_additive] lemma map_comp (g : β → γ) (f : α → β) : map (g ∘ f) = (map g).comp (map f) := hom_eq $ λ x, rfl instance : star_monoid (free_monoid α) := { star := list.reverse, star_involutive := list.reverse_reverse, star_mul := list.reverse_append, } @[simp] lemma star_of (x : α) : star (of x) = of x := rfl /-- Note that `star_one` is already a global simp lemma, but this one works with dsimp too -/ @[simp] lemma star_one : star (1 : free_monoid α) = 1 := rfl end free_monoid
8091fac2347cd43f996b4ee6c60b74761dcbedda
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/meta/exceptional.lean
70364d4c02781915ad815e96546497e135003b03
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,756
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.category.monad init.meta.format /- Remark: we use a function that produces a format object as the exception information. Motivation: the formatting object may be big, and we may create it on demand. -/ meta inductive exceptional (α : Type) | success : α → exceptional | exception : (options → format) → exceptional section open exceptional variables {α : Type} variables [has_to_string α] protected meta def exceptional.to_string : exceptional α → string | (success a) := to_string a | (exception .α e) := "Exception: " ++ to_string (e options.mk) meta instance : has_to_string (exceptional α) := has_to_string.mk exceptional.to_string end namespace exceptional variables {α β : Type} protected meta def to_bool : exceptional α → bool | (success _) := tt | (exception .α _) := ff protected meta def to_option : exceptional α → option α | (success a) := some a | (exception .α _) := none @[inline] protected meta def fmap (f : α → β) (e : exceptional α) : exceptional β := exceptional.cases_on e (λ a, success (f a)) (λ f, exception β f) @[inline] protected meta def bind (e₁ : exceptional α) (e₂ : α → exceptional β) : exceptional β := exceptional.cases_on e₁ (λ a, e₂ a) (λ f, exception β f) @[inline] protected meta def return (a : α) : exceptional α := success a @[inline] meta def fail (f : format) : exceptional α := exception α (λ u, f) end exceptional meta instance : monad exceptional := {map := @exceptional.fmap, ret := @exceptional.return, bind := @exceptional.bind}
f107009382b8d476e85dee4e3e0bd0c209f6bb67
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Load/Elab.lean
98ea541e36a558ceb0bb083364c918d0d8d5cbbf
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,550
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lean.Elab.Frontend import Lake.DSL.Extensions import Lake.Load.Config import Lake.Util.Log namespace Lake open Lean System deriving instance BEq, Hashable for Import /- Cache for the imported header environment of Lake configuration files. -/ initialize importEnvCache : IO.Ref (HashMap (List Import) Environment) ← IO.mkRef {} /-- Like `Lean.Elab.processHeader`, but using `importEnvCache`. -/ def processHeader (header : Syntax) (opts : Options) (trustLevel : UInt32) (inputCtx : Parser.InputContext) : StateT MessageLog IO Environment := do try let imports := Elab.headerToImports header if let some env := (← importEnvCache.get).find? imports then return env let env ← importModules imports opts trustLevel importEnvCache.modify (·.insert imports env) return env catch e => let pos := inputCtx.fileMap.toPosition <| header.getPos?.getD 0 modify (·.add { fileName := inputCtx.fileName, data := toString e, pos }) mkEmptyEnvironment /-- Main module `Name` of a Lake configuration file. -/ def configModuleName : Name := `lakefile /-- Elaborate `configFile` with the given package directory and options. -/ def elabConfigFile (pkgDir : FilePath) (configOpts : NameMap String) (leanOpts := Options.empty) (configFile := pkgDir / defaultConfigFile) : LogIO Environment := do -- Read file and initialize environment let input ← IO.FS.readFile configFile let inputCtx := Parser.mkInputContext input configFile.toString let (header, parserState, messages) ← Parser.parseHeader inputCtx let (env, messages) ← processHeader header leanOpts 1024 inputCtx messages let env := env.setMainModule configModuleName -- Configure extensions let env := dirExt.setState env pkgDir let env := optsExt.setState env configOpts -- Elaborate File let commandState := Elab.Command.mkState env messages leanOpts let s ← Elab.IO.processCommands inputCtx parserState commandState -- Log messages for msg in s.commandState.messages.toList do match msg.severity with | MessageSeverity.information => logInfo (← msg.toString) | MessageSeverity.warning => logWarning (← msg.toString) | MessageSeverity.error => logError (← msg.toString) -- Check result if s.commandState.messages.hasErrors then error s!"{configFile}: package configuration has errors" else return s.commandState.env
7a0c7607169fea11b5a0da0eeb3c318659867030
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/measurable_space_def.lean
65c9533c049ac973c4507a19a928b49fdccca565
[ "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,145
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.set.countable import logic.encodable.lattice import order.conditionally_complete_lattice import order.disjointed import order.symm_diff /-! # Measurable spaces and measurable functions This file defines measurable spaces and measurable functions. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. Do not add measurability lemmas (which could be tagged with @[measurability]) to this file, since the measurability tactic is downstream from here. Use `measure_theory.measurable_space` instead. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function -/ open set encodable function equiv open_locale classical variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (measurable_set' : set α → Prop) (measurable_set_empty : measurable_set' ∅) (measurable_set_compl : ∀ s, measurable_set' s → measurable_set' sᶜ) (measurable_set_Union : ∀ f : ℕ → set α, (∀ i, measurable_set' (f i)) → measurable_set' (⋃ i, f i)) attribute [class] measurable_space instance [h : measurable_space α] : measurable_space αᵒᵈ := h section /-- `measurable_set s` means that `s` is measurable (in the ambient measure space on `α`) -/ def measurable_set [measurable_space α] : set α → Prop := ‹measurable_space α›.measurable_set' localized "notation (name := measurable_set_of) `measurable_set[` m `]` := @measurable_set hole! m" in measure_theory @[simp] lemma measurable_set.empty [measurable_space α] : measurable_set (∅ : set α) := ‹measurable_space α›.measurable_set_empty variable {m : measurable_space α} include m lemma measurable_set.compl : measurable_set s → measurable_set sᶜ := ‹measurable_space α›.measurable_set_compl s lemma measurable_set.of_compl (h : measurable_set sᶜ) : measurable_set s := compl_compl s ▸ h.compl @[simp] lemma measurable_set.compl_iff : measurable_set sᶜ ↔ measurable_set s := ⟨measurable_set.of_compl, measurable_set.compl⟩ @[simp] lemma measurable_set.univ : measurable_set (univ : set α) := by simpa using (@measurable_set.empty α _).compl @[nontriviality] lemma subsingleton.measurable_set [subsingleton α] {s : set α} : measurable_set s := subsingleton.set_cases measurable_set.empty measurable_set.univ s lemma measurable_set.congr {s t : set α} (hs : measurable_set s) (h : s = t) : measurable_set t := by rwa ← h lemma measurable_set.bUnion_decode₂ [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) (n : ℕ) : measurable_set (⋃ b ∈ decode₂ β n, f b) := encodable.Union_decode₂_cases measurable_set.empty h lemma measurable_set.Union [countable ι] ⦃f : ι → set α⦄ (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := begin casesI nonempty_encodable (plift ι), rw [←Union_plift_down, ←encodable.Union_decode₂], exact ‹measurable_space α›.measurable_set_Union _ (measurable_set.bUnion_decode₂ $ λ _, h _), end lemma measurable_set.bUnion {f : β → set α} {s : set β} (hs : s.countable) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact measurable_set.Union (by simpa using h) end lemma set.finite.measurable_set_bUnion {f : β → set α} {s : set β} (hs : s.finite) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := measurable_set.bUnion hs.countable h lemma finset.measurable_set_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := s.finite_to_set.measurable_set_bUnion h lemma measurable_set.sUnion {s : set (set α)} (hs : s.countable) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h } lemma set.finite.measurable_set_sUnion {s : set (set α)} (hs : s.finite) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := measurable_set.sUnion hs.countable h lemma measurable_set.Inter [countable ι] {f : ι → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.compl_iff.1 $ by { rw compl_Inter, exact measurable_set.Union (λ b, (h b).compl) } lemma measurable_set.bInter {f : β → set α} {s : set β} (hs : s.countable) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.compl_iff.1 $ by { rw compl_Inter₂, exact measurable_set.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.measurable_set_bInter {f : β → set α} {s : set β} (hs : s.finite) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.bInter hs.countable h lemma finset.measurable_set_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := s.finite_to_set.measurable_set_bInter h lemma measurable_set.sInter {s : set (set α)} (hs : s.countable) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := by { rw sInter_eq_bInter, exact measurable_set.bInter hs h } lemma set.finite.measurable_set_sInter {s : set (set α)} (hs : s.finite) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := measurable_set.sInter hs.countable h @[simp] lemma measurable_set.union {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∪ s₂) := by { rw union_eq_Union, exact measurable_set.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma measurable_set.inter {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma measurable_set.diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma measurable_set.symm_diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∆ s₂) := (h₁.diff h₂).union (h₂.diff h₁) @[simp] lemma measurable_set.ite {t s₁ s₂ : set α} (ht : measurable_set t) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (t.ite s₁ s₂) := (h₁.inter ht).union (h₂.diff ht) @[simp] lemma measurable_set.cond {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) {i : bool} : measurable_set (cond i s₁ s₂) := by { cases i, exacts [h₂, h₁] } @[simp] lemma measurable_set.disjointed {f : ℕ → set α} (h : ∀ i, measurable_set (f i)) (n) : measurable_set (disjointed f n) := disjointed_rec (λ t i ht, measurable_set.diff ht $ h _) (h n) @[simp] lemma measurable_set.const (p : Prop) : measurable_set {a : α | p} := by { by_cases p; simp [h, measurable_set.empty]; apply measurable_set.univ } /-- Every set has a measurable superset. Declare this as local instance as needed. -/ lemma nonempty_measurable_superset (s : set α) : nonempty { t // s ⊆ t ∧ measurable_set t} := ⟨⟨univ, subset_univ s, measurable_set.univ⟩⟩ end open_locale measure_theory @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, measurable_set[m₁] s ↔ measurable_set[m₂] s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀ s : set α, measurable_set[m₁] s ↔ measurable_set[m₂] s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (measurable_set_singleton : ∀ x, measurable_set ({x} : set α)) export measurable_singleton_class (measurable_set_singleton) attribute [simp] measurable_set_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma measurable_set_eq {a : α} : measurable_set {x | x = a} := measurable_set_singleton a lemma measurable_set.insert {s : set α} (hs : measurable_set s) (a : α) : measurable_set (insert a s) := (measurable_set_singleton a).union hs @[simp] lemma measurable_set_insert {a : α} {s : set α} : measurable_set (insert a s) ↔ measurable_set s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (measurable_set_singleton _), λ h, h.insert a⟩ lemma set.subsingleton.measurable_set {s : set α} (hs : s.subsingleton) : measurable_set s := hs.induction_on measurable_set.empty measurable_set_singleton lemma set.finite.measurable_set {s : set α} (hs : s.finite) : measurable_set s := finite.induction_on hs measurable_set.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.measurable_set (s : finset α) : measurable_set (↑s : set α) := s.finite_to_set.measurable_set lemma set.countable.measurable_set {s : set α} (hs : s.countable) : measurable_set s := begin rw [← bUnion_of_singleton s], exact measurable_set.bUnion hs (λ b hb, measurable_set_singleton b) end end measurable_singleton_class namespace measurable_space section complete_lattice instance : has_le (measurable_space α) := { le := λ m₁ m₂, ∀ s, measurable_set[m₁] s → measurable_set[m₂] s } lemma le_def {α} {a b : measurable_space α} : a ≤ b ↔ a.measurable_set' ≤ b.measurable_set' := iff.rfl instance : partial_order (measurable_space α) := { lt := λ m₁ m₂, m₁ ≤ m₂ ∧ ¬m₂ ≤ m₁, .. measurable_space.has_le, .. partial_order.lift (@measurable_set α) (λ m₁ m₂ h, ext $ λ s, h ▸ iff.rfl) } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀ u ∈ s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀ s, generate_measurable s → generate_measurable sᶜ | union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { measurable_set' := generate_measurable s, measurable_set_empty := generate_measurable.empty, measurable_set_compl := generate_measurable.compl, measurable_set_Union := generate_measurable.union } lemma measurable_set_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : @measurable_set _ (generate_from s) t := generate_measurable.basic t ht @[elab_as_eliminator] lemma generate_from_induction (p : set α → Prop) (C : set (set α)) (hC : ∀ t ∈ C, p t) (h_empty : p ∅) (h_compl : ∀ t, p t → p tᶜ) (h_Union : ∀ f : ℕ → set α, (∀ n, p (f n)) → p (⋃ i, f i)) {s : set α} (hs : measurable_set[generate_from C] s) : p s := by { induction hs, exacts [hC _ hs_H, h_empty, h_compl _ hs_ih, h_Union hs_f hs_ih], } lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, measurable_set[m] t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (measurable_set_empty m) (assume s _ hs, measurable_set_compl m s hs) (assume f _ hf, measurable_set_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | measurable_set[m] t} := iff.intro (assume h u hu, h _ $ measurable_set_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_measurable_set [measurable_space α] : generate_from {s : set α | measurable_set s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, measurable_set_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | measurable_set[generate_from g] t} = g) : measurable_space α := { measurable_set' := λ s, s ∈ g, measurable_set_empty := hg ▸ measurable_set_empty _, measurable_set_compl := hg ▸ measurable_set_compl _, measurable_set_Union := hg ▸ measurable_set_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | measurable_set[generate_from s] t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @measurable_set α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, measurable_set_generate_from, choice := λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ @[mono] lemma generate_from_mono {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm @[simp] lemma generate_from_insert_univ (S : set (set α)) : generate_from (insert set.univ S) = generate_from S := begin refine le_antisymm _ (generate_from_mono (set.subset_insert _ _)), rw generate_from_le_iff, intros t ht, cases ht, { rw ht, exact measurable_set.univ, }, { exact measurable_set_generate_from ht, }, end @[simp] lemma generate_from_insert_empty (S : set (set α)) : generate_from (insert ∅ S) = generate_from S := begin refine le_antisymm _ (generate_from_mono (set.subset_insert _ _)), rw generate_from_le_iff, intros t ht, cases ht, { rw ht, exact @measurable_set.empty _ (generate_from S), }, { exact measurable_set_generate_from ht, }, end lemma measurable_set_bot_iff {s : set α} : @measurable_set α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { measurable_set' := λ s, s = ∅ ∨ s = univ, measurable_set_empty := or.inl rfl, measurable_set_compl := by simp [or_imp_distrib] {contextual := tt}, measurable_set_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (λ s, s.symm ▸ @measurable_set_empty _ ⊥) (λ s, s.symm ▸ @measurable_set.univ _ ⊥), this ▸ iff.rfl @[simp] theorem measurable_set_top {s : set α} : @measurable_set _ ⊤ s := trivial @[simp] theorem measurable_set_inf {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊓ m₂) s ↔ @measurable_set _ m₁ s ∧ @measurable_set _ m₂ s := iff.rfl @[simp] theorem measurable_set_Inf {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Inf ms) s ↔ ∀ m ∈ ms, @measurable_set _ m s := show s ∈ (⋂₀ _) ↔ _, by simp @[simp] theorem measurable_set_infi {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (infi m) s ↔ ∀ i, @measurable_set _ (m i) s := by rw [infi, measurable_set_Inf, forall_range_iff] theorem measurable_set_sup {m₁ m₂ : measurable_space α} {s : set α} : measurable_set[m₁ ⊔ m₂] s ↔ generate_measurable (measurable_set[m₁] ∪ measurable_set[m₂]) s := iff.refl _ theorem measurable_set_Sup {ms : set (measurable_space α)} {s : set α} : measurable_set[Sup ms] s ↔ generate_measurable {s : set α | ∃ m ∈ ms, measurable_set[m] s} s := begin change @measurable_set' _ (generate_from $ ⋃₀ _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem measurable_set_supr {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, measurable_set[m i] s} s := by simp only [supr, measurable_set_Sup, exists_range_iff] lemma measurable_space_supr_eq (m : ι → measurable_space α) : (⨆ n, m n) = measurable_space.generate_from {s | ∃ n, measurable_set[m n] s} := begin ext s, rw measurable_space.measurable_set_supr, refl, end end complete_lattice end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, measurable_set t → measurable_set (f ⁻¹' t) localized "notation (name := measurable_of) `measurable[` m `]` := @measurable hole! hole! m hole!" in measure_theory lemma measurable_id {ma : measurable_space α} : measurable (@id α) := λ t, id lemma measurable_id' {ma : measurable_space α} : measurable (λ a : α, a) := measurable_id lemma measurable.comp {mα : measurable_space α} {mβ : measurable_space β} {mγ : measurable_space γ} {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) @[simp] lemma measurable_const {ma : measurable_space α} {mb : measurable_space β} {a : α} : measurable (λ b : β, a) := assume s hs, measurable_set.const (a ∈ s) lemma measurable.le {α} {m m0 : measurable_space α} {mb : measurable_space β} (hm : m ≤ m0) {f : α → β} (hf : measurable[m] f) : measurable[m0] f := λ s hs, hm _ (hf hs) end measurable_functions
32ebc3a0f48afbec4ad6bea682c549719d338b6d
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/logic/embedding.lean
d4de2953b3f99ebd639623fce9537b9e39e92f7d
[ "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
15,668
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.equiv.basic import data.set.basic import data.sigma.basic /-! # Injective functions -/ universes u v w x namespace function /-- `α ↪ β` is a bundled injective function. -/ @[nolint has_inhabited_instance] -- depending on cardinalities, an injective function may not exist structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj' : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) (λ _, α → β) := ⟨embedding.to_fun⟩ initialize_simps_projections embedding (to_fun → apply) end function section equiv variables {α : Sort u} {β : Sort v} (f : α ≃ β) /-- Convert an `α ≃ β` to `α ↪ β`. This is also available as a coercion `equiv.coe_embedding`. The explicit `equiv.to_embedding` version is preferred though, since the coercion can have issues inferring the type of the resulting embedding. For example: ```lean -- Works: example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f.to_embedding = s.map f := by simp -- Error, `f` has type `fin 3 ≃ fin 3` but is expected to have type `fin 3 ↪ ?m_1 : Type ?` example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f = s.map f.to_embedding := by simp ``` -/ @[simps] protected def equiv.to_embedding : α ↪ β := ⟨f, f.injective⟩ instance equiv.coe_embedding : has_coe (α ≃ β) (α ↪ β) := ⟨equiv.to_embedding⟩ @[reducible] instance equiv.perm.coe_embedding : has_coe (equiv.perm α) (α ↪ α) := equiv.coe_embedding @[simp] lemma equiv.coe_eq_to_embedding : ↑f = f.to_embedding := rfl /-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding set. -/ @[simps] def equiv.as_embedding {p : β → Prop} (e : α ≃ subtype p) : α ↪ β := ⟨coe ∘ e, subtype.coe_injective.comp e.injective⟩ @[simp] lemma equiv.as_embedding_range {α β : Sort*} {p : β → Prop} (e : α ≃ subtype p) : set.range e.as_embedding = set_of p := set.ext $ λ x, ⟨λ ⟨y, h⟩, h ▸ subtype.coe_prop (e y), λ hs, ⟨e.symm ⟨x, hs⟩, by simp⟩⟩ end equiv namespace function namespace embedding lemma coe_injective {α β} : @function.injective (α ↪ β) (α → β) coe_fn | ⟨x, _⟩ ⟨y, _⟩ rfl := rfl @[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := coe_injective (funext h) lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := ⟨ext, λ h _, by rw h⟩ @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl @[simp] lemma mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f := by { ext, simp } protected theorem injective {α β} (f : α ↪ β) : injective f := f.inj' @[simp] lemma apply_eq_iff_eq {α β : Type*} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y := f.injective.eq_iff @[refl, simps {simp_rhs := tt}] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ @[trans, simps {simp_rhs := tt}] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.injective.comp f.injective⟩ @[simp] lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) : e.to_embedding.trans e.symm.to_embedding = embedding.refl _ := by { ext, simp, } @[simp] lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) : e.symm.to_embedding.trans e.to_embedding = embedding.refl _ := by { ext, simp, } @[simps { fully_applied := ff }] protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ /-- Convert a surjective `embedding` to an `equiv` -/ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective f ⟨f.injective, hf⟩ /-- There is always an embedding from an empty type. --/ protected def of_is_empty {α β} [is_empty α] : α ↪ β := ⟨is_empty_elim, is_empty_elim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : α ↪ β := ⟨λ a', if a' = a then b else if f a' = b then f a else f a', begin intros x y h, dsimp at h, split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : set_value f a b a = b := by simp [set_value] /-- Embedding into `option` -/ @[simps { fully_applied := ff }] protected def some {α} : α ↪ option α := ⟨some, option.some_injective α⟩ /-- Given an embedding `f : α ↪ β` and a point outside of `set.range f`, construct an embedding `option α ↪ β`. -/ @[simps] def option_elim {α β} (f : α ↪ β) (x : β) (h : x ∉ set.range f) : option α ↪ β := ⟨λ o, o.elim x f, option.injective_iff.2 ⟨f.2, h⟩⟩ /-- Embedding of a `subtype`. -/ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨coe, λ _ _, subtype.ext_val⟩ @[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort*} (b : β) : punit ↪ β := ⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β := ⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β := ⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩ /-- Restrict the codomain of an embedding. -/ def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩ @[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩ @[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(e₁.prod_map e₂) = prod.map e₁ e₂ := rfl section sum open sum /-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/ def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨sum.map e₁ e₂, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h end⟩ @[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map e₁ e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ @[simps] def inl {α β : Type*} : α ↪ α ⊕ β := ⟨sum.inl, λ a b, sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ @[simps] def inr {α β : Type*} : β ↪ α ⊕ β := ⟨sum.inr, λ a b, sum.inr.inj⟩ end sum section sigma variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*} /-- `sigma.mk` as an `function.embedding`. -/ @[simps apply] def sigma_mk (a : α) : β a ↪ Σ x, β x := ⟨sigma.mk a, sigma_mk_injective⟩ /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `sigma.map f g` is an embedding. -/ @[simps apply] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) : (Σ a, β a) ↪ Σ a', β' a' := ⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩ end sigma def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩ def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := by haveI := classical.prop_decidable; exact let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in ⟨f', assume f₁ f₂ h, funext $ assume c, have ∃c', e c' = e c, from ⟨c, rfl⟩, have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _, have eq_b : classical.some this = c, from e.injective $ classical.some_spec this, by simp [f', this, if_pos, eq_b] at eq'; assumption⟩ protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} := ⟨subtype.map f h, subtype.map_injective h f.2⟩ open set /-- `set.image` as an embedding `set α ↪ set β`. -/ @[simps apply] protected def image {α β} (f : α ↪ β) : set α ↪ set β := ⟨image f, f.2.image_injective⟩ lemma swap_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := f.injective.swap_apply x y z lemma swap_comp {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := f.injective.swap_comp x y end embedding end function namespace equiv open function.embedding /-- The type of embeddings `α ↪ β` is equivalent to the subtype of all injective functions `α → β`. -/ def subtype_injective_equiv_embedding (α β : Sort*) : {f : α → β // function.injective f} ≃ (α ↪ β) := { to_fun := λ f, ⟨f.val, f.property⟩, inv_fun := λ f, ⟨f, f.injective⟩, left_inv := λ f, by simp, right_inv := λ f, by {ext, refl} } /-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁` is equivalent to the type of embeddings `α₂ ↪ β₂`. -/ @[congr, simps apply] def embedding_congr {α β γ δ : Sort*} (h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) := { to_fun := λ f, f.congr h h', inv_fun := λ f, f.congr h.symm h'.symm, left_inv := λ x, by {ext, simp}, right_inv := λ x, by {ext, simp} } @[simp] lemma embedding_congr_refl {α β : Sort*} : embedding_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ↪ β) := by {ext, refl} @[simp] lemma embedding_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : embedding_congr (e₁.trans e₂) (e₁'.trans e₂') = (embedding_congr e₁ e₁').trans (embedding_congr e₂ e₂') := rfl @[simp] lemma embedding_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (embedding_congr e₁ e₂).symm = embedding_congr e₁.symm e₂.symm := rfl lemma embedding_congr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) : equiv.embedding_congr ea ec (f.trans g) = (equiv.embedding_congr ea eb f).trans (equiv.embedding_congr eb ec g) := by {ext, simp} @[simp] lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl @[simp] lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl end equiv namespace set /-- The injection map is an embedding between subsets. -/ @[simps apply] def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t := ⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by { congr, injection h }⟩ end set section subtype variable {α : Type*} /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/ def subtype_or_left_embedding (p q : α → Prop) [decidable_pred p] : {x // p x ∨ q x} ↪ {x // p x} ⊕ {x // q x} := ⟨λ x, if h : p x then sum.inl ⟨x, h⟩ else sum.inr ⟨x, x.prop.resolve_left h⟩, begin intros x y, dsimp only, split_ifs; simp [subtype.ext_iff] end⟩ lemma subtype_or_left_embedding_apply_left {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : p x) : subtype_or_left_embedding p q x = sum.inl ⟨x, hx⟩ := dif_pos hx lemma subtype_or_left_embedding_apply_right {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : ¬ p x) : subtype_or_left_embedding p q x = sum.inr ⟨x, x.prop.resolve_left hx⟩ := dif_neg hx /-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`, if `p x → q x` for all `x : α`. -/ @[simps] def subtype.imp_embedding (p q : α → Prop) (h : p ≤ q) : {x // p x} ↪ {x // q x} := ⟨λ x, ⟨x, h x x.prop⟩, λ x y, by simp [subtype.ext_iff]⟩ /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` is equivalent to a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right, when `disjoint p q`. See also `equiv.sum_compl`, for when `is_compl p q`. -/ @[simps apply] def subtype_or_equiv (p q : α → Prop) [decidable_pred p] (h : disjoint p q) : {x // p x ∨ q x} ≃ {x // p x} ⊕ {x // q x} := { to_fun := subtype_or_left_embedding p q, inv_fun := sum.elim (subtype.imp_embedding _ _ (λ x hx, (or.inl hx : p x ∨ q x))) (subtype.imp_embedding _ _ (λ x hx, (or.inr hx : p x ∨ q x))), left_inv := λ x, begin by_cases hx : p x, { rw subtype_or_left_embedding_apply_left _ hx, simp [subtype.ext_iff] }, { rw subtype_or_left_embedding_apply_right _ hx, simp [subtype.ext_iff] }, end, right_inv := λ x, begin cases x, { simp only [sum.elim_inl], rw subtype_or_left_embedding_apply_left, { simp }, { simpa using x.prop } }, { simp only [sum.elim_inr], rw subtype_or_left_embedding_apply_right, { simp }, { suffices : ¬ p x, { simpa }, intro hp, simpa using h x ⟨hp, x.prop⟩ } } end } @[simp] lemma subtype_or_equiv_symm_inl (p q : α → Prop) [decidable_pred p] (h : disjoint p q) (x : {x // p x}) : (subtype_or_equiv p q h).symm (sum.inl x) = ⟨x, or.inl x.prop⟩ := rfl @[simp] lemma subtype_or_equiv_symm_inr (p q : α → Prop) [decidable_pred p] (h : disjoint p q) (x : {x // q x}) : (subtype_or_equiv p q h).symm (sum.inr x) = ⟨x, or.inr x.prop⟩ := rfl end subtype
85cd1aabee2facc0f8ba9b38721a73ed5ff7b798
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/combinatorics/qualify.lean
a8143931d206761b2c209dd8dcd3593a2b1b9255
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,516
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Suppose we have a list `l` in a type `α`. Suppose we also have a subset `s` of `α`, formalised in the usual way as a term of type `set α`, or equivalently a predicate `α → Prop`. Associated to this we have a subtype `s' = {a : α // a ∈ s}`, and coercions have been defined so that Lean will interpret `s` as `s'` where necessary. If all elements of `l` satisfy the predicate defining `s`, then a mathematician would say that `l` can be regarded as an element of `list s`. In Lean we still have a corresponding term `l'` of type `s`, but it is not literally the same as `l`. This story is not just relevant for lists; there are similar considerations for pairs, finsets, elements of the free group and so on. In this file we use the notation `qualify h l` for `l'`, where `h` is a proof that the elements of `l` satisfy the relevant predicate. We prove various basic lemmas about this operation and its inverse. We have tried to write things in a way that could be smoothly generalised to functors other than `list`, but there should probably be some apparatus of type classes which we have not yet set up. Also, Mario has suggested that `cod_restrict` would be a better name than `qualify`, for compatibility with some existing code. -/ import data.list.basic variables {α : Type*} namespace list open list def qualify {s : set α} (l : list α) (h : ∀ {a}, a ∈ l → s a) : list s := pmap subtype.mk l @h lemma length_qualify {s : set α} (l : list α) (h : ∀ {a}, a ∈ l → s a) : (qualify l @h).length = l.length := length_pmap def unqualify {s : set α} (l : list s) : list α := l.map subtype.val @[simp] lemma unqualify_nil {s : set α} : unqualify (@nil s) = nil := rfl @[simp] lemma unqualify_cons {s : set α} (a : s) (l : list s) : unqualify (a :: l) = a.val :: (unqualify l) := rfl lemma unqualify_eq {s : set α} {l₁ l₂ : list s} : l₁ = l₂ ↔ (unqualify l₁ = unqualify l₂) := begin split, {exact congr_arg unqualify,}, {induction l₁ with x₁ l₁ ih generalizing l₂, {rw[unqualify_nil], rcases l₂ with _ | ⟨x₂,l₂⟩, {intro,refl}, {rw[unqualify_cons],intro eu,exact false.elim (list.no_confusion eu)} },{ rw[unqualify_cons], rcases l₂ with _ | ⟨x₂,l₂⟩, {intro eu,exact false.elim (list.no_confusion eu)}, {rw[unqualify_cons],intro eu,injection eu with euh eut,congr, exact subtype.eq euh,exact ih eut, } } } end @[simp] lemma length_unqualify {s : set α} (l : list s) : (unqualify l).length = l.length := length_map subtype.val l lemma mem_unqualify {s : set α} {l : list s} {a : α} : a ∈ unqualify l ↔ (∃ h : s a, subtype.mk a h ∈ l) := begin rcases (@mem_map s α subtype.val a l) with ⟨h0,h1⟩, split, {intro h2,rcases h0 h2 with ⟨⟨a,a_in_s⟩,⟨a_in_l,rfl⟩⟩,exact ⟨a_in_s,a_in_l⟩ }, {rintro ⟨a_in_s,a_in_l⟩,exact h1 ⟨⟨a,a_in_s⟩,⟨a_in_l,rfl⟩⟩} end lemma mem_unqualify' {s : set α} {l : list s} {a : s} : a.val ∈ unqualify l ↔ a ∈ l := begin split, {intro h0, rcases (mem_unqualify.mp h0) with ⟨a_in_s,a_in_l⟩ , have h1 : a = ⟨a.val,a_in_s⟩ := subtype.eq rfl, rw[h1],exact a_in_l, }, {intro h0,exact mem_map_of_mem _ h0,} end @[simp] lemma un_qualify {s : set α} (l : list α) (h : ∀ {a}, a ∈ l → s a) : unqualify (qualify l @h) = l := begin dsimp[qualify], induction l with x l ih, {refl}, {rw[unqualify,pmap,map],congr, exact ih (λ a a_in_l, h (mem_cons_of_mem x a_in_l)), } end def requalify {s t : set α} (l : list s) (h : ∀ {u : s}, u ∈ l → t u) : list t := qualify (unqualify l) (λ a a_in_l, begin rcases (mem_unqualify.mp a_in_l) with ⟨a_in_s,a_in_l⟩, exact h a_in_l, end ) @[simp] lemma un_requalify {s t : set α} (l : list s) (h : ∀ {u : s}, u ∈ l → t u) : unqualify (requalify l @h) = unqualify l := begin dsimp[requalify],rw[un_qualify] end lemma nodup_unqualify {s : set α} : ∀ {l : list s}, (unqualify l).nodup ↔ l.nodup | [] := by { rw[unqualify_nil],simp only [nodup_nil], } | (a :: l) := begin rw[unqualify_cons,nodup_cons,nodup_cons,nodup_unqualify,@mem_unqualify' α s l a], end lemma nodup_qualify {s : set α} (l : list α) (h : ∀ {a}, a ∈ l → s a) : (qualify l @h).nodup ↔ l.nodup := by { rw[← nodup_unqualify,un_qualify], } end list
fc928e6dd2285d6bfe7d7b4a31cc7e5ecdd3d091
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/cancel_denoms.lean
512ff133cfddcdde930bd9417f2d150b8ffa0f94
[ "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
398
lean
import tactic.cancel_denoms import tactic.ring variables {α : Type} [linear_ordered_field α] (a b c d : α) example (h : a / 5 + b / 4 < c) : 4*a + 5*b < 20*c := begin cancel_denoms at h, exact h end example (h : a > 0) : a / 5 > 0 := begin cancel_denoms, exact h end example (h : a + b = c) : a/5 + d*(b/4) = c - 4*a/5 + b*2*d/8 - b := begin cancel_denoms, rw ← h, ring, end
3a32c4773d4fdd892fc51dfcef94fac0c3a817a5
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/basic_monitor1.lean
3cc16ee2cfdbba5b802c4586e0ec61521e84ca44
[ "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
242
lean
@[vm_monitor] meta def basic_monitor : vm_monitor nat := { init := 0, step := λ s, return (trace ("step " ++ to_string s) (s+1)) >> failure } set_option debugger true def f : nat → nat | 0 := 0 | (a+1) := f a #eval trace "a" (f 4)
408cd6a9116a4309768bb591d49602aa1e60a22a
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Meta/Instances.lean
bc9329de7269d749602f7381fdd5821bdd2473c0
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,333
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.DiscrTree namespace Lean.Meta structure InstanceEntry := (keys : Array DiscrTree.Key) (val : Expr) abbrev Instances := DiscrTree Expr def addInstanceEntry (d : Instances) (e : InstanceEntry) : Instances := d.insertCore e.keys e.val builtin_initialize instanceExtension : SimplePersistentEnvExtension InstanceEntry Instances ← registerSimplePersistentEnvExtension { name := `instanceExt, addEntryFn := addInstanceEntry, addImportedFn := fun es => (mkStateFromImportedEntries addInstanceEntry DiscrTree.empty es) } private def mkInstanceKey (e : Expr) : MetaM (Array DiscrTree.Key) := do let type ← inferType e withNewMCtxDepth do let (_, _, type) ← forallMetaTelescopeReducing type DiscrTree.mkPath type @[export lean_add_instance] def addGlobalInstanceImp (env : Environment) (constName : Name) : IO Environment := do match env.find? constName with | none => throw $ IO.userError "unknown constant" | some cinfo => let c := mkConst constName (cinfo.lparams.map mkLevelParam) let (keys, s, _) ← (mkInstanceKey c).toIO {} { env := env } {} {} pure $ instanceExtension.addEntry s.env { keys := keys, val := c } def addGlobalInstance {m} [Monad m] [MonadEnv m] [MonadIO m] (declName : Name) : m Unit := do let env ← getEnv let env ← liftIO $ Meta.addGlobalInstanceImp env declName setEnv env builtin_initialize registerBuiltinAttribute { name := `instance, descr := "type class instance", add := fun declName args persistent => do if args.hasArgs then throwError "invalid attribute 'instance', unexpected argument" unless persistent do throwError "invalid attribute 'instance', must be persistent" let env ← getEnv let env ← ofExcept (addGlobalInstanceOld env declName); setEnv env; -- TODO: delete after we remove old frontend addGlobalInstance declName } end Meta def Environment.getGlobalInstances (env : Environment) : Meta.Instances := Meta.instanceExtension.getState env namespace Meta def getGlobalInstances : MetaM Instances := do let env ← getEnv pure env.getGlobalInstances end Lean.Meta
ce5afb16cd2eb0369b862c963c4726a2687175da
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1258.lean
6e785b9eaa20803df9c5edd5fbcb4000036cc9eb
[ "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
177
lean
constant P : list ℕ → list ℕ → Prop lemma foo (xs : list ℕ) : Π (ns : list ℕ), P xs ns | [] := sorry | (n::ns) := begin cases xs, exact sorry, exact sorry end
46070a6355cf4acd3a81ea335b56644979911e71
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/digits.lean
7cb64d196fd37e35a90f69f7f57f08b93562e79b
[ "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
22,759
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam, Mario Carneiro -/ import data.int.modeq import data.nat.log import data.nat.parity import data.list.indexes import data.list.palindrome import tactic.interval_cases import tactic.linarith /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. A basic `norm_digits` tactic is also provided for proving goals of the form `nat.digits a b = l` where `a` and `b` are numerals. -/ namespace nat variables {n : ℕ} /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_0 : ℕ → list ℕ | 0 := [] | (n+1) := [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_1 (n : ℕ) : list ℕ := list.repeat 1 n /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux (b : ℕ) (h : 2 ≤ b) : ℕ → list ℕ | 0 := [] | (n+1) := have (n+1)/b < n+1 := nat.div_lt_self (nat.succ_pos _) h, (n+1) % b :: digits_aux ((n+1)/b) @[simp] lemma digits_aux_zero (b : ℕ) (h : 2 ≤ b) : digits_aux b h 0 = [] := by rw digits_aux lemma digits_aux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digits_aux b h n = n % b :: digits_aux b h (n/b) := begin cases n, { cases w, }, { rw [digits_aux], } end /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `of_digits b L = L.foldr (λ x y, x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = list.repeat 1 n`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `nat.to_digits` in core, which is used for printing numerals. In particular, `nat.to_digits b 0 = [0]`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → list ℕ | 0 := digits_aux_0 | 1 := digits_aux_1 | (b+2) := digits_aux (b+2) (by norm_num) @[simp] lemma digits_zero (b : ℕ) : digits b 0 = [] := by rcases b with _|⟨_|⟨_⟩⟩; simp [digits, digits_aux_0, digits_aux_1] @[simp] lemma digits_zero_zero : digits 0 0 = [] := rfl @[simp] lemma digits_zero_succ (n : ℕ) : digits 0 (n.succ) = [n+1] := rfl theorem digits_zero_succ' : ∀ {n : ℕ} (w : 0 < n), digits 0 n = [n] | 0 h := absurd h dec_trivial | (n+1) _ := rfl @[simp] lemma digits_one (n : ℕ) : digits 1 n = list.repeat 1 n := rfl @[simp] lemma digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl @[simp] lemma digits_add_two_add_one (b n : ℕ) : digits (b+2) (n+1) = (((n+1) % (b+2)) :: digits (b+2) ((n+1) / (b+2))) := by { rw [digits, digits_aux_def], exact succ_pos n } theorem digits_def' : ∀ {b : ℕ} (h : 2 ≤ b) {n : ℕ} (w : 0 < n), digits b n = n % b :: digits b (n/b) | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | (b+2) h := digits_aux_def _ _ @[simp] lemma digits_of_lt (b x : ℕ) (w₁ : 0 < x) (w₂ : x < b) : digits b x = [x] := begin cases b, { cases w₂ }, { cases b, { interval_cases x, }, { cases x, { cases w₁, }, { rw [digits_add_two_add_one, nat.div_eq_of_lt w₂, digits_zero, nat.mod_eq_of_lt w₂] } } } end lemma digits_add (b : ℕ) (h : 2 ≤ b) (x y : ℕ) (w : x < b) (w' : 0 < x ∨ 0 < y) : digits b (x + b * y) = x :: digits b y := begin cases b, { cases h, }, { cases b, { norm_num at h, }, { cases y, { norm_num at w', simp [w, w'], }, dsimp [digits], rw digits_aux_def, { congr, { simp [nat.add_mod, nat.mod_eq_of_lt w], }, { simp [mul_comm (b+2), nat.add_mul_div_right, nat.div_eq_of_lt w], } }, { apply nat.succ_pos, }, }, }, end /-- `of_digits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. def of_digits {α : Type*} [semiring α] (b : α) : list ℕ → α | [] := 0 | (h :: t) := h + b * of_digits t lemma of_digits_eq_foldr {α : Type*} [semiring α] (b : α) (L : list ℕ) : of_digits b L = L.foldr (λ x y, x + b * y) 0 := begin induction L with d L ih, { refl, }, { dsimp [of_digits], rw ih, }, end lemma of_digits_eq_sum_map_with_index_aux (b : ℕ) (l : list ℕ) : ((list.range l.length).zip_with ((λ (i a : ℕ), a * b ^ i) ∘ succ) l).sum = b * ((list.range l.length).zip_with (λ i a, a * b ^ i) l).sum := begin suffices : (list.range l.length).zip_with (((λ (i a : ℕ), a * b ^ i) ∘ succ)) l = (list.range l.length).zip_with (λ i a, b * (a * b ^ i)) l, { simp [this] }, congr, ext, simp [pow_succ], ring end lemma of_digits_eq_sum_map_with_index (b : ℕ) (L : list ℕ): of_digits b L = (L.map_with_index (λ i a, a * b ^ i)).sum := begin rw [list.map_with_index_eq_enum_map, list.enum_eq_zip_range, list.map_uncurry_zip_eq_zip_with, of_digits_eq_foldr], induction L with hd tl hl, { simp }, { simpa [list.range_succ_eq_map, list.zip_with_map_left, of_digits_eq_sum_map_with_index_aux] using or.inl hl } end @[simp] lemma of_digits_singleton {b n : ℕ} : of_digits b [n] = n := by simp [of_digits] @[simp] lemma of_digits_one_cons {α : Type*} [semiring α] (h : ℕ) (L : list ℕ) : of_digits (1 : α) (h :: L) = h + of_digits 1 L := by simp [of_digits] lemma of_digits_append {b : ℕ} {l1 l2 : list ℕ} : of_digits b (l1 ++ l2) = of_digits b l1 + b^(l1.length) * of_digits b l2 := begin induction l1 with hd tl IH, { simp [of_digits] }, { rw [of_digits, list.cons_append, of_digits, IH, list.length_cons, pow_succ'], ring } end @[norm_cast] lemma coe_of_digits (α : Type*) [semiring α] (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : α) = of_digits (b : α) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end @[norm_cast] lemma coe_int_of_digits (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : ℤ) = of_digits (b : ℤ) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end lemma digits_zero_of_eq_zero {b : ℕ} (h : 1 ≤ b) {L : list ℕ} (w : of_digits b L = 0) : ∀ l ∈ L, l = 0 := begin induction L with d L ih, { intros l m, cases m, }, { intros l m, dsimp [of_digits] at w, rcases m with ⟨rfl⟩, { convert nat.eq_zero_of_add_eq_zero_right w, simp, }, { exact ih ((nat.mul_right_inj h).mp (nat.eq_zero_of_add_eq_zero_left w)) _ m, }, } end lemma digits_of_digits (b : ℕ) (h : 2 ≤ b) (L : list ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ (h : L ≠ []), L.last h ≠ 0) : digits b (of_digits b L) = L := begin induction L with d L ih, { dsimp [of_digits], simp }, { dsimp [of_digits], replace w₂ := w₂ (by simp), rw digits_add b h, { rw ih, { simp, }, { intros l m, apply w₁, exact list.mem_cons_of_mem _ m, }, { intro h, { rw [list.last_cons h] at w₂, convert w₂, }}}, { convert w₁ d (list.mem_cons_self _ _), simp, }, { by_cases h' : L = [], { rcases h' with rfl, simp at w₂, left, apply nat.pos_of_ne_zero, convert w₂, simp, }, { right, apply nat.pos_of_ne_zero, contrapose! w₂, apply digits_zero_of_eq_zero _ w₂, { rw list.last_cons h', exact list.last_mem h', }, { exact le_of_lt h, }, }, }, }, end lemma of_digits_digits (b n : ℕ) : of_digits b (digits b n) = n := begin cases b with b, { cases n with n, { refl, }, { change of_digits 0 [n+1] = n+1, dsimp [of_digits], simp, } }, { cases b with b, { induction n with n ih, { refl, }, { simp only [ih, add_comm 1, of_digits_one_cons, nat.cast_id, digits_one_succ], } }, { apply nat.strong_induction_on n _, clear n, intros n h, cases n, { rw digits_zero, refl, }, { simp only [nat.succ_eq_add_one, digits_add_two_add_one], dsimp [of_digits], rw h _ (nat.div_lt_self' n b), rw [nat.cast_id, nat.mod_add_div], }, }, }, end lemma of_digits_one (L : list ℕ) : of_digits 1 L = L.sum := begin induction L with d L ih, { refl, }, { simp [of_digits, list.sum_cons, ih], } end /-! ### Properties This section contains various lemmas of properties relating to `digits` and `of_digits`. -/ lemma digits_eq_nil_iff_eq_zero {b n : ℕ} : digits b n = [] ↔ n = 0 := begin split, { intro h, have : of_digits b (digits b n) = of_digits b [], by rw h, convert this, rw of_digits_digits }, { rintro rfl, simp } end lemma digits_ne_nil_iff_ne_zero {b n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero lemma digits_eq_cons_digits_div {b n : ℕ} (h : 2 ≤ b) (w : 0 < n) : digits b n = ((n % b) :: digits b (n / b)) := begin rcases b with _|_|b, { rw [digits_zero_succ' w, nat.mod_zero, nat.div_zero, nat.digits_zero_zero] }, { norm_num at h }, rcases n with _|n, { norm_num at w }, simp, end lemma digits_last {b : ℕ} (m : ℕ) (h : 2 ≤ b) (p q) : (digits b m).last p = (digits b (m/b)).last q := begin by_cases hm : m = 0, { simp [hm], }, simp only [digits_eq_cons_digits_div h (nat.pos_of_ne_zero hm)], rw list.last_cons, end lemma digits.injective (b : ℕ) : function.injective b.digits := function.left_inverse.injective (of_digits_digits b) @[simp] lemma digits_inj_iff {b n m : ℕ} : b.digits n = b.digits m ↔ n = m := (digits.injective b).eq_iff lemma digits_len (b n : ℕ) (hb : 2 ≤ b) (hn : 0 < n) : (b.digits n).length = b.log n + 1 := begin induction n using nat.strong_induction_on with n IH, rw [digits_eq_cons_digits_div hb hn, list.length], cases (n / b).eq_zero_or_pos with h h, { have posb : 0 < b := zero_lt_two.trans_le hb, simp [h, log_eq_zero_iff, ←nat.div_eq_zero_iff posb] }, { have hb' : 1 < b := one_lt_two.trans_le hb, have : n / b < n := div_lt_self hn hb', rw [IH _ this h, log_div_base, tsub_add_cancel_of_le], rw [succ_le_iff], refine log_pos hb' _, contrapose! h, rw div_eq_of_lt h } end lemma last_digit_ne_zero (b : ℕ) {m : ℕ} (hm : m ≠ 0) : (digits b m).last (digits_ne_nil_iff_ne_zero.mpr hm) ≠ 0 := begin rcases b with _|_|b, { cases m, { cases hm rfl }, { simp } }, { cases m, { cases hm rfl }, simp_rw [digits_one, list.last_repeat_succ 1 m], norm_num }, revert hm, apply nat.strong_induction_on m, intros n IH hn, have hnpos : 0 < n := nat.pos_of_ne_zero hn, by_cases hnb : n < b + 2, { simp_rw [digits_of_lt b.succ.succ n hnpos hnb], exact pos_iff_ne_zero.mp hnpos }, { rw digits_last n (show 2 ≤ b + 2, from dec_trivial), refine IH _ (nat.div_lt_self hnpos dec_trivial) _, { rw ←pos_iff_ne_zero, exact nat.div_pos (le_of_not_lt hnb) dec_trivial } }, end /-- The digits in the base b+2 expansion of n are all less than b+2 -/ lemma digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b+2) m → d < b+2 := begin apply nat.strong_induction_on m, intros n IH d hd, cases n with n, { rw digits_zero at hd, cases hd }, -- base b+2 expansion of 0 has no digits rw digits_add_two_add_one at hd, cases hd, { rw hd, exact n.succ.mod_lt (by linarith) }, { exact IH _ (nat.div_lt_self (nat.succ_pos _) (by linarith)) hd } end /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ lemma digits_lt_base {b m d : ℕ} (hb : 2 ≤ b) (hd : d ∈ digits b m) : d < b := begin rcases b with _ | _ | b; try {linarith}, exact digits_lt_base' hd, end /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ lemma of_digits_lt_base_pow_length' {b : ℕ} {l : list ℕ} (hl : ∀ x ∈ l, x < b+2) : of_digits (b+2) l < (b+2)^(l.length) := begin induction l with hd tl IH, { simp [of_digits], }, { rw [of_digits, list.length_cons, pow_succ], have : (of_digits (b + 2) tl + 1) * (b+2) ≤ (b + 2) ^ tl.length * (b+2) := mul_le_mul (IH (λ x hx, hl _ (list.mem_cons_of_mem _ hx))) (by refl) dec_trivial (nat.zero_le _), suffices : ↑hd < b + 2, { linarith }, norm_cast, exact hl hd (list.mem_cons_self _ _) } end /-- an n-digit number in base b is less than b^n if b ≥ 2 -/ lemma of_digits_lt_base_pow_length {b : ℕ} {l : list ℕ} (hb : 2 ≤ b) (hl : ∀ x ∈ l, x < b) : of_digits b l < b^l.length := begin rcases b with _ | _ | b; try { linarith }, exact of_digits_lt_base_pow_length' hl, end /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ lemma lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := begin convert of_digits_lt_base_pow_length' (λ _, digits_lt_base'), rw of_digits_digits (b+2) m, end /-- Any number m is less than b^(number of digits in the base b representation of m) -/ lemma lt_base_pow_length_digits {b m : ℕ} (hb : 2 ≤ b) : m < b^(digits b m).length := begin rcases b with _ | _ | b; try { linarith }, exact lt_base_pow_length_digits', end lemma of_digits_digits_append_digits {b m n : ℕ} : of_digits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m:= by rw [of_digits_append, of_digits_digits, of_digits_digits] lemma digits_len_le_digits_len_succ (b n : ℕ) : (digits b n).length ≤ (digits b (n + 1)).length := begin rcases n.eq_zero_or_pos with rfl|hn, { simp }, cases lt_or_le b 2 with hb hb, { rcases b with _|_|b, { simp [digits_zero_succ', hn] }, { simp, }, { simpa [succ_lt_succ_iff] using hb } }, simpa [digits_len, hb, hn] using log_mono_right (le_succ _) end lemma le_digits_len_le (b n m : ℕ) (h : n ≤ m) : (digits b n).length ≤ (digits b m).length := monotone_nat_of_le_succ (digits_len_le_digits_len_succ b) h lemma pow_length_le_mul_of_digits {b : ℕ} {l : list ℕ} (hl : l ≠ []) (hl2 : l.last hl ≠ 0): (b + 2) ^ l.length ≤ (b + 2) * of_digits (b+2) l := begin rw [←list.init_append_last hl], simp only [list.length_append, list.length, zero_add, list.length_init, of_digits_append, list.length_init, of_digits_singleton, add_comm (l.length - 1), pow_add, pow_one], apply nat.mul_le_mul_left, refine le_trans _ (nat.le_add_left _ _), have : 0 < l.last hl, { rwa [pos_iff_ne_zero] }, convert nat.mul_le_mul_left _ this, rw [mul_one] end /-- Any non-zero natural number `m` is greater than (b+2)^((number of digits in the base (b+2) representation of m) - 1) -/ lemma base_pow_length_digits_le' (b m : ℕ) (hm : m ≠ 0) : (b + 2) ^ ((digits (b + 2) m).length) ≤ (b + 2) * m := begin have : digits (b + 2) m ≠ [], from digits_ne_nil_iff_ne_zero.mpr hm, convert pow_length_le_mul_of_digits this (last_digit_ne_zero _ hm), rwa of_digits_digits, end /-- Any non-zero natural number `m` is greater than b^((number of digits in the base b representation of m) - 1) -/ lemma base_pow_length_digits_le (b m : ℕ) (hb : 2 ≤ b): m ≠ 0 → b ^ ((digits b m).length) ≤ b * m := begin rcases b with _ | _ | b; try { linarith }, exact base_pow_length_digits_le' b m, end /-! ### Modular Arithmetic -/ -- This is really a theorem about polynomials. lemma dvd_of_digits_sub_of_digits {α : Type*} [comm_ring α] {a b k : α} (h : k ∣ a - b) (L : list ℕ) : k ∣ of_digits a L - of_digits b L := begin induction L with d L ih, { change k ∣ 0 - 0, simp, }, { simp only [of_digits, add_sub_add_left_eq_sub], exact dvd_mul_sub_mul h ih, } end lemma of_digits_modeq' (b b' : ℕ) (k : ℕ) (h : b ≡ b' [MOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [MOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [nat.modeq] at *, conv_lhs { rw [nat.add_mod, nat.mul_mod, h, ih], }, conv_rhs { rw [nat.add_mod, nat.mul_mod], }, } end lemma of_digits_modeq (b k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [MOD k] := of_digits_modeq' b (b % k) k (b.mod_modeq k).symm L lemma of_digits_mod (b k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_modeq b k L lemma of_digits_zmodeq' (b b' : ℤ) (k : ℕ) (h : b ≡ b' [ZMOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [ZMOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [int.modeq] at *, conv_lhs { rw [int.add_mod, int.mul_mod, h, ih], }, conv_rhs { rw [int.add_mod, int.mul_mod], }, } end lemma of_digits_zmodeq (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [ZMOD k] := of_digits_zmodeq' b (b % k) k (b.mod_modeq ↑k).symm L lemma of_digits_zmod (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_zmodeq b k L lemma modeq_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : n ≡ (digits b' n).sum [MOD b] := begin rw ←of_digits_one, conv { congr, skip, rw ←(of_digits_digits b' n) }, convert of_digits_modeq _ _ _, exact h.symm, end lemma modeq_three_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 3] := modeq_digits_sum 3 10 (by norm_num) n lemma modeq_nine_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 9] := modeq_digits_sum 9 10 (by norm_num) n lemma zmodeq_of_digits_digits (b b' : ℕ) (c : ℤ) (h : b' ≡ c [ZMOD b]) (n : ℕ) : n ≡ of_digits c (digits b' n) [ZMOD b] := begin conv { congr, skip, rw ←(of_digits_digits b' n) }, rw coe_int_of_digits, apply of_digits_zmodeq' _ _ _ h, end lemma of_digits_neg_one : Π (L : list ℕ), of_digits (-1 : ℤ) L = (L.map (λ n : ℕ, (n : ℤ))).alternating_sum | [] := rfl | [n] := by simp [of_digits, list.alternating_sum] | (a :: b :: t) := begin simp only [of_digits, list.alternating_sum, list.map_cons, of_digits_neg_one t], push_cast, ring, end lemma modeq_eleven_digits_sum (n : ℕ) : n ≡ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum [ZMOD 11] := begin have t := zmodeq_of_digits_digits 11 10 (-1 : ℤ) (by unfold int.modeq; norm_num) n, rwa of_digits_neg_one at t end /-! ## Divisibility -/ lemma dvd_iff_dvd_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ (digits b' n).sum := begin rw ←of_digits_one, conv_lhs { rw ←(of_digits_digits b' n) }, rw [nat.dvd_iff_mod_eq_zero, nat.dvd_iff_mod_eq_zero, of_digits_mod, h], end /-- **Divisibility by 3 Rule** -/ lemma three_dvd_iff (n : ℕ) : 3 ∣ n ↔ 3 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 3 10 (by norm_num) n lemma nine_dvd_iff (n : ℕ) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by norm_num) n lemma dvd_iff_dvd_of_digits (b b' : ℕ) (c : ℤ) (h : (b : ℤ) ∣ (b' : ℤ) - c) (n : ℕ) : b ∣ n ↔ (b : ℤ) ∣ of_digits c (digits b' n) := begin rw ←int.coe_nat_dvd, exact dvd_iff_dvd_of_dvd_sub (zmodeq_of_digits_digits b b' c (int.modeq_iff_dvd.2 h).symm _).symm.dvd, end lemma eleven_dvd_iff : 11 ∣ n ↔ (11 : ℤ) ∣ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum := begin have t := dvd_iff_dvd_of_digits 11 10 (-1 : ℤ) (by norm_num) n, rw of_digits_neg_one at t, exact t, end lemma eleven_dvd_of_palindrome (p : (digits 10 n).palindrome) (h : even (digits 10 n).length) : 11 ∣ n := begin let dig := (digits 10 n).map (coe : ℕ → ℤ), replace h : even dig.length := by rwa list.length_map, refine eleven_dvd_iff.2 ⟨0, (_ : dig.alternating_sum = 0)⟩, have := dig.alternating_sum_reverse, rw [(p.map _).reverse_eq, pow_succ, h.neg_one_pow, mul_one, neg_one_zsmul] at this, exact eq_zero_of_neg_eq this.symm, end /-! ### `norm_digits` tactic -/ namespace norm_digits theorem digits_succ (b n m r l) (e : r + b * m = n) (hr : r < b) (h : nat.digits b m = l ∧ 2 ≤ b ∧ 0 < m) : nat.digits b n = r :: l ∧ 2 ≤ b ∧ 0 < n := begin rcases h with ⟨h, b2, m0⟩, have b0 : 0 < b := by linarith, have n0 : 0 < n := by linarith [mul_pos b0 m0], refine ⟨_, b2, n0⟩, obtain ⟨rfl, rfl⟩ := (nat.div_mod_unique b0).2 ⟨e, hr⟩, subst h, exact nat.digits_def' b2 n0, end theorem digits_one (b n) (n0 : 0 < n) (nb : n < b) : nat.digits b n = [n] ∧ 2 ≤ b ∧ 0 < n := begin have b2 : 2 ≤ b := by linarith, refine ⟨_, b2, n0⟩, rw [nat.digits_def' b2 n0, nat.mod_eq_of_lt nb, (nat.div_eq_zero_iff (by linarith : 0 < b)).2 nb, nat.digits_zero], end open tactic /-- Helper function for the `norm_digits` tactic. -/ meta def eval_aux (eb : expr) (b : ℕ) : expr → ℕ → instance_cache → tactic (instance_cache × expr × expr) | en n ic := do let m := n / b, let r := n % b, (ic, er) ← ic.of_nat r, (ic, pr) ← norm_num.prove_lt_nat ic er eb, if m = 0 then do (_, pn0) ← norm_num.prove_pos ic en, return (ic, `([%%en] : list nat), `(digits_one %%eb %%en %%pn0 %%pr)) else do em ← expr.of_nat `(ℕ) m, (_, pe) ← norm_num.derive `(%%er + %%eb * %%em : ℕ), (ic, el, p) ← eval_aux em m ic, return (ic, `(@list.cons ℕ %%er %%el), `(digits_succ %%eb %%en %%em %%er %%el %%pe %%pr %%p)) /-- A tactic for normalizing expressions of the form `nat.digits a b = l` where `a` and `b` are numerals. ``` example : nat.digits 10 123 = [3,2,1] := by norm_num ``` -/ @[norm_num] meta def eval : expr → tactic (expr × expr) | `(nat.digits %%eb %%en) := do b ← expr.to_nat eb, n ← expr.to_nat en, if n = 0 then return (`([] : list ℕ), `(nat.digits_zero %%eb)) else if b = 0 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_pos ic en, return (`([%%en] : list ℕ), `(@nat.digits_zero_succ' %%en %%pn0)) else if b = 1 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_pos ic en, s ← simp_lemmas.add_simp simp_lemmas.mk `list.repeat, (rhs, p2, _) ← simplify s [] `(list.repeat 1 %%en), p ← mk_eq_trans `(nat.digits_one %%en) p2, return (rhs, p) else do ic ← mk_instance_cache `(ℕ), (_, l, p) ← eval_aux eb b en n ic, p ← mk_app ``and.left [p], return (l, p) | _ := failed end norm_digits end nat
3ad41294d0efc3b8c54ba1157d1c73c5b7027e4c
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Util.lean
d82220439a9092926b7c5474fba86d23e4633a82
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
679
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectFVars import Lean.Util.CollectLevelParams import Lean.Util.CollectMVars import Lean.Util.FindMVar import Lean.Util.FindLevelMVar import Lean.Util.MonadCache import Lean.Util.PPExt import Lean.Util.Path import Lean.Util.Profile import Lean.Util.RecDepth import Lean.Util.Sorry import Lean.Util.Trace import Lean.Util.FindExpr import Lean.Util.ReplaceExpr import Lean.Util.ForEachExpr import Lean.Util.ReplaceLevel import Lean.Util.FoldConsts import Lean.Util.SCC import Lean.Util.OccursCheck
5409c368f61a2008d35f3eeb397250b70f02c94d
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/topological_fiber_bundle.lean
a02e43ee1a3a90e86619ba18110f941db9c6d0f0
[ "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
49,222
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.local_homeomorph import topology.algebra.ordered.basic /-! # Fiber bundles A topological fiber bundle with fiber `F` over a base `B` is a space projecting on `B` for which the fibers are all homeomorphic to `F`, such that the local situation around each point is a direct product. We define a predicate `is_topological_fiber_bundle F p` saying that `p : Z → B` is a topological fiber bundle with fiber `F`. It is in general nontrivial to construct a fiber bundle. A way is to start from the knowledge of how changes of local trivializations act on the fiber. From this, one can construct the total space of the bundle and its topology by a suitable gluing construction. The main content of this file is an implementation of this construction: starting from an object of type `topological_fiber_bundle_core` registering the trivialization changes, one gets the corresponding fiber bundle and projection. ## Main definitions ### Basic definitions * `bundle_trivialization F p` : structure extending local homeomorphisms, defining a local trivialization of a topological space `Z` with projection `p` and fiber `F`. * `is_topological_fiber_bundle F p` : Prop saying that the map `p` between topological spaces is a fiber bundle with fiber `F`. * `is_trivial_topological_fiber_bundle F p` : Prop saying that the map `p : Z → B` between topological spaces is a trivial topological fiber bundle, i.e., there exists a homeomorphism `h : Z ≃ₜ B × F` such that `proj x = (h x).1`. ### Operations on bundles We provide the following operations on `bundle_trivialization`s. * `bundle_trivialization.comap`: given a local trivialization `e` of a fiber bundle `p : Z → B`, a continuous map `f : B' → B` and a point `b' : B'` such that `f b' ∈ e.base_set`, `e.comap f hf b' hb'` is a trivialization of the pullback bundle. The pullback bundle (a.k.a., the induced bundle) has total space `{(x, y) : B' × Z | f x = p y}`, and is given by `λ ⟨(x, y), h⟩, x`. * `is_topological_fiber_bundle.comap`: if `p : Z → B` is a topological fiber bundle, then its pullback along a continuous map `f : B' → B` is a topological fiber bundle as well. * `bundle_trivialization.comp_homeomorph`: given a local trivialization `e` of a fiber bundle `p : Z → B` and a homeomorphism `h : Z' ≃ₜ Z`, returns a local trivialization of the fiber bundle `p ∘ h`. * `is_topological_fiber_bundle.comp_homeomorph`: if `p : Z → B` is a topological fiber bundle and `h : Z' ≃ₜ Z` is a homeomorphism, then `p ∘ h : Z' → B` is a topological fiber bundle with the same fiber. ### Construction of a bundle from trivializations * `bundle.total_space E` is a type synonym for `Σ (x : B), E x`, that we can endow with a suitable topology. * `topological_fiber_bundle_core ι B F` : structure registering how changes of coordinates act on the fiber `F` above open subsets of `B`, where local trivializations are indexed by `ι`. Let `Z : topological_fiber_bundle_core ι B F`. Then we define * `Z.fiber x` : the fiber above `x`, homeomorphic to `F` (and defeq to `F` as a type). * `Z.total_space` : the total space of `Z`, defined as a `Type` as `Σ (b : B), F`, but with a twisted topology coming from the fiber bundle structure. It is (reducibly) the same as `bundle.total_space Z.fiber`. * `Z.proj` : projection from `Z.total_space` to `B`. It is continuous. * `Z.local_triv i`: for `i : ι`, a local homeomorphism from `Z.total_space` to `B × F`, that realizes a trivialization above the set `Z.base_set i`, which is an open set in `B`. ## Implementation notes A topological fiber bundle with fiber `F` over a base `B` is a family of spaces isomorphic to `F`, indexed by `B`, which is locally trivial in the following sense: there is a covering of `B` by open sets such that, on each such open set `s`, the bundle is isomorphic to `s × F`. To construct a fiber bundle formally, the main data is what happens when one changes trivializations from `s × F` to `s' × F` on `s ∩ s'`: one should get a family of homeomorphisms of `F`, depending continuously on the base point, satisfying basic compatibility conditions (cocycle property). Useful classes of bundles can then be specified by requiring that these homeomorphisms of `F` belong to some subgroup, preserving some structure (the "structure group of the bundle"): then these structures are inherited by the fibers of the bundle. Given such trivialization change data (encoded below in a structure called `topological_fiber_bundle_core`), one can construct the fiber bundle. The intrinsic canonical mathematical construction is the following. The fiber above `x` is the disjoint union of `F` over all trivializations, modulo the gluing identifications: one gets a fiber which is isomorphic to `F`, but non-canonically (each choice of one of the trivializations around `x` gives such an isomorphism). Given a trivialization over a set `s`, one gets an isomorphism between `s × F` and `proj^{-1} s`, by using the identification corresponding to this trivialization. One chooses the topology on the bundle that makes all of these into homeomorphisms. For the practical implementation, it turns out to be more convenient to avoid completely the gluing and quotienting construction above, and to declare above each `x` that the fiber is `F`, but thinking that it corresponds to the `F` coming from the choice of one trivialization around `x`. This has several practical advantages: * without any work, one gets a topological space structure on the fiber. And if `F` has more structure it is inherited for free by the fiber. * In the case of the tangent bundle of manifolds, this implies that on vector spaces the derivative (from `F` to `F`) and the manifold derivative (from `tangent_space I x` to `tangent_space I' (f x)`) are equal. A drawback is that some silly constructions will typecheck: in the case of the tangent bundle, one can add two vectors in different tangent spaces (as they both are elements of `F` from the point of view of Lean). To solve this, one could mark the tangent space as irreducible, but then one would lose the identification of the tangent space to `F` with `F`. There is however a big advantage of this situation: even if Lean can not check that two basepoints are defeq, it will accept the fact that the tangent spaces are the same. For instance, if two maps `f` and `g` are locally inverse to each other, one can express that the composition of their derivatives is the identity of `tangent_space I x`. One could fear issues as this composition goes from `tangent_space I x` to `tangent_space I (g (f x))` (which should be the same, but should not be obvious to Lean as it does not know that `g (f x) = x`). As these types are the same to Lean (equal to `F`), there are in fact no dependent type difficulties here! For this construction of a fiber bundle from a `topological_fiber_bundle_core`, we should thus choose for each `x` one specific trivialization around it. We include this choice in the definition of the `topological_fiber_bundle_core`, as it makes some constructions more functorial and it is a nice way to say that the trivializations cover the whole space `B`. With this definition, the type of the fiber bundle space constructed from the core data is just `Σ (b : B), F `, but the topology is not the product one, in general. We also take the indexing type (indexing all the trivializations) as a parameter to the fiber bundle core: it could always be taken as a subtype of all the maps from open subsets of `B` to continuous maps of `F`, but in practice it will sometimes be something else. For instance, on a manifold, one will use the set of charts as a good parameterization for the trivializations of the tangent bundle. Or for the pullback of a `topological_fiber_bundle_core`, the indexing type will be the same as for the initial bundle. ## Tags Fiber bundle, topological bundle, vector bundle, local trivialization, structure group -/ variables {ι : Type*} {B : Type*} {F : Type*} open topological_space filter set open_locale topological_space classical /-! ### General definition of topological fiber bundles -/ section topological_fiber_bundle variables (F) {Z : Type*} [topological_space B] [topological_space Z] [topological_space F] {proj : Z → B} /-- A structure extending local homeomorphisms, defining a local trivialization of a projection `proj : Z → B` with fiber `F`, as a local homeomorphism between `Z` and `B × F` defined between two sets of the form `proj ⁻¹' base_set` and `base_set × F`, acting trivially on the first coordinate. -/ @[nolint has_inhabited_instance] structure bundle_trivialization (proj : Z → B) extends local_homeomorph Z (B × F) := (base_set : set B) (open_base_set : is_open base_set) (source_eq : source = proj ⁻¹' base_set) (target_eq : target = set.prod base_set univ) (proj_to_fun : ∀ p ∈ source, (to_local_homeomorph p).1 = proj p) instance : has_coe_to_fun (bundle_trivialization F proj) := ⟨_, λ e, e.to_fun⟩ variable {F} @[simp, mfld_simps] lemma bundle_trivialization.coe_coe (e : bundle_trivialization F proj) : ⇑e.to_local_homeomorph = e := rfl @[simp, mfld_simps] lemma bundle_trivialization.coe_mk (e : local_homeomorph Z (B × F)) (i j k l m) (x : Z) : (bundle_trivialization.mk e i j k l m : bundle_trivialization F proj) x = e x := rfl variable (F) /-- A topological fiber bundle with fiber `F` over a base `B` is a space projecting on `B` for which the fibers are all homeomorphic to `F`, such that the local situation around each point is a direct product. -/ def is_topological_fiber_bundle (proj : Z → B) : Prop := ∀ x : B, ∃e : bundle_trivialization F proj, x ∈ e.base_set /-- A trivial topological fiber bundle with fiber `F` over a base `B` is a space `Z` projecting on `B` for which there exists a homeomorphism to `B × F` that sends `proj` to `prod.fst`. -/ def is_trivial_topological_fiber_bundle (proj : Z → B) : Prop := ∃ e : Z ≃ₜ (B × F), ∀ x, (e x).1 = proj x variables {F} lemma bundle_trivialization.mem_source (e : bundle_trivialization F proj) {x : Z} : x ∈ e.source ↔ proj x ∈ e.base_set := by rw [e.source_eq, mem_preimage] lemma bundle_trivialization.mem_target (e : bundle_trivialization F proj) {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.base_set := by rw [e.target_eq, prod_univ, mem_preimage] @[simp, mfld_simps] lemma bundle_trivialization.coe_fst (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_to_fun x ex lemma bundle_trivialization.coe_fst' (e : bundle_trivialization F proj) {x : Z} (ex : proj x ∈ e.base_set) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) lemma bundle_trivialization.mk_proj_snd (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst ex).symm rfl lemma bundle_trivialization.mk_proj_snd' (e : bundle_trivialization F proj) {x : Z} (ex : proj x ∈ e.base_set) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst' ex).symm rfl protected lemma bundle_trivialization.eq_on (e : bundle_trivialization F proj) : eq_on (prod.fst ∘ e) proj e.source := λ x hx, e.coe_fst hx lemma bundle_trivialization.proj_symm_apply (e : bundle_trivialization F proj) {x : B × F} (hx : x ∈ e.target) : proj (e.to_local_homeomorph.symm x) = x.1 := begin have := (e.coe_fst (e.to_local_homeomorph.map_target hx)).symm, rwa [← e.coe_coe, e.to_local_homeomorph.right_inv hx] at this end lemma bundle_trivialization.proj_symm_apply' (e : bundle_trivialization F proj) {b : B} {x : F} (hx : b ∈ e.base_set) : proj (e.to_local_homeomorph.symm (b, x)) = b := e.proj_symm_apply (e.mem_target.2 hx) lemma bundle_trivialization.apply_symm_apply (e : bundle_trivialization F proj) {x : B × F} (hx : x ∈ e.target) : e (e.to_local_homeomorph.symm x) = x := e.to_local_homeomorph.right_inv hx lemma bundle_trivialization.apply_symm_apply' (e : bundle_trivialization F proj) {b : B} {x : F} (hx : b ∈ e.base_set) : e (e.to_local_homeomorph.symm (b, x)) = (b, x) := e.apply_symm_apply (e.mem_target.2 hx) @[simp, mfld_simps] lemma bundle_trivialization.symm_apply_mk_proj (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : e.to_local_homeomorph.symm (proj x, (e x).2) = x := by rw [← e.coe_fst ex, prod.mk.eta, ← e.coe_coe, e.to_local_homeomorph.left_inv ex] lemma bundle_trivialization.coe_fst_eventually_eq_proj (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : prod.fst ∘ e =ᶠ[𝓝 x] proj := mem_nhds_iff.2 ⟨e.source, λ y hy, e.coe_fst hy, e.open_source, ex⟩ lemma bundle_trivialization.coe_fst_eventually_eq_proj' (e : bundle_trivialization F proj) {x : Z} (ex : proj x ∈ e.base_set) : prod.fst ∘ e =ᶠ[𝓝 x] proj := e.coe_fst_eventually_eq_proj (e.mem_source.2 ex) lemma is_trivial_topological_fiber_bundle.is_topological_fiber_bundle (h : is_trivial_topological_fiber_bundle F proj) : is_topological_fiber_bundle F proj := let ⟨e, he⟩ := h in λ x, ⟨⟨e.to_local_homeomorph, univ, is_open_univ, rfl, univ_prod_univ.symm, λ x _, he x⟩, mem_univ x⟩ lemma bundle_trivialization.map_proj_nhds (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : map proj (𝓝 x) = 𝓝 (proj x) := by rw [← e.coe_fst ex, ← map_congr (e.coe_fst_eventually_eq_proj ex), ← map_map, ← e.coe_coe, e.to_local_homeomorph.map_nhds_eq ex, map_fst_nhds] /-- In the domain of a bundle trivialization, the projection is continuous-/ lemma bundle_trivialization.continuous_at_proj (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : continuous_at proj x := (e.map_proj_nhds ex).le /-- The projection from a topological fiber bundle to its base is continuous. -/ lemma is_topological_fiber_bundle.continuous_proj (h : is_topological_fiber_bundle F proj) : continuous proj := begin rw continuous_iff_continuous_at, assume x, rcases h (proj x) with ⟨e, ex⟩, apply e.continuous_at_proj, rwa e.source_eq end /-- The projection from a topological fiber bundle to its base is an open map. -/ lemma is_topological_fiber_bundle.is_open_map_proj (h : is_topological_fiber_bundle F proj) : is_open_map proj := begin refine is_open_map_iff_nhds_le.2 (λ x, _), rcases h (proj x) with ⟨e, ex⟩, refine (e.map_proj_nhds _).ge, rwa e.source_eq end /-- The first projection in a product is a trivial topological fiber bundle. -/ lemma is_trivial_topological_fiber_bundle_fst : is_trivial_topological_fiber_bundle F (prod.fst : B × F → B) := ⟨homeomorph.refl _, λ x, rfl⟩ /-- The first projection in a product is a topological fiber bundle. -/ lemma is_topological_fiber_bundle_fst : is_topological_fiber_bundle F (prod.fst : B × F → B) := is_trivial_topological_fiber_bundle_fst.is_topological_fiber_bundle /-- The second projection in a product is a trivial topological fiber bundle. -/ lemma is_trivial_topological_fiber_bundle_snd : is_trivial_topological_fiber_bundle F (prod.snd : F × B → B) := ⟨homeomorph.prod_comm _ _, λ x, rfl⟩ /-- The second projection in a product is a topological fiber bundle. -/ lemma is_topological_fiber_bundle_snd : is_topological_fiber_bundle F (prod.snd : F × B → B) := is_trivial_topological_fiber_bundle_snd.is_topological_fiber_bundle /-- Composition of a `bundle_trivialization` and a `homeomorph`. -/ def bundle_trivialization.comp_homeomorph {Z' : Type*} [topological_space Z'] (e : bundle_trivialization F proj) (h : Z' ≃ₜ Z) : bundle_trivialization F (proj ∘ h) := { to_local_homeomorph := h.to_local_homeomorph.trans e.to_local_homeomorph, base_set := e.base_set, open_base_set := e.open_base_set, source_eq := by simp [e.source_eq, preimage_preimage], target_eq := by simp [e.target_eq], proj_to_fun := λ p hp, have hp : h p ∈ e.source, by simpa using hp, by simp [hp] } lemma is_topological_fiber_bundle.comp_homeomorph {Z' : Type*} [topological_space Z'] (e : is_topological_fiber_bundle F proj) (h : Z' ≃ₜ Z) : is_topological_fiber_bundle F (proj ∘ h) := λ x, let ⟨e, he⟩ := e x in ⟨e.comp_homeomorph h, by simpa [bundle_trivialization.comp_homeomorph] using he⟩ namespace bundle_trivialization /-- If `e` is a `bundle_trivialization` of `proj : Z → B` with fiber `F` and `h` is a homeomorphism `F ≃ₜ F'`, then `e.trans_fiber_homeomorph h` is the trivialization of `proj` with the fiber `F'` that sends `p : Z` to `((e p).1, h (e p).2)`. -/ def trans_fiber_homeomorph {F' : Type*} [topological_space F'] (e : bundle_trivialization F proj) (h : F ≃ₜ F') : bundle_trivialization F' proj := { to_local_homeomorph := e.to_local_homeomorph.trans ((homeomorph.refl _).prod_congr h).to_local_homeomorph, base_set := e.base_set, open_base_set := e.open_base_set, source_eq := by simp [e.source_eq], target_eq := by { ext, simp [e.target_eq] }, proj_to_fun := λ p hp, have p ∈ e.source, by simpa using hp, by simp [this] } @[simp] lemma trans_fiber_homeomorph_apply {F' : Type*} [topological_space F'] (e : bundle_trivialization F proj) (h : F ≃ₜ F') (x : Z) : e.trans_fiber_homeomorph h x = ((e x).1, h (e x).2) := rfl /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations. See also `bundle_trivialization.coord_change_homeomorph` for a version bundled as `F ≃ₜ F`. -/ def coord_change (e₁ e₂ : bundle_trivialization F proj) (b : B) (x : F) : F := (e₂ $ e₁.to_local_homeomorph.symm (b, x)).2 lemma mk_coord_change (e₁ e₂ : bundle_trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) (x : F) : (b, e₁.coord_change e₂ b x) = e₂ (e₁.to_local_homeomorph.symm (b, x)) := begin refine prod.ext _ rfl, rw [e₂.coe_fst', ← e₁.coe_fst', e₁.apply_symm_apply' h₁], { rwa [e₁.proj_symm_apply' h₁] }, { rwa [e₁.proj_symm_apply' h₁] } end lemma coord_change_apply_snd (e₁ e₂ : bundle_trivialization F proj) {p : Z} (h : proj p ∈ e₁.base_set) : e₁.coord_change e₂ (proj p) (e₁ p).snd = (e₂ p).snd := by rw [coord_change, e₁.symm_apply_mk_proj (e₁.mem_source.2 h)] lemma coord_change_same_apply (e : bundle_trivialization F proj) {b : B} (h : b ∈ e.base_set) (x : F) : e.coord_change e b x = x := by rw [bundle_trivialization.coord_change, e.apply_symm_apply' h] lemma coord_change_same (e : bundle_trivialization F proj) {b : B} (h : b ∈ e.base_set) : e.coord_change e b = id := funext $ e.coord_change_same_apply h lemma coord_change_coord_change (e₁ e₂ e₃ : bundle_trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) (x : F) : e₂.coord_change e₃ b (e₁.coord_change e₂ b x) = e₁.coord_change e₃ b x := begin rw [bundle_trivialization.coord_change, e₁.mk_coord_change _ h₁ h₂, ← e₂.coe_coe, e₂.to_local_homeomorph.left_inv, bundle_trivialization.coord_change], rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] end lemma continuous_coord_change (e₁ e₂ : bundle_trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : continuous (e₁.coord_change e₂ b) := begin refine continuous_snd.comp (e₂.to_local_homeomorph.continuous_on.comp_continuous (e₁.to_local_homeomorph.continuous_on_symm.comp_continuous _ _) _), { exact continuous_const.prod_mk continuous_id }, { exact λ x, e₁.mem_target.2 h₁ }, { intro x, rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] } end /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations, as a homeomorphism. -/ def coord_change_homeomorph (e₁ e₂ : bundle_trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : F ≃ₜ F := { to_fun := e₁.coord_change e₂ b, inv_fun := e₂.coord_change e₁ b, left_inv := λ x, by simp only [*, coord_change_coord_change, coord_change_same_apply], right_inv := λ x, by simp only [*, coord_change_coord_change, coord_change_same_apply], continuous_to_fun := e₁.continuous_coord_change e₂ h₁ h₂, continuous_inv_fun := e₂.continuous_coord_change e₁ h₂ h₁ } @[simp] lemma coord_change_homeomorph_coe (e₁ e₂ : bundle_trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : ⇑(e₁.coord_change_homeomorph e₂ h₁ h₂) = e₁.coord_change e₂ b := rfl end bundle_trivialization section comap open_locale classical variables {B' : Type*} [topological_space B'] /-- Given a bundle trivialization of `proj : Z → B` and a continuous map `f : B' → B`, construct a bundle trivialization of `φ : {p : B' × Z | f p.1 = proj p.2} → B'` given by `φ x = (x : B' × Z).1`. -/ noncomputable def bundle_trivialization.comap (e : bundle_trivialization F proj) (f : B' → B) (hf : continuous f) (b' : B') (hb' : f b' ∈ e.base_set) : bundle_trivialization F (λ x : {p : B' × Z | f p.1 = proj p.2}, (x : B' × Z).1) := { to_fun := λ p, ((p : B' × Z).1, (e (p : B' × Z).2).2), inv_fun := λ p, if h : f p.1 ∈ e.base_set then ⟨⟨p.1, e.to_local_homeomorph.symm (f p.1, p.2)⟩, by simp [e.proj_symm_apply' h]⟩ else ⟨⟨b', e.to_local_homeomorph.symm (f b', p.2)⟩, by simp [e.proj_symm_apply' hb']⟩, source := {p | f (p : B' × Z).1 ∈ e.base_set}, target := {p | f p.1 ∈ e.base_set}, map_source' := λ p hp, hp, map_target' := λ p (hp : f p.1 ∈ e.base_set), by simp [hp], left_inv' := begin rintro ⟨⟨b, x⟩, hbx⟩ hb, dsimp at *, have hx : x ∈ e.source, from e.mem_source.2 (hbx ▸ hb), ext; simp * end, right_inv' := λ p (hp : f p.1 ∈ e.base_set), by simp [*, e.apply_symm_apply'], open_source := e.open_base_set.preimage (hf.comp $ continuous_fst.comp continuous_subtype_coe), open_target := e.open_base_set.preimage (hf.comp continuous_fst), continuous_to_fun := ((continuous_fst.comp continuous_subtype_coe).continuous_on).prod $ continuous_snd.comp_continuous_on $ e.continuous_to_fun.comp (continuous_snd.comp continuous_subtype_coe).continuous_on $ by { rintro ⟨⟨b, x⟩, (hbx : f b = proj x)⟩ (hb : f b ∈ e.base_set), rw hbx at hb, exact e.mem_source.2 hb }, continuous_inv_fun := begin rw [embedding_subtype_coe.continuous_on_iff], suffices : continuous_on (λ p : B' × F, (p.1, e.to_local_homeomorph.symm (f p.1, p.2))) {p : B' × F | f p.1 ∈ e.base_set}, { refine this.congr (λ p (hp : f p.1 ∈ e.base_set), _), simp [hp] }, { refine continuous_on_fst.prod (e.to_local_homeomorph.symm.continuous_on.comp _ _), { exact ((hf.comp continuous_fst).prod_mk continuous_snd).continuous_on }, { exact λ p hp, e.mem_target.2 hp } } end, base_set := f ⁻¹' e.base_set, source_eq := rfl, target_eq := by { ext, simp }, open_base_set := e.open_base_set.preimage hf, proj_to_fun := λ _ _, rfl } /-- If `proj : Z → B` is a topological fiber bundle with fiber `F` and `f : B' → B` is a continuous map, then the pullback bundle (a.k.a. induced bundle) is the topological bundle with the total space `{(x, y) : B' × Z | f x = proj y}` given by `λ ⟨(x, y), h⟩, x`. -/ lemma is_topological_fiber_bundle.comap (h : is_topological_fiber_bundle F proj) {f : B' → B} (hf : continuous f) : is_topological_fiber_bundle F (λ x : {p : B' × Z | f p.1 = proj p.2}, (x : B' × Z).1) := λ x, let ⟨e, he⟩ := h (f x) in ⟨e.comap f hf x he, he⟩ end comap lemma bundle_trivialization.is_image_preimage_prod (e : bundle_trivialization F proj) (s : set B) : e.to_local_homeomorph.is_image (proj ⁻¹' s) (s.prod univ) := λ x hx, by simp [e.coe_fst', hx] /-- Restrict a `bundle_trivialization` to an open set in the base. `-/ def bundle_trivialization.restr_open (e : bundle_trivialization F proj) (s : set B) (hs : is_open s) : bundle_trivialization F proj := { to_local_homeomorph := ((e.is_image_preimage_prod s).symm.restr (is_open.inter e.open_target (hs.prod is_open_univ))).symm, base_set := e.base_set ∩ s, open_base_set := is_open.inter e.open_base_set hs, source_eq := by simp [e.source_eq], target_eq := by simp [e.target_eq, prod_univ], proj_to_fun := λ p hp, e.proj_to_fun p hp.1 } section piecewise lemma bundle_trivialization.frontier_preimage (e : bundle_trivialization F proj) (s : set B) : e.source ∩ frontier (proj ⁻¹' s) = proj ⁻¹' (e.base_set ∩ frontier s) := by rw [← (e.is_image_preimage_prod s).frontier.preimage_eq, frontier_prod_univ_eq, (e.is_image_preimage_prod _).preimage_eq, e.source_eq, preimage_inter] /-- Given two bundle trivializations `e`, `e'` of `proj : Z → B` and a set `s : set B` such that the base sets of `e` and `e'` intersect `frontier s` on the same set and `e p = e' p` whenever `proj p ∈ e.base_set ∩ frontier s`, `e.piecewise e' s Hs Heq` is the bundle trivialization over `set.ite s e.base_set e'.base_set` that is equal to `e` on `proj ⁻¹ s` and is equal to `e'` otherwise. -/ noncomputable def bundle_trivialization.piecewise (e e' : bundle_trivialization F proj) (s : set B) (Hs : e.base_set ∩ frontier s = e'.base_set ∩ frontier s) (Heq : eq_on e e' $ proj ⁻¹' (e.base_set ∩ frontier s)) : bundle_trivialization F proj := { to_local_homeomorph := e.to_local_homeomorph.piecewise e'.to_local_homeomorph (proj ⁻¹' s) (s.prod univ) (e.is_image_preimage_prod s) (e'.is_image_preimage_prod s) (by rw [e.frontier_preimage, e'.frontier_preimage, Hs]) (by rwa e.frontier_preimage), base_set := s.ite e.base_set e'.base_set, open_base_set := e.open_base_set.ite e'.open_base_set Hs, source_eq := by simp [e.source_eq, e'.source_eq], target_eq := by simp [e.target_eq, e'.target_eq, prod_univ], proj_to_fun := by rintro p (⟨he, hs⟩|⟨he, hs⟩); simp * } /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.base_set ∩ e'.base_set` such that `e` equals `e'` on `proj ⁻¹' {a}`, `e.piecewise_le_of_eq e' a He He' Heq` is the bundle trivialization over `set.ite (Iic a) e.base_set e'.base_set` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `e'` otherwise. -/ noncomputable def bundle_trivialization.piecewise_le_of_eq [linear_order B] [order_topology B] (e e' : bundle_trivialization F proj) (a : B) (He : a ∈ e.base_set) (He' : a ∈ e'.base_set) (Heq : ∀ p, proj p = a → e p = e' p) : bundle_trivialization F proj := e.piecewise e' (Iic a) (set.ext $ λ x, and.congr_left_iff.2 $ λ hx, by simp [He, He', mem_singleton_iff.1 (frontier_Iic_subset _ hx)]) (λ p hp, Heq p $ frontier_Iic_subset _ hp.2) /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.base_set ∩ e'.base_set`, `e.piecewise_le e' a He He'` is the bundle trivialization over `set.ite (Iic a) e.base_set e'.base_set` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `((e' p).1, h (e' p).2)` otherwise, where `h = `e'.coord_change_homeomorph e _ _` is the homeomorphism of the fiber such that `h (e' p).2 = (e p).2` whenever `e p = a`. -/ noncomputable def bundle_trivialization.piecewise_le [linear_order B] [order_topology B] (e e' : bundle_trivialization F proj) (a : B) (He : a ∈ e.base_set) (He' : a ∈ e'.base_set) : bundle_trivialization F proj := e.piecewise_le_of_eq (e'.trans_fiber_homeomorph (e'.coord_change_homeomorph e He' He)) a He He' $ by { unfreezingI {rintro p rfl }, ext1, { simp [e.coe_fst', e'.coe_fst', *] }, { simp [e'.coord_change_apply_snd, *] } } /-- Given two bundle trivializations `e`, `e'` over disjoint sets, `e.disjoint_union e' H` is the bundle trivialization over the union of the base sets that agrees with `e` and `e'` over their base sets. -/ noncomputable def bundle_trivialization.disjoint_union (e e' : bundle_trivialization F proj) (H : disjoint e.base_set e'.base_set) : bundle_trivialization F proj := { to_local_homeomorph := e.to_local_homeomorph.disjoint_union e'.to_local_homeomorph (λ x hx, by { rw [e.source_eq, e'.source_eq] at hx, exact H hx }) (λ x hx, by { rw [e.target_eq, e'.target_eq] at hx, exact H ⟨hx.1.1, hx.2.1⟩ }), base_set := e.base_set ∪ e'.base_set, open_base_set := is_open.union e.open_base_set e'.open_base_set, source_eq := congr_arg2 (∪) e.source_eq e'.source_eq, target_eq := (congr_arg2 (∪) e.target_eq e'.target_eq).trans union_prod.symm, proj_to_fun := begin rintro p (hp|hp'), { show (e.source.piecewise e e' p).1 = proj p, rw [piecewise_eq_of_mem, e.coe_fst]; exact hp }, { show (e.source.piecewise e e' p).1 = proj p, rw [piecewise_eq_of_not_mem, e'.coe_fst hp'], simp only [e.source_eq, e'.source_eq] at hp' ⊢, exact λ h, H ⟨h, hp'⟩ } end } /-- If `h` is a topological fiber bundle over a conditionally complete linear order, then it is trivial over any closed interval. -/ lemma is_topological_fiber_bundle.exists_trivialization_Icc_subset [conditionally_complete_linear_order B] [order_topology B] (h : is_topological_fiber_bundle F proj) (a b : B) : ∃ e : bundle_trivialization F proj, Icc a b ⊆ e.base_set := begin classical, obtain ⟨ea, hea⟩ : ∃ ea : bundle_trivialization F proj, a ∈ ea.base_set := h a, -- If `a < b`, then `[a, b] = ∅`, and the statement is trivial cases le_or_lt a b with hab hab; [skip, exact ⟨ea, by simp *⟩], /- Let `s` be the set of points `x ∈ [a, b]` such that `proj` is trivializable over `[a, x]`. We need to show that `b ∈ s`. Let `c = Sup s`. We will show that `c ∈ s` and `c = b`. -/ set s : set B := {x ∈ Icc a b | ∃ e : bundle_trivialization F proj, Icc a x ⊆ e.base_set}, have ha : a ∈ s, from ⟨left_mem_Icc.2 hab, ea, by simp [hea]⟩, have sne : s.nonempty := ⟨a, ha⟩, have hsb : b ∈ upper_bounds s, from λ x hx, hx.1.2, have sbd : bdd_above s := ⟨b, hsb⟩, set c := Sup s, have hsc : is_lub s c, from is_lub_cSup sne sbd, have hc : c ∈ Icc a b, from ⟨hsc.1 ha, hsc.2 hsb⟩, obtain ⟨-, ec : bundle_trivialization F proj, hec : Icc a c ⊆ ec.base_set⟩ : c ∈ s, { cases hc.1.eq_or_lt with heq hlt, { rwa ← heq }, refine ⟨hc, _⟩, /- In order to show that `c ∈ s`, consider a trivialization `ec` of `proj` over a neighborhood of `c`. Its base set includes `(c', c]` for some `c' ∈ [a, c)`. -/ rcases h c with ⟨ec, hc⟩, obtain ⟨c', hc', hc'e⟩ : ∃ c' ∈ Ico a c, Ioc c' c ⊆ ec.base_set := (mem_nhds_within_Iic_iff_exists_mem_Ico_Ioc_subset hlt).1 (mem_nhds_within_of_mem_nhds $ is_open.mem_nhds ec.open_base_set hc), /- Since `c' < c = Sup s`, there exists `d ∈ s ∩ (c', c]`. Let `ead` be a trivialization of `proj` over `[a, d]`. Then we can glue `ead` and `ec` into a trivialization over `[a, c]`. -/ obtain ⟨d, ⟨hdab, ead, had⟩, hd⟩ : ∃ d ∈ s, d ∈ Ioc c' c := hsc.exists_between hc'.2, refine ⟨ead.piecewise_le ec d (had ⟨hdab.1, le_rfl⟩) (hc'e hd), subset_ite.2 _⟩, refine ⟨λ x hx, had ⟨hx.1.1, hx.2⟩, λ x hx, hc'e ⟨hd.1.trans (not_le.1 hx.2), hx.1.2⟩⟩ }, /- So, `c ∈ s`. Let `ec` be a trivialization of `proj` over `[a, c]`. If `c = b`, then we are done. Otherwise we show that `proj` can be trivialized over a larger interval `[a, d]`, `d ∈ (c, b]`, hence `c` is not an upper bound of `s`. -/ cases hc.2.eq_or_lt with heq hlt, { exact ⟨ec, heq ▸ hec⟩ }, suffices : ∃ (d ∈ Ioc c b) (e : bundle_trivialization F proj), Icc a d ⊆ e.base_set, { rcases this with ⟨d, hdcb, hd⟩, exact ((hsc.1 ⟨⟨hc.1.trans hdcb.1.le, hdcb.2⟩, hd⟩).not_lt hdcb.1).elim }, /- Since the base set of `ec` is open, it includes `[c, d)` (hence, `[a, d)`) for some `d ∈ (c, b]`. -/ obtain ⟨d, hdcb, hd⟩ : ∃ d ∈ Ioc c b, Ico c d ⊆ ec.base_set := (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hlt).1 (mem_nhds_within_of_mem_nhds $ is_open.mem_nhds ec.open_base_set (hec ⟨hc.1, le_rfl⟩)), have had : Ico a d ⊆ ec.base_set, from subset.trans Ico_subset_Icc_union_Ico (union_subset hec hd), by_cases he : disjoint (Iio d) (Ioi c), { /- If `(c, d) = ∅`, then let `ed` be a trivialization of `proj` over a neighborhood of `d`. Then the disjoint union of `ec` restricted to `(-∞, d)` and `ed` restricted to `(c, ∞)` is a trivialization over `[a, d]`. -/ rcases h d with ⟨ed, hed⟩, refine ⟨d, hdcb, (ec.restr_open (Iio d) is_open_Iio).disjoint_union (ed.restr_open (Ioi c) is_open_Ioi) (he.mono (inter_subset_right _ _) (inter_subset_right _ _)), λ x hx, _⟩, rcases hx.2.eq_or_lt with rfl|hxd, exacts [or.inr ⟨hed, hdcb.1⟩, or.inl ⟨had ⟨hx.1, hxd⟩, hxd⟩] }, { /- If `(c, d)` is nonempty, then take `d' ∈ (c, d)`. Since the base set of `ec` includes `[a, d)`, it includes `[a, d'] ⊆ [a, d)` as well. -/ rw [disjoint_left] at he, push_neg at he, rcases he with ⟨d', hdd' : d' < d, hd'c⟩, exact ⟨d', ⟨hd'c, hdd'.le.trans hdcb.2⟩, ec, subset.trans (Icc_subset_Ico_right hdd') had⟩ } end end piecewise end topological_fiber_bundle /-! ### Constructing topological fiber bundles -/ namespace bundle /- We provide a type synonym of `Σ x, E x` as `bundle.total_space E`, to be able to endow it with a topology which is not the disjoint union topology. In general, the constructions of fiber bundles we will make will be of this form. -/ variable (E : B → Type*) /-- `total_space E` is the total space of the bundle `Σ x, E x`. This type synonym is used to avoid conflicts with general sigma types. -/ def total_space := Σ x, E x instance [inhabited B] [inhabited (E (default B))] : inhabited (total_space E) := ⟨⟨default B, default (E (default B))⟩⟩ /-- `bundle.proj E` is the canonical projection `total_space E → B` on the base space. -/ @[simp, mfld_simps] def proj : total_space E → B := λ (y : total_space E), y.1 instance {x : B} : has_coe_t (E x) (total_space E) := ⟨λ y, (⟨x, y⟩ : total_space E)⟩ lemma to_total_space_coe {x : B} (v : E x) : (v : total_space E) = ⟨x, v⟩ := rfl /-- `bundle.trivial B F` is the trivial bundle over `B` of fiber `F`. -/ @[nolint unused_arguments] def trivial (B : Type*) (F : Type*) : B → Type* := λ x, F instance [inhabited F] {b : B} : inhabited (bundle.trivial B F b) := ⟨(default F : F)⟩ /-- The trivial bundle, unlike other bundles, has a canonical projection on the fiber. -/ def trivial.proj_snd (B : Type*) (F : Type*) : (total_space (bundle.trivial B F)) → F := sigma.snd instance [I : topological_space F] : ∀ x : B, topological_space (trivial B F x) := λ x, I instance [t₁ : topological_space B] [t₂ : topological_space F] : topological_space (total_space (trivial B F)) := topological_space.induced (proj (trivial B F)) t₁ ⊓ topological_space.induced (trivial.proj_snd B F) t₂ end bundle /-- Core data defining a locally trivial topological bundle with fiber `F` over a topological space `B`. Note that "bundle" is used in its mathematical sense. This is the (computer science) bundled version, i.e., all the relevant data is contained in the following structure. A family of local trivializations is indexed by a type ι, on open subsets `base_set i` for each `i : ι`. Trivialization changes from `i` to `j` are given by continuous maps `coord_change i j` from `base_set i ∩ base_set j` to the set of homeomorphisms of `F`, but we express them as maps `B → F → F` and require continuity on `(base_set i ∩ base_set j) × F` to avoid the topology on the space of continuous maps on `F`. -/ @[nolint has_inhabited_instance] structure topological_fiber_bundle_core (ι : Type*) (B : Type*) [topological_space B] (F : Type*) [topological_space F] := (base_set : ι → set B) (is_open_base_set : ∀i, is_open (base_set i)) (index_at : B → ι) (mem_base_set_at : ∀x, x ∈ base_set (index_at x)) (coord_change : ι → ι → B → F → F) (coord_change_self : ∀i, ∀ x ∈ base_set i, ∀v, coord_change i i x v = v) (coord_change_continuous : ∀i j, continuous_on (λp : B × F, coord_change i j p.1 p.2) (set.prod ((base_set i) ∩ (base_set j)) univ)) (coord_change_comp : ∀i j k, ∀x ∈ (base_set i) ∩ (base_set j) ∩ (base_set k), ∀v, (coord_change j k x) (coord_change i j x v) = coord_change i k x v) attribute [simp, mfld_simps] topological_fiber_bundle_core.mem_base_set_at namespace topological_fiber_bundle_core variables [topological_space B] [topological_space F] (Z : topological_fiber_bundle_core ι B F) include Z /-- The index set of a topological fiber bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments has_inhabited_instance] def index := ι /-- The base space of a topological fiber bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments, reducible] def base := B /-- The fiber of a topological fiber bundle core, as a convenience function for dot notation and typeclass inference -/ @[nolint unused_arguments has_inhabited_instance] def fiber (x : B) := F instance topological_space_fiber (x : B) : topological_space (Z.fiber x) := by { dsimp [fiber], apply_instance } /-- The total space of the topological fiber bundle, as a convenience function for dot notation. It is by definition equal to `bundle.total_space Z.fiber`, a.k.a. `Σ x, Z.fiber x` but with a different name for typeclass inference. -/ @[nolint unused_arguments, reducible] def total_space := bundle.total_space Z.fiber /-- The projection from the total space of a topological fiber bundle core, on its base. -/ @[reducible, simp, mfld_simps] def proj : Z.total_space → B := bundle.proj Z.fiber /-- Local homeomorphism version of the trivialization change. -/ def triv_change (i j : ι) : local_homeomorph (B × F) (B × F) := { source := set.prod (Z.base_set i ∩ Z.base_set j) univ, target := set.prod (Z.base_set i ∩ Z.base_set j) univ, to_fun := λp, ⟨p.1, Z.coord_change i j p.1 p.2⟩, inv_fun := λp, ⟨p.1, Z.coord_change j i p.1 p.2⟩, map_source' := λp hp, by simpa using hp, map_target' := λp hp, by simpa using hp, left_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx.1 }, { simp [hx] } end, right_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx.2 }, { simp [hx] }, end, open_source := (is_open.inter (Z.is_open_base_set i) (Z.is_open_base_set j)).prod is_open_univ, open_target := (is_open.inter (Z.is_open_base_set i) (Z.is_open_base_set j)).prod is_open_univ, continuous_to_fun := continuous_on.prod continuous_fst.continuous_on (Z.coord_change_continuous i j), continuous_inv_fun := by simpa [inter_comm] using continuous_on.prod continuous_fst.continuous_on (Z.coord_change_continuous j i) } @[simp, mfld_simps] lemma mem_triv_change_source (i j : ι) (p : B × F) : p ∈ (Z.triv_change i j).source ↔ p.1 ∈ Z.base_set i ∩ Z.base_set j := by { erw [mem_prod], simp } /-- Associate to a trivialization index `i : ι` the corresponding trivialization, i.e., a bijection between `proj ⁻¹ (base_set i)` and `base_set i × F`. As the fiber above `x` is `F` but read in the chart with index `index_at x`, the trivialization in the fiber above x is by definition the coordinate change from i to `index_at x`, so it depends on `x`. The local trivialization will ultimately be a local homeomorphism. For now, we only introduce the local equiv version, denoted with a prime. In further developments, avoid this auxiliary version, and use `Z.local_triv` instead. -/ def local_triv' (i : ι) : local_equiv Z.total_space (B × F) := { source := Z.proj ⁻¹' (Z.base_set i), target := set.prod (Z.base_set i) univ, inv_fun := λp, ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩, to_fun := λp, ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩, map_source' := λp hp, by simpa only [set.mem_preimage, and_true, set.mem_univ, set.prod_mk_mem_set_prod_eq] using hp, map_target' := λp hp, by simpa only [set.mem_preimage, and_true, set.mem_univ, set.mem_prod] using hp, left_inv' := begin rintros ⟨x, v⟩ hx, change x ∈ Z.base_set i at hx, dsimp, rw [Z.coord_change_comp, Z.coord_change_self], { exact Z.mem_base_set_at _ }, { simp [hx] } end, right_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx }, { simp [hx] } end } @[simp, mfld_simps] lemma mem_local_triv'_source (i : ι) (p : Z.total_space) : p ∈ (Z.local_triv' i).source ↔ p.1 ∈ Z.base_set i := iff.rfl @[simp, mfld_simps] lemma mem_local_triv'_target (i : ι) (p : B × F) : p ∈ (Z.local_triv' i).target ↔ p.1 ∈ Z.base_set i := by { erw [mem_prod], simp } @[simp, mfld_simps] lemma local_triv'_apply (i : ι) (p : Z.total_space) : (Z.local_triv' i) p = ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma local_triv'_symm_apply (i : ι) (p : B × F) : (Z.local_triv' i).symm p = ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩ := rfl /-- The composition of two local trivializations is the trivialization change Z.triv_change i j. -/ lemma local_triv'_trans (i j : ι) : (Z.local_triv' i).symm.trans (Z.local_triv' j) ≈ (Z.triv_change i j).to_local_equiv := begin split, { ext x, erw [mem_prod], simp [local_equiv.trans_source] }, { rintros ⟨x, v⟩ hx, simp only [triv_change, local_triv', local_equiv.symm, true_and, prod_mk_mem_set_prod_eq, local_equiv.trans_source, mem_inter_eq, and_true, mem_univ, prod.mk.inj_iff, mem_preimage, proj, local_equiv.coe_mk, eq_self_iff_true, local_equiv.coe_trans, bundle.proj] at hx ⊢, simp [Z.coord_change_comp, hx], } end /-- Topological structure on the total space of a topological bundle created from core, designed so that all the local trivialization are continuous. -/ instance to_topological_space : topological_space (bundle.total_space Z.fiber) := topological_space.generate_from $ ⋃ (i : ι) (s : set (B × F)) (s_open : is_open s), {(Z.local_triv' i).source ∩ (Z.local_triv' i) ⁻¹' s} lemma open_source' (i : ι) : is_open (Z.local_triv' i).source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨i, set.prod (Z.base_set i) univ, (Z.is_open_base_set i).prod is_open_univ, _⟩, ext p, simp only with mfld_simps end lemma open_target' (i : ι) : is_open (Z.local_triv' i).target := (Z.is_open_base_set i).prod is_open_univ /-- Local trivialization of a topological bundle created from core, as a local homeomorphism. -/ def local_triv (i : ι) : local_homeomorph Z.total_space (B × F) := { open_source := Z.open_source' i, open_target := Z.open_target' i, continuous_to_fun := begin rw continuous_on_open_iff (Z.open_source' i), assume s s_open, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨i, s, s_open, rfl⟩ end, continuous_inv_fun := begin apply continuous_on_open_of_generate_from (Z.open_target' i), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, obtain ⟨j, s, s_open, ts⟩ : ∃ j s, is_open s ∧ t = (local_triv' Z j).source ∩ (local_triv' Z j) ⁻¹' s := ht, rw ts, simp only [local_equiv.right_inv, preimage_inter, local_equiv.left_inv], let e := Z.local_triv' i, let e' := Z.local_triv' j, let f := e.symm.trans e', have : is_open (f.source ∩ f ⁻¹' s), { rw [(Z.local_triv'_trans i j).source_inter_preimage_eq], exact (continuous_on_open_iff (Z.triv_change i j).open_source).1 ((Z.triv_change i j).continuous_on) _ s_open }, convert this using 1, dsimp [local_equiv.trans_source], rw [← preimage_comp, inter_assoc] end, to_local_equiv := Z.local_triv' i } /- We will now state again the basic properties of the local trivializations, but without primes, i.e., for the local homeomorphism instead of the local equiv. -/ @[simp, mfld_simps] lemma mem_local_triv_source (i : ι) (p : Z.total_space) : p ∈ (Z.local_triv i).source ↔ p.1 ∈ Z.base_set i := iff.rfl @[simp, mfld_simps] lemma mem_local_triv_target (i : ι) (p : B × F) : p ∈ (Z.local_triv i).target ↔ p.1 ∈ Z.base_set i := by { erw [mem_prod], simp } @[simp, mfld_simps] lemma local_triv_apply (i : ι) (p : Z.total_space) : (Z.local_triv i) p = ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma local_triv_symm_fst (i : ι) (p : B × F) : (Z.local_triv i).symm p = ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩ := rfl /-- The composition of two local trivializations is the trivialization change Z.triv_change i j. -/ lemma local_triv_trans (i j : ι) : (Z.local_triv i).symm.trans (Z.local_triv j) ≈ Z.triv_change i j := Z.local_triv'_trans i j /-- Extended version of the local trivialization of a fiber bundle constructed from core, registering additionally in its type that it is a local bundle trivialization. -/ def local_triv_ext (i : ι) : bundle_trivialization F Z.proj := { base_set := Z.base_set i, open_base_set := Z.is_open_base_set i, source_eq := rfl, target_eq := rfl, proj_to_fun := λp hp, by simp, to_local_homeomorph := Z.local_triv i } /-- A topological fiber bundle constructed from core is indeed a topological fiber bundle. -/ protected theorem is_topological_fiber_bundle : is_topological_fiber_bundle F Z.proj := λx, ⟨Z.local_triv_ext (Z.index_at x), Z.mem_base_set_at x⟩ /-- The projection on the base of a topological bundle created from core is continuous -/ lemma continuous_proj : continuous Z.proj := Z.is_topological_fiber_bundle.continuous_proj /-- The projection on the base of a topological bundle created from core is an open map -/ lemma is_open_map_proj : is_open_map Z.proj := Z.is_topological_fiber_bundle.is_open_map_proj /-- Preferred local trivialization of a fiber bundle constructed from core, at a given point, as a local homeomorphism -/ def local_triv_at (p : Z.total_space) : local_homeomorph Z.total_space (B × F) := Z.local_triv (Z.index_at (Z.proj p)) @[simp, mfld_simps] lemma mem_local_triv_at_source (p : Z.total_space) : p ∈ (Z.local_triv_at p).source := by simp [local_triv_at] @[simp, mfld_simps] lemma local_triv_at_fst (p q : Z.total_space) : ((Z.local_triv_at p) q).1 = q.1 := rfl @[simp, mfld_simps] lemma local_triv_at_symm_fst (p : Z.total_space) (q : B × F) : ((Z.local_triv_at p).symm q).1 = q.1 := rfl /-- Preferred local trivialization of a fiber bundle constructed from core, at a given point, as a bundle trivialization -/ def local_triv_at_ext (p : Z.total_space) : bundle_trivialization F Z.proj := Z.local_triv_ext (Z.index_at (Z.proj p)) @[simp, mfld_simps] lemma local_triv_at_ext_to_local_homeomorph (p : Z.total_space) : (Z.local_triv_at_ext p).to_local_homeomorph = Z.local_triv_at p := rfl /-- If an element of `F` is invariant under all coordinate changes, then one can define a corresponding section of the fiber bundle, which is continuous. This applies in particular to the zero section of a vector bundle. Another example (not yet defined) would be the identity section of the endomorphism bundle of a vector bundle. -/ lemma continuous_const_section (v : F) (h : ∀ i j, ∀ x ∈ (Z.base_set i) ∩ (Z.base_set j), Z.coord_change i j x v = v) : continuous (show B → Z.total_space, from λ x, ⟨x, v⟩) := begin apply continuous_iff_continuous_at.2 (λ x, _), have A : Z.base_set (Z.index_at x) ∈ 𝓝 x := is_open.mem_nhds (Z.is_open_base_set (Z.index_at x)) (Z.mem_base_set_at x), apply ((Z.local_triv (Z.index_at x)).continuous_at_iff_continuous_at_comp_left _).2, { simp only [(∘)] with mfld_simps, apply continuous_at_id.prod, have : continuous_on (λ (y : B), v) (Z.base_set (Z.index_at x)) := continuous_on_const, apply (this.congr _).continuous_at A, assume y hy, simp only [h, hy] with mfld_simps }, { exact A } end end topological_fiber_bundle_core
cbc3dda5ede30568e485822e50a9f5de6ac4889e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/triangle/basic.lean
639207f75591cd8f499a3bc32bc941e468069835
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,163
lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.simple_graph.clique /-! # Triangles in graphs > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A *triangle* in a simple graph is a `3`-clique, namely a set of three vertices that are pairwise adjacent. This module defines and proves properties about triangles in simple graphs. ## Main declarations * `simple_graph.far_from_triangle_free`: Predicate for a graph to have enough triangles that, to remove all of them, one must one must remove a lot of edges. This is the crux of the Triangle Removal lemma. ## TODO * Generalise `far_from_triangle_free` to other graphs, to state and prove the Graph Removal Lemma. * Find a better name for `far_from_triangle_free`. Added 4/26/2022. Remove this TODO if it gets old. -/ open finset fintype nat open_locale classical namespace simple_graph variables {α 𝕜 : Type*} [fintype α] [linear_ordered_field 𝕜] {G H : simple_graph α} {ε δ : 𝕜} {n : ℕ} {s : finset α} /-- A simple graph is *`ε`-triangle-free far* if one must remove at least `ε * (card α)^2` edges to make it triangle-free. -/ def far_from_triangle_free (G : simple_graph α) (ε : 𝕜) : Prop := G.delete_far (λ H, H.clique_free 3) $ ε * (card α^2 : ℕ) lemma far_from_triangle_free_iff : G.far_from_triangle_free ε ↔ ∀ ⦃H⦄, H ≤ G → H.clique_free 3 → ε * (card α^2 : ℕ) ≤ G.edge_finset.card - H.edge_finset.card := delete_far_iff alias far_from_triangle_free_iff ↔ far_from_triangle_free.le_card_sub_card _ lemma far_from_triangle_free.mono (hε : G.far_from_triangle_free ε) (h : δ ≤ ε) : G.far_from_triangle_free δ := hε.mono $ mul_le_mul_of_nonneg_right h $ cast_nonneg _ lemma far_from_triangle_free.clique_finset_nonempty' (hH : H ≤ G) (hG : G.far_from_triangle_free ε) (hcard : (G.edge_finset.card - H.edge_finset.card : 𝕜) < ε * (card α ^ 2 : ℕ)) : (H.clique_finset 3).nonempty := nonempty_of_ne_empty $ H.clique_finset_eq_empty_iff.not.2 $ λ hH', (hG.le_card_sub_card hH hH').not_lt hcard variables [nonempty α] lemma far_from_triangle_free.nonpos (h₀ : G.far_from_triangle_free ε) (h₁ : G.clique_free 3) : ε ≤ 0 := begin have := h₀ (empty_subset _), rw [coe_empty, finset.card_empty, cast_zero, delete_edges_empty_eq] at this, exact nonpos_of_mul_nonpos_left (this h₁) (cast_pos.2 $ sq_pos_of_pos fintype.card_pos), end lemma clique_free.not_far_from_triangle_free (hG : G.clique_free 3) (hε : 0 < ε) : ¬ G.far_from_triangle_free ε := λ h, (h.nonpos hG).not_lt hε lemma far_from_triangle_free.not_clique_free (hG : G.far_from_triangle_free ε) (hε : 0 < ε) : ¬ G.clique_free 3 := λ h, (hG.nonpos h).not_lt hε lemma far_from_triangle_free.clique_finset_nonempty (hG : G.far_from_triangle_free ε) (hε : 0 < ε) : (G.clique_finset 3).nonempty := nonempty_of_ne_empty $ G.clique_finset_eq_empty_iff.not.2 $ hG.not_clique_free hε end simple_graph
47b268ca5c96cccf959053f09ec078efece116ed
ac2987d8c7832fb4a87edb6bee26141facbb6fa0
/Mathlib/Logic/Function/Basic.lean
af81e0d9e6516a2d92de7e7982ab11e79442049d
[ "Apache-2.0" ]
permissive
AurelienSaue/mathlib4
52204b9bd9d207c922fe0cf3397166728bb6c2e2
84271fe0875bafdaa88ac41f1b5a7c18151bd0d5
refs/heads/master
1,689,156,096,545
1,629,378,840,000
1,629,378,840,000
389,648,603
0
0
Apache-2.0
1,627,307,284,000
1,627,307,284,000
null
UTF-8
Lean
false
false
28,496
lean
/- Copyright (c) 2016 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Logic.Basic import Mathlib.Function import Mathlib.Set import Mathlib.SetNotation universe u v w namespace Function section variable {α β γ : Sort _} {f : α → β} /-- Evaluate a function at an argument. Useful if you want to talk about the partially applied `Function.eval x : (∀ x, β x) → β x`. -/ @[reducible] def eval {β : α → Sort _} (x : α) (f : ∀ x, β x) : β x := f x @[simp] lemma eval_apply {β : α → Sort _} (x : α) (f : ∀ x, β x) : eval x f = f x := rfl lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl lemma const_def {y : β} : (λ x : α => y) = const α y := rfl @[simp] lemma const_apply {y : β} {x : α} : const α y x = y := rfl @[simp] lemma const_comp {f : α → β} {c : γ} : const β c ∘ f = const α c := rfl @[simp] lemma comp_const {f : β → γ} {b : β} : f ∘ const α b = const α (f b) := rfl lemma id_def : @id α = λ x => x := rfl lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : ∀a, β a} {f' : ∀a, β' a} (hα : α = α') (h : ∀a a', HEq a a' → HEq (f a) (f' a')) : HEq f f' := by subst hα have : ∀a, HEq (f a) (f' a) := λ a => h a a (HEq.refl a) have : β = β' := by funext a exact type_eq_of_heq (this a) subst this apply heq_of_eq funext a exact eq_of_heq (this a) lemma funext_iff {β : α → Sort _} {f₁ f₂ : ∀ (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := Iff.intro (λ h a => h ▸ rfl) funext protected lemma bijective.injective {f : α → β} (hf : bijective f) : injective f := hf.1 protected lemma bijective.surjective {f : α → β} (hf : bijective f) : surjective f := hf.2 theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ theorem injective.eq_iff' (I : injective f) {a b : α} {c : β} (h : f b = c) : f a = c ↔ a = b := h ▸ I.eq_iff lemma injective.ne (hf : injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ := mt (λ h => hf h) lemma injective.ne_iff (hf : injective f) {x y : α} : f x ≠ f y ↔ x ≠ y := ⟨mt $ congr_arg f, hf.ne⟩ lemma injective.ne_iff' (hf : injective f) {x y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y := h ▸ hf.ne_iff /-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then the domain `α` also has decidable equality. -/ def injective.decidable_eq [DecidableEq β] (I : injective f) : DecidableEq α := λ a b => decidable_of_iff _ I.eq_iff lemma injective.of_comp {g : γ → α} (I : injective (f ∘ g)) : injective g := λ {x y} h => I $ show f (g x) = f (g y) from congr_arg f h lemma injective.of_comp_iff {f : α → β} (hf : injective f) (g : γ → α) : injective (f ∘ g) ↔ injective g := ⟨injective.of_comp, hf.comp⟩ lemma injective.of_comp_iff' (f : α → β) {g : γ → α} (hg : bijective g) : injective (f ∘ g) ↔ injective f := ⟨ λ h x y => let ⟨x', hx⟩ := hg.surjective x let ⟨y', hy⟩ := hg.surjective y hx ▸ hy ▸ λ hf => h hf ▸ rfl, λ h => h.comp hg.injective⟩ lemma injective_of_subsingleton [Subsingleton α] (f : α → β) : injective f := λ {a b} ab => Subsingleton.elim _ _ lemma injective.dite (p : α → Prop) [DecidablePred p] {f : {a : α // p a} → β} {f' : {a : α // ¬ p a} → β} (hf : injective f) (hf' : injective f') (im_disj : ∀ {x x' : α} {hx : p x} {hx' : ¬ p x'}, f ⟨x, hx⟩ ≠ f' ⟨x', hx'⟩) : Function.injective (λ x => if h : p x then f ⟨x, h⟩ else f' ⟨x, h⟩) := by intros x₁ x₂ h --TODO mathlib3 uses dsimp here have hrw1 : (fun (x : α) => if h : p x then f ⟨x, h⟩ else f' ⟨x, h⟩) x₁ = if h : p x₁ then f ⟨x₁, h⟩ else f' ⟨x₁, h⟩ := rfl have hrw2 : (fun (x : α) => if h : p x then f ⟨x, h⟩ else f' ⟨x, h⟩) x₂ = if h : p x₂ then f ⟨x₂, h⟩ else f' ⟨x₂, h⟩ := rfl rw [hrw1, hrw2] at h exact Decidable.byCases (λ (h₁ : p x₁) => Decidable.byCases (λ (h₂ : p x₂) => by rw [dif_pos h₁, dif_pos h₂] at h injection (hf h) assumption) (λ (h₂ : ¬ p x₂) => by rw [dif_pos h₁, dif_neg h₂] at h exact (im_disj h).elim)) (λ (h₁ : ¬ p x₁) => Decidable.byCases (λ (h₂ : p x₂) => by rw [dif_neg h₁, dif_pos h₂] at h exact (im_disj h.symm).elim) (λ (h₂ : ¬ p x₂) => by rw [dif_neg h₁, dif_neg h₂] at h injection (hf' h) assumption)) lemma surjective.of_comp {g : γ → α} (S : surjective (f ∘ g)) : surjective f := λ y => let ⟨x, h⟩ := S y ⟨g x, h⟩ lemma surjective.of_comp_iff (f : α → β) {g : γ → α} (hg : surjective g) : surjective (f ∘ g) ↔ surjective f := ⟨surjective.of_comp, λ h => h.comp hg⟩ lemma surjective.of_comp_iff' {f : α → β} (hf : bijective f) (g : γ → α) : surjective (f ∘ g) ↔ surjective g := ⟨λ h x => let ⟨x', hx'⟩ := h (f x) ⟨x', hf.injective hx'⟩, hf.surjective.comp⟩ instance decidable_eq_pfun (p : Prop) [Decidable p] (α : p → Type _) [∀ hp, DecidableEq (α hp)] : DecidableEq (∀hp, α hp) | f, g => decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm theorem surjective.forall {f : α → β} (hf : surjective f) {p : β → Prop} : (∀ y, p y) ↔ ∀ x, p (f x) := ⟨λ h x => h (f x), λ h y => let ⟨x, hx⟩ := hf y hx ▸ h x⟩ theorem surjective.forall₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∀ y₁ y₂, p y₁ y₂) ↔ ∀ x₁ x₂, p (f x₁) (f x₂) := hf.forall.trans $ forall_congr' $ λ x => hf.forall theorem surjective.forall₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∀ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∀ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.forall.trans $ forall_congr' $ λ x => hf.forall₂ theorem surjective.exists {f : α → β} (hf : surjective f) {p : β → Prop} : (∃ y, p y) ↔ ∃ x, p (f x) := ⟨λ ⟨y, hy⟩ => let ⟨x, hx⟩ := hf y ⟨x, hx.symm ▸ hy⟩, λ ⟨x, hx⟩ => ⟨f x, hx⟩⟩ theorem surjective.exists₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∃ y₁ y₂, p y₁ y₂) ↔ ∃ x₁ x₂, p (f x₁) (f x₂) := hf.exists.trans $ exists_congr $ λ x => hf.exists theorem surjective.exists₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∃ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∃ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.exists.trans $ exists_congr $ λ x => hf.exists₂ lemma bijective_iff_exists_unique (f : α → β) : bijective f ↔ ∀ b : β, ∃! (a : α), f a = b := ⟨ λ hf b => let ⟨a, ha⟩ := hf.surjective b ⟨a, ha, λ a' ha' => hf.injective (ha'.trans ha.symm)⟩, λ he => ⟨ λ {a a'} h => unique_of_exists_unique (he (f a')) h rfl, λ b => ExistsUnique.exists (he b) ⟩⟩ /-- Shorthand for using projection notation with `function.bijective_iff_exists_unique`. -/ lemma bijective.exists_unique {f : α → β} (hf : bijective f) (b : β) : ∃! (a : α), f a = b := (bijective_iff_exists_unique f).mp hf b lemma bijective.of_comp_iff (f : α → β) {g : γ → α} (hg : bijective g) : bijective (f ∘ g) ↔ bijective f := and_congr (injective.of_comp_iff' _ hg) (surjective.of_comp_iff _ hg.surjective) lemma bijective.of_comp_iff' {f : α → β} (hf : bijective f) (g : γ → α) : Function.bijective (f ∘ g) ↔ Function.bijective g := and_congr (injective.of_comp_iff hf.injective _) (surjective.of_comp_iff' hf _) /-- Cantor's diagonal argument implies that there are no surjective functions from `α` to `Set α`. -/ theorem cantor_surjective {α} (f : α → Set α) : ¬ Function.surjective f | h => let ⟨D, e⟩ := h (λ a => ¬ f a a) by have x := @iff_not_self (f D D) exact (@iff_not_self (f D D)) $ iff_of_eq (congr_fun e D) /-- Cantor's diagonal argument implies that there are no injective functions from `Set α` to `α`. -/ theorem cantor_injective {α : Type _} (f : (Set α) → α) : ¬ Function.injective f | i => cantor_surjective (λ a b => ∀ U, a = f U → U b) $ right_inverse.surjective (λ U => funext $ λ a => propext ⟨λ h => h U rfl, λ h' U' e => i e ▸ h'⟩) /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → Option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ {a b} h => Option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) -- TODO mathlib3 uses Mem here theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : g x = some b) (h₂ : g y = some b) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem left_inverse_iff_comp {f : α → β} {g : β → α} : left_inverse f g ↔ f ∘ g = id := ⟨left_inverse.comp_eq_id, congr_fun⟩ theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem right_inverse_iff_comp {f : α → β} {g : β → α} : right_inverse f g ↔ g ∘ f = id := ⟨right_inverse.comp_eq_id, congr_fun⟩ theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := λ a => show h (f (g (i a))) = a by rw [hf (i a), hh a] theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf theorem left_inverse.right_inverse {f : α → β} {g : β → α} (h : left_inverse g f) : right_inverse f g := h theorem right_inverse.left_inverse {f : α → β} {g : β → α} (h : right_inverse g f) : left_inverse f g := h theorem left_inverse.surjective {f : α → β} {g : β → α} (h : left_inverse f g) : surjective f := h.right_inverse.surjective theorem right_inverse.injective {f : α → β} {g : β → α} (h : right_inverse f g) : injective f := h.left_inverse.injective theorem left_inverse.eq_right_inverse {f : α → β} {g₁ g₂ : β → α} (h₁ : left_inverse g₁ f) (h₂ : Function.right_inverse g₂ f) : g₁ = g₂ := by have h₃ : g₁ = g₁ ∘ f ∘ g₂ := by rw [h₂.comp_eq_id, comp.right_id] have h₄ : g₁ ∘ f ∘ g₂ = g₂ := by rw [← comp.assoc, h₁.comp_eq_id, comp.left_id] rwa [←h₄] attribute [local instance] Classical.propDecidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : Option α := if h : ∃ a, f a = b then some (Classical.choose h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a, b => ⟨λ h => have hpi: partial_inv f b = if h : ∃ a, f a = b then some (Classical.choose h) else none := rfl if h' : ∃ a, f a = b then by rw [hpi, dif_pos h'] at h injection h with h subst h apply Classical.choose_spec h' else by rw [hpi, dif_neg h'] at h; contradiction, λ e => e ▸ have h : ∃ a', f a' = f a := ⟨_, rfl⟩ (dif_pos h).trans (congr_arg _ (I $ Classical.choose_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variable {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : Set α} {a : α} {b : β} attribute [local instance] Classical.propDecidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. For a computable version, see `function.injective.inv_of_mem_range`. -/ noncomputable def inv_fun_on (f : α → β) (s : Set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then Classical.choose h else Classical.choice n theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by have h1 : inv_fun_on f s b = if h : ∃a, a ∈ s ∧ f a = b then Classical.choose h else Classical.choice n := rfl rw [dif_pos h] at h1 rw [h1] exact Classical.choose_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have : ∃a'∈s, f a' = f a := ⟨a, ha, rfl⟩ h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = Classical.choice n := by have h1 : inv_fun_on f s b = if h : ∃a, a ∈ s ∧ f a = b then Classical.choose h else Classical.choice n := rfl rwa [dif_neg h] at h1 /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f Set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h ⟨a, trivial, ha⟩ lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = Classical.choice n := by refine inv_fun_on_neg (mt ?_ h); exact λ ⟨a, _, ha⟩ => ⟨a, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ λ b => hf (by rw [hg b] exact inv_fun_eq ⟨g b, hg b⟩) lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := λ b => inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := λ b => have : f (inv_fun f (f b)) = f b := inv_fun_eq ⟨b, rfl⟩ hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := (left_inverse_inv_fun hf).surjective lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf end inv_fun section inv_fun variable {α : Type u} [i : Nonempty α] {β : Sort v} {f : α → β} lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, has_left_inverse.injective⟩ end inv_fun section surj_inv variable {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := Classical.choose (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := Classical.choose_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, has_right_inverse.surjective⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf => ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩ => ⟨gl.injective, gr.surjective⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := (right_inverse_surj_inv h).injective lemma surjective_to_subsingleton [na : Nonempty α] [Subsingleton β] (f : α → β) : surjective f := λ y => let ⟨a⟩ := na; ⟨a, Subsingleton.elim _ _⟩ end surj_inv section update variable {α : Sort u} {β : α → Sort v} {α' : Sort w} [DecidableEq α] [DecidableEq α'] /-- Replacing the value of a function at a given point by a given value. -/ def update (f : ∀a, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then Eq.rec (motive := λ a _ => β a) v h.symm else f a /-- On non-dependent functions, `function.update` can be expressed as an `ite` -/ lemma update_apply {β : Sort _} (f : α → β) (a' : α) (b : β) (a : α) : update f a' b a = if a = a' then b else f a := by have h2 : (h : a = a') → Eq.rec (motive := λ a b => β) b h.symm = b := by intro h rw [eq_rec_constant] have h3 : (λ h : a = a' => Eq.rec (motive := λ a b => β) b h.symm) = (λ _ : a = a' => b) := funext h2 let f := λ x => dite (a = a') x (λ (_: ¬ a = a') => (f a)) exact congrArg f h3 @[simp] lemma update_same (a : α) (v : β a) (f : ∀a, β a) : update f a v a = v := dif_pos rfl lemma update_injective (f : ∀a, β a) (a' : α) : injective (update f a') := by intros v v' h have h' := congrFun h a' rwa [update_same, update_same] at h' @[simp] lemma update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : ∀a, β a) : update f a' v a = f a := dif_neg h lemma forall_update_iff (f : ∀a, β a) {a : α} {b : β a} (p : ∀a, β a → Prop) : (∀ x, p x (update f a b x)) ↔ p a b ∧ ∀ x, x ≠ a → p x (f x) := Iff.intro (by intro h have h1 := h a have h2 : update f a b a = b := update_same _ _ _ rw [h2] at h1 refine ⟨h1, ?_⟩ intro x hx have h3 := update_noteq hx b f rw [←h3] exact h x) (by intro ⟨hp,h⟩ x have h1 : x = a ∨ x ≠ a := Decidable.em _ match h1 with | Or.inl he => rw [he, update_same] exact hp | Or.inr hne => have h4 := update_noteq hne b f rw [h4] exact h x hne) lemma update_eq_iff {a : α} {b : β a} {f g : ∀ a, β a} : update f a b = g ↔ b = g a ∧ ∀ x, x ≠ a -> f x = g x := funext_iff.trans $ forall_update_iff _ (λ x y => y = g x) lemma eq_update_iff {a : α} {b : β a} {f g : ∀ a, β a} : g = update f a b ↔ g a = b ∧ ∀ x, x ≠ a -> g x = f x := funext_iff.trans $ forall_update_iff _ (λ x y => g x = y) @[simp] lemma update_eq_self (a : α) (f : ∀a, β a) : update f a (f a) = f := update_eq_iff.2 ⟨rfl, λ _ _ => rfl⟩ lemma update_comp_eq_of_forall_ne' {α'} (g : ∀ a, β a) {f : α' → α} {i : α} (a : β i) (h : ∀ x, f x ≠ i) : (λ j => (update g i a) (f j)) = (λ j => g (f j)) := funext $ λ x => update_noteq (h _) _ _ /-- Non-dependent version of `function.update_comp_eq_of_forall_ne'` -/ lemma update_comp_eq_of_forall_ne {α β : Sort _} (g : α' → β) {f : α → α'} {i : α'} (a : β) (h : ∀ x, f x ≠ i) : (update g i a) ∘ f = g ∘ f := update_comp_eq_of_forall_ne' g a h lemma update_comp_eq_of_injective' (g : ∀a, β a) {f : α' → α} (hf : Function.injective f) (i : α') (a : β (f i)) : (λ j => update g (f i) a (f j)) = update (λ i => g (f i)) i a := eq_update_iff.2 ⟨update_same _ _ _, λ j hj => update_noteq (hf.ne hj) _ _⟩ /-- Non-dependent version of `function.update_comp_eq_of_injective'` -/ lemma update_comp_eq_of_injective {β : Sort _} (g : α' → β) {f : α → α'} (hf : Function.injective f) (i : α) (a : β) : (Function.update g (f i) a) ∘ f = Function.update (g ∘ f) i a := update_comp_eq_of_injective' g hf i a lemma apply_update {ι : Sort _} [DecidableEq ι] {α β : ι → Sort _} (f : ∀i, α i → β i) (g : ∀i, α i) (i : ι) (v : α i) (j : ι) : f j (update g i v j) = update (λ k => f k (g k)) i (f i v) j := by by_cases h : j = i subst j; simp simp[h] lemma comp_update {α' : Sort _} {β : Sort _} (f : α' → β) (g : α → α') (i : α) (v : α') : f ∘ (update g i v) = update (f ∘ g) i (f v) := funext $ apply_update _ _ _ _ theorem update_comm {α} [DecidableEq α] {β : α → Sort _} {a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : ∀a, β a) : update (update f a v) b w = update (update f b w) a v := by funext c simp only [update] (by_cases h₁ : c = b <;> by_cases h₂ : c = a) - rw [dif_pos h₁, dif_pos h₂] (cases h (h₂.symm.trans h₁)) - rw [dif_pos h₁, dif_pos h₁, dif_neg h₂] - rw [dif_neg h₁, dif_neg h₁, dif_pos h₂] - rw [dif_neg h₁, dif_neg h₁, dif_neg h₂] @[simp] theorem update_idem {α} [DecidableEq α] {β : α → Sort _} {a : α} (v w : β a) (f : ∀a, β a) : update (update f a v) a w = update f a w := by funext b by_cases b = a <;> simp [update, h] end update section extend attribute [local instance] Classical.propDecidable variable {α β γ : Type _} {f : α → β} /-- `extend f g e'` extends a function `g : α → γ` along a function `f : α → β` to a function `β → γ`, by using the values of `g` on the range of `f` and the values of an auxiliary function `e' : β → γ` elsewhere. Mostly useful when `f` is injective. -/ noncomputable def extend (f : α → β) (g : α → γ) (e' : β → γ) : β → γ := λ b => if h : ∃ a, f a = b then g (Classical.choose h) else e' b lemma extend_def (f : α → β) (g : α → γ) (e' : β → γ) (b : β) [hd : Decidable (∃ a, f a = b)] : extend f g e' b = if h : ∃ a, f a = b then g (Classical.choose h) else e' b := by rw [Subsingleton.elim hd] -- align the Decidable instances implicitly used by `dite` exact rfl @[simp] lemma extend_apply (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := by simp only [extend_def, dif_pos, exists_apply_eq_apply] exact congr_arg g (hf $ Classical.choose_spec (exists_apply_eq_apply f a)) @[simp] lemma extend_comp (hf : injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g := funext $ λ a => extend_apply hf g e' a end extend lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp => f p.1 p.2) := rfl @[simp] lemma uncurry_apply_pair {α β γ} (f : α → β → γ) (x : α) (y : β) : uncurry f (x, y) = f x y := rfl @[simp] lemma curry_apply {α β γ} (f : α × β → γ) (x : α) (y : β) : curry f x y = f (x, y) := rfl section bicomp variable {α β γ δ ε : Type _} /-- Compose a binary function `f` with a pair of unary functions `g` and `h`. If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/ def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) := f (g a) (h b) /-- Compose an unary function `f` with a binary function `g`. -/ def bicompr (f : γ → δ) (g : α → β → γ) (a b) := f (g a b) -- Suggested local notation: local notation f " ∘₂ " g => bicompr f g lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) : uncurry (g ∘₂ f) = (g ∘ uncurry f) := rfl lemma uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = (uncurry f) ∘ (Prod.map g h) := funext (by intro x; cases x; exact rfl) end bicomp section uncurry variable {α β γ δ : Type _} /-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ class has_uncurry (α : Type _) (β : outParam (Type _)) (γ : outParam (Type _)) := (uncurry : α → (β → γ)) /- Uncurrying operator. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ notation:max "↿" x:max => has_uncurry.uncurry x instance has_uncurry_base : has_uncurry (α → β) α β := ⟨id⟩ instance has_uncurry_induction [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ := ⟨λ f p => ↿(f p.1) p.2⟩ end uncurry /-- A function is involutive, if `f ∘ f = id`. -/ def involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x -- TODO: involutive_iff_iter_2_eq_id namespace involutive variable {α : Sort u} {f : α → α} (h : involutive f) @[simp] lemma comp_self : f ∘ f = id := funext h protected lemma left_inverse : left_inverse f f := h protected lemma right_inverse : right_inverse f f := h protected lemma injective : injective f := h.left_inverse.injective protected lemma surjective : surjective f := λ x => ⟨f x, h x⟩ protected lemma bijective : bijective f := ⟨h.injective, h.surjective⟩ /-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/ protected lemma ite_not (P : Prop) [Decidable P] (x : α) : f (ite P x (f x)) = ite (¬ P) x (f x) := by rw [apply_ite f, h, ite_not] /-- An involution commutes across an equality. Compare to `function.injective.eq_iff`. -/ protected lemma eq_iff {x y : α} : f x = y ↔ x = f y := Function.injective.eq_iff' (involutive.injective h) (h y) end involutive /-- The property of a binary function `f : α → β → γ` being injective. Mathematically this should be thought of as the corresponding function `α × β → γ` being injective. -/ @[reducible] def injective2 {α β γ} (f : α → β → γ) : Prop := ∀ {a₁ a₂ b₁ b₂}, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂ namespace injective2 variable {α β γ : Type _} (f : α → β → γ) protected lemma left (hf : injective2 f) {a₁ a₂ b₁ b₂} (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ := (hf h).1 protected lemma right (hf : injective2 f) {a₁ a₂ b₁ b₂} (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ := (hf h).2 lemma eq_iff (hf : injective2 f) {a₁ a₂ b₁ b₂} : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ h => hf h, λ⟨h1, h2⟩ => congr_arg2 f h1 h2⟩ end injective2 section sometimes attribute [local instance] Classical.propDecidable /-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially interesting in the case where `α` is a proposition, in which case `f` is necessarily a constant function, so that `sometimes f = f a` for all `a`. -/ noncomputable def sometimes {α β} [Nonempty β] (f : α → β) : β := if h : Nonempty α then f (Classical.choice h) else Classical.choice ‹_› theorem sometimes_eq {p : Prop} {α} [Nonempty α] (f : p → α) (a : p) : sometimes f = f a := dif_pos ⟨a⟩ theorem sometimes_spec {p : Prop} {α} [Nonempty α] (P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) := by rwa [sometimes_eq] end sometimes end Function /-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/ def set.piecewise {α : Type u} {β : α → Sort v} (s : Set α) (f g : ∀i, β i) [∀j, Decidable (j ∈ s)] : ∀i, β i := λi => if i ∈ s then f i else g i -- TODO: eq_rec_on_bijective, eq_mp_bijective, eq_mpr_bijective, cast_biject, eq_rec_inj, cast_inj /-- A set of functions "separates points" if for each pair of distinct points there is a function taking different values on them. -/ def set.separates_points {α β : Type _} (A : Set (α → β)) : Prop := ∀ {x y : α}, x ≠ y → ∃ f ∈ A, (f x : β) ≠ f y -- TODO: is_symm_op.flip_eq
f56d4e412b1e4038cf5d3dc70ff37c547a164cd7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/sheafification.lean
f424ae433bc56ad17046b89aa32c376fb85f3d67
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
24,295
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.adjunction.fully_faithful import category_theory.sites.plus import category_theory.limits.concrete_category import category_theory.concrete_category.elementwise /-! # Sheafification > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We construct the sheafification of a presheaf over a site `C` with values in `D` whenever `D` is a concrete category for which the forgetful functor preserves the appropriate (co)limits and reflects isomorphisms. We generally follow the approach of https://stacks.math.columbia.edu/tag/00W1 -/ namespace category_theory open category_theory.limits opposite universes w v u variables {C : Type u} [category.{v} C] {J : grothendieck_topology C} variables {D : Type w} [category.{max v u} D] section variables [concrete_category.{max v u} D] local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun /-- A concrete version of the multiequalizer, to be used below. -/ @[nolint has_nonempty_instance] def meq {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) := { x : Π (I : S.arrow), P.obj (op I.Y) // ∀ (I : S.relation), P.map I.g₁.op (x I.fst) = P.map I.g₂.op (x I.snd) } end namespace meq variables [concrete_category.{max v u} D] local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun instance {X} (P : Cᵒᵖ ⥤ D) (S : J.cover X) : has_coe_to_fun (meq P S) (λ x, Π (I : S.arrow), P.obj (op I.Y)) := ⟨λ x, x.1⟩ @[ext] lemma ext {X} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x y : meq P S) (h : ∀ I : S.arrow, x I = y I) : x = y := subtype.ext $ funext $ h lemma condition {X} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (I : S.relation) : P.map I.g₁.op (x ((S.index P).fst_to I)) = P.map I.g₂.op (x ((S.index P).snd_to I)) := x.2 _ /-- Refine a term of `meq P T` with respect to a refinement `S ⟶ T` of covers. -/ def refine {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (x : meq P T) (e : S ⟶ T) : meq P S := ⟨λ I, x ⟨I.Y, I.f, (le_of_hom e) _ I.hf⟩, λ I, x.condition ⟨I.Y₁, I.Y₂, I.Z, I.g₁, I.g₂, I.f₁, I.f₂, (le_of_hom e) _ I.h₁, (le_of_hom e) _ I.h₂, I.w⟩⟩ @[simp] lemma refine_apply {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (x : meq P T) (e : S ⟶ T) (I : S.arrow) : x.refine e I = x ⟨I.Y, I.f, (le_of_hom e) _ I.hf⟩ := rfl /-- Pull back a term of `meq P S` with respect to a morphism `f : Y ⟶ X` in `C`. -/ def pullback {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X) : meq P ((J.pullback f).obj S) := ⟨λ I, x ⟨_,I.f ≫ f, I.hf⟩, λ I, x.condition ⟨I.Y₁, I.Y₂, I.Z, I.g₁, I.g₂, I.f₁ ≫ f, I.f₂ ≫ f, I.h₁, I.h₂, by simp [reassoc_of I.w]⟩ ⟩ @[simp] lemma pullback_apply {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X) (I : ((J.pullback f).obj S).arrow) : x.pullback f I = x ⟨_, I.f ≫ f, I.hf⟩ := rfl @[simp] lemma pullback_refine {Y X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (h : S ⟶ T) (f : Y ⟶ X) (x : meq P T) : (x.pullback f).refine ((J.pullback f).map h) = (refine x h).pullback _ := rfl /-- Make a term of `meq P S`. -/ def mk {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) : meq P S := ⟨λ I, P.map I.f.op x, λ I, by { dsimp, simp only [← comp_apply, ← P.map_comp, ← op_comp, I.w] }⟩ lemma mk_apply {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) (I : S.arrow) : mk S x I = P.map I.f.op x := rfl variable [preserves_limits (forget D)] /-- The equivalence between the type associated to `multiequalizer (S.index P)` and `meq P S`. -/ noncomputable def equiv {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) [has_multiequalizer (S.index P)] : (multiequalizer (S.index P) : D) ≃ meq P S := limits.concrete.multiequalizer_equiv _ @[simp] lemma equiv_apply {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} [has_multiequalizer (S.index P)] (x : multiequalizer (S.index P)) (I : S.arrow) : equiv P S x I = multiequalizer.ι (S.index P) I x := rfl @[simp] lemma equiv_symm_eq_apply {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} [has_multiequalizer (S.index P)] (x : meq P S) (I : S.arrow) : multiequalizer.ι (S.index P) I ((meq.equiv P S).symm x) = x I := begin let z := (meq.equiv P S).symm x, rw ← equiv_apply, simp, end end meq namespace grothendieck_topology namespace plus variables [concrete_category.{max v u} D] local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun variable [preserves_limits (forget D)] variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] variables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)] noncomputable theory /-- Make a term of `(J.plus_obj P).obj (op X)` from `x : meq P S`. -/ def mk {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) : (J.plus_obj P).obj (op X) := colimit.ι (J.diagram P X) (op S) ((meq.equiv P S).symm x) lemma res_mk_eq_mk_pullback {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X) : (J.plus_obj P).map f.op (mk x) = mk (x.pullback f) := begin dsimp [mk, plus_obj], simp only [← comp_apply, colimit.ι_pre, ι_colim_map_assoc], simp_rw [comp_apply], congr' 1, apply_fun meq.equiv P _, erw equiv.apply_symm_apply, ext i, simp only [diagram_pullback_app, meq.pullback_apply, meq.equiv_apply, ← comp_apply], erw [multiequalizer.lift_ι, meq.equiv_symm_eq_apply], cases i, refl, end lemma to_plus_mk {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) : (J.to_plus P).app _ x = mk (meq.mk S x) := begin dsimp [mk, to_plus], let e : S ⟶ ⊤ := hom_of_le (order_top.le_top _), rw ← colimit.w _ e.op, delta cover.to_multiequalizer, simp only [comp_apply], congr' 1, dsimp [diagram], apply concrete.multiequalizer_ext, intros i, simpa only [← comp_apply, category.assoc, multiequalizer.lift_ι, category.comp_id, meq.equiv_symm_eq_apply], end lemma to_plus_apply {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : meq P S) (I : S.arrow) : (J.to_plus P).app _ (x I) = (J.plus_obj P).map I.f.op (mk x) := begin dsimp only [to_plus, plus_obj], delta cover.to_multiequalizer, dsimp [mk], simp only [← comp_apply, colimit.ι_pre, ι_colim_map_assoc], simp only [comp_apply], dsimp only [functor.op], let e : (J.pullback I.f).obj (unop (op S)) ⟶ ⊤ := hom_of_le (order_top.le_top _), rw ← colimit.w _ e.op, simp only [comp_apply], congr' 1, apply concrete.multiequalizer_ext, intros i, dsimp [diagram], simp only [← comp_apply, category.assoc, multiequalizer.lift_ι, category.comp_id, meq.equiv_symm_eq_apply], let RR : S.relation := ⟨_, _, _, i.f, 𝟙 _, I.f, i.f ≫ I.f, I.hf, sieve.downward_closed _ I.hf _, by simp⟩, cases I, erw x.condition RR, simpa [RR], end lemma to_plus_eq_mk {X : C} {P : Cᵒᵖ ⥤ D} (x : P.obj (op X)) : (J.to_plus P).app _ x = mk (meq.mk ⊤ x) := begin dsimp [mk, to_plus], delta cover.to_multiequalizer, simp only [comp_apply], congr' 1, apply_fun (meq.equiv P ⊤), ext i, simpa, end variables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)] lemma exists_rep {X : C} {P : Cᵒᵖ ⥤ D} (x : (J.plus_obj P).obj (op X)) : ∃ (S : J.cover X) (y : meq P S), x = mk y := begin obtain ⟨S,y,h⟩ := concrete.colimit_exists_rep (J.diagram P X) x, use [S.unop, meq.equiv _ _ y], rw ← h, dsimp [mk], simp, end lemma eq_mk_iff_exists {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (x : meq P S) (y : meq P T) : mk x = mk y ↔ (∃ (W : J.cover X) (h1 : W ⟶ S) (h2 : W ⟶ T), x.refine h1 = y.refine h2) := begin split, { intros h, obtain ⟨W, h1, h2, hh⟩ := concrete.colimit_exists_of_rep_eq _ _ _ h, use [W.unop, h1.unop, h2.unop], ext I, apply_fun (multiequalizer.ι (W.unop.index P) I) at hh, convert hh, all_goals { dsimp [diagram], simp only [← comp_apply, multiequalizer.lift_ι, category.comp_id, meq.equiv_symm_eq_apply], cases I, refl } }, { rintros ⟨S,h1,h2,e⟩, apply concrete.colimit_rep_eq_of_exists, use [(op S), h1.op, h2.op], apply concrete.multiequalizer_ext, intros i, apply_fun (λ ee, ee i) at e, convert e, all_goals { dsimp [diagram], simp only [← comp_apply, multiequalizer.lift_ι, meq.equiv_symm_eq_apply], cases i, refl } }, end /-- `P⁺` is always separated. -/ theorem sep {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) (x y : (J.plus_obj P).obj (op X)) (h : ∀ (I : S.arrow), (J.plus_obj P).map I.f.op x = (J.plus_obj P).map I.f.op y) : x = y := begin -- First, we choose representatives for x and y. obtain ⟨Sx,x,rfl⟩ := exists_rep x, obtain ⟨Sy,y,rfl⟩ := exists_rep y, simp only [res_mk_eq_mk_pullback] at h, -- Next, using our assumption, -- choose covers over which the pullbacks of these representatives become equal. choose W h1 h2 hh using λ (I : S.arrow), (eq_mk_iff_exists _ _).mp (h I), -- To prove equality, it suffices to prove that there exists a cover over which -- the representatives become equal. rw eq_mk_iff_exists, -- Construct the cover over which the representatives become equal by combining the various -- covers chosen above. let B : J.cover X := S.bind W, use B, -- Prove that this cover refines the two covers over which our representatives are defined -- and use these proofs. let ex : B ⟶ Sx := hom_of_le begin rintros Y f ⟨Z,e1,e2,he2,he1,hee⟩, rw ← hee, apply le_of_hom (h1 ⟨_, _, he2⟩), exact he1, end, let ey : B ⟶ Sy := hom_of_le begin rintros Y f ⟨Z,e1,e2,he2,he1,hee⟩, rw ← hee, apply le_of_hom (h2 ⟨_, _, he2⟩), exact he1, end, use [ex, ey], -- Now prove that indeed the representatives become equal over `B`. -- This will follow by using the fact that our representatives become -- equal over the chosen covers. ext1 I, let IS : S.arrow := I.from_middle, specialize hh IS, let IW : (W IS).arrow := I.to_middle, apply_fun (λ e, e IW) at hh, convert hh, { let Rx : Sx.relation := ⟨I.Y, I.Y, I.Y, 𝟙 _, 𝟙 _, I.f, I.to_middle_hom ≫ I.from_middle_hom, _, _, by simp [I.middle_spec]⟩, have := x.condition Rx, simpa using this }, { let Ry : Sy.relation := ⟨I.Y, I.Y, I.Y, 𝟙 _, 𝟙 _, I.f, I.to_middle_hom ≫ I.from_middle_hom, _, _, by simp [I.middle_spec]⟩, have := y.condition Ry, simpa using this }, end lemma inj_of_sep (P : Cᵒᵖ ⥤ D) (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)), (∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y) (X : C) : function.injective ((J.to_plus P).app (op X)) := begin intros x y h, simp only [to_plus_eq_mk] at h, rw eq_mk_iff_exists at h, obtain ⟨W, h1, h2, hh⟩ := h, apply hsep X W, intros I, apply_fun (λ e, e I) at hh, exact hh end /-- An auxiliary definition to be used in the proof of `exists_of_sep` below. Given a compatible family of local sections for `P⁺`, and representatives of said sections, construct a compatible family of local sections of `P` over the combination of the covers associated to the representatives. The separatedness condition is used to prove compatibility among these local sections of `P`. -/ def meq_of_sep (P : Cᵒᵖ ⥤ D) (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)), (∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y) (X : C) (S : J.cover X) (s : meq (J.plus_obj P) S) (T : Π (I : S.arrow), J.cover I.Y) (t : Π (I : S.arrow), meq P (T I)) (ht : ∀ (I : S.arrow), s I = mk (t I)) : meq P (S.bind T) := { val := λ I, t I.from_middle I.to_middle, property := begin intros II, apply inj_of_sep P hsep, rw [← comp_apply, ← comp_apply, (J.to_plus P).naturality, (J.to_plus P).naturality, comp_apply, comp_apply], erw [to_plus_apply (T II.fst.from_middle) (t II.fst.from_middle) II.fst.to_middle, to_plus_apply (T II.snd.from_middle) (t II.snd.from_middle) II.snd.to_middle, ← ht, ← ht, ← comp_apply, ← comp_apply, ← (J.plus_obj P).map_comp, ← (J.plus_obj P).map_comp], rw [← op_comp, ← op_comp], let IR : S.relation := ⟨_, _, _, II.g₁ ≫ II.fst.to_middle_hom, II.g₂ ≫ II.snd.to_middle_hom, II.fst.from_middle_hom, II.snd.from_middle_hom, II.fst.from_middle_condition, II.snd.from_middle_condition, _⟩, swap, { simp only [category.assoc, II.fst.middle_spec, II.snd.middle_spec], apply II.w }, exact s.condition IR, end } theorem exists_of_sep (P : Cᵒᵖ ⥤ D) (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)), (∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y) (X : C) (S : J.cover X) (s : meq (J.plus_obj P) S) : ∃ t : (J.plus_obj P).obj (op X), meq.mk S t = s := begin have inj : ∀ (X : C), function.injective ((J.to_plus P).app (op X)) := inj_of_sep _ hsep, -- Choose representatives for the given local sections. choose T t ht using λ I, exists_rep (s I), -- Construct a large cover over which we will define a representative that will -- provide the gluing of the given local sections. let B : J.cover X := S.bind T, choose Z e1 e2 he2 he1 hee using λ I : B.arrow, I.hf, -- Construct a compatible system of local sections over this large cover, using the chosen -- representatives of our local sections. -- The compatilibity here follows from the separatedness assumption. let w : meq P B := meq_of_sep P hsep X S s T t ht, -- The associated gluing will be the candidate section. use mk w, ext I, erw [ht, res_mk_eq_mk_pullback], -- Use the separatedness of `P⁺` to prove that this is indeed a gluing of our -- original local sections. apply sep P (T I), intros II, simp only [res_mk_eq_mk_pullback, eq_mk_iff_exists], -- It suffices to prove equality for representatives over a -- convenient sufficiently large cover... use (J.pullback II.f).obj (T I), let e0 : (J.pullback II.f).obj (T I) ⟶ (J.pullback II.f).obj ((J.pullback I.f).obj B) := hom_of_le begin intros Y f hf, apply sieve.le_pullback_bind _ _ _ I.hf, { cases I, exact hf }, end, use [e0, 𝟙 _], ext IV, dsimp only [meq.refine_apply, meq.pullback_apply, w], let IA : B.arrow := ⟨_, (IV.f ≫ II.f) ≫ I.f, _⟩, swap, { refine ⟨I.Y, _, _, I.hf, _, rfl⟩, apply sieve.downward_closed, convert II.hf, cases I, refl }, let IB : S.arrow := IA.from_middle, let IC : (T IB).arrow := IA.to_middle, let ID : (T I).arrow := ⟨IV.Y, IV.f ≫ II.f, sieve.downward_closed (T I) II.hf IV.f⟩, change t IB IC = t I ID, apply inj IV.Y, erw [to_plus_apply (T I) (t I) ID, to_plus_apply (T IB) (t IB) IC, ← ht, ← ht], -- Conclude by constructing the relation showing equality... let IR : S.relation := ⟨_, _, IV.Y, IC.f, ID.f, IB.f, I.f, _, I.hf, IA.middle_spec⟩, convert s.condition IR, cases I, refl, end variable [reflects_isomorphisms (forget D)] /-- If `P` is separated, then `P⁺` is a sheaf. -/ theorem is_sheaf_of_sep (P : Cᵒᵖ ⥤ D) (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)), (∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y) : presheaf.is_sheaf J (J.plus_obj P) := begin rw presheaf.is_sheaf_iff_multiequalizer, intros X S, apply is_iso_of_reflects_iso _ (forget D), rw is_iso_iff_bijective, split, { intros x y h, apply sep P S _ _, intros I, apply_fun (meq.equiv _ _) at h, apply_fun (λ e, e I) at h, convert h, { erw [meq.equiv_apply, ← comp_apply, multiequalizer.lift_ι] }, { erw [meq.equiv_apply, ← comp_apply, multiequalizer.lift_ι] } }, { rintros (x : (multiequalizer (S.index _) : D)), obtain ⟨t,ht⟩ := exists_of_sep P hsep X S (meq.equiv _ _ x), use t, apply_fun meq.equiv _ _, swap, { apply_instance }, rw ← ht, ext i, dsimp, rw [← comp_apply, multiequalizer.lift_ι], refl } end variable (J) /-- `P⁺⁺` is always a sheaf. -/ theorem is_sheaf_plus_plus (P : Cᵒᵖ ⥤ D) : presheaf.is_sheaf J (J.plus_obj (J.plus_obj P)) := begin apply is_sheaf_of_sep, intros X S x y, apply sep, end end plus variables (J) variables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)] [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] /-- The sheafification of a presheaf `P`. *NOTE:* Additional hypotheses are needed to obtain a proof that this is a sheaf! -/ def sheafify (P : Cᵒᵖ ⥤ D) : Cᵒᵖ ⥤ D := J.plus_obj (J.plus_obj P) /-- The canonical map from `P` to its sheafification. -/ def to_sheafify (P : Cᵒᵖ ⥤ D) : P ⟶ J.sheafify P := J.to_plus P ≫ J.plus_map (J.to_plus P) /-- The canonical map on sheafifications induced by a morphism. -/ def sheafify_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : J.sheafify P ⟶ J.sheafify Q := J.plus_map $ J.plus_map η @[simp] lemma sheafify_map_id (P : Cᵒᵖ ⥤ D) : J.sheafify_map (𝟙 P) = 𝟙 (J.sheafify P) := by { dsimp [sheafify_map, sheafify], simp } @[simp] lemma sheafify_map_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) : J.sheafify_map (η ≫ γ) = J.sheafify_map η ≫ J.sheafify_map γ := by { dsimp [sheafify_map, sheafify], simp } @[simp, reassoc] lemma to_sheafify_naturality {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : η ≫ J.to_sheafify _ = J.to_sheafify _ ≫ J.sheafify_map η := by { dsimp [sheafify_map, sheafify, to_sheafify], simp } variable (D) /-- The sheafification of a presheaf `P`, as a functor. *NOTE:* Additional hypotheses are needed to obtain a proof that this is a sheaf! -/ def sheafification : (Cᵒᵖ ⥤ D) ⥤ Cᵒᵖ ⥤ D := (J.plus_functor D ⋙ J.plus_functor D) @[simp] lemma sheafification_obj (P : Cᵒᵖ ⥤ D) : (J.sheafification D).obj P = J.sheafify P := rfl @[simp] lemma sheafification_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : (J.sheafification D).map η = J.sheafify_map η := rfl /-- The canonical map from `P` to its sheafification, as a natural transformation. *Note:* We only show this is a sheaf under additional hypotheses on `D`. -/ def to_sheafification : 𝟭 _ ⟶ sheafification J D := J.to_plus_nat_trans D ≫ whisker_right (J.to_plus_nat_trans D) (J.plus_functor D) @[simp] lemma to_sheafification_app (P : Cᵒᵖ ⥤ D) : (J.to_sheafification D).app P = J.to_sheafify P := rfl variable {D} lemma is_iso_to_sheafify {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) : is_iso (J.to_sheafify P) := begin dsimp [to_sheafify], haveI : is_iso (J.to_plus P) := by { apply is_iso_to_plus_of_is_sheaf J P hP }, haveI : is_iso ((J.plus_functor D).map (J.to_plus P)) := by { apply functor.map_is_iso }, exact @is_iso.comp_is_iso _ _ _ _ _ (J.to_plus P) ((J.plus_functor D).map (J.to_plus P)) _ _, end /-- If `P` is a sheaf, then `P` is isomorphic to `J.sheafify P`. -/ def iso_sheafify {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) : P ≅ J.sheafify P := by letI := is_iso_to_sheafify J hP; exactI as_iso (J.to_sheafify P) @[simp] lemma iso_sheafify_hom {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) : (J.iso_sheafify hP).hom = J.to_sheafify P := rfl /-- Given a sheaf `Q` and a morphism `P ⟶ Q`, construct a morphism from `J.sheafifcation P` to `Q`. -/ def sheafify_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) : J.sheafify P ⟶ Q := J.plus_lift (J.plus_lift η hQ) hQ @[simp, reassoc] lemma to_sheafify_sheafify_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) : J.to_sheafify P ≫ sheafify_lift J η hQ = η := by { dsimp only [sheafify_lift, to_sheafify], simp } lemma sheafify_lift_unique {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) (γ : J.sheafify P ⟶ Q) : J.to_sheafify P ≫ γ = η → γ = sheafify_lift J η hQ := begin intros h, apply plus_lift_unique, apply plus_lift_unique, rw [← category.assoc, ← plus_map_to_plus], exact h, end @[simp] lemma iso_sheafify_inv {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) : (J.iso_sheafify hP).inv = J.sheafify_lift (𝟙 _) hP := begin apply J.sheafify_lift_unique, simp [iso.comp_inv_eq], end lemma sheafify_hom_ext {P Q : Cᵒᵖ ⥤ D} (η γ : J.sheafify P ⟶ Q) (hQ : presheaf.is_sheaf J Q) (h : J.to_sheafify P ≫ η = J.to_sheafify P ≫ γ) : η = γ := begin apply J.plus_hom_ext _ _ hQ, apply J.plus_hom_ext _ _ hQ, rw [← category.assoc, ← category.assoc, ← plus_map_to_plus], exact h, end @[simp, reassoc] lemma sheafify_map_sheafify_lift {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) (hR : presheaf.is_sheaf J R) : J.sheafify_map η ≫ J.sheafify_lift γ hR = J.sheafify_lift (η ≫ γ) hR := begin apply J.sheafify_lift_unique, rw [← category.assoc, ← J.to_sheafify_naturality, category.assoc, to_sheafify_sheafify_lift], end end grothendieck_topology variables (J) variables [concrete_category.{max v u} D] [preserves_limits (forget D)] [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)] [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)] [reflects_isomorphisms (forget D)] lemma grothendieck_topology.sheafify_is_sheaf (P : Cᵒᵖ ⥤ D) : presheaf.is_sheaf J (J.sheafify P) := grothendieck_topology.plus.is_sheaf_plus_plus _ _ variables (D) /-- The sheafification functor, as a functor taking values in `Sheaf`. -/ @[simps] def presheaf_to_Sheaf : (Cᵒᵖ ⥤ D) ⥤ Sheaf J D := { obj := λ P, ⟨J.sheafify P, J.sheafify_is_sheaf P⟩, map := λ P Q η, ⟨J.sheafify_map η⟩, map_id' := λ P, Sheaf.hom.ext _ _ $ J.sheafify_map_id _, map_comp' := λ P Q R f g, Sheaf.hom.ext _ _ $ J.sheafify_map_comp _ _ } instance presheaf_to_Sheaf_preserves_zero_morphisms [preadditive D] : (presheaf_to_Sheaf J D).preserves_zero_morphisms := { map_zero' := λ F G, by { ext, erw [colimit.ι_map, comp_zero, J.plus_map_zero, J.diagram_nat_trans_zero, zero_comp] } } /-- The sheafification functor is left adjoint to the forgetful functor. -/ @[simps unit_app counit_app_val] def sheafification_adjunction : presheaf_to_Sheaf J D ⊣ Sheaf_to_presheaf J D := adjunction.mk_of_hom_equiv { hom_equiv := λ P Q, { to_fun := λ e, J.to_sheafify P ≫ e.val, inv_fun := λ e, ⟨J.sheafify_lift e Q.2⟩, left_inv := λ e, Sheaf.hom.ext _ _ $ (J.sheafify_lift_unique _ _ _ rfl).symm, right_inv := λ e, J.to_sheafify_sheafify_lift _ _ }, hom_equiv_naturality_left_symm' := begin intros P Q R η γ, ext1, dsimp, symmetry, apply J.sheafify_map_sheafify_lift, end, hom_equiv_naturality_right' := λ P Q R η γ, by { dsimp, rw category.assoc } } instance Sheaf_to_presheaf_is_right_adjoint : is_right_adjoint (Sheaf_to_presheaf J D) := ⟨_, sheafification_adjunction J D⟩ instance presheaf_mono_of_mono {F G : Sheaf J D} (f : F ⟶ G) [mono f] : mono f.1 := (Sheaf_to_presheaf J D).map_mono _ lemma Sheaf.hom.mono_iff_presheaf_mono {F G : Sheaf J D} (f : F ⟶ G) : mono f ↔ mono f.1 := ⟨λ m, by { resetI, apply_instance }, λ m, by { resetI, exact Sheaf.hom.mono_of_presheaf_mono J D f }⟩ variables {J D} /-- A sheaf `P` is isomorphic to its own sheafification. -/ @[simps] def sheafification_iso (P : Sheaf J D) : P ≅ (presheaf_to_Sheaf J D).obj P.val := { hom := ⟨(J.iso_sheafify P.2).hom⟩, inv := ⟨(J.iso_sheafify P.2).inv⟩, hom_inv_id' := by { ext1, apply (J.iso_sheafify P.2).hom_inv_id }, inv_hom_id' := by { ext1, apply (J.iso_sheafify P.2).inv_hom_id } } instance is_iso_sheafification_adjunction_counit (P : Sheaf J D) : is_iso ((sheafification_adjunction J D).counit.app P) := is_iso_of_fully_faithful (Sheaf_to_presheaf J D) _ instance sheafification_reflective : is_iso (sheafification_adjunction J D).counit := nat_iso.is_iso_of_is_iso_app _ end category_theory
52181bde5b43f8f63c38296ad54f74a6ac9041df
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab.lean
36a40ec76bd2a7159e6c06f38a7176e9e05231a1
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
1,313
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.Elab.Import import Lean.Elab.Exception import Lean.Elab.Config import Lean.Elab.Command import Lean.Elab.Term import Lean.Elab.App import Lean.Elab.Binders import Lean.Elab.LetRec import Lean.Elab.Frontend import Lean.Elab.BuiltinNotation import Lean.Elab.Declaration import Lean.Elab.Tactic import Lean.Elab.Match -- HACK: must come after `Match` because builtin elaborators (for `match` in this case) do not take priorities import Lean.Elab.Quotation import Lean.Elab.Syntax import Lean.Elab.Do import Lean.Elab.StructInst import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.Print import Lean.Elab.MutualDef import Lean.Elab.AuxDef import Lean.Elab.PreDefinition import Lean.Elab.Deriving import Lean.Elab.DeclarationRange import Lean.Elab.Extra import Lean.Elab.GenInjective import Lean.Elab.BuiltinTerm import Lean.Elab.Arg import Lean.Elab.PatternVar import Lean.Elab.ElabRules import Lean.Elab.Macro import Lean.Elab.Notation import Lean.Elab.Mixfix import Lean.Elab.MacroRules import Lean.Elab.BuiltinCommand import Lean.Elab.RecAppSyntax import Lean.Elab.Eval import Lean.Elab.Calc import Lean.Elab.InheritDoc
00d7cb03a78a95173d1c6c3134a907fa744bd0da
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/limits/constructions/limits_of_products_and_equalizers.lean
ec394cf1ba6b1622fe4a01b4b6daa653f4a0d85c
[ "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
13,121
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.finite_products import category_theory.limits.preserves.shapes.products import category_theory.limits.preserves.shapes.equalizers /-! # Constructing limits from products and equalizers. If a category has all products, and all equalizers, then it has all limits. Similarly, if it has all finite products, and all equalizers, then it has all finite limits. If a functor preserves all products and equalizers, then it preserves all limits. Similarly, if it preserves all finite products and equalizers, then it preserves all finite limits. # TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ open category_theory open opposite namespace category_theory.limits universes v u u₂ variables {C : Type u} [category.{v} C] variables {J : Type v} [small_category J] -- We hide the "implementation details" inside a namespace namespace has_limit_of_has_products_of_has_equalizers variables {F : J ⥤ C} {c₁ : fan F.obj} {c₂ : fan (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2)} (s t : c₁.X ⟶ c₂.X) (hs : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), s ≫ c₂.π.app f = c₁.π.app f.1.1 ≫ F.map f.2) (ht : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), t ≫ c₂.π.app f = c₁.π.app f.1.2) (i : fork s t) include hs ht /-- (Implementation) Given the appropriate product and equalizer cones, build the cone for `F` which is limiting if the given cones are also. -/ @[simps] def build_limit : cone F := { X := i.X, π := { app := λ j, i.ι ≫ c₁.π.app _, naturality' := λ j₁ j₂ f, begin dsimp, rw [category.id_comp, category.assoc, ← hs ⟨⟨_, _⟩, f⟩, i.condition_assoc, ht], end} } variable {i} /-- (Implementation) Show the cone constructed in `build_limit` is limiting, provided the cones used in its construction are. -/ def build_is_limit (t₁ : is_limit c₁) (t₂ : is_limit c₂) (hi : is_limit i) : is_limit (build_limit s t hs ht i) := { lift := λ q, begin refine hi.lift (fork.of_ι _ _), { refine t₁.lift (fan.mk _ (λ j, _)), apply q.π.app j }, { apply t₂.hom_ext, simp [hs, ht] }, end, uniq' := λ q m w, hi.hom_ext (i.equalizer_ext (t₁.hom_ext (by simpa using w))) } end has_limit_of_has_products_of_has_equalizers open has_limit_of_has_products_of_has_equalizers /-- Given the existence of the appropriate (possibly finite) products and equalizers, we know a limit of `F` exists. (This assumes the existence of all equalizers, which is technically stronger than needed.) -/ lemma has_limit_of_equalizer_and_product (F : J ⥤ C) [has_limit (discrete.functor F.obj)] [has_limit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))] [has_equalizers C] : has_limit F := has_limit.mk { cone := _, is_limit := build_is_limit (pi.lift (λ f, limit.π _ _ ≫ F.map f.2)) (pi.lift (λ f, limit.π _ f.1.2)) (by simp) (by simp) (limit.is_limit _) (limit.is_limit _) (limit.is_limit _) } /-- Any category with products and equalizers has all limits. See https://stacks.math.columbia.edu/tag/002N. -/ lemma limits_from_equalizers_and_products [has_products C] [has_equalizers C] : has_limits C := { has_limits_of_shape := λ J 𝒥, { has_limit := λ F, by exactI has_limit_of_equalizer_and_product F } } /-- Any category with finite products and equalizers has all finite limits. See https://stacks.math.columbia.edu/tag/002O. -/ lemma finite_limits_from_equalizers_and_finite_products [has_finite_products C] [has_equalizers C] : has_finite_limits C := ⟨λ J _ _, { has_limit := λ F, by exactI has_limit_of_equalizer_and_product F }⟩ variables {D : Type u₂} [category.{v} D] noncomputable theory section variables [has_limits_of_shape (discrete J) C] [has_limits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) C] [has_equalizers C] variables (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [preserves_limits_of_shape (discrete J) G] [preserves_limits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) G] /-- If a functor preserves equalizers and the appropriate products, it preserves limits. -/ def preserves_limit_of_preserves_equalizers_and_product : preserves_limits_of_shape J G := { preserves_limit := λ K, begin let P := ∏ K.obj, let Q := ∏ (λ (f : (Σ (p : J × J), p.fst ⟶ p.snd)), K.obj f.1.2), let s : P ⟶ Q := pi.lift (λ f, limit.π _ _ ≫ K.map f.2), let t : P ⟶ Q := pi.lift (λ f, limit.π _ f.1.2), let I := equalizer s t, let i : I ⟶ P := equalizer.ι s t, apply preserves_limit_of_preserves_limit_cone (build_is_limit s t (by simp) (by simp) (limit.is_limit _) (limit.is_limit _) (limit.is_limit _)), refine is_limit.of_iso_limit (build_is_limit _ _ _ _ _ _ _) _, { exact fan.mk _ (λ j, G.map (pi.π _ j)) }, { exact fan.mk (G.obj Q) (λ f, G.map (pi.π _ f)) }, { apply G.map s }, { apply G.map t }, { intro f, dsimp, simp only [←G.map_comp, limit.lift_π, fan.mk_π_app] }, { intro f, dsimp, simp only [←G.map_comp, limit.lift_π, fan.mk_π_app] }, { apply fork.of_ι (G.map i) _, simp only [← G.map_comp, equalizer.condition] }, { apply is_limit_of_has_product_of_preserves_limit }, { apply is_limit_of_has_product_of_preserves_limit }, { apply is_limit_fork_map_of_is_limit, apply equalizer_is_equalizer }, refine cones.ext (iso.refl _) _, intro j, dsimp, simp, -- See note [dsimp, simp]. end } end /-- If G preserves equalizers and finite products, it preserves finite limits. -/ def preserves_finite_limits_of_preserves_equalizers_and_finite_products [has_equalizers C] [has_finite_products C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [∀ J [fintype J], preserves_limits_of_shape (discrete J) G] (J : Type v) [small_category J] [fin_category J] : preserves_limits_of_shape J G := preserves_limit_of_preserves_equalizers_and_product G /-- If G preserves equalizers and products, it preserves all limits. -/ def preserves_limits_of_preserves_equalizers_and_products [has_equalizers C] [has_products C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [∀ J, preserves_limits_of_shape (discrete J) G] : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, by exactI preserves_limit_of_preserves_equalizers_and_product G } /-! We now dualize the above constructions, resorting to copy-paste. -/ -- We hide the "implementation details" inside a namespace namespace has_colimit_of_has_coproducts_of_has_coequalizers variables {F : J ⥤ C} {c₁ : cofan (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1)} {c₂ : cofan F.obj} (s t : c₁.X ⟶ c₂.X) (hs : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), c₁.ι.app f ≫ s = F.map f.2 ≫ c₂.ι.app f.1.2) (ht : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), c₁.ι.app f ≫ t = c₂.ι.app f.1.1) (i : cofork s t) include hs ht /-- (Implementation) Given the appropriate coproduct and coequalizer cocones, build the cocone for `F` which is colimiting if the given cocones are also. -/ @[simps] def build_colimit : cocone F := { X := i.X, ι := { app := λ j, c₂.ι.app _ ≫ i.π, naturality' := λ j₁ j₂ f, begin dsimp, rw [category.comp_id, ←reassoc_of (hs ⟨⟨_, _⟩, f⟩), i.condition, ←category.assoc, ht], end} } variable {i} /-- (Implementation) Show the cocone constructed in `build_colimit` is colimiting, provided the cocones used in its construction are. -/ def build_is_colimit (t₁ : is_colimit c₁) (t₂ : is_colimit c₂) (hi : is_colimit i) : is_colimit (build_colimit s t hs ht i) := { desc := λ q, begin refine hi.desc (cofork.of_π _ _), { refine t₂.desc (cofan.mk _ (λ j, _)), apply q.ι.app j }, { apply t₁.hom_ext, simp [reassoc_of hs, reassoc_of ht] }, end, uniq' := λ q m w, hi.hom_ext (i.coequalizer_ext (t₂.hom_ext (by simpa using w))) } end has_colimit_of_has_coproducts_of_has_coequalizers open has_colimit_of_has_coproducts_of_has_coequalizers /-- Given the existence of the appropriate (possibly finite) coproducts and coequalizers, we know a colimit of `F` exists. (This assumes the existence of all coequalizers, which is technically stronger than needed.) -/ lemma has_colimit_of_coequalizer_and_coproduct (F : J ⥤ C) [has_colimit (discrete.functor F.obj)] [has_colimit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1))] [has_coequalizers C] : has_colimit F := has_colimit.mk { cocone := _, is_colimit := build_is_colimit (sigma.desc (λ f, F.map f.2 ≫ colimit.ι (discrete.functor F.obj) f.1.2)) (sigma.desc (λ f, colimit.ι (discrete.functor F.obj) f.1.1)) (by simp) (by simp) (colimit.is_colimit _) (colimit.is_colimit _) (colimit.is_colimit _) } /-- Any category with coproducts and coequalizers has all colimits. See https://stacks.math.columbia.edu/tag/002P. -/ lemma colimits_from_coequalizers_and_coproducts [has_coproducts C] [has_coequalizers C] : has_colimits C := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI has_colimit_of_coequalizer_and_coproduct F } } /-- Any category with finite coproducts and coequalizers has all finite colimits. See https://stacks.math.columbia.edu/tag/002Q. -/ lemma finite_colimits_from_coequalizers_and_finite_coproducts [has_finite_coproducts C] [has_coequalizers C] : has_finite_colimits C := ⟨λ J _ _, { has_colimit := λ F, by exactI has_colimit_of_coequalizer_and_coproduct F }⟩ noncomputable theory section variables [has_colimits_of_shape (discrete J) C] [has_colimits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) C] [has_coequalizers C] variables (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [preserves_colimits_of_shape (discrete J) G] [preserves_colimits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) G] /-- If a functor preserves coequalizers and the appropriate coproducts, it preserves colimits. -/ def preserves_colimit_of_preserves_coequalizers_and_coproduct : preserves_colimits_of_shape J G := { preserves_colimit := λ K, begin let P := ∐ K.obj, let Q := ∐ (λ (f : (Σ (p : J × J), p.fst ⟶ p.snd)), K.obj f.1.1), let s : Q ⟶ P := sigma.desc (λ f, K.map f.2 ≫ colimit.ι (discrete.functor K.obj) _), let t : Q ⟶ P := sigma.desc (λ f, colimit.ι (discrete.functor K.obj) f.1.1), let I := coequalizer s t, let i : P ⟶ I := coequalizer.π s t, apply preserves_colimit_of_preserves_colimit_cocone (build_is_colimit s t (by simp) (by simp) (colimit.is_colimit _) (colimit.is_colimit _) (colimit.is_colimit _)), refine is_colimit.of_iso_colimit (build_is_colimit _ _ _ _ _ _ _) _, { exact cofan.mk (G.obj Q) (λ j, G.map (sigma.ι _ j)) }, { exact cofan.mk _ (λ f, G.map (sigma.ι _ f)) }, { apply G.map s }, { apply G.map t }, { intro f, dsimp, simp only [←G.map_comp, colimit.ι_desc, cofan.mk_ι_app] }, { intro f, dsimp, simp only [←G.map_comp, colimit.ι_desc, cofan.mk_ι_app] }, { apply cofork.of_π (G.map i) _, simp only [← G.map_comp, coequalizer.condition] }, { apply is_colimit_of_has_coproduct_of_preserves_colimit }, { apply is_colimit_of_has_coproduct_of_preserves_colimit }, { apply is_colimit_cofork_map_of_is_colimit, apply coequalizer_is_coequalizer }, refine cocones.ext (iso.refl _) _, intro j, dsimp, simp, -- See note [dsimp, simp]. end } end /-- If G preserves coequalizers and finite coproducts, it preserves finite colimits. -/ def preserves_finite_colimits_of_preserves_coequalizers_and_finite_coproducts [has_coequalizers C] [has_finite_coproducts C] (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [∀ J [fintype J], preserves_colimits_of_shape (discrete J) G] (J : Type v) [small_category J] [fin_category J] : preserves_colimits_of_shape J G := preserves_colimit_of_preserves_coequalizers_and_coproduct G /-- If G preserves coequalizers and coproducts, it preserves all colimits. -/ def preserves_colimits_of_preserves_coequalizers_and_coproducts [has_coequalizers C] [has_coproducts C] (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [∀ J, preserves_colimits_of_shape (discrete J) G] : preserves_colimits G := { preserves_colimits_of_shape := λ J 𝒥, by exactI preserves_colimit_of_preserves_coequalizers_and_coproduct G } end category_theory.limits
a52f55d834e5e8f4365fa2873e5cd6bcdefbcf64
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/hott/types/sigma.hlean
8bdaa1b11b8eb4bc8b3b60e51ece7e0000418a48
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,762
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: types.sigma Author: Floris van Doorn Ported from Coq HoTT Theorems about sigma-types (dependent sums) -/ import types.prod open eq sigma sigma.ops equiv is_equiv namespace sigma local infixr ∘ := function.compose --remove variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {u v w : Σa, B a} -- sigma.eta is already used for the eta rule for strict equality protected definition eta : Π (u : Σa, B a), ⟨u.1 , u.2⟩ = u | eta ⟨u₁, u₂⟩ := idp definition eta2 : Π (u : Σa b, C a b), ⟨u.1, u.2.1, u.2.2⟩ = u | eta2 ⟨u₁, u₂, u₃⟩ := idp definition eta3 : Π (u : Σa b c, D a b c), ⟨u.1, u.2.1, u.2.2.1, u.2.2.2⟩ = u | eta3 ⟨u₁, u₂, u₃, u₄⟩ := idp definition dpair_eq_dpair (p : a = a') (q : p ▹ b = b') : ⟨a, b⟩ = ⟨a', b'⟩ := by cases p; cases q; apply idp /- In Coq they often have to give u and v explicitly -/ definition sigma_eq (p : u.1 = v.1) (q : p ▹ u.2 = v.2) : u = v := by cases u; cases v; apply (dpair_eq_dpair p q) /- Projections of paths from a total space -/ definition eq_pr1 (p : u = v) : u.1 = v.1 := ap pr1 p postfix `..1`:(max+1) := eq_pr1 definition eq_pr2 (p : u = v) : p..1 ▹ u.2 = v.2 := by cases p; apply idp --Coq uses the following proof, which only computes if u,v are dpairs AND p is idp --(transport_compose B dpr1 p u.2)⁻¹ ⬝ apD dpr2 p postfix `..2`:(max+1) := eq_pr2 private definition dpair_sigma_eq (p : u.1 = v.1) (q : p ▹ u.2 = v.2) : ⟨(sigma_eq p q)..1, (sigma_eq p q)..2⟩ = ⟨p, q⟩ := by cases u; cases v; cases p; cases q; apply idp definition sigma_eq_pr1 (p : u.1 = v.1) (q : p ▹ u.2 = v.2) : (sigma_eq p q)..1 = p := (dpair_sigma_eq p q)..1 definition sigma_eq_pr2 (p : u.1 = v.1) (q : p ▹ u.2 = v.2) : sigma_eq_pr1 p q ▹ (sigma_eq p q)..2 = q := (dpair_sigma_eq p q)..2 definition sigma_eq_eta (p : u = v) : sigma_eq (p..1) (p..2) = p := by cases p; cases u; apply idp definition tr_pr1_sigma_eq {B' : A → Type} (p : u.1 = v.1) (q : p ▹ u.2 = v.2) : transport (λx, B' x.1) (sigma_eq p q) = transport B' p := by cases u; cases v; cases p; cases q; apply idp /- the uncurried version of sigma_eq. We will prove that this is an equivalence -/ definition sigma_eq_uncurried : Π (pq : Σ(p : pr1 u = pr1 v), p ▹ (pr2 u) = pr2 v), u = v | sigma_eq_uncurried ⟨pq₁, pq₂⟩ := sigma_eq pq₁ pq₂ definition dpair_sigma_eq_uncurried : Π (pq : Σ(p : u.1 = v.1), p ▹ u.2 = v.2), sigma.mk (sigma_eq_uncurried pq)..1 (sigma_eq_uncurried pq)..2 = pq | dpair_sigma_eq_uncurried ⟨pq₁, pq₂⟩ := dpair_sigma_eq pq₁ pq₂ definition sigma_eq_pr1_uncurried (pq : Σ(p : u.1 = v.1), p ▹ u.2 = v.2) : (sigma_eq_uncurried pq)..1 = pq.1 := (dpair_sigma_eq_uncurried pq)..1 definition sigma_eq_pr2_uncurried (pq : Σ(p : u.1 = v.1), p ▹ u.2 = v.2) : (sigma_eq_pr1_uncurried pq) ▹ (sigma_eq_uncurried pq)..2 = pq.2 := (dpair_sigma_eq_uncurried pq)..2 definition sigma_eq_eta_uncurried (p : u = v) : sigma_eq_uncurried (sigma.mk p..1 p..2) = p := sigma_eq_eta p definition tr_sigma_eq_pr1_uncurried {B' : A → Type} (pq : Σ(p : u.1 = v.1), p ▹ u.2 = v.2) : transport (λx, B' x.1) (@sigma_eq_uncurried A B u v pq) = transport B' pq.1 := destruct pq tr_pr1_sigma_eq definition is_equiv_sigma_eq [instance] (u v : Σa, B a) : is_equiv (@sigma_eq_uncurried A B u v) := adjointify sigma_eq_uncurried (λp, ⟨p..1, p..2⟩) sigma_eq_eta_uncurried dpair_sigma_eq_uncurried definition equiv_sigma_eq (u v : Σa, B a) : (Σ(p : u.1 = v.1), p ▹ u.2 = v.2) ≃ (u = v) := equiv.mk sigma_eq_uncurried !is_equiv_sigma_eq definition dpair_eq_dpair_con (p1 : a = a' ) (q1 : p1 ▹ b = b' ) (p2 : a' = a'') (q2 : p2 ▹ b' = b'') : dpair_eq_dpair (p1 ⬝ p2) (tr_con B p1 p2 b ⬝ ap (transport B p2) q1 ⬝ q2) = dpair_eq_dpair p1 q1 ⬝ dpair_eq_dpair p2 q2 := by cases p1; cases p2; cases q1; cases q2; apply idp definition sigma_eq_con (p1 : u.1 = v.1) (q1 : p1 ▹ u.2 = v.2) (p2 : v.1 = w.1) (q2 : p2 ▹ v.2 = w.2) : sigma_eq (p1 ⬝ p2) (tr_con B p1 p2 u.2 ⬝ ap (transport B p2) q1 ⬝ q2) = sigma_eq p1 q1 ⬝ sigma_eq p2 q2 := by cases u; cases v; cases w; apply dpair_eq_dpair_con local attribute dpair_eq_dpair [reducible] definition dpair_eq_dpair_con_idp (p : a = a') (q : p ▹ b = b') : dpair_eq_dpair p q = dpair_eq_dpair p idp ⬝ dpair_eq_dpair idp q := by cases p; cases q; apply idp /- eq_pr1 commutes with the groupoid structure. -/ definition eq_pr1_idp (u : Σa, B a) : (refl u) ..1 = refl (u.1) := idp definition eq_pr1_con (p : u = v) (q : v = w) : (p ⬝ q) ..1 = (p..1) ⬝ (q..1) := !ap_con definition eq_pr1_inv (p : u = v) : p⁻¹ ..1 = (p..1)⁻¹ := !ap_inv /- Applying dpair to one argument is the same as dpair_eq_dpair with reflexivity in the first place. -/ definition ap_dpair (q : b₁ = b₂) : ap (sigma.mk a) q = dpair_eq_dpair idp q := by cases q; apply idp /- Dependent transport is the same as transport along a sigma_eq. -/ definition transportD_eq_transport (p : a = a') (c : C a b) : p ▹D c = transport (λu, C (u.1) (u.2)) (dpair_eq_dpair p idp) c := by cases p; apply idp definition sigma_eq_eq_sigma_eq {p1 q1 : a = a'} {p2 : p1 ▹ b = b'} {q2 : q1 ▹ b = b'} (r : p1 = q1) (s : r ▹ p2 = q2) : sigma_eq p1 p2 = sigma_eq q1 q2 := by cases r; cases s; apply idp /- A path between paths in a total space is commonly shown component wise. -/ definition sigma_eq2 {p q : u = v} (r : p..1 = q..1) (s : r ▹ p..2 = q..2) : p = q := begin reverts [q, r, s], cases p, cases u with [u1, u2], intros [q, r, s], apply concat, rotate 1, apply sigma_eq_eta, apply (sigma_eq_eq_sigma_eq r s) end /- In Coq they often have to give u and v explicitly when using the following definition -/ definition sigma_eq2_uncurried {p q : u = v} (rs : Σ(r : p..1 = q..1), transport (λx, transport B x u.2 = v.2) r p..2 = q..2) : p = q := destruct rs sigma_eq2 /- Transport -/ /- The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD]. In particular, this indicates why `transport` alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? -/ definition transport_eq (p : a = a') (bc : Σ(b : B a), C a b) : p ▹ bc = ⟨p ▹ bc.1, p ▹D bc.2⟩ := by cases p; cases bc; apply idp /- The special case when the second variable doesn't depend on the first is simpler. -/ definition tr_eq_nondep {B : Type} {C : A → B → Type} (p : a = a') (bc : Σ(b : B), C a b) : p ▹ bc = ⟨bc.1, p ▹ bc.2⟩ := by cases p; cases bc; apply idp /- Or if the second variable contains a first component that doesn't depend on the first. -/ definition tr_eq2_nondep {C : A → Type} {D : Π a:A, B a → C a → Type} (p : a = a') (bcd : Σ(b : B a) (c : C a), D a b c) : p ▹ bcd = ⟨p ▹ bcd.1, p ▹ bcd.2.1, p ▹D2 bcd.2.2⟩ := begin cases p, cases bcd with [b, cd], cases cd, apply idp end /- Functorial action -/ variables (f : A → A') (g : Πa, B a → B' (f a)) definition sigma_functor (u : Σa, B a) : Σa', B' a' := ⟨f u.1, g u.1 u.2⟩ /- Equivalences -/ definition is_equiv_sigma_functor [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : is_equiv (sigma_functor f g) := adjointify (sigma_functor f g) (sigma_functor f⁻¹ (λ(a' : A') (b' : B' a'), ((g (f⁻¹ a'))⁻¹ (transport B' (retr f a')⁻¹ b')))) begin intro u', cases u' with [a', b'], apply (sigma_eq (retr f a')), -- rewrite retr, -- end -- "rewrite retr (g (f⁻¹ a'))" apply concat, apply (ap (λx, (transport B' (retr f a') x))), apply (retr (g (f⁻¹ a'))), show retr f a' ▹ ((retr f a')⁻¹ ▹ b') = b', from tr_inv_tr B' (retr f a') b' end begin intro u, cases u with [a, b], apply (sigma_eq (sect f a)), show transport B (sect f a) ((g (f⁻¹ (f a)))⁻¹ (transport B' (retr f (f a))⁻¹ (g a b))) = b, from calc transport B (sect f a) ((g (f⁻¹ (f a)))⁻¹ (transport B' (retr f (f a))⁻¹ (g a b))) = (g a)⁻¹ (transport (B' ∘ f) (sect f a) (transport B' (retr f (f a))⁻¹ (g a b))) : by rewrite (fn_tr_eq_tr_fn (sect f a) (λ a, (g a)⁻¹)) ... = (g a)⁻¹ (transport B' (ap f (sect f a)) (transport B' (retr f (f a))⁻¹ (g a b))) : ap (g a)⁻¹ !transport_compose ... = (g a)⁻¹ (transport B' (ap f (sect f a)) (transport B' (ap f (sect f a))⁻¹ (g a b))) : ap (λ x, (g a)⁻¹ (transport B' (ap f (sect f a)) (transport B' x⁻¹ (g a b)))) (adj f a) ... = (g a)⁻¹ (g a b) : {!tr_inv_tr} ... = b : by rewrite (sect (g a) b) end definition sigma_equiv_sigma_of_is_equiv [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : (Σa, B a) ≃ (Σa', B' a') := equiv.mk (sigma_functor f g) !is_equiv_sigma_functor context attribute inv [irreducible] attribute function.compose [irreducible] --this is needed for the following class inference problem definition sigma_equiv_sigma (Hf : A ≃ A') (Hg : Π a, B a ≃ B' (to_fun Hf a)) : (Σa, B a) ≃ (Σa', B' a') := sigma_equiv_sigma_of_is_equiv (to_fun Hf) (λ a, to_fun (Hg a)) end definition sigma_equiv_sigma_id {B' : A → Type} (Hg : Π a, B a ≃ B' a) : (Σa, B a) ≃ Σa, B' a := sigma_equiv_sigma equiv.refl Hg definition ap_sigma_functor_eq_dpair (p : a = a') (q : p ▹ b = b') : ap (sigma.sigma_functor f g) (sigma_eq p q) = sigma_eq (ap f p) ((transport_compose _ f p (g a b))⁻¹ ⬝ (fn_tr_eq_tr_fn p g b)⁻¹ ⬝ ap (g a') q) := by cases p; cases q; apply idp definition ap_sigma_functor_eq (p : u.1 = v.1) (q : p ▹ u.2 = v.2) : ap (sigma.sigma_functor f g) (sigma_eq p q) = sigma_eq (ap f p) ((transport_compose B' f p (g u.1 u.2))⁻¹ ⬝ (fn_tr_eq_tr_fn p g u.2)⁻¹ ⬝ ap (g v.1) q) := by cases u; cases v; apply ap_sigma_functor_eq_dpair /- definition 3.11.9(i): Summing up a contractible family of types does nothing. -/ open is_trunc definition is_equiv_pr1 [instance] (B : A → Type) [H : Π a, is_contr (B a)] : is_equiv (@pr1 A B) := adjointify pr1 (λa, ⟨a, !center⟩) (λa, idp) (λu, sigma_eq idp !contr) definition sigma_equiv_of_is_contr_pr2 [H : Π a, is_contr (B a)] : (Σa, B a) ≃ A := equiv.mk pr1 _ /- definition 3.11.9(ii): Dually, summing up over a contractible type does nothing. -/ definition sigma_equiv_of_is_contr_pr1 (B : A → Type) [H : is_contr A] : (Σa, B a) ≃ B (center A) := equiv.mk _ (adjointify (λu, (contr u.1)⁻¹ ▹ u.2) (λb, ⟨!center, b⟩) (λb, ap (λx, x ▹ b) !hprop_eq_of_is_contr) (λu, sigma_eq !contr !tr_inv_tr)) /- Associativity -/ --this proof is harder than in Coq because we don't have eta definitionally for sigma definition sigma_assoc_equiv (C : (Σa, B a) → Type) : (Σa b, C ⟨a, b⟩) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨⟨av.1, av.2.1⟩, av.2.2⟩) (λuc, ⟨uc.1.1, uc.1.2, !eta⁻¹ ▹ uc.2⟩) begin intro uc; cases uc with [u, c]; cases u; apply idp end begin intro av; cases av with [a, v]; cases v; apply idp end) open prod definition assoc_equiv_prod (C : (A × A') → Type) : (Σa a', C (a,a')) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨(av.1, av.2.1), av.2.2⟩) (λuc, ⟨pr₁ (uc.1), pr₂ (uc.1), !prod.eta⁻¹ ▹ uc.2⟩) proof (λuc, destruct uc (λu, prod.destruct u (λa b c, idp))) qed proof (λav, destruct av (λa v, destruct v (λb c, idp))) qed) /- Symmetry -/ definition comm_equiv_uncurried (C : A × A' → Type) : (Σa a', C (a, a')) ≃ (Σa' a, C (a, a')) := calc (Σa a', C (a, a')) ≃ Σu, C u : assoc_equiv_prod ... ≃ Σv, C (flip v) : sigma_equiv_sigma !prod_comm_equiv (λu, prod.destruct u (λa a', equiv.refl)) ... ≃ (Σa' a, C (a, a')) : assoc_equiv_prod definition sigma_comm_equiv (C : A → A' → Type) : (Σa a', C a a') ≃ (Σa' a, C a a') := comm_equiv_uncurried (λu, C (prod.pr1 u) (prod.pr2 u)) definition equiv_prod (A B : Type) : (Σ(a : A), B) ≃ A × B := equiv.mk _ (adjointify (λs, (s.1, s.2)) (λp, ⟨pr₁ p, pr₂ p⟩) proof (λp, prod.destruct p (λa b, idp)) qed proof (λs, destruct s (λa b, idp)) qed) definition comm_equiv_nondep (A B : Type) : (Σ(a : A), B) ≃ Σ(b : B), A := calc (Σ(a : A), B) ≃ A × B : equiv_prod ... ≃ B × A : prod_comm_equiv ... ≃ Σ(b : B), A : equiv_prod /- ** Universal mapping properties -/ /- *** The positive universal property. -/ section definition is_equiv_sigma_rec [instance] (C : (Σa, B a) → Type) : is_equiv (@sigma.rec _ _ C) := adjointify _ (λ g a b, g ⟨a, b⟩) (λ g, proof eq_of_homotopy (λu, destruct u (λa b, idp)) qed) (λ f, refl f) definition equiv_sigma_rec (C : (Σa, B a) → Type) : (Π(a : A) (b: B a), C ⟨a, b⟩) ≃ (Πxy, C xy) := equiv.mk sigma.rec _ /- *** The negative universal property. -/ protected definition coind_uncurried (fg : Σ(f : Πa, B a), Πa, C a (f a)) (a : A) : Σ(b : B a), C a b := ⟨fg.1 a, fg.2 a⟩ protected definition coind (f : Π a, B a) (g : Π a, C a (f a)) (a : A) : Σ(b : B a), C a b := coind_uncurried ⟨f, g⟩ a --is the instance below dangerous? --in Coq this can be done without function extensionality definition is_equiv_coind [instance] (C : Πa, B a → Type) : is_equiv (@coind_uncurried _ _ C) := adjointify _ (λ h, ⟨λa, (h a).1, λa, (h a).2⟩) (λ h, proof eq_of_homotopy (λu, !eta) qed) (λfg, destruct fg (λ(f : Π (a : A), B a) (g : Π (x : A), C x (f x)), proof idp qed)) definition sigma_pi_equiv_pi_sigma : (Σ(f : Πa, B a), Πa, C a (f a)) ≃ (Πa, Σb, C a b) := equiv.mk coind_uncurried _ end /- ** Subtypes (sigma types whose second components are hprops) -/ /- To prove equality in a subtype, we only need equality of the first component. -/ definition subtype_eq [H : Πa, is_hprop (B a)] (u v : Σa, B a) : u.1 = v.1 → u = v := (sigma_eq_uncurried ∘ (@inv _ _ pr1 (@is_equiv_pr1 _ _ (λp, !is_trunc.is_trunc_eq)))) definition is_equiv_subtype_eq [H : Πa, is_hprop (B a)] (u v : Σa, B a) : is_equiv (subtype_eq u v) := !is_equiv_compose local attribute is_equiv_subtype_eq [instance] definition equiv_subtype [H : Πa, is_hprop (B a)] (u v : Σa, B a) : (u.1 = v.1) ≃ (u = v) := equiv.mk !subtype_eq _ /- truncatedness -/ definition is_trunc_sigma (B : A → Type) (n : trunc_index) [HA : is_trunc n A] [HB : Πa, is_trunc n (B a)] : is_trunc n (Σa, B a) := begin reverts [A, B, HA, HB], apply (trunc_index.rec_on n), intros [A, B, HA, HB], fapply is_trunc.is_trunc_equiv_closed, apply equiv.symm, apply sigma_equiv_of_is_contr_pr1, intros [n, IH, A, B, HA, HB], fapply is_trunc.is_trunc_succ_intro, intros [u, v], fapply is_trunc.is_trunc_equiv_closed, apply equiv_sigma_eq, apply IH, apply is_trunc.is_trunc_eq, intro p, show is_trunc n (p ▹ u .2 = v .2), from is_trunc.is_trunc_eq n (p ▹ u.2) (v.2), end end sigma attribute sigma.is_trunc_sigma [instance] open is_trunc sigma prod /- truncatedness -/ definition prod.is_trunc_prod [instance] (A B : Type) (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B] : is_trunc n (A × B) := is_trunc.is_trunc_equiv_closed n !equiv_prod
dee2c888836eab03987654ad7f76e27fb0828421
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/tests/lean/unused_univ.lean
ef4c7e688c4521a05bad1862b5ed032fb5fd2674
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
272
lean
variable (y : Nat) def f.{u} (x : Nat) : Nat := -- error unused universe parameter 'u' x universes u def f.{v, w} (α : Type v) (a : α) : α := -- error unused universe parameter 'w' a axiom f.{w} (α : Type u) (a : α) : α -- error unused universe parameter 'w'
b3168f935ad78ebc1b84bcf79fc21a64e770c124
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Init/Data/String/Basic.lean
16a28bc643a8e886e143c6ea9bba86c40b40b5fe
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
16,256
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.List.Basic import Init.Data.Char.Basic import Init.Data.Option.Basic universes u def List.asString (s : List Char) : String := ⟨s⟩ namespace String instance : LT String := ⟨fun s₁ s₂ => s₁.data < s₂.data⟩ @[extern "lean_string_dec_lt"] instance decLt (s₁ s₂ : @& String) : Decidable (s₁ < s₂) := List.hasDecidableLt s₁.data s₂.data @[extern "lean_string_length"] def length : (@& String) → Nat | ⟨s⟩ => s.length /-- The internal implementation uses dynamic arrays and will perform destructive updates if the String is not shared. -/ @[extern "lean_string_push"] def push : String → Char → String | ⟨s⟩, c => ⟨s ++ [c]⟩ /-- The internal implementation uses dynamic arrays and will perform destructive updates if the String is not shared. -/ @[extern "lean_string_append"] def append : String → (@& String) → String | ⟨a⟩, ⟨b⟩ => ⟨a ++ b⟩ /-- O(n) in the runtime, where n is the length of the String -/ def toList (s : String) : List Char := s.data private def utf8GetAux : List Char → Pos → Pos → Char | [], i, p => arbitrary | c::cs, i, p => if i = p then c else utf8GetAux cs (i + csize c) p @[extern "lean_string_utf8_get"] def get : (@& String) → (@& Pos) → Char | ⟨s⟩, p => utf8GetAux s 0 p def getOp (self : String) (idx : Pos) : Char := self.get idx private def utf8SetAux (c' : Char) : List Char → Pos → Pos → List Char | [], i, p => [] | c::cs, i, p => if i = p then (c'::cs) else c::(utf8SetAux c' cs (i + csize c) p) @[extern "lean_string_utf8_set"] def set : String → (@& Pos) → Char → String | ⟨s⟩, i, c => ⟨utf8SetAux c s 0 i⟩ def modify (s : String) (i : Pos) (f : Char → Char) : String := s.set i <| f <| s.get i @[extern "lean_string_utf8_next"] def next (s : @& String) (p : @& Pos) : Pos := let c := get s p p + csize c private def utf8PrevAux : List Char → Pos → Pos → Pos | [], i, p => 0 | c::cs, i, p => let cz := csize c let i' := i + cz if i' = p then i else utf8PrevAux cs i' p @[extern "lean_string_utf8_prev"] def prev : (@& String) → (@& Pos) → Pos | ⟨s⟩, p => if p = 0 then 0 else utf8PrevAux s 0 p def front (s : String) : Char := get s 0 def back (s : String) : Char := get s (prev s (bsize s)) @[extern "lean_string_utf8_at_end"] def atEnd : (@& String) → (@& Pos) → Bool | s, p => p ≥ utf8ByteSize s /- TODO: remove `partial` keywords after we restore the tactic framework and wellfounded recursion support -/ partial def posOfAux (s : String) (c : Char) (stopPos : Pos) (pos : Pos) : Pos := if pos == stopPos then pos else if s.get pos == c then pos else posOfAux s c stopPos (s.next pos) @[inline] def posOf (s : String) (c : Char) : Pos := posOfAux s c s.bsize 0 partial def revPosOfAux (s : String) (c : Char) (pos : Pos) : Option Pos := if s.get pos == c then some pos else if pos == 0 then none else revPosOfAux s c (s.prev pos) def revPosOf (s : String) (c : Char) : Option Pos := if s.bsize == 0 then none else revPosOfAux s c (s.prev s.bsize) private def utf8ExtractAux₂ : List Char → Pos → Pos → List Char | [], _, _ => [] | c::cs, i, e => if i = e then [] else c :: utf8ExtractAux₂ cs (i + csize c) e private def utf8ExtractAux₁ : List Char → Pos → Pos → Pos → List Char | [], _, _, _ => [] | s@(c::cs), i, b, e => if i = b then utf8ExtractAux₂ s i e else utf8ExtractAux₁ cs (i + csize c) b e @[extern "lean_string_utf8_extract"] def extract : (@& String) → (@& Pos) → (@& Pos) → String | ⟨s⟩, b, e => if b ≥ e then ⟨[]⟩ else ⟨utf8ExtractAux₁ s 0 b e⟩ @[specialize] partial def splitAux (s : String) (p : Char → Bool) (b : Pos) (i : Pos) (r : List String) : List String := if s.atEnd i then let r := (s.extract b i)::r r.reverse else if p (s.get i) then let i := s.next i splitAux s p i i (s.extract b (i-1)::r) else splitAux s p b (s.next i) r @[specialize] def split (s : String) (p : Char → Bool) : List String := splitAux s p 0 0 [] partial def splitOnAux (s sep : String) (b : Pos) (i : Pos) (j : Pos) (r : List String) : List String := if s.atEnd i then let r := if sep.atEnd j then ""::(s.extract b (i-j))::r else (s.extract b i)::r r.reverse else if s.get i == sep.get j then let i := s.next i let j := sep.next j if sep.atEnd j then splitOnAux s sep i i 0 (s.extract b (i-j)::r) else splitOnAux s sep b i j r else splitOnAux s sep b (s.next i) 0 r def splitOn (s : String) (sep : String := " ") : List String := if sep == "" then [s] else splitOnAux s sep 0 0 0 [] instance : Inhabited String := ⟨""⟩ instance : Append String := ⟨String.append⟩ def str : String → Char → String := push def pushn (s : String) (c : Char) (n : Nat) : String := n.repeat (fun s => s.push c) s def isEmpty (s : String) : Bool := s.bsize == 0 def join (l : List String) : String := l.foldl (fun r s => r ++ s) "" def singleton (c : Char) : String := "".push c def intercalate (s : String) (ss : List String) : String := (List.intercalate s.toList (ss.map toList)).asString structure Iterator where s : String i : Pos def mkIterator (s : String) : Iterator := ⟨s, 0⟩ namespace Iterator def toString : Iterator → String | ⟨s, _⟩ => s def remainingBytes : Iterator → Nat | ⟨s, i⟩ => s.bsize - i def pos : Iterator → Pos | ⟨s, i⟩ => i def curr : Iterator → Char | ⟨s, i⟩ => get s i def next : Iterator → Iterator | ⟨s, i⟩ => ⟨s, s.next i⟩ def prev : Iterator → Iterator | ⟨s, i⟩ => ⟨s, s.prev i⟩ def hasNext : Iterator → Bool | ⟨s, i⟩ => i < utf8ByteSize s def hasPrev : Iterator → Bool | ⟨s, i⟩ => i > 0 def setCurr : Iterator → Char → Iterator | ⟨s, i⟩, c => ⟨s.set i c, i⟩ def toEnd : Iterator → Iterator | ⟨s, _⟩ => ⟨s, s.bsize⟩ def extract : Iterator → Iterator → String | ⟨s₁, b⟩, ⟨s₂, e⟩ => if s₁ ≠ s₂ || b > e then "" else s₁.extract b e def forward : Iterator → Nat → Iterator | it, 0 => it | it, n+1 => forward it.next n def remainingToString : Iterator → String | ⟨s, i⟩ => s.extract i s.bsize /-- `(isPrefixOfRemaining it₁ it₂)` is `true` iff `it₁.remainingToString` is a prefix of `it₂.remainingToString`. -/ def isPrefixOfRemaining : Iterator → Iterator → Bool | ⟨s₁, i₁⟩, ⟨s₂, i₂⟩ => s₁.extract i₁ s₁.bsize = s₂.extract i₂ (i₂ + (s₁.bsize - i₁)) def nextn : Iterator → Nat → Iterator | it, 0 => it | it, i+1 => nextn it.next i def prevn : Iterator → Nat → Iterator | it, 0 => it | it, i+1 => prevn it.prev i end Iterator partial def offsetOfPosAux (s : String) (pos : Pos) (i : Pos) (offset : Nat) : Nat := if i == pos || s.atEnd i then offset else offsetOfPosAux s pos (s.next i) (offset+1) def offsetOfPos (s : String) (pos : Pos) : Nat := offsetOfPosAux s pos 0 0 @[specialize] partial def foldlAux {α : Type u} (f : α → Char → α) (s : String) (stopPos : Pos) (i : Pos) (a : α) : α := let rec loop (i : Pos) (a : α) := if i == stopPos then a else loop (s.next i) (f a (s.get i)) loop i a @[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : String) : α := foldlAux f s s.bsize 0 a @[specialize] partial def foldrAux {α : Type u} (f : Char → α → α) (a : α) (s : String) (stopPos : Pos) (i : Pos) : α := let rec loop (i : Pos) := if i == stopPos then a else f (s.get i) (loop (s.next i)) loop i @[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : String) : α := foldrAux f a s s.bsize 0 @[specialize] partial def anyAux (s : String) (stopPos : Pos) (p : Char → Bool) (i : Pos) : Bool := let rec loop (i : Pos) := if i == stopPos then false else if p (s.get i) then true else loop (s.next i) loop i @[inline] def any (s : String) (p : Char → Bool) : Bool := anyAux s s.bsize p 0 @[inline] def all (s : String) (p : Char → Bool) : Bool := !s.any (fun c => !p c) def contains (s : String) (c : Char) : Bool := s.any (fun a => a == c) @[specialize] partial def mapAux (f : Char → Char) (i : Pos) (s : String) : String := if s.atEnd i then s else let c := f (s.get i) let s := s.set i c mapAux f (s.next i) s @[inline] def map (f : Char → Char) (s : String) : String := mapAux f 0 s def isNat (s : String) : Bool := s.all fun c => c.isDigit def toNat? (s : String) : Option Nat := if s.isNat then some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0 else none /-- Return true iff `p` is a prefix of `s` -/ partial def isPrefixOf (p : String) (s : String) : Bool := let rec loop (i : Pos) := if p.atEnd i then true else let c₁ := p.get i let c₂ := s.get i c₁ == c₂ && loop (s.next i) p.length ≤ s.length && loop 0 end String namespace Substring @[inline] def isEmpty (ss : Substring) : Bool := ss.bsize == 0 @[inline] def toString : Substring → String | ⟨s, b, e⟩ => s.extract b e @[inline] def toIterator : Substring → String.Iterator | ⟨s, b, _⟩ => ⟨s, b⟩ /-- Return the codepoint at the given offset into the substring. -/ @[inline] def get : Substring → String.Pos → Char | ⟨s, b, _⟩, p => s.get (b+p) /-- Given an offset of a codepoint into the substring, return the offset there of the next codepoint. -/ @[inline] private def next : Substring → String.Pos → String.Pos | ⟨s, b, e⟩, p => let absP := b+p if absP = e then p else s.next absP - b /-- Given an offset of a codepoint into the substring, return the offset there of the previous codepoint. -/ @[inline] private def prev : Substring → String.Pos → String.Pos | ⟨s, b, _⟩, p => let absP := b+p if absP = b then p else s.prev absP - b private def nextn : Substring → Nat → String.Pos → String.Pos | ss, 0, p => p | ss, i+1, p => ss.nextn i (ss.next p) private def prevn : Substring → String.Pos → Nat → String.Pos | ss, 0, p => p | ss, i+1, p => ss.prevn i (ss.prev p) @[inline] def front (s : Substring) : Char := s.get 0 /-- Return the offset into `s` of the first occurence of `c` in `s`, or `s.bsize` if `c` doesn't occur. -/ @[inline] def posOf (s : Substring) (c : Char) : String.Pos := match s with | ⟨s, b, e⟩ => (String.posOfAux s c e b) - b @[inline] def drop : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b + ss.nextn n 0, e⟩ @[inline] def dropRight : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b, b + ss.prevn n ss.bsize⟩ @[inline] def take : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b, b + ss.nextn n 0⟩ @[inline] def takeRight : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b + ss.prevn n ss.bsize, e⟩ @[inline] def atEnd : Substring → String.Pos → Bool | ⟨s, b, e⟩, p => b + p == e @[inline] def extract : Substring → String.Pos → String.Pos → Substring | ⟨s, b, _⟩, b', e' => if b' ≥ e' then ⟨"", 0, 1⟩ else ⟨s, b+b', b+e'⟩ partial def splitOn (s : Substring) (sep : String := " ") : List Substring := if sep == "" then [s] else let stopPos := s.stopPos let str := s.str let rec loop (b i j : String.Pos) (r : List Substring) : List Substring := if i == stopPos then let r := if sep.atEnd j then "".toSubstring::{ str := str, startPos := b, stopPos := i-j } :: r else { str := str, startPos := b, stopPos := i } :: r r.reverse else if s.get i == sep.get j then let i := s.next i let j := sep.next j if sep.atEnd j then loop i i 0 ({ str := str, startPos := b, stopPos := i-j } :: r) else loop b i j r else loop b (s.next i) 0 r loop s.startPos s.startPos 0 [] @[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : Substring) : α := match s with | ⟨s, b, e⟩ => String.foldlAux f s e b a @[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : Substring) : α := match s with | ⟨s, b, e⟩ => String.foldrAux f a s e b @[inline] def any (s : Substring) (p : Char → Bool) : Bool := match s with | ⟨s, b, e⟩ => String.anyAux s e p b @[inline] def all (s : Substring) (p : Char → Bool) : Bool := !s.any (fun c => !p c) def contains (s : Substring) (c : Char) : Bool := s.any (fun a => a == c) @[specialize] private partial def takeWhileAux (s : String) (stopPos : String.Pos) (p : Char → Bool) (i : String.Pos) : String.Pos := if i == stopPos then i else if p (s.get i) then takeWhileAux s stopPos p (s.next i) else i @[inline] def takeWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let e := takeWhileAux s e p b; ⟨s, b, e⟩ @[inline] def dropWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let b := takeWhileAux s e p b; ⟨s, b, e⟩ @[specialize] private partial def takeRightWhileAux (s : String) (begPos : String.Pos) (p : Char → Bool) (i : String.Pos) : String.Pos := if i == begPos then i else let i' := s.prev i let c := s.get i' if !p c then i else takeRightWhileAux s begPos p i' @[inline] def takeRightWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let b := takeRightWhileAux s b p e ⟨s, b, e⟩ @[inline] def dropRightWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let e := takeRightWhileAux s b p e ⟨s, b, e⟩ @[inline] def trimLeft (s : Substring) : Substring := s.dropWhile Char.isWhitespace @[inline] def trimRight (s : Substring) : Substring := s.dropRightWhile Char.isWhitespace @[inline] def trim : Substring → Substring | ⟨s, b, e⟩ => let b := takeWhileAux s e Char.isWhitespace b let e := takeRightWhileAux s b Char.isWhitespace e ⟨s, b, e⟩ def isNat (s : Substring) : Bool := s.all fun c => c.isDigit def toNat? (s : Substring) : Option Nat := if s.isNat then some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0 else none def beq (ss1 ss2 : Substring) : Bool := ss1.toString == ss2.toString instance hasBeq : BEq Substring := ⟨beq⟩ end Substring namespace String def drop (s : String) (n : Nat) : String := (s.toSubstring.drop n).toString def dropRight (s : String) (n : Nat) : String := (s.toSubstring.dropRight n).toString def take (s : String) (n : Nat) : String := (s.toSubstring.take n).toString def takeRight (s : String) (n : Nat) : String := (s.toSubstring.takeRight n).toString def takeWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.takeWhile p).toString def dropWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.dropWhile p).toString def takeRightWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.takeRightWhile p).toString def dropRightWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.dropRightWhile p).toString def trimRight (s : String) : String := s.toSubstring.trimRight.toString def trimLeft (s : String) : String := s.toSubstring.trimLeft.toString def trim (s : String) : String := s.toSubstring.trim.toString @[inline] def nextWhile (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos := Substring.takeWhileAux s s.bsize p i @[inline] def nextUntil (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos := nextWhile s (fun c => !p c) i def toUpper (s : String) : String := s.map Char.toUpper def toLower (s : String) : String := s.map Char.toLower def capitalize (s : String) := s.set 0 <| s.get 0 |>.toUpper def decapitalize (s : String) := s.set 0 <| s.get 0 |>.toLower end String protected def Char.toString (c : Char) : String := String.singleton c
50d6369d086f187b8c65c68efc83b649f7e8d3c5
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/tactic/lift.lean
c4a393f1c239201ed457bec15ea19f265e3ccddc
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,785
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 tactic.rcases /-! # lift tactic This file defines the `lift` tactic, allowing the user to lift elements from one type to another under a specified condition. ## Tags lift, tactic -/ /-- A class specifying that you can lift elements from `α` to `β` assuming `cond` is true. Used by the tactic `lift`. -/ class can_lift (α β : Sort*) := (coe : β → α) (cond : α → Prop) (prf : ∀(x : α), cond x → ∃(y : β), coe y = x) open tactic /-- A user attribute used internally by the `lift` tactic. This should not be applied by hand. -/ @[user_attribute] meta def can_lift_attr : user_attribute (list name) := { name := "_can_lift", descr := "internal attribute used by the lift tactic", parser := failed, cache_cfg := { mk_cache := λ _, do { ls ← attribute.get_instances `instance, ls.mfilter $ λ l, do { (_,t) ← mk_const l >>= infer_type >>= open_pis, return $ t.is_app_of `can_lift } }, dependencies := [`instance] } } instance : can_lift ℤ ℕ := ⟨coe, λ n, 0 ≤ n, λ n hn, ⟨n.nat_abs, int.nat_abs_of_nonneg hn⟩⟩ /-- Enable automatic handling of pi types in `can_lift`. -/ instance pi.can_lift (ι : Type*) (α : Π i : ι, Type*) (β : Π i : ι, Type*) [Π i : ι, can_lift (α i) (β i)] : can_lift (Π i : ι, α i) (Π i : ι, β i) := { coe := λ f i, can_lift.coe (f i), cond := λ f, ∀ i, can_lift.cond (β i) (f i), prf := λ f hf, ⟨λ i, classical.some (can_lift.prf (f i) (hf i)), funext $ λ i, classical.some_spec (can_lift.prf (f i) (hf i))⟩ } instance pi_subtype.can_lift (ι : Type*) (α : Π i : ι, Type*) [ne : Π i, nonempty (α i)] (p : ι → Prop) : can_lift (Π i : subtype p, α i) (Π i, α i) := { coe := λ f i, f i, cond := λ _, true, prf := begin classical, refine λ f _, ⟨λ i, if hi : p i then f ⟨i, hi⟩ else classical.choice (ne i), funext _⟩, rintro ⟨i, hi⟩, exact dif_pos hi end } instance pi_subtype.can_lift' (ι : Type*) (α : Type*) [ne : nonempty α] (p : ι → Prop) : can_lift (subtype p → α) (ι → α) := pi_subtype.can_lift ι (λ _, α) p namespace tactic /-- Construct the proof of `cond x` in the lift tactic. * `e` is the expression being lifted and `h` is the specified proof of `can_lift.cond e`. * `old_tp` and `new_tp` are the arguments to `can_lift` and `inst` is the `can_lift`-instance. * `s` and `to_unfold` contain the information of the simp set used to simplify. If the proof was specified, we check whether it has the correct type. If it doesn't have the correct type, we display an error message (but first call dsimp on the expression in the message). If the proof was not specified, we create assert it as a local constant. (The name of this local constant doesn't matter, since `lift` will remove it from the context.) -/ meta def get_lift_prf (h : option pexpr) (old_tp new_tp inst e : expr) (s : simp_lemmas) (to_unfold : list name) : tactic expr := do expected_prf_ty ← mk_app `can_lift.cond [old_tp, new_tp, inst, e], expected_prf_ty ← s.dsimplify to_unfold expected_prf_ty, if h_some : h.is_some then decorate_error "lift tactic failed." $ i_to_expr ``((%%(option.get h_some) : %%expected_prf_ty)) else do prf_nm ← get_unused_name, prf ← assert prf_nm expected_prf_ty, swap, return prf /-- Lift the expression `p` to the type `t`, with proof obligation given by `h`. The list `n` is used for the two newly generated names, and to specify whether `h` should remain in the local context. See the doc string of `tactic.interactive.lift` for more information. -/ meta def lift (p : pexpr) (t : pexpr) (h : option pexpr) (n : list name) : tactic unit := do propositional_goal <|> fail "lift tactic failed. Tactic is only applicable when the target is a proposition.", e ← i_to_expr p, old_tp ← infer_type e, new_tp ← i_to_expr ``(%%t : Sort*), inst_type ← mk_app ``can_lift [old_tp, new_tp], inst ← mk_instance inst_type <|> pformat!"Failed to find a lift from {old_tp} to {new_tp}. Provide an instance of\n {inst_type}" >>= fail, /- make the simp set to get rid of `can_lift` projections -/ can_lift_instances ← can_lift_attr.get_cache >>= λ l, l.mmap resolve_name, (s, to_unfold) ← mk_simp_set tt [] $ can_lift_instances.map simp_arg_type.expr, prf_cond ← get_lift_prf h old_tp new_tp inst e s to_unfold, let prf_nm := if prf_cond.is_local_constant then some prf_cond.local_pp_name else none, /- We use mk_mapp to apply `can_lift.prf` to all but one argument, and then just use expr.app for the last argument. For some reason we get an error when applying mk_mapp it to all arguments. -/ prf_ex0 ← mk_mapp `can_lift.prf [old_tp, new_tp, inst, e], let prf_ex := prf_ex0 prf_cond, /- Find the name of the new variable -/ new_nm ← if n ≠ [] then return n.head else if e.is_local_constant then return e.local_pp_name else get_unused_name, /- Find the name of the proof of the equation -/ eq_nm ← if hn : 1 < n.length then return (n.nth_le 1 hn) else if e.is_local_constant then return `rfl else get_unused_name `h, /- We add the proof of the existential statement to the context and then apply `dsimp` to it, unfolding all `can_lift` instances. -/ temp_nm ← get_unused_name, temp_e ← note temp_nm none prf_ex, dsimp_hyp temp_e s to_unfold {}, /- We case on the existential. We use `rcases` because `eq_nm` could be `rfl`. -/ rcases none (pexpr.of_expr temp_e) $ rcases_patt.tuple ([new_nm, eq_nm].map rcases_patt.one), /- If the lifted variable is not a local constant, try to rewrite it away using the new equality. -/ when (¬ e.is_local_constant) (get_local eq_nm >>= λ e, interactive.rw ⟨[⟨⟨0, 0⟩, tt, (pexpr.of_expr e)⟩], none⟩ interactive.loc.wildcard), /- If the proof `prf_cond` is a local constant, remove it from the context, unless `n` specifies to keep it. -/ if h_prf_nm : prf_nm.is_some ∧ n.nth 2 ≠ prf_nm then get_local (option.get h_prf_nm.1) >>= clear else skip open lean.parser interactive interactive.types local postfix `?`:9001 := optional /-- Parses an optional token "using" followed by a trailing `pexpr`. -/ meta def using_texpr := (tk "using" *> texpr)? /-- Parses a token "to" followed by a trailing `pexpr`. -/ meta def to_texpr := (tk "to" *> texpr) namespace interactive /-- Lift an expression to another type. * Usage: `'lift' expr 'to' expr ('using' expr)? ('with' id (id id?)?)?`. * If `n : ℤ` and `hn : n ≥ 0` then the tactic `lift n to ℕ using hn` creates a new constant of type `ℕ`, also named `n` and replaces all occurrences of the old variable `(n : ℤ)` with `↑n` (where `n` in the new variable). It will remove `n` and `hn` from the context. + So for example the tactic `lift n to ℕ using hn` transforms the goal `n : ℤ, hn : n ≥ 0, h : P n ⊢ n = 3` to `n : ℕ, h : P ↑n ⊢ ↑n = 3` (here `P` is some term of type `ℤ → Prop`). * The argument `using hn` is optional, the tactic `lift n to ℕ` does the same, but also creates a new subgoal that `n ≥ 0` (where `n` is the old variable). + So for example the tactic `lift n to ℕ` transforms the goal `n : ℤ, h : P n ⊢ n = 3` to two goals `n : ℕ, h : P ↑n ⊢ ↑n = 3` and `n : ℤ, h : P n ⊢ n ≥ 0`. * You can also use `lift n to ℕ using e` where `e` is any expression of type `n ≥ 0`. * Use `lift n to ℕ with k` to specify the name of the new variable. * Use `lift n to ℕ with k hk` to also specify the name of the equality `↑k = n`. In this case, `n` will remain in the context. You can use `rfl` for the name of `hk` to substitute `n` away (i.e. the default behavior). * You can also use `lift e to ℕ with k hk` where `e` is any expression of type `ℤ`. In this case, the `hk` will always stay in the context, but it will be used to rewrite `e` in all hypotheses and the target. + So for example the tactic `lift n + 3 to ℕ using hn with k hk` transforms the goal `n : ℤ, hn : n + 3 ≥ 0, h : P (n + 3) ⊢ n + 3 = 2 * n` to the goal `n : ℤ, k : ℕ, hk : ↑k = n + 3, h : P ↑k ⊢ ↑k = 2 * n`. * The tactic `lift n to ℕ using h` will remove `h` from the context. If you want to keep it, specify it again as the third argument to `with`, like this: `lift n to ℕ using h with n rfl h`. * More generally, this can lift an expression from `α` to `β` assuming that there is an instance of `can_lift α β`. In this case the proof obligation is specified by `can_lift.cond`. * Given an instance `can_lift β γ`, it can also lift `α → β` to `α → γ`; more generally, given `β : Π a : α, Type*`, `γ : Π a : α, Type*`, and `[Π a : α, can_lift (β a) (γ a)]`, it automatically generates an instance `can_lift (Π a, β a) (Π a, γ a)`. `lift` is in some sense dual to the `zify` tactic. `lift (z : ℤ) to ℕ` will change the type of an integer `z` (in the supertype) to `ℕ` (the subtype), given a proof that `z ≥ 0`; propositions concerning `z` will still be over `ℤ`. `zify` changes propositions about `ℕ` (the subtype) to propositions about `ℤ` (the supertype), without changing the type of any variable. -/ meta def lift (p : parse texpr) (t : parse to_texpr) (h : parse using_texpr) (n : parse with_ident_list) : tactic unit := tactic.lift p t h n add_tactic_doc { name := "lift", category := doc_category.tactic, decl_names := [`tactic.interactive.lift], tags := ["coercions"] } end interactive end tactic
b80a68d99d481780dcf971314576a04efb5a46d4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/choose/sum.lean
23a502f0b19184b1d06e70e60ea2a8e2407024ea
[ "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,860
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import data.nat.choose.basic import tactic.linarith import algebra.big_operators.ring import algebra.big_operators.intervals import algebra.big_operators.order import algebra.big_operators.nat_antidiagonal /-! # Sums of binomial coefficients This file includes variants of the binomial theorem and other results on sums of binomial coefficients. Theorems whose proofs depend on such sums may also go in this file for import reasons. -/ open nat open finset open_locale big_operators variables {R : Type*} namespace commute variables [semiring R] {x y : R} (h : commute x y) (n : ℕ) include h /-- A version of the **binomial theorem** for noncommutative semirings. -/ theorem add_pow : (x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m := begin let t : ℕ → ℕ → R := λ n m, x ^ m * (y ^ (n - m)) * (choose n m), change (x + y) ^ n = ∑ m in range (n + 1), t n m, have h_first : ∀ n, t n 0 = y ^ n := λ n, by { dsimp [t], rw [choose_zero_right, pow_zero, nat.cast_one, mul_one, one_mul] }, have h_last : ∀ n, t n n.succ = 0 := λ n, by { dsimp [t], rw [choose_succ_self, nat.cast_zero, mul_zero] }, have h_middle : ∀ (n i : ℕ), (i ∈ range n.succ) → ((t n.succ) ∘ nat.succ) i = x * (t n i) + y * (t n i.succ) := begin intros n i h_mem, have h_le : i ≤ n := nat.le_of_lt_succ (mem_range.mp h_mem), dsimp [t], rw [choose_succ_succ, nat.cast_add, mul_add], congr' 1, { rw [pow_succ x, succ_sub_succ, mul_assoc, mul_assoc, mul_assoc] }, { rw [← mul_assoc y, ← mul_assoc y, (h.symm.pow_right i.succ).eq], by_cases h_eq : i = n, { rw [h_eq, choose_succ_self, nat.cast_zero, mul_zero, mul_zero] }, { rw [succ_sub (lt_of_le_of_ne h_le h_eq)], rw [pow_succ y, mul_assoc, mul_assoc, mul_assoc, mul_assoc] } } end, induction n with n ih, { rw [pow_zero, sum_range_succ, range_zero, sum_empty, zero_add], dsimp [t], rw [pow_zero, pow_zero, choose_self, nat.cast_one, mul_one, mul_one] }, { rw [sum_range_succ', h_first], rw [sum_congr rfl (h_middle n), sum_add_distrib, add_assoc], rw [pow_succ (x + y), ih, add_mul, mul_sum, mul_sum], congr' 1, rw [sum_range_succ', sum_range_succ, h_first, h_last, mul_zero, add_zero, pow_succ] } end /-- A version of `commute.add_pow` that avoids ℕ-subtraction by summing over the antidiagonal and also with the binomial coefficient applied via scalar action of ℕ. -/ lemma add_pow' : (x + y) ^ n = ∑ m in nat.antidiagonal n, choose n m.fst • (x ^ m.fst * y ^ m.snd) := by simp_rw [finset.nat.sum_antidiagonal_eq_sum_range_succ (λ m p, choose n m • (x^m * y^p)), _root_.nsmul_eq_mul, cast_comm, h.add_pow] end commute /-- The **binomial theorem** -/ theorem add_pow [comm_semiring R] (x y : R) (n : ℕ) : (x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m := (commute.all x y).add_pow n namespace nat /-- The sum of entries in a row of Pascal's triangle -/ theorem sum_range_choose (n : ℕ) : ∑ m in range (n + 1), choose n m = 2 ^ n := by simpa using (add_pow 1 1 n).symm lemma sum_range_choose_halfway (m : nat) : ∑ i in range (m + 1), choose (2 * m + 1) i = 4 ^ m := have ∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) = ∑ i in range (m + 1), choose (2 * m + 1) i, from sum_congr rfl $ λ i hi, choose_symm $ by linarith [mem_range.1 hi], mul_right_injective₀ two_ne_zero $ calc 2 * (∑ i in range (m + 1), choose (2 * m + 1) i) = (∑ i in range (m + 1), choose (2 * m + 1) i) + ∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) : by rw [two_mul, this] ... = (∑ i in range (m + 1), choose (2 * m + 1) i) + ∑ i in Ico (m + 1) (2 * m + 2), choose (2 * m + 1) i : begin rw [range_eq_Ico, sum_Ico_reflect], { congr, have A : m + 1 ≤ 2 * m + 1, by linarith, rw [add_comm, add_tsub_assoc_of_le A, ← add_comm], congr, rw tsub_eq_iff_eq_add_of_le A, ring, }, { linarith } end ... = ∑ i in range (2 * m + 2), choose (2 * m + 1) i : sum_range_add_sum_Ico _ (by linarith) ... = 2^(2 * m + 1) : sum_range_choose (2 * m + 1) ... = 2 * 4^m : by { rw [pow_succ, pow_mul], refl } lemma choose_middle_le_pow (n : ℕ) : choose (2 * n + 1) n ≤ 4 ^ n := begin have t : choose (2 * n + 1) n ≤ ∑ i in range (n + 1), choose (2 * n + 1) i := single_le_sum (λ x _, by linarith) (self_mem_range_succ n), simpa [sum_range_choose_halfway n] using t end lemma four_pow_le_two_mul_add_one_mul_central_binom (n : ℕ) : 4 ^ n ≤ (2 * n + 1) * choose (2 * n) n := calc 4 ^ n = (1 + 1) ^ (2 * n) : by norm_num [pow_mul] ... = ∑ m in range (2 * n + 1), choose (2 * n) m : by simp [add_pow] ... ≤ ∑ m in range (2 * n + 1), choose (2 * n) (2 * n / 2) : sum_le_sum (λ i hi, choose_le_middle i (2 * n)) ... = (2 * n + 1) * choose (2 * n) n : by simp end nat theorem int.alternating_sum_range_choose {n : ℕ} : ∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = if n = 0 then 1 else 0 := begin cases n, { simp }, have h := add_pow (-1 : ℤ) 1 n.succ, simp only [one_pow, mul_one, add_left_neg] at h, rw [← h, zero_pow (nat.succ_pos n), if_neg (nat.succ_ne_zero n)], end theorem int.alternating_sum_range_choose_of_ne {n : ℕ} (h0 : n ≠ 0) : ∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = 0 := by rw [int.alternating_sum_range_choose, if_neg h0] namespace finset theorem sum_powerset_apply_card {α β : Type*} [add_comm_monoid α] (f : ℕ → α) {x : finset β} : ∑ m in x.powerset, f m.card = ∑ m in range (x.card + 1), (x.card.choose m) • f m := begin transitivity ∑ m in range (x.card + 1), ∑ j in x.powerset.filter (λ z, z.card = m), f j.card, { refine (sum_fiberwise_of_maps_to _ _).symm, intros y hy, rw [mem_range, nat.lt_succ_iff], rw mem_powerset at hy, exact card_le_of_subset hy }, { refine sum_congr rfl (λ y hy, _), rw [← card_powerset_len, ← sum_const], refine sum_congr powerset_len_eq_filter.symm (λ z hz, _), rw (mem_powerset_len.1 hz).2 } end theorem sum_powerset_neg_one_pow_card {α : Type*} [decidable_eq α] {x : finset α} : ∑ m in x.powerset, (-1 : ℤ) ^ m.card = if x = ∅ then 1 else 0 := begin rw sum_powerset_apply_card, simp only [nsmul_eq_mul', ← card_eq_zero, int.alternating_sum_range_choose] end theorem sum_powerset_neg_one_pow_card_of_nonempty {α : Type*} {x : finset α} (h0 : x.nonempty) : ∑ m in x.powerset, (-1 : ℤ) ^ m.card = 0 := begin classical, rw [sum_powerset_neg_one_pow_card, if_neg], rw [← ne.def, ← nonempty_iff_ne_empty], apply h0, end end finset
7061bc81d286ff278f5dc7580a8c27c4ed662584
682dc1c167e5900ba3168b89700ae1cf501cfa29
/src/basicmodal/semantics/definability.lean
6882ed7c5dcedbd6f7d1ab0c62a14542e1850b6a
[]
no_license
paulaneeley/modal
834558c87f55cdd6d8a29bb46c12f4d1de3239bc
ee5d149d4ecb337005b850bddf4453e56a5daf04
refs/heads/master
1,675,911,819,093
1,609,785,144,000
1,609,785,144,000
270,388,715
13
1
null
null
null
null
UTF-8
Lean
false
false
2,817
lean
/- Copyright (c) 2021 Paula Neeley. All rights reserved. Author: Paula Neeley -/ import basicmodal.language basicmodal.syntax.syntax import basicmodal.semantics.semantics basicmodal.paths import data.set.basic local attribute [instance] classical.prop_decidable open form ---------------------- Frame Definability ---------------------- -- φ defines F (a class of frames) def defines (φ : form) (F : set (frame)) := ∀ f, f ∈ F ↔ f_valid φ f ---------------------- Definability Proofs ---------------------- variable f : frame variables {α : Type} (r : α → α → Prop) def euclidean := ∀ ⦃x y z⦄, r x y → r x z → r y z def ref_class : set (frame) := { f : frame | reflexive (f.rel) } def symm_class : set (frame) := { f : frame | symmetric (f.rel) } def trans_class : set (frame) := { f : frame | transitive (f.rel) } def euclid_class : set (frame) := { f : frame | euclidean (f.rel) } def equiv_class : set (frame) := { f : frame | equivalence (f.rel) } def ref_trans_class : set (frame) := ref_class ∩ trans_class lemma equiv_ref_euclid (f : frame) : f ∈ equiv_class ↔ f ∈ (ref_class ∩ euclid_class) := begin split, intro h1, cases h1 with h1 h2, cases h2 with h2 h3, split, exact h1, intros x y z h4 h5, exact h3 (h2 h4) h5, intro h1, split, cases h1, exact h1_left, split, cases h1 with h1 h2, intros x y h3, exact h2 h3 (h1 x), intros x y z h2 h3, cases h1 with h1 h4, exact h4 (h4 h2 (h1 x)) h3 end lemma ref_helper : ∀ φ f, f ∈ ref_class → f_valid ((box φ) ⊃ φ) f := begin intros φ f h v x h1, apply h1 x, apply h x end theorem ref_def : defines ((□ (p 0)) ⊃ (p 0)) (ref_class) := begin intro f, split, {exact ref_helper (p 0) f}, {intros h x, let v := λ n y, n = 0 ∧ f.rel x y, specialize h v x, simp [forces, v] at h, exact h} end lemma symm_helper : ∀ φ f, f ∈ symm_class → f_valid (φ ⊃ (□ (◇φ))) f := begin dsimp, intros φ f h v x h1 y h2 h3, by_contradiction h4, exact ((h3 x) (h h2)) h1 end theorem symm_def : defines ((p 0) ⊃ (□ (◇ (p 0)))) (symm_class) := begin intro f, split, {exact symm_helper (p 0) f}, {intro h1, by_contradiction h2, rw symm_class at h2, rw set.nmem_set_of_eq at h2, rw symmetric at h2, push_neg at h2, cases h2 with x h2, cases h2 with y h2, let v := λ n x, n = 0 ∧ ¬ f.rel y x, specialize h1 v x, simp [forces, v] at h1, apply h1 h2.right y h2.left, intros y1 h3 h4, exact absurd h3 h4} end lemma trans_helper : ∀ φ f, f ∈ trans_class → f_valid (□ φ ⊃ □ (□ φ)) f := begin intros φ f h v x h1 y h3 z h4, exact (h1 z) ((h h3) h4) end lemma euclid_helper : ∀ φ f, f ∈ euclid_class → f_valid (◇ φ ⊃ □ (◇ φ)) f := begin intros φ f h v x h1 y h2 h3, apply h1, intros z h4, exact h3 z ((h h2) h4) end
5ddf8161634ccbfc8999ccaa2d05a62684a53e35
49ffcd4736fa3bdcc1cdbb546d4c855d67c0f28a
/library/init/data/char/basic.lean
5b744abd92c034b7e3b5477802c65e2b29dc8b86
[ "Apache-2.0" ]
permissive
black13/lean
979e24d09e17b2fdf8ec74aac160583000086bc8
1a80ea9c8e28902cadbfb612896bcd45ba4ce697
refs/heads/master
1,626,839,620,164
1,509,113,016,000
1,509,122,889,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,647
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat.basic open nat @[reducible] def is_valid_char (n : nat) : Prop := n < 0xd800 ∨ (0xdfff < n ∧ n < 0x110000) lemma is_valid_char_range_1 (n : nat) (h : n < 0xd800) : is_valid_char n := or.inl h lemma is_valid_char_range_2 (n : nat) (h₁ : 0xdfff < n) (h₂ : n < 0x110000) : is_valid_char n := or.inr ⟨h₁, h₂⟩ /-- The `char` type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure char := (val : nat) (valid : is_valid_char val) instance : has_sizeof char := ⟨λ c, c.val⟩ namespace char /- We cannot use tactic dec_trivial here because the tactic framework has not been defined yet. -/ lemma zero_lt_d800 : 0 < 0xd800 := zero_lt_succ _ @[pattern] def of_nat (n : nat) : char := if h : is_valid_char n then {val := n, valid := h} else {val := 0, valid := or.inl zero_lt_d800} def to_nat (c : char) : nat := c.val lemma eq_of_veq : ∀ {c d : char}, c.val = d.val → c = d | ⟨v, h⟩ ⟨_, _⟩ rfl := rfl lemma veq_of_eq : ∀ {c d : char}, c = d → c.val = d.val | _ _ rfl := rfl lemma ne_of_vne {c d : char} (h : c.val ≠ d.val) : c ≠ d := λ h', absurd (veq_of_eq h') h lemma vne_of_ne {c d : char} (h : c ≠ d) : c.val ≠ d.val := λ h', absurd (eq_of_veq h') h end char instance : decidable_eq char := λ i j, decidable_of_decidable_of_iff (nat.decidable_eq i.val j.val) ⟨char.eq_of_veq, char.veq_of_eq⟩ instance : inhabited char := ⟨'A'⟩
aa1e51e3688dc11b46a847c647305f62aef7163c
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/ring_theory/free_comm_ring.lean
198f88117f804284b5a09bcc63b4533cdb20e0b4
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
16,037
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import group_theory.free_abelian_group data.equiv.functor data.mv_polynomial import ring_theory.ideal_operations ring_theory.free_ring noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v variables (α : Type u) def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring instance : comm_ring (free_comm_ring α) := free_abelian_group.comm_ring _ instance : inhabited (free_comm_ring α) := ⟨0⟩ variables {α} def of (x : α) : free_comm_ring α := free_abelian_group.of ([x] : multiset α) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {β : Type v} [comm_ring β] (f : α → β) /-- Lift a map `α → R` to a ring homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : free_comm_ring α → β := free_abelian_group.lift $ λ s, (s.map f).prod @[simp] lemma lift_zero : lift f 0 = 0 := rfl @[simp] lemma lift_one : lift f 1 = 1 := free_abelian_group.lift.of _ _ @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_add (x y) : lift f (x + y) = lift f x + lift f y := free_abelian_group.lift.add _ _ _ @[simp] lemma lift_neg (x) : lift f (-x) = -lift f x := free_abelian_group.lift.neg _ _ @[simp] lemma lift_sub (x y) : lift f (x - y) = lift f x - lift f y := free_abelian_group.lift.sub _ _ _ @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros s2, conv { to_lhs, dsimp only [(*), mul_zero_class.mul, semiring.mul, ring.mul, semigroup.mul, comm_ring.mul] }, rw [free_abelian_group.lift.of, lift, free_abelian_group.lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros s1, iterate 3 { rw free_abelian_group.lift.of }, calc _ = multiset.prod ((multiset.map f s1) + (multiset.map f s2)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _ }, { intros s1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros s2 ih, rw [mul_neg_eq_neg_mul_symm, lift_neg, lift_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, lift_add, lift_add, mul_add, ih1, ih2] }, end /-- Lift of a map `f : α → β` to `free_comm_ring α` as a ring homomorphism. We don't use it as the canonical form because Lean fails to coerce it to a function. -/ def lift_hom : free_comm_ring α →+* β := ⟨lift f, lift_one f, lift_mul f, lift_zero f, lift_add f⟩ instance : is_ring_hom (lift f) := (lift_hom f).is_ring_hom @[simp] lemma coe_lift_hom : ⇑(lift_hom f : free_comm_ring α →+* β) = lift f := rfl @[simp] lemma lift_pow (x) (n : ℕ) : lift f (x ^ n) = lift f x ^ n := (lift_hom f).map_pow _ _ @[simp] lemma lift_comp_of (f : free_comm_ring α → β) [is_ring_hom f] : lift (f ∘ of) = f := funext $ λ x, free_comm_ring.induction_on x (by rw [lift_neg, lift_one, is_ring_hom.map_neg f, is_ring_hom.map_one f]) (lift_of _) (λ x y ihx ihy, by rw [lift_add, is_ring_hom.map_add f, ihx, ihy]) (λ x y ihx ihy, by rw [lift_mul, is_ring_hom.map_mul f, ihx, ihy]) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α → free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift_hom $ of ∘ f lemma map_zero : map f 0 = 0 := rfl lemma map_one : map f 1 = 1 := rfl lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ lemma map_add (x y) : map f (x + y) = map f x + map f y := lift_add _ _ _ lemma map_neg (x) : map f (-x) = -map f x := lift_neg _ _ lemma map_sub (x y) : map f (x - y) = map f x - map f y := lift_sub _ _ _ lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ lemma map_pow (x) (n : ℕ) : map f (x ^ n) = (map f x) ^ n := lift_pow _ _ _ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ ring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem _ _ _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero : is_supported 0 s := is_add_submonoid.zero_mem theorem is_supported_one : is_supported 1 s := is_submonoid.one_mem theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported def restriction (s : set α) [decidable_pred s] (x : free_comm_ring α) : free_comm_ring s := lift (λ p, if H : p ∈ s then of ⟨p, H⟩ else 0) x section restriction variables (s : set α) [decidable_pred s] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ @[simp] lemma restriction_zero : restriction s 0 = 0 := lift_zero _ @[simp] lemma restriction_one : restriction s 1 = 1 := lift_one _ @[simp] lemma restriction_add : restriction s (x + y) = restriction s x + restriction s y := lift_add _ _ _ @[simp] lemma restriction_neg : restriction s (-x) = -restriction s x := lift_neg _ _ @[simp] lemma restriction_sub : restriction s (x - y) = restriction s x - restriction s y := lift_sub _ _ _ @[simp] lemma restriction_mul : restriction s (x * y) = restriction s x * restriction s y := lift_mul _ _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, ring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin classical, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : polynomial ℤ) else polynomial.X) x = n, { intros x hx, refine ring.in_closure.rec_on hx _ _ _ _, { use 1, rw [lift_one], norm_cast }, { use -1, rw [lift_neg, lift_one], norm_cast }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [lift_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [lift_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw polynomial.int_cast_eq_C at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg one_ne_zero, polynomial.coeff_X, if_pos rfl] at this, apply_instance end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred s] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw restriction_one, refl }, { rw [restriction_neg, map_neg, restriction_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, restriction_of, dif_pos hps, map_mul, map_of, ih] }, { intros x y ihx ihy, rw [restriction_add, map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ finset.mem_singleton_self _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, set.finite_union hfs hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, set.finite_union hfs hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa finset.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) def to_free_comm_ring {α} : free_ring α → free_comm_ring α := free_ring.lift free_comm_ring.of instance to_free_comm_ring.is_ring_hom : is_ring_hom (@to_free_comm_ring α) := free_ring.is_ring_hom free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ instance coe.is_ring_hom : is_ring_hom (coe : free_ring α → free_comm_ring α) := free_ring.to_free_comm_ring.is_ring_hom _ @[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := free_ring.lift_neg _ _ @[simp, norm_cast] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := free_ring.lift_add _ _ _ @[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := free_ring.lift_sub _ _ _ @[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := free_ring.lift_mul _ _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact free_ring.lift_add _ _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact free_ring.lift_mul _ _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := begin funext, apply @free_abelian_group.lift.ext _ _ _ (coe : free_ring α → free_comm_ring α) _ _ (free_abelian_group.lift.is_add_group_hom _), intros x, change free_ring.lift free_comm_ring.of (free_abelian_group.of x) = _, change _ = free_abelian_group.of (↑x), induction x with hd tl ih, {refl}, simp only [*, free_ring.lift, free_comm_ring.of, free_abelian_group.of, free_abelian_group.lift, free_group.of, free_group.to_group, free_group.to_group.aux, mul_one, free_group.quot_lift_mk, abelianization.lift.of, bool.cond_tt, list.prod_cons, cond, list.prod_nil, list.map] at *, refl end def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := @ring_equiv.of' (free_ring α) (free_comm_ring α) _ _ (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) $ begin delta functor.map_equiv, rw congr_arg is_ring_hom _, work_on_goal 2 { symmetry, exact coe_eq α }, apply_instance end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by rw [← (subsingleton_equiv_free_comm_ring α).left_inv (y * x), is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, mul_comm, ← is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, (subsingleton_equiv_free_comm_ring α).left_inv], .. free_ring.ring α } end free_ring def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := { to_fun := free_comm_ring.lift $ λ a, mv_polynomial.X a, inv_fun := mv_polynomial.eval₂ coe free_comm_ring.of, left_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, refine free_abelian_group.induction_on x rfl _ _ _, { intro s, refine multiset.induction_on s _ _, { unfold free_comm_ring.lift, rw [free_abelian_group.lift.of], exact mv_polynomial.eval₂_one _ _ }, { intros hd tl ih, show mv_polynomial.eval₂ coe free_comm_ring.of (free_comm_ring.lift (λ a, mv_polynomial.X a) (free_comm_ring.of hd * free_abelian_group.of tl)) = free_comm_ring.of hd * free_abelian_group.of tl, rw [free_comm_ring.lift_mul, free_comm_ring.lift_of, mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, ih] } }, { intros s ih, rw [free_comm_ring.lift_neg, ← neg_one_mul, mv_polynomial.eval₂_mul, ← mv_polynomial.C_1, ← mv_polynomial.C_neg, mv_polynomial.eval₂_C, int.cast_neg, int.cast_one, neg_one_mul, ih] }, { intros x₁ x₂ ih₁ ih₂, rw [free_comm_ring.lift_add, mv_polynomial.eval₂_add, ih₁, ih₂] } end, right_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, have : ∀ i : ℤ, free_comm_ring.lift (λ (a : α), mv_polynomial.X a) ↑i = mv_polynomial.C i, { exact λ i, int.induction_on i (by rw [int.cast_zero, free_comm_ring.lift_zero, mv_polynomial.C_0]) (λ i ih, by rw [int.cast_add, int.cast_one, free_comm_ring.lift_add, free_comm_ring.lift_one, ih, mv_polynomial.C_add, mv_polynomial.C_1]) (λ i ih, by rw [int.cast_sub, int.cast_one, free_comm_ring.lift_sub, free_comm_ring.lift_one, ih, mv_polynomial.C_sub, mv_polynomial.C_1]) }, apply mv_polynomial.induction_on x, { intro i, rw [mv_polynomial.eval₂_C, this] }, { intros p q ihp ihq, rw [mv_polynomial.eval₂_add, free_comm_ring.lift_add, ihp, ihq] }, { intros p a ih, rw [mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, free_comm_ring.lift_mul, free_comm_ring.lift_of, ih] } end, .. free_comm_ring.lift_hom $ λ a, mv_polynomial.X a } def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.pempty_ring_equiv _) def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.punit_ring_equiv _) open free_ring def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
f23b48a324084507bcd56ce71caa5b11bd687b8b
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Widget/Basic.lean
52c2e442df90448a23b38b4ed34e49c64259ed4e
[ "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
988
lean
import Lean.Elab.InfoTree import Lean.Message import Lean.Server.Rpc.Basic namespace Lean.Widget open Elab Server /-- Elaborator information with elaborator context. This is used to tag different parts of expressions in `ppExprTagged`. This is the input to the RPC call `Lean.Widget.InteractiveDiagnostics.infoToInteractive`. The purpose of `InfoWithCtx` is to carry over information about delaborated `Info` nodes in a `CodeWithInfos`, and the associated pretty-printing functionality is purpose-specific to showing the contents of infoview popups. -/ structure InfoWithCtx where ctx : Elab.ContextInfo info : Elab.Info deriving Inhabited, Std.TypeName deriving instance Std.TypeName for MessageData instance : ToJson FVarId := ⟨fun f => toJson f.name⟩ instance : ToJson MVarId := ⟨fun f => toJson f.name⟩ instance : FromJson FVarId := ⟨fun j => FVarId.mk <$> fromJson? j⟩ instance : FromJson MVarId := ⟨fun j => MVarId.mk <$> fromJson? j⟩ end Lean.Widget
148d7cc1f7dc42415f2d7d84dab5df2de7ec0f9c
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/polynomial.lean
6e546ece1fd33445e6461ba02dfce7ebb1a17e2b
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,196
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import analysis.normed_space.basic import data.polynomial.algebra_map import data.polynomial.inductions /-! # Polynomials and limits In this file we prove the following lemmas. * `polynomial.continuous_eval₂: `polynomial.eval₂` defines a continuous function. * `polynomial.continuous_aeval: `polynomial.aeval` defines a continuous function; we also prove convenience lemmas `polynomial.continuous_at_aeval`, `polynomial.continuous_within_at_aeval`, `polynomial.continuous_on_aeval`. * `polynomial.continuous`: `polynomial.eval` defines a continuous functions; we also prove convenience lemmas `polynomial.continuous_at`, `polynomial.continuous_within_at`, `polynomial.continuous_on`. * `polynomial.tendsto_norm_at_top`: `λ x, ∥polynomial.eval (z x) p∥` tends to infinity provided that `λ x, ∥z x∥` tends to infinity and `0 < degree p`; * `polynomial.tendsto_abv_eval₂_at_top`, `polynomial.tendsto_abv_at_top`, `polynomial.tendsto_abv_aeval_at_top`: a few versions of the previous statement for `is_absolute_value abv` instead of norm. ## Tags polynomial, continuity -/ open is_absolute_value filter namespace polynomial open_locale polynomial section topological_semiring variables {R S : Type*} [semiring R] [topological_space R] [topological_semiring R] (p : R[X]) @[continuity] protected lemma continuous_eval₂ [semiring S] (p : S[X]) (f : S →+* R) : continuous (λ x, p.eval₂ f x) := begin dsimp only [eval₂_eq_sum, finsupp.sum], exact continuous_finset_sum _ (λ c hc, continuous_const.mul (continuous_pow _)) end @[continuity] protected lemma continuous : continuous (λ x, p.eval x) := p.continuous_eval₂ _ protected lemma continuous_at {a : R} : continuous_at (λ x, p.eval x) a := p.continuous.continuous_at protected lemma continuous_within_at {s a} : continuous_within_at (λ x, p.eval x) s a := p.continuous.continuous_within_at protected lemma continuous_on {s} : continuous_on (λ x, p.eval x) s := p.continuous.continuous_on end topological_semiring section topological_algebra variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] [topological_space A] [topological_semiring A] (p : R[X]) @[continuity] protected lemma continuous_aeval : continuous (λ x : A, aeval x p) := p.continuous_eval₂ _ protected lemma continuous_at_aeval {a : A} : continuous_at (λ x : A, aeval x p) a := p.continuous_aeval.continuous_at protected lemma continuous_within_at_aeval {s a} : continuous_within_at (λ x : A, aeval x p) s a := p.continuous_aeval.continuous_within_at protected lemma continuous_on_aeval {s} : continuous_on (λ x : A, aeval x p) s := p.continuous_aeval.continuous_on end topological_algebra lemma tendsto_abv_eval₂_at_top {R S k α : Type*} [semiring R] [ring S] [linear_ordered_field k] (f : R →+* S) (abv : S → k) [is_absolute_value abv] (p : R[X]) (hd : 0 < degree p) (hf : f p.leading_coeff ≠ 0) {l : filter α} {z : α → S} (hz : tendsto (abv ∘ z) l at_top) : tendsto (λ x, abv (p.eval₂ f (z x))) l at_top := begin revert hf, refine degree_pos_induction_on p hd _ _ _; clear hd p, { rintros c - hc, rw [leading_coeff_mul_X, leading_coeff_C] at hc, simpa [abv_mul abv] using hz.const_mul_at_top ((abv_pos abv).2 hc) }, { intros p hpd ihp hf, rw [leading_coeff_mul_X] at hf, simpa [abv_mul abv] using (ihp hf).at_top_mul_at_top hz }, { intros p a hd ihp hf, rw [add_comm, leading_coeff_add_of_degree_lt (degree_C_le.trans_lt hd)] at hf, refine tendsto_at_top_of_add_const_right (abv (-f a)) _, refine tendsto_at_top_mono (λ _, abv_add abv _ _) _, simpa using ihp hf } end lemma tendsto_abv_at_top {R k α : Type*} [ring R] [linear_ordered_field k] (abv : R → k) [is_absolute_value abv] (p : R[X]) (h : 0 < degree p) {l : filter α} {z : α → R} (hz : tendsto (abv ∘ z) l at_top) : tendsto (λ x, abv (p.eval (z x))) l at_top := tendsto_abv_eval₂_at_top _ _ _ h (mt leading_coeff_eq_zero.1 $ ne_zero_of_degree_gt h) hz lemma tendsto_abv_aeval_at_top {R A k α : Type*} [comm_semiring R] [ring A] [algebra R A] [linear_ordered_field k] (abv : A → k) [is_absolute_value abv] (p : R[X]) (hd : 0 < degree p) (h₀ : algebra_map R A p.leading_coeff ≠ 0) {l : filter α} {z : α → A} (hz : tendsto (abv ∘ z) l at_top) : tendsto (λ x, abv (aeval (z x) p)) l at_top := tendsto_abv_eval₂_at_top _ abv p hd h₀ hz variables {α R : Type*} [normed_ring R] [is_absolute_value (norm : R → ℝ)] lemma tendsto_norm_at_top (p : R[X]) (h : 0 < degree p) {l : filter α} {z : α → R} (hz : tendsto (λ x, ∥z x∥) l at_top) : tendsto (λ x, ∥p.eval (z x)∥) l at_top := p.tendsto_abv_at_top norm h hz lemma exists_forall_norm_le [proper_space R] (p : R[X]) : ∃ x, ∀ y, ∥p.eval x∥ ≤ ∥p.eval y∥ := if hp0 : 0 < degree p then p.continuous.norm.exists_forall_le $ p.tendsto_norm_at_top hp0 tendsto_norm_cocompact_at_top else ⟨p.coeff 0, by rw [eq_C_of_degree_le_zero (le_of_not_gt hp0)]; simp⟩ end polynomial
aa8d1c490d824ff7052b8b4b4ba2dfef68caea02
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/subsemigroup/membership.lean
4a8ded253af3fd713ada6c3f5e72ac7a3d7859dc
[ "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
4,880
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import group_theory.subsemigroup.basic /-! # Subsemigroups: membership criteria In this file we prove various facts about membership in a subsemigroup. The intent is to mimic `group_theory/submonoid/membership`, but currently this file is mostly a stub and only provides rudimentary support. * `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`, `coe_Sup_of_directed_on`: the supremum of a directed collection of subsemigroup is their union. ## TODO * Define the `free_semigroup` generated by a set. This might require some rather substantial additions to low-level API. For example, developing the subtype of nonempty lists, then defining a product on nonempty lists, powers where the exponent is a positive natural, et cetera. Another option would be to define the `free_semigroup` as the subsemigroup (pushed to be a semigroup) of the `free_monoid` consisting of non-identity elements. ## Tags subsemigroup -/ variables {ι : Sort*} {M A B : Type*} section non_assoc variables [has_mul M] open set namespace subsemigroup -- TODO: this section can be generalized to `[mul_mem_class B M] [complete_lattice B]` -- such that `complete_lattice.le` coincides with `set_like.le` @[to_additive] lemma mem_supr_of_directed {S : ι → subsemigroup M} (hS : directed (≤) S) {x : M} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq (S _)] using this, refine (λ hx, closure_induction hx (λ y hy, mem_Union.mp hy) _), { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hS i j with ⟨k, hki, hkj⟩, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end @[to_additive] lemma coe_supr_of_directed {S : ι → subsemigroup M} (hS : directed (≤) S) : ((⨆ i, S i : subsemigroup M) : set M) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {S : set (subsemigroup M)} (hS : directed_on (≤) S) {x : M} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := by simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] @[to_additive] lemma coe_Sup_of_directed_on {S : set (subsemigroup M)} (hS : directed_on (≤) S) : (↑(Sup S) : set M) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on hS] @[to_additive] lemma mem_sup_left {S T : subsemigroup M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subsemigroup M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mul_mem_sup {S T : subsemigroup M} {x y : M} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T := mul_mem (mem_sup_left hx) (mem_sup_right hy) @[to_additive] lemma mem_supr_of_mem {S : ι → subsemigroup M} (i : ι) : ∀ {x : M}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subsemigroup M)} {s : subsemigroup M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs /-- An induction principle for elements of `⨆ i, S i`. If `C` holds all elements of `S i` for all `i`, and is preserved under multiplication, then it holds for all elements of the supremum of `S`. -/ @[elab_as_eliminator, to_additive /-" An induction principle for elements of `⨆ i, S i`. If `C` holds all elements of `S i` for all `i`, and is preserved under addition, then it holds for all elements of the supremum of `S`. "-/] lemma supr_induction (S : ι → subsemigroup M) {C : M → Prop} {x : M} (hx : x ∈ ⨆ i, S i) (hp : ∀ i (x ∈ S i), C x) (hmul : ∀ x y, C x → C y → C (x * y)) : C x := begin rw supr_eq_closure at hx, refine closure_induction hx (λ x hx, _) hmul, obtain ⟨i, hi⟩ := set.mem_Union.mp hx, exact hp _ _ hi, end /-- A dependent version of `subsemigroup.supr_induction`. -/ @[elab_as_eliminator, to_additive /-"A dependent version of `add_subsemigroup.supr_induction`. "-/] lemma supr_induction' (S : ι → subsemigroup M) {C : Π x, (x ∈ ⨆ i, S i) → Prop} (hp : ∀ i (x ∈ S i), C x (mem_supr_of_mem i ‹_›)) (hmul : ∀ x y hx hy, C x hx → C y hy → C (x * y) (mul_mem ‹_› ‹_›)) {x : M} (hx : x ∈ ⨆ i, S i) : C x hx := begin refine exists.elim _ (λ (hx : x ∈ ⨆ i, S i) (hc : C x hx), hc), refine supr_induction S hx (λ i x hx, _) (λ x y, _), { exact ⟨_, hp _ _ hx⟩ }, { rintro ⟨_, Cx⟩ ⟨_, Cy⟩, exact ⟨_, hmul _ _ _ _ Cx Cy⟩ }, end end subsemigroup end non_assoc
7ffb5018d740ebef0eb7df860e2360ead330a888
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/linear_algebra/multilinear.lean
08150e1b878fc2ca07e70ef8f9daaca220dc6aa6
[ "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
33,815
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import linear_algebra.basic import tactic.omega import data.fintype.sort /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set open_locale big_operators universes u v v' v₁ v₂ v₃ w u' variables {R : Type u} {ι : Type u'} {n : ℕ} {M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ι] /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] := (to_fun : (Πi, M₁ i) → M₂) (map_add' : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (map_smul' : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (update m i (c • x)) = c • to_fun (update m i x)) namespace multilinear_map section semiring variables [semiring R] [∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, semimodule R (M i)] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] [semimodule R M'] (f f' : multilinear_map R M₁ M₂) instance : has_coe_to_fun (multilinear_map R M₁ M₂) := ⟨_, to_fun⟩ @[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := by cases f; cases f'; congr'; exact funext H @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := begin have : (0 : R) • (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := begin obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ M₂) := ⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_zero (multilinear_map R M₁ M₂) := ⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl instance : add_comm_monoid (multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ := { to_fun := λx, f (update m i x), map_add' := λx y, by simp, map_smul' := λc x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := { to_fun := λ m, (f m, g m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ noncomputable def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (λ i : fin k, M') M₂ := { to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.mono_equiv_of_fin hk).symm ⟨j, h⟩) else z), map_add' := λ v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, map_smul' := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma snoc_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c • x)) = c • f (snoc m x) := by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last] /- If `R` and `M₂` are implicit in the next definition, Lean is never able to infer them, even given `g` and `f`. Therefore, we make them explicit. -/ variables (R M₂) /-- If `g` is multilinear and `f` is linear, then `g (f m₁, ..., f mₙ)` is again a multilinear function, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R (λ (i : ι), M₂) M₃) (f : M' →ₗ[R] M₂) : multilinear_map R (λ (i : ι), M') M₃ := { to_fun := λ m, g (f ∘ m), map_add' := λ m i x y, by simp [comp_update], map_smul' := λ m i c x, by simp [comp_update] } variables {R M₂} /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (λs hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) open_locale classical open fintype finset /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux {n : ℕ} (h : ∑ i, (A i).card = n) : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := begin induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : ∃ i, A i = ∅, { rcases Ai_empty with ⟨i, hi⟩, have : ∑ j in A i, g i j = 0, by convert sum_empty, rw f.map_coord_zero i this, have : pi_finset A = ∅, { apply finset.eq_empty_of_forall_not_mem (λ r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, convert sum_empty.symm }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : ∀ i, (A i).card ≤ 1, { have Ai_card : ∀ i, (A i).card = 1, { assume i, have : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≤ 1 := Ai_singleton i, omega }, have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, ∑ j in A i, g i j), { assume r hr, unfold_coes, congr, ext i, have : ∀ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, one_nsmul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul, sum_const] }, -- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2. -- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i` -- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ := finset.one_lt_card_iff.1 hi₀, let B := function.update A i₀ (A i₀ \ {j₂}), let C := function.update A i₀ {j₂}, have B_subset_A : ∀ i, B i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : ∀ i, C i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity. have A_eq_BC : (λ i, ∑ j in A i, g i j) = function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j + ∑ j in C i₀, g i₀ j), { ext i, by_cases hi : i = i₀, { rw [hi], simp only [function.update_same], have : A i₀ = B i₀ ∪ C i₀, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hj₂, finset.singleton_subset_iff, union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (λ j hj, _), have : j = j₂, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j) = (λ i, ∑ j in B i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in C i₀, g i₀ j) = (λ i, ∑ j in C i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (λ i, ∑ j in B i, g i j) = ∑ r in pi_finset B, f (λ i, g i (r i)), { have : ∑ i, finset.card (B i) < ∑ i, finset.card (A i), { refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i)) ⟨i₀, finset.mem_univ _, _⟩, have : {j₂} ⊆ A i₀, by simp [hj₂], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans zero_lt_one hi₀)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (λ i, ∑ j in C i, g i j) = ∑ r in pi_finset C, f (λ i, g i (r i)), { have : ∑ i, finset.card (C i) < ∑ i, finset.card (A i) := finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i)) ⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B i₀) (C i₀), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hri₀ : r i₀ = j₂, { apply finset.mem_union_right, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ C i₀, by simp [C, hri₀], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ B i₀, by simp [B, hri₀, mem_pi_finset.1 hr i₀], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i)) (pi_finset_subset _ _ (λ i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.map_sum_finset_aux _ _ rfl /-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.map_sum_finset g (λ i, finset.univ) end apply_sum end semiring section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)] [add_comm_monoid M₂] [∀i, semimodule R (M i)] [∀i, semimodule R (M₁ i)] [semimodule R M₂] (f f' : multilinear_map R M₁ M₂) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λi, c i • m i) m) = (∏ i in s, c i) • f m := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) = s.piecewise (λi, c i • m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λi, c i • m i) = (∏ i, c i) • f m := by simpa using map_piecewise_smul f c m finset.univ instance : has_scalar R (multilinear_map R M₁ M₂) := ⟨λ c f, ⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (c : R) (m : Πi, M₁ i) : (c • f) m = c • f m := rfl variables (R ι) /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ := { to_fun := λm, (∏ i, m i) • z, map_add' := λ m i x y, by simp [finset.prod_update_of_mem, add_mul, add_smul], map_smul' := λ m i c x, by { rw [smul_eq_mul], simp [finset.prod_update_of_mem, smul_smul, mul_assoc] } } variables {R ι} @[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) : (multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = (∏ i, m i) • z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) : multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end end comm_semiring section ring variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := by { simp only [map_add, add_left_inj, sub_eq_add_neg, (neg_one_smul R y).symm, map_smul], simp } instance : has_neg (multilinear_map R M₁ M₂) := ⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : add_comm_group (multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] end ring section comm_ring variables [comm_ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] variables (R ι M₁ M₂) /-- The space of multilinear maps is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance semimodule : semimodule R (multilinear_map R M₁ M₂) := semimodule.of_core $ by refine { smul := (•), ..}; intros; ext; simp [smul_add, add_smul, smul_smul] -- This instance should not be needed! instance semimodule_ring : semimodule R (multilinear_map R (λ (i : ι), R) M₂) := multilinear_map.semimodule _ _ (λ (i : ι), R) _ /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) := { to_fun := λ z, multilinear_map.mk_pi_ring R ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } end comm_ring end multilinear_map namespace linear_map variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := { to_fun := λ m, g (f m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } end linear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M M₂} [comm_ring R] [∀i, add_comm_group (M i)] [add_comm_group M'] [add_comm_group M₂] [∀i, module R (M i)] [module R M'] [module R M₂] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : multilinear_map R M M₂ := { to_fun := λm, f (m 0) (tail m), map_add' := λm i x y, begin by_cases h : i = 0, { revert x y, rw h, assume x y, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] } end, map_smul' := λm i c x, begin by_cases h : i = 0, { revert x, rw h, assume x, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M M₂) : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) := { to_fun := λx, { to_fun := λm, f (cons x m), map_add' := λm i y y', by simp, map_smul' := λm i y c, by simp }, map_add' := λx y, by { ext m, exact cons_add f m x y }, map_smul' := λc x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M M₂) : f.curry_left.uncurry_left = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M M₂} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) : multilinear_map R M M₂ := { to_fun := λm, f (init m) (m (last n)), map_add' := λm i x y, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, map_smul' := λm i c x, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M M₂) : multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) := { to_fun := λm, { to_fun := λx, f (snoc m x), map_add' := λx y, by rw f.snoc_add, map_smul' := λc x, by rw f.snoc_smul }, map_add' := λm i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, map_smul' := λm i c x, begin ext z, change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } end currying
2a60745ce1de2cc4483bdef2880a74b4814d474e
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/04_Quantifiers_and_Equality.org.29.lean
24e623862252f5de65e86d76017735f1b430e3ac
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
336
lean
/- page 59 -/ import standard import data.nat open nat variable f : ℕ → ℕ premise H : ∀ x : ℕ, f x ≤ f (x + 1) -- BEGIN example : f 0 ≤ f 3 := have f 0 ≤ f 1, from H 0, have f 1 ≤ f 2, from H 1, have f 2 ≤ f 3, from H 2, show f 0 ≤ f 3, from le.trans `f 0 ≤ f 1` (le.trans `f 1 ≤ f 2` `f 2 ≤ f 3`) -- END
09b563c8a7958bcbbaa64ef6022da2a892f206ec
4727251e0cd73359b15b664c3170e5d754078599
/test/slim_check.lean
7e50cd1a8a4193d6a7b0b30e45bac553db4d49a6
[ "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
7,039
lean
import tactic.slim_check import testing.slim_check.functions import .mk_slim_check_test example : true := begin have : ∀ i j : ℕ, i < j → j < i, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! i := 0 j := 1 guard: 0 < 1 (by construction) issue: 1 < 0 does not hold (0 shrinks) ------------------- ", admit, trivial end example : true := begin have : (∀ x : ℕ, 2 ∣ x → x < 100), success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! x := 104 issue: 104 < 100 does not hold (2 shrinks) ------------------- ", admit, trivial end example (xs : list ℕ) (w : ∃ x ∈ xs, x < 3) : true := begin have : ∀ y ∈ xs, y < 5, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! xs := [5, 5, 0, 1] x := 0 y := 5 issue: 5 < 5 does not hold (5 shrinks) ------------------- ", admit, trivial end example (x : ℕ) (h : 2 ∣ x) : true := begin have : x < 100, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! x := 104 issue: 104 < 100 does not hold (2 shrinks) ------------------- ", admit, trivial end example (α : Type) (xs ys : list α) : true := begin have : xs ++ ys = ys ++ xs, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! α := ℤ xs := [0] ys := [1] issue: [0, 1] = [1, 0] does not hold (4 shrinks) ------------------- ", admit, trivial end example : true := begin have : ∀ x ∈ [1,2,3], x < 4, slim_check { random_seed := some 257, quiet := tt }, -- success trivial, end open function slim_check example (f : ℤ → ℤ) (h : injective f) : true := begin have : monotone (f ∘ small.mk), success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! f := [2 ↦ 3, 3 ↦ 9, 4 ↦ 6, 5 ↦ 4, 6 ↦ 2, 8 ↦ 5, 9 ↦ 8, x ↦ x] x := 3 y := 4 guard: 3 ≤ 4 (by construction) issue: 9 ≤ 6 does not hold (5 shrinks) ------------------- ", admit, trivial, end example (f : ℤ → ℤ) (h : injective f) (g : ℤ → ℤ) (h : injective g) (i) : true := begin have : f i = g i, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! f := [x ↦ x] g := [1 ↦ 2, 2 ↦ 1, x ↦ x] i := 1 issue: 1 = 2 does not hold (5 shrinks) ------------------- ", admit, trivial, end example (f : ℤ → ℤ) (h : injective f) : true := begin have : monotone f, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! f := [2 ↦ 3, 3 ↦ 9, 4 ↦ 6, 5 ↦ 4, 6 ↦ 2, 8 ↦ 5, 9 ↦ 8, x ↦ x] x := 3 y := 4 guard: 3 ≤ 4 (by construction) issue: 9 ≤ 6 does not hold (5 shrinks) ------------------- ", admit, trivial, end example (f : ℤ → ℤ) : true := begin have : injective f, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! f := [_ ↦ 0] x := 0 y := -1 guard: 0 = 0 issue: 0 = -1 does not hold (0 shrinks) ------------------- ", admit, trivial, end example (f : ℤ → ℤ) : true := begin have : monotone f, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! f := [-6 ↦ 97, 0 ↦ 0, _ ↦ 4] x := -6 y := -2 guard: -6 ≤ -2 (by construction) issue: 97 ≤ 4 does not hold (5 shrinks) ------------------- ", admit, trivial, end example (xs ys : list ℤ) (h : xs ~ ys) : true := begin have : list.qsort (λ x y, x ≠ y) xs = list.qsort (λ x y, x ≠ y) ys, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! xs := [0, 1] ys := [1, 0] guard: [0, 1] ~ [1, 0] (by construction) issue: [0, 1] = [1, 0] does not hold (4 shrinks) ------------------- ", admit, trivial end example (x y : ℕ) : true := begin have : y ≤ x → x + y < 100, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! x := 59 y := 41 guard: 41 ≤ 59 (by construction) issue: 100 < 100 does not hold (8 shrinks) ------------------- ", admit, trivial, end example (x : ℤ) : true := begin have : x ≤ 3 → 3 ≤ x, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! x := 2 guard: 2 ≤ 3 (by construction) issue: 3 ≤ 2 does not hold (1 shrinks) ------------------- ", admit, trivial, end example (x y : ℤ) : true := begin have : y ≤ x → x + y < 100, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! x := 52 y := 52 guard: 52 ≤ 52 (by construction) issue: 104 < 100 does not hold (4 shrinks) ------------------- ", admit, trivial, end example (x y : Prop) : true := begin have : x ∨ y → y ∧ x, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! x := tt y := ff guard: (true ∨ false) issue: false does not hold (0 shrinks) ------------------- ", admit, trivial, end example (x y : Prop) : true := begin have : (¬x ↔ y) → y ∧ x, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! x := tt y := ff guard: (¬ true ↔ false) issue: false does not hold (0 shrinks) ------------------- ", admit, trivial, end example (x y : Prop) : true := begin -- deterministic have : (x ↔ y) → y ∨ x, success_if_fail_with_msg { slim_check } " =================== Found problems! x := ff y := ff guard: (false ↔ false) issue: false does not hold issue: false does not hold (0 shrinks) ------------------- ", admit, trivial, end example (x y : Prop) : true := begin -- deterministic have : y ∨ x, success_if_fail_with_msg { slim_check } " =================== Found problems! x := ff y := ff issue: false does not hold issue: false does not hold (0 shrinks) ------------------- ", admit, trivial, end example (x y : Prop) : true := begin have : x ↔ y, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! x := tt y := ff issue: false does not hold issue: ¬ true does not hold (0 shrinks) ------------------- ", admit, trivial, end example (f : ℕ →₀ ℕ) : true := begin have : f = 0, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! f := [0 ↦ 1, _ ↦ 0] (2 shrinks) ------------------- ", admit, trivial, end example (f : Π₀ n : ℕ, ℕ) : true := begin have : f.update 0 0 = 0, success_if_fail_with_msg { slim_check { random_seed := some 257 } } " =================== Found problems! f := [1 ↦ 1, _ ↦ 0] (1 shrinks) ------------------- ", admit, trivial, end
d0fc2bc74893f6c929539eeaf93ac2c05c039446
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/lp_space.lean
519890f3f49d6652dd50864da44baeadabd37327
[ "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
45,452
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 analysis.mean_inequalities import analysis.mean_inequalities_pow import analysis.special_functions.pow.continuity import topology.algebra.order.liminf_limsup /-! # ℓp space > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file describes properties of elements `f` of a pi-type `Π i, E i` with finite "norm", defined for `p:ℝ≥0∞` as the size of the support of `f` if `p=0`, `(∑' a, ‖f a‖^p) ^ (1/p)` for `0 < p < ∞` and `⨆ a, ‖f a‖` for `p=∞`. The Prop-valued `mem_ℓp f p` states that a function `f : Π i, E i` has finite norm according to the above definition; that is, `f` has finite support if `p = 0`, `summable (λ a, ‖f a‖^p)` if `0 < p < ∞`, and `bdd_above (norm '' (set.range f))` if `p = ∞`. The space `lp E p` is the subtype of elements of `Π i : α, E i` which satisfy `mem_ℓp f p`. For `1 ≤ p`, the "norm" is genuinely a norm and `lp` is a complete metric space. ## Main definitions * `mem_ℓp f p` : property that the function `f` satisfies, as appropriate, `f` finitely supported if `p = 0`, `summable (λ a, ‖f a‖^p)` if `0 < p < ∞`, and `bdd_above (norm '' (set.range f))` if `p = ∞`. * `lp E p` : elements of `Π i : α, E i` such that `mem_ℓp f p`. Defined as an `add_subgroup` of a type synonym `pre_lp` for `Π i : α, E i`, and equipped with a `normed_add_comm_group` structure. Under appropriate conditions, this is also equipped with the instances `lp.normed_space`, `lp.complete_space`. For `p=∞`, there is also `lp.infty_normed_ring`, `lp.infty_normed_algebra`, `lp.infty_star_ring` and `lp.infty_cstar_ring`. ## Main results * `mem_ℓp.of_exponent_ge`: For `q ≤ p`, a function which is `mem_ℓp` for `q` is also `mem_ℓp` for `p` * `lp.mem_ℓp_of_tendsto`, `lp.norm_le_of_tendsto`: A pointwise limit of functions in `lp`, all with `lp` norm `≤ C`, is itself in `lp` and has `lp` norm `≤ C`. * `lp.tsum_mul_le_mul_norm`: basic form of Hölder's inequality ## Implementation Since `lp` is defined as an `add_subgroup`, dot notation does not work. Use `lp.norm_neg f` to say that `‖-f‖ = ‖f‖`, instead of the non-working `f.norm_neg`. ## TODO * More versions of Hölder's inequality (for example: the case `p = 1`, `q = ∞`; a version for normed rings which has `‖∑' i, f i * g i‖` rather than `∑' i, ‖f i‖ * g i‖` on the RHS; a version for three exponents satisfying `1 / r = 1 / p + 1 / q`) -/ noncomputable theory open_locale nnreal ennreal big_operators variables {α : Type*} {E : α → Type*} {p q : ℝ≥0∞} [Π i, normed_add_comm_group (E i)] /-! ### `mem_ℓp` predicate -/ /-- The property that `f : Π i : α, E i` * is finitely supported, if `p = 0`, or * admits an upper bound for `set.range (λ i, ‖f i‖)`, if `p = ∞`, or * has the series `∑' i, ‖f i‖ ^ p` be summable, if `0 < p < ∞`. -/ def mem_ℓp (f : Π i, E i) (p : ℝ≥0∞) : Prop := if p = 0 then (set.finite {i | f i ≠ 0}) else (if p = ∞ then bdd_above (set.range (λ i, ‖f i‖)) else summable (λ i, ‖f i‖ ^ p.to_real)) lemma mem_ℓp_zero_iff {f : Π i, E i} : mem_ℓp f 0 ↔ set.finite {i | f i ≠ 0} := by dsimp [mem_ℓp]; rw [if_pos rfl] lemma mem_ℓp_zero {f : Π i, E i} (hf : set.finite {i | f i ≠ 0}) : mem_ℓp f 0 := mem_ℓp_zero_iff.2 hf lemma mem_ℓp_infty_iff {f : Π i, E i} : mem_ℓp f ∞ ↔ bdd_above (set.range (λ i, ‖f i‖)) := by dsimp [mem_ℓp]; rw [if_neg ennreal.top_ne_zero, if_pos rfl] lemma mem_ℓp_infty {f : Π i, E i} (hf : bdd_above (set.range (λ i, ‖f i‖))) : mem_ℓp f ∞ := mem_ℓp_infty_iff.2 hf lemma mem_ℓp_gen_iff (hp : 0 < p.to_real) {f : Π i, E i} : mem_ℓp f p ↔ summable (λ i, ‖f i‖ ^ p.to_real) := begin rw ennreal.to_real_pos_iff at hp, dsimp [mem_ℓp], rw [if_neg hp.1.ne', if_neg hp.2.ne], end lemma mem_ℓp_gen {f : Π i, E i} (hf : summable (λ i, ‖f i‖ ^ p.to_real)) : mem_ℓp f p := begin rcases p.trichotomy with rfl | rfl | hp, { apply mem_ℓp_zero, have H : summable (λ i : α, (1:ℝ)) := by simpa using hf, exact (finite_of_summable_const (by norm_num) H).subset (set.subset_univ _) }, { apply mem_ℓp_infty, have H : summable (λ i : α, (1:ℝ)) := by simpa using hf, simpa using ((finite_of_summable_const (by norm_num) H).image (λ i, ‖f i‖)).bdd_above }, exact (mem_ℓp_gen_iff hp).2 hf end lemma mem_ℓp_gen' {C : ℝ} {f : Π i, E i} (hf : ∀ s : finset α, ∑ i in s, ‖f i‖ ^ p.to_real ≤ C) : mem_ℓp f p := begin apply mem_ℓp_gen, use ⨆ s : finset α, ∑ i in s, ‖f i‖ ^ p.to_real, apply has_sum_of_is_lub_of_nonneg, { intros b, exact real.rpow_nonneg_of_nonneg (norm_nonneg _) _ }, apply is_lub_csupr, use C, rintros - ⟨s, rfl⟩, exact hf s end lemma zero_mem_ℓp : mem_ℓp (0 : Π i, E i) p := begin rcases p.trichotomy with rfl | rfl | hp, { apply mem_ℓp_zero, simp }, { apply mem_ℓp_infty, simp only [norm_zero, pi.zero_apply], exact bdd_above_singleton.mono set.range_const_subset, }, { apply mem_ℓp_gen, simp [real.zero_rpow hp.ne', summable_zero], } end lemma zero_mem_ℓp' : mem_ℓp (λ i : α, (0 : E i)) p := zero_mem_ℓp namespace mem_ℓp lemma finite_dsupport {f : Π i, E i} (hf : mem_ℓp f 0) : set.finite {i | f i ≠ 0} := mem_ℓp_zero_iff.1 hf lemma bdd_above {f : Π i, E i} (hf : mem_ℓp f ∞) : bdd_above (set.range (λ i, ‖f i‖)) := mem_ℓp_infty_iff.1 hf lemma summable (hp : 0 < p.to_real) {f : Π i, E i} (hf : mem_ℓp f p) : summable (λ i, ‖f i‖ ^ p.to_real) := (mem_ℓp_gen_iff hp).1 hf lemma neg {f : Π i, E i} (hf : mem_ℓp f p) : mem_ℓp (-f) p := begin rcases p.trichotomy with rfl | rfl | hp, { apply mem_ℓp_zero, simp [hf.finite_dsupport] }, { apply mem_ℓp_infty, simpa using hf.bdd_above }, { apply mem_ℓp_gen, simpa using hf.summable hp }, end @[simp] lemma neg_iff {f : Π i, E i} : mem_ℓp (-f) p ↔ mem_ℓp f p := ⟨λ h, neg_neg f ▸ h.neg, mem_ℓp.neg⟩ lemma of_exponent_ge {p q : ℝ≥0∞} {f : Π i, E i} (hfq : mem_ℓp f q) (hpq : q ≤ p) : mem_ℓp f p := begin rcases ennreal.trichotomy₂ hpq with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, hp⟩ | ⟨rfl, rfl⟩ | ⟨hq, rfl⟩ | ⟨hq, hp, hpq'⟩, { exact hfq }, { apply mem_ℓp_infty, obtain ⟨C, hC⟩ := (hfq.finite_dsupport.image (λ i, ‖f i‖)).bdd_above, use max 0 C, rintros x ⟨i, rfl⟩, by_cases hi : f i = 0, { simp [hi] }, { exact (hC ⟨i, hi, rfl⟩).trans (le_max_right _ _) } }, { apply mem_ℓp_gen, have : ∀ i ∉ hfq.finite_dsupport.to_finset, ‖f i‖ ^ p.to_real = 0, { intros i hi, have : f i = 0 := by simpa using hi, simp [this, real.zero_rpow hp.ne'] }, exact summable_of_ne_finset_zero this }, { exact hfq }, { apply mem_ℓp_infty, obtain ⟨A, hA⟩ := (hfq.summable hq).tendsto_cofinite_zero.bdd_above_range_of_cofinite, use A ^ (q.to_real⁻¹), rintros x ⟨i, rfl⟩, have : 0 ≤ ‖f i‖ ^ q.to_real := real.rpow_nonneg_of_nonneg (norm_nonneg _) _, simpa [← real.rpow_mul, mul_inv_cancel hq.ne'] using real.rpow_le_rpow this (hA ⟨i, rfl⟩) (inv_nonneg.mpr hq.le) }, { apply mem_ℓp_gen, have hf' := hfq.summable hq, refine summable_of_norm_bounded_eventually _ hf' (@set.finite.subset _ {i | 1 ≤ ‖f i‖} _ _ _), { have H : {x : α | 1 ≤ ‖f x‖ ^ q.to_real}.finite, { simpa using eventually_lt_of_tendsto_lt (by norm_num : (0:ℝ) < 1) hf'.tendsto_cofinite_zero }, exact H.subset (λ i hi, real.one_le_rpow hi hq.le) }, { show ∀ i, ¬ (|‖f i‖ ^ p.to_real| ≤ ‖f i‖ ^ q.to_real) → 1 ≤ ‖f i‖, intros i hi, have : 0 ≤ ‖f i‖ ^ p.to_real := real.rpow_nonneg_of_nonneg (norm_nonneg _) p.to_real, simp only [abs_of_nonneg, this] at hi, contrapose! hi, exact real.rpow_le_rpow_of_exponent_ge' (norm_nonneg _) hi.le hq.le hpq' } } end lemma add {f g : Π i, E i} (hf : mem_ℓp f p) (hg : mem_ℓp g p) : mem_ℓp (f + g) p := begin rcases p.trichotomy with rfl | rfl | hp, { apply mem_ℓp_zero, refine (hf.finite_dsupport.union hg.finite_dsupport).subset (λ i, _), simp only [pi.add_apply, ne.def, set.mem_union, set.mem_set_of_eq], contrapose!, rintros ⟨hf', hg'⟩, simp [hf', hg'] }, { apply mem_ℓp_infty, obtain ⟨A, hA⟩ := hf.bdd_above, obtain ⟨B, hB⟩ := hg.bdd_above, refine ⟨A + B, _⟩, rintros a ⟨i, rfl⟩, exact le_trans (norm_add_le _ _) (add_le_add (hA ⟨i, rfl⟩) (hB ⟨i, rfl⟩)) }, apply mem_ℓp_gen, let C : ℝ := if p.to_real < 1 then 1 else 2 ^ (p.to_real - 1), refine summable_of_nonneg_of_le _ (λ i, _) (((hf.summable hp).add (hg.summable hp)).mul_left C), { exact λ b, real.rpow_nonneg_of_nonneg (norm_nonneg (f b + g b)) p.to_real }, { refine (real.rpow_le_rpow (norm_nonneg _) (norm_add_le _ _) hp.le).trans _, dsimp [C], split_ifs with h h, { simpa using nnreal.coe_le_coe.2 (nnreal.rpow_add_le_add_rpow (‖f i‖₊) (‖g i‖₊) hp.le h.le) }, { let F : fin 2 → ℝ≥0 := ![‖f i‖₊, ‖g i‖₊], have : ∀ i, (0:ℝ) ≤ F i := λ i, (F i).coe_nonneg, simp only [not_lt] at h, simpa [F, fin.sum_univ_succ] using real.rpow_sum_le_const_mul_sum_rpow_of_nonneg (finset.univ : finset (fin 2)) h (λ i _, (F i).coe_nonneg) } } end lemma sub {f g : Π i, E i} (hf : mem_ℓp f p) (hg : mem_ℓp g p) : mem_ℓp (f - g) p := by { rw sub_eq_add_neg, exact hf.add hg.neg } lemma finset_sum {ι} (s : finset ι) {f : ι → Π i, E i} (hf : ∀ i ∈ s, mem_ℓp (f i) p) : mem_ℓp (λ a, ∑ i in s, f i a) p := begin haveI : decidable_eq ι := classical.dec_eq _, revert hf, refine finset.induction_on s _ _, { simp only [zero_mem_ℓp', finset.sum_empty, implies_true_iff], }, { intros i s his ih hf, simp only [his, finset.sum_insert, not_false_iff], exact (hf i (s.mem_insert_self i)).add (ih (λ j hj, hf j (finset.mem_insert_of_mem hj))), }, end section has_bounded_smul variables {𝕜 : Type*} [normed_ring 𝕜] [Π i, module 𝕜 (E i)] [∀ i, has_bounded_smul 𝕜 (E i)] lemma const_smul {f : Π i, E i} (hf : mem_ℓp f p) (c : 𝕜) : mem_ℓp (c • f) p := begin rcases p.trichotomy with rfl | rfl | hp, { apply mem_ℓp_zero, refine hf.finite_dsupport.subset (λ i, (_ : ¬c • f i = 0 → ¬f i = 0)), exact not_imp_not.mpr (λ hf', hf'.symm ▸ (smul_zero c)) }, { obtain ⟨A, hA⟩ := hf.bdd_above, refine mem_ℓp_infty ⟨‖c‖ * A, _⟩, rintros a ⟨i, rfl⟩, refine (norm_smul_le _ _).trans _, exact mul_le_mul_of_nonneg_left (hA ⟨i, rfl⟩) (norm_nonneg c) }, { apply mem_ℓp_gen, have := (hf.summable hp).mul_left (↑(‖c‖₊ ^ p.to_real) : ℝ), simp_rw [← coe_nnnorm, ←nnreal.coe_rpow, ←nnreal.coe_mul, nnreal.summable_coe, ←nnreal.mul_rpow] at this ⊢, refine nnreal.summable_of_le _ this, intro i, exact nnreal.rpow_le_rpow (nnnorm_smul_le _ _) (ennreal.to_real_nonneg), }, end lemma const_mul {f : α → 𝕜} (hf : mem_ℓp f p) (c : 𝕜) : mem_ℓp (λ x, c * f x) p := @mem_ℓp.const_smul α (λ i, 𝕜) _ _ 𝕜 _ _ (λ i, by apply_instance) _ hf c end has_bounded_smul end mem_ℓp /-! ### lp space The space of elements of `Π i, E i` satisfying the predicate `mem_ℓp`. -/ /-- We define `pre_lp E` to be a type synonym for `Π i, E i` which, importantly, does not inherit the `pi` topology on `Π i, E i` (otherwise this topology would descend to `lp E p` and conflict with the normed group topology we will later equip it with.) We choose to deal with this issue by making a type synonym for `Π i, E i` rather than for the `lp` subgroup itself, because this allows all the spaces `lp E p` (for varying `p`) to be subgroups of the same ambient group, which permits lemma statements like `lp.monotone` (below). -/ @[derive add_comm_group, nolint unused_arguments] def pre_lp (E : α → Type*) [Π i, normed_add_comm_group (E i)] : Type* := Π i, E i instance pre_lp.unique [is_empty α] : unique (pre_lp E) := pi.unique_of_is_empty E /-- lp space -/ def lp (E : α → Type*) [Π i, normed_add_comm_group (E i)] (p : ℝ≥0∞) : add_subgroup (pre_lp E) := { carrier := {f | mem_ℓp f p}, zero_mem' := zero_mem_ℓp, add_mem' := λ f g, mem_ℓp.add, neg_mem' := λ f, mem_ℓp.neg } namespace lp instance : has_coe (lp E p) (Π i, E i) := coe_subtype instance : has_coe_to_fun (lp E p) (λ _, Π i, E i) := ⟨λ f, ((f : Π i, E i) : Π i, E i)⟩ @[ext] lemma ext {f g : lp E p} (h : (f : Π i, E i) = g) : f = g := subtype.ext h protected lemma ext_iff {f g : lp E p} : f = g ↔ (f : Π i, E i) = g := subtype.ext_iff lemma eq_zero' [is_empty α] (f : lp E p) : f = 0 := subsingleton.elim f 0 protected lemma monotone {p q : ℝ≥0∞} (hpq : q ≤ p) : lp E q ≤ lp E p := λ f hf, mem_ℓp.of_exponent_ge hf hpq protected lemma mem_ℓp (f : lp E p) : mem_ℓp f p := f.prop variables (E p) @[simp] lemma coe_fn_zero : ⇑(0 : lp E p) = 0 := rfl variables {E p} @[simp] lemma coe_fn_neg (f : lp E p) : ⇑(-f) = -f := rfl @[simp] lemma coe_fn_add (f g : lp E p) : ⇑(f + g) = f + g := rfl @[simp] lemma coe_fn_sum {ι : Type*} (f : ι → lp E p) (s : finset ι) : ⇑(∑ i in s, f i) = ∑ i in s, ⇑(f i) := begin classical, refine finset.induction _ _ s, { simp }, intros i s his, simp [finset.sum_insert his], end @[simp] lemma coe_fn_sub (f g : lp E p) : ⇑(f - g) = f - g := rfl instance : has_norm (lp E p) := { norm := λ f, if hp : p = 0 then by subst hp; exact (lp.mem_ℓp f).finite_dsupport.to_finset.card else (if p = ∞ then ⨆ i, ‖f i‖ else (∑' i, ‖f i‖ ^ p.to_real) ^ (1/p.to_real)) } lemma norm_eq_card_dsupport (f : lp E 0) : ‖f‖ = (lp.mem_ℓp f).finite_dsupport.to_finset.card := dif_pos rfl lemma norm_eq_csupr (f : lp E ∞) : ‖f‖ = ⨆ i, ‖f i‖ := begin dsimp [norm], rw [dif_neg ennreal.top_ne_zero, if_pos rfl] end lemma is_lub_norm [nonempty α] (f : lp E ∞) : is_lub (set.range (λ i, ‖f i‖)) ‖f‖ := begin rw lp.norm_eq_csupr, exact is_lub_csupr (lp.mem_ℓp f) end lemma norm_eq_tsum_rpow (hp : 0 < p.to_real) (f : lp E p) : ‖f‖ = (∑' i, ‖f i‖ ^ p.to_real) ^ (1/p.to_real) := begin dsimp [norm], rw ennreal.to_real_pos_iff at hp, rw [dif_neg hp.1.ne', if_neg hp.2.ne], end lemma norm_rpow_eq_tsum (hp : 0 < p.to_real) (f : lp E p) : ‖f‖ ^ p.to_real = ∑' i, ‖f i‖ ^ p.to_real := begin rw [norm_eq_tsum_rpow hp, ← real.rpow_mul], { field_simp [hp.ne'] }, apply tsum_nonneg, intros i, calc (0:ℝ) = 0 ^ p.to_real : by rw real.zero_rpow hp.ne' ... ≤ _ : real.rpow_le_rpow rfl.le (norm_nonneg (f i)) hp.le end lemma has_sum_norm (hp : 0 < p.to_real) (f : lp E p) : has_sum (λ i, ‖f i‖ ^ p.to_real) (‖f‖ ^ p.to_real) := begin rw norm_rpow_eq_tsum hp, exact ((lp.mem_ℓp f).summable hp).has_sum end lemma norm_nonneg' (f : lp E p) : 0 ≤ ‖f‖ := begin rcases p.trichotomy with rfl | rfl | hp, { simp [lp.norm_eq_card_dsupport f] }, { cases is_empty_or_nonempty α with _i _i; resetI, { rw lp.norm_eq_csupr, simp [real.csupr_empty] }, inhabit α, exact (norm_nonneg (f default)).trans ((lp.is_lub_norm f).1 ⟨default, rfl⟩) }, { rw lp.norm_eq_tsum_rpow hp f, refine real.rpow_nonneg_of_nonneg (tsum_nonneg _) _, exact λ i, real.rpow_nonneg_of_nonneg (norm_nonneg _) _ }, end @[simp] lemma norm_zero : ‖(0 : lp E p)‖ = 0 := begin rcases p.trichotomy with rfl | rfl | hp, { simp [lp.norm_eq_card_dsupport] }, { simp [lp.norm_eq_csupr] }, { rw lp.norm_eq_tsum_rpow hp, have hp' : 1 / p.to_real ≠ 0 := one_div_ne_zero hp.ne', simpa [real.zero_rpow hp.ne'] using real.zero_rpow hp' } end lemma norm_eq_zero_iff {f : lp E p} : ‖f‖ = 0 ↔ f = 0 := begin classical, refine ⟨λ h, _, by { rintros rfl, exact norm_zero }⟩, rcases p.trichotomy with rfl | rfl | hp, { ext i, have : {i : α | ¬f i = 0} = ∅ := by simpa [lp.norm_eq_card_dsupport f] using h, have : (¬ (f i = 0)) = false := congr_fun this i, tauto }, { cases is_empty_or_nonempty α with _i _i; resetI, { simp }, have H : is_lub (set.range (λ i, ‖f i‖)) 0, { simpa [h] using lp.is_lub_norm f }, ext i, have : ‖f i‖ = 0 := le_antisymm (H.1 ⟨i, rfl⟩) (norm_nonneg _), simpa using this }, { have hf : has_sum (λ (i : α), ‖f i‖ ^ p.to_real) 0, { have := lp.has_sum_norm hp f, rwa [h, real.zero_rpow hp.ne'] at this }, have : ∀ i, 0 ≤ ‖f i‖ ^ p.to_real := λ i, real.rpow_nonneg_of_nonneg (norm_nonneg _) _, rw has_sum_zero_iff_of_nonneg this at hf, ext i, have : f i = 0 ∧ p.to_real ≠ 0, { simpa [real.rpow_eq_zero_iff_of_nonneg (norm_nonneg (f i))] using congr_fun hf i }, exact this.1 }, end lemma eq_zero_iff_coe_fn_eq_zero {f : lp E p} : f = 0 ↔ ⇑f = 0 := by rw [lp.ext_iff, coe_fn_zero] @[simp] lemma norm_neg ⦃f : lp E p⦄ : ‖-f‖ = ‖f‖ := begin rcases p.trichotomy with rfl | rfl | hp, { simp [lp.norm_eq_card_dsupport] }, { cases is_empty_or_nonempty α; resetI, { simp [lp.eq_zero' f], }, apply (lp.is_lub_norm (-f)).unique, simpa using lp.is_lub_norm f }, { suffices : ‖-f‖ ^ p.to_real = ‖f‖ ^ p.to_real, { exact real.rpow_left_inj_on hp.ne' (norm_nonneg' _) (norm_nonneg' _) this }, apply (lp.has_sum_norm hp (-f)).unique, simpa using lp.has_sum_norm hp f } end instance [hp : fact (1 ≤ p)] : normed_add_comm_group (lp E p) := add_group_norm.to_normed_add_comm_group { to_fun := norm, map_zero' := norm_zero, neg' := norm_neg, add_le' := λ f g, begin unfreezingI { rcases p.dichotomy with rfl | hp' }, { casesI is_empty_or_nonempty α, { simp [lp.eq_zero' f] }, refine (lp.is_lub_norm (f + g)).2 _, rintros x ⟨i, rfl⟩, refine le_trans _ (add_mem_upper_bounds_add (lp.is_lub_norm f).1 (lp.is_lub_norm g).1 ⟨_, _, ⟨i, rfl⟩, ⟨i, rfl⟩, rfl⟩), exact norm_add_le (f i) (g i) }, { have hp'' : 0 < p.to_real := zero_lt_one.trans_le hp', have hf₁ : ∀ i, 0 ≤ ‖f i‖ := λ i, norm_nonneg _, have hg₁ : ∀ i, 0 ≤ ‖g i‖ := λ i, norm_nonneg _, have hf₂ := lp.has_sum_norm hp'' f, have hg₂ := lp.has_sum_norm hp'' g, -- apply Minkowski's inequality obtain ⟨C, hC₁, hC₂, hCfg⟩ := real.Lp_add_le_has_sum_of_nonneg hp' hf₁ hg₁ (norm_nonneg' _) (norm_nonneg' _) hf₂ hg₂, refine le_trans _ hC₂, rw ← real.rpow_le_rpow_iff (norm_nonneg' (f + g)) hC₁ hp'', refine has_sum_le _ (lp.has_sum_norm hp'' (f + g)) hCfg, intros i, exact real.rpow_le_rpow (norm_nonneg _) (norm_add_le _ _) hp''.le }, end, eq_zero_of_map_eq_zero' := λ f, norm_eq_zero_iff.1 } -- TODO: define an `ennreal` version of `is_conjugate_exponent`, and then express this inequality -- in a better version which also covers the case `p = 1, q = ∞`. /-- Hölder inequality -/ protected lemma tsum_mul_le_mul_norm {p q : ℝ≥0∞} (hpq : p.to_real.is_conjugate_exponent q.to_real) (f : lp E p) (g : lp E q) : summable (λ i, ‖f i‖ * ‖g i‖) ∧ ∑' i, ‖f i‖ * ‖g i‖ ≤ ‖f‖ * ‖g‖ := begin have hf₁ : ∀ i, 0 ≤ ‖f i‖ := λ i, norm_nonneg _, have hg₁ : ∀ i, 0 ≤ ‖g i‖ := λ i, norm_nonneg _, have hf₂ := lp.has_sum_norm hpq.pos f, have hg₂ := lp.has_sum_norm hpq.symm.pos g, obtain ⟨C, -, hC', hC⟩ := real.inner_le_Lp_mul_Lq_has_sum_of_nonneg hpq (norm_nonneg' _) (norm_nonneg' _) hf₁ hg₁ hf₂ hg₂, rw ← hC.tsum_eq at hC', exact ⟨hC.summable, hC'⟩ end protected lemma summable_mul {p q : ℝ≥0∞} (hpq : p.to_real.is_conjugate_exponent q.to_real) (f : lp E p) (g : lp E q) : summable (λ i, ‖f i‖ * ‖g i‖) := (lp.tsum_mul_le_mul_norm hpq f g).1 protected lemma tsum_mul_le_mul_norm' {p q : ℝ≥0∞} (hpq : p.to_real.is_conjugate_exponent q.to_real) (f : lp E p) (g : lp E q) : ∑' i, ‖f i‖ * ‖g i‖ ≤ ‖f‖ * ‖g‖ := (lp.tsum_mul_le_mul_norm hpq f g).2 section compare_pointwise lemma norm_apply_le_norm (hp : p ≠ 0) (f : lp E p) (i : α) : ‖f i‖ ≤ ‖f‖ := begin rcases eq_or_ne p ∞ with rfl | hp', { haveI : nonempty α := ⟨i⟩, exact (is_lub_norm f).1 ⟨i, rfl⟩ }, have hp'' : 0 < p.to_real := ennreal.to_real_pos hp hp', have : ∀ i, 0 ≤ ‖f i‖ ^ p.to_real, { exact λ i, real.rpow_nonneg_of_nonneg (norm_nonneg _) _ }, rw ← real.rpow_le_rpow_iff (norm_nonneg _) (norm_nonneg' _) hp'', convert le_has_sum (has_sum_norm hp'' f) i (λ i hi, this i), end lemma sum_rpow_le_norm_rpow (hp : 0 < p.to_real) (f : lp E p) (s : finset α) : ∑ i in s, ‖f i‖ ^ p.to_real ≤ ‖f‖ ^ p.to_real := begin rw lp.norm_rpow_eq_tsum hp f, have : ∀ i, 0 ≤ ‖f i‖ ^ p.to_real, { exact λ i, real.rpow_nonneg_of_nonneg (norm_nonneg _) _ }, refine sum_le_tsum _ (λ i hi, this i) _, exact (lp.mem_ℓp f).summable hp end lemma norm_le_of_forall_le' [nonempty α] {f : lp E ∞} (C : ℝ) (hCf : ∀ i, ‖f i‖ ≤ C) : ‖f‖ ≤ C := begin refine (is_lub_norm f).2 _, rintros - ⟨i, rfl⟩, exact hCf i, end lemma norm_le_of_forall_le {f : lp E ∞} {C : ℝ} (hC : 0 ≤ C) (hCf : ∀ i, ‖f i‖ ≤ C) : ‖f‖ ≤ C := begin casesI is_empty_or_nonempty α, { simpa [eq_zero' f] using hC, }, { exact norm_le_of_forall_le' C hCf }, end lemma norm_le_of_tsum_le (hp : 0 < p.to_real) {C : ℝ} (hC : 0 ≤ C) {f : lp E p} (hf : ∑' i, ‖f i‖ ^ p.to_real ≤ C ^ p.to_real) : ‖f‖ ≤ C := begin rw [← real.rpow_le_rpow_iff (norm_nonneg' _) hC hp, norm_rpow_eq_tsum hp], exact hf, end lemma norm_le_of_forall_sum_le (hp : 0 < p.to_real) {C : ℝ} (hC : 0 ≤ C) {f : lp E p} (hf : ∀ s : finset α, ∑ i in s, ‖f i‖ ^ p.to_real ≤ C ^ p.to_real) : ‖f‖ ≤ C := norm_le_of_tsum_le hp hC (tsum_le_of_sum_le ((lp.mem_ℓp f).summable hp) hf) end compare_pointwise section has_bounded_smul variables {𝕜 : Type*} {𝕜' : Type*} variables [normed_ring 𝕜] [normed_ring 𝕜'] variables [Π i, module 𝕜 (E i)] [Π i, module 𝕜' (E i)] instance : module 𝕜 (pre_lp E) := pi.module α E 𝕜 instance [Π i, smul_comm_class 𝕜' 𝕜 (E i)] : smul_comm_class 𝕜' 𝕜 (pre_lp E) := pi.smul_comm_class instance [has_smul 𝕜' 𝕜] [Π i, is_scalar_tower 𝕜' 𝕜 (E i)] : is_scalar_tower 𝕜' 𝕜 (pre_lp E) := pi.is_scalar_tower instance [Π i, module 𝕜ᵐᵒᵖ (E i)] [Π i, is_central_scalar 𝕜 (E i)] : is_central_scalar 𝕜 (pre_lp E) := pi.is_central_scalar variables [∀ i, has_bounded_smul 𝕜 (E i)] [∀ i, has_bounded_smul 𝕜' (E i)] lemma mem_lp_const_smul (c : 𝕜) (f : lp E p) : c • (f : pre_lp E) ∈ lp E p := (lp.mem_ℓp f).const_smul c variables (E p 𝕜) /-- The `𝕜`-submodule of elements of `Π i : α, E i` whose `lp` norm is finite. This is `lp E p`, with extra structure. -/ def _root_.lp_submodule : submodule 𝕜 (pre_lp E) := { smul_mem' := λ c f hf, by simpa using mem_lp_const_smul c ⟨f, hf⟩, .. lp E p } variables {E p 𝕜} lemma coe_lp_submodule : (lp_submodule E p 𝕜).to_add_subgroup = lp E p := rfl instance : module 𝕜 (lp E p) := { .. (lp_submodule E p 𝕜).module } @[simp] lemma coe_fn_smul (c : 𝕜) (f : lp E p) : ⇑(c • f) = c • f := rfl instance [Π i, smul_comm_class 𝕜' 𝕜 (E i)] : smul_comm_class 𝕜' 𝕜 (lp E p) := ⟨λ r c f, subtype.ext $ smul_comm _ _ _⟩ instance [has_smul 𝕜' 𝕜] [Π i, is_scalar_tower 𝕜' 𝕜 (E i)] : is_scalar_tower 𝕜' 𝕜 (lp E p) := ⟨λ r c f, subtype.ext $ smul_assoc _ _ _⟩ instance [Π i, module 𝕜ᵐᵒᵖ (E i)] [Π i, is_central_scalar 𝕜 (E i)] : is_central_scalar 𝕜 (lp E p) := ⟨λ r f, subtype.ext $ op_smul_eq_smul _ _⟩ lemma norm_const_smul_le (hp : p ≠ 0) (c : 𝕜) (f : lp E p) : ‖c • f‖ ≤ ‖c‖ * ‖f‖ := begin rcases p.trichotomy with rfl | rfl | hp, { exact absurd rfl hp }, { cases is_empty_or_nonempty α; resetI, { simp [lp.eq_zero' f], }, have hcf := lp.is_lub_norm (c • f), have hfc := (lp.is_lub_norm f).mul_left (norm_nonneg c), simp_rw [←set.range_comp, function.comp] at hfc, -- TODO: some `is_lub` API should make it a one-liner from here. refine hcf.right _, have := hfc.left, simp_rw [mem_upper_bounds, set.mem_range, forall_exists_index, forall_apply_eq_imp_iff'] at this ⊢, intro a, exact (norm_smul_le _ _).trans (this a) }, { letI inst : has_nnnorm (lp E p) := ⟨λ f, ⟨‖f‖, norm_nonneg' _⟩⟩, have coe_nnnorm : ∀ f : lp E p, ↑‖f‖₊ = ‖f‖ := λ _, rfl, suffices : ‖c • f‖₊ ^ p.to_real ≤ (‖c‖₊ * ‖f‖₊) ^ p.to_real, { rwa nnreal.rpow_le_rpow_iff hp at this }, unfreezingI { clear_value inst }, rw [nnreal.mul_rpow], have hLHS := (lp.has_sum_norm hp (c • f)), have hRHS := (lp.has_sum_norm hp f).mul_left (‖c‖ ^ p.to_real), simp_rw [←coe_nnnorm, ←_root_.coe_nnnorm, ←nnreal.coe_rpow, ←nnreal.coe_mul, nnreal.has_sum_coe] at hRHS hLHS, refine has_sum_mono hLHS hRHS (λ i, _), dsimp only, rw [←nnreal.mul_rpow], exact nnreal.rpow_le_rpow (nnnorm_smul_le _ _) ennreal.to_real_nonneg } end instance [fact (1 ≤ p)] : has_bounded_smul 𝕜 (lp E p) := has_bounded_smul.of_norm_smul_le $ norm_const_smul_le (zero_lt_one.trans_le $ fact.out (1 ≤ p)).ne' end has_bounded_smul section division_ring variables {𝕜 : Type*} variables [normed_division_ring 𝕜] [Π i, module 𝕜 (E i)] [∀ i, has_bounded_smul 𝕜 (E i)] lemma norm_const_smul (hp : p ≠ 0) {c : 𝕜} (f : lp E p) : ‖c • f‖ = ‖c‖ * ‖f‖ := begin obtain rfl | hc := eq_or_ne c 0, { simp }, refine le_antisymm (norm_const_smul_le hp c f) _, have := mul_le_mul_of_nonneg_left (norm_const_smul_le hp c⁻¹ (c • f)) (norm_nonneg c), rwa [inv_smul_smul₀ hc, norm_inv, mul_inv_cancel_left₀ (norm_ne_zero_iff.mpr hc)] at this, end end division_ring section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [Π i, normed_space 𝕜 (E i)] instance [fact (1 ≤ p)] : normed_space 𝕜 (lp E p) := { norm_smul_le := λ c f, norm_smul_le _ _} end normed_space section normed_star_group variables [Π i, star_add_monoid (E i)] [Π i, normed_star_group (E i)] lemma _root_.mem_ℓp.star_mem {f : Π i, E i} (hf : mem_ℓp f p) : mem_ℓp (star f) p := begin rcases p.trichotomy with rfl | rfl | hp, { apply mem_ℓp_zero, simp [hf.finite_dsupport] }, { apply mem_ℓp_infty, simpa using hf.bdd_above }, { apply mem_ℓp_gen, simpa using hf.summable hp }, end @[simp] lemma _root_.mem_ℓp.star_iff {f : Π i, E i} : mem_ℓp (star f) p ↔ mem_ℓp f p := ⟨λ h, star_star f ▸ mem_ℓp.star_mem h ,mem_ℓp.star_mem⟩ instance : has_star (lp E p) := { star := λ f, ⟨(star f : Π i, E i), f.property.star_mem⟩} @[simp] lemma coe_fn_star (f : lp E p) : ⇑(star f) = star f := rfl @[simp] protected theorem star_apply (f : lp E p) (i : α) : star f i = star (f i) := rfl instance : has_involutive_star (lp E p) := { star_involutive := λ x, by {ext, simp} } instance : star_add_monoid (lp E p) := { star_add := λ f g, ext $ star_add _ _ } instance [hp : fact (1 ≤ p)] : normed_star_group (lp E p) := { norm_star := λ f, begin unfreezingI { rcases p.trichotomy with rfl | rfl | h }, { exfalso, have := ennreal.to_real_mono ennreal.zero_ne_top hp.elim, norm_num at this,}, { simp only [lp.norm_eq_csupr, lp.star_apply, norm_star] }, { simp only [lp.norm_eq_tsum_rpow h, lp.star_apply, norm_star] } end } variables {𝕜 : Type*} [has_star 𝕜] [normed_ring 𝕜] variables [Π i, module 𝕜 (E i)] [∀ i, has_bounded_smul 𝕜 (E i)] [Π i, star_module 𝕜 (E i)] instance : star_module 𝕜 (lp E p) := { star_smul := λ r f, ext $ star_smul _ _ } end normed_star_group section non_unital_normed_ring variables {I : Type*} {B : I → Type*} [Π i, non_unital_normed_ring (B i)] lemma _root_.mem_ℓp.infty_mul {f g : Π i, B i} (hf : mem_ℓp f ∞) (hg : mem_ℓp g ∞) : mem_ℓp (f * g) ∞ := begin rw mem_ℓp_infty_iff, obtain ⟨⟨Cf, hCf⟩, ⟨Cg, hCg⟩⟩ := ⟨hf.bdd_above, hg.bdd_above⟩, refine ⟨Cf * Cg, _⟩, rintros _ ⟨i, rfl⟩, calc ‖(f * g) i‖ ≤ ‖f i‖ * ‖g i‖ : norm_mul_le (f i) (g i) ... ≤ Cf * Cg : mul_le_mul (hCf ⟨i, rfl⟩) (hCg ⟨i, rfl⟩) (norm_nonneg _) ((norm_nonneg _).trans (hCf ⟨i, rfl⟩)) end instance : has_mul (lp B ∞) := { mul := λ f g, ⟨(f * g : Π i, B i) , f.property.infty_mul g.property⟩} @[simp] lemma infty_coe_fn_mul (f g : lp B ∞) : ⇑(f * g) = f * g := rfl instance : non_unital_ring (lp B ∞) := function.injective.non_unital_ring lp.has_coe_to_fun.coe (subtype.coe_injective) (lp.coe_fn_zero B ∞) lp.coe_fn_add infty_coe_fn_mul lp.coe_fn_neg lp.coe_fn_sub (λ _ _, rfl) (λ _ _,rfl) instance : non_unital_normed_ring (lp B ∞) := { norm_mul := λ f g, lp.norm_le_of_forall_le (mul_nonneg (norm_nonneg f) (norm_nonneg g)) (λ i, calc ‖(f * g) i‖ ≤ ‖f i‖ * ‖g i‖ : norm_mul_le _ _ ... ≤ ‖f‖ * ‖g‖ : mul_le_mul (lp.norm_apply_le_norm ennreal.top_ne_zero f i) (lp.norm_apply_le_norm ennreal.top_ne_zero g i) (norm_nonneg _) (norm_nonneg _)), .. lp.normed_add_comm_group } -- we also want a `non_unital_normed_comm_ring` instance, but this has to wait for #13719 instance infty_is_scalar_tower {𝕜} [normed_ring 𝕜] [Π i, module 𝕜 (B i)] [∀ i, has_bounded_smul 𝕜 (B i)] [Π i, is_scalar_tower 𝕜 (B i) (B i)] : is_scalar_tower 𝕜 (lp B ∞) (lp B ∞) := ⟨λ r f g, lp.ext $ smul_assoc r ⇑f ⇑g⟩ instance infty_smul_comm_class {𝕜} [normed_ring 𝕜] [Π i, module 𝕜 (B i)] [∀ i, has_bounded_smul 𝕜 (B i)] [Π i, smul_comm_class 𝕜 (B i) (B i)] : smul_comm_class 𝕜 (lp B ∞) (lp B ∞) := ⟨λ r f g, lp.ext $ smul_comm r ⇑f ⇑g⟩ section star_ring variables [Π i, star_ring (B i)] [Π i, normed_star_group (B i)] instance infty_star_ring : star_ring (lp B ∞) := { star_mul := λ f g, ext $ star_mul (_ : Π i, B i) _, .. (show star_add_monoid (lp B ∞), by { letI : Π i, star_add_monoid (B i) := λ i, infer_instance, apply_instance }) } instance infty_cstar_ring [∀ i, cstar_ring (B i)] : cstar_ring (lp B ∞) := { norm_star_mul_self := λ f, begin apply le_antisymm, { rw ←sq, refine lp.norm_le_of_forall_le (sq_nonneg ‖ f ‖) (λ i, _), simp only [lp.star_apply, cstar_ring.norm_star_mul_self, ←sq, infty_coe_fn_mul, pi.mul_apply], refine sq_le_sq' _ (lp.norm_apply_le_norm ennreal.top_ne_zero _ _), linarith [norm_nonneg (f i), norm_nonneg f] }, { rw [←sq, ←real.le_sqrt (norm_nonneg _) (norm_nonneg _)], refine lp.norm_le_of_forall_le (‖star f * f‖.sqrt_nonneg) (λ i, _), rw [real.le_sqrt (norm_nonneg _) (norm_nonneg _), sq, ←cstar_ring.norm_star_mul_self], exact lp.norm_apply_le_norm ennreal.top_ne_zero (star f * f) i, } end } end star_ring end non_unital_normed_ring section normed_ring variables {I : Type*} {B : I → Type*} [Π i, normed_ring (B i)] instance _root_.pre_lp.ring : ring (pre_lp B) := pi.ring variables [Π i, norm_one_class (B i)] lemma _root_.one_mem_ℓp_infty : mem_ℓp (1 : Π i, B i) ∞ := ⟨1, by { rintros i ⟨i, rfl⟩, exact norm_one.le,}⟩ variables (B) /-- The `𝕜`-subring of elements of `Π i : α, B i` whose `lp` norm is finite. This is `lp E ∞`, with extra structure. -/ def _root_.lp_infty_subring : subring (pre_lp B) := { carrier := {f | mem_ℓp f ∞}, one_mem' := one_mem_ℓp_infty, mul_mem' := λ f g hf hg, hf.infty_mul hg, .. lp B ∞ } variables {B} instance infty_ring : ring (lp B ∞) := (lp_infty_subring B).to_ring lemma _root_.mem_ℓp.infty_pow {f : Π i, B i} (hf : mem_ℓp f ∞) (n : ℕ) : mem_ℓp (f ^ n) ∞ := (lp_infty_subring B).pow_mem hf n lemma _root_.nat_cast_mem_ℓp_infty (n : ℕ) : mem_ℓp (n : Π i, B i) ∞ := nat_cast_mem (lp_infty_subring B) n lemma _root_.int_cast_mem_ℓp_infty (z : ℤ) : mem_ℓp (z : Π i, B i) ∞ := coe_int_mem (lp_infty_subring B) z @[simp] lemma infty_coe_fn_one : ⇑(1 : lp B ∞) = 1 := rfl @[simp] lemma infty_coe_fn_pow (f : lp B ∞) (n : ℕ) : ⇑(f ^ n) = f ^ n := rfl @[simp] lemma infty_coe_fn_nat_cast (n : ℕ) : ⇑(n : lp B ∞) = n := rfl @[simp] lemma infty_coe_fn_int_cast (z : ℤ) : ⇑(z : lp B ∞) = z := rfl instance [nonempty I] : norm_one_class (lp B ∞) := { norm_one := by simp_rw [lp.norm_eq_csupr, infty_coe_fn_one, pi.one_apply, norm_one, csupr_const]} instance infty_normed_ring : normed_ring (lp B ∞) := { .. lp.infty_ring, .. lp.non_unital_normed_ring } end normed_ring section normed_comm_ring variables {I : Type*} {B : I → Type*} [Π i, normed_comm_ring (B i)] [∀ i, norm_one_class (B i)] instance infty_comm_ring : comm_ring (lp B ∞) := { mul_comm := λ f g, by { ext, simp only [lp.infty_coe_fn_mul, pi.mul_apply, mul_comm] }, .. lp.infty_ring } instance infty_normed_comm_ring : normed_comm_ring (lp B ∞) := { .. lp.infty_comm_ring, .. lp.infty_normed_ring } end normed_comm_ring section algebra variables {I : Type*} {𝕜 : Type*} {B : I → Type*} variables [normed_field 𝕜] [Π i, normed_ring (B i)] [Π i, normed_algebra 𝕜 (B i)] /-- A variant of `pi.algebra` that lean can't find otherwise. -/ instance _root_.pi.algebra_of_normed_algebra : algebra 𝕜 (Π i, B i) := @pi.algebra I 𝕜 B _ _ $ λ i, normed_algebra.to_algebra instance _root_.pre_lp.algebra : algebra 𝕜 (pre_lp B) := _root_.pi.algebra_of_normed_algebra variables [∀ i, norm_one_class (B i)] lemma _root_.algebra_map_mem_ℓp_infty (k : 𝕜) : mem_ℓp (algebra_map 𝕜 (Π i, B i) k) ∞ := begin rw algebra.algebra_map_eq_smul_one, exact (one_mem_ℓp_infty.const_smul k : mem_ℓp (k • 1 : Π i, B i) ∞) end variables (𝕜 B) /-- The `𝕜`-subalgebra of elements of `Π i : α, B i` whose `lp` norm is finite. This is `lp E ∞`, with extra structure. -/ def _root_.lp_infty_subalgebra : subalgebra 𝕜 (pre_lp B) := { carrier := {f | mem_ℓp f ∞}, algebra_map_mem' := algebra_map_mem_ℓp_infty, .. lp_infty_subring B } variables {𝕜 B} instance infty_normed_algebra : normed_algebra 𝕜 (lp B ∞) := { ..(lp_infty_subalgebra 𝕜 B).algebra, ..(lp.normed_space : normed_space 𝕜 (lp B ∞)) } end algebra section single variables {𝕜 : Type*} [normed_ring 𝕜] [Π i, module 𝕜 (E i)] [∀ i, has_bounded_smul 𝕜 (E i)] variables [decidable_eq α] /-- The element of `lp E p` which is `a : E i` at the index `i`, and zero elsewhere. -/ protected def single (p) (i : α) (a : E i) : lp E p := ⟨ λ j, if h : j = i then eq.rec a h.symm else 0, begin refine (mem_ℓp_zero _).of_exponent_ge (zero_le p), refine (set.finite_singleton i).subset _, intros j, simp only [forall_exists_index, set.mem_singleton_iff, ne.def, dite_eq_right_iff, set.mem_set_of_eq, not_forall], rintros rfl, simp, end ⟩ protected lemma single_apply (p) (i : α) (a : E i) (j : α) : lp.single p i a j = if h : j = i then eq.rec a h.symm else 0 := rfl protected lemma single_apply_self (p) (i : α) (a : E i) : lp.single p i a i = a := by rw [lp.single_apply, dif_pos rfl] protected lemma single_apply_ne (p) (i : α) (a : E i) {j : α} (hij : j ≠ i) : lp.single p i a j = 0 := by rw [lp.single_apply, dif_neg hij] @[simp] protected lemma single_neg (p) (i : α) (a : E i) : lp.single p i (- a) = - lp.single p i a := begin ext j, by_cases hi : j = i, { subst hi, simp [lp.single_apply_self] }, { simp [lp.single_apply_ne p i _ hi] } end @[simp] protected lemma single_smul (p) (i : α) (a : E i) (c : 𝕜) : lp.single p i (c • a) = c • lp.single p i a := begin ext j, by_cases hi : j = i, { subst hi, simp [lp.single_apply_self] }, { simp [lp.single_apply_ne p i _ hi] } end protected lemma norm_sum_single (hp : 0 < p.to_real) (f : Π i, E i) (s : finset α) : ‖∑ i in s, lp.single p i (f i)‖ ^ p.to_real = ∑ i in s, ‖f i‖ ^ p.to_real := begin refine (has_sum_norm hp (∑ i in s, lp.single p i (f i))).unique _, simp only [lp.single_apply, coe_fn_sum, finset.sum_apply, finset.sum_dite_eq], have h : ∀ i ∉ s, ‖ite (i ∈ s) (f i) 0‖ ^ p.to_real = 0, { intros i hi, simp [if_neg hi, real.zero_rpow hp.ne'], }, have h' : ∀ i ∈ s, ‖f i‖ ^ p.to_real = ‖ite (i ∈ s) (f i) 0‖ ^ p.to_real, { intros i hi, rw if_pos hi }, simpa [finset.sum_congr rfl h'] using has_sum_sum_of_ne_finset_zero h, end protected lemma norm_single (hp : 0 < p.to_real) (f : Π i, E i) (i : α) : ‖lp.single p i (f i)‖ = ‖f i‖ := begin refine real.rpow_left_inj_on hp.ne' (norm_nonneg' _) (norm_nonneg _) _, simpa using lp.norm_sum_single hp f {i}, end protected lemma norm_sub_norm_compl_sub_single (hp : 0 < p.to_real) (f : lp E p) (s : finset α) : ‖f‖ ^ p.to_real - ‖f - ∑ i in s, lp.single p i (f i)‖ ^ p.to_real = ∑ i in s, ‖f i‖ ^ p.to_real := begin refine ((has_sum_norm hp f).sub (has_sum_norm hp (f - ∑ i in s, lp.single p i (f i)))).unique _, let F : α → ℝ := λ i, ‖f i‖ ^ p.to_real - ‖(f - ∑ i in s, lp.single p i (f i)) i‖ ^ p.to_real, have hF : ∀ i ∉ s, F i = 0, { intros i hi, suffices : ‖f i‖ ^ p.to_real - ‖f i - ite (i ∈ s) (f i) 0‖ ^ p.to_real = 0, { simpa only [F, coe_fn_sum, lp.single_apply, coe_fn_sub, pi.sub_apply, finset.sum_apply, finset.sum_dite_eq] using this, }, simp only [if_neg hi, sub_zero, sub_self] }, have hF' : ∀ i ∈ s, F i = ‖f i‖ ^ p.to_real, { intros i hi, simp only [F, coe_fn_sum, lp.single_apply, if_pos hi, sub_self, eq_self_iff_true, coe_fn_sub, pi.sub_apply, finset.sum_apply, finset.sum_dite_eq, sub_eq_self], simp [real.zero_rpow hp.ne'], }, have : has_sum F (∑ i in s, F i) := has_sum_sum_of_ne_finset_zero hF, rwa [finset.sum_congr rfl hF'] at this, end protected lemma norm_compl_sum_single (hp : 0 < p.to_real) (f : lp E p) (s : finset α) : ‖f - ∑ i in s, lp.single p i (f i)‖ ^ p.to_real = ‖f‖ ^ p.to_real - ∑ i in s, ‖f i‖ ^ p.to_real := by linarith [lp.norm_sub_norm_compl_sub_single hp f s] /-- The canonical finitely-supported approximations to an element `f` of `lp` converge to it, in the `lp` topology. -/ protected lemma has_sum_single [fact (1 ≤ p)] (hp : p ≠ ⊤) (f : lp E p) : has_sum (λ i : α, lp.single p i (f i : E i)) f := begin have hp₀ : 0 < p := zero_lt_one.trans_le (fact.out _), have hp' : 0 < p.to_real := ennreal.to_real_pos hp₀.ne' hp, have := lp.has_sum_norm hp' f, rw [has_sum, metric.tendsto_nhds] at this ⊢, intros ε hε, refine (this _ (real.rpow_pos_of_pos hε p.to_real)).mono _, intros s hs, rw ← real.rpow_lt_rpow_iff dist_nonneg (le_of_lt hε) hp', rw dist_comm at hs, simp only [dist_eq_norm, real.norm_eq_abs] at hs ⊢, have H : ‖∑ i in s, lp.single p i (f i : E i) - f‖ ^ p.to_real = ‖f‖ ^ p.to_real - ∑ i in s, ‖f i‖ ^ p.to_real, { simpa only [coe_fn_neg, pi.neg_apply, lp.single_neg, finset.sum_neg_distrib, neg_sub_neg, norm_neg, _root_.norm_neg] using lp.norm_compl_sum_single hp' (-f) s }, rw ← H at hs, have : |‖∑ i in s, lp.single p i (f i : E i) - f‖ ^ p.to_real| = ‖∑ i in s, lp.single p i (f i : E i) - f‖ ^ p.to_real, { simp only [real.abs_rpow_of_nonneg (norm_nonneg _), abs_norm] }, linarith end end single section topology open filter open_locale topology uniformity /-- The coercion from `lp E p` to `Π i, E i` is uniformly continuous. -/ lemma uniform_continuous_coe [_i : fact (1 ≤ p)] : uniform_continuous (coe : lp E p → Π i, E i) := begin have hp : p ≠ 0 := (zero_lt_one.trans_le _i.elim).ne', rw uniform_continuous_pi, intros i, rw normed_add_comm_group.uniformity_basis_dist.uniform_continuous_iff normed_add_comm_group.uniformity_basis_dist, intros ε hε, refine ⟨ε, hε, _⟩, rintros f g (hfg : ‖f - g‖ < ε), have : ‖f i - g i‖ ≤ ‖f - g‖ := norm_apply_le_norm hp (f - g) i, exact this.trans_lt hfg, end variables {ι : Type*} {l : filter ι} [filter.ne_bot l] lemma norm_apply_le_of_tendsto {C : ℝ} {F : ι → lp E ∞} (hCF : ∀ᶠ k in l, ‖F k‖ ≤ C) {f : Π a, E a} (hf : tendsto (id (λ i, F i) : ι → Π a, E a) l (𝓝 f)) (a : α) : ‖f a‖ ≤ C := begin have : tendsto (λ k, ‖F k a‖) l (𝓝 ‖f a‖) := (tendsto.comp (continuous_apply a).continuous_at hf).norm, refine le_of_tendsto this (hCF.mono _), intros k hCFk, exact (norm_apply_le_norm ennreal.top_ne_zero (F k) a).trans hCFk, end variables [_i : fact (1 ≤ p)] include _i lemma sum_rpow_le_of_tendsto (hp : p ≠ ∞) {C : ℝ} {F : ι → lp E p} (hCF : ∀ᶠ k in l, ‖F k‖ ≤ C) {f : Π a, E a} (hf : tendsto (id (λ i, F i) : ι → Π a, E a) l (𝓝 f)) (s : finset α) : ∑ (i : α) in s, ‖f i‖ ^ p.to_real ≤ C ^ p.to_real := begin have hp' : p ≠ 0 := (zero_lt_one.trans_le _i.elim).ne', have hp'' : 0 < p.to_real := ennreal.to_real_pos hp' hp, let G : (Π a, E a) → ℝ := λ f, ∑ a in s, ‖f a‖ ^ p.to_real, have hG : continuous G, { refine continuous_finset_sum s _, intros a ha, have : continuous (λ f : Π a, E a, f a):= continuous_apply a, exact this.norm.rpow_const (λ _, or.inr hp''.le) }, refine le_of_tendsto (hG.continuous_at.tendsto.comp hf) _, refine hCF.mono _, intros k hCFk, refine (lp.sum_rpow_le_norm_rpow hp'' (F k) s).trans _, exact real.rpow_le_rpow (norm_nonneg _) hCFk hp''.le, end /-- "Semicontinuity of the `lp` norm": If all sufficiently large elements of a sequence in `lp E p` have `lp` norm `≤ C`, then the pointwise limit, if it exists, also has `lp` norm `≤ C`. -/ lemma norm_le_of_tendsto {C : ℝ} {F : ι → lp E p} (hCF : ∀ᶠ k in l, ‖F k‖ ≤ C) {f : lp E p} (hf : tendsto (id (λ i, F i) : ι → Π a, E a) l (𝓝 f)) : ‖f‖ ≤ C := begin obtain ⟨i, hi⟩ := hCF.exists, have hC : 0 ≤ C := (norm_nonneg _).trans hi, unfreezingI { rcases eq_top_or_lt_top p with rfl | hp }, { apply norm_le_of_forall_le hC, exact norm_apply_le_of_tendsto hCF hf, }, { have : 0 < p := zero_lt_one.trans_le _i.elim, have hp' : 0 < p.to_real := ennreal.to_real_pos this.ne' hp.ne, apply norm_le_of_forall_sum_le hp' hC, exact sum_rpow_le_of_tendsto hp.ne hCF hf, } end /-- If `f` is the pointwise limit of a bounded sequence in `lp E p`, then `f` is in `lp E p`. -/ lemma mem_ℓp_of_tendsto {F : ι → lp E p} (hF : metric.bounded (set.range F)) {f : Π a, E a} (hf : tendsto (id (λ i, F i) : ι → Π a, E a) l (𝓝 f)) : mem_ℓp f p := begin obtain ⟨C, hC, hCF'⟩ := hF.exists_pos_norm_le, have hCF : ∀ k, ‖F k‖ ≤ C := λ k, hCF' _ ⟨k, rfl⟩, unfreezingI { rcases eq_top_or_lt_top p with rfl | hp }, { apply mem_ℓp_infty, use C, rintros _ ⟨a, rfl⟩, refine norm_apply_le_of_tendsto (eventually_of_forall hCF) hf a, }, { apply mem_ℓp_gen', exact sum_rpow_le_of_tendsto hp.ne (eventually_of_forall hCF) hf }, end /-- If a sequence is Cauchy in the `lp E p` topology and pointwise convergent to a element `f` of `lp E p`, then it converges to `f` in the `lp E p` topology. -/ lemma tendsto_lp_of_tendsto_pi {F : ℕ → lp E p} (hF : cauchy_seq F) {f : lp E p} (hf : tendsto (id (λ i, F i) : ℕ → Π a, E a) at_top (𝓝 f)) : tendsto F at_top (𝓝 f) := begin rw metric.nhds_basis_closed_ball.tendsto_right_iff, intros ε hε, have hε' : {p : (lp E p) × (lp E p) | ‖p.1 - p.2‖ < ε} ∈ 𝓤 (lp E p), { exact normed_add_comm_group.uniformity_basis_dist.mem_of_mem hε }, refine (hF.eventually_eventually hε').mono _, rintros n (hn : ∀ᶠ l in at_top, ‖(λ f, F n - f) (F l)‖ < ε), refine norm_le_of_tendsto (hn.mono (λ k hk, hk.le)) _, rw tendsto_pi_nhds, intros a, exact (hf.apply a).const_sub (F n a), end variables [Π a, complete_space (E a)] instance : complete_space (lp E p) := metric.complete_of_cauchy_seq_tendsto begin intros F hF, -- A Cauchy sequence in `lp E p` is pointwise convergent; let `f` be the pointwise limit. obtain ⟨f, hf⟩ := cauchy_seq_tendsto_of_complete (uniform_continuous_coe.comp_cauchy_seq hF), -- Since the Cauchy sequence is bounded, its pointwise limit `f` is in `lp E p`. have hf' : mem_ℓp f p := mem_ℓp_of_tendsto hF.bounded_range hf, -- And therefore `f` is its limit in the `lp E p` topology as well as pointwise. exact ⟨⟨f, hf'⟩, tendsto_lp_of_tendsto_pi hF hf⟩ end end topology end lp
928faf4c90c6249d076dc6e244c75305009ee058
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/rewrite5.lean
acfb30b7ede894b6f333c7f757d09b62295202b1
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
185
lean
import algebra.group open algebra variable {A : Type} variable [s : group A] include s theorem mul.right_inv (a : A) : a * a⁻¹ = 1 := by rewrite [-{a}inv_inv at {1}, mul.left_inv]
6c97875082e926eb858ad3b087e49c35598d1de6
e6b8240a90527fd55d42d0ec6649253d5d0bd414
/src/data/set/basic.lean
8ecc149ed40166ce0bd4a00dac2bd4745d1b7cbe
[ "Apache-2.0" ]
permissive
mattearnshaw/mathlib
ac90f9fb8168aa642223bea3ffd0286b0cfde44f
d8dc1445cf8a8c74f8df60b9f7a1f5cf10946666
refs/heads/master
1,606,308,351,137
1,576,594,130,000
1,576,594,130,000
228,666,195
0
0
Apache-2.0
1,576,603,094,000
1,576,603,093,000
null
UTF-8
Lean
false
false
60,898
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import tactic.basic tactic.finish data.subtype logic.unique open function /-! # Basic properties of sets This file provides some basic definitions related to sets and functions (e.g., `preimage`) not present in the core library, as well as extra lemmas. -/ /-! ### Set coercion to a type -/ namespace set instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ end set section set_coe universe u variables {α : Type u} theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.property namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[ext] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {α : Type u} {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /-! ### Lemmas about `mem` and `set_of` -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl lemma set_of_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := iff.rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {α} {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl @[simp] lemma set_of_mem {α} {s : set α} : {a | a ∈ s} = s := rfl /-! #### Lemmas about subsets -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {α : Type u} {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alterantive name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a, a ∈ s ∧ a ∉ t := by simp [subset_def, classical.not_forall] /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ s ≠ t instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ s ≠ t) := rfl lemma exists_of_ssubset {α : Type u} {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := classical.by_contradiction $ assume hn, have t ⊆ s, from assume a hat, classical.by_contradiction $ assume has, hn ⟨a, hat, has⟩, h.2 $ subset.antisymm h.1 this lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : ¬ (a ∉ s) ↔ a ∈ s := not_not /-! ### Non-empty sets -/ /-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩ theorem nonempty.ne_empty : s.nonempty → s ≠ ∅ | ⟨x, hx⟩ hs := by { rw hs at hx, exact hx } /-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/ protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h lemma nonempty.of_subset (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := let ⟨x, xt, xs⟩ := exists_of_ssubset ht in ⟨x, xt, xs⟩ lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr @[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty := ⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩ lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty | ⟨x⟩ := ⟨x, trivial⟩ /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem, set.nonempty] theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := ne_empty_iff_nonempty theorem exists_mem_of_ne_empty {s : set α} : s ≠ ∅ → ∃ x, x ∈ s := ne_empty_iff_exists_mem.1 theorem ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := ne_empty_iff_nonempty.2 ⟨x, h⟩ theorem coe_nonempty_iff_ne_empty {s : set α} : nonempty s ↔ s ≠ ∅ := nonempty_subtype.trans ne_empty_iff_exists_mem.symm -- TODO: remove when simplifier stops rewriting `a ≠ b` to `¬ a = b` theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem subset_ne_empty {s t : set α} (h : t ⊆ s) : t ≠ ∅ → s ≠ ∅ := mt (subset_eq_empty h) theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /-! ### Universal set. In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : inhabited α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 @[simp] lemma univ_eq_empty_iff {α : Type*} : (univ : set α) = ∅ ↔ ¬ nonempty α := eq_empty_iff_forall_not_mem.trans ⟨λ H ⟨x⟩, H x trivial, λ H x _, H ⟨x⟩⟩ lemma nonempty_iff_univ_ne_empty {α : Type*} : nonempty α ↔ (univ : set α) ≠ ∅ := by classical; exact iff_not_comm.1 univ_eq_empty_iff lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ @[simp] lemma univ_ne_empty {α} [h : nonempty α] : (univ : set α) ≠ ∅ := λ e, univ_eq_empty_iff.1 e h instance univ_decidable : decidable_pred (@set.univ α) := λ x, is_true trivial /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set α} (h : s ∩ t ≠ ∅) : t ≠ ∅ := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set α} (h : s ∩ t ≠ ∅) : s ≠ ∅ := by finish [ext_iff, iff_def] /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_def, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ theorem insert_ne_empty (a : α) (s : set α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /-! ### Lemmas about singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] @[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := set.ext $ λ n, (set.mem_singleton_iff).symm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := insert_nonempty _ _ @[simp] theorem singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := ext $ by simp @[simp] theorem union_singleton : s ∪ {a} = insert a s := by simp [singleton_def] @[simp] theorem singleton_union : {a} ∪ s = insert a s := by rw [union_comm, union_singleton] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ nonempty s := by simp [coe_nonempty_iff_ne_empty] instance unique_singleton {α : Type*} (a : α) : unique ↥({a} : set α) := { default := ⟨a, mem_singleton a⟩, uniq := begin intros x, apply subtype.coe_ext.2, apply eq_of_mem_singleton (subtype.mem x), end} /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := set.ext $ by simp /-! ### Lemmas about complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h lemma compl_set_of {α} (p : α → Prop) : - {a | p a} = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] lemma compl_empty_iff {s : set α} : -s = ∅ ↔ s = univ := by { split, intro h, rw [←compl_compl s, h, compl_empty], intro h, rw [h, compl_univ] } lemma compl_univ_iff {s : set α} : -s = univ ↔ s = ∅ := by rw [←compl_empty_iff, compl_compl] lemma nonempty_compl {s : set α} : nonempty (-s : set α) ↔ s ≠ univ := by { symmetry, rw [coe_nonempty_iff_ne_empty], apply not_congr, split, intro h, rw [h, compl_univ], intro h, rw [←compl_compl s, h, compl_empty] } theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ -b ∪ c := begin haveI := classical.prop_decidable, split, { intros h x xa, by_cases h' : x ∈ b, simp [h ⟨xa, h'⟩], simp [h'] }, intros h x, rintro ⟨xa, xb⟩, cases h xa, contradiction, assumption end /-! ### Lemmas about set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := set.ext $ λ _, and_or_distrib_left theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := set.ext $ λ _, and_or_distrib_right theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := set.ext $ λ _, or_and_distrib_left theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := set.ext $ λ _, or_and_distrib_right theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] @[simp] lemma empty_diff {α : Type*} (s : set α) : (∅ \ s : set α) = ∅ := eq_empty_of_subset_empty $ assume x ⟨hx, _⟩, hx theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma subset_insert_diff (s t : set α) : s ⊆ (s \ t) ∪ t := by rw [union_comm, ←diff_subset_iff] @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := ext $ by simp lemma mem_diff_singleton {s s' : set α} {t : set (set α)} : s ∈ t \ {s'} ↔ (s ∈ t ∧ s ≠ s') := by simp lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} : s ∈ t \ {∅} ↔ (s ∈ t ∧ nonempty s) := by simp [coe_nonempty_iff_ne_empty] /- powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /- inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _ @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl @[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : α → β) (a : set α) : Prop := ∀ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem mono_image {f : α → β} {s t : set α} (h : s ⊆ t) : f '' s ⊆ f '' t := assume x ⟨y, hy, y_eq⟩, y_eq ▸ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /- A common special case of `image_congr` -/ lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s := image_congr (λx _, h x) theorem image_eq_image_of_eq_on {f₁ f₂ : α → β} {s : set α} (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s := (image_comp g f s).symm theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := ext $ λ x, by simp [image]; rw eq_comm theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} := ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _, λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩ @[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ := by simp only [eq_empty_iff_forall_not_mem]; exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ lemma inter_singleton_ne_empty {s : set α} {a : α} : s ∩ {a} ≠ ∅ ↔ a ∈ s := by finish [set.inter_singleton_eq_empty] theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set α) : id '' s = s := ext $ by simp /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := image_id s theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) lemma nonempty_image (f : α → β) {s : set α} : nonempty s → nonempty (f '' s) | ⟨⟨x, hx⟩⟩ := ⟨⟨f x, mem_image_of_mem f hx⟩⟩ /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq]) (assume eq, eq ▸ rfl) lemma surjective_preimage {f : β → α} (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma injective_image {f : α → β} (hf : injective f) : injective (('') f) := assume s t, (image_eq_image hf).1 lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) /-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/ def image_factorization (f : α → β) (s : set α) : s → f '' s := λ p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : α → β} {s : set α} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ λ p, rfl lemma surjective_onto_image {f : α → β} {s : set α} : surjective (image_factorization f s) := λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) /-! ### Lemmas about range of a function. -/ section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := ⟨assume ⟨a, ⟨i, eq⟩, h⟩, ⟨i, eq.symm ▸ h⟩, assume ⟨i, h⟩, ⟨f i, mem_range_self _, h⟩⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := ext $ by simp [image, range] theorem image_subset_range {ι : Type*} (f : ι → β) (s : set ι) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {s : set α} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g := by rw range_comp; apply image_subset_range lemma range_ne_empty_iff_nonempty : range f ≠ ∅ ↔ nonempty ι := ne_empty_iff_exists_mem.trans ⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩ lemma range_ne_empty [h : nonempty ι] (f : ι → α) : range f ≠ ∅ := range_ne_empty_iff_nonempty.2 h @[simp] lemma range_eq_empty {α : Type u} {β : Type v} {f : α → β} : range f = ∅ ↔ ¬ nonempty α := by rw ← set.image_univ; simp [-set.image_univ] theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma range_const_subset {c : α} : range (λx:ι, c) ⊆ {c} := range_subset_iff.2 $ λ x, or.inl rfl @[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c} | ⟨x⟩ c := subset.antisymm range_const_subset $ assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x /-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/ def range_factorization (f : ι → β) : ι → range f := λ i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ι → β} : subtype.val ∘ range_factorization f = f := funext $ λ i, rfl lemma surjective_onto_range : surjective (range_factorization f) := λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x.1) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } @[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) : range (sum.elim f g) = range f ∪ range g := by simp [set.ext_iff, mem_range] lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} : range (if p then f else g) ⊆ range f ∪ range g := begin by_cases h : p, {rw if_pos h, exact subset_union_left _ _}, {rw if_neg h, exact subset_union_right _ _} end lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} : range (λ x, if p x then f x else g x) ⊆ range f ∪ range g := begin rw range_subset_iff, intro x, by_cases h : p x, simp [if_pos h, mem_union, mem_range_self], simp [if_neg h, mem_union, mem_range_self] end end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y theorem pairwise_on.mono {s t : set α} {r} (h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r := λ x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop} (H : ∀ a b, r a b → r' a b) (hp : pairwise_on s r) : pairwise_on s r' := λ x xs y ys h, H _ _ (hp x xs y ys h) end set open set /-! ### Image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ @[simp] lemma val_range {p : α → Prop} : set.range (@subtype.val _ p) = {x | p x} := by rw ← set.image_univ; simp [-set.image_univ, val_image] @[simp] lemma range_val (s : set α) : range (subtype.val : s → α) = s := val_range theorem val_image_subset (s : set α) (t : set (subtype s)) : t.image val ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem val_image_univ (s : set α) : @val _ s '' set.univ = s := set.eq_of_subset_of_subset (val_image_subset _ _) (λ x xs, ⟨⟨x, xs⟩, ⟨set.mem_univ _, rfl⟩⟩) theorem image_preimage_val (s t : set α) : (@subtype.val _ s) '' ((@subtype.val _ s) ⁻¹' t) = t ∩ s := begin ext x, simp, split, { rintros ⟨y, ys, yt, yx⟩, rw ←yx, exact ⟨yt, ys⟩ }, rintros ⟨xt, xs⟩, exact ⟨x, xs, xt, rfl⟩ end theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((@subtype.val _ s) ⁻¹' t = (@subtype.val _ s) ⁻¹' u) ↔ (t ∩ s = u ∩ s) := begin rw [←image_preimage_val, ←image_preimage_val], split, { intro h, rw h }, intro h, exact set.injective_image (val_injective) h end lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (subtype.val '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨subtype.val '' s, _, hs⟩, convert image_subset_range _ _, rw [range_val] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨subtype.val ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_val], exact hs₁ end end subtype namespace set section range variable {α : Type*} @[simp] lemma subtype.val_range {p : α → Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype.val_image] @[simp] lemma range_coe_subtype (s : set α) : range (coe : s → α) = s := subtype.val_range end range /-! ### Lemmas about cartesian product of sets -/ section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma prod_eq (s : set α) (t : set β) : set.prod s t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ lemma prod_subset_iff {P : set (α × β)} : (set.prod s t ⊆ P) ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ xin _ yin, h (mk_mem_prod xin yin), λ h _ pin, by { cases mem_prod.1 pin with hs ht, simpa using h _ hs _ ht }⟩ @[simp] theorem prod_empty : set.prod s ∅ = (∅ : set (α × β)) := ext $ by simp [set.prod] @[simp] theorem empty_prod : set.prod ∅ t = (∅ : set (α × β)) := ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] theorem prod_range_univ_eq {α β γ} {m₁ : α → γ} : set.prod (range m₁) (univ : set β) = range (λp:α×β, (m₁ p.1, p.2)) := ext $ by simp [range] theorem prod_univ_range_eq {α β δ} {m₂ : β → δ} : set.prod (univ : set α) (range m₂) = range (λp:α×β, (p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := ext $ by simp [set.prod] theorem nonempty.prod : s.nonempty → t.nonempty → (s.prod t).nonempty | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨(x, y), ⟨hx, hy⟩⟩ theorem nonempty.fst : (s.prod t).nonempty → s.nonempty | ⟨p, hp⟩ := ⟨p.1, hp.1⟩ theorem nonempty.snd : (s.prod t).nonempty → t.nonempty | ⟨p, hp⟩ := ⟨p.2, hp.2⟩ theorem prod_nonempty_iff : (s.prod t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, nonempty.prod h.1 h.2⟩ theorem prod_ne_empty_iff : s.prod t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := by simp only [ne_empty_iff_nonempty, prod_nonempty_iff] theorem prod_eq_empty_iff {s : set α} {t : set β} : set.prod s t = ∅ ↔ (s = ∅ ∨ t = ∅) := suffices (¬ set.prod s t ≠ ∅) ↔ (¬ s ≠ ∅ ∨ ¬ t ≠ ∅), by simpa only [(≠), classical.not_not], by classical; rw [prod_ne_empty_iff, not_and_distrib] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' (set.prod s t) ⊆ s := λ _ h, let ⟨_, ⟨h₂, _⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_fst (s : set α) (t : set β) : set.prod s t ⊆ prod.fst ⁻¹' s := image_subset_iff.1 (fst_image_prod_subset s t) lemma fst_image_prod (s : set β) {t : set α} (ht : t ≠ ∅) : prod.fst '' (set.prod s t) = s := set.subset.antisymm (fst_image_prod_subset _ _) $ λ y y_in, let (⟨x, x_in⟩ : ∃ (x : α), x ∈ t) := set.exists_mem_of_ne_empty ht in ⟨(y, x), ⟨y_in, x_in⟩, rfl⟩ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' (set.prod s t) ⊆ t := λ _ h, let ⟨_, ⟨_, h₂⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_snd (s : set α) (t : set β) : set.prod s t ⊆ prod.snd ⁻¹' t := image_subset_iff.1 (snd_image_prod_subset s t) lemma snd_image_prod {s : set α} (hs : s ≠ ∅) (t : set β) : prod.snd '' (set.prod s t) = t := set.subset.antisymm (snd_image_prod_subset _ _) $ λ y y_in, let (⟨x, x_in⟩ : ∃ (x : α), x ∈ s) := set.exists_mem_of_ne_empty hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : (set.prod s t ⊆ set.prod s₁ t₁) ↔ (s ⊆ s₁ ∧ t ⊆ t₁) ∨ (s = ∅) ∨ (t = ∅) := begin classical, by_cases h : set.prod s t = ∅, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s ≠ ∅ ∧ t ≠ ∅, by rwa [← ne.def, prod_ne_empty_iff] at h, split, { assume H : set.prod s t ⊆ set.prod s₁ t₁, have h' : s₁ ≠ ∅ ∧ t₁ ≠ ∅ := prod_ne_empty_iff.1 (subset_ne_empty H h), refine or.inl ⟨_, _⟩, show s ⊆ s₁, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ h'.2] at this }, show t ⊆ t₁, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod h'.1] at this } }, { assume H, simp [st] at H, exact prod_mono H.1 H.2 } } end end prod section pi variables {α : Type*} {π : α → Type*} def pi (i : set α) (s : Πa, set (π a)) : set (Πa, π a) := { f | ∀a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Πa, set (π a)) : pi ∅ s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : α) (i : set α) (s : Πa, set (π a)) : pi (insert a i) s = ((λf, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : α) (s : Πa, set (π a)) : pi {a} s = ((λf:(Πa, π a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : α → Prop} [h : decidable_pred p] (i : set α) (s t : Πa, set (π a)) : pi i (λa, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | ¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi section inclusion variable {α : Type*} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion {s t : set α} (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self {s : set α} (x : s) : inclusion (set.subset.refl _) x = x := by cases x; refl @[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x := by cases x; refl lemma inclusion_injective {s t : set α} (h : s ⊆ t) : function.injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext.2 ∘ subtype.ext.1 end inclusion end set
67572cbdbd212cb1caaf86188b40025346b5b487
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/05_Interacting_with_Lean.org.20.lean
f21c9b993c4a6f1967a470b97d097827c3a7c9b2
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
228
lean
/- page 74 -/ import standard import data.bool data.nat open bool nat -- BEGIN definition bool.to_nat (b : bool) : nat := bool.cond b 1 0 attribute bool.to_nat [coercion] -- END eval 2 + ff eval 2 + tt eval tt + tt + tt + ff
a49176f8c2162981838e30eb78e6b903394fb2b2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/ring/opposite.lean
79f69ea9d9d64b02496b4e84d661eb410b045441
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
11,501
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.group_with_zero.basic import algebra.group.opposite import algebra.hom.ring /-! # Ring structures on the multiplicative opposite > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes u v variables (α : Type u) namespace mul_opposite instance [distrib α] : distrib αᵐᵒᵖ := { left_distrib := λ x y z, unop_injective $ add_mul (unop y) (unop z) (unop x), right_distrib := λ x y z, unop_injective $ mul_add (unop z) (unop x) (unop y), .. mul_opposite.has_add α, .. mul_opposite.has_mul α } instance [mul_zero_class α] : mul_zero_class αᵐᵒᵖ := { zero := 0, mul := (*), zero_mul := λ x, unop_injective $ mul_zero $ unop x, mul_zero := λ x, unop_injective $ zero_mul $ unop x } instance [mul_zero_one_class α] : mul_zero_one_class αᵐᵒᵖ := { .. mul_opposite.mul_zero_class α, .. mul_opposite.mul_one_class α } instance [semigroup_with_zero α] : semigroup_with_zero αᵐᵒᵖ := { .. mul_opposite.semigroup α, .. mul_opposite.mul_zero_class α } instance [monoid_with_zero α] : monoid_with_zero αᵐᵒᵖ := { .. mul_opposite.monoid α, .. mul_opposite.mul_zero_one_class α } instance [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵐᵒᵖ := { .. mul_opposite.add_comm_monoid α, .. mul_opposite.mul_zero_class α, .. mul_opposite.distrib α } instance [non_unital_semiring α] : non_unital_semiring αᵐᵒᵖ := { .. mul_opposite.semigroup_with_zero α, .. mul_opposite.non_unital_non_assoc_semiring α } instance [non_assoc_semiring α] : non_assoc_semiring αᵐᵒᵖ := { .. mul_opposite.add_monoid_with_one α, .. mul_opposite.mul_zero_one_class α, .. mul_opposite.non_unital_non_assoc_semiring α } instance [semiring α] : semiring αᵐᵒᵖ := { .. mul_opposite.non_unital_semiring α, .. mul_opposite.non_assoc_semiring α, .. mul_opposite.monoid_with_zero α } instance [non_unital_comm_semiring α] : non_unital_comm_semiring αᵐᵒᵖ := { .. mul_opposite.non_unital_semiring α, .. mul_opposite.comm_semigroup α } instance [comm_semiring α] : comm_semiring αᵐᵒᵖ := { .. mul_opposite.semiring α, .. mul_opposite.comm_semigroup α } instance [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵐᵒᵖ := { .. mul_opposite.add_comm_group α, .. mul_opposite.mul_zero_class α, .. mul_opposite.distrib α} instance [non_unital_ring α] : non_unital_ring αᵐᵒᵖ := { .. mul_opposite.add_comm_group α, .. mul_opposite.semigroup_with_zero α, .. mul_opposite.distrib α} instance [non_assoc_ring α] : non_assoc_ring αᵐᵒᵖ := { .. mul_opposite.add_comm_group α, .. mul_opposite.mul_zero_one_class α, .. mul_opposite.distrib α, .. mul_opposite.add_group_with_one α } instance [ring α] : ring αᵐᵒᵖ := { .. mul_opposite.monoid α, .. mul_opposite.non_assoc_ring α } instance [non_unital_comm_ring α] : non_unital_comm_ring αᵐᵒᵖ := { .. mul_opposite.non_unital_ring α, .. mul_opposite.non_unital_comm_semiring α } instance [comm_ring α] : comm_ring αᵐᵒᵖ := { .. mul_opposite.ring α, .. mul_opposite.comm_semiring α } instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors αᵐᵒᵖ := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)), or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_injective H) (λ hy, or.inr $ unop_injective $ hy) (λ hx, or.inl $ unop_injective $ hx), } instance [ring α] [is_domain α] : is_domain αᵐᵒᵖ := no_zero_divisors.to_is_domain _ instance [group_with_zero α] : group_with_zero αᵐᵒᵖ := { mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ unop_injective.ne hx, inv_zero := unop_injective inv_zero, .. mul_opposite.monoid_with_zero α, .. mul_opposite.div_inv_monoid α, .. mul_opposite.nontrivial α } end mul_opposite namespace add_opposite instance [distrib α] : distrib αᵃᵒᵖ := { left_distrib := λ x y z, unop_injective $ @mul_add α _ _ _ x z y, right_distrib := λ x y z, unop_injective $ @add_mul α _ _ _ y x z, .. add_opposite.has_add α, .. @add_opposite.has_mul α _} instance [mul_zero_class α] : mul_zero_class αᵃᵒᵖ := { zero := 0, mul := (*), zero_mul := λ x, unop_injective $ zero_mul $ unop x, mul_zero := λ x, unop_injective $ mul_zero $ unop x } instance [mul_zero_one_class α] : mul_zero_one_class αᵃᵒᵖ := { .. add_opposite.mul_zero_class α, .. add_opposite.mul_one_class α } instance [semigroup_with_zero α] : semigroup_with_zero αᵃᵒᵖ := { .. add_opposite.semigroup α, .. add_opposite.mul_zero_class α } instance [monoid_with_zero α] : monoid_with_zero αᵃᵒᵖ := { .. add_opposite.monoid α, .. add_opposite.mul_zero_one_class α } instance [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵃᵒᵖ := { .. add_opposite.add_comm_monoid α, .. add_opposite.mul_zero_class α, .. add_opposite.distrib α } instance [non_unital_semiring α] : non_unital_semiring αᵃᵒᵖ := { .. add_opposite.semigroup_with_zero α, .. add_opposite.non_unital_non_assoc_semiring α } instance [non_assoc_semiring α] : non_assoc_semiring αᵃᵒᵖ := { ..add_opposite.mul_zero_one_class α, ..add_opposite.non_unital_non_assoc_semiring α, ..add_opposite.add_comm_monoid_with_one _ } instance [semiring α] : semiring αᵃᵒᵖ := { .. add_opposite.non_unital_semiring α, .. add_opposite.non_assoc_semiring α, .. add_opposite.monoid_with_zero α } instance [non_unital_comm_semiring α] : non_unital_comm_semiring αᵃᵒᵖ := { .. add_opposite.non_unital_semiring α, .. add_opposite.comm_semigroup α } instance [comm_semiring α] : comm_semiring αᵃᵒᵖ := { .. add_opposite.semiring α, .. add_opposite.comm_semigroup α } instance [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵃᵒᵖ := { .. add_opposite.add_comm_group α, .. add_opposite.mul_zero_class α, .. add_opposite.distrib α} instance [non_unital_ring α] : non_unital_ring αᵃᵒᵖ := { .. add_opposite.add_comm_group α, .. add_opposite.semigroup_with_zero α, .. add_opposite.distrib α} instance [non_assoc_ring α] : non_assoc_ring αᵃᵒᵖ := { .. add_opposite.add_comm_group_with_one α, .. add_opposite.mul_zero_one_class α, .. add_opposite.distrib α} instance [ring α] : ring αᵃᵒᵖ := { .. add_opposite.non_assoc_ring α, .. add_opposite.semiring α } instance [non_unital_comm_ring α] : non_unital_comm_ring αᵃᵒᵖ := { .. add_opposite.non_unital_ring α, .. add_opposite.non_unital_comm_semiring α } instance [comm_ring α] : comm_ring αᵃᵒᵖ := { .. add_opposite.ring α, .. add_opposite.comm_semiring α } instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors αᵃᵒᵖ := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)), or.imp (λ hx, unop_injective hx) (λ hy, unop_injective hy) ((@eq_zero_or_eq_zero_of_mul_eq_zero α _ _ _ _ _) $ op_injective H) } instance [ring α] [is_domain α] : is_domain αᵃᵒᵖ := no_zero_divisors.to_is_domain _ instance [group_with_zero α] : group_with_zero αᵃᵒᵖ := { mul_inv_cancel := λ x hx, unop_injective $ mul_inv_cancel $ unop_injective.ne hx, inv_zero := unop_injective inv_zero, .. add_opposite.monoid_with_zero α, .. add_opposite.div_inv_monoid α, .. add_opposite.nontrivial α } end add_opposite open mul_opposite /-- A non-unital ring homomorphism `f : R →ₙ+* S` such that `f x` commutes with `f y` for all `x, y` defines a non-unital ring homomorphism to `Sᵐᵒᵖ`. -/ @[simps {fully_applied := ff}] def non_unital_ring_hom.to_opposite {R S : Type*} [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] (f : R →ₙ+* S) (hf : ∀ x y, commute (f x) (f y)) : R →ₙ+* Sᵐᵒᵖ := { to_fun := mul_opposite.op ∘ f, .. ((op_add_equiv : S ≃+ Sᵐᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵐᵒᵖ), .. f.to_mul_hom.to_opposite hf } /-- A non-unital ring homomorphism `f : R →ₙ* S` such that `f x` commutes with `f y` for all `x, y` defines a non-unital ring homomorphism from `Rᵐᵒᵖ`. -/ @[simps {fully_applied := ff}] def non_unital_ring_hom.from_opposite {R S : Type*} [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] (f : R →ₙ+* S) (hf : ∀ x y, commute (f x) (f y)) : Rᵐᵒᵖ →ₙ+* S := { to_fun := f ∘ mul_opposite.unop, .. (f.to_add_monoid_hom.comp (op_add_equiv : R ≃+ Rᵐᵒᵖ).symm.to_add_monoid_hom : Rᵐᵒᵖ →+ S), .. f.to_mul_hom.from_opposite hf } /-- A non-unital ring hom `α →ₙ+* β` can equivalently be viewed as a non-unital ring hom `αᵐᵒᵖ →+* βᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[simps] def non_unital_ring_hom.op {α β} [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] : (α →ₙ+* β) ≃ (αᵐᵒᵖ →ₙ+* βᵐᵒᵖ) := { to_fun := λ f, { ..f.to_add_monoid_hom.mul_op, ..f.to_mul_hom.op }, inv_fun := λ f, { ..f.to_add_monoid_hom.mul_unop, ..f.to_mul_hom.unop }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of a non-unital ring hom `αᵐᵒᵖ →ₙ+* βᵐᵒᵖ`. Inverse to `non_unital_ring_hom.op`. -/ @[simp] def non_unital_ring_hom.unop {α β} [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] : (αᵐᵒᵖ →ₙ+* βᵐᵒᵖ) ≃ (α →ₙ+* β) := non_unital_ring_hom.op.symm /-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines a ring homomorphism to `Sᵐᵒᵖ`. -/ @[simps {fully_applied := ff}] def ring_hom.to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : R →+* Sᵐᵒᵖ := { to_fun := mul_opposite.op ∘ f, .. ((op_add_equiv : S ≃+ Sᵐᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵐᵒᵖ), .. f.to_monoid_hom.to_opposite hf } /-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines a ring homomorphism from `Rᵐᵒᵖ`. -/ @[simps {fully_applied := ff}] def ring_hom.from_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : Rᵐᵒᵖ →+* S := { to_fun := f ∘ mul_opposite.unop, .. (f.to_add_monoid_hom.comp (op_add_equiv : R ≃+ Rᵐᵒᵖ).symm.to_add_monoid_hom : Rᵐᵒᵖ →+ S), .. f.to_monoid_hom.from_opposite hf } /-- A ring hom `α →+* β` can equivalently be viewed as a ring hom `αᵐᵒᵖ →+* βᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[simps] def ring_hom.op {α β} [non_assoc_semiring α] [non_assoc_semiring β] : (α →+* β) ≃ (αᵐᵒᵖ →+* βᵐᵒᵖ) := { to_fun := λ f, { ..f.to_add_monoid_hom.mul_op, ..f.to_monoid_hom.op }, inv_fun := λ f, { ..f.to_add_monoid_hom.mul_unop, ..f.to_monoid_hom.unop }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of a ring hom `αᵐᵒᵖ →+* βᵐᵒᵖ`. Inverse to `ring_hom.op`. -/ @[simp] def ring_hom.unop {α β} [non_assoc_semiring α] [non_assoc_semiring β] : (αᵐᵒᵖ →+* βᵐᵒᵖ) ≃ (α →+* β) := ring_hom.op.symm
bacf60cc1422142d49eb42ae170170e66264713a
dfbb669f3f58ceb57cb207dcfab5726a07425b03
/vscode-lean4/test/test-fixtures/multi/foo/Foo.lean
83a5fe84cc63cd33489eba8333622c645d0a1c78
[ "Apache-2.0" ]
permissive
leanprover/vscode-lean4
8bcf7f06867b3c1d42007fe6da863a7a17444dbb
6ef0bfa668bdeaad0979e6df10551d42fcc01094
refs/heads/master
1,692,247,771,767
1,691,608,804,000
1,691,608,804,000
325,845,305
64
24
Apache-2.0
1,694,176,429,000
1,609,435,614,000
TypeScript
UTF-8
Lean
false
false
45
lean
def hello := "foo" #eval Lean.versionString
decbe180f96c9086c2ea0e455cb9c9afc673f88c
6214e13b31733dc9aeb4833db6a6466005763162
/src/vcgen.lean
8ce6a5a24ea59b416d3e95e9471ef8985c8373ae
[]
no_license
joshua0pang/esverify-theory
272a250445f3aeea49a7e72d1ab58c2da6618bbe
8565b123c87b0113f83553d7732cd6696c9b5807
refs/heads/master
1,585,873,849,081
1,527,304,393,000
1,527,304,393,000
154,901,199
1
0
null
1,540,593,067,000
1,540,593,067,000
null
UTF-8
Lean
false
false
16,170
lean
import .definitions3 .qi lemma exp.vcgen.extension {P: prop} {e: exp} {Q: propctx}: (P ⊢ e : Q) → (P ⊩ e : Q) := begin assume e_verified: P ⊢ e : Q, induction e_verified, case exp.vcgen.tru P y e' Q y_not_in_P e'_verified ih { apply exp.dvcgen.tru, from y_not_in_P, from ih }, case exp.vcgen.fals P y e' Q y_not_in_P e'_verified ih { apply exp.dvcgen.fals, from y_not_in_P, from ih }, case exp.vcgen.num P y n e' Q y_not_in_P e'_verified ih { apply exp.dvcgen.num, from y_not_in_P, from ih }, case exp.vcgen.func P f fx R S e₁ e₂ Q₁ Q₂ f_not_in_P fx_not_in_P f_neq_fx fx_in_R fv_R fv_S e₁_verified e₂_verified func_vc ih₁ ih₂ { apply exp.dvcgen.func, from f_not_in_P, from fx_not_in_P, from f_neq_fx, from fx_in_R, from fv_R, from fv_S, from ih₁, from ih₂, from vc_valid_from_inst_valid func_vc }, case exp.vcgen.unop op P e' x₁ y Q x_free_in_P y_not_in_P e'_verified vc_valid ih { apply exp.dvcgen.unop, from x_free_in_P, from y_not_in_P, from ih, from vc_valid_from_inst_valid vc_valid }, case exp.vcgen.binop op P e' x₁ x₂ y Q x₁_free_in_P x₂_free_in_P y_not_in_P e'_verified vc_valid ih { apply exp.dvcgen.binop, from x₁_free_in_P, from x₂_free_in_P, from y_not_in_P, from ih, from vc_valid_from_inst_valid vc_valid }, case exp.vcgen.app P y f e' x₁ Q f_free_in_P x₁_free_in_P y_not_in_P e'_verified vc_valid ih { apply exp.dvcgen.app, from f_free_in_P, from x₁_free_in_P, from y_not_in_P, from ih, from vc_valid_from_inst_valid vc_valid }, case exp.vcgen.ite P e₁ e₂ y Q₁ Q₂ y_free_in_P e₁_verified e₂_verified vc_valid ih₁ ih₂ { apply exp.dvcgen.ite, from y_free_in_P, from ih₁, from ih₂, from vc_valid_from_inst_valid vc_valid }, case exp.vcgen.return P y y_free_in_P { apply exp.dvcgen.return, from y_free_in_P } end lemma exp.dvcgen.return.inv {P: prop} {x: var} {Q: propctx}: (P ⊩ exp.return x : Q) → x ∈ FV P := assume return_verified: P ⊩ exp.return x : Q, begin cases return_verified, case exp.dvcgen.return x_free { show x ∈ FV P, from x_free } end lemma stack.dvcgen.top.inv {R: spec} {σ: env} {e: exp} {Q: propctx}: (⊩ₛ (R, σ, e) : Q) → ∃P Q₂, (⊩ σ: P) ∧ (FV R.to_prop ⊆ FV P) ∧ (σ ⊨ R.to_prop.to_vc) ∧ (R ⋀ P ⊩ e: Q₂) := assume top_verified: ⊩ₛ (R, σ, e) : Q, begin cases top_verified, case stack.dvcgen.top P Q env_verified fv_R R_valid e_verified { show ∃P Q₂, (⊩ σ: P) ∧ (FV R.to_prop ⊆ FV P) ∧ (σ ⊨ R.to_prop.to_vc) ∧ (R ⋀ P ⊩ e: Q₂), from exists.intro P (exists.intro Q ⟨env_verified, ⟨fv_R, ⟨R_valid, e_verified⟩⟩⟩) } end lemma env.dvcgen.inv {σ: env} {P: prop} {x: var} {v: value}: (⊩ σ : P) → (σ x = v) → ∃σ' Q', ⊩ (σ'[x↦v]) : Q' := assume env_verified: ⊩ σ : P, assume σ_x_is_v: σ x = v, show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', by begin induction env_verified, case env.dvcgen.empty { from have env.apply env.empty x = none, by unfold env.apply, have some v = none, from eq.trans σ_x_is_v.symm this, show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from false.elim (option.no_confusion this) }, case env.dvcgen.tru σ' y Q y_not_in_σ' σ'_verified ih { from have env.apply (σ'[y↦value.true]) x = v, from σ_x_is_v, have h1: (if y = x ∧ option.is_none (σ'.apply x) then ↑value.true else σ'.apply x) = v, by { unfold env.apply at this, from this }, if h2: y = x ∧ option.is_none (σ'.apply x) then ( have (↑value.true) = ↑v, by { simp[h2] at h1, from h1 }, have v_is_true: v = value.true, from (option.some.inj this).symm, have x_not_in_σ': x ∉ σ', from h2.left ▸ y_not_in_σ', have ⊩ (σ'[x↦value.true]) : Q ⋀ x ≡ value.true, from env.dvcgen.tru x_not_in_σ' σ'_verified, have ⊩ (σ'[x↦v]) : Q ⋀ x ≡ value.true, from v_is_true.symm ▸ this, show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from exists.intro σ' (exists.intro (Q ⋀ x ≡ value.true) this) ) else ( have (σ'.apply x) = v, by { simp[h2] at h1, from h1 }, show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from ih this ) }, case env.dvcgen.fls σ' y Q y_not_in_σ' σ'_verified ih { from have env.apply (σ'[y↦value.false]) x = v, from σ_x_is_v, have h1: (if y = x ∧ option.is_none (σ'.apply x) then ↑value.false else σ'.apply x) = v, by { unfold env.apply at this, from this }, if h2: y = x ∧ option.is_none (σ'.apply x) then ( have (↑value.false) = ↑v, by { simp[h2] at h1, from h1 }, have v_is_false: v = value.false, from (option.some.inj this).symm, have x_not_in_σ': x ∉ σ', from h2.left ▸ y_not_in_σ', have ⊩ (σ'[x↦value.false]) : Q ⋀ x ≡ value.false, from env.dvcgen.fls x_not_in_σ' σ'_verified, have ⊩ (σ'[x↦v]) : Q ⋀ x ≡ value.false, from v_is_false.symm ▸ this, show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from exists.intro σ' (exists.intro (Q ⋀ x ≡ value.false) this) ) else ( have (σ'.apply x) = v, by { simp[h2] at h1, from h1 }, show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from ih this ) }, case env.dvcgen.num n σ' y Q y_not_in_σ' σ'_verified ih { from have env.apply (σ'[y↦value.num n]) x = v, from σ_x_is_v, have h1: (if y = x ∧ option.is_none (σ'.apply x) then ↑(value.num n) else σ'.apply x) = v, by { unfold env.apply at this, from this }, if h2: y = x ∧ option.is_none (σ'.apply x) then ( have ↑(value.num n) = ↑v, by { simp[h2] at h1, from h1 }, have v_is_num: v = value.num n, from (option.some.inj this).symm, have x_not_in_σ': x ∉ σ', from h2.left ▸ y_not_in_σ', have ⊩ (σ'[x↦value.num n]) : Q ⋀ x ≡ value.num n, from env.dvcgen.num x_not_in_σ' σ'_verified, have ⊩ (σ'[x↦v]) : Q ⋀ x ≡ value.num n, from v_is_num.symm ▸ this, show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from exists.intro σ' (exists.intro (Q ⋀ x ≡ value.num n) this) ) else ( have (σ'.apply x) = v, by { simp[h2] at h1, from h1 }, show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from ih this ) }, case env.dvcgen.func f σ₂ σ₁ g gx R S e Q₁ Q₂ Q₃ f_not_in_σ₁ g_not_in_σ₂ gx_not_in_σ₂ g_neq_gx σ₁_verified σ₂_verified x_free_in_R fv_R fv_S e_verified func_vc ih₁ ih₂ { from have env.apply (σ₁[f↦value.func g gx R S e σ₂]) x = v, from σ_x_is_v, have h1: (if f = x ∧ option.is_none (σ₁.apply x) then ↑(value.func g gx R S e σ₂) else σ₁.apply x) = v, by { unfold env.apply at this, from this }, if h2: f = x ∧ option.is_none (σ₁.apply x) then ( have ↑(value.func g gx R S e σ₂) = ↑v, by { simp[h2] at h1, from h1 }, have v_is_num: v = value.func g gx R S e σ₂, from (option.some.inj this).symm, have x_not_in_σ₁: x ∉ σ₁, from h2.left ▸ f_not_in_σ₁, have ⊩ (σ₁[x↦value.func g gx R S e σ₂]) : (Q₁ ⋀ x ≡ value.func g gx R S e σ₂ ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from env.dvcgen.func x_not_in_σ₁ g_not_in_σ₂ gx_not_in_σ₂ g_neq_gx σ₁_verified σ₂_verified x_free_in_R fv_R fv_S e_verified func_vc, have ⊩ (σ₁[x↦v]) : (Q₁ ⋀ x ≡ value.func g gx R S e σ₂ ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from v_is_num.symm ▸ this, show ∃σ₁ Q', ⊩ (σ₁[x↦v]) : Q', from exists.intro σ₁ (exists.intro (Q₁ ⋀ x ≡ value.func g gx R S e σ₂ ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))) this) ) else ( have (σ₁.apply x) = v, by { simp[h2] at h1, from h1 }, show ∃σ₁ Q₁, ⊩ (σ₁[x↦v]) : Q₁, from ih₁ this ) } end lemma env.dvcgen.tru.inv {σ: env} {x: var} {Q: prop}: (⊩ (σ[x ↦ value.true]) : Q ⋀ x ≡ value.true) → x ∉ σ ∧ (⊩ σ : Q) := assume h: ⊩ (σ[x ↦ value.true]) : Q ⋀ x ≡ value.true, begin cases h, case env.dvcgen.tru h1 h2 { from ⟨h1, h2⟩ } end lemma env.dvcgen.fls.inv {σ: env} {x: var} {Q: prop}: (⊩ (σ[x ↦ value.false]) : Q ⋀ x ≡ value.false) → x ∉ σ ∧ (⊩ σ : Q) := assume h: ⊩ (σ[x ↦ value.false]) : Q ⋀ x ≡ value.false, begin cases h, case env.dvcgen.fls h1 h2 { from ⟨h1, h2⟩ } end lemma env.dvcgen.num.inv {σ: env} {x: var} {n: ℕ} {Q: prop}: (⊩ (σ[x ↦ value.num n]) : Q ⋀ x ≡ value.num n) → x ∉ σ ∧ (⊩ σ : Q) := assume h: ⊩ (σ[x ↦ value.num n]) : Q ⋀ x ≡ value.num n, begin cases h, case env.dvcgen.num h1 h2 { from ⟨h1, h2⟩ } end lemma env.dvcgen.func.inv {σ₁ σ₂: env} {f g x: var} {R S: spec} {e: exp} {Q: prop}: (⊩ (σ₁[f ↦ value.func g x R S e σ₂]) : Q) → ∃Q₁ Q₂ Q₃, f ∉ σ₁ ∧ g ∉ σ₂ ∧ x ∉ σ₂ ∧ g ≠ x ∧ (⊩ σ₁ : Q₁) ∧ (⊩ σ₂ : Q₂) ∧ x ∈ FV R.to_prop.to_vc ∧ FV R.to_prop ⊆ FV Q₂ ∪ { g, x } ∧ FV S.to_prop ⊆ FV Q₂ ∪ { g, x } ∧ (Q₂ ⋀ spec.func g x R S ⋀ R ⊩ e : Q₃) ∧ ⦃ prop.implies (Q₂ ⋀ spec.func g x R S ⋀ R ⋀ Q₃ (term.app g x)) S ⦄ ∧ (Q = (Q₁ ⋀ ((f ≡ (value.func g x R S e σ₂)) ⋀ prop.subst_env (σ₂[g↦value.func g x R S e σ₂]) (prop.func g x R (Q₃ (term.app g ↑x) ⋀ S))))) := assume h : ⊩ (σ₁[f ↦ value.func g x R S e σ₂]) : Q, begin cases h, case env.dvcgen.func Q₁ Q₂ Q₃ f_not_in_σ₁ g_not_in_σ₂ x_not_in_σ₂ g_neq_x σ₁_verified σ₂_verified x_free_in_R fv_R fv_S e_verified func_vc { from ⟨Q₁, ⟨Q₂, ⟨Q₃, ⟨f_not_in_σ₁, ⟨g_not_in_σ₂, ⟨x_not_in_σ₂, ⟨g_neq_x, ⟨σ₁_verified, ⟨σ₂_verified, ⟨x_free_in_R, ⟨fv_R, ⟨fv_S, ⟨e_verified, ⟨func_vc, rfl⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩ } end lemma env.dvcgen.copy {σ₁ σ₂: env} {P₁ P₂} {x y: var} {v: value}: (⊩ σ₁ : P₁) → (y ∉ σ₁) → (⊩ (σ₂[x↦v]) : P₂) → ∃P₃, (⊩ (σ₁[y↦v]) : P₁ ⋀ P₃) := assume σ₁_verified: ⊩ σ₁ : P₁, assume y_not_in_σ₁: y ∉ σ₁, assume σ₂_xv_verified: ⊩ (σ₂[x↦v]) : P₂, show ∃P₃, (⊩ (σ₁[y↦v]) : P₁ ⋀ P₃), by begin cases σ₂_xv_verified, case env.dvcgen.tru { from have ⊩ (σ₁[y↦value.true]) : P₁ ⋀ y ≡ value.true, from env.dvcgen.tru y_not_in_σ₁ σ₁_verified, show ∃P₃, ⊩ (σ₁[y↦value.true]) : P₁ ⋀ P₃, from exists.intro (y ≡ value.true) this }, case env.dvcgen.fls { from have ⊩ (σ₁[y↦value.false]) : P₁ ⋀ y ≡ value.false, from env.dvcgen.fls y_not_in_σ₁ σ₁_verified, show ∃P₃, ⊩ (σ₁[y↦value.false]) : P₁ ⋀ P₃, from exists.intro (y ≡ value.false) this }, case env.dvcgen.num n { from have ⊩ (σ₁[y↦value.num n]) : P₁ ⋀ y ≡ value.num n, from env.dvcgen.num y_not_in_σ₁ σ₁_verified, show ∃P₃, ⊩ (σ₁[y↦value.num n]) : P₁ ⋀ P₃, from exists.intro (y ≡ value.num n) this }, case env.dvcgen.func σ₃ f fx R S e Q₃ Q₄ Q₂ x_not_in_σ₂ f_not_in_σ₃ fx_not_in_σ₃ f_neq_fx σ₂_verified σ₃_verified x_free_in_R fv_R fv_S e_verified func_vc { from have ⊩ (σ₁[y↦value.func f fx R S e σ₃]) : (P₁ ⋀ y ≡ value.func f fx R S e σ₃ ⋀ prop.subst_env (σ₃[f↦value.func f fx R S e σ₃]) (prop.func f fx R (Q₃ (term.app f fx) ⋀ S))), from env.dvcgen.func y_not_in_σ₁ f_not_in_σ₃ fx_not_in_σ₃ f_neq_fx σ₁_verified σ₃_verified x_free_in_R fv_R fv_S e_verified func_vc, show ∃P₃, ⊩ (σ₁[y↦value.func f fx R S e σ₃]) : P₁ ⋀ P₃, from exists.intro ( y ≡ value.func f fx R S e σ₃ ⋀ prop.subst_env (σ₃[f↦value.func f fx R S e σ₃]) (prop.func f fx R (Q₃ (term.app f fx) ⋀ S))) this } end lemma exp.dvcgen.inj {P: prop} {Q: propctx} {e: exp}: (P ⊩ e : Q) → ∀Q', (P ⊩ e : Q') → (Q = Q') := assume h1: P ⊩ e : Q, begin induction h1, intros Q' h2, cases h2, have : (Q_1 = Q_2), from ih_1 Q_2 a_3, rw[this], intros Q' h2, cases h2, have : (Q_1 = Q_2), from ih_1 Q_2 a_3, rw[this], intros Q' h2, cases h2, have : (Q_1 = Q_2), from ih_1 Q_2 a_3, rw[this], intros Q' h2, cases h2, have h3: (Q₁ = Q₁_1), from ih_1 Q₁_1 a_15, rw[←h3] at a_16, have : (Q₂ = Q₂_1), from ih_2 Q₂_1 a_16, rw[this], rw[h3], intros Q' h2, cases h2, have : (Q_1 = Q_2), from ih_1 Q_2 a_6, rw[this], intros Q' h2, cases h2, have : (Q_1 = Q_2), from ih_1 Q_2 a_8, rw[this], intros Q' h2, cases h2, have : (Q_1 = Q_2), from ih_1 Q_2 a_8, rw[this], intros Q' h2, cases h2, have : (Q₁ = Q₁_1), from ih_1 Q₁_1 a_5, rw[this], have : (Q₂ = Q₂_1), from ih_2 Q₂_1 a_6, rw[this], refl, intros Q' h2, cases h2, refl end lemma env.dvcgen.inj {P: prop} {σ: env}: (⊩ σ : P) → ∀Q, (⊩ σ : Q) → (P = Q) := assume h1: ⊩ σ : P, begin induction h1, intros Q h2, cases h2, refl, intros Q h2, cases h2, have : (Q = Q_1), from ih_1 Q_1 a_3, rw[this], refl, intros Q h2, cases h2, have : (Q = Q_1), from ih_1 Q_1 a_3, rw[this], refl, intros Q h2, cases h2, have : (Q = Q_1), from ih_1 Q_1 a_3, rw[this], refl, intros Q h2, cases h2, have h3: (Q₁ = Q₁_1), from ih_1 Q₁_1 a_15, rw[h3], have h4: (Q₂ = Q₂_1), from ih_2 Q₂_1 a_16, rw[←h4] at a_20, have : (Q₃ = Q₃_1), from exp.dvcgen.inj a_9 Q₃_1 a_20, rw[this], refl end lemma stack.dvcgen.inj {s: dstack} {Q₁: propctx}: (⊩ₛ s : Q₁) → ∀Q₂, (⊩ₛ s : Q₂) → (Q₁ = Q₂) := assume h1: ⊩ₛ s : Q₁, have ∀s' Q₂, (s = s') → (⊩ₛ s' : Q₂) → (Q₁ = Q₂), by begin cases h1, intros s' Q₂ h2 h3, cases h3, injection h2, have h4: (R = R_1), from h_1, have h6: (σ = σ_1), from h_2, have h7: (e = e_1), from h_3, have h8: (P = P_1), from env.dvcgen.inj a P_1 (h6.symm ▸ a_4), have : ↑R ⋀ P ⊩ e : Q_1, from h4.symm ▸ h7.symm ▸ h8.symm ▸ a_7, have h9: (Q = Q_1), from exp.dvcgen.inj a_3 Q_1 this, rw[←h8], rw[←h9], contradiction, intros s' Q₂ h2 h3, cases h3, contradiction, injection h2, have h4: (P₁ = P₁_1), from env.dvcgen.inj a_2 P₁_1 (h_3.symm ▸ a_17), rw[h4.symm] at a_24, rw[h_4.symm] at a_24, rw[h_5.symm] at a_24, rw[h_7.symm] at a_24, rw[h_6.symm] at a_24, rw[h_2.symm] at a_24, have h5: (Q₁_1 = Q₁), from exp.dvcgen.inj a_9 Q₁ a_24, rw[←h4], rw[←h_5], rw[←h_6], rw[←h_4], rw[h5] end, show ∀Q₂, (⊩ₛ s : Q₂) → (Q₁ = Q₂), from λQ₂ h1, (this s Q₂) rfl h1
b0bfe1148f569f21433d0b46647c1c4e7e4cc0ff
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/sub/basic.lean
82627122e80e08d05abfb7cff9506aac3cc79889
[ "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,324
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 order.hom.basic import algebra.hom.equiv.basic import algebra.ring.basic import algebra.order.sub.defs /-! # Additional results about ordered Subtraction > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α β : Type*} section has_add variables [preorder α] [has_add α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma add_hom.le_map_tsub [preorder β] [has_add β] [has_sub β] [has_ordered_sub β] (f : add_hom α β) (hf : monotone f) (a b : α) : f a - f b ≤ f (a - b) := by { rw [tsub_le_iff_right, ← f.map_add], exact hf le_tsub_add } lemma le_mul_tsub {R : Type*} [distrib R] [preorder R] [has_sub R] [has_ordered_sub R] [covariant_class R R (*) (≤)] {a b c : R} : a * b - a * c ≤ a * (b - c) := (add_hom.mul_left a).le_map_tsub (monotone_id.const_mul' a) _ _ lemma le_tsub_mul {R : Type*} [comm_semiring R] [preorder R] [has_sub R] [has_ordered_sub R] [covariant_class R R (*) (≤)] {a b c : R} : a * c - b * c ≤ (a - b) * c := by simpa only [mul_comm _ c] using le_mul_tsub end has_add /-- An order isomorphism between types with ordered subtraction preserves subtraction provided that it preserves addition. -/ lemma order_iso.map_tsub {M N : Type*} [preorder M] [has_add M] [has_sub M] [has_ordered_sub M] [partial_order N] [has_add N] [has_sub N] [has_ordered_sub N] (e : M ≃o N) (h_add : ∀ a b, e (a + b) = e a + e b) (a b : M) : e (a - b) = e a - e b := begin set e_add : M ≃+ N := { map_add' := h_add, .. e }, refine le_antisymm _ (e_add.to_add_hom.le_map_tsub e.monotone a b), suffices : e (e.symm (e a) - e.symm (e b)) ≤ e (e.symm (e a - e b)), by simpa, exact e.monotone (e_add.symm.to_add_hom.le_map_tsub e.symm.monotone _ _) end /-! ### Preorder -/ section preorder variables [preorder α] variables [add_comm_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma add_monoid_hom.le_map_tsub [preorder β] [add_comm_monoid β] [has_sub β] [has_ordered_sub β] (f : α →+ β) (hf : monotone f) (a b : α) : f a - f b ≤ f (a - b) := f.to_add_hom.le_map_tsub hf a b end preorder
75b0e74e1476c51e7d896600962f6d42c5601ee8
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/pnat/intervals.lean
44de07669ad77b8bfc9e571f0147ed10c977a9cd
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
959
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison -/ import data.pnat.basic import data.finset namespace pnat /-- `Ico l u` is the set of positive natural numbers `l ≤ k < u`. -/ def Ico (l u : ℕ+) : finset ℕ+ := (finset.Ico l u).attach.map { to_fun := λ n, ⟨(n : ℕ), lt_of_lt_of_le l.2 (finset.Ico.mem.1 n.2).1⟩, inj := λ n m h, subtype.ext.2 (by { replace h := congr_arg subtype.val h, exact h }) } -- why can't we do this directly? @[simp] lemma Ico.mem {n m l : ℕ+} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := begin dsimp [Ico], simp only [finset.mem_attach, finset.mem_map, function.embedding.coe_fn_mk, exists_prop_of_true, subtype.exists], split, { rintro ⟨a, ⟨h, rfl⟩⟩, simp at h, exact ⟨h.1, h.2⟩ }, { rintro ⟨h₁, h₂⟩, use l, split; simp, exact ⟨h₁, h₂⟩ } end end pnat
0b8dc1e7e8fbbfa61c9f1d64ff5e8eb1c6e92a9b
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/continued_fractions/terminated_stable.lean
0bdcae77dd7789c7736e8428449f179d18b4297f
[ "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
3,695
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 algebra.continued_fractions.translations /-! # Stabilisation of gcf Computations Under Termination ## Summary We show that the continuants and convergents of a gcf stabilise once the gcf terminates. -/ namespace generalized_continued_fraction variables {K : Type*} {g : generalized_continued_fraction K} {n m : ℕ} /-- If a gcf terminated at position `n`, it also terminated at `m ≥ n`.-/ lemma terminated_stable (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.terminated_at m := g.s.terminated_stable n_le_m terminated_at_n variable [division_ring K] lemma continuants_aux_stable_step_of_terminated (terminated_at_n : g.terminated_at n) : g.continuants_aux (n + 2) = g.continuants_aux (n + 1) := by { rw [terminated_at_iff_s_none] at terminated_at_n, simp only [terminated_at_n, continuants_aux] } lemma continuants_aux_stable_of_terminated (n_lt_m : n < m) (terminated_at_n : g.terminated_at n) : g.continuants_aux m = g.continuants_aux (n + 1) := begin refine nat.le_induction rfl (λ k hnk hk, _) _ n_lt_m, rcases nat.exists_eq_add_of_lt hnk with ⟨k, rfl⟩, refine (continuants_aux_stable_step_of_terminated _).trans hk, exact terminated_stable (nat.le_add_right _ _) terminated_at_n end lemma convergents'_aux_stable_step_of_terminated {s : seq $ pair K} (terminated_at_n : s.terminated_at n) : convergents'_aux s (n + 1) = convergents'_aux s n := begin change s.nth n = none at terminated_at_n, induction n with n IH generalizing s, case nat.zero { simp only [convergents'_aux, terminated_at_n, seq.head] }, case nat.succ { cases s_head_eq : s.head with gp_head, case option.none { simp only [convergents'_aux, s_head_eq] }, case option.some { have : s.tail.terminated_at n, by simp only [seq.terminated_at, s.nth_tail, terminated_at_n], simp only [convergents'_aux, s_head_eq, (IH this)] } } end lemma convergents'_aux_stable_of_terminated {s : seq $ pair K} (n_le_m : n ≤ m) (terminated_at_n : s.terminated_at n) : convergents'_aux s m = convergents'_aux s n := begin induction n_le_m with m n_le_m IH, { refl }, { refine (convergents'_aux_stable_step_of_terminated _).trans IH, exact s.terminated_stable n_le_m terminated_at_n } end lemma continuants_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.continuants m = g.continuants n := by simp only [nth_cont_eq_succ_nth_cont_aux, (continuants_aux_stable_of_terminated (nat.pred_le_iff.elim_left n_le_m) terminated_at_n)] lemma numerators_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.numerators m = g.numerators n := by simp only [num_eq_conts_a, (continuants_stable_of_terminated n_le_m terminated_at_n)] lemma denominators_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.denominators m = g.denominators n := by simp only [denom_eq_conts_b, (continuants_stable_of_terminated n_le_m terminated_at_n)] lemma convergents_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.convergents m = g.convergents n := by simp only [convergents, (denominators_stable_of_terminated n_le_m terminated_at_n), (numerators_stable_of_terminated n_le_m terminated_at_n)] lemma convergents'_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.convergents' m = g.convergents' n := by simp only [convergents', (convergents'_aux_stable_of_terminated n_le_m terminated_at_n)] end generalized_continued_fraction
b8fa8ac402a413346606a43a9a9d2127e071a323
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/user_rec_crash.lean
80c3f84902cb4a9df4705f9e1f2025a5c137b0e0
[ "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
99
lean
example (a b : Prop) (h : a ∧ b) : a := begin induction h using and.rec_on with h₁ h₂, end
aaa0be306fb5a4058bc0c6d9d5c011f782264718
bb31430994044506fa42fd667e2d556327e18dfe
/src/geometry/euclidean/angle/unoriented/affine.lean
c273b56f612534680800941f2b864c87d00a6d25
[ "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,769
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Manuel Candales -/ import analysis.convex.between import geometry.euclidean.angle.unoriented.basic /-! # Angles between points This file defines unoriented angles in Euclidean affine spaces. ## Main definitions * `euclidean_geometry.angle`, with notation `∠`, is the undirected angle determined by three points. -/ noncomputable theory open_locale big_operators open_locale real open_locale real_inner_product_space namespace euclidean_geometry open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The undirected angle at `p2` between the line segments to `p1` and `p3`. If either of those points equals `p2`, this is π/2. Use `open_locale euclidean_geometry` to access the `∠ p1 p2 p3` notation. -/ def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2) localized "notation (name := angle) `∠` := euclidean_geometry.angle" in euclidean_geometry lemma continuous_at_angle {x : P × P × P} (hx12 : x.1 ≠ x.2.1) (hx32 : x.2.2 ≠ x.2.1) : continuous_at (λ y : P × P × P, ∠ y.1 y.2.1 y.2.2) x := begin let f : P × P × P → V × V := λ y, (y.1 -ᵥ y.2.1, y.2.2 -ᵥ y.2.1), have hf1 : (f x).1 ≠ 0, by simp [hx12], have hf2 : (f x).2 ≠ 0, by simp [hx32], exact (inner_product_geometry.continuous_at_angle hf1 hf2).comp ((continuous_fst.vsub continuous_snd.fst).prod_mk (continuous_snd.snd.vsub continuous_snd.fst)).continuous_at end @[simp] lemma _root_.affine_isometry.angle_map {V₂ P₂ : Type*} [inner_product_space ℝ V₂] [metric_space P₂] [normed_add_torsor V₂ P₂] (f : P →ᵃⁱ[ℝ] P₂) (p₁ p₂ p₃ : P) : ∠ (f p₁) (f p₂) (f p₃) = ∠ p₁ p₂ p₃ := by simp_rw [angle, ←affine_isometry.map_vsub, linear_isometry.angle_map] @[simp, norm_cast] lemma _root_.affine_subspace.angle_coe {s : affine_subspace ℝ P} (p₁ p₂ p₃ : s) : by haveI : nonempty s := ⟨p₁⟩; exact ∠ (p₁ : P) (p₂ : P) (p₃ : P) = ∠ p₁ p₂ p₃ := by haveI : nonempty s := ⟨p₁⟩; exact s.subtypeₐᵢ.angle_map p₁ p₂ p₃ /-- Angles are translation invariant -/ @[simp] lemma angle_const_vadd (v : V) (p₁ p₂ p₃ : P) : ∠ (v +ᵥ p₁) (v +ᵥ p₂) (v +ᵥ p₃) = ∠ p₁ p₂ p₃ := (affine_isometry_equiv.const_vadd ℝ P v).to_affine_isometry.angle_map _ _ _ /-- Angles are translation invariant -/ @[simp] lemma angle_vadd_const (v₁ v₂ v₃ : V) (p : P) : ∠ (v₁ +ᵥ p) (v₂ +ᵥ p) (v₃ +ᵥ p) = ∠ v₁ v₂ v₃ := (affine_isometry_equiv.vadd_const ℝ p).to_affine_isometry.angle_map _ _ _ /-- Angles are translation invariant -/ @[simp] lemma angle_const_vsub (p p₁ p₂ p₃ : P) : ∠ (p -ᵥ p₁) (p -ᵥ p₂) (p -ᵥ p₃) = ∠ p₁ p₂ p₃ := (affine_isometry_equiv.const_vsub ℝ p).to_affine_isometry.angle_map _ _ _ /-- Angles are translation invariant -/ @[simp] lemma angle_vsub_const (p₁ p₂ p₃ p : P) : ∠ (p₁ -ᵥ p) (p₂ -ᵥ p) (p₃ -ᵥ p) = ∠ p₁ p₂ p₃ := (affine_isometry_equiv.vadd_const ℝ p).symm.to_affine_isometry.angle_map _ _ _ /-- Angles in a vector space are translation invariant -/ @[simp] lemma angle_add_const (v₁ v₂ v₃ : V) (v : V) : ∠ (v₁ + v) (v₂ + v) (v₃ + v) = ∠ v₁ v₂ v₃ := angle_vadd_const _ _ _ _ /-- Angles in a vector space are translation invariant -/ @[simp] lemma angle_const_add (v : V) (v₁ v₂ v₃ : V) : ∠ (v + v₁) (v + v₂) (v + v₃) = ∠ v₁ v₂ v₃ := angle_const_vadd _ _ _ _ /-- Angles in a vector space are translation invariant -/ @[simp] lemma angle_sub_const (v₁ v₂ v₃ : V) (v : V) : ∠ (v₁ - v) (v₂ - v) (v₃ - v) = ∠ v₁ v₂ v₃ := by simpa only [vsub_eq_sub] using angle_vsub_const v₁ v₂ v₃ v /-- Angles in a vector space are invariant to inversion -/ @[simp] lemma angle_const_sub (v : V) (v₁ v₂ v₃ : V) : ∠ (v - v₁) (v - v₂) (v - v₃) = ∠ v₁ v₂ v₃ := by simpa only [vsub_eq_sub] using angle_const_vsub _ _ _ _ /-- Angles in a vector space are invariant to inversion -/ @[simp] lemma angle_neg (v₁ v₂ v₃ : V) : ∠ (-v₁) (-v₂) (-v₃) = ∠ v₁ v₂ v₃ := by simpa only [zero_sub] using angle_const_sub 0 v₁ v₂ v₃ /-- The angle at a point does not depend on the order of the other two points. -/ lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 := angle_comm _ _ /-- The angle at a point is nonnegative. -/ lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 := angle_nonneg _ _ /-- The angle at a point is at most π. -/ lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π := angle_le_pi _ _ /-- The angle ∠AAB at a point. -/ lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 := begin unfold angle, rw vsub_self, exact angle_zero_left _ end /-- The angle ∠ABB at a point. -/ lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 := by rw [angle_comm, angle_eq_left] /-- The angle ∠ABA at a point. -/ lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 := angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he)) /-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p1 p3 = 0 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, rw angle_eq_zero_iff, rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2, use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one], rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg], simp [←hpr] end /-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p3 p1 = 0 := begin rw angle_comm at h, exact angle_eq_zero_of_angle_eq_pi_left h end /-- If ∠BCD = π, then ∠ABC = ∠ABD. -/ lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p2 p3 = ∠ p1 p2 p4 := begin unfold angle at *, rcases angle_eq_pi_iff.1 h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩, rw [eq_comm], convert angle_smul_right_of_pos (p1 -ᵥ p2) (p3 -ᵥ p2) (add_pos (neg_pos_of_neg hr) zero_lt_one), rw [add_smul, ← neg_vsub_eq_vsub_rev p2 p3, smul_neg, neg_smul, ← hpr], simp end /-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p3 p2 + ∠ p1 p3 p4 = π := begin unfold angle at h, rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4], unfold angle, exact angle_add_angle_eq_pi_of_angle_eq_pi _ h end /-- Vertical Angles Theorem: angles opposite each other, formed by two intersecting straight lines, are equal. -/ lemma angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi {p1 p2 p3 p4 p5 : P} (hapc : ∠ p1 p5 p3 = π) (hbpd : ∠ p2 p5 p4 = π) : ∠ p1 p5 p2 = ∠ p3 p5 p4 := by linarith [angle_add_angle_eq_pi_of_angle_eq_pi p1 hbpd, angle_comm p4 p5 p1, angle_add_angle_eq_pi_of_angle_eq_pi p4 hapc, angle_comm p4 p5 p3] /-- If ∠ABC = π then dist A B ≠ 0. -/ lemma left_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p2 ≠ 0 := begin by_contra heq, rw [dist_eq_zero] at heq, rw [heq, angle_eq_left] at h, exact real.pi_ne_zero (by linarith), end /-- If ∠ABC = π then dist C B ≠ 0. -/ lemma right_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p3 p2 ≠ 0 := left_dist_ne_zero_of_angle_eq_pi $ (angle_comm _ _ _).trans h /-- If ∠ABC = π, then (dist A C) = (dist A B) + (dist B C). -/ lemma dist_eq_add_dist_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p3 = dist p1 p2 + dist p3 p2 := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_add_norm_of_angle_eq_pi h, end /-- If A ≠ B and C ≠ B then ∠ABC = π if and only if (dist A C) = (dist A B) + (dist B C). -/ lemma dist_eq_add_dist_iff_angle_eq_pi {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) : dist p1 p3 = dist p1 p2 + dist p3 p2 ↔ ∠ p1 p2 p3 = π := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_add_norm_iff_angle_eq_pi ((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)), end /-- If ∠ABC = 0, then (dist A C) = abs ((dist A B) - (dist B C)). -/ lemma dist_eq_abs_sub_dist_of_angle_eq_zero {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = 0) : (dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_abs_sub_norm_of_angle_eq_zero h, end /-- If A ≠ B and C ≠ B then ∠ABC = 0 if and only if (dist A C) = abs ((dist A B) - (dist B C)). -/ lemma dist_eq_abs_sub_dist_iff_angle_eq_zero {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) : (dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| ↔ ∠ p1 p2 p3 = 0 := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_abs_sub_norm_iff_angle_eq_zero ((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)), end /-- If M is the midpoint of the segment AB, then ∠AMB = π. -/ lemma angle_midpoint_eq_pi (p1 p2 : P) (hp1p2 : p1 ≠ p2) : ∠ p1 (midpoint ℝ p1 p2) p2 = π := have p2 -ᵥ midpoint ℝ p1 p2 = -(p1 -ᵥ midpoint ℝ p1 p2), by { rw neg_vsub_eq_vsub_rev, simp }, by simp [angle, this, hp1p2, -zero_lt_one] /-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B then ∠CMA = π / 2. -/ lemma angle_left_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) : ∠ p3 (midpoint ℝ p1 p2) p1 = π / 2 := begin let m : P := midpoint ℝ p1 p2, have h1 : p3 -ᵥ p1 = (p3 -ᵥ m) - (p1 -ᵥ m) := (vsub_sub_vsub_cancel_right p3 p1 m).symm, have h2 : p3 -ᵥ p2 = (p3 -ᵥ m) + (p1 -ᵥ m), { rw [left_vsub_midpoint, ← midpoint_vsub_right, vsub_add_vsub_cancel] }, rw [dist_eq_norm_vsub V p3 p1, dist_eq_norm_vsub V p3 p2, h1, h2] at h, exact (norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (p3 -ᵥ m) (p1 -ᵥ m)).mp h.symm, end /-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B then ∠CMB = π / 2. -/ lemma angle_right_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) : ∠ p3 (midpoint ℝ p1 p2) p2 = π / 2 := by rw [midpoint_comm p1 p2, angle_left_midpoint_eq_pi_div_two_of_dist_eq h.symm] /-- If the second of three points is strictly between the other two, the angle at that point is π. -/ lemma _root_.sbtw.angle₁₂₃_eq_pi {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₁ p₂ p₃ = π := begin rw [angle, angle_eq_pi_iff], rcases h with ⟨⟨r, ⟨hr0, hr1⟩, hp₂⟩, hp₂p₁, hp₂p₃⟩, refine ⟨vsub_ne_zero.2 hp₂p₁.symm, -(1 - r) / r, _⟩, have hr0' : r ≠ 0, { rintro rfl, rw ←hp₂ at hp₂p₁, simpa using hp₂p₁ }, have hr1' : r ≠ 1, { rintro rfl, rw ←hp₂ at hp₂p₃, simpa using hp₂p₃ }, replace hr0 := hr0.lt_of_ne hr0'.symm, replace hr1 := hr1.lt_of_ne hr1', refine ⟨div_neg_of_neg_of_pos (left.neg_neg_iff.2 (sub_pos.2 hr1)) hr0, _⟩, rw [←hp₂, affine_map.line_map_apply, vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, smul_neg, smul_smul, div_mul_cancel _ hr0', neg_smul, neg_neg, sub_eq_iff_eq_add, ←add_smul, sub_add_cancel, one_smul] end /-- If the second of three points is strictly between the other two, the angle at that point (reversed) is π. -/ lemma _root_.sbtw.angle₃₂₁_eq_pi {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₃ p₂ p₁ = π := by rw [←h.angle₁₂₃_eq_pi, angle_comm] /-- The angle between three points is π if and only if the second point is strictly between the other two. -/ lemma angle_eq_pi_iff_sbtw {p₁ p₂ p₃ : P} : ∠ p₁ p₂ p₃ = π ↔ sbtw ℝ p₁ p₂ p₃ := begin refine ⟨_, λ h, h.angle₁₂₃_eq_pi⟩, rw [angle, angle_eq_pi_iff], rintro ⟨hp₁p₂, r, hr, hp₃p₂⟩, refine ⟨⟨1 / (1 - r), ⟨div_nonneg zero_le_one (sub_nonneg.2 (hr.le.trans zero_le_one)), (div_le_one (sub_pos.2 (hr.trans zero_lt_one))).2 ((le_sub_self_iff 1).2 hr.le)⟩, _⟩, (vsub_ne_zero.1 hp₁p₂).symm, _⟩, { rw ←eq_vadd_iff_vsub_eq at hp₃p₂, rw [affine_map.line_map_apply, hp₃p₂, vadd_vsub_assoc, ←neg_vsub_eq_vsub_rev p₂ p₁, smul_neg, ←neg_smul, smul_add, smul_smul, ←add_smul, eq_comm, eq_vadd_iff_vsub_eq], convert (one_smul ℝ (p₂ -ᵥ p₁)).symm, field_simp [(sub_pos.2 (hr.trans zero_lt_one)).ne.symm], abel }, { rw [ne_comm, ←@vsub_ne_zero V, hp₃p₂, smul_ne_zero_iff], exact ⟨hr.ne, hp₁p₂⟩ } end /-- If the second of three points is weakly between the other two, and not equal to the first, the angle at the first point is zero. -/ lemma _root_.wbtw.angle₂₁₃_eq_zero_of_ne {p₁ p₂ p₃ : P} (h : wbtw ℝ p₁ p₂ p₃) (hp₂p₁ : p₂ ≠ p₁) : ∠ p₂ p₁ p₃ = 0 := begin rw [angle, angle_eq_zero_iff], rcases h with ⟨r, ⟨hr0, hr1⟩, rfl⟩, have hr0' : r ≠ 0, { rintro rfl, simpa using hp₂p₁ }, replace hr0 := hr0.lt_of_ne hr0'.symm, refine ⟨vsub_ne_zero.2 hp₂p₁, r⁻¹, inv_pos.2 hr0, _⟩, rw [affine_map.line_map_apply, vadd_vsub_assoc, vsub_self, add_zero, smul_smul, inv_mul_cancel hr0', one_smul] end /-- If the second of three points is strictly between the other two, the angle at the first point is zero. -/ lemma _root_.sbtw.angle₂₁₃_eq_zero {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₂ p₁ p₃ = 0 := h.wbtw.angle₂₁₃_eq_zero_of_ne h.ne_left /-- If the second of three points is weakly between the other two, and not equal to the first, the angle at the first point (reversed) is zero. -/ lemma _root_.wbtw.angle₃₁₂_eq_zero_of_ne {p₁ p₂ p₃ : P} (h : wbtw ℝ p₁ p₂ p₃) (hp₂p₁ : p₂ ≠ p₁) : ∠ p₃ p₁ p₂ = 0 := by rw [←h.angle₂₁₃_eq_zero_of_ne hp₂p₁, angle_comm] /-- If the second of three points is strictly between the other two, the angle at the first point (reversed) is zero. -/ lemma _root_.sbtw.angle₃₁₂_eq_zero {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₃ p₁ p₂ = 0 := h.wbtw.angle₃₁₂_eq_zero_of_ne h.ne_left /-- If the second of three points is weakly between the other two, and not equal to the third, the angle at the third point is zero. -/ lemma _root_.wbtw.angle₂₃₁_eq_zero_of_ne {p₁ p₂ p₃ : P} (h : wbtw ℝ p₁ p₂ p₃) (hp₂p₃ : p₂ ≠ p₃) : ∠ p₂ p₃ p₁ = 0 := h.symm.angle₂₁₃_eq_zero_of_ne hp₂p₃ /-- If the second of three points is strictly between the other two, the angle at the third point is zero. -/ lemma _root_.sbtw.angle₂₃₁_eq_zero {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₂ p₃ p₁ = 0 := h.wbtw.angle₂₃₁_eq_zero_of_ne h.ne_right /-- If the second of three points is weakly between the other two, and not equal to the third, the angle at the third point (reversed) is zero. -/ lemma _root_.wbtw.angle₁₃₂_eq_zero_of_ne {p₁ p₂ p₃ : P} (h : wbtw ℝ p₁ p₂ p₃) (hp₂p₃ : p₂ ≠ p₃) : ∠ p₁ p₃ p₂ = 0 := h.symm.angle₃₁₂_eq_zero_of_ne hp₂p₃ /-- If the second of three points is strictly between the other two, the angle at the third point (reversed) is zero. -/ lemma _root_.sbtw.angle₁₃₂_eq_zero {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₁ p₃ p₂ = 0 := h.wbtw.angle₁₃₂_eq_zero_of_ne h.ne_right /-- The angle between three points is zero if and only if one of the first and third points is weakly between the other two, and not equal to the second. -/ lemma angle_eq_zero_iff_ne_and_wbtw {p₁ p₂ p₃ : P} : ∠ p₁ p₂ p₃ = 0 ↔ (p₁ ≠ p₂ ∧ wbtw ℝ p₂ p₁ p₃) ∨ (p₃ ≠ p₂ ∧ wbtw ℝ p₂ p₃ p₁) := begin split, { rw [angle, angle_eq_zero_iff], rintro ⟨hp₁p₂, r, hr0, hp₃p₂⟩, rcases le_or_lt 1 r with hr1 | hr1, { refine or.inl ⟨vsub_ne_zero.1 hp₁p₂, r⁻¹, ⟨(inv_pos.2 hr0).le, inv_le_one hr1⟩, _⟩, rw [affine_map.line_map_apply, hp₃p₂, smul_smul, inv_mul_cancel hr0.ne.symm, one_smul, vsub_vadd] }, { refine or.inr ⟨_, r, ⟨hr0.le, hr1.le⟩, _⟩, { rw [←@vsub_ne_zero V, hp₃p₂, smul_ne_zero_iff], exact ⟨hr0.ne.symm, hp₁p₂⟩ }, { rw [affine_map.line_map_apply, ←hp₃p₂, vsub_vadd] } } }, { rintro (⟨hp₁p₂, h⟩ | ⟨hp₃p₂, h⟩), { exact h.angle₂₁₃_eq_zero_of_ne hp₁p₂ }, { exact h.angle₃₁₂_eq_zero_of_ne hp₃p₂ } } end /-- The angle between three points is zero if and only if one of the first and third points is strictly between the other two, or those two points are equal but not equal to the second. -/ lemma angle_eq_zero_iff_eq_and_ne_or_sbtw {p₁ p₂ p₃ : P} : ∠ p₁ p₂ p₃ = 0 ↔ (p₁ = p₃ ∧ p₁ ≠ p₂) ∨ sbtw ℝ p₂ p₁ p₃ ∨ sbtw ℝ p₂ p₃ p₁ := begin rw angle_eq_zero_iff_ne_and_wbtw, by_cases hp₁p₂ : p₁ = p₂, { simp [hp₁p₂] }, by_cases hp₁p₃ : p₁ = p₃, { simp [hp₁p₃] }, by_cases hp₃p₂ : p₃ = p₂, { simp [hp₃p₂] }, simp [hp₁p₂, hp₁p₃, ne.symm hp₁p₃, sbtw, hp₃p₂] end /-- Three points are collinear if and only if the first or third point equals the second or the angle between them is 0 or π. -/ lemma collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi {p₁ p₂ p₃ : P} : collinear ℝ ({p₁, p₂, p₃} : set P) ↔ p₁ = p₂ ∨ p₃ = p₂ ∨ ∠ p₁ p₂ p₃ = 0 ∨ ∠ p₁ p₂ p₃ = π := begin refine ⟨λ h, _, λ h, _⟩, { replace h := h.wbtw_or_wbtw_or_wbtw, by_cases h₁₂ : p₁ = p₂, { exact or.inl h₁₂ }, by_cases h₃₂ : p₃ = p₂, { exact or.inr (or.inl h₃₂) }, rw [or_iff_right h₁₂, or_iff_right h₃₂], rcases h with h | h | h, { exact or.inr (angle_eq_pi_iff_sbtw.2 ⟨h, ne.symm h₁₂, ne.symm h₃₂⟩) }, { exact or.inl (h.angle₃₁₂_eq_zero_of_ne h₃₂) }, { exact or.inl (h.angle₂₃₁_eq_zero_of_ne h₁₂) } }, { rcases h with rfl | rfl | h | h, { simpa using collinear_pair ℝ p₁ p₃ }, { simpa using collinear_pair ℝ p₁ p₃ }, { rw angle_eq_zero_iff_ne_and_wbtw at h, rcases h with ⟨-, h⟩ | ⟨-, h⟩, { rw set.insert_comm, exact h.collinear }, { rw [set.insert_comm, set.pair_comm], exact h.collinear } }, { rw angle_eq_pi_iff_sbtw at h, exact h.wbtw.collinear } } end /-- If the angle between three points is 0, they are collinear. -/ lemma collinear_of_angle_eq_zero {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = 0) : collinear ℝ ({p₁, p₂, p₃} : set P) := collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi.2 $ or.inr $ or.inr $ or.inl h /-- If the angle between three points is π, they are collinear. -/ lemma collinear_of_angle_eq_pi {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π) : collinear ℝ ({p₁, p₂, p₃} : set P) := collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi.2 $ or.inr $ or.inr $ or.inr h /-- If three points are not collinear, the angle between them is nonzero. -/ lemma angle_ne_zero_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) : ∠ p₁ p₂ p₃ ≠ 0 := mt collinear_of_angle_eq_zero h /-- If three points are not collinear, the angle between them is not π. -/ lemma angle_ne_pi_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) : ∠ p₁ p₂ p₃ ≠ π := mt collinear_of_angle_eq_pi h /-- If three points are not collinear, the angle between them is positive. -/ lemma angle_pos_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) : 0 < ∠ p₁ p₂ p₃ := (angle_nonneg _ _ _).lt_of_ne (angle_ne_zero_of_not_collinear h).symm /-- If three points are not collinear, the angle between them is less than π. -/ lemma angle_lt_pi_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) : ∠ p₁ p₂ p₃ < π := (angle_le_pi _ _ _).lt_of_ne $ angle_ne_pi_of_not_collinear h end euclidean_geometry
4289c0655b13f4b2ae790c80e639cfcd5da39148
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/field_theory/mv_polynomial.lean
de704df4c817c4fbbca7c0ac247912c67722e281
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
6,764
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 Multivariate functions of the form `α^n → α` are isomorphic to multivariate polynomials in `n` variables. -/ import linear_algebra.finsupp field_theory.finite noncomputable theory local attribute [instance, priority 0] classical.prop_decidable open lattice set linear_map submodule namespace mv_polynomial variables {α : Type*} {σ : Type*} variables [discrete_field α] [fintype α] [fintype σ] [decidable_eq σ] def indicator (a : σ → α) : mv_polynomial σ α := finset.univ.prod (λn, 1 - (X n - C (a n))^(fintype.card α - 1)) lemma eval_indicator_apply_eq_one (a : σ → α) : eval a (indicator a) = 1 := have 0 < fintype.card α - 1, begin rw [← finite_field.card_units, fintype.card_pos_iff], exact ⟨1⟩ end, by simp only [indicator, (finset.prod_hom (eval a)).symm, eval_sub, is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] lemma eval_indicator_apply_eq_zero (a b : σ → α) (h : a ≠ b) : eval a (indicator b) = 0 := have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h, begin rcases this with ⟨i, hi⟩, simp only [indicator, (finset.prod_hom (eval a)).symm, eval_sub, is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end lemma degrees_indicator (c : σ → α) : degrees (indicator c) ≤ finset.univ.sum (λs:σ, add_monoid.smul (fintype.card α - 1) {s}) := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (add_monoid.smul_le_smul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X _ end set_option class.instance_max_depth 50 lemma indicator_mem_restrict_degree (c : σ → α) : indicator c ∈ restrict_degree σ α (fintype.card α - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), rw [← finset.sum_hom (multiset.count n)], simp only [is_add_monoid_hom.map_smul (multiset.count n), multiset.singleton_eq_singleton, add_monoid.smul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_cons_self, multiset.count_zero, mul_one] } end section variables (α σ) def evalₗ : mv_polynomial σ α →ₗ[α] (σ → α) → α := ⟨ λp e, p.eval e, assume p q, funext $ assume e, eval_add, assume a p, funext $ assume e, by rw [smul_eq_C_mul, eval_mul, eval_C]; refl ⟩ end section set_option class.instance_max_depth 50 lemma evalₗ_apply (p : mv_polynomial σ α) (e : σ → α) : evalₗ α σ p e = p.eval e := rfl end lemma map_restrict_dom_evalₗ : (restrict_degree σ α (fintype.card α - 1)).map (evalₗ α σ) = ⊤ := begin refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _), refine ⟨finset.univ.sum (λn:σ → α, e n • indicator n), _, _⟩, { exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @pi.finset_sum_apply (σ → α) (λ_, α) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n _ _, { assume b _ h, rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { assume h, exact (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [decidable_eq σ] [fintype σ] [discrete_field α] [fintype α] def R : Type u := restrict_degree σ α (fintype.card α - 1) instance R.add_comm_group : add_comm_group (R σ α) := by dunfold R; apply_instance instance R.vector_space : vector_space α (R σ α) := by dunfold R; apply_instance set_option class.instance_max_depth 50 lemma dim_R : vector_space.dim α (R σ α) = fintype.card (σ → α) := calc vector_space.dim α (R σ α) = vector_space.dim α (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} →₀ α) : linear_equiv.dim_eq (finsupp.restrict_dom_equiv_finsupp α α {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card α - 1 }) ... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} : by rw [finsupp.dim_eq, dim_of_field, mul_one] ... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card α } : begin refine quotient.sound ⟨equiv.subtype_congr finsupp.equiv_fun_on_fintype $ assume f, _⟩, refine forall_congr (assume n, nat.le_sub_right_iff_add_le _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = cardinal.mk (σ → {n // n < fintype.card α}) : quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card α)⟩ ... = cardinal.mk (σ → fin (fintype.card α)) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩ ... = cardinal.mk (σ → α) : begin refine (trunc.induction_on (fintype.equiv_fin α) $ assume (e : α ≃ fin (fintype.card α)), _), refine quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) e.symm⟩ end ... = fintype.card (σ → α) : cardinal.fintype_card _ def evalᵢ : R σ α →ₗ[α] (σ → α) → α := ((evalₗ α σ).comp (restrict_degree σ α (fintype.card α - 1)).subtype) lemma range_evalᵢ : (evalᵢ σ α).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ : (evalᵢ σ α).ker = ⊥ := begin refine injective_of_surjective _ _ _ (range_evalᵢ _ _), { rw [dim_R], exact cardinal.nat_lt_omega _ }, { rw [dim_R, dim_fun, dim_of_field, mul_one] } end lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ α) (h : ∀v:σ → α, p.eval v = 0) (hp : p ∈ restrict_degree σ α (fintype.card α - 1)) : p = 0 := let p' : R σ α := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ α).ker := by rw [mem_ker]; ext v; exact h v, show p'.1 = (0 : R σ α).1, begin rw [ker_evalₗ, mem_bot] at this, rw [this] end end mv_polynomial
c57eaab8f2690e95eee31569e68fe6e37936d6f9
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world5/level9.lean
b275d94e382ac3b9e28c7e6feee0352abb984c88
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
1,035
lean
/- # Function world. ## Level 9 : a big maze. I asked around on Zulip and apparently there is not a tactic for this, perhaps because this level is rather artificial. In world 6 we will see a variant of this example which can be solved by a tactic. It would be an interesting project to make a tactic which could solve this sort of level in Lean. You can of course work both forwards and backwards, or you could crack and draw a picture. -/ /- Lemma : no-side-bar There is a way through the following maze. -/ example (A B C D E F G H I J K L : Type) (f1 : A → B) (f2 : B → E) (f3 : E → D) (f4 : D → A) (f5 : E → F) (f6 : F → C) (f7 : B → C) (f8 : F → G) (f9 : G → J) (f10 : I → J) (f11 : J → I) (f12 : I → H) (f13 : E → H) (f14 : H → K) (f15 : I → L) : A → L := begin intro a, apply f15, apply f11, apply f9, apply f8, apply f5, apply f2, apply f1, assumption, end /- Next it's Proposition world, and the tactics you've learnt in function world are enough to solve all nine levels! -/
bf47dcc158e34fbe4176093026ec3560f66ba327
618003631150032a5676f229d13a079ac875ff77
/src/ring_theory/noetherian.lean
1b7c5c21fc38dfd4c80d614c063183f8f5efb944
[ "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
23,068
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal_operations import linear_algebra.basis /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set namespace submodule variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ideal.quotient.mk_one] at hr1 hc1 ⊢, rw [ideal.quotient.mk_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, finite_union ht₁.1 ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_group P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, finite_image _ ht.1, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨prod.inl '' tb ∪ prod.inr '' tc, finite_union (finite_image _ htb.1) (finite_image _ htc.1), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [ring R] [add_comm_group M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext i, cases i, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext i, cases i with i his, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext i, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, finite_insert _ hs, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nonzero R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (subtype.val : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, order_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (subtype.val ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((subtype.val ∘ f) '' {m | m ≤ a}) ≤ span R ((subtype.val ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff zero_ne_one hs (this a) (this b), set.image_subset_image_iff (subtype.val_injective.comp f.inj), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((subtype.val ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one R h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨s.attach.sum (λ i, f i • i.1), N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change s.attach.sum (λ i, (f i + g i) • _) = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change s.attach.sum (λ i, (c • f i) • _) = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x.1, subtype.eq _⟩, change s.attach.sum (λ i, l i.1 • i.1) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin unfold is_noetherian_ring at H ⊢, rw is_noetherian_iff_well_founded at H ⊢, convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace is_noetherian_ring variables {R : Type*} [integral_domain R] [is_noetherian_ring R] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : R, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set R)) (well_founded_submodule_gt _ _) lemma exists_irreducible_factor {a : R} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : R → Prop} (a : R) (h0 : P 0) (hu : ∀ u : R, is_unit u → P u) (hi : ∀ a i : R, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : R) : a ≠ 0 → ∃f : multiset R, (∀b ∈ f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) local attribute [instance] set.pointwise_mul_semiring theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, set.pointwise_mul_finite hfm hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
fb51336be848b1dae5c5d535e75f715f52c1238a
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/data/unit/thms.lean
1ac15428f5cecb58d166a499fcc07447c7ed121a
[ "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
357
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import data.unit.decl logic.eq namespace unit protected theorem equal (a b : unit) : a = b := rec_on a (rec_on b rfl) theorem eq_star (a : unit) : a = star := equal a star end unit
6255aab15dcb5ceb0d4ce9420cb4cd10e78a9ade
c777c32c8e484e195053731103c5e52af26a25d1
/src/group_theory/group_action/conj_act.lean
94d3aa0d6bdf4e5f108eca7eb35277882bcddc38
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
9,364
lean
/- Copyright (c) 2021 . All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action.basic import group_theory.subgroup.zpowers import algebra.group_ring_action.basic /-! # Conjugation action of a group on itself > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the conjugation action of a group on itself. See also `mul_aut.conj` for the definition of conjugation as a homomorphism into the automorphism group. ## Main definitions A type alias `conj_act G` is introduced for a group `G`. The group `conj_act G` acts on `G` by conjugation. The group `conj_act G` also acts on any normal subgroup of `G` by conjugation. As a generalization, this also allows: * `conj_act Mˣ` to act on `M`, when `M` is a `monoid` * `conj_act G₀` to act on `G₀`, when `G₀` is a `group_with_zero` ## Implementation Notes The scalar action in defined in this file can also be written using `mul_aut.conj g • h`. This has the advantage of not using the type alias `conj_act`, but the downside of this approach is that some theorems about the group actions will not apply when since this `mul_aut.conj g • h` describes an action of `mul_aut G` on `G`, and not an action of `G`. -/ variables (α M G G₀ R K : Type*) /-- A type alias for a group `G`. `conj_act G` acts on `G` by conjugation -/ def conj_act : Type* := G namespace conj_act open mul_action subgroup variables {M G G₀ R K} instance : Π [group G], group (conj_act G) := id instance : Π [div_inv_monoid G], div_inv_monoid (conj_act G) := id instance : Π [group_with_zero G], group_with_zero (conj_act G) := id instance : Π [fintype G], fintype (conj_act G) := id @[simp] lemma card [fintype G] : fintype.card (conj_act G) = fintype.card G := rfl section div_inv_monoid variable [div_inv_monoid G] instance : inhabited (conj_act G) := ⟨1⟩ /-- Reinterpret `g : conj_act G` as an element of `G`. -/ def of_conj_act : conj_act G ≃* G := ⟨id, id, λ _, rfl, λ _, rfl, λ _ _, rfl⟩ /-- Reinterpret `g : G` as an element of `conj_act G`. -/ def to_conj_act : G ≃* conj_act G := of_conj_act.symm /-- A recursor for `conj_act`, for use as `induction x using conj_act.rec` when `x : conj_act G`. -/ protected def rec {C : conj_act G → Sort*} (h : Π g, C (to_conj_act g)) : Π g, C g := h @[simp] lemma «forall» (p : conj_act G → Prop) : (∀ (x : conj_act G), p x) ↔ ∀ x : G, p (to_conj_act x) := iff.rfl @[simp] lemma of_mul_symm_eq : (@of_conj_act G _).symm = to_conj_act := rfl @[simp] lemma to_mul_symm_eq : (@to_conj_act G _).symm = of_conj_act := rfl @[simp] lemma to_conj_act_of_conj_act (x : conj_act G) : to_conj_act (of_conj_act x) = x := rfl @[simp] lemma of_conj_act_to_conj_act (x : G) : of_conj_act (to_conj_act x) = x := rfl @[simp] lemma of_conj_act_one : of_conj_act (1 : conj_act G) = 1 := rfl @[simp] lemma to_conj_act_one : to_conj_act (1 : G) = 1 := rfl @[simp] lemma of_conj_act_inv (x : conj_act G) : of_conj_act (x⁻¹) = (of_conj_act x)⁻¹ := rfl @[simp] lemma to_conj_act_inv (x : G) : to_conj_act (x⁻¹) = (to_conj_act x)⁻¹ := rfl @[simp] lemma of_conj_act_mul (x y : conj_act G) : of_conj_act (x * y) = of_conj_act x * of_conj_act y := rfl @[simp] lemma to_conj_act_mul (x y : G) : to_conj_act (x * y) = to_conj_act x * to_conj_act y := rfl instance : has_smul (conj_act G) G := { smul := λ g h, of_conj_act g * h * (of_conj_act g)⁻¹ } lemma smul_def (g : conj_act G) (h : G) : g • h = of_conj_act g * h * (of_conj_act g)⁻¹ := rfl end div_inv_monoid section units section monoid variables [monoid M] instance has_units_scalar : has_smul (conj_act Mˣ) M := { smul := λ g h, of_conj_act g * h * ↑(of_conj_act g)⁻¹ } lemma units_smul_def (g : conj_act Mˣ) (h : M) : g • h = of_conj_act g * h * ↑(of_conj_act g)⁻¹ := rfl instance units_mul_distrib_mul_action : mul_distrib_mul_action (conj_act Mˣ) M := { smul := (•), one_smul := by simp [units_smul_def], mul_smul := by simp [units_smul_def, mul_assoc, mul_inv_rev], smul_mul := by simp [units_smul_def, mul_assoc], smul_one := by simp [units_smul_def], } instance units_smul_comm_class [has_smul α M] [smul_comm_class α M M] [is_scalar_tower α M M] : smul_comm_class α (conj_act Mˣ) M := { smul_comm := λ a um m, by rw [units_smul_def, units_smul_def, mul_smul_comm, smul_mul_assoc] } instance units_smul_comm_class' [has_smul α M] [smul_comm_class M α M] [is_scalar_tower α M M] : smul_comm_class (conj_act Mˣ) α M := by { haveI : smul_comm_class α M M := smul_comm_class.symm _ _ _, exact smul_comm_class.symm _ _ _ } end monoid section semiring variables [semiring R] instance units_mul_semiring_action : mul_semiring_action (conj_act Rˣ) R := { smul := (•), smul_zero := by simp [units_smul_def], smul_add := by simp [units_smul_def, mul_add, add_mul], ..conj_act.units_mul_distrib_mul_action} end semiring end units section group_with_zero variable [group_with_zero G₀] @[simp] lemma of_conj_act_zero : of_conj_act (0 : conj_act G₀) = 0 := rfl @[simp] lemma to_conj_act_zero : to_conj_act (0 : G₀) = 0 := rfl instance mul_action₀ : mul_action (conj_act G₀) G₀ := { smul := (•), one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_assoc, mul_inv_rev] } instance smul_comm_class₀ [has_smul α G₀] [smul_comm_class α G₀ G₀] [is_scalar_tower α G₀ G₀] : smul_comm_class α (conj_act G₀) G₀ := { smul_comm := λ a ug g, by rw [smul_def, smul_def, mul_smul_comm, smul_mul_assoc] } instance smul_comm_class₀' [has_smul α G₀] [smul_comm_class G₀ α G₀] [is_scalar_tower α G₀ G₀] : smul_comm_class (conj_act G₀) α G₀ := by { haveI := smul_comm_class.symm G₀ α G₀, exact smul_comm_class.symm _ _ _ } end group_with_zero section division_ring variables [division_ring K] instance distrib_mul_action₀ : distrib_mul_action (conj_act K) K := { smul := (•), smul_zero := by simp [smul_def], smul_add := by simp [smul_def, mul_add, add_mul], ..conj_act.mul_action₀ } end division_ring variables [group G] instance : mul_distrib_mul_action (conj_act G) G := { smul := (•), smul_mul := by simp [smul_def, mul_assoc], smul_one := by simp [smul_def], one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_assoc] } instance smul_comm_class [has_smul α G] [smul_comm_class α G G] [is_scalar_tower α G G] : smul_comm_class α (conj_act G) G := { smul_comm := λ a ug g, by rw [smul_def, smul_def, mul_smul_comm, smul_mul_assoc] } instance smul_comm_class' [has_smul α G] [smul_comm_class G α G] [is_scalar_tower α G G] : smul_comm_class (conj_act G) α G := by { haveI := smul_comm_class.symm G α G, exact smul_comm_class.symm _ _ _ } lemma smul_eq_mul_aut_conj (g : conj_act G) (h : G) : g • h = mul_aut.conj (of_conj_act g) h := rfl /-- The set of fixed points of the conjugation action of `G` on itself is the center of `G`. -/ lemma fixed_points_eq_center : fixed_points (conj_act G) G = center G := begin ext x, simp [mem_center_iff, smul_def, mul_inv_eq_iff_eq_mul] end lemma stabilizer_eq_centralizer (g : G) : stabilizer (conj_act G) g = (zpowers g).centralizer := le_antisymm (le_centralizer_iff.mp (zpowers_le.mpr (λ x, mul_inv_eq_iff_eq_mul.mp))) (λ x h, mul_inv_eq_of_eq_mul (h g (mem_zpowers g)).symm) /-- As normal subgroups are closed under conjugation, they inherit the conjugation action of the underlying group. -/ instance subgroup.conj_action {H : subgroup G} [hH : H.normal] : has_smul (conj_act G) H := ⟨λ g h, ⟨g • h, hH.conj_mem h.1 h.2 (of_conj_act g)⟩⟩ lemma subgroup.coe_conj_smul {H : subgroup G} [hH : H.normal] (g : conj_act G) (h : H) : ↑(g • h) = g • (h : G) := rfl instance subgroup.conj_mul_distrib_mul_action {H : subgroup G} [hH : H.normal] : mul_distrib_mul_action (conj_act G) H := (subtype.coe_injective).mul_distrib_mul_action H.subtype subgroup.coe_conj_smul /-- Group conjugation on a normal subgroup. Analogous to `mul_aut.conj`. -/ def _root_.mul_aut.conj_normal {H : subgroup G} [hH : H.normal] : G →* mul_aut H := (mul_distrib_mul_action.to_mul_aut (conj_act G) H).comp to_conj_act.to_monoid_hom @[simp] lemma _root_.mul_aut.conj_normal_apply {H : subgroup G} [H.normal] (g : G) (h : H) : ↑(mul_aut.conj_normal g h) = g * h * g⁻¹ := rfl @[simp] lemma _root_.mul_aut.conj_normal_symm_apply {H : subgroup G} [H.normal] (g : G) (h : H) : ↑((mul_aut.conj_normal g).symm h) = g⁻¹ * h * g := by { change _ * (_)⁻¹⁻¹ = _, rw inv_inv, refl } @[simp] lemma _root_.mul_aut.conj_normal_inv_apply {H : subgroup G} [H.normal] (g : G) (h : H) : ↑((mul_aut.conj_normal g)⁻¹ h) = g⁻¹ * h * g := mul_aut.conj_normal_symm_apply g h lemma _root_.mul_aut.conj_normal_coe {H : subgroup G} [H.normal] {h : H} : mul_aut.conj_normal ↑h = mul_aut.conj h := mul_equiv.ext (λ x, rfl) instance normal_of_characteristic_of_normal {H : subgroup G} [hH : H.normal] {K : subgroup H} [h : K.characteristic] : (K.map H.subtype).normal := ⟨λ a ha b, by { obtain ⟨a, ha, rfl⟩ := ha, exact K.apply_coe_mem_map H.subtype ⟨_, ((set_like.ext_iff.mp (h.fixed (mul_aut.conj_normal b)) a).mpr ha)⟩ }⟩ end conj_act
1765b2b5b726acab9124056f788490230cab91e8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/monoidal/End.lean
7a37d952ac68f7c8d61c40831bf6df5f2470e073
[ "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
10,502
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Andrew Yang -/ import category_theory.monoidal.functor /-! # Endofunctors as a monoidal category. We give the monoidal category structure on `C ⥤ C`, and show that when `C` itself is monoidal, it embeds via a monoidal functor into `C ⥤ C`. ## TODO Can we use this to show coherence results, e.g. a cheap proof that `λ_ (𝟙_ C) = ρ_ (𝟙_ C)`? I suspect this is harder than is usually made out. -/ universes v u namespace category_theory variables (C : Type u) [category.{v} C] /-- The category of endofunctors of any category is a monoidal category, with tensor product given by composition of functors (and horizontal composition of natural transformations). -/ def endofunctor_monoidal_category : monoidal_category (C ⥤ C) := { tensor_obj := λ F G, F ⋙ G, tensor_hom := λ F G F' G' α β, α ◫ β, tensor_unit := 𝟭 C, associator := λ F G H, functor.associator F G H, left_unitor := λ F, functor.left_unitor F, right_unitor := λ F, functor.right_unitor F, }. open category_theory.monoidal_category local attribute [instance] endofunctor_monoidal_category local attribute [reducible] endofunctor_monoidal_category /-- Tensoring on the right gives a monoidal functor from `C` into endofunctors of `C`. -/ @[simps] def tensoring_right_monoidal [monoidal_category.{v} C] : monoidal_functor C (C ⥤ C) := { ε := (right_unitor_nat_iso C).inv, μ := λ X Y, { app := λ Z, (α_ Z X Y).hom, naturality' := λ Z Z' f, by { dsimp, rw associator_naturality, simp, } }, μ_natural' := λ X Y X' Y' f g, by { ext Z, dsimp, simp [associator_naturality], }, associativity' := λ X Y Z, by { ext W, dsimp, simp [pentagon], }, left_unitality' := λ X, by { ext Y, dsimp, rw [category.id_comp, triangle, ←tensor_comp], simp, }, right_unitality' := λ X, begin ext Y, dsimp, rw [tensor_id, category.comp_id, right_unitor_tensor_inv, category.assoc, iso.inv_hom_id_assoc, ←id_tensor_comp, iso.inv_hom_id, tensor_id], end, ε_is_iso := by apply_instance, μ_is_iso := λ X Y, -- We could avoid needing to do this explicitly by -- constructing a partially applied analogue of `associator_nat_iso`. ⟨⟨{ app := λ Z, (α_ Z X Y).inv, naturality' := λ Z Z' f, by { dsimp, rw ←associator_inv_naturality, simp, } }, by tidy⟩⟩, ..tensoring_right C }. variable {C} variables {M : Type*} [category M] [monoidal_category M] (F : monoidal_functor M (C ⥤ C)) @[simp, reassoc] lemma μ_hom_inv_app (i j : M) (X : C) : (F.μ i j).app X ≫ (F.μ_iso i j).inv.app X = 𝟙 _ := (F.μ_iso i j).hom_inv_id_app X @[simp, reassoc] lemma μ_inv_hom_app (i j : M) (X : C) : (F.μ_iso i j).inv.app X ≫ (F.μ i j).app X = 𝟙 _ := (F.μ_iso i j).inv_hom_id_app X @[simp, reassoc] lemma ε_hom_inv_app (X : C) : F.ε.app X ≫ F.ε_iso.inv.app X = 𝟙 _ := F.ε_iso.hom_inv_id_app X @[simp, reassoc] lemma ε_inv_hom_app (X : C) : F.ε_iso.inv.app X ≫ F.ε.app X = 𝟙 _ := F.ε_iso.inv_hom_id_app X @[simp, reassoc] lemma ε_naturality {X Y : C} (f : X ⟶ Y) : F.ε.app X ≫ (F.obj (𝟙_M)).map f = f ≫ F.ε.app Y := (F.ε.naturality f).symm @[simp, reassoc] lemma ε_inv_naturality {X Y : C} (f : X ⟶ Y) : (F.obj (𝟙_M)).map f ≫ F.ε_iso.inv.app Y = F.ε_iso.inv.app X ≫ f := F.ε_iso.inv.naturality f @[simp, reassoc] lemma μ_naturality {m n : M} {X Y : C} (f : X ⟶ Y) : (F.obj n).map ((F.obj m).map f) ≫ (F.μ m n).app Y = (F.μ m n).app X ≫ (F.obj _).map f := (F.to_lax_monoidal_functor.μ m n).naturality f -- This is a simp lemma in the reverse direction via `nat_trans.naturality`. @[reassoc] lemma μ_inv_naturality {m n : M} {X Y : C} (f : X ⟶ Y) : (F.μ_iso m n).inv.app X ≫ (F.obj n).map ((F.obj m).map f) = (F.obj _).map f ≫ (F.μ_iso m n).inv.app Y := ((F.μ_iso m n).inv.naturality f).symm -- This is not a simp lemma since it could be proved by the lemmas later. @[reassoc] lemma μ_naturality₂ {m n m' n' : M} (f : m ⟶ m') (g : n ⟶ n') (X : C) : (F.map g).app ((F.obj m).obj X) ≫ (F.obj n').map ((F.map f).app X) ≫ (F.μ m' n').app X = (F.μ m n).app X ≫ (F.map (f ⊗ g)).app X := begin have := congr_app (F.to_lax_monoidal_functor.μ_natural f g) X, dsimp at this, simpa using this, end @[simp, reassoc] lemma μ_naturalityₗ {m n m' : M} (f : m ⟶ m') (X : C) : (F.obj n).map ((F.map f).app X) ≫ (F.μ m' n).app X = (F.μ m n).app X ≫ (F.map (f ⊗ 𝟙 n)).app X := begin rw ← μ_naturality₂ F f (𝟙 n) X, simp, end @[simp, reassoc] lemma μ_naturalityᵣ {m n n' : M} (g : n ⟶ n') (X : C) : (F.map g).app ((F.obj m).obj X) ≫ (F.μ m n').app X = (F.μ m n).app X ≫ (F.map (𝟙 m ⊗ g)).app X := begin rw ← μ_naturality₂ F (𝟙 m) g X, simp, end @[simp, reassoc] lemma μ_inv_naturalityₗ {m n m' : M} (f : m ⟶ m') (X : C) : (F.μ_iso m n).inv.app X ≫ (F.obj n).map ((F.map f).app X) = (F.map (f ⊗ 𝟙 n)).app X ≫ (F.μ_iso m' n).inv.app X := begin rw [← is_iso.comp_inv_eq, category.assoc, ← is_iso.eq_inv_comp], simp, end @[simp, reassoc] lemma μ_inv_naturalityᵣ {m n n' : M} (g : n ⟶ n') (X : C) : (F.μ_iso m n).inv.app X ≫ (F.map g).app ((F.obj m).obj X) = (F.map (𝟙 m ⊗ g)).app X ≫ (F.μ_iso m n').inv.app X := begin rw [← is_iso.comp_inv_eq, category.assoc, ← is_iso.eq_inv_comp], simp, end @[reassoc] lemma left_unitality_app (n : M) (X : C) : (F.obj n).map (F.ε.app X) ≫ (F.μ (𝟙_M) n).app X ≫ (F.map (λ_ n).hom).app X = 𝟙 _ := begin have := congr_app (F.to_lax_monoidal_functor.left_unitality n) X, dsimp at this, simpa using this.symm, end @[reassoc, simp] lemma obj_ε_app (n : M) (X : C) : (F.obj n).map (F.ε.app X) = (F.map (λ_ n).inv).app X ≫ (F.μ_iso (𝟙_M) n).inv.app X := begin refine eq.trans _ (category.id_comp _), rw [← category.assoc, ← is_iso.comp_inv_eq, ← is_iso.comp_inv_eq, category.assoc], convert left_unitality_app F n X, { simp }, { ext, simpa } end @[reassoc, simp] lemma obj_ε_inv_app (n : M) (X : C) : (F.obj n).map (F.ε_iso.inv.app X) = (F.μ (𝟙_M) n).app X ≫ (F.map (λ_ n).hom).app X := begin rw [← cancel_mono ((F.obj n).map (F.ε.app X)), ← functor.map_comp], simpa, end @[reassoc] lemma right_unitality_app (n : M) (X : C) : F.ε.app ((F.obj n).obj X) ≫ (F.μ n (𝟙_M)).app X ≫ (F.map (ρ_ n).hom).app X = 𝟙 _ := begin have := congr_app (F.to_lax_monoidal_functor.right_unitality n) X, dsimp at this, simpa using this.symm, end @[simp] lemma ε_app_obj (n : M) (X : C) : F.ε.app ((F.obj n).obj X) = (F.map (ρ_ n).inv).app X ≫ (F.μ_iso n (𝟙_M)).inv.app X := begin refine eq.trans _ (category.id_comp _), rw [← category.assoc, ← is_iso.comp_inv_eq, ← is_iso.comp_inv_eq, category.assoc], convert right_unitality_app F n X, { simp }, { ext, simpa } end @[simp] lemma ε_inv_app_obj (n : M) (X : C) : F.ε_iso.inv.app ((F.obj n).obj X) = (F.μ n (𝟙_M)).app X ≫ (F.map (ρ_ n).hom).app X := begin rw [← cancel_mono (F.ε.app ((F.obj n).obj X)), ε_inv_hom_app], simpa end @[reassoc] lemma associativity_app (m₁ m₂ m₃: M) (X : C) : (F.obj m₃).map ((F.μ m₁ m₂).app X) ≫ (F.μ (m₁ ⊗ m₂) m₃).app X ≫ (F.map (α_ m₁ m₂ m₃).hom).app X = (F.μ m₂ m₃).app ((F.obj m₁).obj X) ≫ (F.μ m₁ (m₂ ⊗ m₃)).app X := begin have := congr_app (F.to_lax_monoidal_functor.associativity m₁ m₂ m₃) X, dsimp at this, simpa using this, end @[reassoc, simp] lemma obj_μ_app (m₁ m₂ m₃ : M) (X : C) : (F.obj m₃).map ((F.μ m₁ m₂).app X) = (F.μ m₂ m₃).app ((F.obj m₁).obj X) ≫ (F.μ m₁ (m₂ ⊗ m₃)).app X ≫ (F.map (α_ m₁ m₂ m₃).inv).app X ≫ (F.μ_iso (m₁ ⊗ m₂) m₃).inv.app X := begin rw [← associativity_app_assoc], dsimp, simp, dsimp, simp, end @[reassoc, simp] lemma obj_μ_inv_app (m₁ m₂ m₃ : M) (X : C) : (F.obj m₃).map ((F.μ_iso m₁ m₂).inv.app X) = (F.μ (m₁ ⊗ m₂) m₃).app X ≫ (F.map (α_ m₁ m₂ m₃).hom).app X ≫ (F.μ_iso m₁ (m₂ ⊗ m₃)).inv.app X ≫ (F.μ_iso m₂ m₃).inv.app ((F.obj m₁).obj X) := begin rw ← is_iso.inv_eq_inv, convert obj_μ_app F m₁ m₂ m₃ X using 1, { ext, rw ← functor.map_comp, simp }, { simp only [monoidal_functor.μ_iso_hom, category.assoc, nat_iso.inv_inv_app, is_iso.inv_comp], congr, { ext, simp }, { ext, simpa } } end @[simp, reassoc] lemma obj_zero_map_μ_app {m : M} {X Y : C} (f : X ⟶ (F.obj m).obj Y) : (F.obj (𝟙_M)).map f ≫ (F.μ m (𝟙_M)).app _ = F.ε_iso.inv.app _ ≫ f ≫ (F.map (ρ_ m).inv).app _ := begin rw [← is_iso.inv_comp_eq, ← is_iso.comp_inv_eq], simp, end @[simp] lemma obj_μ_zero_app (m₁ m₂ : M) (X : C) : (F.obj m₂).map ((F.μ m₁ (𝟙_M)).app X) = (F.μ (𝟙_M) m₂).app ((F.obj m₁).obj X) ≫ (F.map (λ_ m₂).hom).app ((F.obj m₁).obj X) ≫ (F.obj m₂).map ((F.map (ρ_ m₁).inv).app X) := begin rw [← obj_ε_inv_app_assoc, ← functor.map_comp], congr, simp, end /-- If `m ⊗ n ≅ 𝟙_M`, then `F.obj m` is a left inverse of `F.obj n`. -/ @[simps] noncomputable def unit_of_tensor_iso_unit (m n : M) (h : m ⊗ n ≅ 𝟙_M) : F.obj m ⋙ F.obj n ≅ 𝟭 C := F.μ_iso m n ≪≫ F.to_functor.map_iso h ≪≫ F.ε_iso.symm /-- If `m ⊗ n ≅ 𝟙_M` and `n ⊗ m ≅ 𝟙_M` (subject to some commuting constraints), then `F.obj m` and `F.obj n` forms a self-equivalence of `C`. -/ @[simps] noncomputable def equiv_of_tensor_iso_unit (m n : M) (h₁ : m ⊗ n ≅ 𝟙_M) (h₂ : n ⊗ m ≅ 𝟙_M) (H : (h₁.hom ⊗ 𝟙 m) ≫ (λ_ m).hom = (α_ m n m).hom ≫ (𝟙 m ⊗ h₂.hom) ≫ (ρ_ m).hom) : C ≌ C := { functor := F.obj m, inverse := F.obj n, unit_iso := (unit_of_tensor_iso_unit F m n h₁).symm, counit_iso := unit_of_tensor_iso_unit F n m h₂, functor_unit_iso_comp' := begin intro X, dsimp, simp only [μ_naturalityᵣ_assoc, μ_naturalityₗ_assoc, ε_inv_app_obj, category.assoc, obj_μ_inv_app, functor.map_comp, μ_inv_hom_app_assoc, obj_ε_app, unit_of_tensor_iso_unit_inv_app], simp [← nat_trans.comp_app, ← F.to_functor.map_comp, ← H, - functor.map_comp] end } end category_theory
dbcb5449fc05380e936348dcbaab547ee71196b7
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/order/filter/at_top_bot.lean
67ae2f141ce88347c32594006bb1e433e3fc95fb
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
41,684
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, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import order.filter.bases /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := no_top x in mem_sets_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_sets a $ subset.refl _ lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := no_bot x in mem_sets_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ lemma at_bot_basis [nonempty α] [semilattice_inf α] : (@at_bot α _).has_basis (λ _, true) Iic := @at_top_basis (order_dual α) _ _ lemma at_bot_basis' [semilattice_inf α] (a : α) : (@at_bot α _).has_basis (λ x, x ≤ a) Iic := @at_top_basis' (order_dual α) _ _ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.forall_nonempty_iff_ne_bot.1 $ λ a _, nonempty_Ici @[instance] lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) := @at_top_ne_bot (order_dual α) _ _ @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp] lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} : s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s := @mem_at_top_sets (order_dual α) _ _ _ @[simp] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets @[simp] lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) := mem_at_bot_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := countable_encodable _, .. at_top_basis } lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [encodable α] : has_countable_basis (at_bot : filter α) (λ _, true) Iic := { countable := countable_encodable _, .. at_bot_basis } lemma is_countably_generated_at_top [nonempty α] [semilattice_sup α] [encodable α] : (at_top : filter $ α).is_countably_generated := at_top_countable_basis.is_countably_generated lemma is_countably_generated_at_bot [nonempty α] [semilattice_inf α] [encodable α] : (at_bot : filter $ α).is_countably_generated := at_bot_countable_basis.is_countably_generated lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma order_bot.at_bot_eq (α) [order_bot α] : (at_bot : filter α) = pure ⊥ := @order_top.at_top_eq (order_dual α) _ lemma tendsto_at_top_pure [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ lemma tendsto_at_bot_pure [order_bot α] (f : α → β) : tendsto f at_bot (pure $ f ⊥) := @tendsto_at_top_pure (order_dual α) _ _ _ lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b := eventually_at_bot.mp h lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp only [filter.frequently, eventually_at_top, not_exists, not_forall, not_not] lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) := @frequently_at_top (order_dual α) _ _ _ lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := begin rw frequently_at_top, split ; intros h a, { cases no_top a with a' ha', rcases h a' with ⟨b, hb, hb'⟩, exact ⟨b, lt_of_lt_of_le ha' hb, hb'⟩ }, { rcases h a with ⟨b, hb, hb'⟩, exact ⟨b, le_of_lt hb, hb'⟩ }, end lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_bot_order α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) := @frequently_at_top' (order_dual α) _ _ _ _ lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b := frequently_at_bot.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} : at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) := @map_at_top_eq (order_dual α) _ _ _ _ lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_set_of_eq] lemma tendsto_at_bot [preorder β] (m : α → β) (f : filter α) : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α (order_dual β) _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, (tendsto_at_top _ _).2 $ λ b, mp_sets ((tendsto_at_top _ _).1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := @tendsto_at_top_mono' _ (order_dual β) _ _ _ _ h lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := @tendsto_at_top_mono _ (order_dual β) _ _ _ _ h /-! ### Sequences -/ lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U := @inf_map_at_top_ne_bot_iff (order_dual α) _ _ _ _ _ lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono.nat (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) : ∀ a b, ∃ a' ≥ a, b ≤ u a' := begin intros a b, have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b := @exists_le_of_tendsto_at_top _ (order_dual β) _ _ _ h lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) : ∀ a b, ∃ a' ≥ a, b < u a' := begin intros a b, cases no_top b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_bot_order β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b := @exists_lt_of_tendsto_at_top _ (order_dual β) _ _ _ _ h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin letI := classical.DLO β, intros N, let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N} have Ane : A.nonempty, from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩, let M := multiset.sup' A.1 Ane, have ex : ∃ n ≥ N, M < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M, { use nat.find ex, rw ← and_assoc, split, { simpa using nat.find_spec ex }, { intros k hk hk', simpa [hk] using nat.find_min ex hk' } }, use [n, hnN], intros k hk, by_cases H : k ≤ N, { have : u k ∈ A, from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H), have : u k ≤ M, from multiset.le_sup' _ (u k) this, exact lt_of_le_of_lt this hnM }, { push_neg at H, calc u k ≤ M : hn_min k (le_of_lt H) hk ... < u n : hnM }, end /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k := @high_scores (order_dual β) _ _ _ hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ lemma frequently_low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k := @frequently_high_scores (order_dual β) _ _ _ hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma strict_mono_tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' ((tendsto_at_top (λ (a : α), f a) l).mp hf 0) hg lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add _ (order_dual β) _ _ _ _ hf hg end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, ((tendsto_at_top _ _).1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, ((tendsto_at_top _ _).1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) : tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left _ (order_dual β) _ _ _ _ C hC lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right _ (order_dual β) _ _ _ _ C hC end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, C + f x) l at_bot := @tendsto_at_top_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, f x + C) l at_bot := @tendsto_at_top_add_const_right _ (order_dual β) _ _ _ C hf end ordered_group open_locale filter lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] (f : α → β) (l : filter β) : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' (order_dual α) _ _ _ _ _ theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s := @tendsto_at_top_principal _ (order_dual β) _ _ _ _ /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin rw [tendsto_at_top, tendsto_at_top], split, { assume hc b, filter_upwards [hc (e b)] assume a, (hm b (f a)).1 }, { assume hb c, rcases hu c with ⟨b, hc⟩, filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) } end /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_bot_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := begin rw [tendsto_at_bot, tendsto_at_bot], split, { assume hc b, filter_upwards [hc (e b)] assume a, (hm (f a) b).1 }, { assume hb c, rcases hu c with ⟨b, hc⟩, filter_upwards [hb b] assume a ha, le_trans ((hm (f a) b).2 ha) hc } end lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] (f : α → β) : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top (order_dual α) β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] (f : α → β) : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, f a ≤ b) : tendsto f at_bot at_bot := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := (tendsto_at_top_at_top f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b := (tendsto_at_bot_at_bot f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top alias tendsto_at_bot_at_bot_of_monotone ← monotone.tendsto_at_bot_at_bot alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff alias tendsto_at_bot_at_bot_iff_of_monotone ← monotone.tendsto_at_bot_at_bot_iff lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) := begin refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _, refine le_infi (λ s, le_principal_iff.2 $ mem_infi_iff.2 _), refine ⟨↑s, s.finite_to_set, _, λ i, mem_principal_self _, _⟩, simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset, finset.mem_singleton, finset.subset_iff, forall_eq], dsimp, exact λ t, id end /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma tendsto_at_top_finset_of_monotone [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal], intro a, rcases h' a with ⟨b, hb⟩, exact eventually.mono (mem_at_top b) (λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')), end alias tendsto_at_top_finset_of_monotone ← monotone.tendsto_at_top_finset lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_finset $ assume a, ⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩ lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) : tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top := (finset.monotone_preimage hf).tendsto_at_top_finset $ λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin by_cases ne : nonempty β₁ ∧ nonempty β₂, { cases ne, resetI, simp [at_top, prod_infi_left, prod_infi_right, infi_prod], exact infi_comm }, { rw not_and_distrib at ne, cases ne; { have : ¬ (nonempty (β₁ × β₂)), by simp [ne], rw [at_top.filter_eq_bot_of_not_nonempty ne, at_top.filter_eq_bot_of_not_nonempty this], simp only [bot_prod, prod_bot] } } end lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] : (at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) := @prod_at_top_at_top_eq (order_dual β₁) (order_dual β₂) _ _ lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := @prod_map_at_top_eq _ _ (order_dual β₁) (order_dual β₂) _ _ _ _ /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin refine le_antisymm (hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _, rw [@map_at_top_eq _ _ ⟨g b'⟩], refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _), rw [mem_set_of_eq, sup_le_iff] at hb, exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 (le_refl _)) (hgi _ hb.2)⟩ end lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) : map f at_bot = at_bot := @map_at_top_eq_of_gc (order_dual α) (order_dual β) _ _ _ _ _ hf.order_dual gc hgi lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) : tendsto u at_bot at_bot := @tendsto_at_top_at_top_of_monotone' (order_dual ι) (order_dual α) _ _ _ h.order_dual H lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a (le_refl _) ... ≤ M : hM (set.mem_range_self a) end lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top _ (order_dual β) _ _ _ _ _ h lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬ bdd_above (range f) := @unbounded_of_tendsto_at_top (order_dual α) _ _ _ _ _ _ h lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := @tendsto_at_top_of_monotone_of_filter (order_dual ι) (order_dual α) _ _ _ _ h.order_dual _ hu lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_neg_at_top_at_bot [ordered_add_comm_group α] : tendsto (has_neg.neg : α → α) at_top at_bot := begin simp only [tendsto_at_bot, neg_le], exact λ b, eventually_ge_at_top _ end lemma tendsto_neg_at_bot_at_top [ordered_add_comm_group α] : tendsto (has_neg.neg : α → α) at_bot at_top := @tendsto_neg_at_top_at_bot (order_dual α) _ /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := (at_top_basis.tendsto_iff hl.to_has_basis).2 $ assume i hi, ⟨i, trivial, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩ namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rcases hcb.exists_antimono_seq with ⟨g, gmon, gbasis⟩, have gbasis : k.has_basis (λ _, true) (λ i, (g i)), { subst gbasis, exact has_basis_infi_principal (directed_of_sup gmon) }, contrapose, simp only [not_forall, gbasis.tendsto_left_iff, exists_const, not_exists, not_imp], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { exact (at_top_basis.tendsto_iff gbasis).2 (λ i _, ⟨i, trivial, λ j hj, gmon hj (h j).1⟩) }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin rcases hf.has_antimono_basis with ⟨B, h⟩, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp $ strict_mono_tendsto_at_top hψ⟩, end end is_countably_generated end filter open filter finset /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
55ac0e6576440ce47be1574378fd55cd01a65a1e
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/Exams/FinalExam2102F19.lean
960aa1e0b298f5f0328a7f2ac7a729b8073875e4
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
10,216
lean
/- Complete exam below. Attest to agreement to honor code. Submit your exam when done. -/ namespace hidden -- you can ignore this /- 1. [10 points] We define a polymorphic tree type. A tree of values of type α is either empty or it is a node formed from value of type α along with two smaller trees, left and right, of the same kind. The left and right trees are often called the children of a given node. We formalize this definition as a polymorphic inductive type with two constructors, one, empty, with no arguments, and one, with three arguments, as follows. -/ inductive tree (α : Type) : Type | empty : tree | node (value : α) (left : tree) (right : tree) : tree /- 1A. Define three values of type "tree nat": the first, t1, as the empty tree (of nat); the second, as a tree of nat with one node, containing the value 5 and with two empty children; and t3, a tree with 1 value in its "top" node, where each child tree is a node with the value 5 and two empty children. Note: You need to give a type argment explicitly when you use the empty constructor, but now when you use the node constructor, as its value can be inferred in the second case. -/ open tree --ANSWER def t1 : tree nat := tree.empty ℕ def t2 : tree nat := tree.node 5 t1 t1 def t3 : tree nat := tree.node 1 t2 t2 /- 1b. Define a function, tree_sum, that takes a value of type tree nat, and that returns the *sum* of all of the values in the given tree. Hint: You may want to test your function using some of the trees you just defined as arguments. -/ -- ANSWER def tree_sum : (tree nat) → ℕ | (tree.empty α) := 0 | (tree.node a l r) := a + (tree_sum l) + (tree_sum r) #eval tree_sum t3 /- 2. [10 points] The memory of a computer is an array of memory cells called words. Each word has a numerical "address", from zero to the number of words in the memory minus one. If an address is a represented as a 16-bit value, how big can the memory of the computer be? -/ -- ANSWER -- 2^16 /- 3. [10 points] Define a polymorphic function, tree_to_list, that takes a value of type tree α as an argument and returns a value of type list α, where the returned list contains all and only the values that appear in the tree: none if the tree is empty, otherwise the value in the top (given) node, then all the values in the left child, then all of the values in the right child. Hints: Remember to specify α as the type argument to tree.empty explicitly, and put parentheses around the "patterns" to the left of := when pattern matching. Also, the list namespace is not open by default, so use list.cons and list.nil for the list constructors. Remember that list.append can be used to append two lists. Finally, you might want to test your definition using the tree values you defined above. -/ open list -- ANSWER def tree_to_list {α : Type} : (tree α) → list α | (tree.empty α) := list.nil | (tree.node a l r) := list.cons a (tree_to_list l) /- 4. [15 points] The next two problems ask you to specify the set of natural numbers that are multiples of three in two different ways: first as a simple predicate, and then as an inductive definition. 4a. Specify a simple predicate (hint, use the mod function, denoted %) that is true for each multiple of three and false otherwise. -/ def mult_three (n: ℕ) : Prop := ∀(n), n%3=0 /- 4b. Specify the set of multiples of three as an inductively defined family of propositions called is_mult_three taking a natural number argument. The proof constructors should provide proofs for argument values that are multiples of three and not for values that are not multiples of three. Hint: zero is a multiple of three, and, for any n, if n is a multiple of three, then so is n+3. -/ inductive is_mult_three : ℕ → Prop | pf_zero : (is_mult_three 0) | pf_mult_three : ∀(n : ℕ), is_mult_three (n) → is_mult_three(nat.succ(nat.succ(nat.succ n))) /- 4c. State and prove the proposition that 9 is a multiple of three: is_mult_three 9. (Don't use the "mod" version here.) -/ example : is_mult_three 9 := begin apply is_mult_three.pf_mult_three, apply is_mult_three.pf_mult_three, apply is_mult_three.pf_mult_three, apply is_mult_three.pf_zero, end /- 5. [5 points]. Consider a binary relation, R, on a set of values of some arbitrary type, α. In plain but precise mathematical English, explain what it means for R to be transitive. -/ -- Answer /- 6. [10 points] Here we set up a set of assumptions and you are to prove a conclusion. -/ axioms (Raining Sprinkler Wet : Prop) axiom rw : Raining → Wet axiom sw : Sprinkler → Wet axiom h : Raining ∨ Sprinkler /- Given these assumptions, prove "Wet". Hint: it's a one-line proof, very short. -/ example : Wet := begin cases h, apply rw h, apply sw h, end /- [10 points] 7. Use an inductive definition to formally specify a ternary (three-place) relation, times_rel, on ℕ numbers, such that a triple, (m, n, k) is in the relation if and only if k = m * n, then state and prove the proposition that the triple, (5, 6, 30), is in the relation. Hint: You need one constructor. Call it intro. -/ -- Answer here inductive times_rel : nat → nat → nat → Prop | intro : ∀(m n k : ℕ), (k = m*n) → times_rel m n k example : times_rel 5 6 30 := begin apply times_rel.intro, apply eq.refl (30), end /- 8. [10 points] Suppose there are balls; that a ball can be made of uranium; that a ball can be heavy; and that if a ball is made from uranium then it is heavy. Prove that there if there is a ball made of uranium then there is a ball that is heavy. -/ -- Here are the assumptions axiom Ball : Type axiom Uranium : Ball → Prop axiom Heavy : Ball → Prop axiom uh: ∀ (b : Ball), Uranium b → Heavy b /- 8a. *Informally* (in English) prove the conjecture that if there is a Ball that is made of uranium then there is a heavy ball. Identify exactly the rules of inference (introduction and elimination) that you are using to reach your conclusion. I.e., give a precise and complete mathematical proof, without constructing a formal proof. -/ -- Answer /- Assume that a ball, a, is made of Uranium. Assume the proposition, uh, that if a ball is made of Uranium it is also heavy. These two assume statements were reached using introduction. Since it is true that ball a is made of urianium, by proposition uh we know that ball a is heavy. This can be proven using the definition of implication. -/ /- 8b. Formally prove the conjecture that if there is a ball made of uranium, then there is a heavy ball. Hint: Put parentheses around the major elements of the proposition to be proved. Second hint: Lean won't show the preceding axioms as being in your proof contet, but you may (and will have to) use at least one of them. -/ example : (∃ (b : Ball), Uranium b) → ∃ (b : Ball), Heavy b := begin intros, cases a with b ub, have hb := uh b, have haevy := hb ub, apply exists.intro b, assumption, end /- 9. [10 points] Recall that a binary relation, R, on a set of values of some type, α, is said to be asymmetric if whenever a pair (x, y) is in R, the pair (y, x) is not; and that R is said to be irreflexive if for all x, (x, x) is not in R. Give a mathematically precise but informal (English language) proof that if a given binary relation, R, is asymmetric then it is irreflexive. As part of your proof, define, using precise but informal mathematical English, what each of these properties means. And define using mathematical notation the conjecture you are to prove. Identify each inference rule you use in writing your informal proof. -/ -- Answer /- A binary relation is Asymmetric when the ordering of the supplied pair affects the outcome of the relation. For example, if R is asymmetric then whenever a pair (x, y) is in R, the pair (y, x) is not. In mathematical notation, ∀ (x y : α), R x y → ¬ R y x A binary relation is Irreflexive if applying the same value as both arguments to the relation result in a statment that is not true. For example, a binary relation, R, is irreflexive if the pair (x,x) is not in R. In mathematical notation, ∀ (x : α), ¬ R x x If a binary relation is asymmetric it implies that it is also irreflexive. This is shown with the mathematical expression below ∀ (α : Type) (F : α → α → Prop), asymmetric F → irreflexive F Using the mathematical notation for asymmetric and irreflexive from above we can write the second half of the Proposition as follows, ∀ (x y : α),(R : Bin_op), (R x y → ¬ R y x) → (∀ (x : α),(¬ R x x)) To prove this relation we do the followig 1) Assume there is some value x of type α 2) Assume there is a value rxx that is bin_op R applied to the pair (x,x). 3) Apply value x to the asymmetric definition and call this val rxxnrxx. rxxnrxx evaluates to R x x → ¬R x x 4) apply value rxx to the Proposition rxxnrxx. This will yield a value of ¬ R x x which we will can nrxx 5) At this point we have a contradiction in our assumptions. A contradiction is when two oposite claims are held at the same time. The opposite claims that we are holding are rxx and nrxx. Since these can not both be true we have proved irreflexive by contradiction. -/ /- 10. [5 points]. Formally prove the proposition, ¬ false. -/ example : ¬ false := begin apply false.elim, end /- 11. [5 points] Formally prove the proposition, ¬ true → false. -/ -- Answer example : ¬ true → false := begin assume nt, apply not.intro nt, apply true.intro, end /- Extra credit. Suppose P and Q are arbitrary propositions. Formally prove that, ¬ ( P ∧ Q) ↔ (¬ P ∨ ¬ Q). Hint: Do you have to reason classically? Or does it help? -/ -- Answer example (P Q : Prop): ¬ ( P ∧ Q) ↔ (¬ P ∨ ¬ Q) := begin intros, apply iff.intro, intros npandq, apply or.inl, assume p, end end hidden -- You can ignore this
e5feeefc9669d2a234ec866aae85f953ff52dd45
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/opaque_hint_bug.lean
70ef84fb447453f324a3794d7dce9b041b5bb031
[ "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
230
lean
inductive list (T : Type) : Type := nil {} : list T, cons : T → list T → list T section variable {T : Type} definition concat (s t : list T) : list T := list.rec t (fun x l u, list.cons x u) s reducible concat end
8d38def1efdde580eeb6c88dd5c41534afeca4ba
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/src/tidy/rewrite_search/tracer/graph.lean
8ef4563ba99f1ea09151db018d8c657a2d9f384c
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
5,426
lean
import tidy.rewrite_search.engine import tidy.lib import system.io open tidy.rewrite_search namespace tidy.rewrite_search.tracer.graph open tactic open io.process.stdio def SUCCESS_CHAR : string := "S" def ERROR_CHAR : string := "E" def SEARCH_PATHS : list string := [ "_target/deps/lean-tidy/res/graph_tracer", "res/graph_tracer" ] def get_app_path (dir : string) (app : string) : string := dir ++ "/" ++ app ++ ".py" def args (dir : string) (app : string) : io.process.spawn_args := { cmd := "python3", args := [get_app_path dir app], stdin := piped, stdout := piped, stderr := inherit, env := [ ("PYTHONPATH", some (dir ++ "/pygraphvis.zip/pygraphvis")), ("PYTHONIOENCODING", "utf-8") ], } structure visualiser := (proc : io.proc.child) meta def visualiser.publish (v : visualiser) (s : string) : tactic unit := let chrs : list char := (s.to_list.stripl ['\n', '\x0D']).append ['\n'] in tactic.unsafe_run_io (io.fs.write v.proc.stdin (char_buffer.from_list (utf8decode chrs))) meta def visualiser.pause (v : visualiser) : tactic unit := tactic.unsafe_run_io (do io.fs.read v.proc.stdout 1, return ()) def file_exists (path : string) : io bool := do c ← io.proc.spawn { cmd := "test", args := ["-f", path] }, retval ← io.proc.wait c, return (retval = 0) inductive spawn_result | success : io.proc.child → spawn_result -- Client launched and the client reported success status | abort : string → spawn_result -- Client launched and we got a bad response code | failure -- Could not launch client | missing -- The script we tried to launch does't exist meta def read_until_nl (h : io.handle) : io string := do c ← io.fs.read h 1, match c.to_list with | ['\n'] := return "" | [c] := do r ← read_until_nl, return (c.to_string ++ r) | _ := return "" end meta def try_launch_with_path (path : string) : io spawn_result := do ex ← file_exists (get_app_path path "client"), if ex then do c ← io.proc.spawn (args path "client"), buff ← io.fs.read c.stdout 1, str ← pure (buff.to_string), if str = SUCCESS_CHAR then return (spawn_result.success c) else if str = ERROR_CHAR then do reason ← read_until_nl c.stdout, return (spawn_result.abort reason) else if str = "" then return spawn_result.failure else return (spawn_result.abort (format!"bug: unknown client status character \"{str}\"").to_string) else return spawn_result.missing meta def try_launch_with_paths : list string → io spawn_result | [] := return spawn_result.failure | (p :: rest) := do sr ← try_launch_with_path p, match sr with | spawn_result.missing := try_launch_with_paths rest | _ := return sr end meta def diagnose_launch_failure : io string := do c ← io.proc.spawn { cmd := "python3", args := ["--version"], stdin := piped, stdout := piped, stderr := piped }, r ← io.proc.wait c, match r with | 255 := return "python3 is missing, and the graph visualiser requires it. Please install python3." | 0 := return "bug: python3 present but could not launch client!" | ret := return (format!"bug: unexpected return code {ret} during launch failure diagnosis").to_string end open tidy.rewrite_search.init_result meta def graph_tracer_init : tactic (init_result visualiser) := do c ← tactic.unsafe_run_io (try_launch_with_paths SEARCH_PATHS), match c with | spawn_result.success c := let vs : visualiser := ⟨ c ⟩ in do vs.publish "S\n", return (success vs) | spawn_result.abort reason := return (failure visualiser ("Error! " ++ reason)) | spawn_result.failure := do reason ← tactic.unsafe_run_io diagnose_launch_failure, return (failure visualiser ("Error! " ++ reason)) | spawn_result.missing := return (failure visualiser ("Error! bug: could not determine client location")) end meta def graph_tracer_publish_vertex (vs : visualiser) (v : vertex) : tactic unit := do vs.publish (to_string (format!"V|{v.id.to_string}|{v.s.to_string}|{v.pp}")) meta def graph_tracer_publish_edge (vs : visualiser) (e : edge) : tactic unit := vs.publish (to_string (format!"E|{e.f.to_string}|{e.t.to_string}")) meta def graph_tracer_publish_pair (vs : visualiser) (l r : vertex_ref) : tactic unit := vs.publish (to_string (format!"P|{l.to_string}|{r.to_string}")) meta def graph_tracer_publish_visited (vs : visualiser) (v : vertex) : tactic unit := vs.publish (to_string (format!"B|{v.id.to_string}")) meta def graph_tracer_publish_finished (vs : visualiser) (es : list edge) : tactic unit := do es.mmap' (λ e : edge, vs.publish (to_string (format!"F|{e.f.to_string}|{e.t.to_string}"))), vs.publish (to_string (format!"D")) meta def graph_tracer_dump (vs : visualiser) (str : string) : tactic unit := vs.publish (str ++ "\n") meta def graph_tracer_pause (vs : visualiser) : tactic unit := vs.pause end tidy.rewrite_search.tracer.graph namespace tidy.rewrite_search.tracer open tidy.rewrite_search.tracer.graph meta def graph_tracer : tracer visualiser := ⟨ graph_tracer_init, graph_tracer_publish_vertex, graph_tracer_publish_edge, graph_tracer_publish_pair, graph_tracer_publish_visited, graph_tracer_publish_finished, graph_tracer_dump, graph_tracer_pause ⟩ end tidy.rewrite_search.tracer
8039983a86e131677955a2c9a2e9b7be170ce41d
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Elab/Do.lean
a32b9ad12fbf3a3e2204f98355c425fc492f89d5
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,093
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.Quotation import Lean.Elab.Match namespace Lean namespace Elab namespace Term open Meta @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" private partial def hasLiftMethod : Syntax → Bool | Syntax.node k args => if k == `Lean.Parser.Term.do then false else if k == `Lean.Parser.Term.doSeqIndent then false else if k == `Lean.Parser.Term.doSeqBracketed then false else if k == `Lean.Parser.Term.quot then false else if k == `Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult := (m : Expr) (α : Expr) (hasBindInst : Expr) private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do u ← getLevel type; let id := Lean.mkConst `Id [u]; let idBindVal := Lean.mkConst `Id.hasBind [u]; pure { m := id, hasBindInst := idBindVal, α := type } private def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid do notation, expected type is not available" | some expectedType => do type ← withReducible $ whnf expectedType; when type.getAppFn.isMVar $ throwError "invalid do notation, expected type is not available"; match type with | Expr.app m α _ => catch (do bindInstType ← mkAppM `HasBind #[m]; bindInstVal ← synthesizeInst bindInstType; pure { m := m, hasBindInst := bindInstVal, α := α }) (fun ex => mkIdBindFor type) | _ => mkIdBindFor type namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) := (ref : Syntax) (vars : Array Name) (patterns : Array Syntax) (rhs : σ) /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return`: returning the result of the computation. - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue` and `return` are "exit points" The terminal `return` also contains the name of the variable containing the result of the computation. We ignore this value when inside a `for x in s`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `action` is an action-like `doElem` (e.g., `IO.println "hello"`, `dbgTrace! "foo"`). A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code | decl (xs : Array Name) (stx : Syntax) (cont : Code) | reassign (xs : Array Name) (stx : Syntax) (cont : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (cont : Code) | action (stx : Syntax) (cond : Code) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (discrs : Array Syntax) (type? : Option Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) instance Code.inhabited : Inhabited Code := ⟨Code.«break» (arbitrary _)⟩ instance Alt.inhabited : Inhabited (Alt Code) := ⟨{ ref := arbitrary _, vars := #[], patterns := #[], rhs := arbitrary _ }⟩ /- A code block, and the collection of variables updated by it. -/ structure CodeBlock := (code : Code) (uvars : NameSet := {}) -- set of variables updated by `code` private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def toMessageDataAux (updateVars : MessageData) : Code → MessageData | Code.decl xs _ k => "let " ++ varsToMessageData xs ++ " := ... " ++ Format.line ++ toMessageDataAux k | Code.reassign xs _ k => varsToMessageData xs ++ " := ... " ++ Format.line ++ toMessageDataAux k | Code.joinpoint n ps body k => "let " ++ n.simpMacroScopes ++ " " ++ varsToMessageData (ps.map Prod.fst) ++ " := " ++ indentD (toMessageDataAux body) ++ Format.line ++ toMessageDataAux k | Code.action e k => e ++ Format.line ++ toMessageDataAux k | Code.ite _ _ _ c t e => "if " ++ c ++ " then " ++ indentD (toMessageDataAux t) ++ Format.line ++ "else " ++ indentD (toMessageDataAux e) | Code.jmp _ j xs => "jmp " ++ j.simpMacroScopes ++ " " ++ toString xs.toList | Code.«break» _ => "break " ++ updateVars | Code.«continue» _ => "continue " ++ updateVars | Code.«return» _ _ => "return ... " ++ updateVars | Code.«match» _ ds t alts => "match " ++ MessageData.joinSep (ds.toList.map MessageData.ofSyntax) ", " ++ " with " ++ alts.foldl (fun (acc : MessageData) (alt : Alt Code) => acc ++ Format.line ++ "| " ++ MessageData.joinSep (alt.patterns.toList.map MessageData.ofSyntax) ", " ++ " => " ++ toMessageDataAux alt.rhs) Format.nil private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] def CodeBlock.toMessageData (c : CodeBlock) : MessageData := let us := (nameSetToArray c.uvars).toList.map MessageData.ofName; toMessageDataAux (MessageData.ofList us) c.code partial def hasExitPoint : Code → Bool | Code.decl _ _ k => hasExitPoint k | Code.reassign _ _ k => hasExitPoint k | Code.joinpoint _ _ b k => hasExitPoint b || hasExitPoint k | Code.action _ k => hasExitPoint k | Code.ite _ _ _ _ t e => hasExitPoint t || hasExitPoint e | Code.jmp _ _ _ => false | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | Code.«match» _ _ _ alts => alts.any fun alt => hasExitPoint alt.rhs partial def hasContinueBreak : Code → Bool | Code.decl _ _ k => hasContinueBreak k | Code.reassign _ _ k => hasContinueBreak k | Code.joinpoint _ _ b k => hasContinueBreak b || hasContinueBreak k | Code.action _ k => hasContinueBreak k | Code.ite _ _ _ _ t e => hasContinueBreak t || hasContinueBreak e | Code.jmp _ _ _ => false | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => false | Code.«match» _ _ _ alts => alts.any fun alt => hasContinueBreak alt.rhs partial def convertReturnIntoJmpAux (jp : Name) (xs : Array Name) : Code → Code | Code.decl xs stx k => Code.decl xs stx $ convertReturnIntoJmpAux k | Code.reassign xs stx k => Code.reassign xs stx $ convertReturnIntoJmpAux k | Code.joinpoint n ps b k => Code.joinpoint n ps (convertReturnIntoJmpAux b) (convertReturnIntoJmpAux k) | Code.action e k => Code.action e $ convertReturnIntoJmpAux k | Code.ite ref x? h c t e => Code.ite ref x? h c (convertReturnIntoJmpAux t) (convertReturnIntoJmpAux e) | Code.«match» ref ds t alts => Code.«match» ref ds t $ alts.map fun alt => { alt with rhs := convertReturnIntoJmpAux alt.rhs } /- Remark: the joint point doesn't use the value `val`, but we pass `val` as an extra `jmp` argument to make sure all `return` values have the same type. The following example would fail to be elaborated without this trick. ``` do unless x == 0 throw (IO.userError "error") IO.println "hello" ``` The `unless` is expanded into ``` if x == 0 then let aux ← throw (IO.userError "error") return aux else return PUnit.unit ``` If we did not pass the value as an extra parameter, we would not be able to infer the type of `aux`. -/ | Code.«return» ref val => Code.jmp ref jp ((xs.map $ mkIdentFrom ref).push val) | c => c /- Convert `return _ x` instructions in `c` into `jmp _ jp xs`. -/ def convertReturnIntoJmp (c : Code) (jp : Name) (xs : Array Name) : Code := convertReturnIntoJmpAux jp xs c structure JPDecl := (name : Name) (params : Array (Name × Bool)) (body : Code) def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do ps ← if ps.isEmpty then do y ← mkFreshUserName `y; pure #[(y, false)] else pure ps; name ← mkFreshUserName `jp; pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do jp ← liftM $ mkFreshJP ps body; modify fun (jps : Array JPDecl) => jps.push jp; pure jp.name def addFreshJP' (xs : Array Name) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := addFreshJP (xs.map fun x => (x, true)) body def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (fun (rs : NameSet) x => rs.insert x) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (fun (rs : NameSet) x => rs.erase x) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x def mkJmp (ref : Syntax) (jp : Name) (xs : Array Name) : TermElabM Code := do if xs.isEmpty then do unit ← `(Unit.unit); pure $ Code.jmp ref jp #[unit] else pure $ Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => Code.decl xs stx <$> pullExitPointsAux (eraseVars rs xs) k | rs, Code.reassign xs stx k => Code.reassign xs stx <$> pullExitPointsAux (insertVars rs xs) k | rs, Code.joinpoint j ps b k => Code.joinpoint j ps <$> pullExitPointsAux rs b <*> pullExitPointsAux rs k | rs, Code.action e k => Code.action e <$> pullExitPointsAux rs k | rs, Code.ite ref x? o c t e => Code.ite ref x? o c <$> pullExitPointsAux (eraseOptVar rs x?) t <*> pullExitPointsAux (eraseOptVar rs x?) e | rs, Code.«match» ref ds t alts => Code.«match» ref ds t <$> alts.mapM fun alt => do rhs ← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs; pure { alt with rhs := rhs } | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => do let xs := nameSetToArray rs; jp ← addFreshJP' xs (Code.«break» ref); liftM $ mkJmp ref jp xs | rs, Code.«continue» ref => do let xs := nameSetToArray rs; jp ← addFreshJP' xs (Code.«continue» ref); liftM $ mkJmp ref jp xs | rs, Code.«return» ref val => do let xs := nameSetToArray rs; let args := xs.map $ mkIdentFrom ref; let args := args.push val; yFresh ← mkFreshUserName `y; let ps := xs.map fun x => (x, true); let ps := ps.push (yFresh, false); jp ← addFreshJP ps (Code.«return» ref (mkIdentFrom ref yFresh)); pure $ Code.jmp ref jp args /- Auxiliary operation for adding new variables to `c.uvars` (updated variables). When a new variable is not already in `c.uvars`, but is shadowed by some declaration in `c.code`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := if hasExitPoint c then do (c, jpDecls) ← (pullExitPointsAux {} c).run #[]; pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (ws : NameSet) : Code → TermElabM Code | Code.joinpoint j ps b k => Code.joinpoint j ps <$> extendUpdatedVarsAux b <*> extendUpdatedVarsAux k | Code.action e k => Code.action e <$> extendUpdatedVarsAux k | c@(Code.«match» ref ds t alts) => if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref ds t <$> alts.mapM fun alt => do rhs ← extendUpdatedVarsAux alt.rhs; pure { alt with rhs := rhs } | Code.ite ref none o c t e => Code.ite ref none o c <$> extendUpdatedVarsAux t <*> extendUpdatedVarsAux e | c@(Code.ite ref (some h) o cond t e) => if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond <$> extendUpdatedVarsAux t <*> extendUpdatedVarsAux e | Code.reassign xs stx k => Code.reassign xs stx <$> extendUpdatedVarsAux k | c@(Code.decl xs stx k) => if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx <$> extendUpdatedVarsAux k | c => pure c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := if ws.any fun x => !c.uvars.contains x then do -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) code ← extendUpdatedVarsAux ws c.code; pure { code := code, uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (fun (s : NameSet) x => s.insert x) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars; c₁ ← extendUpdatedVars c₁ ws; c₂ ← extendUpdatedVars c₂ ws; pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars; let ws := insertVars us xs; -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux ws c.code else pure c.code; pure { code := Code.reassign xs stx code, uvars := ws } def mkAction (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.action action c.code } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some (optIdent.getArg 0).getId; (thenBranch, elseBranch) ← homogenize thenBranch elseBranch; pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } def mkUnless (ref : Syntax) (cond : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do unit ← `(PUnit.unit); let unit := unit.copyInfo ref; pure { c with code := Code.ite ref none mkNullNode cond (Code.«return» ref unit) c.code } /- Return a code block that executes `terminal` and then `k`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (k : CodeBlock) : TermElabM CodeBlock := do (terminal, k) ← homogenize terminal k; let xs := nameSetToArray k.uvars; yFresh ← mkFreshUserName `y; let ps := xs.map fun x => (x, true); let ps := ps.push (yFresh, false); jpDecl ← mkFreshJP ps k.code; let jp := jpDecl.name; pure { code := attachJP jpDecl (convertReturnIntoJmp terminal.code jp xs), uvars := terminal.uvars, } private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then (doSeq.getArg 1).getArgs.getSepElems.toList else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then (doSeq.getArg 0).getArgs.getSepElems.toList else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx.getArg 1 def getLetIdDeclVar (letIdDecl : Syntax) : Name := (letIdDecl.getArg 0).getId def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl.getArg 0; patternVars ← getPatternVars pattern; pure $ patternVars.filterMap fun patternVar => match patternVar with | PatternVar.localVar x => some x | _ => none def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := (letEqnsDecl.getArg 0).getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl.getArg 0; if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := getLetDeclVars (doLet.getArg 1) -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := (doIdDecl.getArg 0).getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl.getArg 0; patternVars ← getPatternVars pattern; pure $ patternVars.filterMap fun patternVar => match patternVar with | PatternVar.localVar x => some x | _ => none -- parser! "let " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow.getArg 1; if decl.getKind == `Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == `Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign.getArg 0; if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def toDoSeq (doElem : Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode #[doElem, mkNullNode]] /- Recall that the `doIf` syntax is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (" else " >> " if ") >> optIdent >> termParser >> " then " >> doSeq) >> optional (" else " >> doSeq) ``` Given a `doIf`, return an equivalente `doIf` that has no `else if`s and the `else` is not none. -/ private def expandDoIf (doIf : Syntax) : Syntax := let ref := doIf; let doElseIfs := (doIf.getArg 5).getArgs; let doElse := doIf.getArg 6; if doElseIfs.isEmpty && !doElse.isNone then doIf else let doElse := if doElse.isNone then mkNullNode #[ mkAtomFrom ref "else", toDoSeq (mkNode `Lean.Parser.Term.doReturn #[mkAtomFrom ref "return", mkNullNode]) ] else doElse; let doElse := doElseIfs.foldr (fun doElseIf doElse => let ifAtom := (doElseIf.getArg 0).getArg 1; let doIfArgs := (doElseIf.getArgs).set! 0 ifAtom; let doIfArgs := doIfArgs.push mkNullNode; let doIfArgs := doIfArgs.push doElse; mkNullNode #[mkAtomFrom doElseIf "else", toDoSeq $ mkNode `Lean.Parser.Term.doIf doIfArgs]) doElse; let doIf := doIf.setArg 6 doElse; doIf.setArg 5 mkNullNode -- remove else-ifs structure DoIfView := (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) private def mkDoIfView (doIf : Syntax) : DoIfView := let doIf := expandDoIf doIf; { ref := doIf, optIdent := doIf.getArg 1, cond := doIf.getArg 2, thenBranch := doIf.getArg 4, elseBranch := (doIf.getArg 6).getArg 1 } private def mkPUnit (ref : Syntax) : MacroM Syntax := do unit ← `(PUnit.unit); pure $ unit.copyInfo ref private def mkTuple (ref : Syntax) (elems : Array Syntax) : MacroM Syntax := if elems.size == 0 then do mkPUnit ref else if elems.size == 1 then pure (elems.get! 0) else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => do tuple ← `(($elem, $tuple)); pure $ tuple.copyInfo ref) (elems.back) -- Code block to syntax term namespace ToTerm inductive Kind | regular | forInNestedTerm | forIn | forInMap structure Context := (m : Syntax) -- Syntax to reference the monad associated with the do notation. (uvars : Array Name) (kind : Kind) abbrev M := ReaderT Context MacroM def mkUVarTuple (ref : Syntax) : M Syntax := do ctx ← read; let uvarIdents := ctx.uvars.map fun x => mkIdentFrom ref x; liftM $ mkTuple ref uvarIdents /- Note that, in the current design, we can only reassign variables that were declared in the do-block. Thus, if `ctx.kind == Kind.regular`, then `ctx.uvars` must be empty. Therefore, the following method should never create a tuple. We keep it as-is because we may change the design decision in the future. -/ def mkResultUVarTuple (ref : Syntax) (val : Syntax) : M Syntax := do ctx ← read; if ctx.uvars.isEmpty then pure val else do uvars ← mkUVarTuple ref; liftM $ mkTuple ref #[val, uvars] def returnToTermCore (ref : Syntax) (val : Syntax) : M Syntax := do ctx ← read; match ctx.kind with | Kind.forInNestedTerm => do u ← mkUVarTuple ref; `(HasPure.pure (DoResult.«return» $u)) | Kind.regular => do r ← mkResultUVarTuple ref val; `(HasPure.pure $r) | _ => do u ← mkUVarTuple ref; `(HasPure.pure (ForInStep.yield $u)) def returnToTerm (ref : Syntax) (val : Syntax) : M Syntax := do r ← returnToTermCore ref val; pure $ r.copyInfo ref def continueToTermCore (ref : Syntax) : M Syntax := do ctx ← read; match ctx.kind with | Kind.regular => unreachable! | Kind.forInNestedTerm => do u ← mkUVarTuple ref; `(HasPure.pure (DoResult.«continue» $u)) | _ => do u ← mkUVarTuple ref; `(HasPure.pure (ForInStep.yield $u)) def continueToTerm (ref : Syntax) : M Syntax := do r ← continueToTermCore ref; pure $ r.copyInfo ref def breakToTermCore (ref : Syntax) : M Syntax := do ctx ← read; match ctx.kind with | Kind.regular => unreachable! | Kind.forInNestedTerm => do u ← mkUVarTuple ref; `(HasPure.pure (DoResult.«break» $u)) | _ => do u ← mkUVarTuple ref; `(HasPure.pure (ForInStep.done $u)) def breakToTerm (ref : Syntax) : M Syntax := do r ← breakToTermCore ref; pure $ r.copyInfo ref def actionToTermCore (action : Syntax) (k : Syntax) : MacroM Syntax := withFreshMacroScope do if action.getKind == `Lean.Parser.Term.doDbgTrace then let msg := action.getArg 1; `(dbgTrace! $msg; $k) else if action.getKind == `Lean.Parser.Term.doAssert then let cond := action.getArg 1; `(assert! $cond; $k) else do `(HasBind.bind $action (fun _ => $k)) def actionToTerm (action : Syntax) (k : Syntax) : MacroM Syntax := do r ← actionToTermCore action k; pure $ r.copyInfo action def declToTermCore (decl : Syntax) (k : Syntax) : M Syntax := withFreshMacroScope do let kind := decl.getKind; if kind == `Lean.Parser.Term.doLet then let letDecl := decl.getArg 1; `(let $letDecl:letDecl; $k) else if kind == `Lean.Parser.Term.doLetRec then liftM $ Macro.throwError decl "WIP" else if kind == `Lean.Parser.Term.doLetArrow then let arg := decl.getArg 1; let ref := arg; if arg.getKind == `Lean.Parser.Term.doIdDecl then let id := arg.getArg 0; let type := expandOptType ref (arg.getArg 1); let val := arg.getArg 3; `(HasBind.bind $val (fun ($id:ident : $type) => $k)) else if arg.getKind == `Lean.Parser.Term.doPatDecl then do -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) let pat := arg.getArg 0; let discr := arg.getArg 2; let optElse := arg.getArg 3; if optElse.isNone then `(HasBind.bind $discr (fun x => match x with | $pat => $k)) else do let elseBody := optElse.getArg 1; y ← `(y); ret ← returnToTerm ref y; elseBody ← `(HasBind.bind $elseBody (fun y => $ret)); `(HasBind.bind $discr (fun x => match x with | $pat => $k | _ => $elseBody)) else liftM $ Macro.throwError decl "unexpected kind of 'do' declaration" else if kind == `Lean.Parser.Term.doHave then liftM $ Macro.throwError decl ("WIP " ++ toString decl) else liftM $ Macro.throwError decl "unexpected kind of 'do' declaration" def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := do r ← declToTermCore decl k; pure $ r.copyInfo decl def reassignToTermCore (reassign : Syntax) (k : Syntax) : MacroM Syntax := withFreshMacroScope do let kind := reassign.getKind; if kind == `Lean.Parser.Term.doReassign then let letDecl := mkNode `Lean.Parser.Term.letDecl #[reassign.getArg 0]; `(let $letDecl:letDecl; $k) else if kind == `Lean.Parser.Term.doReassignArrow then Macro.throwError reassign ("WIP " ++ toString reassign) else Macro.throwError reassign "unexpected kind of 'do' reassignment" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := do r ← reassignToTermCore reassign k; pure $ r.copyInfo reassign def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : Syntax := mkNode `Lean.Parser.Term.«if» #[mkAtomFrom ref "if", optIdent, cond, mkAtomFrom ref "then", thenBranch, mkAtomFrom ref "else", elseBranch] def mkJoinPointCore (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withFreshMacroScope do let ref := body; binders ← ps.mapM fun ⟨id, useTypeOf⟩ => do { type ← if useTypeOf then `(typeOf! $(mkIdentFrom ref id)) else `(_); let binderType := mkNullNode #[mkAtomFrom ref ":", type]; pure $ mkNode `Lean.Parser.Term.explicitBinder #[mkAtomFrom ref "(", mkNullNode #[mkIdentFrom ref id], binderType, mkNullNode, mkAtomFrom ref ")"] }; ctx ← read; let m := ctx.m; type ← `($m _); `(let $(mkIdentFrom ref j):ident $binders:explicitBinder* : $type := $body; $k) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := do r ← mkJoinPointCore j ps body k; pure $ r.copyInfo body def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := mkAppStx (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => returnToTerm ref val | Code.«continue» ref => continueToTerm ref | Code.«break» ref => breakToTerm ref | Code.joinpoint j ps b k => do b ← toTerm b; k ← toTerm k; mkJoinPoint j ps b k | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do k ← toTerm k; declToTerm stx k | Code.reassign _ stx k => do k ← toTerm k; liftM $ reassignToTerm stx k | Code.action stx k => do k ← toTerm k; liftM $ actionToTerm stx k | Code.ite ref _ o c t e => do t ← toTerm t; e ← toTerm e; pure $ mkIte ref o c t e | _ => liftM $ Macro.throwError Syntax.missing "WIP" private def getKindUVars (c : CodeBlock) (forInVar? : Option Name) : Kind × Array Name := match forInVar? with | none => if hasContinueBreak c.code then (Kind.forInNestedTerm, nameSetToArray c.uvars) else (Kind.regular, nameSetToArray c.uvars) | some forInVar => if c.uvars.contains forInVar then let uvars := #[forInVar] ++ nameSetToArray (c.uvars.erase forInVar); (Kind.forInMap, uvars) else (Kind.forIn, nameSetToArray c.uvars) def run (c : CodeBlock) (m : Syntax) (forInVar? : Option Name := none) : MacroM (Array Name × Syntax) := do let code := c.code; let (kind, uvars) := getKindUVars c forInVar?; term ← toTerm code { m := m, kind := kind, uvars := uvars }; pure (uvars, term) end ToTerm namespace ToCodeBlock structure Context := (ref : Syntax) (m : Syntax) -- Syntax representing the monad associated with the do notation. (varSet : NameSet := {}) (insideFor : Bool := false) abbrev M := ReaderT Context TermElabM @[inline] def withNewVars {α} (newVars : Array Name) (x : M α) : M α := adaptReader (fun (ctx : Context) => { ctx with varSet := insertVars ctx.varSet newVars }) x def ensureInsideFor : M Unit := do ctx ← read; unless ctx.insideFor $ throwError "invalid statement, can only be used inside 'for ... in ... do ...'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty $ throwError "must be last element in a 'do' sequence" def isDoVar? (stx : Syntax) : M (Option Name) := do if stx.isIdent then do ctx ← read; let x := stx.getId; if ctx.varSet.contains x then pure (some x) else pure none else pure none def checkReassignable (xs : Array Name) : M Unit := do ctx ← read; xs.forM fun x => unless (ctx.varSet.contains x) do throwError ("'" ++ x.simpMacroScopes ++ "' cannot be reassigned, only variables declared in the do-block can be reassigned") private partial def expandLiftMethodAux : Syntax → StateT (List Syntax) MacroM Syntax | stx@(Syntax.node k args) => if k == `Lean.Parser.Term.do then pure stx else if k == `Lean.Parser.Term.doSeqIndent then pure stx else if k == `Lean.Parser.Term.doSeqBracketed then pure stx else if k == `Lean.Parser.Term.quot then pure stx else if k == `Lean.Parser.Term.liftMethod then withFreshMacroScope $ do let term := args.get! 1; term ← expandLiftMethodAux term; auxDo ← `(do let a ← $term); let auxDoElems := getDoSeqElems (getDoSeq auxDo); modify fun s => s ++ auxDoElems; `(a) else do args ← args.mapM expandLiftMethodAux; pure $ Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax × Syntax) := if !hasLiftMethod doElem then pure ([], doElem) else do (doElem, doElemsNew) ← (expandLiftMethodAux doElem).run []; pure (doElemsNew, doElem) instance auususus : HasToString SourceInfo := { toString := fun info => toString info.pos } def mkReturnUnit (ref : Syntax) : M CodeBlock := do unit ← `(PUnit.unit); let unit := unit.copyInfo ref; pure $ mkReturn ref unit partial def doSeqToCode : List Syntax → M CodeBlock | [] => do ctx ← read; mkReturnUnit ctx.ref | doElem::doElems => withRef doElem do (liftedDoElems, doElem) ← liftM (liftMacroM $ expandLiftMethod doElem : TermElabM _); if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else do let ref := doElem; let concatWithRest (c : CodeBlock) : M CodeBlock := match doElems with | [] => pure c | _ => do { k ← doSeqToCode doElems; liftM $ concat c k }; let auxDoToCode (auxDo : Syntax) : M CodeBlock := do { let auxDoElems := getDoSeqElems (getDoSeq auxDo); let auxDoElems := auxDoElems.map fun auxDoElem => auxDoElem.copyInfo doElem; doSeqToCode auxDoElems }; let k := doElem.getKind; if k == `Lean.Parser.Term.doLet then do vars ← liftM $ getDoLetVars doElem; mkVarDeclCore vars doElem <$> withNewVars vars (doSeqToCode doElems) else if k == `Lean.Parser.Term.doLetRec then do throwError "WIP" else if k == `Lean.Parser.Term.doLetArrow then do vars ← liftM $ getDoLetArrowVars doElem; mkVarDeclCore vars doElem <$> withNewVars vars (doSeqToCode doElems) else if k == `Lean.Parser.Term.doReassign then do vars ← liftM $ getDoReassignVars doElem; checkReassignable vars; k ← doSeqToCode doElems; liftM $ mkReassignCore vars doElem k else if k == `Lean.Parser.Term.doReassignArrow then throwError "WIP" else if k == `Lean.Parser.Term.doHave then throwError "WIP" else if k == `Lean.Parser.Term.doIf then do let view := mkDoIfView doElem; thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch); elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch); ite ← liftM $ mkIte view.ref view.optIdent view.cond thenBranch elseBranch; concatWithRest ite else if k == `Lean.Parser.Term.doUnless then do let cond := doElem.getArg 1; let doSeq := doElem.getArg 3; body ← doSeqToCode (getDoSeqElems doSeq); unless ← liftM $ mkUnless ref cond body; concatWithRest unless else if k == `Lean.Parser.Term.doFor then throwError "WIP" else if k == `Lean.Parser.Term.doMatch then throwError "WIP" else if k == `Lean.Parser.Term.doTry then throwError "WIP" else if k == `Lean.Parser.Term.doBreak then do ensureInsideFor; ensureEOS doElems; pure $ mkBreak ref else if k == `Lean.Parser.Term.doContinue then do ensureInsideFor; ensureEOS doElems; pure $ mkContinue ref else if k == `Lean.Parser.Term.doReturn then do ensureEOS doElems; let argOpt := doElem.getArg 1; if argOpt.isNone then mkReturnUnit ref else do let arg := argOpt.getArg 0; pure $ mkReturn ref arg else if k == `Lean.Parser.Term.doDbgTrace then mkAction doElem <$> doSeqToCode doElems else if k == `Lean.Parser.Term.doAssert then mkAction doElem <$> doSeqToCode doElems else if k == `Lean.Parser.Term.doExpr then let term := doElem.getArg 0; if doElems.isEmpty then withFreshMacroScope do auxDo ← `(do let x ← $term; return x); auxDoToCode auxDo else mkAction term <$> doSeqToCode doElems else throwError ("unexpected do-element" ++ Format.line ++ toString doElem) def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode $ getDoSeqElems $ getDoSeq doStx).run { ref := doStx, m := m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do result ← `(?m); mType ← inferType m; mvar ← elabTerm result mType; assignExprMVar mvar.mvarId! m; pure result @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType?; bindInfo ← extractBind expectedType?; m ← mkMonadAlias bindInfo.m; codeBlock ← ToCodeBlock.run stx m; -- trace! `Elab.do ("codeBlock: " ++ Format.line ++ codeBlock.toMessageData); (_, stxNew) ← liftMacroM $ ToTerm.run codeBlock m; trace! `Elab.do stxNew; withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? end Do @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.do; pure () end Term end Elab end Lean
bb5e15acba4bb9d35bd69810a7f46e00f3d9fa75
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/combinatorics/pigeonhole.lean
73e806c28f105a2eae183309a7d804188d42aec7
[ "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
19,345
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Yury Kudryashov -/ import data.set.finite import data.nat.modeq import algebra.big_operators.order /-! # Pigeonhole principles Given pigeons (possibly infinitely many) in pigeonholes, the pigeonhole principle states that, if there are more pigeons than pigeonholes, then there is a pigeonhole with two or more pigeons. There are a few variations on this statement, and the conclusion can be made stronger depending on how many pigeons you know you might have. The basic statements of the pigeonhole principle appear in the following locations: * `data.finset.basic` has `finset.exists_ne_map_eq_of_card_lt_of_maps_to` * `data.fintype.basic` has `fintype.exists_ne_map_eq_of_card_lt` * `data.fintype.basic` has `fintype.exists_ne_map_eq_of_infinite` * `data.fintype.basic` has `fintype.exists_infinite_fiber` * `data.set.finite` has `set.infinite.exists_ne_map_eq_of_maps_to` This module gives access to these pigeonhole principles along with 20 more. The versions vary by: * using a function between `fintype`s or a function between possibly infinite types restricted to `finset`s; * counting pigeons by a general weight function (`∑ x in s, w x`) or by heads (`finset.card s`); * using strict or non-strict inequalities; * establishing upper or lower estimate on the number (or the total weight) of the pigeons in one pigeonhole; * in case when we count pigeons by some weight function `w` and consider a function `f` between `finset`s `s` and `t`, we can either assume that each pigeon is in one of the pigeonholes (`∀ x ∈ s, f x ∈ t`), or assume that for `y ∉ t`, the total weight of the pigeons in this pigeonhole `∑ x in s.filter (λ x, f x = y), w x` is nonpositive or nonnegative depending on the inequality we are proving. Lemma names follow `mathlib` convention (e.g., `finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`); "pigeonhole principle" is mentioned in the docstrings instead of the names. ## See also * `ordinal.infinite_pigeonhole`: pigeonhole principle for cardinals, formulated using cofinality; * `measure_theory.exists_nonempty_inter_of_measure_univ_lt_tsum_measure`, `measure_theory.exists_nonempty_inter_of_measure_univ_lt_sum_measure`: pigeonhole principle in a measure space. ## Tags pigeonhole principle -/ universes u v w variables {α : Type u} {β : Type v} {M : Type w} [linear_ordered_cancel_add_comm_monoid M] [decidable_eq β] open_locale big_operators namespace finset variables {s : finset α} {t : finset β} {f : α → β} {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `finset`s, pigeons counted by weight In this section we prove the following version of the pigeonhole principle: if the total weight of a finite set of pigeons is greater than `n • b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than `b`, and a few variations of this theorem. The principle is formalized in the following way, see `finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`: if `f : α → β` is a function which maps all elements of `s : finset α` to `t : finset β` and `card t • b < ∑ x in s, w x`, where `w : α → M` is a weight function taking values in a `linear_ordered_cancel_add_comm_monoid`, then for some `y ∈ t`, the sum of the weights of all `x ∈ s` such that `f x = y` is greater than `b`. There are a few bits we can change in this theorem: * reverse all inequalities, with obvious adjustments to the name; * replace the assumption `∀ a ∈ s, f a ∈ t` with `∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0`, and replace `of_maps_to` with `of_sum_fiber_nonpos` in the name; * use non-strict inequalities assuming `t` is nonempty. We can do all these variations independently, so we have eight versions of the theorem. -/ /-! #### Strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n • b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ lemma exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (hf : ∀ a ∈ s, f a ∈ t) (hb : t.card • b < ∑ x in s, w x) : ∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x := exists_lt_of_sum_lt $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n • b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than `b`. -/ lemma exists_sum_fiber_lt_of_maps_to_of_sum_lt_nsmul (hf : ∀ a ∈ s, f a ∈ t) (hb : (∑ x in s, w x) < t.card • b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ hf hb /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n • b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ lemma exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum (ht : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (hb : t.card • b < ∑ x in s, w x) : ∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x := exists_lt_of_sum_lt $ calc (∑ y in t, b) < ∑ x in s, w x : by simpa ... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x : sum_le_sum_fiberwise_of_sum_fiber_nonpos ht /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n • b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than `b`. -/ lemma exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (ht : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (hb : (∑ x in s, w x) < t.card • b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ ht hb /-! #### Non-strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n • b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ lemma exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hb : t.card • b ≤ ∑ x in s, w x) : ∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x := exists_le_of_sum_le ht $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n • b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ lemma exists_sum_fiber_le_of_maps_to_of_sum_le_nsmul (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hb : (∑ x in s, w x) ≤ t.card • b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n • b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ lemma exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum (hf : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (ht : t.nonempty) (hb : t.card • b ≤ ∑ x in s, w x) : ∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x := exists_le_of_sum_le ht $ calc (∑ y in t, b) ≤ ∑ x in s, w x : by simpa ... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x : sum_le_sum_fiberwise_of_sum_fiber_nonpos hf /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n • b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ lemma exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (hf : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (ht : t.nonempty) (hb : (∑ x in s, w x) ≤ t.card • b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb /-! ### The pigeonhole principles on `finset`s, pigeons counted by heads In this section we formalize a few versions of the following pigeonhole principle: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. First, we can use strict or non-strict inequalities. While the versions with non-strict inequalities are weaker than those with strict inequalities, sometimes it might be more convenient to apply the weaker version. Second, we can either state that there exists a pigeonhole with at least `n` pigeons, or state that there exists a pigeonhole with at most `n` pigeons. In the latter case we do not need the assumption `∀ a ∈ s, f a ∈ t`. So, we prove four theorems: `finset.exists_lt_card_fiber_of_maps_to_of_mul_lt_card`, `finset.exists_le_card_fiber_of_maps_to_of_mul_le_card`, `finset.exists_card_fiber_lt_of_card_lt_mul`, and `finset.exists_card_fiber_le_of_card_le_mul`. -/ /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function between finite sets `s` and `t` and a natural number `n` such that `card t * n < card s`, there exists `y ∈ t` such that its preimage in `s` has more than `n` elements. -/ lemma exists_lt_card_fiber_of_mul_lt_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (hn : t.card * n < s.card) : ∃ y ∈ t, n < (s.filter (λ x, f x = y)).card := begin simp only [card_eq_sum_ones], apply exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum hf, simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `card s < card t * n`, there exists `y ∈ t` such that its preimage in `s` has less than `n` elements. -/ lemma exists_card_fiber_lt_of_card_lt_mul (hn : s.card < t.card * n) : ∃ y ∈ t, (s.filter (λ x, f x = y)).card < n:= begin simp only [card_eq_sum_ones], apply exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (λ _ _, nat.zero_le _), simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function between finite sets `s` and `t` and a natural number `n` such that `card t * n ≤ card s`, there exists `y ∈ t` such that its preimage in `s` has at least `n` elements. See also `finset.exists_lt_card_fiber_of_mul_lt_card_of_maps_to` for a stronger statement. -/ lemma exists_le_card_fiber_of_mul_le_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hn : t.card * n ≤ s.card) : ∃ y ∈ t, n ≤ (s.filter (λ x, f x = y)).card := begin simp only [card_eq_sum_ones], apply exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum hf ht, simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `card s ≤ card t * n`, there exists `y ∈ t` such that its preimage in `s` has no more than `n` elements. See also `finset.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ lemma exists_card_fiber_le_of_card_le_mul (ht : t.nonempty) (hn : s.card ≤ t.card * n) : ∃ y ∈ t, (s.filter (λ x, f x = y)).card ≤ n:= begin simp only [card_eq_sum_ones], apply exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (λ _ _, nat.zero_le _) ht, simpa end end finset namespace fintype open finset variables [fintype α] [fintype β] (f : α → β) {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `fintypes`s, pigeons counted by weight In this section we specialize theorems from the previous section to the special case of functions between `fintype`s and `s = univ`, `t = univ`. In this case the assumption `∀ x ∈ s, f x ∈ t` always holds, so we have four theorems instead of eight. -/ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than `b` provided that the total number of pigeonholes times `b` is less than the total weight of all pigeons. -/ lemma exists_lt_sum_fiber_of_nsmul_lt_sum (hb : card β • b < ∑ x, w x) : ∃ y, b < ∑ x in univ.filter (λ x, f x = y), w x := let ⟨y, _, hy⟩ := exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (λ _ _, mem_univ _) hb in ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than or equal to `b` provided that the total number of pigeonholes times `b` is less than or equal to the total weight of all pigeons. -/ lemma exists_le_sum_fiber_of_nsmul_le_sum [nonempty β] (hb : card β • b ≤ ∑ x, w x) : ∃ y, b ≤ ∑ x in univ.filter (λ x, f x = y), w x := let ⟨y, _, hy⟩ := exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (λ _ _, mem_univ _) univ_nonempty hb in ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than `b` provided that the total number of pigeonholes times `b` is greater than the total weight of all pigeons. -/ lemma exists_sum_fiber_lt_of_sum_lt_nsmul (hb : (∑ x, w x) < card β • b) : ∃ y, (∑ x in univ.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ w b hb /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than or equal to `b` provided that the total number of pigeonholes times `b` is greater than or equal to the total weight of all pigeons. -/ lemma exists_sum_fiber_le_of_sum_le_nsmul [nonempty β] (hb : (∑ x, w x) ≤ card β • b) : ∃ y, (∑ x in univ.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ w b _ hb /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n < card α`, there exists an element `y : β` such that its preimage has more than `n` elements. -/ lemma exists_lt_card_fiber_of_mul_lt_card (hn : card β * n < card α) : ∃ y : β, n < (univ.filter (λ x, f x = y)).card := let ⟨y, _, h⟩ := exists_lt_card_fiber_of_mul_lt_card_of_maps_to (λ _ _, mem_univ _) hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card α < card β * n`, there exists an element `y : β` such that its preimage has less than `n` elements. -/ lemma exists_card_fiber_lt_of_card_lt_mul (hn : card α < card β * n) : ∃ y : β, (univ.filter (λ x, f x = y)).card < n := let ⟨y, _, h⟩ := exists_card_fiber_lt_of_card_lt_mul hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n ≤ card α`, there exists an element `y : β` such that its preimage has at least `n` elements. See also `fintype.exists_lt_card_fiber_of_mul_lt_card` for a stronger statement. -/ lemma exists_le_card_fiber_of_mul_le_card [nonempty β] (hn : card β * n ≤ card α) : ∃ y : β, n ≤ (univ.filter (λ x, f x = y)).card := let ⟨y, _, h⟩ := exists_le_card_fiber_of_mul_le_card_of_maps_to (λ _ _, mem_univ _) univ_nonempty hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card α ≤ card β * n`, there exists an element `y : β` such that its preimage has at most `n` elements. See also `fintype.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ lemma exists_card_fiber_le_of_card_le_mul [nonempty β] (hn : card α ≤ card β * n) : ∃ y : β, (univ.filter (λ x, f x = y)).card ≤ n := let ⟨y, _, h⟩ := exists_card_fiber_le_of_card_le_mul univ_nonempty hn in ⟨y, h⟩ end fintype namespace nat open set /-- If `s` is an infinite set of natural numbers and `k > 0`, then `s` contains two elements `m < n` that are equal mod `k`. -/ theorem exists_lt_modeq_of_infinite {s : set ℕ} (hs : s.infinite) {k : ℕ} (hk : 0 < k) : ∃ (m ∈ s) (n ∈ s), m < n ∧ m ≡ n [MOD k] := hs.exists_lt_map_eq_of_maps_to (λ n _, show n % k ∈ Iio k, from nat.mod_lt n hk) $ finite_lt_nat k end nat
4834e070761a58e03feb1cc88c7d30a75d151401
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/equiv/encodable/lattice.lean
53a5e9611e892f8f44e73ba679f1848ff6dbf8a6
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,970
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import data.equiv.encodable.basic import data.finset.basic import data.set.disjointed /-! # Lattice operations on encodable types Lemmas about lattice and set operations on encodable types ## Implementation Notes This is a separate file, to avoid unnecessary imports in basic files. Previously some of these results were in the `measure_theory` folder. -/ open set namespace encodable variables {α : Type*} {β : Type*} [encodable β] lemma supr_decode₂ [complete_lattice α] (f : β → α) : (⨆ (i : ℕ) (b ∈ decode₂ β i), f b) = (⨆ b, f b) := by { rw [supr_comm], simp [mem_decode₂] } lemma Union_decode₂ (f : β → set α) : (⋃ (i : ℕ) (b ∈ decode₂ β i), f b) = (⋃ b, f b) := supr_decode₂ f @[elab_as_eliminator] lemma Union_decode₂_cases {f : β → set α} {C : set α → Prop} (H0 : C ∅) (H1 : ∀ b, C (f b)) {n} : C (⋃ b ∈ decode₂ β n, f b) := match decode₂ β n with | none := by { simp, apply H0 } | (some b) := by { convert H1 b, simp [ext_iff] } end theorem Union_decode₂_disjoint_on {f : β → set α} (hd : pairwise (disjoint on f)) : pairwise (disjoint on λ i, ⋃ b ∈ decode₂ β i, f b) := begin rintro i j ij x ⟨h₁, h₂⟩, revert h₁ h₂, simp, intros b₁ e₁ h₁ b₂ e₂ h₂, refine hd _ _ _ ⟨h₁, h₂⟩, cases encodable.mem_decode₂.1 e₁, cases encodable.mem_decode₂.1 e₂, exact mt (congr_arg _) ij end end encodable namespace finset lemma nonempty_encodable {α} (t : finset α) : nonempty $ encodable {i // i ∈ t} := begin classical, induction t using finset.induction with x t hx ih, { refine ⟨⟨λ _, 0, λ _, none, λ ⟨x,y⟩, y.rec _⟩⟩ }, { cases ih with ih, exactI ⟨encodable.of_equiv _ (finset.subtype_insert_equiv_option hx)⟩ } end end finset
75cafbabf8e955cbdb08998318a2c70e753fda20
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/analysis/calculus/tangent_cone.lean
aa9c47a8ff0d96b3892dcbab8964476933fe38eb
[ "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
17,765
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel In this file, we define two predicates `unique_diff_within_at k s x` and `unique_diff_on k s` ensuring that, if a function has two derivatives, then they have to coincide. As a direct definition of this fact (quantifying on all target types and all functions) would depend on universes, we use a more intrinsic definition: if all the possible tangent directions to the set `s` at the point `x` span a dense subset of the whole subset, it is easy to check that the derivative has to be unique. Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`, and express `unique_diff_within_at` and `unique_diff_on` in terms of it. One should however think of this definition as an implementation detail: the only reason to introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness of the derivative. This is why their names reflect their uses, and not how they are defined. Note that this file is imported by `deriv.lean`. Hence, derivatives are not defined yet. The property of uniqueness of the derivative is therefore proved in `deriv.lean`, but based on the properties of the tangent cone we prove here. -/ import analysis.convex analysis.normed_space.bounded_linear_maps variables (k : Type*) [nondiscrete_normed_field k] variables {E : Type*} [normed_group E] [normed_space k E] variables {F : Type*} [normed_group F] [normed_space k F] variables {G : Type*} [normed_group G] [normed_space ℝ G] set_option class.instance_max_depth 50 open filter set /-- The set of all tangent directions to the set `s` at the point `x`. -/ def tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → k) (d : ℕ → E), {n:ℕ | x + d n ∈ s} ∈ (at_top : filter ℕ) ∧ (tendsto (λn, ∥c n∥) at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (nhds y))} /-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space. The main role of this property is to ensure that the differential within `s` at `x` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `deriv.lean`. To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which is automatic when `E` is not `0`-dimensional). -/ def unique_diff_within_at (s : set E) (x : E) : Prop := closure ((submodule.span k (tangent_cone_at k s x)) : set E) = univ ∧ x ∈ closure s /-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of the whole space. The main role of this property is to ensure that the differential along `s` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in `deriv.lean`. -/ def unique_diff_on (s : set E) : Prop := ∀x ∈ s, unique_diff_within_at k s x variables {k} {x y : E} {s t : set E} section tangent_cone /- This section is devoted to the properties of the tangent cone. -/ lemma tangent_cone_univ : tangent_cone_at k univ x = univ := begin refine univ_subset_iff.1 (λy hy, _), rcases exists_one_lt_norm k with ⟨w, hw⟩, refine ⟨λn, w^n, λn, (w^n)⁻¹ • y, univ_mem_sets' (λn, mem_univ _), _, _⟩, { simp only [norm_pow], exact tendsto_pow_at_top_at_top_of_gt_1 hw }, { convert tendsto_const_nhds, ext n, have : w ^ n * (w ^ n)⁻¹ = 1, { apply mul_inv_cancel, apply pow_ne_zero, simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm }, rw [smul_smul, this, one_smul] } end lemma tangent_cone_mono (h : s ⊆ t) : tangent_cone_at k s x ⊆ tangent_cone_at k t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, exact ⟨c, d, mem_sets_of_superset ds (λn hn, h hn), ctop, clim⟩ end /-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone, the sequence `d` tends to 0 at infinity. -/ lemma tangent_cone_at.lim_zero {c : ℕ → k} {d : ℕ → E} (hc : tendsto (λn, ∥c n∥) at_top at_top) (hd : tendsto (λn, c n • d n) at_top (nhds y)) : tendsto d at_top (nhds 0) := begin have A : tendsto (λn, ∥c n∥⁻¹) at_top (nhds 0) := tendsto_inverse_at_top_nhds_0.comp hc, have B : tendsto (λn, ∥c n • d n∥) at_top (nhds ∥y∥) := (continuous_norm.tendsto _).comp hd, have C : tendsto (λn, ∥c n∥⁻¹ * ∥c n • d n∥) at_top (nhds (0 * ∥y∥)) := tendsto_mul A B, rw zero_mul at C, have : {n | ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥} ∈ (@at_top ℕ _), { have : {n | 1 ≤ ∥c n∥} ∈ (@at_top ℕ _) := hc (mem_at_top 1), apply mem_sets_of_superset this (λn hn, _), rw mem_set_of_eq at hn, rw [mem_set_of_eq, ← norm_inv, ← norm_smul, smul_smul, inv_mul_cancel, one_smul], simpa [norm_eq_zero] using (ne_of_lt (lt_of_lt_of_le zero_lt_one hn)).symm }, have D : tendsto (λ (n : ℕ), ∥d n∥) at_top (nhds 0) := tendsto.congr' this C, rw tendsto_zero_iff_norm_tendsto_zero, exact D end /-- Intersecting with a neighborhood of the point does not change the tangent cone. -/ lemma tangent_cone_inter_nhds (ht : t ∈ nhds x) : tangent_cone_at k (s ∩ t) x = tangent_cone_at k s x := begin refine subset.antisymm (tangent_cone_mono (inter_subset_left _ _)) _, rintros y ⟨c, d, ds, ctop, clim⟩, refine ⟨c, d, _, ctop, clim⟩, have : {n : ℕ | x + d n ∈ t} ∈ at_top, { have : tendsto (λn, x + d n) at_top (nhds (x + 0)) := tendsto_add tendsto_const_nhds (tangent_cone_at.lim_zero ctop clim), rw add_zero at this, exact mem_map.1 (this ht) }, exact inter_mem_sets ds this end /-- The tangent cone of a product contains the tangent cone of its left factor. -/ lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y ∈ closure t) : set.prod (tangent_cone_at k s x) {(0 : F)} ⊆ tangent_cone_at k (set.prod s t) (x, y) := begin rintros ⟨v, w⟩ ⟨⟨c, d, hd, hc, hy⟩, hw⟩, have : w = 0, by simpa using hw, rw this, have : ∀n, ∃d', y + d' ∈ t ∧ ∥c n • d'∥ ≤ ((1:ℝ)/2)^n, { assume n, have c_pos : 0 < 1 + ∥c n∥ := add_pos_of_pos_of_nonneg zero_lt_one (norm_nonneg _), rcases metric.mem_closure_iff'.1 ht ((1 + ∥c n∥)⁻¹ * (1/2)^n) _ with ⟨z, z_pos, hz⟩, refine ⟨z - y, _, _⟩, { convert z_pos, abel }, { rw [norm_smul, ← dist_eq_norm, dist_comm], calc ∥c n∥ * dist y z ≤ (1 + ∥c n∥) * ((1 + ∥c n∥)⁻¹ * (1/2)^n) : begin apply mul_le_mul _ (le_of_lt hz) dist_nonneg (le_of_lt c_pos), simp only [zero_le_one, le_add_iff_nonneg_left] end ... = (1/2)^n : begin rw [← mul_assoc, mul_inv_cancel, one_mul], exact ne_of_gt c_pos end }, { apply mul_pos (inv_pos c_pos) (pow_pos _ _), norm_num } }, choose d' hd' using this, refine ⟨c, λn, (d n, d' n), _, hc, _⟩, show {n : ℕ | (x, y) + (d n, d' n) ∈ set.prod s t} ∈ at_top, { apply filter.mem_sets_of_superset hd, assume n hn, simp at hn, simp [hn, (hd' n).1] }, { apply tendsto_prod_mk_nhds hy, change tendsto (λ (n : ℕ), c n • d' n) at_top (nhds 0), rw tendsto_zero_iff_norm_tendsto_zero, refine squeeze_zero (λn, norm_nonneg _) (λn, (hd' n).2) _, apply tendsto_pow_at_top_nhds_0_of_lt_1; norm_num } end /-- The tangent cone of a product contains the tangent cone of its right factor. -/ lemma subset_tangent_cone_prod_right {t : set F} {y : F} (hs : x ∈ closure s) : set.prod {(0 : E)} (tangent_cone_at k t y) ⊆ tangent_cone_at k (set.prod s t) (x, y) := begin rintros ⟨v, w⟩ ⟨hv, ⟨c, d, hd, hc, hy⟩⟩, have : v = 0, by simpa using hv, rw this, have : ∀n, ∃d', x + d' ∈ s ∧ ∥c n • d'∥ ≤ ((1:ℝ)/2)^n, { assume n, have c_pos : 0 < 1 + ∥c n∥ := add_pos_of_pos_of_nonneg zero_lt_one (norm_nonneg _), rcases metric.mem_closure_iff'.1 hs ((1 + ∥c n∥)⁻¹ * (1/2)^n) _ with ⟨z, z_pos, hz⟩, refine ⟨z - x, _, _⟩, { convert z_pos, abel }, { rw [norm_smul, ← dist_eq_norm, dist_comm], calc ∥c n∥ * dist x z ≤ (1 + ∥c n∥) * ((1 + ∥c n∥)⁻¹ * (1/2)^n) : begin apply mul_le_mul _ (le_of_lt hz) dist_nonneg (le_of_lt c_pos), simp only [zero_le_one, le_add_iff_nonneg_left] end ... = (1/2)^n : begin rw [← mul_assoc, mul_inv_cancel, one_mul], exact ne_of_gt c_pos end }, { apply mul_pos (inv_pos c_pos) (pow_pos _ _), norm_num } }, choose d' hd' using this, refine ⟨c, λn, (d' n, d n), _, hc, _⟩, show {n : ℕ | (x, y) + (d' n, d n) ∈ set.prod s t} ∈ at_top, { apply filter.mem_sets_of_superset hd, assume n hn, simp at hn, simp [hn, (hd' n).1] }, { apply tendsto_prod_mk_nhds _ hy, change tendsto (λ (n : ℕ), c n • d' n) at_top (nhds 0), rw tendsto_zero_iff_norm_tendsto_zero, refine squeeze_zero (λn, norm_nonneg _) (λn, (hd' n).2) _, apply tendsto_pow_at_top_nhds_0_of_lt_1; norm_num } end /-- If a subset of a real vector space contains a segment, then the direction of this segment belongs to the tangent cone at its endpoints. -/ lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment x y ⊆ s) : y - x ∈ tangent_cone_at ℝ s x := begin let w : ℝ := 2, let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩, show x + d n ∈ segment x y, { refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩, { rw inv_nonneg, apply pow_nonneg, norm_num }, { apply inv_le_one, apply one_le_pow_of_one_le, norm_num }, { simp only [d], abel } }, show filter.tendsto (λ (n : ℕ), ∥c n∥) filter.at_top filter.at_top, { have : (λ (n : ℕ), ∥c n∥) = c, by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) }, rw this, exact tendsto_pow_at_top_at_top_of_gt_1 (by norm_num) }, show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (nhds (y - x)), { have : (λ (n : ℕ), c n • d n) = (λn, y - x), { ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ (by norm_num) }, rw this, apply tendsto_const_nhds } end end tangent_cone section unique_diff /- This section is devoted to properties of the predicates `unique_diff_within_at` and `unique_diff_on`. -/ lemma unique_diff_within_at_univ : unique_diff_within_at k univ x := by { rw [unique_diff_within_at, tangent_cone_univ], simp } lemma unique_diff_on_univ : unique_diff_on k (univ : set E) := λx hx, unique_diff_within_at_univ lemma unique_diff_within_at_inter (ht : t ∈ nhds x) : unique_diff_within_at k (s ∩ t) x ↔ unique_diff_within_at k s x := begin have : x ∈ closure (s ∩ t) ↔ x ∈ closure s, { split, { assume h, exact closure_mono (inter_subset_left _ _) h }, { assume h, rw mem_closure_iff_nhds at ⊢ h, assume u hu, rw [inter_comm s t, ← inter_assoc], exact h _ (filter.inter_mem_sets hu ht) } }, rw [unique_diff_within_at, unique_diff_within_at, tangent_cone_inter_nhds ht, this] end lemma unique_diff_within_at.inter (hs : unique_diff_within_at k s x) (ht : t ∈ nhds x) : unique_diff_within_at k (s ∩ t) x := (unique_diff_within_at_inter ht).2 hs lemma unique_diff_within_at.mono (h : unique_diff_within_at k s x) (st : s ⊆ t) : unique_diff_within_at k t x := begin unfold unique_diff_within_at at *, rw [← univ_subset_iff, ← h.1], exact ⟨closure_mono (submodule.span_mono (tangent_cone_mono st)), closure_mono st h.2⟩ end lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at k s x := begin have := unique_diff_within_at_univ.inter (mem_nhds_sets hs xs), rwa univ_inter at this end lemma unique_diff_on_inter (hs : unique_diff_on k s) (ht : is_open t) : unique_diff_on k (s ∩ t) := λx hx, (hs x hx.1).inter (mem_nhds_sets ht hx.2) lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on k s := λx hx, is_open.unique_diff_within_at hs hx /-- The product of two sets of unique differentiability at points `x` and `y` has unique differentiability at `(x, y)`. -/ lemma unique_diff_within_at.prod {t : set F} {y : F} (hs : unique_diff_within_at k s x) (ht : unique_diff_within_at k t y) : unique_diff_within_at k (set.prod s t) (x, y) := begin rw [unique_diff_within_at, ← univ_subset_iff] at ⊢ hs ht, split, { assume v _, rw metric.mem_closure_iff', assume ε ε_pos, rcases v with ⟨v₁, v₂⟩, rcases metric.mem_closure_iff'.1 (hs.1 (mem_univ v₁)) ε ε_pos with ⟨w₁, w₁_mem, h₁⟩, rcases metric.mem_closure_iff'.1 (ht.1 (mem_univ v₂)) ε ε_pos with ⟨w₂, w₂_mem, h₂⟩, have I₁ : (w₁, (0 : F)) ∈ submodule.span k (tangent_cone_at k (set.prod s t) (x, y)), { apply submodule.span_induction w₁_mem, { assume w hw, have : (w, (0 : F)) ∈ (set.prod (tangent_cone_at k s x) {(0 : F)}), { rw mem_prod, simp [hw], apply mem_insert }, have : (w, (0 : F)) ∈ tangent_cone_at k (set.prod s t) (x, y) := subset_tangent_cone_prod_left ht.2 this, exact submodule.subset_span this }, { exact submodule.zero_mem _ }, { assume a b ha hb, have : (a, (0 : F)) + (b, (0 : F)) = (a + b, (0 : F)), by simp, rw ← this, exact submodule.add_mem _ ha hb }, { assume c a ha, have : c • (0 : F) = (0 : F), by simp, rw ← this, exact submodule.smul_mem _ _ ha } }, have I₂ : ((0 : E), w₂) ∈ submodule.span k (tangent_cone_at k (set.prod s t) (x, y)), { apply submodule.span_induction w₂_mem, { assume w hw, have : ((0 : E), w) ∈ (set.prod {(0 : E)} (tangent_cone_at k t y)), { rw mem_prod, simp [hw], apply mem_insert }, have : ((0 : E), w) ∈ tangent_cone_at k (set.prod s t) (x, y) := subset_tangent_cone_prod_right hs.2 this, exact submodule.subset_span this }, { exact submodule.zero_mem _ }, { assume a b ha hb, have : ((0 : E), a) + ((0 : E), b) = ((0 : E), a + b), by simp, rw ← this, exact submodule.add_mem _ ha hb }, { assume c a ha, have : c • (0 : E) = (0 : E), by simp, rw ← this, exact submodule.smul_mem _ _ ha } }, have I : (w₁, w₂) ∈ submodule.span k (tangent_cone_at k (set.prod s t) (x, y)), { have : (w₁, (0 : F)) + ((0 : E), w₂) = (w₁, w₂), by simp, rw ← this, exact submodule.add_mem _ I₁ I₂ }, refine ⟨(w₁, w₂), I, _⟩, simp [dist, h₁, h₂] }, { simp [closure_prod_eq, mem_prod_iff, hs.2, ht.2] } end /-- The product of two sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on k s) (ht : unique_diff_on k t) : unique_diff_on k (set.prod s t) := λ ⟨x, y⟩ h, unique_diff_within_at.prod (hs x h.1) (ht y h.2) /-- In a real vector space, a convex set with nonempty interior is a set of unique differentiability. -/ theorem unique_diff_on_convex {s : set G} (conv : convex s) (hs : interior s ≠ ∅) : unique_diff_on ℝ s := begin assume x xs, have A : ∀v, ∃a∈ tangent_cone_at ℝ s x, ∃b∈ tangent_cone_at ℝ s x, ∃δ>(0:ℝ), δ • v = b-a, { assume v, rcases ne_empty_iff_exists_mem.1 hs with ⟨y, hy⟩, have ys : y ∈ s := interior_subset hy, have : ∃(δ : ℝ), 0<δ ∧ y + δ • v ∈ s, { by_cases h : ∥v∥ = 0, { exact ⟨1, zero_lt_one, by simp [(norm_eq_zero _).1 h, ys]⟩ }, { rcases mem_interior.1 hy with ⟨u, us, u_open, yu⟩, rcases metric.is_open_iff.1 u_open y yu with ⟨ε, εpos, hε⟩, let δ := (ε/2) / ∥v∥, have δpos : 0 < δ := div_pos (half_pos εpos) (lt_of_le_of_ne (norm_nonneg _) (ne.symm h)), have : y + δ • v ∈ s, { apply us (hε _), rw [metric.mem_ball, dist_eq_norm], calc ∥(y + δ • v) - y ∥ = ∥δ • v∥ : by {congr' 1, abel } ... = ∥δ∥ * ∥v∥ : norm_smul _ _ ... = δ * ∥v∥ : by simp only [norm, abs_of_nonneg (le_of_lt δpos)] ... = ε /2 : div_mul_cancel _ h ... < ε : half_lt_self εpos }, exact ⟨δ, δpos, this⟩ } }, rcases this with ⟨δ, δpos, hδ⟩, refine ⟨y-x, _, (y + δ • v) - x, _, δ, δpos, by abel⟩, exact mem_tangent_cone_of_segment_subset ((convex_segment_iff _).1 conv x y xs ys), exact mem_tangent_cone_of_segment_subset ((convex_segment_iff _).1 conv x _ xs hδ) }, have B : ∀v:G, v ∈ submodule.span ℝ (tangent_cone_at ℝ s x), { assume v, rcases A v with ⟨a, ha, b, hb, δ, hδ, h⟩, have : v = δ⁻¹ • (b - a), by { rw [← h, smul_smul, inv_mul_cancel, one_smul], exact (ne_of_gt hδ) }, rw this, exact submodule.smul_mem _ _ (submodule.sub_mem _ (submodule.subset_span hb) (submodule.subset_span ha)) }, refine ⟨univ_subset_iff.1 (λv hv, subset_closure (B v)), subset_closure xs⟩ end /-- The real interval `[0, 1]` is a set of unique differentiability. -/ lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) := begin apply unique_diff_on_convex (convex_Icc 0 1), have : (1/(2:ℝ)) ∈ interior (Icc (0:ℝ) 1) := mem_interior.2 ⟨Ioo (0:ℝ) 1, Ioo_subset_Icc_self, is_open_Ioo, by norm_num, by norm_num⟩, exact ne_empty_of_mem this, end end unique_diff
3242e8bfb8bfba3b88fd2c4a70ae78291d768caa
1a61aba1b67cddccce19532a9596efe44be4285f
/library/data/num.lean
7746fedf3ebb4826d69d7e03d86ad2a6bd2cc328
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
17,903
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import data.bool tools.helper_tactics open bool eq.ops decidable helper_tactics namespace pos_num theorem succ_not_is_one (a : pos_num) : is_one (succ a) = ff := pos_num.induction_on a rfl (take n iH, rfl) (take n iH, rfl) theorem succ_one : succ one = bit0 one theorem succ_bit1 (a : pos_num) : succ (bit1 a) = bit0 (succ a) theorem succ_bit0 (a : pos_num) : succ (bit0 a) = bit1 a theorem ne_of_bit0_ne_bit0 {a b : pos_num} (H₁ : bit0 a ≠ bit0 b) : a ≠ b := suppose a = b, absurd rfl (this ▸ H₁) theorem ne_of_bit1_ne_bit1 {a b : pos_num} (H₁ : bit1 a ≠ bit1 b) : a ≠ b := suppose a = b, absurd rfl (this ▸ H₁) theorem pred_succ : ∀ (a : pos_num), pred (succ a) = a | one := rfl | (bit0 a) := by rewrite succ_bit0 | (bit1 a) := calc pred (succ (bit1 a)) = cond (is_one (succ a)) one (bit1 (pred (succ a))) : rfl ... = cond ff one (bit1 (pred (succ a))) : succ_not_is_one ... = bit1 (pred (succ a)) : rfl ... = bit1 a : pred_succ a section variables (a b : pos_num) theorem one_add_one : one + one = bit0 one theorem one_add_bit0 : one + (bit0 a) = bit1 a theorem one_add_bit1 : one + (bit1 a) = succ (bit1 a) theorem bit0_add_one : (bit0 a) + one = bit1 a theorem bit1_add_one : (bit1 a) + one = succ (bit1 a) theorem bit0_add_bit0 : (bit0 a) + (bit0 b) = bit0 (a + b) theorem bit0_add_bit1 : (bit0 a) + (bit1 b) = bit1 (a + b) theorem bit1_add_bit0 : (bit1 a) + (bit0 b) = bit1 (a + b) theorem bit1_add_bit1 : (bit1 a) + (bit1 b) = succ (bit1 (a + b)) theorem one_mul : one * a = a end theorem mul_one : ∀ a, a * one = a | one := rfl | (bit1 n) := calc bit1 n * one = bit0 (n * one) + one : rfl ... = bit0 n + one : mul_one n ... = bit1 n : bit0_add_one | (bit0 n) := calc bit0 n * one = bit0 (n * one) : rfl ... = bit0 n : mul_one n theorem decidable_eq [instance] : ∀ (a b : pos_num), decidable (a = b) | one one := inl rfl | one (bit0 b) := inr (by contradiction) | one (bit1 b) := inr (by contradiction) | (bit0 a) one := inr (by contradiction) | (bit0 a) (bit0 b) := match decidable_eq a b with | inl H₁ := inl (by rewrite H₁) | inr H₁ := inr (by intro H; injection H; contradiction) end | (bit0 a) (bit1 b) := inr (by contradiction) | (bit1 a) one := inr (by contradiction) | (bit1 a) (bit0 b) := inr (by contradiction) | (bit1 a) (bit1 b) := match decidable_eq a b with | inl H₁ := inl (by rewrite H₁) | inr H₁ := inr (by intro H; injection H; contradiction) end local notation a < b := (lt a b = tt) local notation a `≮`:50 b:50 := (lt a b = ff) theorem lt_one_right_eq_ff : ∀ a : pos_num, a ≮ one | one := rfl | (bit0 a) := rfl | (bit1 a) := rfl theorem lt_one_succ_eq_tt : ∀ a : pos_num, one < succ a | one := rfl | (bit0 a) := rfl | (bit1 a) := rfl theorem lt_of_lt_bit0_bit0 {a b : pos_num} (H : bit0 a < bit0 b) : a < b := H theorem lt_of_lt_bit0_bit1 {a b : pos_num} (H : bit1 a < bit0 b) : a < b := H theorem lt_of_lt_bit1_bit1 {a b : pos_num} (H : bit1 a < bit1 b) : a < b := H theorem lt_of_lt_bit1_bit0 {a b : pos_num} (H : bit0 a < bit1 b) : a < succ b := H theorem lt_bit0_bit0_eq_lt (a b : pos_num) : lt (bit0 a) (bit0 b) = lt a b := rfl theorem lt_bit1_bit1_eq_lt (a b : pos_num) : lt (bit1 a) (bit1 b) = lt a b := rfl theorem lt_bit1_bit0_eq_lt (a b : pos_num) : lt (bit1 a) (bit0 b) = lt a b := rfl theorem lt_bit0_bit1_eq_lt_succ (a b : pos_num) : lt (bit0 a) (bit1 b) = lt a (succ b) := rfl theorem lt_irrefl : ∀ (a : pos_num), a ≮ a | one := rfl | (bit0 a) := begin rewrite lt_bit0_bit0_eq_lt, apply lt_irrefl end | (bit1 a) := begin rewrite lt_bit1_bit1_eq_lt, apply lt_irrefl end theorem ne_of_lt_eq_tt : ∀ {a b : pos_num}, a < b → a = b → false | one ⌞one⌟ H₁ (eq.refl one) := absurd H₁ ff_ne_tt | (bit0 a) ⌞(bit0 a)⌟ H₁ (eq.refl (bit0 a)) := begin rewrite lt_bit0_bit0_eq_lt at H₁, apply ne_of_lt_eq_tt H₁ (eq.refl a) end | (bit1 a) ⌞(bit1 a)⌟ H₁ (eq.refl (bit1 a)) := begin rewrite lt_bit1_bit1_eq_lt at H₁, apply ne_of_lt_eq_tt H₁ (eq.refl a) end theorem lt_base : ∀ a : pos_num, a < succ a | one := rfl | (bit0 a) := begin rewrite [succ_bit0, lt_bit0_bit1_eq_lt_succ], apply lt_base end | (bit1 a) := begin rewrite [succ_bit1, lt_bit1_bit0_eq_lt], apply lt_base end theorem lt_step : ∀ {a b : pos_num}, a < b → a < succ b | one one H := rfl | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := begin rewrite [succ_bit0, lt_bit0_bit1_eq_lt_succ, lt_bit0_bit0_eq_lt at H], apply lt_step H end | (bit0 a) (bit1 b) H := begin rewrite [succ_bit1, lt_bit0_bit0_eq_lt, lt_bit0_bit1_eq_lt_succ at H], exact H end | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite [succ_bit0, lt_bit1_bit1_eq_lt, lt_bit1_bit0_eq_lt at H], exact H end | (bit1 a) (bit1 b) H := begin rewrite [succ_bit1, lt_bit1_bit0_eq_lt, lt_bit1_bit1_eq_lt at H], apply lt_step H end theorem lt_of_lt_succ_succ : ∀ {a b : pos_num}, succ a < succ b → a < b | one one H := absurd H ff_ne_tt | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := begin rewrite [succ_bit0 at H, succ_one at H, lt_bit1_bit0_eq_lt at H], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H end | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := by exact H | (bit1 a) one H := begin rewrite [succ_bit1 at H, succ_one at H, lt_bit0_bit0_eq_lt at H], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff (succ a)) H end | (bit1 a) (bit0 b) H := begin rewrite [succ_bit1 at H, succ_bit0 at H, lt_bit0_bit1_eq_lt_succ at H], rewrite lt_bit1_bit0_eq_lt, apply lt_of_lt_succ_succ H end | (bit1 a) (bit1 b) H := begin rewrite [lt_bit1_bit1_eq_lt, *succ_bit1 at H, lt_bit0_bit0_eq_lt at H], apply lt_of_lt_succ_succ H end theorem lt_succ_succ : ∀ {a b : pos_num}, a < b → succ a < succ b | one one H := absurd H ff_ne_tt | one (bit0 b) H := begin rewrite [succ_bit0, succ_one, lt_bit0_bit1_eq_lt_succ], apply lt_one_succ_eq_tt end | one (bit1 b) H := begin rewrite [succ_one, succ_bit1, lt_bit0_bit0_eq_lt], apply lt_one_succ_eq_tt end | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := by exact H | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite [succ_bit1, succ_bit0, lt_bit0_bit1_eq_lt_succ, lt_bit1_bit0_eq_lt at H], apply lt_succ_succ H end | (bit1 a) (bit1 b) H := begin rewrite [lt_bit1_bit1_eq_lt at H, *succ_bit1, lt_bit0_bit0_eq_lt], apply lt_succ_succ H end theorem lt_of_lt_succ : ∀ {a b : pos_num}, succ a < b → a < b | one one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := begin rewrite [succ_bit0 at H, lt_bit1_bit1_eq_lt at H, lt_bit0_bit1_eq_lt_succ], apply lt_step H end | (bit1 a) one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | (bit1 a) (bit0 b) H := begin rewrite [lt_bit1_bit0_eq_lt, succ_bit1 at H, lt_bit0_bit0_eq_lt at H], apply lt_of_lt_succ H end | (bit1 a) (bit1 b) H := begin rewrite [succ_bit1 at H, lt_bit0_bit1_eq_lt_succ at H, lt_bit1_bit1_eq_lt], apply lt_of_lt_succ_succ H end theorem lt_of_lt_succ_of_ne : ∀ {a b : pos_num}, a < succ b → a ≠ b → a < b | one one H₁ H₂ := absurd rfl H₂ | one (bit0 b) H₁ H₂ := rfl | one (bit1 b) H₁ H₂ := rfl | (bit0 a) one H₁ H₂ := begin rewrite [succ_one at H₁, lt_bit0_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [lt_bit0_bit0_eq_lt, succ_bit0 at H₁, lt_bit0_bit1_eq_lt_succ at H₁], apply lt_of_lt_succ_of_ne H₁ (ne_of_bit0_ne_bit0 H₂) end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [succ_bit1 at H₁, lt_bit0_bit0_eq_lt at H₁, lt_bit0_bit1_eq_lt_succ], exact H₁ end | (bit1 a) one H₁ H₂ := begin rewrite [succ_one at H₁, lt_bit1_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [succ_bit0 at H₁, lt_bit1_bit1_eq_lt at H₁, lt_bit1_bit0_eq_lt], exact H₁ end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [succ_bit1 at H₁, lt_bit1_bit0_eq_lt at H₁, lt_bit1_bit1_eq_lt], apply lt_of_lt_succ_of_ne H₁ (ne_of_bit1_ne_bit1 H₂) end theorem lt_trans : ∀ {a b c : pos_num}, a < b → b < c → a < c | one b (bit0 c) H₁ H₂ := rfl | one b (bit1 c) H₁ H₂ := rfl | a (bit0 b) one H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | a (bit1 b) one H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | (bit0 a) (bit0 b) (bit0 c) H₁ H₂ := begin rewrite lt_bit0_bit0_eq_lt at *, apply lt_trans H₁ H₂ end | (bit0 a) (bit0 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at *, lt_bit0_bit0_eq_lt at H₁], apply lt_trans H₁ H₂ end | (bit0 a) (bit1 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at H₁, lt_bit1_bit0_eq_lt at H₂, lt_bit0_bit0_eq_lt], apply @by_cases (a = b), begin intro H, rewrite -H at H₂, exact H₂ end, begin intro H, apply lt_trans (lt_of_lt_succ_of_ne H₁ H) H₂ end end | (bit0 a) (bit1 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at *, lt_bit1_bit1_eq_lt at H₂], apply lt_trans H₁ (lt_succ_succ H₂) end | (bit1 a) (bit0 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit0_bit0_eq_lt at H₂, lt_bit1_bit0_eq_lt at *], apply lt_trans H₁ H₂ end | (bit1 a) (bit0 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit1_bit0_eq_lt at H₁, lt_bit0_bit1_eq_lt_succ at H₂, lt_bit1_bit1_eq_lt], apply @by_cases (b = c), begin intro H, rewrite H at H₁, exact H₁ end, begin intro H, apply lt_trans H₁ (lt_of_lt_succ_of_ne H₂ H) end end | (bit1 a) (bit1 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit1_bit1_eq_lt at H₁, lt_bit1_bit0_eq_lt at H₂, lt_bit1_bit0_eq_lt], apply lt_trans H₁ H₂ end | (bit1 a) (bit1 b) (bit1 c) H₁ H₂ := begin rewrite lt_bit1_bit1_eq_lt at *, apply lt_trans H₁ H₂ end theorem lt_antisymm : ∀ {a b : pos_num}, a < b → b ≮ a | one one H := rfl | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := begin rewrite lt_bit0_bit0_eq_lt at *, apply lt_antisymm H end | (bit0 a) (bit1 b) H := begin rewrite lt_bit1_bit0_eq_lt, rewrite lt_bit0_bit1_eq_lt_succ at H, have H₁ : succ b ≮ a, from lt_antisymm H, apply eq_ff_of_ne_tt, intro H₂, apply @by_cases (succ b = a), show succ b = a → false, begin intro Hp, rewrite -Hp at H, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl (succ b)) H end, show succ b ≠ a → false, begin intro Hn, have H₃ : succ b < succ a, from lt_succ_succ H₂, have H₄ : succ b < a, from lt_of_lt_succ_of_ne H₃ Hn, apply absurd_of_eq_ff_of_eq_tt H₁ H₄ end, end | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite lt_bit0_bit1_eq_lt_succ, rewrite lt_bit1_bit0_eq_lt at H, have H₁ : lt b a = ff, from lt_antisymm H, apply eq_ff_of_ne_tt, intro H₂, apply @by_cases (b = a), show b = a → false, begin intro Hp, rewrite -Hp at H, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl b) H end, show b ≠ a → false, begin intro Hn, have H₃ : b < a, from lt_of_lt_succ_of_ne H₂ Hn, apply absurd_of_eq_ff_of_eq_tt H₁ H₃ end, end | (bit1 a) (bit1 b) H := begin rewrite lt_bit1_bit1_eq_lt at *, apply lt_antisymm H end local notation a ≤ b := (le a b = tt) theorem le_refl : ∀ a : pos_num, a ≤ a := lt_base theorem le_eq_lt_succ {a b : pos_num} : le a b = lt a (succ b) := rfl theorem not_lt_of_le : ∀ {a b : pos_num}, a ≤ b → b < a → false | one one H₁ H₂ := absurd H₂ ff_ne_tt | one (bit0 b) H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | one (bit1 b) H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | (bit0 a) one H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_one at H₁, lt_bit0_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit0 at H₁, lt_bit0_bit1_eq_lt_succ at H₁], rewrite [lt_bit0_bit0_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit1 at H₁, lt_bit0_bit0_eq_lt at H₁], rewrite [lt_bit1_bit0_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end | (bit1 a) one H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_one at H₁, lt_bit1_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit0 at H₁, lt_bit1_bit1_eq_lt at H₁], rewrite lt_bit0_bit1_eq_lt_succ at H₂, have H₃ : a < succ b, from lt_step H₁, apply @by_cases (b = a), begin intro Hba, rewrite -Hba at H₁, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl b) H₁ end, begin intro Hnba, have H₄ : b < a, from lt_of_lt_succ_of_ne H₂ Hnba, apply not_lt_of_le H₃ H₄ end end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit1 at H₁, lt_bit1_bit0_eq_lt at H₁], rewrite [lt_bit1_bit1_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end theorem le_antisymm : ∀ {a b : pos_num}, a ≤ b → b ≤ a → a = b | one one H₁ H₂ := rfl | one (bit0 b) H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff b) H₂ | one (bit1 b) H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff b) H₂ | (bit0 a) one H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H₁ | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit0 at *, lt_bit0_bit1_eq_lt_succ at *], have H : a = b, from le_antisymm H₁ H₂, rewrite H end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit1 at H₁, succ_bit0 at H₂], rewrite [lt_bit0_bit0_eq_lt at H₁, lt_bit1_bit1_eq_lt at H₂], apply false.rec _ (not_lt_of_le H₁ H₂) end | (bit1 a) one H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H₁ | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit0 at H₁, succ_bit1 at H₂], rewrite [lt_bit1_bit1_eq_lt at H₁, lt_bit0_bit0_eq_lt at H₂], apply false.rec _ (not_lt_of_le H₂ H₁) end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit1 at *, lt_bit1_bit0_eq_lt at *], have H : a = b, from le_antisymm H₁ H₂, rewrite H end theorem le_trans {a b c : pos_num} : a ≤ b → b ≤ c → a ≤ c := begin intro H₁ H₂, rewrite [le_eq_lt_succ at *], apply @by_cases (a = b), begin intro Hab, rewrite Hab, exact H₂ end, begin intro Hnab, have Haltb : a < b, from lt_of_lt_succ_of_ne H₁ Hnab, apply lt_trans Haltb H₂ end, end end pos_num namespace num open pos_num theorem decidable_eq [instance] : ∀ (a b : num), decidable (a = b) | zero zero := inl rfl | zero (pos b) := inr (by contradiction) | (pos a) zero := inr (by contradiction) | (pos a) (pos b) := if H : a = b then inl (by rewrite H) else inr (suppose pos a = pos b, begin injection this, contradiction end) end num
0fcdb67315574012f09583a5dd7a7b2678effc2f
4727251e0cd73359b15b664c3170e5d754078599
/src/model_theory/syntax.lean
c00dd715c441204e9d8e84eeebc131b6d3065e03
[ "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
30,601
lean
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import data.list.prod_sigma import data.set.prod import logic.equiv.fin import model_theory.language_map /-! # Basics on First-Order Syntax This file defines first-order terms, formulas, sentences, and theories in a style inspired by the [Flypitch project](https://flypitch.github.io/). ## Main Definitions * A `first_order.language.term` is defined so that `L.term α` is the type of `L`-terms with free variables indexed by `α`. * A `first_order.language.formula` is defined so that `L.formula α` is the type of `L`-formulas with free variables indexed by `α`. * A `first_order.language.sentence` is a formula with no free variables. * A `first_order.language.Theory` is a set of sentences. * The variables of terms and formulas can be relabelled with `first_order.language.term.relabel`, `first_order.language.bounded_formula.relabel`, and `first_order.language.formula.relabel`. * `first_order.language.bounded_formula.cast_le` adds more `fin`-indexed variables. * `first_order.language.bounded_formula.lift_at` raises the indexes of the `fin`-indexed variables above a particular index. * `first_order.language.term.subst` and `first_order.language.bounded_formula.subst` substitute variables with given terms. * Language maps can act on syntactic objects with functions such as `first_order.language.Lhom.on_formula`. ## Implementation Notes * Formulas use a modified version of de Bruijn variables. Specifically, a `L.bounded_formula α n` is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some indexed by `fin n`, which can. For any `φ : L.bounded_formula α (n + 1)`, we define the formula `∀' φ : L.bounded_formula α n` by universally quantifying over the variable indexed by `n : fin (n + 1)`. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universes u v w u' v' namespace first_order namespace language variables (L : language.{u v}) {L' : language} variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P] variables {α : Type u'} {β : Type v'} open_locale first_order open Structure fin /-- A term on `α` is either a variable indexed by an element of `α` or a function symbol applied to simpler terms. -/ inductive term (α : Type u') : Type (max u u') | var {} : ∀ (a : α), term | func {} : ∀ {l : ℕ} (f : L.functions l) (ts : fin l → term), term export term variable {L} namespace term open finset /-- The `finset` of variables used in a given term. -/ @[simp] def var_finset [decidable_eq α] : L.term α → finset α | (var i) := {i} | (func f ts) := univ.bUnion (λ i, (ts i).var_finset) /-- The `finset` of variables from the left side of a sum used in a given term. -/ @[simp] def var_finset_left [decidable_eq α] : L.term (α ⊕ β) → finset α | (var (sum.inl i)) := {i} | (var (sum.inr i)) := ∅ | (func f ts) := univ.bUnion (λ i, (ts i).var_finset_left) /-- Relabels a term's variables along a particular function. -/ @[simp] def relabel (g : α → β) : L.term α → L.term β | (var i) := var (g i) | (func f ts) := func f (λ i, (ts i).relabel) /-- Restricts a term to use only a set of the given variables. -/ def restrict_var [decidable_eq α] : Π (t : L.term α) (f : t.var_finset → β), L.term β | (var a) f := var (f ⟨a, mem_singleton_self a⟩) | (func F ts) f := func F (λ i, (ts i).restrict_var (f ∘ (set.inclusion (subset_bUnion_of_mem _ (mem_univ i))))) /-- Restricts a term to use only a set of the given variables on the left side of a sum. -/ def restrict_var_left [decidable_eq α] {γ : Type*} : Π (t : L.term (α ⊕ γ)) (f : t.var_finset_left → β), L.term (β ⊕ γ) | (var (sum.inl a)) f := var (sum.inl (f ⟨a, mem_singleton_self a⟩)) | (var (sum.inr a)) f := var (sum.inr a) | (func F ts) f := func F (λ i, (ts i).restrict_var_left (f ∘ (set.inclusion (subset_bUnion_of_mem _ (mem_univ i))))) end term /-- The representation of a constant symbol as a term. -/ def constants.term (c : L.constants) : (L.term α) := func c default /-- Applies a unary function to a term. -/ def functions.apply₁ (f : L.functions 1) (t : L.term α) : L.term α := func f ![t] /-- Applies a binary function to two terms. -/ def functions.apply₂ (f : L.functions 2) (t₁ t₂ : L.term α) : L.term α := func f ![t₁, t₂] namespace term instance inhabited_of_var [inhabited α] : inhabited (L.term α) := ⟨var default⟩ instance inhabited_of_constant [inhabited L.constants] : inhabited (L.term α) := ⟨(default : L.constants).term⟩ /-- Raises all of the `fin`-indexed variables of a term greater than or equal to `m` by `n'`. -/ def lift_at {n : ℕ} (n' m : ℕ) : L.term (α ⊕ fin n) → L.term (α ⊕ fin (n + n')) := relabel (sum.map id (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i)) /-- Substitutes the variables in a given term with terms. -/ @[simp] def subst : L.term α → (α → L.term β) → L.term β | (var a) tf := tf a | (func f ts) tf := (func f (λ i, (ts i).subst tf)) end term localized "prefix `&`:max := first_order.language.term.var ∘ sum.inr" in first_order namespace Lhom /-- Maps a term's symbols along a language map. -/ @[simp] def on_term (φ : L →ᴸ L') : L.term α → L'.term α | (var i) := var i | (func f ts) := func (φ.on_function f) (λ i, on_term (ts i)) @[simp] lemma id_on_term : ((Lhom.id L).on_term : L.term α → L.term α) = id := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end @[simp] lemma comp_on_term {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_term : L.term α → L''.term α) = φ.on_term ∘ ψ.on_term := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end end Lhom /-- Maps a term's symbols along a language equivalence. -/ @[simps] def Lequiv.on_term (φ : L ≃ᴸ L') : L.term α ≃ L'.term α := { to_fun := φ.to_Lhom.on_term, inv_fun := φ.inv_Lhom.on_term, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_term, φ.left_inv, Lhom.id_on_term], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_term, φ.right_inv, Lhom.id_on_term] } variables (L) (α) /-- `bounded_formula α n` is the type of formulas with free variables indexed by `α` and up to `n` additional free variables. -/ inductive bounded_formula : ℕ → Type (max u v u') | falsum {} {n} : bounded_formula n | equal {n} (t₁ t₂ : L.term (α ⊕ fin n)) : bounded_formula n | rel {n l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : bounded_formula n | imp {n} (f₁ f₂ : bounded_formula n) : bounded_formula n | all {n} (f : bounded_formula (n+1)) : bounded_formula n /-- `formula α` is the type of formulas with all free variables indexed by `α`. -/ @[reducible] def formula := L.bounded_formula α 0 /-- A sentence is a formula with no free variables. -/ @[reducible] def sentence := L.formula empty /-- A theory is a set of sentences. -/ @[reducible] def Theory := set L.sentence variables {L} {α} {n : ℕ} /-- Applies a relation to terms as a bounded formula. -/ def relations.bounded_formula {l : ℕ} (R : L.relations n) (ts : fin n → L.term (α ⊕ fin l)) : L.bounded_formula α l := bounded_formula.rel R ts /-- Applies a unary relation to a term as a bounded formula. -/ def relations.bounded_formula₁ (r : L.relations 1) (t : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t] /-- Applies a binary relation to two terms as a bounded formula. -/ def relations.bounded_formula₂ (r : L.relations 2) (t₁ t₂ : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t₁, t₂] /-- The equality of two terms as a bounded formula. -/ def term.bd_equal (t₁ t₂ : L.term (α ⊕ fin n)) : (L.bounded_formula α n) := bounded_formula.equal t₁ t₂ /-- Applies a relation to terms as a bounded formula. -/ def relations.formula (R : L.relations n) (ts : fin n → L.term α) : L.formula α := R.bounded_formula (λ i, (ts i).relabel sum.inl) /-- Applies a unary relation to a term as a formula. -/ def relations.formula₁ (r : L.relations 1) (t : L.term α) : L.formula α := r.formula ![t] /-- Applies a binary relation to two terms as a formula. -/ def relations.formula₂ (r : L.relations 2) (t₁ t₂ : L.term α) : L.formula α := r.formula ![t₁, t₂] /-- The equality of two terms as a first-order formula. -/ def term.equal (t₁ t₂ : L.term α) : (L.formula α) := (t₁.relabel sum.inl).bd_equal (t₂.relabel sum.inl) namespace bounded_formula instance : inhabited (L.bounded_formula α n) := ⟨falsum⟩ instance : has_bot (L.bounded_formula α n) := ⟨falsum⟩ /-- The negation of a bounded formula is also a bounded formula. -/ @[pattern] protected def not (φ : L.bounded_formula α n) : L.bounded_formula α n := φ.imp ⊥ /-- Puts an `∃` quantifier on a bounded formula. -/ @[pattern] protected def ex (φ : L.bounded_formula α (n + 1)) : L.bounded_formula α n := φ.not.all.not instance : has_top (L.bounded_formula α n) := ⟨bounded_formula.not ⊥⟩ instance : has_inf (L.bounded_formula α n) := ⟨λ f g, (f.imp g.not).not⟩ instance : has_sup (L.bounded_formula α n) := ⟨λ f g, f.not.imp g⟩ /-- The biimplication between two bounded formulas. -/ protected def iff (φ ψ : L.bounded_formula α n) := φ.imp ψ ⊓ ψ.imp φ open finset /-- The `finset` of variables used in a given formula. -/ @[simp] def free_var_finset [decidable_eq α] : ∀ {n}, L.bounded_formula α n → finset α | n falsum := ∅ | n (equal t₁ t₂) := t₁.var_finset_left ∪ t₂.var_finset_left | n (rel R ts) := univ.bUnion (λ i, (ts i).var_finset_left) | n (imp f₁ f₂) := f₁.free_var_finset ∪ f₂.free_var_finset | n (all f) := f.free_var_finset /-- Casts `L.bounded_formula α m` as `L.bounded_formula α n`, where `m ≤ n`. -/ def cast_le : ∀ {m n : ℕ} (h : m ≤ n), L.bounded_formula α m → L.bounded_formula α n | m n h falsum := falsum | m n h (equal t₁ t₂) := (t₁.relabel (sum.map id (fin.cast_le h))).bd_equal (t₂.relabel (sum.map id (fin.cast_le h))) | m n h (rel R ts) := R.bounded_formula (term.relabel (sum.map id (fin.cast_le h)) ∘ ts) | m n h (imp f₁ f₂) := (f₁.cast_le h).imp (f₂.cast_le h) | m n h (all f) := (f.cast_le (add_le_add_right h 1)).all /-- A function to help relabel the variables in bounded formulas. -/ def relabel_aux (g : α → (β ⊕ fin n)) (k : ℕ) : α ⊕ fin k → β ⊕ fin (n + k) := (sum.map id fin_sum_fin_equiv) ∘ (equiv.sum_assoc _ _ _) ∘ (sum.map g id) @[simp] lemma sum_elim_comp_relabel_aux {m : ℕ} {g : α → (β ⊕ fin n)} {v : β → M} {xs : fin (n + m) → M} : sum.elim v xs ∘ relabel_aux g m = sum.elim (sum.elim v (xs ∘ cast_add m) ∘ g) (xs ∘ nat_add n) := begin ext x, cases x, { simp only [bounded_formula.relabel_aux, function.comp_app, sum.map_inl, sum.elim_inl], cases g x with l r; simp }, { simp [bounded_formula.relabel_aux] } end /-- Relabels a bounded formula's variables along a particular function. -/ def relabel (g : α → (β ⊕ fin n)) : ∀ {k : ℕ}, L.bounded_formula α k → L.bounded_formula β (n + k) | k falsum := falsum | k (equal t₁ t₂) := (t₁.relabel (relabel_aux g k)).bd_equal (t₂.relabel (relabel_aux g k)) | k (rel R ts) := R.bounded_formula (term.relabel (relabel_aux g k) ∘ ts) | k (imp f₁ f₂) := f₁.relabel.imp f₂.relabel | k (all f) := f.relabel.all /-- Restricts a bounded formula to only use a particular set of free variables. -/ def restrict_free_var [decidable_eq α] : Π {n : ℕ} (φ : L.bounded_formula α n) (f : φ.free_var_finset → β), L.bounded_formula β n | n falsum f := falsum | n (equal t₁ t₂) f := equal (t₁.restrict_var_left (f ∘ (set.inclusion (subset_union_left _ _)))) (t₂.restrict_var_left (f ∘ (set.inclusion (subset_union_right _ _)))) | n (rel R ts) f := rel R (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) | n (imp φ₁ φ₂) f := (φ₁.restrict_free_var (f ∘ (set.inclusion (subset_union_left _ _)))).imp (φ₂.restrict_free_var (f ∘ (set.inclusion (subset_union_right _ _)))) | n (all φ) f := (φ.restrict_free_var f).all /-- Places universal quantifiers on all extra variables of a bounded formula. -/ def alls : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.all.alls /-- Places existential quantifiers on all extra variables of a bounded formula. -/ def exs : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.ex.exs /-- Raises all of the `fin`-indexed variables of a formula greater than or equal to `m` by `n'`. -/ def lift_at : ∀ {n : ℕ} (n' m : ℕ), L.bounded_formula α n → L.bounded_formula α (n + n') | n n' m falsum := falsum | n n' m (equal t₁ t₂) := (t₁.lift_at n' m).bd_equal (t₂.lift_at n' m) | n n' m (rel R ts) := R.bounded_formula (term.lift_at n' m ∘ ts) | n n' m (imp f₁ f₂) := (f₁.lift_at n' m).imp (f₂.lift_at n' m) | n n' m (all f) := ((f.lift_at n' m).cast_le (by rw [add_assoc, add_comm 1, ← add_assoc])).all /-- Substitutes the variables in a given formula with terms. -/ @[simp] def subst : ∀ {n : ℕ}, L.bounded_formula α n → (α → L.term β) → L.bounded_formula β n | n falsum tf := falsum | n (equal t₁ t₂) tf := equal (t₁.subst (sum.elim (term.relabel sum.inl ∘ tf) (var ∘ sum.inr))) (t₂.subst (sum.elim (term.relabel sum.inl ∘ tf) (var ∘ sum.inr))) | n (rel R ts) tf := rel R (λ i, (ts i).subst (sum.elim (term.relabel sum.inl ∘ tf) (var ∘ sum.inr))) | n (imp φ₁ φ₂) tf := (φ₁.subst tf).imp (φ₂.subst tf) | n (all φ) tf := (φ.subst tf).all variables {l : ℕ} {φ ψ : L.bounded_formula α l} {θ : L.bounded_formula α l.succ} variables {v : α → M} {xs : fin l → M} /-- An atomic formula is either equality or a relation symbol applied to terms. Note that `⊥` and `⊤` are not considered atomic in this convention. -/ inductive is_atomic : L.bounded_formula α n → Prop | equal (t₁ t₂ : L.term (α ⊕ fin n)) : is_atomic (bd_equal t₁ t₂) | rel {l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : is_atomic (R.bounded_formula ts) lemma not_all_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_atomic := λ con, by cases con lemma not_ex_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_atomic := λ con, by cases con lemma is_atomic.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_atomic) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.lift_at {k m : ℕ} (h : is_atomic φ) : (φ.lift_at k m).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.cast_le {h : l ≤ n} (hφ : is_atomic φ) : (φ.cast_le h).is_atomic := is_atomic.rec_on hφ (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) /-- A quantifier-free formula is a formula defined without quantifiers. These are all equivalent to boolean combinations of atomic formulas. -/ inductive is_qf : L.bounded_formula α n → Prop | falsum : is_qf falsum | of_is_atomic {φ} (h : is_atomic φ) : is_qf φ | imp {φ₁ φ₂} (h₁ : is_qf φ₁) (h₂ : is_qf φ₂) : is_qf (φ₁.imp φ₂) lemma is_atomic.is_qf {φ : L.bounded_formula α n} : is_atomic φ → is_qf φ := is_qf.of_is_atomic lemma is_qf_bot : is_qf (⊥ : L.bounded_formula α n) := is_qf.falsum lemma is_qf.not {φ : L.bounded_formula α n} (h : is_qf φ) : is_qf φ.not := h.imp is_qf_bot lemma is_qf.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_qf) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_qf := is_qf.rec_on h is_qf_bot (λ _ h, (h.relabel f).is_qf) (λ _ _ _ _ h1 h2, h1.imp h2) lemma is_qf.lift_at {k m : ℕ} (h : is_qf φ) : (φ.lift_at k m).is_qf := is_qf.rec_on h is_qf_bot (λ _ ih, ih.lift_at.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma is_qf.cast_le {h : l ≤ n} (hφ : is_qf φ) : (φ.cast_le h).is_qf := is_qf.rec_on hφ is_qf_bot (λ _ ih, ih.cast_le.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma not_all_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_qf := λ con, begin cases con with _ con, exact (φ.not_all_is_atomic con), end lemma not_ex_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_qf := λ con, begin cases con with _ con _ _ con, { exact (φ.not_ex_is_atomic con) }, { exact not_all_is_qf _ con } end /-- Indicates that a bounded formula is in prenex normal form - that is, it consists of quantifiers applied to a quantifier-free formula. -/ inductive is_prenex : ∀ {n}, L.bounded_formula α n → Prop | of_is_qf {n} {φ : L.bounded_formula α n} (h : is_qf φ) : is_prenex φ | all {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.all | ex {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.ex lemma is_qf.is_prenex {φ : L.bounded_formula α n} : is_qf φ → is_prenex φ := is_prenex.of_is_qf lemma is_atomic.is_prenex {φ : L.bounded_formula α n} (h : is_atomic φ) : is_prenex φ := h.is_qf.is_prenex lemma is_prenex.induction_on_all_not {P : ∀ {n}, L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_prenex φ) (hq : ∀ {m} {ψ : L.bounded_formula α m}, ψ.is_qf → P ψ) (ha : ∀ {m} {ψ : L.bounded_formula α (m + 1)}, P ψ → P ψ.all) (hn : ∀ {m} {ψ : L.bounded_formula α m}, P ψ → P ψ.not) : P φ := is_prenex.rec_on h (λ _ _, hq) (λ _ _ _, ha) (λ _ _ _ ih, hn (ha (hn ih))) lemma is_prenex.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_prenex) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_prenex := is_prenex.rec_on h (λ _ _ h, (h.relabel f).is_prenex) (λ _ _ _ h, h.all) (λ _ _ _ h, h.ex) lemma is_prenex.cast_le (hφ : is_prenex φ) : ∀ {n} {h : l ≤ n}, (φ.cast_le h).is_prenex := is_prenex.rec_on hφ (λ _ _ ih _ _, ih.cast_le.is_prenex) (λ _ _ _ ih _ _, ih.all) (λ _ _ _ ih _ _, ih.ex) lemma is_prenex.lift_at {k m : ℕ} (h : is_prenex φ) : (φ.lift_at k m).is_prenex := is_prenex.rec_on h (λ _ _ ih, ih.lift_at.is_prenex) (λ _ _ _ ih, ih.cast_le.all) (λ _ _ _ ih, ih.cast_le.ex) /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` is quantifier-free and `ψ` is in prenex normal form, then `φ.to_prenex_imp_right ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp_right : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n φ (bounded_formula.ex ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).ex | n φ (all ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).all | n φ ψ := φ.imp ψ lemma is_qf.to_prenex_imp_right {φ : L.bounded_formula α n} : Π {ψ : L.bounded_formula α n}, is_qf ψ → (φ.to_prenex_imp_right ψ = φ.imp ψ) | _ is_qf.falsum := rfl | _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ (is_qf.imp is_qf.falsum _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp_right {φ ψ : L.bounded_formula α n} (hφ : is_qf φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp_right ψ) := begin induction hψ with _ _ hψ _ _ _ ih1 _ _ _ ih2, { rw hψ.to_prenex_imp_right, exact (hφ.imp hψ).is_prenex }, { exact (ih1 hφ.lift_at).all }, { exact (ih2 hφ.lift_at).ex } end /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` and `ψ` are in prenex normal form, then `φ.to_prenex_imp ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n (bounded_formula.ex φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).all | n (all φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).ex | _ φ ψ := φ.to_prenex_imp_right ψ lemma is_qf.to_prenex_imp : Π {φ ψ : L.bounded_formula α n}, φ.is_qf → φ.to_prenex_imp ψ = φ.to_prenex_imp_right ψ | _ _ is_qf.falsum := rfl | _ _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ _ (is_qf.imp is_qf.falsum _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp {φ ψ : L.bounded_formula α n} (hφ : is_prenex φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp ψ) := begin induction hφ with _ _ hφ _ _ _ ih1 _ _ _ ih2, { rw hφ.to_prenex_imp, exact is_prenex_to_prenex_imp_right hφ hψ }, { exact (ih1 hψ.lift_at).ex }, { exact (ih2 hψ.lift_at).all } end /-- For any bounded formula `φ`, `φ.to_prenex` is a semantically-equivalent formula in prenex normal form. -/ def to_prenex : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n | _ falsum := ⊥ | _ (equal t₁ t₂) := t₁.bd_equal t₂ | _ (rel R ts) := rel R ts | _ (imp f₁ f₂) := f₁.to_prenex.to_prenex_imp f₂.to_prenex | _ (all f) := f.to_prenex.all lemma to_prenex_is_prenex (φ : L.bounded_formula α n) : φ.to_prenex.is_prenex := bounded_formula.rec_on φ (λ _, is_qf_bot.is_prenex) (λ _ _ _, (is_atomic.equal _ _).is_prenex) (λ _ _ _ _, (is_atomic.rel _ _).is_prenex) (λ _ _ _ h1 h2, is_prenex_to_prenex_imp h1 h2) (λ _ _, is_prenex.all) end bounded_formula namespace Lhom open bounded_formula /-- Maps a bounded formula's symbols along a language map. -/ @[simp] def on_bounded_formula (g : L →ᴸ L') : ∀ {k : ℕ}, L.bounded_formula α k → L'.bounded_formula α k | k falsum := falsum | k (equal t₁ t₂) := (g.on_term t₁).bd_equal (g.on_term t₂) | k (rel R ts) := (g.on_relation R).bounded_formula (g.on_term ∘ ts) | k (imp f₁ f₂) := (on_bounded_formula f₁).imp (on_bounded_formula f₂) | k (all f) := (on_bounded_formula f).all @[simp] lemma id_on_bounded_formula : ((Lhom.id L).on_bounded_formula : L.bounded_formula α n → L.bounded_formula α n) = id := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { rw [on_bounded_formula, Lhom.id_on_term, id.def, id.def, id.def, bd_equal] }, { rw [on_bounded_formula, Lhom.id_on_term], refl, }, { rw [on_bounded_formula, ih1, ih2, id.def, id.def, id.def] }, { rw [on_bounded_formula, ih3, id.def, id.def] } end @[simp] lemma comp_on_bounded_formula {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_bounded_formula : L.bounded_formula α n → L''.bounded_formula α n) = φ.on_bounded_formula ∘ ψ.on_bounded_formula := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp only [on_bounded_formula, comp_on_term, function.comp_app], refl, }, { simp only [on_bounded_formula, comp_on_relation, comp_on_term, function.comp_app], refl }, { simp only [on_bounded_formula, function.comp_app, ih1, ih2, eq_self_iff_true, and_self], }, { simp only [ih3, on_bounded_formula, function.comp_app] } end /-- Maps a formula's symbols along a language map. -/ def on_formula (g : L →ᴸ L') : L.formula α → L'.formula α := g.on_bounded_formula /-- Maps a sentence's symbols along a language map. -/ def on_sentence (g : L →ᴸ L') : L.sentence → L'.sentence := g.on_formula /-- Maps a theory's symbols along a language map. -/ def on_Theory (g : L →ᴸ L') (T : L.Theory) : L'.Theory := g.on_sentence '' T @[simp] lemma mem_on_Theory {g : L →ᴸ L'} {T : L.Theory} {φ : L'.sentence} : φ ∈ g.on_Theory T ↔ ∃ φ₀, φ₀ ∈ T ∧ g.on_sentence φ₀ = φ := set.mem_image _ _ _ end Lhom namespace Lequiv /-- Maps a bounded formula's symbols along a language equivalence. -/ @[simps] def on_bounded_formula (φ : L ≃ᴸ L') : L.bounded_formula α n ≃ L'.bounded_formula α n := { to_fun := φ.to_Lhom.on_bounded_formula, inv_fun := φ.inv_Lhom.on_bounded_formula, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.left_inv, Lhom.id_on_bounded_formula], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.right_inv, Lhom.id_on_bounded_formula] } lemma on_bounded_formula_symm (φ : L ≃ᴸ L') : (φ.on_bounded_formula.symm : L'.bounded_formula α n ≃ L.bounded_formula α n) = φ.symm.on_bounded_formula := rfl /-- Maps a formula's symbols along a language equivalence. -/ def on_formula (φ : L ≃ᴸ L') : L.formula α ≃ L'.formula α := φ.on_bounded_formula @[simp] lemma on_formula_apply (φ : L ≃ᴸ L') : (φ.on_formula : L.formula α → L'.formula α) = φ.to_Lhom.on_formula := rfl @[simp] lemma on_formula_symm (φ : L ≃ᴸ L') : (φ.on_formula.symm : L'.formula α ≃ L.formula α) = φ.symm.on_formula := rfl /-- Maps a sentence's symbols along a language equivalence. -/ @[simps] def on_sentence (φ : L ≃ᴸ L') : L.sentence ≃ L'.sentence := φ.on_formula end Lequiv localized "infix ` =' `:88 := first_order.language.term.bd_equal" in first_order -- input \~- or \simeq localized "infixr ` ⟹ `:62 := first_order.language.bounded_formula.imp" in first_order -- input \==> localized "prefix `∀'`:110 := first_order.language.bounded_formula.all" in first_order localized "prefix `∼`:max := first_order.language.bounded_formula.not" in first_order -- input \~, the ASCII character ~ has too low precedence localized "infix ` ⇔ `:61 := first_order.language.bounded_formula.iff" in first_order -- input \<=> localized "prefix `∃'`:110 := first_order.language.bounded_formula.ex" in first_order -- input \ex namespace formula /-- Relabels a formula's variables along a particular function. -/ def relabel (g : α → β) : L.formula α → L.formula β := @bounded_formula.relabel _ _ _ 0 (sum.inl ∘ g) 0 /-- The graph of a function as a first-order formula. -/ def graph (f : L.functions n) : L.formula (fin (n + 1)) := equal (var 0) (func f (λ i, var i.succ)) /-- The negation of a formula. -/ protected def not (φ : L.formula α) : L.formula α := φ.not /-- The implication between formulas, as a formula. -/ protected def imp : L.formula α → L.formula α → L.formula α := bounded_formula.imp /-- The biimplication between formulas, as a formula. -/ protected def iff (φ ψ : L.formula α) : L.formula α := φ.iff ψ lemma is_atomic_graph (f : L.functions n) : (graph f).is_atomic := bounded_formula.is_atomic.equal _ _ end formula namespace relations variable (r : L.relations 2) /-- The sentence indicating that a basic relation symbol is reflexive. -/ protected def reflexive : L.sentence := ∀' r.bounded_formula₂ &0 &0 /-- The sentence indicating that a basic relation symbol is irreflexive. -/ protected def irreflexive : L.sentence := ∀' ∼ (r.bounded_formula₂ &0 &0) /-- The sentence indicating that a basic relation symbol is symmetric. -/ protected def symmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &0) /-- The sentence indicating that a basic relation symbol is antisymmetric. -/ protected def antisymmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ (r.bounded_formula₂ &1 &0 ⟹ term.bd_equal &0 &1)) /-- The sentence indicating that a basic relation symbol is transitive. -/ protected def transitive : L.sentence := ∀' ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &2 ⟹ r.bounded_formula₂ &0 &2) /-- The sentence indicating that a basic relation symbol is total. -/ protected def total : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⊔ r.bounded_formula₂ &1 &0) end relations section cardinality variable (L) /-- A sentence indicating that a structure has `n` distinct elements. -/ protected def sentence.card_ge (n) : L.sentence := (((((list.fin_range n).product (list.fin_range n)).filter (λ ij : _ × _, ij.1 ≠ ij.2)).map (λ (ij : _ × _), ∼ ((& ij.1).bd_equal (& ij.2)))).foldr (⊓) ⊤).exs /-- A theory indicating that a structure is infinite. -/ def infinite_theory : L.Theory := set.range (sentence.card_ge L) /-- A theory that indicates a structure is nonempty. -/ def nonempty_theory : L.Theory := {sentence.card_ge L 1} /-- A theory indicating that each of a set of constants is distinct. -/ def distinct_constants_theory (s : set α) : L[[α]].Theory := ((s ×ˢ s) ∩ (set.diagonal α).compl).image (λ ab, (((L.con ab.1).term.equal (L.con ab.2).term).not)) variables {L} {α} open set lemma monotone_distinct_constants_theory : monotone (L.distinct_constants_theory : set α → L[[α]].Theory) := λ s t st, (image_subset _ (inter_subset_inter_left _ (prod_mono st st))) lemma directed_distinct_constants_theory : directed (⊆) (L.distinct_constants_theory : set α → L[[α]].Theory) := monotone.directed_le monotone_distinct_constants_theory lemma distinct_constants_theory_eq_Union (s : set α) : L.distinct_constants_theory s = ⋃ (t : finset s), L.distinct_constants_theory (t.map (function.embedding.subtype (λ x, x ∈ s))) := begin classical, simp only [distinct_constants_theory], rw [← image_Union, ← Union_inter], refine congr rfl (congr (congr rfl _) rfl), ext ⟨i, j⟩, simp only [prod_mk_mem_set_prod_eq, finset.coe_map, function.embedding.coe_subtype, mem_Union, mem_image, finset.mem_coe, subtype.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right], refine ⟨λ h, ⟨{⟨i, h.1⟩, ⟨j, h.2⟩}, ⟨h.1, _⟩, ⟨h.2, _⟩⟩, _⟩, { simp }, { simp }, { rintros ⟨t, ⟨is, _⟩, ⟨js, _⟩⟩, exact ⟨is, js⟩ } end end cardinality end language end first_order
d45df42671236b9610f485d1c196574016dd0495
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/category/Rel.lean
739fef394762d94e3382362700c9e16bf4e8d276
[ "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
743
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.category /-! The category of types with binary relations as morphisms. -/ namespace category_theory universe u /-- A type synonym for `Type`, which carries the category instance for which morphisms are binary relations. -/ def Rel := Type u instance Rel.inhabited : inhabited Rel := by unfold Rel; apply_instance /-- The category of types with binary relations as morphisms. -/ instance rel : large_category Rel := { hom := λ X Y, X → Y → Prop, id := λ X, λ x y, x = y, comp := λ X Y Z f g x z, ∃ y, f x y ∧ g y z } end category_theory
e4f2fa30e31def05784ea82ba8ce025f20f62a9e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/IR/Format.lean
39f97980818a12dae1105edb22ea7fdc92cb5481
[ "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
7,032
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.IR.Basic namespace Lean namespace IR private def formatArg : Arg → Format | Arg.var id => format id | Arg.irrelevant => "◾" instance : ToFormat Arg := ⟨formatArg⟩ def formatArray {α : Type} [ToFormat α] (args : Array α) : Format := args.foldl (fun r a => r ++ " " ++ format a) Format.nil private def formatLitVal : LitVal → Format | LitVal.num v => format v | LitVal.str v => format (repr v) instance : ToFormat LitVal := ⟨formatLitVal⟩ private def formatCtorInfo : CtorInfo → Format | { name := name, cidx := cidx, usize := usize, ssize := ssize, .. } => Id.run do let mut r := f!"ctor_{cidx}" if usize > 0 || ssize > 0 then r := f!"{r}.{usize}.{ssize}" if name != Name.anonymous then r := f!"{r}[{name}]" r instance : ToFormat CtorInfo := ⟨formatCtorInfo⟩ private def formatExpr : Expr → Format | Expr.ctor i ys => format i ++ formatArray ys | Expr.reset n x => "reset[" ++ format n ++ "] " ++ format x | Expr.reuse x i u ys => "reuse" ++ (if u then "!" else "") ++ " " ++ format x ++ " in " ++ format i ++ formatArray ys | Expr.proj i x => "proj[" ++ format i ++ "] " ++ format x | Expr.uproj i x => "uproj[" ++ format i ++ "] " ++ format x | Expr.sproj n o x => "sproj[" ++ format n ++ ", " ++ format o ++ "] " ++ format x | Expr.fap c ys => format c ++ formatArray ys | Expr.pap c ys => "pap " ++ format c ++ formatArray ys | Expr.ap x ys => "app " ++ format x ++ formatArray ys | Expr.box _ x => "box " ++ format x | Expr.unbox x => "unbox " ++ format x | Expr.lit v => format v | Expr.isShared x => "isShared " ++ format x instance : ToFormat Expr := ⟨formatExpr⟩ instance : ToString Expr := ⟨fun e => Format.pretty (format e)⟩ private partial def formatIRType : IRType → Format | IRType.float => "float" | IRType.uint8 => "u8" | IRType.uint16 => "u16" | IRType.uint32 => "u32" | IRType.uint64 => "u64" | IRType.usize => "usize" | IRType.irrelevant => "◾" | IRType.object => "obj" | IRType.tobject => "tobj" | IRType.struct _ tys => let _ : ToFormat IRType := ⟨formatIRType⟩ "struct " ++ Format.bracket "{" (Format.joinSep tys.toList ", ") "}" | IRType.union _ tys => let _ : ToFormat IRType := ⟨formatIRType⟩ "union " ++ Format.bracket "{" (Format.joinSep tys.toList ", ") "}" instance : ToFormat IRType := ⟨formatIRType⟩ instance : ToString IRType := ⟨toString ∘ format⟩ private def formatParam : Param → Format | { x := name, borrow := b, ty := ty } => "(" ++ format name ++ " : " ++ (if b then "@& " else "") ++ format ty ++ ")" instance : ToFormat Param := ⟨formatParam⟩ def formatAlt (fmt : FnBody → Format) (indent : Nat) : Alt → Format | Alt.ctor i b => format i.name ++ " →" ++ Format.nest indent (Format.line ++ fmt b) | Alt.default b => "default →" ++ Format.nest indent (Format.line ++ fmt b) def formatParams (ps : Array Param) : Format := formatArray ps def formatFnBodyHead : FnBody → Format | FnBody.vdecl x ty e _ => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e | FnBody.jdecl j xs _ _ => format j ++ formatParams xs ++ " := ..." | FnBody.set x i y _ => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y | FnBody.uset x i y _ => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y | FnBody.sset x i o y ty _ => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y | FnBody.setTag x cidx _ => "setTag " ++ format x ++ " := " ++ format cidx | FnBody.inc x n _ _ _ => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x | FnBody.dec x n _ _ _ => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x | FnBody.del x _ => "del " ++ format x | FnBody.mdata d _ => "mdata " ++ format d | FnBody.case _ x _ _ => "case " ++ format x ++ " of ..." | FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys | FnBody.ret x => "ret " ++ format x | FnBody.unreachable => "⊥" @[export lean_ir_format_fn_body_head] private def formatFnBodyHead' (fn : FnBody) : String := formatFnBodyHead fn |>.pretty partial def formatFnBody (fnBody : FnBody) (indent : Nat := 2) : Format := let rec loop : FnBody → Format | FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e ++ ";" ++ Format.line ++ loop b | FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " :=" ++ Format.nest indent (Format.line ++ loop v) ++ ";" ++ Format.line ++ loop b | FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx ++ ";" ++ Format.line ++ loop b | FnBody.inc x n _ _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.dec x n _ _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.del x b => "del " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.mdata d b => "mdata " ++ format d ++ ";" ++ Format.line ++ loop b | FnBody.case _ x xType cs => "case " ++ format x ++ " : " ++ format xType ++ " of" ++ cs.foldl (fun r c => r ++ Format.line ++ formatAlt loop indent c) Format.nil | FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys | FnBody.ret x => "ret " ++ format x | FnBody.unreachable => "⊥" loop fnBody instance : ToFormat FnBody := ⟨formatFnBody⟩ instance : ToString FnBody := ⟨fun b => (format b).pretty⟩ def formatDecl (decl : Decl) (indent : Nat := 2) : Format := match decl with | Decl.fdecl f xs ty b _ => "def " ++ format f ++ formatParams xs ++ format " : " ++ format ty ++ " :=" ++ Format.nest indent (Format.line ++ formatFnBody b indent) | Decl.extern f xs ty _ => "extern " ++ format f ++ formatParams xs ++ format " : " ++ format ty instance : ToFormat Decl := ⟨formatDecl⟩ @[export lean_ir_decl_to_string] def declToString (d : Decl) : String := (format d).pretty instance : ToString Decl := ⟨declToString⟩ end Lean.IR
632585d6dfaa4fa9d33f515b1a325e1e5d4ef87a
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/finite_presentation.lean
3084be7a24354a937815d39b7c81c089454352a4
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
19,584
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.finite_type import ring_theory.mv_polynomial.tower import ring_theory.ideal.quotient_operations /-! # Finiteness conditions in commutative algebra In this file we define several notions of finiteness that are common in commutative algebra. ## Main declarations - `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite` all of these express that some object is finitely generated *as module* over some base ring. - `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type` all of these express that some object is finitely generated *as algebra* over some base ring. - `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation` all of these express that some object is finitely presented *as algebra* over some base ring. -/ open function (surjective) open_locale big_operators polynomial section module_and_algebra variables (R A B M N : Type*) /-- An algebra over a commutative semiring is `finite_presentation` if it is the quotient of a polynomial ring in `n` variables by a finitely generated ideal. -/ def algebra.finite_presentation [comm_semiring R] [semiring A] [algebra R A] : Prop := ∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg namespace algebra variables [comm_ring R] [comm_ring A] [algebra R A] [comm_ring B] [algebra R B] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] namespace finite_type variables {R A B} /-- A finitely presented algebra is of finite type. -/ lemma of_finite_presentation : finite_presentation R A → finite_type R A := begin rintro ⟨n, f, hf⟩, apply (finite_type.iff_quotient_mv_polynomial'').2, exact ⟨n, f, hf.1⟩ end end finite_type namespace finite_presentation variables {R A B} /-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely presented. -/ lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A := begin refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩, obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h, refine ⟨n, f, hf, _⟩, have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance, replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian, exact hnoet f.to_ring_hom.ker, end /-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/ lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B := begin obtain ⟨n, f, hf⟩ := hfp, use [n, alg_hom.comp ↑e f], split, { exact function.surjective.comp e.surjective hf.1 }, suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker, { rw hker, exact hf.2 }, { have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom, { have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl, have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl, rw [h, h1] }, rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot, ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] } end variable (R) /-- The ring of polynomials in finitely many variables is finitely presented. -/ protected lemma mv_polynomial (ι : Type u_2) [finite ι] : finite_presentation R (mv_polynomial ι R) := by casesI nonempty_fintype ι; exact let eqv := (mv_polynomial.rename_equiv R $ fintype.equiv_fin ι).symm in ⟨fintype.card ι, eqv, eqv.surjective, ((ring_hom.injective_iff_ker_eq_bot _).1 eqv.injective).symm ▸ submodule.fg_bot⟩ /-- `R` is finitely presented as `R`-algebra. -/ lemma self : finite_presentation R R := equiv (finite_presentation.mv_polynomial R pempty) (mv_polynomial.is_empty_alg_equiv R pempty) /-- `R[X]` is finitely presented as `R`-algebra. -/ lemma polynomial : finite_presentation R R[X] := equiv (finite_presentation.mv_polynomial R punit) (mv_polynomial.punit_alg_equiv R) variable {R} /-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely presented. -/ protected lemma quotient {I : ideal A} (h : I.fg) (hfp : finite_presentation R A) : finite_presentation R (A ⧸ I) := begin obtain ⟨n, f, hf⟩ := hfp, refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩, { exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 }, { refine ideal.fg_ker_comp _ _ hf.2 _ hf.1, simp [h] } end /-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented, then so is `B`. -/ lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg) (hfp : finite_presentation R A) : finite_presentation R B := equiv (hfp.quotient hker) (ideal.quotient_ker_alg_equiv_of_surjective hf) lemma iff : finite_presentation R A ↔ ∃ n (I : ideal (mv_polynomial (fin n) R)) (e : (_ ⧸ I) ≃ₐ[R] A), I.fg := begin split, { rintros ⟨n, f, hf⟩, exact ⟨n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2⟩ }, { rintros ⟨n, I, e, hfg⟩, exact equiv ((finite_presentation.mv_polynomial R _).quotient hfg) e } end /-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype by a finitely generated ideal. -/ lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) (_ : fintype ι) (f : mv_polynomial ι R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg := begin split, { rintro ⟨n, f, hfs, hfk⟩, set ulift_var := mv_polynomial.rename_equiv R equiv.ulift, refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom, hfs.comp ulift_var.surjective, ideal.fg_ker_comp _ _ _ hfk ulift_var.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, }, { rintro ⟨ι, hfintype, f, hf⟩, resetI, have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι), refine ⟨fintype.card ι, f.comp equiv.symm, hf.1.comp (alg_equiv.symm equiv).surjective, ideal.fg_ker_comp _ f _ hf.2 equiv.symm.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), } end /-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented as `R`-algebra. -/ lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*) [finite ι] : finite_presentation R (mv_polynomial ι A) := begin rw iff_quotient_mv_polynomial' at hfp ⊢, classical, obtain ⟨ι', _, f, hf_surj, hf_ker⟩ := hfp, resetI, let g := (mv_polynomial.map_alg_hom f).comp (mv_polynomial.sum_alg_equiv R ι ι').to_alg_hom, casesI nonempty_fintype (ι ⊕ ι'), refine ⟨ι ⊕ ι', by apply_instance, g, (mv_polynomial.map_surjective f.to_ring_hom hf_surj).comp (alg_equiv.surjective _), ideal.fg_ker_comp _ _ _ _ (alg_equiv.surjective _)⟩, { convert submodule.fg_bot, exact ring_hom.ker_coe_equiv (mv_polynomial.sum_alg_equiv R ι ι').to_ring_equiv }, { rw [alg_hom.to_ring_hom_eq_coe, mv_polynomial.map_alg_hom_coe_ring_hom, mv_polynomial.ker_map], exact hf_ker.map mv_polynomial.C, } end /-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is finitely presented as `R`-algebra. -/ lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A) (hfpB : finite_presentation A B) : finite_presentation R B := begin obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB, exact equiv ((mv_polynomial_of_finite_presentation hfpA _).quotient hfg) (e.restrict_scalars R) end open mv_polynomial -- We follow the proof of https://stacks.math.columbia.edu/tag/0561 -- TODO: extract out helper lemmas and tidy proof. lemma of_restrict_scalars_finite_presentation [algebra A B] [is_scalar_tower R A B] (hRB : finite_presentation R B) [hRA : finite_type R A] : finite_presentation A B := begin classical, obtain ⟨n, f, hf, s, hs⟩ := hRB, let RX := mv_polynomial (fin n) R, let AX := mv_polynomial (fin n) A, refine ⟨n, mv_polynomial.aeval (f ∘ X), _, _⟩, { rw [← algebra.range_top_iff_surjective, ← algebra.adjoin_range_eq_range_aeval, set.range_comp, _root_.eq_top_iff, ← @adjoin_adjoin_of_tower R A B, adjoin_image, adjoin_range_X, algebra.map_top, (algebra.range_top_iff_surjective _).mpr hf], exact subset_adjoin }, { obtain ⟨t, ht⟩ := hRA.out, have := λ i : t, hf (algebra_map A B i), choose t' ht', have ht'' : algebra.adjoin R ((algebra_map A AX) '' t ∪ set.range (X : _ → AX)) = ⊤, { rw [adjoin_union_eq_adjoin_adjoin, ← subalgebra.restrict_scalars_top R], congr' 1, swap, { exact subalgebra.is_scalar_tower_mid _ }, rw [adjoin_algebra_map, ht], apply subalgebra.restrict_scalars_injective R, rw [← adjoin_restrict_scalars, adjoin_range_X, subalgebra.restrict_scalars_top, subalgebra.restrict_scalars_top] }, let g : t → AX := λ x, C (x : A) - map (algebra_map R A) (t' x), refine ⟨s.image (map (algebra_map R A)) ∪ t.attach.image g, _⟩, rw [finset.coe_union, finset.coe_image, finset.coe_image, finset.attach_eq_univ, finset.coe_univ, set.image_univ], let s₀ := _, let I := _, change ideal.span s₀ = I, have leI : ideal.span s₀ ≤ I, { rw [ideal.span_le], rintros _ (⟨x, hx, rfl⟩|⟨⟨x, hx⟩, rfl⟩), all_goals { dsimp [g], rw [ring_hom.mem_ker, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom] }, { rw [mv_polynomial.aeval_map_algebra_map, ← aeval_unique], have := ideal.subset_span hx, rwa hs at this }, { rw [map_sub, mv_polynomial.aeval_map_algebra_map, ← aeval_unique, aeval_C, ht', subtype.coe_mk, sub_self] } }, apply leI.antisymm, intros x hx, rw [ring_hom.mem_ker, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom] at hx, let s₀ := _, change x ∈ ideal.span s₀, have : x ∈ (map (algebra_map R A) : _ →+* AX).srange.to_add_submonoid ⊔ (ideal.span s₀).to_add_submonoid, { have : x ∈ (⊤ : subalgebra R AX) := trivial, rw ← ht'' at this, apply adjoin_induction this, { rintros _ (⟨x, hx, rfl⟩|⟨i, rfl⟩), { rw [algebra_map_eq, ← sub_add_cancel (C x) (map (algebra_map R A) (t' ⟨x, hx⟩)), add_comm], apply add_submonoid.add_mem_sup, { exact set.mem_range_self _ }, { apply ideal.subset_span, apply set.mem_union_right, exact set.mem_range_self ⟨x, hx⟩ } }, { apply add_submonoid.mem_sup_left, exact ⟨X i, map_X _ _⟩ } }, { intro r, apply add_submonoid.mem_sup_left, exact ⟨C r, map_C _ _⟩ }, { intros _ _ h₁ h₂, exact add_mem h₁ h₂ }, { intros x₁ x₂ h₁ h₂, obtain ⟨_, ⟨p₁, rfl⟩, q₁, hq₁, rfl⟩ := add_submonoid.mem_sup.mp h₁, obtain ⟨_, ⟨p₂, rfl⟩, q₂, hq₂, rfl⟩ := add_submonoid.mem_sup.mp h₂, rw [add_mul, mul_add, add_assoc, ← map_mul], apply add_submonoid.add_mem_sup, { exact set.mem_range_self _ }, { refine add_mem (ideal.mul_mem_left _ _ hq₂) (ideal.mul_mem_right _ _ hq₁) } } }, obtain ⟨_, ⟨p, rfl⟩, q, hq, rfl⟩ := add_submonoid.mem_sup.mp this, rw [map_add, aeval_map_algebra_map, ← aeval_unique, (show aeval (f ∘ X) q = 0, from leI hq), add_zero] at hx, suffices : ideal.span (s : set RX) ≤ (ideal.span s₀).comap (map $ algebra_map R A), { refine add_mem _ hq, rw hs at this, exact this hx }, rw ideal.span_le, intros x hx, apply ideal.subset_span, apply set.mem_union_left, exact set.mem_image_of_mem _ hx } end /-- This is used to prove the strictly stronger `ker_fg_of_surjective`. Use it instead. -/ -- TODO: extract out helper lemmas and tidy proof. lemma ker_fg_of_mv_polynomial {n : ℕ} (f : mv_polynomial (fin n) R →ₐ[R] A) (hf : function.surjective f) (hfp : finite_presentation R A) : f.to_ring_hom.ker.fg := begin classical, obtain ⟨m, f', hf', s, hs⟩ := hfp, let RXn := mv_polynomial (fin n) R, let RXm := mv_polynomial (fin m) R, have := λ (i : fin n), hf' (f $ X i), choose g hg, have := λ (i : fin m), hf (f' $ X i), choose h hh, let aeval_h : RXm →ₐ[R] RXn := aeval h, let g' : fin n → RXn := λ i, X i - aeval_h (g i), refine ⟨finset.univ.image g' ∪ s.image aeval_h, _⟩, simp only [finset.coe_image, finset.coe_union, finset.coe_univ, set.image_univ], have hh' : ∀ x, f (aeval_h x) = f' x, { intro x, rw [← f.coe_to_ring_hom, map_aeval], simp_rw [alg_hom.coe_to_ring_hom, hh], rw [alg_hom.comp_algebra_map, ← aeval_eq_eval₂_hom, ← aeval_unique] }, let s' := set.range g' ∪ aeval_h '' s, have leI : ideal.span s' ≤ f.to_ring_hom.ker, { rw ideal.span_le, rintros _ (⟨i, rfl⟩|⟨x, hx, rfl⟩), { change f (g' i) = 0, rw [map_sub, ← hg, hh', sub_self], }, { change f (aeval_h x) = 0, rw hh', change x ∈ f'.to_ring_hom.ker, rw ← hs, exact ideal.subset_span hx } }, apply leI.antisymm, intros x hx, have : x ∈ aeval_h.range.to_add_submonoid ⊔ (ideal.span s').to_add_submonoid, { have : x ∈ adjoin R (set.range X : set RXn) := by { rw [adjoin_range_X], trivial }, apply adjoin_induction this, { rintros _ ⟨i, rfl⟩, rw [← sub_add_cancel (X i) (aeval h (g i)), add_comm], apply add_submonoid.add_mem_sup, { exact set.mem_range_self _ }, { apply submodule.subset_span, apply set.mem_union_left, exact set.mem_range_self _ } }, { intros r, apply add_submonoid.mem_sup_left, exact ⟨C r, aeval_C _ _⟩ }, { intros _ _ h₁ h₂, exact add_mem h₁ h₂ }, { intros p₁ p₂ h₁ h₂, obtain ⟨_, ⟨x₁, rfl⟩, y₁, hy₁, rfl⟩ := add_submonoid.mem_sup.mp h₁, obtain ⟨_, ⟨x₂, rfl⟩, y₂, hy₂, rfl⟩ := add_submonoid.mem_sup.mp h₂, rw [mul_add, add_mul, add_assoc, ← map_mul], apply add_submonoid.add_mem_sup, { exact set.mem_range_self _ }, { exact add_mem (ideal.mul_mem_right _ _ hy₁) (ideal.mul_mem_left _ _ hy₂) } } }, obtain ⟨_, ⟨x, rfl⟩, y, hy, rfl⟩ := add_submonoid.mem_sup.mp this, refine add_mem _ hy, simp only [ring_hom.mem_ker, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom, map_add, (show f y = 0, from leI hy), add_zero, hh'] at hx, suffices : ideal.span (s : set RXm) ≤ (ideal.span s').comap aeval_h, { apply this, rwa hs }, rw ideal.span_le, intros x hx, apply submodule.subset_span, apply set.mem_union_right, exact set.mem_image_of_mem _ hx end /-- If `f : A →ₐ[R] B` is a sujection between finitely-presented `R`-algebras, then the kernel of `f` is finitely generated. -/ lemma ker_fg_of_surjective (f : A →ₐ[R] B) (hf : function.surjective f) (hRA : finite_presentation R A) (hRB : finite_presentation R B) : f.to_ring_hom.ker.fg := begin obtain ⟨n, g, hg, hg'⟩ := hRA, convert (ker_fg_of_mv_polynomial (f.comp g) (hf.comp hg) hRB).map g.to_ring_hom, simp_rw [ring_hom.ker_eq_comap_bot, alg_hom.to_ring_hom_eq_coe, alg_hom.comp_to_ring_hom], rw [← ideal.comap_comap, ideal.map_comap_of_surjective (g : mv_polynomial (fin n) R →+* A) hg], end end finite_presentation end algebra end module_and_algebra namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] /-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra namespace finite_type lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type := @algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf end finite_type namespace finite_presentation variables (A) lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.ker.fg) : (g.comp f).finite_presentation := @algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra { to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation := by { rw ← f.comp_id, exact (id A).comp_surjective hf hker} lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation := @algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _ lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := @algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra { smul_assoc := λ a b c, begin simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end } hf hg lemma of_comp_finite_type (f : A →+* B) {g : B →+* C} (hg : (g.comp f).finite_presentation) (hf : f.finite_type) : g.finite_presentation := @@algebra.finite_presentation.of_restrict_scalars_finite_presentation _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra (@@is_scalar_tower.of_algebra_map_eq' _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra rfl) hg hf end finite_presentation end ring_hom namespace alg_hom variables {R A B C : Type*} [comm_ring R] variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra R A] [algebra R B] [algebra R C] /-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation namespace finite_type variables {R A} lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type := ring_hom.finite_type.of_finite_presentation hf end finite_type namespace finite_presentation variables (R A) lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp_surjective hf hg hker lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) : f.finite_presentation := ring_hom.finite_presentation.of_surjective f hf hker lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} : f.finite_type ↔ f.finite_presentation := ring_hom.finite_presentation.of_finite_type lemma of_comp_finite_type (f : A →ₐ[R] B) {g : B →ₐ[R] C} (h : (g.comp f).finite_presentation) (h' : f.finite_type) : g.finite_presentation := h.of_comp_finite_type _ h' end finite_presentation end alg_hom
f1374e3bcafaddb40dd6eca080ea3ed5a0eed97d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/unification_hints2.lean
c85c4f3a6b9564db0e523b3efa0fb9e37f86ad12
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,110
lean
open nat constant F : nat → Type constant F.suc (n : nat) (f : F n) : F (succ n) constant F.raise (n m : nat) (f : F m) : F (m + n) example (m n : nat) (i : F m) : F.raise (succ n) m i = F.suc _ (F.raise n _ i) := begin trace_state, -- the result should not contain recursor applications because the stdlib contains the unification hint add_succ_defeq_succ_add_hint admit end @[unify] def {u} cons_append_hint (α : Type u) (a b : α) (l₁ l₂ l₃: list α) : unification_hint := { pattern := (a :: l₁) ++ l₂ =?= b :: l₃, constraints := [l₃ =?= l₁ ++ l₂, a =?= b] } constant {u} G (α : Type u) : list α → Type constant {u} G.cons (α : Type u) (a : α) (l : list α) (g : G α l) : G α (a :: l) constant {u} G.raise (α : Type u) (l₁ l₂ : list α) (g : G α l₂) : G α (l₁ ++ l₂) universe u example (α : Type u) (a b : α) (l₁ l₂ : list α) (i : G α l₂) : G.raise α (a::l₁) l₂ i = G.cons α a _ (G.raise α _ _ i) := begin trace_state, -- the result should not contain recursor applications because we declared cons_append_hint above admit end
5158db754437cf9c0282ade623b8a8b2fa58c288
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/ideal/over.lean
5dc5663624ada2d0cf43ffa59fd2461d0fc5a4e4
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,367
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.algebraic import ring_theory.localization /-! # Ideals over/under ideals This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ variables {R : Type*} [comm_ring R] namespace ideal open polynomial open submodule section comm_ring variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma coeff_zero_mem_comap_of_root_mem_of_eval_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r ∈ I) : p.coeff 0 ∈ I.comap f := begin rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp, refine mem_comap.mpr ((I.add_mem_iff_right _).mp hp), exact I.mul_mem_left _ hr end lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (hp.symm ▸ I.zero_mem) lemma exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {r : S} (r_non_zero_divisor : ∀ {x}, x * r = 0 → x = 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := begin refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp, refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩, simp [coeff_eq_zero, a_ne_zero] }, { intros p p_nonzero ih mul_nonzero hp, rw [eval₂_mul, eval₂_X] at hp, obtain ⟨i, hi, mem⟩ := ih p_nonzero (r_non_zero_divisor hp), refine ⟨i + 1, _, _⟩; simp [hi, mem] } end /-- Let `P` be an ideal in `R[x]`. The map `R[x]/P → (R / (P ∩ R))[x] / (P / (P ∩ R))` is injective. -/ lemma injective_quotient_le_comap_map (P : ideal (polynomial R)) : function.injective ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map) := begin refine quotient_map_injective' (le_of_eq _), rw comap_map_of_surjective (map_ring_hom (quotient.mk (P.comap C))) (map_surjective _ quotient.mk_surjective), refine le_antisymm (sup_le le_rfl _) (le_sup_of_le_left le_rfl), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using ext_iff.mp (ideal.mem_bot.mp (mem_comap.mp hp)) n, end /-- The identity in this lemma asserts that the "obvious" square ``` R → (R / (P ∩ R)) ↓ ↓ R[x] / P → (R / (P ∩ R))[x] / (P / (P ∩ R)) ``` commutes. It is used, for instance, in the proof of `quotient_mk_comp_C_is_integral_of_jacobson`, in the file `ring_theory/jacobson`. -/ lemma quotient_mk_maps_eq (P : ideal (polynomial R)) : ((quotient.mk (map (map_ring_hom (quotient.mk (P.comap C))) P)).comp C).comp (quotient.mk (P.comap C)) = ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map).comp ((quotient.mk P).comp C) := begin refine ring_hom.ext (λ x, _), repeat { rw [ring_hom.coe_comp, function.comp_app] }, rw [quotient_map_mk, coe_map_ring_hom, map_C], end /-- This technical lemma asserts the existence of a polynomial `p` in an ideal `P ⊂ R[x]` that is non-zero in the quotient `R / (P ∩ R) [x]`. The assumptions are equivalent to `P ≠ 0` and `P ∩ R = (0)`. -/ lemma exists_nonzero_mem_of_ne_bot {P : ideal (polynomial R)} (Pb : P ≠ ⊥) (hP : ∀ (x : R), C x ∈ P → x = 0) : ∃ p : polynomial R, p ∈ P ∧ (polynomial.map (quotient.mk (P.comap C)) p) ≠ 0 := begin obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr Pb), refine ⟨m, submodule.coe_mem m, λ pp0, hm (submodule.coe_eq_zero.mp _)⟩, refine (ring_hom.injective_iff (polynomial.map_ring_hom (quotient.mk (P.comap C)))).mp _ _ pp0, refine map_injective _ ((quotient.mk (P.comap C)).injective_iff_ker_eq_bot.mpr _), rw [mk_ker], exact (submodule.eq_bot_iff _).mpr (λ x hx, hP x (mem_comap.mp hx)), end variables {p : ideal R} {P : ideal S} /-- If there is an injective map `R/p → S/P` such that following diagram commutes: ``` R → S ↓ ↓ R/p → S/P ``` then `P` lies over `p`. -/ lemma comap_eq_of_scalar_tower_quotient [algebra R S] [algebra p.quotient P.quotient] [is_scalar_tower R p.quotient P.quotient] (h : function.injective (algebra_map p.quotient P.quotient)) : comap (algebra_map R S) P = p := begin ext x, split; rw [mem_comap, ← quotient.eq_zero_iff_mem, ← quotient.eq_zero_iff_mem, quotient.mk_algebra_map, is_scalar_tower.algebra_map_apply _ p.quotient, quotient.algebra_map_eq], { intro hx, exact (algebra_map p.quotient P.quotient).injective_iff.mp h _ hx }, { intro hx, rw [hx, ring_hom.map_zero] }, end /-- If `P` lies over `p`, then `R / p` has a canonical map to `S / P`. -/ def quotient.algebra_quotient_of_le_comap (h : p ≤ comap f P) : algebra p.quotient P.quotient := ring_hom.to_algebra $ quotient_map _ f h /-- `R / p` has a canonical map to `S / pS`. -/ instance quotient.algebra_quotient_map_quotient : algebra p.quotient (map f p).quotient := quotient.algebra_quotient_of_le_comap le_comap_map @[simp] lemma quotient.algebra_map_quotient_map_quotient (x : R) : algebra_map p.quotient (map f p).quotient (quotient.mk p x) = quotient.mk _ (f x) := rfl @[simp] lemma quotient.mk_smul_mk_quotient_map_quotient (x : R) (y : S) : quotient.mk p x • quotient.mk (map f p) y = quotient.mk _ (f x * y) := rfl instance quotient.tower_quotient_map_quotient [algebra R S] : is_scalar_tower R p.quotient (map (algebra_map R S) p).quotient := is_scalar_tower.of_algebra_map_eq $ λ x, by rw [quotient.algebra_map_eq, quotient.algebra_map_quotient_map_quotient, quotient.mk_algebra_map] end comm_ring section is_domain variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma exists_coeff_ne_zero_mem_comap_of_root_mem [is_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (λ _ h, or.resolve_right (mul_eq_zero.mp h) r_ne_zero) hr lemma exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hpI : p.eval₂ f r ∈ I) : ∃ i, p.coeff i ∈ (J.comap f : set R) \ (I.comap f) := begin obtain ⟨hrJ, hrI⟩ := hr, have rbar_ne_zero : quotient.mk I r ≠ 0 := mt (quotient.mk_eq_zero I).mp hrI, have rbar_mem_J : quotient.mk I r ∈ J.map (quotient.mk I) := mem_map_of_mem _ hrJ, have quotient_f : ∀ x ∈ I.comap f, (quotient.mk I).comp f x = 0, { simp [quotient.eq_zero_iff_mem] }, have rbar_root : (p.map (quotient.mk (I.comap f))).eval₂ (quotient.lift (I.comap f) _ quotient_f) (quotient.mk I r) = 0, { convert quotient.eq_zero_iff_mem.mpr hpI, exact trans (eval₂_map _ _ _) (hom_eval₂ p f (quotient.mk I) r).symm }, obtain ⟨i, ne_zero, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem rbar_ne_zero rbar_mem_J p_ne_zero rbar_root, rw coeff_map at ne_zero mem, refine ⟨i, (mem_quotient_iff_mem hIJ).mp _, mt _ ne_zero⟩, { simpa using mem }, simp [quotient.eq_zero_iff_mem], end lemma comap_lt_comap_of_root_mem_sdiff [I.is_prime] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hp : p.eval₂ f r ∈ I) : I.comap f < J.comap f := let ⟨i, hJ, hI⟩ := exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff hIJ hr p_ne_zero hp in set_like.lt_iff_le_and_exists.mpr ⟨comap_mono hIJ, p.coeff i, hJ, hI⟩ lemma mem_of_one_mem (h : (1 : S) ∈ I) (x) : x ∈ I := (I.eq_top_iff_one.mpr h).symm ▸ mem_top lemma comap_lt_comap_of_integral_mem_sdiff [algebra R S] [hI : I.is_prime] (hIJ : I ≤ J) {x : S} (mem : x ∈ (J : set S) \ I) (integral : is_integral R x) : I.comap (algebra_map R S) < J.comap (algebra_map _ _) := begin obtain ⟨p, p_monic, hpx⟩ := integral, refine comap_lt_comap_of_root_mem_sdiff hIJ mem _ _, swap, { apply map_monic_ne_zero p_monic, apply quotient.nontrivial, apply mt comap_eq_top_iff.mp, apply hI.1 }, convert I.zero_mem end lemma comap_ne_bot_of_root_mem [is_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) : I.comap f ≠ ⊥ := λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in absurd (mem_bot.mp (eq_bot_iff.mp h mem)) hi lemma is_maximal_of_is_integral_of_is_maximal_comap [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R S))) : is_maximal I := ⟨⟨mt comap_eq_top_iff.mpr hI.1.1, λ J I_lt_J, let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_eq_top_iff.1 $ hI.1.2 _ (comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (hRS x))⟩⟩ lemma is_maximal_of_is_integral_of_is_maximal_comap' (f : R →+* S) (hf : f.is_integral) (I : ideal S) [hI' : I.is_prime] (hI : is_maximal (I.comap f)) : is_maximal I := @is_maximal_of_is_integral_of_is_maximal_comap R _ S _ f.to_algebra hf I hI' hI variables [algebra R S] lemma comap_ne_bot_of_algebraic_mem [is_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ := let ⟨p, p_ne_zero, hp⟩ := hx in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp lemma comap_ne_bot_of_integral_mem [nontrivial R] [is_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R) lemma eq_bot_of_comap_eq_bot [nontrivial R] [is_domain S] (hRS : algebra.is_integral R S) (hI : I.comap (algebra_map R S) = ⊥) : I = ⊥ := begin refine eq_bot_iff.2 (λ x hx, _), by_cases hx0 : x = 0, { exact hx0.symm ▸ ideal.zero_mem ⊥ }, { exact absurd hI (comap_ne_bot_of_integral_mem hx0 hx (hRS x)) } end lemma is_maximal_comap_of_is_integral_of_is_maximal (hRS : algebra.is_integral R S) (I : ideal S) [hI : I.is_maximal] : is_maximal (I.comap (algebra_map R S)) := begin refine quotient.maximal_of_is_field _ _, haveI : is_prime (I.comap (algebra_map R S)) := comap_is_prime _ _, exact is_field_of_is_integral_of_is_field (is_integral_quotient_of_is_integral hRS) algebra_map_quotient_injective (by rwa ← quotient.maximal_ideal_iff_is_field_quotient), end lemma is_maximal_comap_of_is_integral_of_is_maximal' {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) (hI : I.is_maximal) : is_maximal (I.comap f) := @is_maximal_comap_of_is_integral_of_is_maximal R _ S _ f.to_algebra hf I hI section is_integral_closure variables (S) {A : Type*} [comm_ring A] variables [algebra R A] [algebra A S] [is_scalar_tower R A S] [is_integral_closure A R S] lemma is_integral_closure.comap_lt_comap {I J : ideal A} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R A) < J.comap (algebra_map _ _) := let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (is_integral_closure.is_integral R S x) lemma is_integral_closure.is_maximal_of_is_maximal_comap (I : ideal A) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R A))) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (λ x, is_integral_closure.is_integral R S x) I hI variables [is_domain A] lemma is_integral_closure.comap_ne_bot [nontrivial R] {I : ideal A} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R A) ≠ ⊥ := let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in comap_ne_bot_of_integral_mem x_ne_zero x_mem (is_integral_closure.is_integral R S x) lemma is_integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal A} : I.comap (algebra_map R A) = ⊥ → I = ⊥ := imp_of_not_imp_not _ _ (is_integral_closure.comap_ne_bot S) end is_integral_closure lemma integral_closure.comap_lt_comap {I J : ideal (integral_closure R S)} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R (integral_closure R S)) < J.comap (algebra_map _ _) := is_integral_closure.comap_lt_comap S I_lt_J lemma integral_closure.is_maximal_of_is_maximal_comap (I : ideal (integral_closure R S)) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R (integral_closure R S)))) : is_maximal I := is_integral_closure.is_maximal_of_is_maximal_comap S I hI section variables [is_domain S] lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ := is_integral_closure.comap_ne_bot S I_ne_bot lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} : I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ := is_integral_closure.eq_bot_of_comap_eq_bot S /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_prime_of_is_integral' (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ Q.comap (algebra_map R S) = P := begin have hP0 : (0 : S) ∉ algebra.algebra_map_submonoid S P.prime_compl, { rintro ⟨x, ⟨hx, x0⟩⟩, exact absurd (hP x0) hx }, let Rₚ := localization P.prime_compl, let Sₚ := localization (algebra.algebra_map_submonoid S P.prime_compl), letI : is_domain (localization (algebra.algebra_map_submonoid S P.prime_compl)) := is_localization.is_domain_localization (le_non_zero_divisors_of_no_zero_divisors hP0), obtain ⟨Qₚ : ideal Sₚ, Qₚ_maximal⟩ := exists_maximal Sₚ, haveI Qₚ_max : is_maximal (comap _ Qₚ) := @is_maximal_comap_of_is_integral_of_is_maximal Rₚ _ Sₚ _ (localization_algebra P.prime_compl S) (is_integral_localization H) _ Qₚ_maximal, refine ⟨comap (algebra_map S Sₚ) Qₚ, ⟨comap_is_prime _ Qₚ, _⟩⟩, convert localization.at_prime.comap_maximal_ideal, rw [comap_comap, ← local_ring.eq_maximal_ideal Qₚ_max, ← is_localization.map_comp _], refl end end /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : I.comap (algebra_map R S) ≤ P) : ∃ Q ≥ I, is_prime Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q' : ideal I.quotient, ⟨Q'_prime, hQ'⟩⟩ := @exists_ideal_over_prime_of_is_integral' (I.comap (algebra_map R S)).quotient _ I.quotient _ ideal.quotient_algebra _ (is_integral_quotient_of_is_integral H) (map (quotient.mk (I.comap (algebra_map R S))) P) (map_is_prime_of_surjective quotient.mk_surjective (by simp [hIP])) (le_trans (le_of_eq ((ring_hom.injective_iff_ker_eq_bot _).1 algebra_map_quotient_injective)) bot_le), haveI := Q'_prime, refine ⟨Q'.comap _, le_trans (le_of_eq mk_ker.symm) (ker_le_comap _), ⟨comap_is_prime _ Q', _⟩⟩, rw comap_comap, refine trans _ (trans (congr_arg (comap (quotient.mk (comap (algebra_map R S) I))) hQ') _), { simpa [comap_comap] }, { refine trans (comap_map_of_surjective _ quotient.mk_surjective _) (sup_eq_left.2 _), simpa [← ring_hom.ker_eq_comap_bot] using hIP}, end /-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_maximal_of_is_integral [is_domain S] (H : algebra.is_integral R S) (P : ideal R) [P_max : is_maximal P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_maximal Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q, ⟨Q_prime, hQ⟩⟩ := exists_ideal_over_prime_of_is_integral' H P hP, haveI : Q.is_prime := Q_prime, exact ⟨Q, is_maximal_of_is_integral_of_is_maximal_comap H _ (hQ.symm ▸ P_max), hQ⟩, end end is_domain end ideal
2eae61499a999cdde780e587c411b914f6f14545
c777c32c8e484e195053731103c5e52af26a25d1
/src/category_theory/extensive.lean
6623631672aedefd34436b218e0ca1f80f1127bc
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
25,219
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import category_theory.limits.shapes.comm_sq import category_theory.limits.shapes.strict_initial import category_theory.limits.shapes.types import topology.category.Top.limits.pullbacks import category_theory.limits.functor_category /-! # Extensive categories ## Main definitions - `category_theory.is_van_kampen_colimit`: A (colimit) cocone over a diagram `F : J ⥤ C` is van Kampen if for every cocone `c'` over the pullback of the diagram `F' : J ⥤ C'`, `c'` is colimiting iff `c'` is the pullback of `c`. - `category_theory.finitary_extensive`: A category is (finitary) extensive if it has finite coproducts, and binary coproducts are van Kampen. ## Main Results - `category_theory.has_strict_initial_objects_of_finitary_extensive`: The initial object in extensive categories is strict. - `category_theory.finitary_extensive.mono_inr_of_is_colimit`: Coproduct injections are monic in extensive categories. - `category_theory.binary_cofan.is_pullback_initial_to_of_is_van_kampen`: In extensive categories, sums are disjoint, i.e. the pullback of `X ⟶ X ⨿ Y` and `Y ⟶ X ⨿ Y` is the initial object. - `category_theory.types.finitary_extensive`: The category of types is extensive. ## TODO Show that the following are finitary extensive: - the categories of sheaves over a site - `Scheme` - `AffineScheme` (`CommRingᵒᵖ`) ## References - https://ncatlab.org/nlab/show/extensive+category - [Carboni et al, Introduction to extensive and distributive categories][CARBONI1993145] -/ open category_theory.limits namespace category_theory universes v' u' v u variables {J : Type v'} [category.{u'} J] {C : Type u} [category.{v} C] /-- A natural transformation is equifibered if every commutative square of the following form is a pullback. ``` F(X) → F(Y) ↓ ↓ G(X) → G(Y) ``` -/ def nat_trans.equifibered {F G : J ⥤ C} (α : F ⟶ G) : Prop := ∀ ⦃i j : J⦄ (f : i ⟶ j), is_pullback (F.map f) (α.app i) (α.app j) (G.map f) lemma nat_trans.equifibered_of_is_iso {F G : J ⥤ C} (α : F ⟶ G) [is_iso α] : α.equifibered := λ _ _ f, is_pullback.of_vert_is_iso ⟨nat_trans.naturality _ f⟩ lemma nat_trans.equifibered.comp {F G H : J ⥤ C} {α : F ⟶ G} {β : G ⟶ H} (hα : α.equifibered) (hβ : β.equifibered) : (α ≫ β).equifibered := λ i j f, (hα f).paste_vert (hβ f) /-- A (colimit) cocone over a diagram `F : J ⥤ C` is universal if it is stable under pullbacks. -/ def is_universal_colimit {F : J ⥤ C} (c : cocone F) : Prop := ∀ ⦃F' : J ⥤ C⦄ (c' : cocone F') (α : F' ⟶ F) (f : c'.X ⟶ c.X) (h : α ≫ c.ι = c'.ι ≫ (functor.const J).map f) (hα : α.equifibered), (∀ j : J, is_pullback (c'.ι.app j) (α.app j) f (c.ι.app j)) → nonempty (is_colimit c') /-- A (colimit) cocone over a diagram `F : J ⥤ C` is van Kampen if for every cocone `c'` over the pullback of the diagram `F' : J ⥤ C'`, `c'` is colimiting iff `c'` is the pullback of `c`. TODO: Show that this is iff the functor `C ⥤ Catᵒᵖ` sending `x` to `C/x` preserves it. TODO: Show that this is iff the inclusion functor `C ⥤ Span(C)` preserves it. -/ def is_van_kampen_colimit {F : J ⥤ C} (c : cocone F) : Prop := ∀ ⦃F' : J ⥤ C⦄ (c' : cocone F') (α : F' ⟶ F) (f : c'.X ⟶ c.X) (h : α ≫ c.ι = c'.ι ≫ (functor.const J).map f) (hα : α.equifibered), nonempty (is_colimit c') ↔ ∀ j : J, is_pullback (c'.ι.app j) (α.app j) f (c.ι.app j) lemma is_van_kampen_colimit.is_universal {F : J ⥤ C} {c : cocone F} (H : is_van_kampen_colimit c) : is_universal_colimit c := λ _ c' α f h hα, (H c' α f h hα).mpr /-- A van Kampen colimit is a colimit. -/ noncomputable def is_van_kampen_colimit.is_colimit {F : J ⥤ C} {c : cocone F} (h : is_van_kampen_colimit c) : is_colimit c := begin refine ((h c (𝟙 F) (𝟙 c.X : _) (by rw [functor.map_id, category.comp_id, category.id_comp]) (nat_trans.equifibered_of_is_iso _)).mpr $ λ j, _).some, haveI : is_iso (𝟙 c.X) := infer_instance, exact is_pullback.of_vert_is_iso ⟨by erw [nat_trans.id_app, category.comp_id, category.id_comp]⟩, end lemma is_initial.is_van_kampen_colimit [has_strict_initial_objects C] {X : C} (h : is_initial X) : is_van_kampen_colimit (as_empty_cocone X) := begin intros F' c' α f hf hα, have : F' = functor.empty C := by apply functor.hext; rintro ⟨⟨⟩⟩, subst this, haveI := h.is_iso_to f, refine ⟨by rintro _ ⟨⟨⟩⟩, λ _, ⟨is_colimit.of_iso_colimit h (cocones.ext (as_iso f).symm $ by rintro ⟨⟨⟩⟩)⟩⟩ end section extensive variables {X Y : C} /-- A category is (finitary) extensive if it has finite coproducts, and binary coproducts are van Kampen. TODO: Show that this is iff all finite coproducts are van Kampen. -/ class finitary_extensive (C : Type u) [category.{v} C] : Prop := [has_finite_coproducts : has_finite_coproducts C] (van_kampen' : ∀ {X Y : C} (c : binary_cofan X Y), is_colimit c → is_van_kampen_colimit c) attribute [priority 100, instance] finitary_extensive.has_finite_coproducts lemma finitary_extensive.van_kampen [finitary_extensive C] {F : discrete walking_pair ⥤ C} (c : cocone F) (hc : is_colimit c) : is_van_kampen_colimit c := begin let X := F.obj ⟨walking_pair.left⟩, let Y := F.obj ⟨walking_pair.right⟩, have : F = pair X Y, { apply functor.hext, { rintros ⟨⟨⟩⟩; refl }, { rintros ⟨⟨⟩⟩ ⟨j⟩ ⟨⟨rfl : _ = j⟩⟩; simpa } }, clear_value X Y, subst this, exact finitary_extensive.van_kampen' c hc end lemma map_pair_equifibered {F F' : discrete walking_pair ⥤ C} (α : F ⟶ F') : α.equifibered := begin rintros ⟨⟨⟩⟩ ⟨j⟩ ⟨⟨rfl : _ = j⟩⟩, all_goals { dsimp, simp only [discrete.functor_map_id], exact is_pullback.of_horiz_is_iso ⟨by simp only [category.comp_id, category.id_comp]⟩ } end lemma binary_cofan.is_van_kampen_iff (c : binary_cofan X Y) : is_van_kampen_colimit c ↔ ∀ {X' Y' : C} (c' : binary_cofan X' Y') (αX : X' ⟶ X) (αY : Y' ⟶ Y) (f : c'.X ⟶ c.X) (hαX : αX ≫ c.inl = c'.inl ≫ f) (hαY : αY ≫ c.inr = c'.inr ≫ f), nonempty (is_colimit c') ↔ is_pullback c'.inl αX f c.inl ∧ is_pullback c'.inr αY f c.inr := begin split, { introv H hαX hαY, rw H c' (map_pair αX αY) f (by ext ⟨⟨⟩⟩; dsimp; assumption) (map_pair_equifibered _), split, { intro H, exact ⟨H _, H _⟩ }, { rintros H ⟨⟨⟩⟩, exacts [H.1, H.2] } }, { introv H F' hα h, let X' := F'.obj ⟨walking_pair.left⟩, let Y' := F'.obj ⟨walking_pair.right⟩, have : F' = pair X' Y', { apply functor.hext, { rintros ⟨⟨⟩⟩; refl }, { rintros ⟨⟨⟩⟩ ⟨j⟩ ⟨⟨rfl : _ = j⟩⟩; simpa } }, clear_value X' Y', subst this, change binary_cofan X' Y' at c', rw H c' _ _ _ (nat_trans.congr_app hα ⟨walking_pair.left⟩) (nat_trans.congr_app hα ⟨walking_pair.right⟩), split, { rintros H ⟨⟨⟩⟩, exacts [H.1, H.2] }, { intro H, exact ⟨H _, H _⟩ } } end lemma binary_cofan.is_van_kampen_mk {X Y : C} (c : binary_cofan X Y) (cofans : ∀ (X Y : C), binary_cofan X Y) (colimits : ∀ X Y, is_colimit (cofans X Y)) (cones : ∀ {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z), pullback_cone f g) (limits : ∀ {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z), is_limit (cones f g)) (h₁ : ∀ {X' Y' : C} (αX : X' ⟶ X) (αY : Y' ⟶ Y) (f : (cofans X' Y').X ⟶ c.X) (hαX : αX ≫ c.inl = (cofans X' Y').inl ≫ f) (hαY : αY ≫ c.inr = (cofans X' Y').inr ≫ f), is_pullback (cofans X' Y').inl αX f c.inl ∧ is_pullback (cofans X' Y').inr αY f c.inr) (h₂ : ∀ {Z : C} (f : Z ⟶ c.X), is_colimit (binary_cofan.mk (cones f c.inl).fst (cones f c.inr).fst)) : is_van_kampen_colimit c := begin rw binary_cofan.is_van_kampen_iff, introv hX hY, split, { rintros ⟨h⟩, let e := h.cocone_point_unique_up_to_iso (colimits _ _), obtain ⟨hl, hr⟩ := h₁ αX αY (e.inv ≫ f) (by simp [hX]) (by simp [hY]), split, { rw [← category.id_comp αX, ← iso.hom_inv_id_assoc e f], have : c'.inl ≫ e.hom = 𝟙 X' ≫ (cofans X' Y').inl := by { dsimp, simp }, haveI : is_iso (𝟙 X') := infer_instance, exact (is_pullback.of_vert_is_iso ⟨this⟩).paste_vert hl }, { rw [← category.id_comp αY, ← iso.hom_inv_id_assoc e f], have : c'.inr ≫ e.hom = 𝟙 Y' ≫ (cofans X' Y').inr := by { dsimp, simp }, haveI : is_iso (𝟙 Y') := infer_instance, exact (is_pullback.of_vert_is_iso ⟨this⟩).paste_vert hr } }, { rintro ⟨H₁, H₂⟩, refine ⟨is_colimit.of_iso_colimit _ $ (iso_binary_cofan_mk _).symm⟩, let e₁ : X' ≅ _ := H₁.is_limit.cone_point_unique_up_to_iso (limits _ _), let e₂ : Y' ≅ _ := H₂.is_limit.cone_point_unique_up_to_iso (limits _ _), have he₁ : c'.inl = e₁.hom ≫ (cones f c.inl).fst := by simp, have he₂ : c'.inr = e₂.hom ≫ (cones f c.inr).fst := by simp, rw [he₁, he₂], apply binary_cofan.is_colimit_comp_right_iso (binary_cofan.mk _ _), apply binary_cofan.is_colimit_comp_left_iso (binary_cofan.mk _ _), exact h₂ f } end . lemma binary_cofan.mono_inr_of_is_van_kampen [has_initial C] {X Y : C} {c : binary_cofan X Y} (h : is_van_kampen_colimit c) : mono c.inr := begin refine pullback_cone.mono_of_is_limit_mk_id_id _ (is_pullback.is_limit _), refine (h (binary_cofan.mk (initial.to Y) (𝟙 Y)) (map_pair (initial.to X) (𝟙 Y)) c.inr _ (map_pair_equifibered _)).mp ⟨_⟩ ⟨walking_pair.right⟩, { ext ⟨⟨⟩⟩; dsimp; simp }, { exact ((binary_cofan.is_colimit_iff_is_iso_inr initial_is_initial _).mpr (by { dsimp, apply_instance })).some } end lemma finitary_extensive.mono_inr_of_is_colimit [finitary_extensive C] {c : binary_cofan X Y} (hc : is_colimit c) : mono c.inr := binary_cofan.mono_inr_of_is_van_kampen (finitary_extensive.van_kampen c hc) lemma finitary_extensive.mono_inl_of_is_colimit [finitary_extensive C] {c : binary_cofan X Y} (hc : is_colimit c) : mono c.inl := finitary_extensive.mono_inr_of_is_colimit (binary_cofan.is_colimit_flip hc) instance [finitary_extensive C] (X Y : C) : mono (coprod.inl : X ⟶ X ⨿ Y) := (finitary_extensive.mono_inl_of_is_colimit (coprod_is_coprod X Y) : _) instance [finitary_extensive C] (X Y : C) : mono (coprod.inr : Y ⟶ X ⨿ Y) := (finitary_extensive.mono_inr_of_is_colimit (coprod_is_coprod X Y) : _) lemma binary_cofan.is_pullback_initial_to_of_is_van_kampen [has_initial C] {c : binary_cofan X Y} (h : is_van_kampen_colimit c) : is_pullback (initial.to _) (initial.to _) c.inl c.inr := begin refine ((h (binary_cofan.mk (initial.to Y) (𝟙 Y)) (map_pair (initial.to X) (𝟙 Y)) c.inr _ (map_pair_equifibered _)).mp ⟨_⟩ ⟨walking_pair.left⟩).flip, { ext ⟨⟨⟩⟩; dsimp; simp }, { exact ((binary_cofan.is_colimit_iff_is_iso_inr initial_is_initial _).mpr (by { dsimp, apply_instance })).some } end lemma finitary_extensive.is_pullback_initial_to_binary_cofan [finitary_extensive C] {c : binary_cofan X Y} (hc : is_colimit c) : is_pullback (initial.to _) (initial.to _) c.inl c.inr := binary_cofan.is_pullback_initial_to_of_is_van_kampen (finitary_extensive.van_kampen c hc) lemma has_strict_initial_of_is_universal [has_initial C] (H : is_universal_colimit (binary_cofan.mk (𝟙 (⊥_ C)) (𝟙 (⊥_ C)))) : has_strict_initial_objects C := has_strict_initial_objects_of_initial_is_strict begin intros A f, suffices : is_colimit (binary_cofan.mk (𝟙 A) (𝟙 A)), { obtain ⟨l, h₁, h₂⟩ := limits.binary_cofan.is_colimit.desc' this (f ≫ initial.to A) (𝟙 A), rcases (category.id_comp _).symm.trans h₂ with rfl, exact ⟨⟨_, ((category.id_comp _).symm.trans h₁).symm, initial_is_initial.hom_ext _ _⟩⟩ }, refine (H (binary_cofan.mk (𝟙 _) (𝟙 _)) (map_pair f f) f (by ext ⟨⟨⟩⟩; dsimp; simp) (map_pair_equifibered _) _).some, rintro ⟨⟨⟩⟩; dsimp; exact is_pullback.of_horiz_is_iso ⟨(category.id_comp _).trans (category.comp_id _).symm⟩ end @[priority 100] instance has_strict_initial_objects_of_finitary_extensive [finitary_extensive C] : has_strict_initial_objects C := has_strict_initial_of_is_universal (finitary_extensive.van_kampen _ ((binary_cofan.is_colimit_iff_is_iso_inr initial_is_initial _).mpr (by { dsimp, apply_instance })).some).is_universal lemma finitary_extensive_iff_of_is_terminal (C : Type u) [category.{v} C] [has_finite_coproducts C] (T : C) (HT : is_terminal T) (c₀ : binary_cofan T T) (hc₀ : is_colimit c₀) : finitary_extensive C ↔ is_van_kampen_colimit c₀ := begin refine ⟨λ H, H.2 c₀ hc₀, λ H, _⟩, constructor, simp_rw binary_cofan.is_van_kampen_iff at H ⊢, intros X Y c hc X' Y' c' αX αY f hX hY, obtain ⟨d, hd, hd'⟩ := limits.binary_cofan.is_colimit.desc' hc (HT.from _ ≫ c₀.inl) (HT.from _ ≫ c₀.inr), rw H c' (αX ≫ HT.from _) (αY ≫ HT.from _) (f ≫ d) (by rw [← reassoc_of hX, hd, category.assoc]) (by rw [← reassoc_of hY, hd', category.assoc]), obtain ⟨hl, hr⟩ := (H c (HT.from _) (HT.from _) d hd.symm hd'.symm).mp ⟨hc⟩, rw [hl.paste_vert_iff hX.symm, hr.paste_vert_iff hY.symm] end instance types.finitary_extensive : finitary_extensive (Type u) := begin rw [finitary_extensive_iff_of_is_terminal (Type u) punit types.is_terminal_punit _ (types.binary_coproduct_colimit _ _)], apply binary_cofan.is_van_kampen_mk _ _ (λ X Y, types.binary_coproduct_colimit X Y) _ (λ X Y Z f g, (limits.types.pullback_limit_cone f g).2), { intros, split, { refine ⟨⟨hαX.symm⟩, ⟨pullback_cone.is_limit_aux' _ _⟩⟩, intro s, have : ∀ x, ∃! y, s.fst x = sum.inl y, { intro x, cases h : s.fst x, { simp_rw sum.inl_injective.eq_iff, exact exists_unique_eq' }, { apply_fun f at h, cases ((congr_fun s.condition x).symm.trans h).trans (congr_fun hαY val : _).symm } }, delta exists_unique at this, choose l hl hl', exact ⟨l, (funext hl).symm, types.is_terminal_punit.hom_ext _ _, λ l' h₁ h₂, funext $ λ x, hl' x (l' x) (congr_fun h₁ x).symm⟩ }, { refine ⟨⟨hαY.symm⟩, ⟨pullback_cone.is_limit_aux' _ _⟩⟩, intro s, dsimp, have : ∀ x, ∃! y, s.fst x = sum.inr y, { intro x, cases h : s.fst x, { apply_fun f at h, cases ((congr_fun s.condition x).symm.trans h).trans (congr_fun hαX val : _).symm }, { simp_rw sum.inr_injective.eq_iff, exact exists_unique_eq' } }, delta exists_unique at this, choose l hl hl', exact ⟨l, (funext hl).symm, types.is_terminal_punit.hom_ext _ _, λ l' h₁ h₂, funext $ λ x, hl' x (l' x) (congr_fun h₁ x).symm⟩ } }, { intros Z f, dsimp [limits.types.binary_coproduct_cocone], delta types.pullback_obj, have : ∀ x, f x = sum.inl punit.star ∨ f x = sum.inr punit.star, { intro x, rcases f x with (⟨⟨⟩⟩|⟨⟨⟩⟩), exacts [or.inl rfl, or.inr rfl] }, let eX : {p : Z × punit // f p.fst = sum.inl p.snd} ≃ {x : Z // f x = sum.inl punit.star } := ⟨λ p, ⟨p.1.1, by convert p.2⟩, λ x, ⟨⟨_, _⟩, x.2⟩, λ _, by ext; refl, λ _, by ext; refl⟩, let eY : {p : Z × punit // f p.fst = sum.inr p.snd} ≃ {x : Z // f x = sum.inr punit.star } := ⟨λ p, ⟨p.1.1, p.2.trans (congr_arg sum.inr $ subsingleton.elim _ _)⟩, λ x, ⟨⟨_, _⟩, x.2⟩, λ _, by ext; refl, λ _, by ext; refl⟩, fapply binary_cofan.is_colimit_mk, { exact λ s x, dite _ (λ h, s.inl $ eX.symm ⟨x, h⟩) (λ h, s.inr $ eY.symm ⟨x, (this x).resolve_left h⟩) }, { intro s, ext ⟨⟨x, ⟨⟩⟩, _⟩, dsimp, split_ifs; refl }, { intro s, ext ⟨⟨x, ⟨⟩⟩, hx⟩, dsimp, split_ifs, { cases h.symm.trans hx }, { refl } }, { intros s m e₁ e₂, ext x, split_ifs, { rw ← e₁, refl }, { rw ← e₂, refl } } } end section Top /-- (Implementation) An auxiliary lemma for the proof that `Top` is finitary extensive. -/ def finitary_extensive_Top_aux (Z : Top.{u}) (f : Z ⟶ Top.of (punit.{u+1} ⊕ punit.{u+1})) : is_colimit (binary_cofan.mk (Top.pullback_fst f (Top.binary_cofan (Top.of punit) (Top.of punit)).inl) (Top.pullback_fst f (Top.binary_cofan (Top.of punit) (Top.of punit)).inr)) := begin have : ∀ x, f x = sum.inl punit.star ∨ f x = sum.inr punit.star, { intro x, rcases f x with (⟨⟨⟩⟩|⟨⟨⟩⟩), exacts [or.inl rfl, or.inr rfl] }, let eX : {p : Z × punit // f p.fst = sum.inl p.snd} ≃ { x : Z // f x = sum.inl punit.star } := ⟨λ p, ⟨p.1.1, p.2.trans (congr_arg sum.inl $ subsingleton.elim _ _)⟩, λ x, ⟨⟨_, _⟩, x.2⟩, λ _, by ext; refl, λ _, by ext; refl⟩, let eY : {p : Z × punit // f p.fst = sum.inr p.snd} ≃ { x : Z // f x = sum.inr punit.star } := ⟨λ p, ⟨p.1.1, p.2.trans (congr_arg sum.inr $ subsingleton.elim _ _)⟩, λ x, ⟨⟨_, _⟩, x.2⟩, λ _, by ext; refl, λ _, by ext; refl⟩, fapply binary_cofan.is_colimit_mk, { refine λ s, ⟨λ x, dite _ (λ h, s.inl $ eX.symm ⟨x, h⟩) (λ h, s.inr $ eY.symm ⟨x, (this x).resolve_left h⟩), _⟩, rw continuous_iff_continuous_at, intro x, by_cases f x = sum.inl punit.star, { revert h x, apply (is_open.continuous_on_iff _).mp, { rw continuous_on_iff_continuous_restrict, convert_to continuous (λ x : {x|f x = sum.inl punit.star}, s.inl ⟨(x, punit.star), x.2⟩), { ext ⟨x, hx⟩, exact dif_pos hx }, continuity }, { convert f.2.1 _ (open_embedding_inl).open_range, ext x, exact ⟨λ h, ⟨_, h.symm⟩, λ ⟨e, h⟩, h.symm.trans (congr_arg sum.inl $ subsingleton.elim _ _)⟩ } }, { revert h x, apply (is_open.continuous_on_iff _).mp, { rw continuous_on_iff_continuous_restrict, convert_to continuous (λ x : {x|f x ≠ sum.inl punit.star}, s.inr ⟨(x, punit.star), (this _).resolve_left x.2⟩), { ext ⟨x, hx⟩, exact dif_neg hx }, continuity }, { convert f.2.1 _ (open_embedding_inr).open_range, ext x, change f x ≠ sum.inl punit.star ↔ f x ∈ set.range sum.inr, transitivity f x = sum.inr punit.star, { rcases f x with (⟨⟨⟩⟩|⟨⟨⟩⟩); simp only [iff_self, eq_self_iff_true, not_true, ne.def, not_false_iff] }, { exact ⟨λ h, ⟨_, h.symm⟩, λ ⟨e, h⟩, h.symm.trans (congr_arg sum.inr $ subsingleton.elim _ _)⟩ } } } }, { intro s, ext ⟨⟨x, ⟨⟩⟩, _⟩, change dite _ _ _ = _, split_ifs; refl }, { intro s, ext ⟨⟨x, ⟨⟩⟩, hx⟩, change dite _ _ _ = _, split_ifs, { cases h.symm.trans hx }, { refl } }, { intros s m e₁ e₂, ext x, change m x = dite _ _ _, split_ifs, { rw ← e₁, refl }, { rw ← e₂, refl } } end instance : finitary_extensive Top.{u} := begin rw [finitary_extensive_iff_of_is_terminal Top.{u} _ Top.is_terminal_punit _ (Top.binary_cofan_is_colimit _ _)], apply binary_cofan.is_van_kampen_mk _ _ (λ X Y, Top.binary_cofan_is_colimit X Y) _ (λ X Y Z f g, Top.pullback_cone_is_limit f g), { intros, split, { refine ⟨⟨hαX.symm⟩, ⟨pullback_cone.is_limit_aux' _ _⟩⟩, intro s, have : ∀ x, ∃! y, s.fst x = sum.inl y, { intro x, cases h : s.fst x, { simp_rw sum.inl_injective.eq_iff, exact exists_unique_eq' }, { apply_fun f at h, cases ((concrete_category.congr_hom s.condition x).symm.trans h).trans (concrete_category.congr_hom hαY val : _).symm } }, delta exists_unique at this, choose l hl hl', refine ⟨⟨l, _⟩, continuous_map.ext (λ a, (hl a).symm), Top.is_terminal_punit.hom_ext _ _, λ l' h₁ h₂, continuous_map.ext $ λ x, hl' x (l' x) (concrete_category.congr_hom h₁ x).symm⟩, apply embedding_inl.to_inducing.continuous_iff.mpr, convert s.fst.2 using 1, exact (funext hl).symm }, { refine ⟨⟨hαY.symm⟩, ⟨pullback_cone.is_limit_aux' _ _⟩⟩, intro s, dsimp, have : ∀ x, ∃! y, s.fst x = sum.inr y, { intro x, cases h : s.fst x, { apply_fun f at h, cases ((concrete_category.congr_hom s.condition x).symm.trans h).trans (concrete_category.congr_hom hαX val : _).symm }, { simp_rw sum.inr_injective.eq_iff, exact exists_unique_eq' } }, delta exists_unique at this, choose l hl hl', refine ⟨⟨l, _⟩, continuous_map.ext (λ a, (hl a).symm), Top.is_terminal_punit.hom_ext _ _, λ l' h₁ h₂, continuous_map.ext $ λ x, hl' x (l' x) (concrete_category.congr_hom h₁ x).symm⟩, apply embedding_inr.to_inducing.continuous_iff.mpr, convert s.fst.2 using 1, exact (funext hl).symm } }, { intros Z f, exact finitary_extensive_Top_aux Z f } end end Top section functor universes v'' u'' variables {D : Type u''} [category.{v''} D] lemma nat_trans.equifibered.whisker_right {F G : J ⥤ C} {α : F ⟶ G} (hα : α.equifibered) (H : C ⥤ D) [preserves_limits_of_shape walking_cospan H] : (whisker_right α H).equifibered := λ i j f, (hα f).map H lemma is_van_kampen_colimit.of_iso {F : J ⥤ C} {c c' : cocone F} (H : is_van_kampen_colimit c) (e : c ≅ c') : is_van_kampen_colimit c' := begin intros F' c'' α f h hα, have : c'.ι ≫ (functor.const J).map e.inv.hom = c.ι, { ext j, exact e.inv.2 j }, rw H c'' α (f ≫ e.inv.1) (by rw [functor.map_comp, ← reassoc_of h, this]) hα, apply forall_congr, intro j, conv_lhs { rw [← category.comp_id (α.app j)] }, haveI : is_iso e.inv.hom := functor.map_is_iso (cocones.forget _) e.inv, exact (is_pullback.of_vert_is_iso ⟨by simp⟩).paste_vert_iff (nat_trans.congr_app h j).symm end lemma is_van_kampen_colimit.of_map {D : Type*} [category D] (G : C ⥤ D) {F : J ⥤ C} {c : cocone F} [preserves_limits_of_shape walking_cospan G] [reflects_limits_of_shape walking_cospan G] [preserves_colimits_of_shape J G] [reflects_colimits_of_shape J G] (H : is_van_kampen_colimit (G.map_cocone c)) : is_van_kampen_colimit c := begin intros F' c' α f h hα, refine (iff.trans _ (H (G.map_cocone c') (whisker_right α G) (G.map f) (by { ext j, simpa using G.congr_map (nat_trans.congr_app h j) }) (hα.whisker_right G))).trans (forall_congr $ λ j, _), { exact ⟨λ h, ⟨is_colimit_of_preserves G h.some⟩, λ h, ⟨is_colimit_of_reflects G h.some⟩⟩ }, { exact is_pullback.map_iff G (nat_trans.congr_app h.symm j) } end lemma is_van_kampen_colimit_of_evaluation [has_pullbacks D] [has_colimits_of_shape J D] (F : J ⥤ C ⥤ D) (c : cocone F) (hc : ∀ x : C, is_van_kampen_colimit (((evaluation C D).obj x).map_cocone c)) : is_van_kampen_colimit c := begin intros F' c' α f e hα, have := λ x, hc x (((evaluation C D).obj x).map_cocone c') (whisker_right α _) (((evaluation C D).obj x).map f) (by { ext y, dsimp, exact nat_trans.congr_app (nat_trans.congr_app e y) x }) (hα.whisker_right _), split, { rintros ⟨hc'⟩ j, refine ⟨⟨(nat_trans.congr_app e j).symm⟩, ⟨evaluation_jointly_reflects_limits _ _⟩⟩, refine λ x, (is_limit_map_cone_pullback_cone_equiv _ _).symm _, exact ((this x).mp ⟨preserves_colimit.preserves hc'⟩ _).is_limit }, { exact λ H, ⟨evaluation_jointly_reflects_colimits _ (λ x, ((this x).mpr (λ j, (H j).map ((evaluation C D).obj x))).some)⟩ } end instance [has_pullbacks C] [finitary_extensive C] : finitary_extensive (D ⥤ C) := begin haveI : has_finite_coproducts (D ⥤ C) := ⟨λ n, limits.functor_category_has_colimits_of_shape⟩, exact ⟨λ X Y c hc, is_van_kampen_colimit_of_evaluation _ c (λ x, finitary_extensive.van_kampen _ $ preserves_colimit.preserves hc)⟩ end lemma finitary_extensive_of_preserves_and_reflects (F : C ⥤ D) [finitary_extensive D] [has_finite_coproducts C] [preserves_limits_of_shape walking_cospan F] [reflects_limits_of_shape walking_cospan F] [preserves_colimits_of_shape (discrete walking_pair) F] [reflects_colimits_of_shape (discrete walking_pair) F] : finitary_extensive C := ⟨λ X Y c hc, (finitary_extensive.van_kampen _ (is_colimit_of_preserves F hc)).of_map F⟩ lemma finitary_extensive_of_preserves_and_reflects_isomorphism (F : C ⥤ D) [finitary_extensive D] [has_finite_coproducts C] [has_pullbacks C] [preserves_limits_of_shape walking_cospan F] [preserves_colimits_of_shape (discrete walking_pair) F] [reflects_isomorphisms F] : finitary_extensive C := begin haveI : reflects_limits_of_shape walking_cospan F := reflects_limits_of_shape_of_reflects_isomorphisms, haveI : reflects_colimits_of_shape (discrete walking_pair) F := reflects_colimits_of_shape_of_reflects_isomorphisms, exact finitary_extensive_of_preserves_and_reflects F, end end functor end extensive end category_theory
9bd4f5ebb7a33644c63fd881e8e903e3eeb9e4b8
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_1081.lean
ed10de77a68d8fbf7f537dfce5a0e7cebc625050
[]
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
303
lean
import data.real.basic variables a b c : ℝ -- BEGIN #check (le_refl : ∀ a, a ≤ a) #check (le_trans : a ≤ b → b ≤ c → a ≤ c) #check (lt_of_le_of_lt : a ≤ b → b < c → a < c) #check (lt_of_lt_of_le : a < b → b ≤ c → a < c) #check (lt_trans : a < b → b < c → a < c) -- END
54c040c7e5713412d28c0e1c5ce674f2c824b485
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/finset/gcd.lean
54d6153b600808b1414a58017b6fe63639fc6c79
[ "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
7,008
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson -/ import data.finset.fold import data.multiset.gcd /-! # GCD and LCM operations on finsets ## Main definitions - `finset.gcd` - the greatest common denominator of a `finset` of elements of a `gcd_monoid` - `finset.lcm` - the least common multiple of a `finset` of elements of a `gcd_monoid` ## Implementation notes Many of the proofs use the lemmas `gcd.def` and `lcm.def`, which relate `finset.gcd` and `finset.lcm` to `multiset.gcd` and `multiset.lcm`. TODO: simplify with a tactic and `data.finset.lattice` ## Tags finset, gcd -/ variables {α β γ : Type*} namespace finset open multiset variables [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] /-! ### lcm -/ section lcm /-- Least common multiple of a finite set -/ def lcm (s : finset β) (f : β → α) : α := s.fold gcd_monoid.lcm 1 f variables {s s₁ s₂ : finset β} {f : β → α} lemma lcm_def : s.lcm f = (s.1.map f).lcm := rfl @[simp] lemma lcm_empty : (∅ : finset β).lcm f = 1 := fold_empty @[simp] lemma lcm_dvd_iff {a : α} : s.lcm f ∣ a ↔ (∀b ∈ s, f b ∣ a) := begin apply iff.trans multiset.lcm_dvd, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma lcm_dvd {a : α} : (∀b ∈ s, f b ∣ a) → s.lcm f ∣ a := lcm_dvd_iff.2 lemma dvd_lcm {b : β} (hb : b ∈ s) : f b ∣ s.lcm f := lcm_dvd_iff.1 (dvd_refl _) _ hb @[simp] lemma lcm_insert [decidable_eq β] {b : β} : (insert b s : finset β).lcm f = gcd_monoid.lcm (f b) (s.lcm f) := begin by_cases h : b ∈ s, { rw [insert_eq_of_mem h, (lcm_eq_right_iff (f b) (s.lcm f) (multiset.normalize_lcm (s.1.map f))).2 (dvd_lcm h)] }, apply fold_insert h, end @[simp] lemma lcm_singleton {b : β} : ({b} : finset β).lcm f = normalize (f b) := multiset.lcm_singleton @[simp] lemma normalize_lcm : normalize (s.lcm f) = s.lcm f := by simp [lcm_def] lemma lcm_union [decidable_eq β] : (s₁ ∪ s₂).lcm f = gcd_monoid.lcm (s₁.lcm f) (s₂.lcm f) := finset.induction_on s₁ (by rw [empty_union, lcm_empty, lcm_one_left, normalize_lcm]) $ λ a s has ih, by rw [insert_union, lcm_insert, lcm_insert, ih, lcm_assoc] theorem lcm_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a ∈ s₂, f a = g a) : s₁.lcm f = s₂.lcm g := by { subst hs, exact finset.fold_congr hfg } lemma lcm_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ∣ g b) : s.lcm f ∣ s.lcm g := lcm_dvd (λ b hb, dvd_trans (h b hb) (dvd_lcm hb)) lemma lcm_mono (h : s₁ ⊆ s₂) : s₁.lcm f ∣ s₂.lcm f := lcm_dvd $ assume b hb, dvd_lcm (h hb) end lcm /-! ### gcd -/ section gcd /-- Greatest common divisor of a finite set -/ def gcd (s : finset β) (f : β → α) : α := s.fold gcd_monoid.gcd 0 f variables {s s₁ s₂ : finset β} {f : β → α} lemma gcd_def : s.gcd f = (s.1.map f).gcd := rfl @[simp] lemma gcd_empty : (∅ : finset β).gcd f = 0 := fold_empty lemma dvd_gcd_iff {a : α} : a ∣ s.gcd f ↔ ∀b ∈ s, a ∣ f b := begin apply iff.trans multiset.dvd_gcd, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma gcd_dvd {b : β} (hb : b ∈ s) : s.gcd f ∣ f b := dvd_gcd_iff.1 (dvd_refl _) _ hb lemma dvd_gcd {a : α} : (∀b ∈ s, a ∣ f b) → a ∣ s.gcd f := dvd_gcd_iff.2 @[simp] lemma gcd_insert [decidable_eq β] {b : β} : (insert b s : finset β).gcd f = gcd_monoid.gcd (f b) (s.gcd f) := begin by_cases h : b ∈ s, { rw [insert_eq_of_mem h, (gcd_eq_right_iff (f b) (s.gcd f) (multiset.normalize_gcd (s.1.map f))).2 (gcd_dvd h)] ,}, apply fold_insert h, end @[simp] lemma gcd_singleton {b : β} : ({b} : finset β).gcd f = normalize (f b) := multiset.gcd_singleton @[simp] lemma normalize_gcd : normalize (s.gcd f) = s.gcd f := by simp [gcd_def] lemma gcd_union [decidable_eq β] : (s₁ ∪ s₂).gcd f = gcd_monoid.gcd (s₁.gcd f) (s₂.gcd f) := finset.induction_on s₁ (by rw [empty_union, gcd_empty, gcd_zero_left, normalize_gcd]) $ λ a s has ih, by rw [insert_union, gcd_insert, gcd_insert, ih, gcd_assoc] theorem gcd_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a ∈ s₂, f a = g a) : s₁.gcd f = s₂.gcd g := by { subst hs, exact finset.fold_congr hfg } lemma gcd_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ∣ g b) : s.gcd f ∣ s.gcd g := dvd_gcd (λ b hb, dvd_trans (gcd_dvd hb) (h b hb)) lemma gcd_mono (h : s₁ ⊆ s₂) : s₂.gcd f ∣ s₁.gcd f := dvd_gcd $ assume b hb, gcd_dvd (h hb) theorem gcd_eq_zero_iff : s.gcd f = 0 ↔ ∀ (x : β), x ∈ s → f x = 0 := begin rw [gcd_def, multiset.gcd_eq_zero_iff], split; intro h, { intros b bs, apply h (f b), simp only [multiset.mem_map, mem_def.1 bs], use b, simp [mem_def.1 bs] }, { intros a as, rw multiset.mem_map at as, rcases as with ⟨b, ⟨bs, rfl⟩⟩, apply h b (mem_def.1 bs) } end lemma gcd_eq_gcd_filter_ne_zero [decidable_pred (λ (x : β), f x = 0)] : s.gcd f = (s.filter (λ x, f x ≠ 0)).gcd f := begin classical, transitivity ((s.filter (λ x, f x = 0)) ∪ (s.filter (λ x, f x ≠ 0))).gcd f, { rw filter_union_filter_neg_eq }, rw gcd_union, transitivity gcd_monoid.gcd (0 : α) _, { refine congr (congr rfl _) rfl, apply s.induction_on, { simp }, intros a s has h, rw filter_insert, split_ifs with h1; simp [h, h1], }, simp [gcd_zero_left, normalize_gcd], end lemma gcd_mul_left {a : α} : s.gcd (λ x, a * f x) = normalize a * s.gcd f := begin classical, apply s.induction_on, { simp }, intros b t hbt h, rw [gcd_insert, gcd_insert, h, ← gcd_mul_left], apply gcd_eq_of_associated_right, apply associated_mul_mul _ (associated.refl _), apply normalize_associated, end lemma gcd_mul_right {a : α} : s.gcd (λ x, f x * a) = s.gcd f * normalize a := begin classical, apply s.induction_on, { simp }, intros b t hbt h, rw [gcd_insert, gcd_insert, h, ← gcd_mul_right], apply gcd_eq_of_associated_right, apply associated_mul_mul (associated.refl _), apply normalize_associated, end end gcd end finset namespace finset section integral_domain variables [nontrivial β] [integral_domain α] [gcd_monoid α] lemma gcd_eq_of_dvd_sub {s : finset β} {f g : β → α} {a : α} (h : ∀ x : β, x ∈ s → a ∣ f x - g x) : gcd_monoid.gcd a (s.gcd f) = gcd_monoid.gcd a (s.gcd g) := begin classical, revert h, apply s.induction_on, { simp }, intros b s bs hi h, rw [gcd_insert, gcd_insert, gcd_comm (f b), ← gcd_assoc, hi (λ x hx, h _ (mem_insert_of_mem hx)), gcd_comm a, gcd_assoc, gcd_comm a (gcd_monoid.gcd _ _), gcd_comm (g b), gcd_assoc _ _ a, gcd_comm _ a], refine congr rfl _, apply gcd_eq_of_dvd_sub_right (h _ (mem_insert_self _ _)), end end integral_domain end finset
c7155c44a6ffae099029ad3364c53c9945540509
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/metric_space/emetric_paracompact.lean
590b98f412cf24d10fb2b2adc960c018c7e288f3
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
8,374
lean
/- Copyright (c) 202 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import topology.metric_space.emetric_space import topology.paracompact import set_theory.ordinal /-! # (Extended) metric spaces are paracompact In this file we provide two instances: * `emetric.paracompact_space`: a `pseudo_emetric_space` is paracompact; formalization is based on [MR0236876]; * `emetric.normal_of_metric`: an `emetric_space` is a normal topological space. ## Tags metric space, paracompact space, normal space -/ variable {α : Type*} open_locale ennreal topological_space open set namespace emetric /-- A `pseudo_emetric_space` is always a paracompact space. Formalization is based on [MR0236876]. -/ @[priority 100] -- See note [lower instance priority] instance [pseudo_emetric_space α] : paracompact_space α := begin classical, /- We start with trivial observations about `1 / 2 ^ k`. Here and below we use `1 / 2 ^ k` in the comments and `2⁻¹ ^ k` in the code. -/ have pow_pos : ∀ k : ℕ, (0 : ℝ≥0∞) < 2⁻¹ ^ k, from λ k, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _, have hpow_le : ∀ {m n : ℕ}, m ≤ n → (2⁻¹ : ℝ≥0∞) ^ n ≤ 2⁻¹ ^ m, from λ m n h, ennreal.pow_le_pow_of_le_one (ennreal.inv_le_one.2 ennreal.one_lt_two.le) h, have h2pow : ∀ n : ℕ, 2 * (2⁻¹ : ℝ≥0∞) ^ (n + 1) = 2⁻¹ ^ n, by { intro n, simp [pow_succ, ← mul_assoc, ennreal.mul_inv_cancel] }, -- Consider an open covering `S : set (set α)` refine ⟨λ ι s ho hcov, _⟩, simp only [Union_eq_univ_iff] at hcov, -- choose a well founded order on `S` letI : linear_order ι := linear_order_of_STO' well_ordering_rel, have wf : well_founded ((<) : ι → ι → Prop) := @is_well_order.wf ι well_ordering_rel _, -- Let `ind x` be the minimal index `s : S` such that `x ∈ s`. set ind : α → ι := λ x, wf.min {i : ι | x ∈ s i} (hcov x), have mem_ind : ∀ x, x ∈ s (ind x), from λ x, wf.min_mem _ (hcov x), have nmem_of_lt_ind : ∀ {x i}, i < (ind x) → x ∉ s i, from λ x i hlt hxi, wf.not_lt_min _ (hcov x) hxi hlt, /- The refinement `D : ℕ → ι → set α` is defined recursively. For each `n` and `i`, `D n i` is the union of balls `ball x (1 / 2 ^ n)` over all points `x` such that * `ind x = i`; * `x` does not belong to any `D m j`, `m < n`; * `ball x (3 / 2 ^ n) ⊆ s i`; We define this sequence using `nat.strong_rec_on'`, then restate it as `Dn` and `memD`. -/ set D : ℕ → ι → set α := λ n, nat.strong_rec_on' n (λ n D' i, ⋃ (x : α) (hxs : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D' m ‹_› j), ball x (2⁻¹ ^ n)), have Dn : ∀ n i, D n i = ⋃ (x : α) (hxs : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D m j), ball x (2⁻¹ ^ n), from λ n s, by { simp only [D], rw nat.strong_rec_on_beta' }, have memD : ∀ {n i y}, y ∈ D n i ↔ ∃ x (hi : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D m j), edist y x < 2⁻¹ ^ n, { intros n i y, rw [Dn n i], simp only [mem_Union, mem_ball] }, -- The sets `D n i` cover the whole space. Indeed, for each `x` we can choose `n` such that -- `ball x (3 / 2 ^ n) ⊆ s (ind x)`, then either `x ∈ D n i`, or `x ∈ D m i` for some `m < n`. have Dcov : ∀ x, ∃ n i, x ∈ D n i, { intro x, obtain ⟨n, hn⟩ : ∃ n : ℕ, ball x (3 * 2⁻¹ ^ n) ⊆ s (ind x), { -- This proof takes 5 lines because we can't import `specific_limits` here rcases is_open_iff.1 (ho $ ind x) x (mem_ind x) with ⟨ε, ε0, hε⟩, have : 0 < ε / 3 := ennreal.div_pos_iff.2 ⟨ε0.lt.ne', ennreal.coe_ne_top⟩, rcases ennreal.exists_inv_two_pow_lt this.ne' with ⟨n, hn⟩, refine ⟨n, subset.trans (ball_subset_ball _) hε⟩, simpa only [div_eq_mul_inv, mul_comm] using (ennreal.mul_lt_of_lt_div hn).le }, by_contra h, push_neg at h, apply h n (ind x), exact memD.2 ⟨x, rfl, hn, λ _ _ _, h _ _, mem_ball_self (pow_pos _)⟩ }, -- Each `D n i` is a union of open balls, hence it is an open set have Dopen : ∀ n i, is_open (D n i), { intros n i, rw Dn, iterate 4 { refine is_open_Union (λ _, _) }, exact is_open_ball }, -- the covering `D n i` is a refinement of the original covering: `D n i ⊆ s i` have HDS : ∀ n i, D n i ⊆ s i, { intros n s x, rw memD, rintro ⟨y, rfl, hsub, -, hyx⟩, refine hsub (lt_of_lt_of_le hyx _), calc 2⁻¹ ^ n = 1 * 2⁻¹ ^ n : (one_mul _).symm ... ≤ 3 * 2⁻¹ ^ n : ennreal.mul_le_mul _ le_rfl, -- TODO: use `norm_num` have : ((1 : ℕ) : ℝ≥0∞) ≤ (3 : ℕ), from ennreal.coe_nat_le_coe_nat.2 (by norm_num1), exact_mod_cast this }, -- Let us show the rest of the properties. Since the definition expects a family indexed -- by a single parameter, we use `ℕ × ι` as the domain. refine ⟨ℕ × ι, λ ni, D ni.1 ni.2, λ _, Dopen _ _, _, _, λ ni, ⟨ni.2, HDS _ _⟩⟩, -- The sets `D n i` cover the whole space as we proved earlier { refine Union_eq_univ_iff.2 (λ x, _), rcases Dcov x with ⟨n, i, h⟩, exact ⟨⟨n, i⟩, h⟩ }, { /- Let us prove that the covering `D n i` is locally finite. Take a point `x` and choose `n`, `i` so that `x ∈ D n i`. Since `D n i` is an open set, we can choose `k` so that `B = ball x (1 / 2 ^ (n + k + 1)) ⊆ D n i`. -/ intro x, rcases Dcov x with ⟨n, i, hn⟩, have : D n i ∈ 𝓝 x, from is_open.mem_nhds (Dopen _ _) hn, rcases (nhds_basis_uniformity uniformity_basis_edist_inv_two_pow).mem_iff.1 this with ⟨k, -, hsub : ball x (2⁻¹ ^ k) ⊆ D n i⟩, set B := ball x (2⁻¹ ^ (n + k + 1)), refine ⟨B, ball_mem_nhds _ (pow_pos _), _⟩, -- The sets `D m i`, `m > n + k`, are disjoint with `B` have Hgt : ∀ (m ≥ n + k + 1) (i : ι), disjoint (D m i) B, { rintros m hm i y ⟨hym, hyx⟩, rcases memD.1 hym with ⟨z, rfl, hzi, H, hz⟩, have : z ∉ ball x (2⁻¹ ^ k), from λ hz, H n (by linarith) i (hsub hz), apply this, calc edist z x ≤ edist y z + edist y x : edist_triangle_left _ _ _ ... < (2⁻¹ ^ m) + (2⁻¹ ^ (n + k + 1)) : ennreal.add_lt_add hz hyx ... ≤ (2⁻¹ ^ (k + 1)) + (2⁻¹ ^ (k + 1)) : add_le_add (hpow_le $ by linarith) (hpow_le $ by linarith) ... = (2⁻¹ ^ k) : by rw [← two_mul, h2pow] }, -- For each `m ≤ n + k` there is at most one `j` such that `D m j ∩ B` is nonempty. have Hle : ∀ m ≤ n + k, set.subsingleton {j | (D m j ∩ B).nonempty}, { rintros m hm j₁ ⟨y, hyD, hyB⟩ j₂ ⟨z, hzD, hzB⟩, by_contra h, wlog h : j₁ < j₂ := ne.lt_or_lt h using [j₁ j₂ y z, j₂ j₁ z y], rcases memD.1 hyD with ⟨y', rfl, hsuby, -, hdisty⟩, rcases memD.1 hzD with ⟨z', rfl, -, -, hdistz⟩, suffices : edist z' y' < 3 * 2⁻¹ ^ m, from nmem_of_lt_ind h (hsuby this), calc edist z' y' ≤ edist z' x + edist x y' : edist_triangle _ _ _ ... ≤ (edist z z' + edist z x) + (edist y x + edist y y') : add_le_add (edist_triangle_left _ _ _) (edist_triangle_left _ _ _) ... < (2⁻¹ ^ m + 2⁻¹ ^ (n + k + 1)) + (2⁻¹ ^ (n + k + 1) + 2⁻¹ ^ m) : by apply_rules [ennreal.add_lt_add] ... = 2 * (2⁻¹ ^ m + 2⁻¹ ^ (n + k + 1)) : by simp only [two_mul, add_comm] ... ≤ 2 * (2⁻¹ ^ m + 2⁻¹ ^ (m + 1)) : ennreal.mul_le_mul le_rfl $ add_le_add le_rfl $ hpow_le (add_le_add hm le_rfl) ... = 3 * 2⁻¹ ^ m : by rw [mul_add, h2pow, bit1, add_mul, one_mul] }, -- Finally, we glue `Hgt` and `Hle` have : (⋃ (m ≤ n + k) (i ∈ {i : ι | (D m i ∩ B).nonempty}), {(m, i)}).finite, from (finite_le_nat _).bUnion (λ i hi, (Hle i hi).finite.bUnion (λ _ _, finite_singleton _)), refine this.subset (λ I hI, _), simp only [mem_Union], refine ⟨I.1, _, I.2, hI, prod.mk.eta.symm⟩, exact not_lt.1 (λ hlt, Hgt I.1 hlt I.2 hI.some_spec) } end @[priority 100] -- see Note [lower instance priority] instance normal_of_emetric [emetric_space α] : normal_space α := normal_of_paracompact_t2 end emetric
2a39dd9a968564026cc4ff8aa0b7d2e4bcccb63e
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/multiset.lean
2977f312deb06686b09f55b4c6577c3e6721cd49
[ "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
134,927
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.equiv.basic data.list.basic data.list.perm data.list.sort data.quot data.string.basic algebra.order_functions algebra.group_power algebra.ordered_group category.traversable.lemmas tactic.interactive category.traversable.instances category.basic open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} open_locale add_monoid /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by induction n; simp [succ_smul, *, nat.succ_mul] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl @[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ @[simp] theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive] def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (add_monoid.smul n m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive] prod_repeat @[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := multiset.induction_on m (by simp) (by simp) @[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := multiset.induction_on m (by simp) (by simp) attribute [to_additive] prod_map_one @[simp, to_additive] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) lemma prod_hom [comm_monoid α] [comm_monoid β] (f : α → β) [is_monoid_hom f] (s : multiset α) : (s.map f).prod = f s.prod := multiset.induction_on s (by simp [is_monoid_hom.map_one f]) (by simp [is_monoid_hom.map_mul f] {contextual := tt}) lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma sum_hom [add_comm_monoid α] [add_comm_monoid β] (f : α → β) [is_add_monoid_hom f] (s : multiset α) : (s.map f).sum = f s.sum := multiset.induction_on s (by simp [is_add_monoid_hom.map_zero f]) (by simp [is_add_monoid_hom.map_add f] {contextual := tt}) attribute [to_additive] multiset.prod_hom lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left' ih) lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by rw sum_cons; exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy))))) /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, -map_const, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _ @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- antidiagonal -/ theorem revzip_powerset_aux {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact perm_map _ powerset_aux_perm_powerset_aux', end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact perm_map _ (powerset_aux_perm p) end /-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem antidiagonal_coe (l : list α) : @antidiagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem antidiagonal_coe' (l : list α) : @antidiagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' /-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s` if and only if `t₁ + t₂ = s`. -/ @[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} : x ∈ antidiagonal s ↔ x.1 + x.2 = s := quotient.induction_on s $ λ l, begin simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], cases x with x₁ x₂, exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩ end @[simp] theorem antidiagonal_map_fst (s : multiset α) : (antidiagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_map_snd (s : multiset α) : (antidiagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0)::0 := rfl @[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a::s) = map (prod.map id (cons a)) (antidiagonal s) + map (prod.map (cons a) id) (antidiagonal s) := quotient.induction_on s $ λ l, begin simp [revzip, reverse_append], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_antidiagonal (s : multiset α) : card (antidiagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← antidiagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] }, end /- powerset_len -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, (perm_length p.symm).trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, (perm_length p).trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact perm_app IH (perm_map _ (IHn p)) }, { simp, apply perm_app_right, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = 0::0 := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a::s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_sublists' _ _)) theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_of_sublist _ h)) /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add, map_zero := countp_zero _ } theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom @[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero {} : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono h lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem injective_map {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ theorem nodup_powerset_len {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.map f = t.map g := have t = s.attach.map (λ x, i x.1 x.2), from (nodup_ext ht (nodup_map (show function.injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy, subtype.eq (i_inj x.1 y.1 x.2 y.2 hxy)) (nodup_attach.2 hs))).2 (λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach]; exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩), calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map] ... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach] ... = t.map g : by rw [this, multiset.map_map]; exact map_congr (λ x _, h _ _) section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 := ⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _, λ h, h.symm ▸ erase_dup_zero⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sup variables [semilattice_sup_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a :: s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup := fold_erase_dup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 (le_refl _) _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) end sup section inf variables [semilattice_inf_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a :: s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf := fold_erase_dup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 (le_refl _) _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) end inf section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] @[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card := quot.induction_on s $ length_merge_sort _ end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp, split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset namespace multiset instance : functor multiset := { map := @map } instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F] variables {α' β' : Type u_1} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.skip { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end instance : monad multiset := { pure := λ α x, x::0, bind := @bind, .. multiset.functor } instance : is_lawful_monad multiset := { bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih, by rw [bind_cons, map_cons, bind_zero, add_zero], pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero], bind_assoc := @bind_assoc } open functor open traversable is_lawful_traversable @[simp] lemma lift_beta {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_beta _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x (by { intro, rw [traverse,quotient.lift_beta,function.comp], simp, congr }) lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [comp_map,map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp 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 /- Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := congr_arg coe $ list.Ico.map_sub _ _ _ h theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 := congr_arg coe $ list.Ico.bag_inter_consecutive n m l @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := congr_arg coe $ list.Ico.filter_le_of_le_bot hln lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ := congr_arg coe $ list.Ico.filter_le_of_top_le hml lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := congr_arg coe $ list.Ico.filter_le_of_le hnl @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_le n m l end Ico variable (α) def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le (perm_length h) $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } namespace nat /-- The antidiagonal of a natural number `n` is the multiset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) := list.nat.antidiagonal n /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by rw [antidiagonal, coe_card, list.nat.length_antidiagonal] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := by { rw [antidiagonal, list.nat.antidiagonal_zero], refl } /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := coe_nodup.2 $ list.nat.nodup_antidiagonal n end nat end multiset
648ac4c5caceba88eeb722809d3fd1a745a39101
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/connected_auto.lean
b94d5e010f1590b80d55884315d76c6df96f0615
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,903
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.shapes.pullbacks import Mathlib.category_theory.limits.shapes.equalizers import Mathlib.category_theory.limits.preserves.basic import Mathlib.category_theory.is_connected import Mathlib.PostPort universes v₁ u_1 u₂ v₂ namespace Mathlib /-! # Connected limits A connected limit is a limit whose shape is a connected category. We give examples of connected categories, and prove that the functor given by `(X × -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X × -)`. -/ namespace category_theory protected instance wide_pullback_shape_connected (J : Type v₁) : is_connected (limits.wide_pullback_shape J) := is_connected.of_induct fun (p : set (limits.wide_pullback_shape J)) (hp : none ∈ p) (t : ∀ {j₁ j₂ : limits.wide_pullback_shape J}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.wide_pullback_shape J) => option.cases_on j hp fun (j : J) => eq.mpr (id (Eq._oldrec (Eq.refl (some j ∈ p)) (propext (t (limits.wide_pullback_shape.hom.term j))))) hp protected instance wide_pushout_shape_connected (J : Type v₁) : is_connected (limits.wide_pushout_shape J) := is_connected.of_induct fun (p : set (limits.wide_pushout_shape J)) (hp : none ∈ p) (t : ∀ {j₁ j₂ : limits.wide_pushout_shape J}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.wide_pushout_shape J) => option.cases_on j hp fun (j : J) => eq.mpr (id (Eq._oldrec (Eq.refl (some j ∈ p)) (Eq.symm (propext (t (limits.wide_pushout_shape.hom.init j)))))) hp protected instance parallel_pair_inhabited : Inhabited limits.walking_parallel_pair := { default := limits.walking_parallel_pair.one } protected instance parallel_pair_connected : is_connected limits.walking_parallel_pair := is_connected.of_induct fun (p : set limits.walking_parallel_pair) (ᾰ : limits.walking_parallel_pair.one ∈ p) (t : ∀ {j₁ j₂ : limits.walking_parallel_pair}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.walking_parallel_pair) => limits.walking_parallel_pair.cases_on j (eq.mpr (id (Eq._oldrec (Eq.refl (limits.walking_parallel_pair.zero ∈ p)) (propext (t limits.walking_parallel_pair_hom.left)))) ᾰ) ᾰ namespace prod_preserves_connected_limits /-- (Impl). The obvious natural transformation from (X × K -) to K. -/ def γ₂ {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {K : J ⥤ C} (X : C) : K ⋙ functor.obj limits.prod.functor X ⟶ K := nat_trans.mk fun (Y : J) => limits.prod.snd /-- (Impl). The obvious natural transformation from (X × K -) to X -/ @[simp] theorem γ₁_app {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {K : J ⥤ C} (X : C) (Y : J) : nat_trans.app (γ₁ X) Y = limits.prod.fst := Eq.refl (nat_trans.app (γ₁ X) Y) /-- (Impl). Given a cone for (X × K -), produce a cone for K using the natural transformation `γ₂` -/ @[simp] theorem forget_cone_π {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {X : C} {K : J ⥤ C} (s : limits.cone (K ⋙ functor.obj limits.prod.functor X)) : limits.cone.π (forget_cone s) = limits.cone.π s ≫ γ₂ X := Eq.refl (limits.cone.π (forget_cone s)) end prod_preserves_connected_limits /-- The functor `(X × -)` preserves any connected limit. Note that this functor does not preserve the two most obvious disconnected limits - that is, `(X × -)` does not preserve products or terminal object, eg `(X ⨯ A) ⨯ (X ⨯ B)` is not isomorphic to `X ⨯ (A ⨯ B)` and `X ⨯ 1` is not isomorphic to `1`. -/ def prod_preserves_connected_limits {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] [is_connected J] (X : C) : limits.preserves_limits_of_shape J (functor.obj limits.prod.functor X) := limits.preserves_limits_of_shape.mk fun (K : J ⥤ C) => limits.preserves_limit.mk fun (c : limits.cone K) (l : limits.is_limit c) => limits.is_limit.mk fun (s : limits.cone (K ⋙ functor.obj limits.prod.functor X)) => limits.prod.lift (nat_trans.app (limits.cone.π s) (classical.arbitrary J) ≫ limits.prod.fst) (limits.is_limit.lift l sorry) end Mathlib
b788c92b161e1f532d4b1971fc67cc6ff67af4f2
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/meta/declaration.lean
83be55f3ca5cb1d0bf850a71bb831a0adacf3af1
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,269
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.expr init.meta.name init.meta.task /- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` constructor are: the definitional height and the flag `self_opt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. For definitions marked as regular, we also have a hint for constraints such as (f a) =?= (f b) if self_opt == true, then checker will first try to solve (a =?= b), only if it fails, it unfolds f. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during type checking. Remark: the reducibility_hints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the elaborator. The reducibility_hints are used by the kernel (and elaborator). Moreover, the reducibility_hints cannot be changed after a declaration is added to the kernel. -/ inductive reducibility_hints | opaque : reducibility_hints | abbrev : reducibility_hints | regular : nat → bool → reducibility_hints /- Reflect a C++ declaration object. The VM replaces it with the C++ implementation. -/ meta inductive declaration /- definition: name, list universe parameters, type, value, is_trusted -/ | defn : name → list name → expr → expr → reducibility_hints → bool → declaration /- theorem: name, list universe parameters, type, value (remark: theorems are always trusted) -/ | thm : name → list name → expr → task expr → declaration /- constant assumption: name, list universe parameters, type, is_trusted -/ | cnst : name → list name → expr → bool → declaration /- axiom : name → list universe parameters, type (remark: axioms are always trusted) -/ | ax : name → list name → expr → declaration open declaration meta def mk_definition (n : name) (ls : list name) (v : expr) (e : expr) : declaration := defn n ls v e (reducibility_hints.regular 1 tt) tt namespace declaration meta def to_name : declaration → name | (defn n _ _ _ _ _) := n | (thm n _ _ _) := n | (cnst n _ _ _) := n | (ax n _ _) := n meta def univ_params : declaration → list name | (defn _ ls _ _ _ _) := ls | (thm _ ls _ _) := ls | (cnst _ ls _ _) := ls | (ax _ ls _) := ls meta def type : declaration → expr | (defn _ _ t _ _ _) := t | (thm _ _ t _) := t | (cnst _ _ t _) := t | (ax _ _ t) := t meta def value : declaration → expr | (defn _ _ _ v _ _) := v | (thm _ _ _ v) := v^.get | _ := default expr meta def value_task : declaration → task expr | (defn _ _ _ v _ _) := task.pure v | (thm _ _ _ v) := v | _ := task.pure (default expr) meta def update_type : declaration → expr → declaration | (defn n ls t v h tr) new_t := defn n ls new_t v h tr | (thm n ls t v) new_t := thm n ls new_t v | (cnst n ls t tr) new_t := cnst n ls new_t tr | (ax n ls t) new_t := ax n ls new_t meta def update_name : declaration → name → declaration | (defn n ls t v h tr) new_n := defn new_n ls t v h tr | (thm n ls t v) new_n := thm new_n ls t v | (cnst n ls t tr) new_n := cnst new_n ls t tr | (ax n ls t) new_n := ax new_n ls t meta def update_value : declaration → expr → declaration | (defn n ls t v h tr) new_v := defn n ls t new_v h tr | (thm n ls t v) new_v := thm n ls t (task.pure new_v) | d new_v := d meta def update_value_task : declaration → task expr → declaration | (defn n ls t v h tr) new_v := defn n ls t new_v^.get h tr | (thm n ls t v) new_v := thm n ls t new_v | d new_v := d meta def map_value : declaration → (expr → expr) → declaration | (defn n ls t v h tr) f := defn n ls t (f v) h tr | (thm n ls t v) f := thm n ls t (task.map f v) | d f := d meta def to_definition : declaration → declaration | (cnst n ls t tr) := defn n ls t (default expr) reducibility_hints.abbrev tr | (ax n ls t) := thm n ls t (task.pure (default expr)) | d := d /- Instantiate a universe polymorphic declaration type with the given universes. -/ meta constant instantiate_type_univ_params : declaration → list level → option expr /- Instantiate a universe polymorphic declaration value with the given universes. -/ meta constant instantiate_value_univ_params : declaration → list level → option expr end declaration
d63124029aad45efa16f3e000f19c3a7de94ebd9
e5169dbb8b1bea3ec2a32737442bc91a4a94b46a
/library/data/tuple.lean
d54ca30d0d78f35736fd805f518355273872fadd
[ "Apache-2.0" ]
permissive
pazthor/lean
733b775e3123f6bbd2c4f7ccb5b560b467b76800
c923120db54276a22a75b12c69765765608a8e76
refs/heads/master
1,610,703,744,289
1,448,419,395,000
1,448,419,703,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,110
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 Tuples are lists of a fixed size. It is implemented as a subtype. -/ import logic data.list data.fin open nat list subtype function algebra definition tuple [reducible] (A : Type) (n : nat) := {l : list A | length l = n} namespace tuple variables {A B C : Type} theorem induction_on [recursor 4] {P : ∀ {n}, tuple A n → Prop} : ∀ {n} (v : tuple A n), (∀ (l : list A) {n : nat} (h : length l = n), P (tag l h)) → P v | n (tag l h) H := @H l n h definition nil : tuple A 0 := tag [] rfl lemma length_succ {n : nat} {l : list A} (a : A) : length l = n → length (a::l) = succ n := λ h, congr_arg succ h definition cons {n : nat} : A → tuple A n → tuple A (succ n) | a (tag v h) := tag (a::v) (length_succ a h) notation a :: b := cons a b protected definition is_inhabited [instance] [h : inhabited A] : ∀ (n : nat), inhabited (tuple A n) | 0 := inhabited.mk nil | (succ n) := inhabited.mk (inhabited.value h :: inhabited.value (is_inhabited n)) protected definition has_decidable_eq [instance] [h : decidable_eq A] : ∀ (n : nat), decidable_eq (tuple A n) := λ n, subtype.has_decidable_eq definition head {n : nat} : tuple A (succ n) → A | (tag [] h) := by contradiction | (tag (a::v) h) := a definition tail {n : nat} : tuple A (succ n) → tuple A n | (tag [] h) := by contradiction | (tag (a::v) h) := tag v (succ.inj h) theorem head_cons {n : nat} (a : A) (v : tuple A n) : head (a :: v) = a := by induction v; reflexivity theorem tail_cons {n : nat} (a : A) (v : tuple A n) : tail (a :: v) = v := by induction v; reflexivity theorem head_lcons {n : nat} (a : A) (l : list A) (h : length (a::l) = succ n) : head (tag (a::l) h) = a := rfl theorem tail_lcons {n : nat} (a : A) (l : list A) (h : length (a::l) = succ n) : tail (tag (a::l) h) = tag l (succ.inj h) := rfl definition last {n : nat} : tuple A (succ n) → A | (tag l h) := list.last l (ne_nil_of_length_eq_succ h) theorem eta : ∀ {n : nat} (v : tuple A (succ n)), head v :: tail v = v | 0 (tag [] h) := by contradiction | 0 (tag (a::l) h) := rfl | (n+1) (tag [] h) := by contradiction | (n+1) (tag (a::l) h) := rfl definition of_list (l : list A) : tuple A (list.length l) := tag l rfl definition to_list {n : nat} : tuple A n → list A | (tag l h) := l theorem to_list_of_list (l : list A) : to_list (of_list l) = l := rfl theorem to_list_nil : to_list nil = ([] : list A) := rfl theorem length_to_list {n : nat} : ∀ (v : tuple A n), list.length (to_list v) = n | (tag l h) := h theorem heq_of_list_eq {n m} : ∀ {v₁ : tuple A n} {v₂ : tuple A m}, to_list v₁ = to_list v₂ → n = m → v₁ == v₂ | (tag l₁ h₁) (tag l₂ h₂) e₁ e₂ := begin clear heq_of_list_eq, subst e₂, subst h₁, unfold to_list at e₁, subst l₁ end theorem list_eq_of_heq {n m} {v₁ : tuple A n} {v₂ : tuple A m} : v₁ == v₂ → n = m → to_list v₁ = to_list v₂ := begin intro h₁ h₂, revert v₁ v₂ h₁, subst n, intro v₁ v₂ h₁, rewrite [heq.to_eq h₁] end theorem of_list_to_list {n : nat} (v : tuple A n) : of_list (to_list v) == v := begin apply heq_of_list_eq, rewrite to_list_of_list, rewrite length_to_list end /- append -/ definition append {n m : nat} : tuple A n → tuple A m → tuple A (n + m) | (tag l₁ h₁) (tag l₂ h₂) := tag (list.append l₁ l₂) (by rewrite [length_append, h₁, h₂]) infix ++ := append open eq.ops lemma push_eq_rec : ∀ {n m : nat} {l : list A} (h₁ : n = m) (h₂ : length l = n), h₁ ▹ (tag l h₂) = tag l (h₁ ▹ h₂) | n n l (eq.refl n) h₂ := rfl theorem append_nil_right {n : nat} (v : tuple A n) : v ++ nil = v := induction_on v (λ l n h, by unfold [tuple.append, tuple.nil]; congruence; apply list.append_nil_right) theorem append_nil_left {n : nat} (v : tuple A n) : !zero_add ▹ (nil ++ v) = v := induction_on v (λ l n h, begin unfold [tuple.append, tuple.nil], rewrite [push_eq_rec] end) theorem append_nil_left_heq {n : nat} (v : tuple A n) : nil ++ v == v := heq_of_eq_rec_left !zero_add (append_nil_left v) theorem append.assoc {n₁ n₂ n₃} : ∀ (v₁ : tuple A n₁) (v₂ : tuple A n₂) (v₃ : tuple A n₃), !add.assoc ▹ ((v₁ ++ v₂) ++ v₃) = v₁ ++ (v₂ ++ v₃) | (tag l₁ h₁) (tag l₂ h₂) (tag l₃ h₃) := begin unfold tuple.append, rewrite push_eq_rec, congruence, apply list.append.assoc end theorem append.assoc_heq {n₁ n₂ n₃} (v₁ : tuple A n₁) (v₂ : tuple A n₂) (v₃ : tuple A n₃) : (v₁ ++ v₂) ++ v₃ == v₁ ++ (v₂ ++ v₃) := heq_of_eq_rec_left !add.assoc (append.assoc v₁ v₂ v₃) /- reverse -/ definition reverse {n : nat} : tuple A n → tuple A n | (tag l h) := tag (list.reverse l) (by rewrite [length_reverse, h]) theorem reverse_reverse {n : nat} (v : tuple A n) : reverse (reverse v) = v := induction_on v (λ l n h, begin unfold reverse, congruence, apply list.reverse_reverse end) theorem tuple0_eq_nil : ∀ (v : tuple A 0), v = nil | (tag [] h) := rfl | (tag (a::l) h) := by contradiction /- mem -/ definition mem {n : nat} (a : A) (v : tuple A n) : Prop := a ∈ elt_of v notation e ∈ s := mem e s notation e ∉ s := ¬ e ∈ s theorem not_mem_nil (a : A) : a ∉ nil := list.not_mem_nil a theorem mem_cons [simp] {n : nat} (a : A) (v : tuple A n) : a ∈ a :: v := induction_on v (λ l n h, !list.mem_cons) theorem mem_cons_of_mem {n : nat} (y : A) {x : A} {v : tuple A n} : x ∈ v → x ∈ y :: v := induction_on v (λ l n h₁ h₂, list.mem_cons_of_mem y h₂) theorem eq_or_mem_of_mem_cons {n : nat} {x y : A} {v : tuple A n} : x ∈ y::v → x = y ∨ x ∈ v := induction_on v (λ l n h₁ h₂, eq_or_mem_of_mem_cons h₂) theorem mem_singleton {n : nat} {x a : A} : x ∈ (a::nil : tuple A 1) → x = a := assume h, list.mem_singleton h /- map -/ definition map {n : nat} (f : A → B) : tuple A n → tuple B n | (tag l h) := tag (list.map f l) (by clear map; substvars; rewrite length_map) theorem map_nil (f : A → B) : map f nil = nil := rfl theorem map_cons {n : nat} (f : A → B) (a : A) (v : tuple A n) : map f (a::v) = f a :: map f v := by induction v; reflexivity theorem map_tag {n : nat} (f : A → B) (l : list A) (h : length l = n) : map f (tag l h) = tag (list.map f l) (by substvars; rewrite length_map) := by reflexivity theorem map_map {n : nat} (g : B → C) (f : A → B) (v : tuple A n) : map g (map f v) = map (g ∘ f) v := begin cases v, rewrite *map_tag, apply subtype.eq, apply list.map_map end theorem map_id {n : nat} (v : tuple A n) : map id v = v := begin induction v, unfold map, congruence, apply list.map_id end theorem mem_map {n : nat} {a : A} {v : tuple A n} (f : A → B) : a ∈ v → f a ∈ map f v := begin induction v, unfold map, apply list.mem_map end theorem exists_of_mem_map {n : nat} {f : A → B} {b : B} {v : tuple A n} : b ∈ map f v → ∃a, a ∈ v ∧ f a = b := begin induction v, unfold map, apply list.exists_of_mem_map end theorem eq_of_map_const {n : nat} {b₁ b₂ : B} {v : tuple A n} : b₁ ∈ map (const A b₂) v → b₁ = b₂ := begin induction v, unfold map, apply list.eq_of_map_const end /- product -/ definition product {n m : nat} : tuple A n → tuple B m → tuple (A × B) (n * m) | (tag l₁ h₁) (tag l₂ h₂) := tag (list.product l₁ l₂) (by rewrite [length_product, h₁, h₂]) theorem nil_product {m : nat} (v : tuple B m) : !zero_mul ▹ product (@nil A) v = nil := begin induction v, unfold [nil, product], rewrite push_eq_rec end theorem nil_product_heq {m : nat} (v : tuple B m) : product (@nil A) v == (@nil (A × B)) := heq_of_eq_rec_left _ (nil_product v) theorem product_nil {n : nat} (v : tuple A n) : product v (@nil B) = nil := begin induction v, unfold [nil, product], congruence, apply list.product_nil end theorem mem_product {n m : nat} {a : A} {b : B} {v₁ : tuple A n} {v₂ : tuple B m} : a ∈ v₁ → b ∈ v₂ → (a, b) ∈ product v₁ v₂ := begin cases v₁, cases v₂, unfold product, apply list.mem_product end theorem mem_of_mem_product_left {n m : nat} {a : A} {b : B} {v₁ : tuple A n} {v₂ : tuple B m} : (a, b) ∈ product v₁ v₂ → a ∈ v₁ := begin cases v₁, cases v₂, unfold product, apply list.mem_of_mem_product_left end theorem mem_of_mem_product_right {n m : nat} {a : A} {b : B} {v₁ : tuple A n} {v₂ : tuple B m} : (a, b) ∈ product v₁ v₂ → b ∈ v₂ := begin cases v₁, cases v₂, unfold product, apply list.mem_of_mem_product_right end /- ith -/ open fin definition ith {n : nat} : tuple A n → fin n → A | (tag l h₁) (mk i h₂) := list.ith l i (by rewrite h₁; exact h₂) lemma ith_zero {n : nat} (a : A) (v : tuple A n) (h : 0 < succ n) : ith (a::v) (mk 0 h) = a := by induction v; reflexivity lemma ith_fin_zero {n : nat} (a : A) (v : tuple A n) : ith (a::v) (fin.zero n) = a := by unfold fin.zero; apply ith_zero lemma ith_succ {n : nat} (a : A) (v : tuple A n) (i : nat) (h : succ i < succ n) : ith (a::v) (mk (succ i) h) = ith v (mk_pred i h) := by induction v; reflexivity lemma ith_fin_succ {n : nat} (a : A) (v : tuple A n) (i : fin n) : ith (a::v) (succ i) = ith v i := begin cases i, unfold fin.succ, rewrite ith_succ end lemma ith_zero_eq_head {n : nat} (v : tuple A (nat.succ n)) : ith v (fin.zero n) = head v := by rewrite [-eta v, ith_fin_zero, head_cons] lemma ith_succ_eq_ith_tail {n : nat} (v : tuple A (nat.succ n)) (i : fin n) : ith v (succ i) = ith (tail v) i := by rewrite [-eta v, ith_fin_succ, tail_cons] protected lemma ext {n : nat} (v₁ v₂ : tuple A n) (h : ∀ i : fin n, ith v₁ i = ith v₂ i) : v₁ = v₂ := begin induction n with n ih, rewrite [tuple0_eq_nil v₁, tuple0_eq_nil v₂], rewrite [-eta v₁, -eta v₂], congruence, show head v₁ = head v₂, by rewrite [-ith_zero_eq_head, -ith_zero_eq_head]; apply h, have ∀ i : fin n, ith (tail v₁) i = ith (tail v₂) i, from take i, by rewrite [-ith_succ_eq_ith_tail, -ith_succ_eq_ith_tail]; apply h, show tail v₁ = tail v₂, from ih _ _ this end /- tabulate -/ definition tabulate : Π {n : nat}, (fin n → A) → tuple A n | 0 f := nil | (n+1) f := f (fin.zero n) :: tabulate (λ i : fin n, f (succ i)) theorem ith_tabulate {n : nat} (f : fin n → A) (i : fin n) : ith (tabulate f) i = f i := begin induction n with n ih, apply elim0 i, cases i with v hlt, cases v, {unfold tabulate, rewrite ith_zero}, {unfold tabulate, rewrite [ith_succ, ih]} end end tuple
17b66c1a8f8584d6503abb76e2b41f87539f044a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/real/basic.lean
dbddb697e0b87bf96689936ef0c03449fe607981
[ "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
28,876
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import algebra.bounds import algebra.order.archimedean import algebra.star.basic import data.real.cau_seq_completion /-! # Real numbers from Cauchy sequences > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers. This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply lifting everything to `ℚ`. -/ assert_not_exists finset assert_not_exists module assert_not_exists submonoid open_locale pointwise /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : cau_seq.completion.Cauchy (abs : ℚ → ℚ)) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace cau_seq.completion -- this can't go in `data.real.cau_seq_completion` as the structure on `rat` isn't available @[simp] theorem of_rat_rat {abv : ℚ → ℚ} [is_absolute_value abv] (q : ℚ) : of_rat (q : ℚ) = (q : @Cauchy _ _ _ _ abv _) := rfl end cau_seq.completion namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy abs := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ instance : has_sub ℝ := ⟨λ a b, a + (-b)⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma of_cauchy_zero : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma of_cauchy_one : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma of_cauchy_add (a b) : (⟨a + b⟩ : ℝ) = ⟨a⟩ + ⟨b⟩ := show _ = add _ _, by rw add lemma of_cauchy_neg (a) : (⟨-a⟩ : ℝ) = -⟨a⟩ := show _ = neg _, by rw neg lemma of_cauchy_sub (a b) : (⟨a - b⟩ : ℝ) = ⟨a⟩ - ⟨b⟩ := by { rw [sub_eq_add_neg, of_cauchy_add, of_cauchy_neg], refl } lemma of_cauchy_mul (a b) : (⟨a * b⟩ : ℝ) = ⟨a⟩ * ⟨b⟩ := show _ = mul _ _, by rw mul lemma of_cauchy_inv {f} : (⟨f⁻¹⟩ : ℝ) = ⟨f⟩⁻¹ := show _ = inv' _, by rw inv' lemma cauchy_zero : (0 : ℝ).cauchy = 0 := show zero.cauchy = 0, by rw zero lemma cauchy_one : (1 : ℝ).cauchy = 1 := show one.cauchy = 1, by rw one lemma cauchy_add : ∀ a b, (a + b : ℝ).cauchy = a.cauchy + b.cauchy | ⟨a⟩ ⟨b⟩ := show (add _ _).cauchy = _, by rw add lemma cauchy_neg : ∀ a, (-a : ℝ).cauchy = -a.cauchy | ⟨a⟩ := show (neg _).cauchy = _, by rw neg lemma cauchy_mul : ∀ a b, (a * b : ℝ).cauchy = a.cauchy * b.cauchy | ⟨a⟩ ⟨b⟩ := show (mul _ _).cauchy = _, by rw mul lemma cauchy_sub : ∀ a b, (a - b : ℝ).cauchy = a.cauchy - b.cauchy | ⟨a⟩ ⟨b⟩ := by { rw [sub_eq_add_neg, ←cauchy_neg, ←cauchy_add], refl } lemma cauchy_inv : ∀ f, (f⁻¹ : ℝ).cauchy = f.cauchy⁻¹ | ⟨f⟩ := show (inv' _).cauchy = _, by rw inv' instance : has_nat_cast ℝ := { nat_cast := λ n, ⟨n⟩ } instance : has_int_cast ℝ := { int_cast := λ z, ⟨z⟩ } instance : has_rat_cast ℝ := { rat_cast := λ q, ⟨q⟩ } lemma of_cauchy_nat_cast (n : ℕ) : (⟨n⟩ : ℝ) = n := rfl lemma of_cauchy_int_cast (z : ℤ) : (⟨z⟩ : ℝ) = z := rfl lemma of_cauchy_rat_cast (q : ℚ) : (⟨q⟩ : ℝ) = q := rfl lemma cauchy_nat_cast (n : ℕ) : (n : ℝ).cauchy = n := rfl lemma cauchy_int_cast (z : ℤ) : (z : ℝ).cauchy = z := rfl lemma cauchy_rat_cast (q : ℚ) : (q : ℝ).cauchy = q := rfl instance : comm_ring ℝ := begin refine_struct { zero := (0 : ℝ), one := (1 : ℝ), mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := @has_sub.sub ℝ _, npow := @npow_rec ℝ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec ℝ ⟨0⟩ ⟨(+)⟩, zsmul := @zsmul_rec ℝ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩, ..real.has_nat_cast, ..real.has_int_cast, }; repeat { rintro ⟨_⟩, }; try { refl }; simp [← of_cauchy_zero, ← of_cauchy_one, ←of_cauchy_add, ←of_cauchy_neg, ←of_cauchy_mul, λ n, show @coe ℕ ℝ ⟨_⟩ n = ⟨n⟩, from rfl, has_nat_cast.nat_cast, has_int_cast.int_cast]; apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip, end /-- `real.equiv_Cauchy` as a ring equivalence. -/ @[simps] def ring_equiv_Cauchy : ℝ ≃+* cau_seq.completion.Cauchy abs := { to_fun := cauchy, inv_fun := of_cauchy, map_add' := cauchy_add, map_mul' := cauchy_mul, ..equiv_Cauchy } /-! Extra instances to short-circuit type class resolution. These short-circuits have an additional property of ensuring that a computable path is found; if `field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable` version of them. -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : comm_monoid_with_zero ℝ := by apply_instance instance : monoid_with_zero ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : star_ring ℝ := star_ring_of_comm instance : has_trivial_star ℝ := ⟨λ _, rfl⟩ /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ := quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← of_cauchy_zero; refl lemma mk_one : mk 1 = 1 := by rw ← of_cauchy_one; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, ←of_cauchy_add] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, ←of_cauchy_mul] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, ←of_cauchy_neg] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem rat_cast_lt {x y : ℚ} : (x : ℝ) < (y : ℝ) ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert rat_cast_lt.2 zero_lt_one; simp [←of_cauchy_rat_cast, of_cauchy_one, of_cauchy_zero] protected lemma fact_zero_lt_one : fact ((0 : ℝ) < 1) := ⟨real.zero_lt_one⟩ protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : strict_ordered_comm_ring ℝ := { exists_pair_ne := ⟨0, 1, real.zero_lt_one.ne⟩, add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : strict_ordered_ring ℝ := infer_instance instance : strict_ordered_comm_semiring ℝ := infer_instance instance : strict_ordered_semiring ℝ := infer_instance instance : ordered_ring ℝ := infer_instance instance : ordered_semiring ℝ := infer_instance instance : ordered_add_comm_group ℝ := infer_instance instance : ordered_cancel_add_comm_monoid ℝ := infer_instance instance : ordered_add_comm_monoid ℝ := infer_instance instance : nontrivial ℝ := infer_instance @[irreducible] private def sup : ℝ → ℝ → ℝ | ⟨x⟩ ⟨y⟩ := ⟨quotient.map₂ (⊔) (λ x₁ x₂ hx y₁ y₂ hy, sup_equiv_sup hx hy) x y⟩ instance : has_sup ℝ := ⟨sup⟩ lemma of_cauchy_sup (a b) : (⟨⟦a ⊔ b⟧⟩ : ℝ) = ⟨⟦a⟧⟩ ⊔ ⟨⟦b⟧⟩ := show _ = sup _ _, by { rw sup, refl } @[simp] lemma mk_sup (a b) : (mk (a ⊔ b) : ℝ) = mk a ⊔ mk b := of_cauchy_sup _ _ @[irreducible] private def inf : ℝ → ℝ → ℝ | ⟨x⟩ ⟨y⟩ := ⟨quotient.map₂ (⊓) (λ x₁ x₂ hx y₁ y₂ hy, inf_equiv_inf hx hy) x y⟩ instance : has_inf ℝ := ⟨inf⟩ lemma of_cauchy_inf (a b) : (⟨⟦a ⊓ b⟧⟩ : ℝ) = ⟨⟦a⟧⟩ ⊓ ⟨⟦b⟧⟩ := show _ = inf _ _, by { rw inf, refl } @[simp] lemma mk_inf (a b) : (mk (a ⊓ b) : ℝ) = mk a ⊓ mk b := of_cauchy_inf _ _ instance : distrib_lattice ℝ := { sup := (⊔), le := (≤), le_sup_left := λ a, real.ind_mk a $ λ a b, real.ind_mk b $ λ b, begin rw [←mk_sup, mk_le], exact cau_seq.le_sup_left, end, le_sup_right := λ a, real.ind_mk a $ λ a b, real.ind_mk b $ λ b, begin rw [←mk_sup, mk_le], exact cau_seq.le_sup_right, end, sup_le := λ a, real.ind_mk a $ λ a b, real.ind_mk b $ λ b c, real.ind_mk c $ λ c, begin simp_rw [←mk_sup, mk_le], exact cau_seq.sup_le, end, inf := (⊓), inf_le_left := λ a, real.ind_mk a $ λ a b, real.ind_mk b $ λ b, begin rw [←mk_inf, mk_le], exact cau_seq.inf_le_left, end, inf_le_right := λ a, real.ind_mk a $ λ a b, real.ind_mk b $ λ b, begin rw [←mk_inf, mk_le], exact cau_seq.inf_le_right, end, le_inf := λ a, real.ind_mk a $ λ a b, real.ind_mk b $ λ b c, real.ind_mk c $ λ c, begin simp_rw [←mk_inf, mk_le], exact cau_seq.le_inf, end, le_sup_inf := λ a, real.ind_mk a $ λ a b, real.ind_mk b $ λ b c, real.ind_mk c $ λ c, eq.le begin simp only [←mk_sup, ←mk_inf], exact congr_arg mk (cau_seq.sup_inf_distrib_left _ _ _).symm end, .. real.partial_order } /- Extra instances to short-circuit type class resolution -/ instance : lattice ℝ := infer_instance instance : semilattice_inf ℝ := infer_instance instance : semilattice_sup ℝ := infer_instance open_locale classical instance : is_total ℝ (≤) := ⟨λ a, real.ind_mk a $ λ a b, real.ind_mk b $ λ b, by simpa using le_total a b⟩ noncomputable instance : linear_order ℝ := lattice.to_linear_order _ noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.strict_ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : is_domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.is_domain } noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [←of_cauchy_inv, ←of_cauchy_mul, ← of_cauchy_one, ← of_cauchy_zero, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← of_cauchy_zero, ←of_cauchy_inv], rat_cast := coe, rat_cast_mk := λ n d hd h2, by rw [←of_cauchy_rat_cast, rat.cast_mk', of_cauchy_mul, of_cauchy_inv, of_cauchy_nat_cast, of_cauchy_int_cast], ..real.linear_ordered_comm_ring } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance /-- Show an underlying cauchy sequence for real numbers. The representative chosen is the one passed in the VM to `quot.mk`, so two cauchy sequences converging to the same number may be printed differently. -/ meta instance : has_repr ℝ := { repr := λ r, "real.of_cauchy " ++ repr r.cauchy } theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ le_rfl).1, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ le_rfl).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| ≤ ε) : |mk f - x| ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le_comm.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le_comm.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_is_lub (S : set ℝ) (hne : S.nonempty) (hbdd : bdd_above S) : ∃ x, is_lub S x := begin rcases ⟨hne, hbdd⟩ with ⟨⟨L, hL⟩, ⟨U, hU⟩⟩, have : ∀ d : ℕ, bdd_above {m : ℤ | ∃ y ∈ S, (m : ℝ) ≤ y * d}, { cases exists_int_gt U with k hk, refine λ d, ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (hy.trans _), push_cast, exact mul_le_mul_of_nonneg_right ((hU yS).trans hk.le) d.cast_nonneg }, choose f hf using λ d : ℕ, int.exists_greatest_of_bdd (this d) ⟨⌊L * d⌋, L, hL, int.floor_le _⟩, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := (int.sub_one_lt_floor _).trans_le (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, int.floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, have hg : is_cau_seq abs (λ n, f n / n : ℕ → ℚ), { intros ε ε0, suffices : ∀ j k ≥ ⌈ε⁻¹⌉₊, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ ij _ le_rfl⟩⟩, rw [neg_lt, neg_sub], exact this _ le_rfl _ ij }, intros j ij k ik, replace ij := le_trans (nat.le_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (nat.le_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 ((inv_pos.2 ε0).trans_le ij), have k0 := nat.cast_pos.1 ((inv_pos.2 ε0).trans_le ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) }, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, ⟨λ x xS, _, λ y h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := hK.le.trans (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 ((inv_pos.2 xz).trans_le hK), refine le_trans _ (hf₂ _ n0 _ xS).le, rwa [le_sub_comm, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h xS)⟩ } end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : S.nonempty ∧ bdd_above S then classical.some (exists_is_lub S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : S.nonempty ∧ bdd_above S then classical.some (exists_is_lub S h.1 h.2) else 0 := rfl protected theorem is_lub_Sup (S : set ℝ) (h₁ : S.nonempty) (h₂ : bdd_above S) : is_lub S (Sup S) := by { simp only [Sup_def, dif_pos (and.intro h₁ h₂)], apply classical.some_spec } noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup (-S)⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup (-S) := rfl protected theorem is_glb_Inf (S : set ℝ) (h₁ : S.nonempty) (h₂ : bdd_below S) : is_glb S (Inf S) := begin rw [Inf_def, ← is_lub_neg', neg_neg], exact real.is_lub_Sup _ h₁.neg h₂.neg end noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := λ s a hs ha, (real.is_lub_Sup s ⟨a, ha⟩ hs).1 ha, cSup_le := λ s a hs ha, (real.is_lub_Sup s hs ⟨a, ha⟩).2 ha, cInf_le := λ s a hs ha, (real.is_glb_Inf s ⟨a, ha⟩ hs).1 ha, le_cInf := λ s a hs ha, (real.is_glb_Inf s hs ⟨a, ha⟩).2 ha, ..real.linear_order, ..real.lattice} lemma lt_Inf_add_pos {s : set ℝ} (h : s.nonempty) {ε : ℝ} (hε : 0 < ε) : ∃ a ∈ s, a < Inf s + ε := exists_lt_of_cInf_lt h $ lt_add_of_pos_right _ hε lemma add_neg_lt_Sup {s : set ℝ} (h : s.nonempty) {ε : ℝ} (hε : ε < 0) : ∃ a ∈ s, Sup s + ε < a := exists_lt_of_lt_cSup h $ add_lt_iff_neg_left.2 hε lemma Inf_le_iff {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {a : ℝ} : Inf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε := begin rw le_iff_forall_pos_lt_add, split; intros H ε ε_pos, { exact exists_lt_of_cInf_lt h' (H ε ε_pos) }, { rcases H ε ε_pos with ⟨x, x_in, hx⟩, exact cInf_lt_of_lt h x_in hx } end lemma le_Sup_iff {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {a : ℝ} : a ≤ Sup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x := begin rw le_iff_forall_pos_lt_add, refine ⟨λ H ε ε_neg, _, λ H ε ε_pos, _⟩, { exact exists_lt_of_lt_cSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) }, { rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩, exact sub_lt_iff_lt_add.mp (lt_cSup_of_lt h x_in hx) } end @[simp] theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp lemma csupr_empty {α : Sort*} [is_empty α] (f : α → ℝ) : (⨆ i, f i) = 0 := begin dsimp [supr], convert real.Sup_empty, rw set.range_eq_empty_iff, apply_instance end @[simp] lemma csupr_const_zero {α : Sort*} : (⨆ i : α, (0:ℝ)) = 0 := begin casesI is_empty_or_nonempty α, { exact real.csupr_empty _ }, { exact csupr_const }, end theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 lemma supr_of_not_bdd_above {α : Sort*} {f : α → ℝ} (hf : ¬ bdd_above (set.range f)) : (⨆ i, f i) = 0 := Sup_of_not_bdd_above hf theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) @[simp] theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] lemma cinfi_empty {α : Sort*} [is_empty α] (f : α → ℝ) : (⨅ i, f i) = 0 := by rw [infi_of_empty', Inf_empty] @[simp] lemma cinfi_const_zero {α : Sort*} : (⨅ i : α, (0:ℝ)) = 0 := begin casesI is_empty_or_nonempty α, { exact real.cinfi_empty _ }, { exact cinfi_const }, end theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := neg_eq_zero.2 $ Sup_of_not_bdd_above $ mt bdd_above_neg.1 hs lemma infi_of_not_bdd_below {α : Sort*} {f : α → ℝ} (hf : ¬ bdd_below (set.range f)) : (⨅ i, f i) = 0 := Inf_of_not_bdd_below hf /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Sup S`. -/ lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { exact Sup_empty.ge }, { apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) } end /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that `f i` is nonnegative to show that `0 ≤ ⨆ i, f i`. -/ protected lemma supr_nonneg {ι : Sort*} {f : ι → ℝ} (hf : ∀ i, 0 ≤ f i) : 0 ≤ ⨆ i, f i := Sup_nonneg _ $ set.forall_range_iff.2 hf /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that all elements of `S` are bounded by a nonnagative number to show that `Sup S` is bounded by this number. -/ protected lemma Sup_le {S : set ℝ} {a : ℝ} (hS : ∀ x ∈ S, x ≤ a) (ha : 0 ≤ a) : Sup S ≤ a := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, exacts [Sup_empty.trans_le ha, cSup_le hS₂ hS], end protected lemma supr_le {ι : Sort*} {f : ι → ℝ} {a : ℝ} (hS : ∀ i, f i ≤ a) (ha : 0 ≤ a) : (⨆ i, f i) ≤ a := real.Sup_le (set.forall_range_iff.2 hS) ha /-- As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is bounded above by `0` to show that `Sup S ≤ 0`. -/ lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 := real.Sup_le hS le_rfl /-- As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, exacts [Inf_empty.ge, le_cInf hS₂ hS] end /-- As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`. -/ lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { exact Inf_empty.le }, { apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) } end lemma Inf_le_Sup (s : set ℝ) (h₁ : bdd_below s) (h₂ : bdd_above s) : Inf s ≤ Sup s := begin rcases s.eq_empty_or_nonempty with rfl | hne, { rw [Inf_empty, Sup_empty] }, { exact cInf_le_cSup h₁ h₂ hne } end theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine (cSup_le lb (ub' _ _)).not_lt (sub_lt_self _ (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine (le_cSup ub _).not_lt ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real
ccdbb352beaac801820864191aab8595fc28086a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/MacroRules.lean
aa61889682eabc943a8c418d1c6051f4738f71c5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
3,300
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Syntax import Lean.Elab.AuxDef namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command /-- Remark: `k` is the user provided kind with the current namespace included. Recall that syntax node kinds contain the current namespace. -/ def elabMacroRulesAux (doc? : Option (TSyntax ``docComment)) (attrs? : Option (TSepArray ``attrInstance ",")) (attrKind : TSyntax ``attrKind) (tk : Syntax) (k : SyntaxNodeKind) (alts : Array (TSyntax ``matchAlt)) : CommandElabM Syntax := do let alts ← alts.mapM fun (alt : TSyntax ``matchAlt) => match alt with | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0]! if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat let k' := quoted.getKind if checkRuleKind k' k then pure alt else if k' == choiceKind then match quoted.getArgs.find? fun quotAlt => checkRuleKind quotAlt.getKind k with | none => throwErrorAt alt "invalid macro_rules alternative, expected syntax node kind '{k}'" | some quoted => let pat := pat.setArg 1 quoted let pats := pats.elemsAndSeps.set! 0 pat `(matchAltExpr| | $(⟨pats⟩),* => $rhs) else throwErrorAt alt "invalid macro_rules alternative, unexpected syntax node kind '{k'}'" | _ => throwUnsupportedSyntax let attr ← `(attrInstance| $attrKind macro $(Lean.mkIdent k)) let attrs := match attrs? with | some attrs => attrs.getElems.push attr | none => #[attr] `($[$doc?:docComment]? @[$attrs,*] aux_def macroRules $(mkIdentFrom tk k) : Macro := fun $alts:matchAlt* | _ => no_error_if_unused% throw Lean.Macro.Exception.unsupportedSyntax) @[builtinCommandElab «macro_rules»] def elabMacroRules : CommandElab := adaptExpander fun stx => match stx with | `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro_rules%$tk $alts:matchAlt*) => -- exclude command prefix from synthetic position used for e.g. jumping to the macro definition withRef (mkNullNode #[tk, mkNullNode alts]) do expandNoKindMacroRulesAux alts "macro_rules" fun kind? alts => `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro_rules $[(kind := $(mkIdent <$> kind?))]? $alts:matchAlt*) | `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro_rules%$tk (kind := $kind) | $x:ident => $rhs) => withRef (mkNullNode #[tk, rhs]) do let attr ← `(attrInstance| $attrKind:attrKind macro $kind) let attrs := match attrs? with | some attrs => attrs.getElems.push attr | none => #[attr] `($[$doc?:docComment]? @[$attrs,*] aux_def $(mkIdentFrom tk kind.getId) $kind : Macro := fun $x:ident => $rhs) | `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro_rules%$tk (kind := $kind) $alts:matchAlt*) => withRef (mkNullNode #[tk, mkNullNode alts]) do elabMacroRulesAux doc? attrs? attrKind tk (← resolveSyntaxKind kind.getId) alts | _ => throwUnsupportedSyntax end Lean.Elab.Command
3e5e033e4a9bb05a70330aeaf03be77631ef32d4
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world9/level2.lean
4089a4dbbdbdd9161f625c98b96f0a115934c57f
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
554
lean
import game.world9.level1 -- hide namespace mynat -- hide /- # Advanced Multiplication World ## Level 2: `eq_zero_or_eq_zero_of_mul_eq_zero` A variant on the previous level. -/ /- Theorem If $ab = 0$, then at least one of $a$ or $b$ is equal to zero. -/ theorem eq_zero_or_eq_zero_of_mul_eq_zero (a b : mynat) (h : a * b = 0) : a = 0 ∨ b = 0 := begin [nat_num_game] cases a with d, left, refl, cases b with e he, right, refl, exfalso, rw mul_succ at h, rw add_succ at h, exact succ_ne_zero _ h, end end mynat -- hide
a8131c3580ea58c64ff8bd9ff4a81ae38776a4ce
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/hott/num.lean
f2f5577a9b7fde0c633f3c39fd6e5cd810ab99c0
[ "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
667
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import logic namespace num -- pos_num and num are two auxiliary datatypes used when parsing numerals such as 13, 0, 26. -- The parser will generate the terms (pos (bit1 (bit1 (bit0 one)))), zero, and (pos (bit0 (bit1 (bit1 one)))). -- This representation can be coerced in whatever we want (e.g., naturals, integers, reals, etc). inductive pos_num : Type := | one : pos_num | bit1 : pos_num → pos_num | bit0 : pos_num → pos_num inductive num : Type := | zero : num | pos : pos_num → num end
a9f932d606067a7d54231ce48d4bf1cfeb3ef14b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/notation_pp_priority.lean
3ffa212099f3af4bf4027c4e932ee95ee2894dbe
[ "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
602
lean
prelude import init.data.nat.basic noncomputable theory constant some_type : Type constants foo bar : some_type /- Test that notation with a high priority is used by the pretty-printer, regardless of the order in which they are declared. -/ section notation [priority 2000] `high_before_low` := foo notation [priority 1] `low_after_high` := foo def test_high_before_low := foo #print test_high_before_low end section notation [priority 1] `low_before_high` := bar notation [priority 2000] `high_after_low` := bar def test_high_after_low := bar #print test_high_after_low end