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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1e1891172f0ba28865835113f7d8ac7644bb8d7b | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/group/semiconj.lean | da73a2a73d141d5c963e3823688c7f79c9123ba8 | [
"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,601 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
Some proofs and docs came from `algebra/commute` (c) Neil Strickland
-/
import algebra.group.units
/-!
# Semiconjugate elements of a semigroup
## Main definitions
We say that `x` is semiconjugate to `y` by `a` (`semiconj_by a x y`), if `a * x = y * a`.
In this file we provide operations on `semiconj_by _ _ _`.
In the names of these operations, we treat `a` as the “left” argument, and both `x` and `y` as
“right” arguments. This way most names in this file agree with the names of the corresponding lemmas
for `commute a b = semiconj_by a b b`. As a side effect, some lemmas have only `_right` version.
Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like
`rw [(h.pow_right 5).eq]` rather than just `rw [h.pow_right 5]`.
This file provides only basic operations (`mul_left`, `mul_right`, `inv_right` etc). Other
operations (`pow_right`, field inverse etc) are in the files that define corresponding notions.
-/
universes u v
/-- `x` is semiconjugate to `y` by `a`, if `a * x = y * a`. -/
@[to_additive add_semiconj_by "`x` is additive semiconjugate to `y` by `a` if `a + x = y + a`"]
def semiconj_by {M : Type u} [has_mul M] (a x y : M) : Prop := a * x = y * a
namespace semiconj_by
/-- Equality behind `semiconj_by a x y`; useful for rewriting. -/
@[to_additive]
protected lemma eq {S : Type u} [has_mul S] {a x y : S} (h : semiconj_by a x y) :
a * x = y * a := h
section semigroup
variables {S : Type u} [semigroup S] {a b x y z x' y' : S}
/-- If `a` semiconjugates `x` to `y` and `x'` to `y'`,
then it semiconjugates `x * x'` to `y * y'`. -/
@[simp, to_additive] lemma mul_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x * x') (y * y') :=
by unfold semiconj_by; assoc_rw [h.eq, h'.eq]
/-- If both `a` and `b` semiconjugate `x` to `y`, then so does `a * b`. -/
@[to_additive]
lemma mul_left (ha : semiconj_by a y z) (hb : semiconj_by b x y) :
semiconj_by (a * b) x z :=
by unfold semiconj_by; assoc_rw [hb.eq, ha.eq, mul_assoc]
end semigroup
section monoid
variables {M : Type u} [monoid M]
/-- Any element semiconjugates `1` to `1`. -/
@[simp, to_additive]
lemma one_right (a : M) : semiconj_by a 1 1 := by rw [semiconj_by, mul_one, one_mul]
/-- One semiconjugates any element to itself. -/
@[simp, to_additive]
lemma one_left (x : M) : semiconj_by 1 x x := eq.symm $ one_right x
/-- If `a` semiconjugates a unit `x` to a unit `y`, then it semiconjugates `x⁻¹` to `y⁻¹`. -/
@[to_additive] lemma units_inv_right {a : M} {x y : units M} (h : semiconj_by a x y) :
semiconj_by a ↑x⁻¹ ↑y⁻¹ :=
calc a * ↑x⁻¹ = ↑y⁻¹ * (y * a) * ↑x⁻¹ : by rw [units.inv_mul_cancel_left]
... = ↑y⁻¹ * a : by rw [← h.eq, mul_assoc, units.mul_inv_cancel_right]
@[simp, to_additive] lemma units_inv_right_iff {a : M} {x y : units M} :
semiconj_by a ↑x⁻¹ ↑y⁻¹ ↔ semiconj_by a x y :=
⟨units_inv_right, units_inv_right⟩
/-- If a unit `a` semiconjugates `x` to `y`, then `a⁻¹` semiconjugates `y` to `x`. -/
@[to_additive] lemma units_inv_symm_left {a : units M} {x y : M} (h : semiconj_by ↑a x y) :
semiconj_by ↑a⁻¹ y x :=
calc ↑a⁻¹ * y = ↑a⁻¹ * (y * a * ↑a⁻¹) : by rw [units.mul_inv_cancel_right]
... = x * ↑a⁻¹ : by rw [← h.eq, ← mul_assoc, units.inv_mul_cancel_left]
@[simp, to_additive] lemma units_inv_symm_left_iff {a : units M} {x y : M} :
semiconj_by ↑a⁻¹ y x ↔ semiconj_by ↑a x y :=
⟨units_inv_symm_left, units_inv_symm_left⟩
@[to_additive] theorem units_coe {a x y : units M} (h : semiconj_by a x y) :
semiconj_by (a : M) x y :=
congr_arg units.val h
@[to_additive] theorem units_of_coe {a x y : units M} (h : semiconj_by (a : M) x y) :
semiconj_by a x y :=
units.ext h
@[simp, to_additive] theorem units_coe_iff {a x y : units M} :
semiconj_by (a : M) x y ↔ semiconj_by a x y :=
⟨units_of_coe, units_coe⟩
end monoid
section group
variables {G : Type u} [group G] {a x y : G}
@[simp, to_additive] lemma inv_right_iff : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y :=
@units_inv_right_iff G _ a ⟨x, x⁻¹, mul_inv_self x, inv_mul_self x⟩
⟨y, y⁻¹, mul_inv_self y, inv_mul_self y⟩
@[to_additive] lemma inv_right : semiconj_by a x y → semiconj_by a x⁻¹ y⁻¹ :=
inv_right_iff.2
@[simp, to_additive] lemma inv_symm_left_iff : semiconj_by a⁻¹ y x ↔ semiconj_by a x y :=
@units_inv_symm_left_iff G _ ⟨a, a⁻¹, mul_inv_self a, inv_mul_self a⟩ _ _
@[to_additive] lemma inv_symm_left : semiconj_by a x y → semiconj_by a⁻¹ y x :=
inv_symm_left_iff.2
@[to_additive] lemma inv_inv_symm (h : semiconj_by a x y) : semiconj_by a⁻¹ y⁻¹ x⁻¹ :=
h.inv_right.inv_symm_left
-- this is not a simp lemma because it can be deduced from other simp lemmas
@[to_additive] lemma inv_inv_symm_iff : semiconj_by a⁻¹ y⁻¹ x⁻¹ ↔ semiconj_by a x y :=
inv_right_iff.trans inv_symm_left_iff
/-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/
@[to_additive] lemma conj_mk (a x : G) : semiconj_by a x (a * x * a⁻¹) :=
by unfold semiconj_by; rw [mul_assoc, inv_mul_self, mul_one]
end group
end semiconj_by
/-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/
@[to_additive]
lemma units.mk_semiconj_by {M : Type u} [monoid M] (u : units M) (x : M) :
semiconj_by ↑u x (u * x * ↑u⁻¹) :=
by unfold semiconj_by; rw [units.inv_mul_cancel_right]
|
c08672d8796e1426daff3c1696c41f7af9f039a9 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/order/closure.lean | 745cd61782643ad89ce2ea22bf26fb829619b330 | [
"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 | 17,280 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Yaël Dillies
-/
import data.set_like
import order.basic
import order.preorder_hom
import order.galois_connection
import tactic.monotonicity
/-!
# Closure operators between preorders
We define (bundled) closure operators on a preorder as monotone (increasing), extensive
(inflationary) and idempotent functions.
We define closed elements for the operator as elements which are fixed by it.
Lower adjoints to a function between preorders `u : β → α` allow to generalise closure operators to
situations where the closure operator we are dealing with naturally decomposes as `u ∘ l` where `l`
is a worthy function to have on its own. Typical examples include
`l : set G → subgroup G := subgroup.closure`, `u : subgroup G → set G := coe`, where `G` is a group.
This shows there is a close connection between closure operators, lower adjoints and Galois
connections/insertions: every Galois connection induces a lower adjoint which itself induces a
closure operator by composition (see `galois_connection.lower_adjoint` and
`lower_adjoint.closure_operator`), and every closure operator on a partial order induces a Galois
insertion from the set of closed elements to the underlying type (see `closure_operator.gi`).
## Main definitions
* `closure_operator`: A closure operator is a monotone function `f : α → α` such that
`∀ x, x ≤ f x` and `∀ x, f (f x) = f x`.
* `lower_adjoint`: A lower adjoint to `u : β → α` is a function `l : α → β` such that `l` and `u`
form a Galois connection.
## Implementation details
Although `lower_adjoint` is technically a generalisation of `closure_operator` (by defining
`to_fun := id`), it is diserable to have both as otherwise `id`s would be carried all over the
place when using concrete closure operators such as `convex_hull`.
`lower_adjoint` really is a semibundled `structure` version of `galois_connection`.
## References
* https://en.wikipedia.org/wiki/Closure_operator#Closure_operators_on_partially_ordered_sets
-/
universe u
/-! ### Closure operator -/
variable (α : Type*)
/-- A closure operator on the preorder `α` is a monotone function which is extensive (every `x`
is less than its closure) and idempotent. -/
structure closure_operator [preorder α] extends α →ₘ α :=
(le_closure' : ∀ x, x ≤ to_fun x)
(idempotent' : ∀ x, to_fun (to_fun x) = to_fun x)
namespace closure_operator
instance [preorder α] : has_coe_to_fun (closure_operator α) :=
{ F := _, coe := λ c, c.to_fun }
/-- See Note [custom simps projection] -/
def simps.apply [preorder α] (f : closure_operator α) : α → α := f
initialize_simps_projections closure_operator (to_preorder_hom_to_fun → apply, -to_preorder_hom)
section partial_order
variable [partial_order α]
/-- The identity function as a closure operator. -/
@[simps]
def id : closure_operator α :=
{ to_fun := λ x, x,
monotone' := λ _ _ h, h,
le_closure' := λ _, le_rfl,
idempotent' := λ _, rfl }
instance : inhabited (closure_operator α) := ⟨id α⟩
variables {α} (c : closure_operator α)
@[ext] lemma ext :
∀ (c₁ c₂ : closure_operator α), (c₁ : α → α) = (c₂ : α → α) → c₁ = c₂
| ⟨⟨c₁, _⟩, _, _⟩ ⟨⟨c₂, _⟩, _, _⟩ h := by { congr, exact h }
/-- Constructor for a closure operator using the weaker idempotency axiom: `f (f x) ≤ f x`. -/
@[simps]
def mk' (f : α → α) (hf₁ : monotone f) (hf₂ : ∀ x, x ≤ f x) (hf₃ : ∀ x, f (f x) ≤ f x) :
closure_operator α :=
{ to_fun := f,
monotone' := hf₁,
le_closure' := hf₂,
idempotent' := λ x, (hf₃ x).antisymm (hf₁ (hf₂ x)) }
/-- Convenience constructor for a closure operator using the weaker minimality axiom:
`x ≤ f y → f x ≤ f y`, which is sometimes easier to prove in practice. -/
@[simps]
def mk₂ (f : α → α) (hf : ∀ x, x ≤ f x) (hmin : ∀ ⦃x y⦄, x ≤ f y → f x ≤ f y) :
closure_operator α :=
{ to_fun := f,
monotone' := λ x y hxy, hmin (hxy.trans (hf y)),
le_closure' := hf,
idempotent' := λ x, (hmin le_rfl).antisymm (hf _) }
/-- Expanded out version of `mk₂`. `p` implies being closed. This constructor should be used when
you already know a sufficient condition for being closed and using `mem_mk₃_closed` will avoid you
the (slight) hassle of having to prove it both inside and outside the constructor. -/
@[simps]
def mk₃ (f : α → α) (p : α → Prop) (hf : ∀ x, x ≤ f x) (hfp : ∀ x, p (f x))
(hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y) :
closure_operator α :=
mk₂ f hf (λ x y hxy, hmin hxy (hfp y))
/-- This lemma shows that the image of `x` of a closure operator built from the `mk₃` constructor
respects `p`, the property that was fed into it. -/
lemma closure_mem_mk₃ {f : α → α} {p : α → Prop} {hf : ∀ x, x ≤ f x} {hfp : ∀ x, p (f x)}
{hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y} (x : α) :
p (mk₃ f p hf hfp hmin x) :=
hfp x
/-- Analogue of `closure_le_closed_iff_le` but with the `p` that was fed into the `mk₃` constructor.
-/
lemma closure_le_mk₃_iff {f : α → α} {p : α → Prop} {hf : ∀ x, x ≤ f x} {hfp : ∀ x, p (f x)}
{hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y} {x y : α} (hxy : x ≤ y) (hy : p y) :
mk₃ f p hf hfp hmin x ≤ y :=
hmin hxy hy
@[mono] lemma monotone : monotone c := c.monotone'
/-- Every element is less than its closure. This property is sometimes referred to as extensivity or
inflationarity. -/
lemma le_closure (x : α) : x ≤ c x := c.le_closure' x
@[simp] lemma idempotent (x : α) : c (c x) = c x := c.idempotent' x
lemma le_closure_iff (x y : α) : x ≤ c y ↔ c x ≤ c y :=
⟨λ h, c.idempotent y ▸ c.monotone h, λ h, (c.le_closure x).trans h⟩
/-- An element `x` is closed for the closure operator `c` if it is a fixed point for it. -/
def closed : set α := λ x, c x = x
lemma mem_closed_iff (x : α) : x ∈ c.closed ↔ c x = x := iff.rfl
lemma mem_closed_iff_closure_le (x : α) : x ∈ c.closed ↔ c x ≤ x :=
⟨le_of_eq, λ h, h.antisymm (c.le_closure x)⟩
lemma closure_eq_self_of_mem_closed {x : α} (h : x ∈ c.closed) : c x = x := h
@[simp] lemma closure_is_closed (x : α) : c x ∈ c.closed := c.idempotent x
/-- The set of closed elements for `c` is exactly its range. -/
lemma closed_eq_range_close : c.closed = set.range c :=
set.ext $ λ x, ⟨λ h, ⟨x, h⟩, by { rintro ⟨y, rfl⟩, apply c.idempotent }⟩
/-- Send an `x` to an element of the set of closed elements (by taking the closure). -/
def to_closed (x : α) : c.closed := ⟨c x, c.closure_is_closed x⟩
@[simp] lemma closure_le_closed_iff_le (x : α) {y : α} (hy : c.closed y) : c x ≤ y ↔ x ≤ y :=
by rw [←c.closure_eq_self_of_mem_closed hy, ←le_closure_iff]
/-- A closure operator is equal to the closure operator obtained by feeding `c.closed` into the
`mk₃` constructor. -/
lemma eq_mk₃_closed (c : closure_operator α) :
c = mk₃ c c.closed c.le_closure c.closure_is_closed
(λ x y hxy hy, (c.closure_le_closed_iff_le x hy).2 hxy) :=
by { ext, refl }
/-- The property `p` fed into the `mk₃` constructor implies being closed. -/
lemma mem_mk₃_closed {f : α → α} {p : α → Prop} {hf : ∀ x, x ≤ f x} {hfp : ∀ x, p (f x)}
{hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y} {x : α} (hx : p x) :
x ∈ (mk₃ f p hf hfp hmin).closed :=
(hmin (le_refl _) hx).antisymm (hf _)
end partial_order
variable {α}
section order_top
variables [order_top α] (c : closure_operator α)
@[simp] lemma closure_top : c ⊤ = ⊤ :=
le_top.antisymm (c.le_closure _)
lemma top_mem_closed : ⊤ ∈ c.closed :=
c.closure_top
end order_top
lemma closure_inf_le [semilattice_inf α] (c : closure_operator α) (x y : α) :
c (x ⊓ y) ≤ c x ⊓ c y :=
c.monotone.map_inf_le _ _
section semilattice_sup
variables [semilattice_sup α] (c : closure_operator α)
lemma closure_sup_closure_le (x y : α) :
c x ⊔ c y ≤ c (x ⊔ y) :=
c.monotone.le_map_sup _ _
lemma closure_sup_closure_left (x y : α) :
c (c x ⊔ y) = c (x ⊔ y) :=
((c.le_closure_iff _ _).1 (sup_le (c.monotone le_sup_left) (le_sup_right.trans
(c.le_closure _)))).antisymm (c.monotone (sup_le_sup_right (c.le_closure _) _))
lemma closure_sup_closure_right (x y : α) :
c (x ⊔ c y) = c (x ⊔ y) :=
by rw [sup_comm, closure_sup_closure_left, sup_comm]
lemma closure_sup_closure (x y : α) :
c (c x ⊔ c y) = c (x ⊔ y) :=
by rw [closure_sup_closure_left, closure_sup_closure_right]
end semilattice_sup
section complete_lattice
variables [complete_lattice α] (c : closure_operator α)
lemma closure_supr_closure {ι : Type u} (x : ι → α) :
c (⨆ i, c (x i)) = c (⨆ i, x i) :=
le_antisymm ((c.le_closure_iff _ _).1 (supr_le (λ i, c.monotone
(le_supr x i)))) (c.monotone (supr_le_supr (λ i, c.le_closure _)))
lemma closure_bsupr_closure (p : α → Prop) :
c (⨆ x (H : p x), c x) = c (⨆ x (H : p x), x) :=
le_antisymm ((c.le_closure_iff _ _).1 (bsupr_le (λ x hx, c.monotone
(le_bsupr_of_le x hx (le_refl x))))) (c.monotone (bsupr_le_bsupr (λ x hx, c.le_closure x)))
end complete_lattice
end closure_operator
/-! ### Lower adjoint -/
variables {α} {β : Type*}
/-- A lower adjoint of `u` on the preorder `α` is a function `l` such that `l` and `u` form a Galois
connection. It allows us to define closure operators whose output does not match the input. In
practice, `u` is often `coe : β → α`. -/
structure lower_adjoint [preorder α] [preorder β] (u : β → α) :=
(to_fun : α → β)
(gc' : galois_connection to_fun u)
namespace lower_adjoint
variable (α)
/-- The identity function as a lower adjoint to itself. -/
@[simps]
protected def id [preorder α] : lower_adjoint (id : α → α) :=
{ to_fun := λ x, x,
gc' := galois_connection.id }
variable {α}
instance [preorder α] : inhabited (lower_adjoint (id : α → α)) := ⟨lower_adjoint.id α⟩
section preorder
variables [preorder α] [preorder β] {u : β → α} (l : lower_adjoint u)
instance : has_coe_to_fun (lower_adjoint u) :=
{ F := λ _, α → β, coe := to_fun }
/-- See Note [custom simps projection] -/
def simps.apply : α → β := l
lemma gc : galois_connection l u := l.gc'
@[ext] lemma ext :
∀ (l₁ l₂ : lower_adjoint u), (l₁ : α → β) = (l₂ : α → β) → l₁ = l₂
| ⟨l₁, _⟩ ⟨l₂, _⟩ h := by { congr, exact h }
@[mono] lemma monotone : monotone (u ∘ l) := l.gc.monotone_u.comp l.gc.monotone_l
/-- Every element is less than its closure. This property is sometimes referred to as extensivity or
inflationarity. -/
lemma le_closure (x : α) : x ≤ u (l x) := l.gc.le_u_l _
end preorder
section partial_order
variables [partial_order α] [preorder β] {u : β → α} (l : lower_adjoint u)
/-- Every lower adjoint induces a closure operator given by the composition. This is the partial
order version of the statement that every adjunction induces a monad. -/
@[simps]
def closure_operator :
closure_operator α :=
{ to_fun := λ x, u (l x),
monotone' := l.monotone,
le_closure' := l.le_closure,
idempotent' := λ x, show (u ∘ l ∘ u) (l x) = u (l x), by rw l.gc.u_l_u_eq_u }
lemma idempotent (x : α) : u (l (u (l x))) = u (l x) :=
l.closure_operator.idempotent _
lemma le_closure_iff (x y : α) : x ≤ u (l y) ↔ u (l x) ≤ u (l y) :=
l.closure_operator.le_closure_iff _ _
end partial_order
section preorder
variables [preorder α] [preorder β] {u : β → α} (l : lower_adjoint u)
/-- An element `x` is closed for `l : lower_adjoint u` if it is a fixed point: `u (l x) = x` -/
def closed : set α := λ x, u (l x) = x
lemma mem_closed_iff (x : α) : x ∈ l.closed ↔ u (l x) = x := iff.rfl
lemma closure_eq_self_of_mem_closed {x : α} (h : x ∈ l.closed) : u (l x) = x := h
end preorder
section partial_order
variables [partial_order α] [partial_order β] {u : β → α} (l : lower_adjoint u)
lemma mem_closed_iff_closure_le (x : α) : x ∈ l.closed ↔ u (l x) ≤ x :=
l.closure_operator.mem_closed_iff_closure_le _
@[simp] lemma closure_is_closed (x : α) : u (l x) ∈ l.closed := l.idempotent x
/-- The set of closed elements for `l` is the range of `u ∘ l`. -/
lemma closed_eq_range_close : l.closed = set.range (u ∘ l) :=
l.closure_operator.closed_eq_range_close
/-- Send an `x` to an element of the set of closed elements (by taking the closure). -/
def to_closed (x : α) : l.closed := ⟨u (l x), l.closure_is_closed x⟩
@[simp] lemma closure_le_closed_iff_le (x : α) {y : α} (hy : l.closed y) : u (l x) ≤ y ↔ x ≤ y :=
l.closure_operator.closure_le_closed_iff_le x hy
end partial_order
lemma closure_top [order_top α] [preorder β] {u : β → α} (l : lower_adjoint u) :
u (l ⊤) = ⊤ :=
l.closure_operator.closure_top
lemma closure_inf_le [semilattice_inf α] [preorder β] {u : β → α} (l : lower_adjoint u) (x y : α) :
u (l (x ⊓ y)) ≤ u (l x) ⊓ u (l y) :=
l.closure_operator.closure_inf_le x y
section semilattice_sup
variables [semilattice_sup α] [preorder β] {u : β → α} (l : lower_adjoint u)
lemma closure_sup_closure_le (x y : α) :
u (l x) ⊔ u (l y) ≤ u (l (x ⊔ y)) :=
l.closure_operator.closure_sup_closure_le x y
lemma closure_sup_closure_left (x y : α) :
u (l (u (l x) ⊔ y)) = u (l (x ⊔ y)) :=
l.closure_operator.closure_sup_closure_left x y
lemma closure_sup_closure_right (x y : α) :
u (l (x ⊔ u (l y))) = u (l (x ⊔ y)) :=
l.closure_operator.closure_sup_closure_right x y
lemma closure_sup_closure (x y : α) :
u (l (u (l x) ⊔ u (l y))) = u (l (x ⊔ y)) :=
l.closure_operator.closure_sup_closure x y
end semilattice_sup
section complete_lattice
variables [complete_lattice α] [preorder β] {u : β → α} (l : lower_adjoint u)
lemma closure_supr_closure {ι : Type u} (x : ι → α) :
u (l (⨆ i, u (l (x i)))) = u (l (⨆ i, x i)) :=
l.closure_operator.closure_supr_closure x
lemma closure_bsupr_closure (p : α → Prop) :
u (l (⨆ x (H : p x), u (l x))) = u (l (⨆ x (H : p x), x)) :=
l.closure_operator.closure_bsupr_closure p
end complete_lattice
/- Lemmas for `lower_adjoint (coe : α → set β)`, where `set_like α β` -/
section coe_to_set
variables [set_like α β] (l : lower_adjoint (coe : α → set β))
lemma subset_closure (s : set β) : s ⊆ l s :=
l.le_closure s
lemma le_iff_subset (s : set β) (S : α) : l s ≤ S ↔ s ⊆ S :=
l.gc s S
lemma mem_iff (s : set β) (x : β) : x ∈ l s ↔ ∀ S : α, s ⊆ S → x ∈ S :=
by { simp_rw [←set_like.mem_coe, ←set.singleton_subset_iff, ←l.le_iff_subset],
exact ⟨λ h S, h.trans, λ h, h _ le_rfl⟩ }
lemma eq_of_le {s : set β} {S : α} (h₁ : s ⊆ S) (h₂ : S ≤ l s) : l s = S :=
((l.le_iff_subset _ _).2 h₁).antisymm h₂
lemma closure_union_closure_subset (x y : α) :
(l x : set β) ∪ (l y) ⊆ l (x ∪ y) :=
l.closure_sup_closure_le x y
@[simp] lemma closure_union_closure_left (x y : α) :
(l ((l x) ∪ y) : set β) = l (x ∪ y) :=
l.closure_sup_closure_left x y
@[simp] lemma closure_union_closure_right (x y : α) :
l (x ∪ (l y)) = l (x ∪ y) :=
set_like.coe_injective (l.closure_sup_closure_right x y)
@[simp] lemma closure_union_closure (x y : α) :
l ((l x) ∪ (l y)) = l (x ∪ y) :=
set_like.coe_injective (l.closure_operator.closure_sup_closure x y)
@[simp] lemma closure_Union_closure {ι : Type u} (x : ι → α) :
l (⋃ i, l (x i)) = l (⋃ i, x i) :=
set_like.coe_injective (l.closure_supr_closure (coe ∘ x))
@[simp] lemma closure_bUnion_closure (p : set β → Prop) :
l (⋃ x (H : p x), l x) = l (⋃ x (H : p x), x) :=
set_like.coe_injective (l.closure_bsupr_closure p)
end coe_to_set
end lower_adjoint
/-! ### Translations between `galois_connection`, `lower_adjoint`, `closure_operator` -/
variable {α}
/-- Every Galois connection induces a lower adjoint. -/
@[simps]
def galois_connection.lower_adjoint [preorder α] [preorder β] {l : α → β} {u : β → α}
(gc : galois_connection l u) :
lower_adjoint u :=
{ to_fun := l,
gc' := gc }
/-- Every Galois connection induces a closure operator given by the composition. This is the partial
order version of the statement that every adjunction induces a monad. -/
@[simps]
def galois_connection.closure_operator [partial_order α] [preorder β] {l : α → β} {u : β → α}
(gc : galois_connection l u) :
closure_operator α :=
gc.lower_adjoint.closure_operator
/-- The set of closed elements has a Galois insertion to the underlying type. -/
def closure_operator.gi [partial_order α] (c : closure_operator α) :
galois_insertion c.to_closed coe :=
{ choice := λ x hx, ⟨x, hx.antisymm (c.le_closure x)⟩,
gc := λ x y, (c.closure_le_closed_iff_le _ y.2),
le_l_u := λ x, c.le_closure _,
choice_eq := λ x hx, le_antisymm (c.le_closure x) hx }
/-- The Galois insertion associated to a closure operator can be used to reconstruct the closure
operator.
Note that the inverse in the opposite direction does not hold in general. -/
@[simp]
lemma closure_operator_gi_self [partial_order α] (c : closure_operator α) :
c.gi.gc.closure_operator = c :=
by { ext x, refl }
|
411022707ae3e45b51e12fea6347a3db5ebdfe51 | fe25de614feb5587799621c41487aaee0d083b08 | /src/Lean/Environment.lean | f845fbfa8d1e946000d2a7c157ea1dd07fe68f0f | [
"Apache-2.0"
] | permissive | pollend/lean4 | e8469c2f5fb8779b773618c3267883cf21fb9fac | c913886938c4b3b83238a3f99673c6c5a9cec270 | refs/heads/master | 1,687,973,251,481 | 1,628,039,739,000 | 1,628,039,739,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 33,974 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Std.Data.HashMap
import Lean.ImportingFlag
import Lean.Data.SMap
import Lean.Declaration
import Lean.LocalContext
import Lean.Util.Path
import Lean.Util.FindExpr
import Lean.Util.Profile
namespace Lean
/- Opaque environment extension state. -/
constant EnvExtensionStateSpec : PointedType.{0}
def EnvExtensionState : Type := EnvExtensionStateSpec.type
instance : Inhabited EnvExtensionState where
default := EnvExtensionStateSpec.val
def ModuleIdx := Nat
instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat)
abbrev ConstMap := SMap Name ConstantInfo
structure Import where
module : Name
runtimeOnly : Bool := false
instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩
/--
A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk.
Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean
files are compacted regions. -/
def CompactedRegion := USize
/-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/
@[extern 2 "lean_compacted_region_free"]
unsafe constant CompactedRegion.free : CompactedRegion → IO Unit
/- Environment fields that are not used often. -/
structure EnvironmentHeader where
trustLevel : UInt32 := 0
quotInit : Bool := false
mainModule : Name := arbitrary
imports : Array Import := #[] -- direct imports
regions : Array CompactedRegion := #[] -- compacted regions of all imported modules
moduleNames : Array Name := #[] -- names of all imported modules
deriving Inhabited
open Std (HashMap)
structure Environment where
const2ModIdx : HashMap Name ModuleIdx
constants : ConstMap
extensions : Array EnvExtensionState
header : EnvironmentHeader := {}
deriving Inhabited
namespace Environment
def addAux (env : Environment) (cinfo : ConstantInfo) : Environment :=
{ env with constants := env.constants.insert cinfo.name cinfo }
@[export lean_environment_find]
def find? (env : Environment) (n : Name) : Option ConstantInfo :=
/- It is safe to use `find'` because we never overwrite imported declarations. -/
env.constants.find?' n
def contains (env : Environment) (n : Name) : Bool :=
env.constants.contains n
def imports (env : Environment) : Array Import :=
env.header.imports
def allImportedModuleNames (env : Environment) : Array Name :=
env.header.moduleNames
@[export lean_environment_set_main_module]
def setMainModule (env : Environment) (m : Name) : Environment :=
{ env with header := { env.header with mainModule := m } }
@[export lean_environment_main_module]
def mainModule (env : Environment) : Name :=
env.header.mainModule
@[export lean_environment_mark_quot_init]
private def markQuotInit (env : Environment) : Environment :=
{ env with header := { env.header with quotInit := true } }
@[export lean_environment_quot_init]
private def isQuotInit (env : Environment) : Bool :=
env.header.quotInit
@[export lean_environment_trust_level]
private def getTrustLevel (env : Environment) : UInt32 :=
env.header.trustLevel
def getModuleIdxFor? (env : Environment) (c : Name) : Option ModuleIdx :=
env.const2ModIdx.find? c
def isConstructor (env : Environment) (c : Name) : Bool :=
match env.find? c with
| ConstantInfo.ctorInfo _ => true
| _ => false
end Environment
inductive KernelException where
| unknownConstant (env : Environment) (name : Name)
| alreadyDeclared (env : Environment) (name : Name)
| declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr)
| declHasMVars (env : Environment) (name : Name) (expr : Expr)
| declHasFVars (env : Environment) (name : Name) (expr : Expr)
| funExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr)
| exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr)
| appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr)
| invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr)
| other (msg : String)
namespace Environment
/- Type check given declaration and add it to the environment -/
@[extern "lean_add_decl"]
constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment
/- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/
@[extern "lean_compile_decl"]
constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment
def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do
let env ← addDecl env decl
compileDecl env opt decl
end Environment
/- Interface for managing environment extensions. -/
structure EnvExtensionInterface where
ext : Type → Type
inhabitedExt {σ} : Inhabited σ → Inhabited (ext σ)
registerExt {σ} (mkInitial : IO σ) : IO (ext σ)
setState {σ} (e : ext σ) (env : Environment) : σ → Environment
modifyState {σ} (e : ext σ) (env : Environment) : (σ → σ) → Environment
getState {σ} [Inhabited σ] (e : ext σ) (env : Environment) : σ
mkInitialExtStates : IO (Array EnvExtensionState)
ensureExtensionsSize : Environment → IO Environment
instance : Inhabited EnvExtensionInterface where
default := {
ext := id
inhabitedExt := id
ensureExtensionsSize := fun env => pure env
registerExt := fun mk => mk
setState := fun _ env _ => env
modifyState := fun _ env _ => env
getState := fun ext _ => ext
mkInitialExtStates := pure #[]
}
/- Unsafe implementation of `EnvExtensionInterface` -/
namespace EnvExtensionInterfaceUnsafe
structure Ext (σ : Type) where
idx : Nat
mkInitial : IO σ
deriving Inhabited
private builtin_initialize envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState)) ← IO.mkRef #[]
/--
User-defined environment extensions are declared using the `initialize` command.
This command is just syntax sugar for the `init` attribute.
When we `import` lean modules, the vector stored at `envExtensionsRef` may increase in size because of
user-defined environment extensions. When this happens, we must adjust the size of the `env.extensions`.
This method is invoked when processing `import`s.
-/
partial def ensureExtensionsArraySize (env : Environment) : IO Environment := do
loop env.extensions.size env
where
loop (i : Nat) (env : Environment) : IO Environment := do
let envExtensions ← envExtensionsRef.get
if h : i < envExtensions.size then
let s ← envExtensions[i].mkInitial
let env := { env with extensions := env.extensions.push s }
loop (i + 1) env
else
return env
private def invalidExtMsg := "invalid environment extension has been accessed"
unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment :=
if h : ext.idx < env.extensions.size then
{ env with extensions := env.extensions.set ⟨ext.idx, h⟩ (unsafeCast s) }
else
panic! invalidExtMsg
@[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment :=
if ext.idx < env.extensions.size then
{ env with
extensions := env.extensions.modify ext.idx fun s =>
let s : σ := unsafeCast s
let s : σ := f s
unsafeCast s }
else
panic! invalidExtMsg
unsafe def getState {σ} [Inhabited σ] (ext : Ext σ) (env : Environment) : σ :=
if h : ext.idx < env.extensions.size then
let s : EnvExtensionState := env.extensions.get ⟨ext.idx, h⟩
unsafeCast s
else
panic! invalidExtMsg
unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do
unless (← initializing) do
throw (IO.userError "failed to register environment, extensions can only be registered during initialization")
let exts ← envExtensionsRef.get
let idx := exts.size
let ext : Ext σ := {
idx := idx,
mkInitial := mkInitial,
}
envExtensionsRef.modify fun exts => exts.push (unsafeCast ext)
pure ext
def mkInitialExtStates : IO (Array EnvExtensionState) := do
let exts ← envExtensionsRef.get
exts.mapM fun ext => ext.mkInitial
unsafe def imp : EnvExtensionInterface := {
ext := Ext
ensureExtensionsSize := ensureExtensionsArraySize
inhabitedExt := fun _ => ⟨arbitrary⟩
registerExt := registerExt
setState := setState
modifyState := modifyState
getState := getState
mkInitialExtStates := mkInitialExtStates
}
end EnvExtensionInterfaceUnsafe
@[implementedBy EnvExtensionInterfaceUnsafe.imp]
constant EnvExtensionInterfaceImp : EnvExtensionInterface
def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ
private def ensureExtensionsArraySize (env : Environment) : IO Environment :=
EnvExtensionInterfaceImp.ensureExtensionsSize env
namespace EnvExtension
instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s
def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s
def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f
def getState {σ : Type} [Inhabited σ] (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env
end EnvExtension
/- Environment extensions can only be registered during initialization.
Reasons:
1- Our implementation assumes the number of extensions does not change after an environment object is created.
2- We do not use any synchronization primitive to access `envExtensionsRef`. -/
def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial
private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates
@[export lean_mk_empty_environment]
def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do
let initializing ← IO.initializing
if initializing then throw (IO.userError "environment objects cannot be created during initialization")
let exts ← mkInitialExtensionStates
pure {
const2ModIdx := {},
constants := {},
header := { trustLevel := trustLevel },
extensions := exts
}
structure PersistentEnvExtensionState (α : Type) (σ : Type) where
importedEntries : Array (Array α) -- entries per imported module
state : σ
structure ImportM.Context where
env : Environment
opts : Options
abbrev ImportM := ReaderT Lean.ImportM.Context IO
/- An environment extension with support for storing/retrieving entries from a .olean file.
- α is the type of the entries that are stored in .olean files.
- β is the type of values used to update the state.
- σ is the actual state.
Remark: for most extensions α and β coincide.
Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as
```
def addAlias (env : Environment) (a : Name) (e : Name) : Environment :=
aliasExtension.addEntry env (a, e)
```
without using `IO`. We have many functions like `addAlias`.
`α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example,
closures which we currently cannot store in files. -/
structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) where
toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ)
name : Name
addImportedFn : Array (Array α) → ImportM σ
addEntryFn : σ → β → σ
exportEntriesFn : σ → Array α
statsFn : σ → Format
/- Opaque persistent environment extension entry. -/
constant EnvExtensionEntrySpec : PointedType.{0}
def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type
instance : Inhabited EnvExtensionEntry := ⟨EnvExtensionEntrySpec.val⟩
instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) :=
⟨{importedEntries := #[], state := arbitrary }⟩
instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) where
default := {
toEnvExtension := arbitrary,
name := arbitrary,
addImportedFn := fun _ => arbitrary,
addEntryFn := fun s _ => s,
exportEntriesFn := fun _ => #[],
statsFn := fun _ => Format.nil
}
namespace PersistentEnvExtension
def getModuleEntries {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α :=
(ext.toEnvExtension.getState env).importedEntries.get! m
def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment :=
ext.toEnvExtension.modifyState env fun s =>
let state := ext.addEntryFn s.state b;
{ s with state := state }
def getState {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) : σ :=
(ext.toEnvExtension.getState env).state
def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment :=
ext.toEnvExtension.modifyState env $ fun ps => { ps with state := s }
def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment :=
ext.toEnvExtension.modifyState env $ fun ps => { ps with state := f (ps.state) }
end PersistentEnvExtension
builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[]
structure PersistentEnvExtensionDescr (α β σ : Type) where
name : Name
mkInitial : IO σ
addImportedFn : Array (Array α) → ImportM σ
addEntryFn : σ → β → σ
exportEntriesFn : σ → Array α
statsFn : σ → Format := fun _ => Format.nil
unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do
let pExts ← persistentEnvExtensionsRef.get
if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used")
let ext ← registerEnvExtension do
let initial ← descr.mkInitial
let s : PersistentEnvExtensionState α σ := {
importedEntries := #[],
state := initial
}
pure s
let pExt : PersistentEnvExtension α β σ := {
toEnvExtension := ext,
name := descr.name,
addImportedFn := descr.addImportedFn,
addEntryFn := descr.addEntryFn,
exportEntriesFn := descr.exportEntriesFn,
statsFn := descr.statsFn
}
persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt)
return pExt
@[implementedBy registerPersistentEnvExtensionUnsafe]
constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ)
/- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/
def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ)
@[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ :=
as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState
structure SimplePersistentEnvExtensionDescr (α σ : Type) where
name : Name
addEntryFn : σ → α → σ
addImportedFn : Array (Array α) → σ
toArrayFn : List α → Array α := fun es => es.toArray
def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) :=
registerPersistentEnvExtension {
name := descr.name,
mkInitial := pure ([], descr.addImportedFn #[]),
addImportedFn := fun as => pure ([], descr.addImportedFn as),
addEntryFn := fun s e => match s with
| (entries, s) => (e::entries, descr.addEntryFn s e),
exportEntriesFn := fun s => descr.toArrayFn s.1.reverse,
statsFn := fun s => format "number of local entries: " ++ format s.1.length
}
namespace SimplePersistentEnvExtension
instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) :=
inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ)))
def getEntries {α σ : Type} [Inhabited σ] (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α :=
(PersistentEnvExtension.getState ext env).1
def getState {α σ : Type} [Inhabited σ] (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ :=
(PersistentEnvExtension.getState ext env).2
def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s))
def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s))
end SimplePersistentEnvExtension
/-- Environment extension for tagging declarations.
Declarations must only be tagged in the module where they were declared. -/
def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet
def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension :=
registerSimplePersistentEnvExtension {
name := name,
addImportedFn := fun as => {},
addEntryFn := fun s n => s.insert n,
toArrayFn := fun es => es.toArray.qsort Name.quickLt
}
namespace TagDeclarationExtension
instance : Inhabited TagDeclarationExtension :=
inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet))
def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment :=
ext.addEntry env n
def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool :=
match env.getModuleIdxFor? n with
| some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt
| none => (ext.getState env).contains n
end TagDeclarationExtension
/-- Environment extension for mapping declarations to values. -/
def MapDeclarationExtension (α : Type) := SimplePersistentEnvExtension (Name × α) (NameMap α)
def mkMapDeclarationExtension [Inhabited α] (name : Name) : IO (MapDeclarationExtension α) :=
registerSimplePersistentEnvExtension {
name := name,
addImportedFn := fun as => {},
addEntryFn := fun s n => s.insert n.1 n.2 ,
toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1)
}
namespace MapDeclarationExtension
instance : Inhabited (MapDeclarationExtension α) :=
inferInstanceAs (Inhabited (SimplePersistentEnvExtension ..))
def insert (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) (val : α) : Environment :=
ext.addEntry env (declName, val)
def find? [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Option α :=
match env.getModuleIdxFor? declName with
| some modIdx =>
match (ext.getModuleEntries env modIdx).binSearch (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) with
| some e => some e.2
| none => none
| none => (ext.getState env).find? declName
def contains [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Bool :=
match env.getModuleIdxFor? declName with
| some modIdx => (ext.getModuleEntries env modIdx).binSearchContains (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1)
| none => (ext.getState env).contains declName
end MapDeclarationExtension
/- Content of a .olean file.
We use `compact.cpp` to generate the image of this object in disk. -/
structure ModuleData where
imports : Array Import
constants : Array ConstantInfo
entries : Array (Name × Array EnvExtensionEntry)
instance : Inhabited ModuleData :=
⟨{imports := arbitrary, constants := arbitrary, entries := arbitrary }⟩
@[extern 3 "lean_save_module_data"]
constant saveModuleData (fname : @& System.FilePath) (m : ModuleData) : IO Unit
@[extern 2 "lean_read_module_data"]
constant readModuleData (fname : @& System.FilePath) : IO (ModuleData × CompactedRegion)
/--
Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in
particular, `env` should be the last reference to any `Environment` derived from these imports. -/
@[noinline, export lean_environment_free_regions]
unsafe def Environment.freeRegions (env : Environment) : IO Unit :=
/-
NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field.
Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in
compacted regions, is freed after the regions.
In the currently produced IR, we indeed see:
```
def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj :=
let x_3 : obj := proj[3] x_1;
inc x_3;
dec x_1;
...
```
TODO: statically check for this. -/
env.header.regions.forM CompactedRegion.free
def mkModuleData (env : Environment) : IO ModuleData := do
let pExts ← persistentEnvExtensionsRef.get
let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold
(fun i result =>
let state := (pExts.get! i).getState env
let exportEntriesFn := (pExts.get! i).exportEntriesFn
let extName := (pExts.get! i).name
result.push (extName, exportEntriesFn state))
#[]
pure {
imports := env.header.imports,
constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[],
entries := entries
}
@[export lean_write_module]
def writeModule (env : Environment) (fname : System.FilePath) : IO Unit := do
let modData ← mkModuleData env; saveModuleData fname modData
private partial def getEntriesFor (mod : ModuleData) (extId : Name) (i : Nat) : Array EnvExtensionEntry :=
if i < mod.entries.size then
let curr := mod.entries.get! i;
if curr.1 == extId then curr.2 else getEntriesFor mod extId (i+1)
else
#[]
private def setImportedEntries (env : Environment) (mods : Array ModuleData) (startingAt : Nat := 0) : IO Environment := do
let mut env := env
let pExtDescrs ← persistentEnvExtensionsRef.get
for mod in mods do
for extDescr in pExtDescrs[startingAt:] do
let entries := getEntriesFor mod extDescr.name 0
env ← extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.push entries }
return env
/-
"Forward declaration" needed for updating the attribute table with user-defined attributes.
User-defined attributes are declared using the `initialize` command. The `initialize` command is just syntax sugar for the `init` attribute.
The `init` attribute is initialized after the `attributeExtension` is initialized. We cannot change the order since the `init` attribute is an attribute,
and requires this extension.
The `attributeExtension` initializer uses `attributeMapRef` to initialize the attribute mapping.
When we a new user-defined attribute declaration is imported, `attributeMapRef` is updated.
Later, we set this method with code that adds the user-defined attributes that were imported after we initialized `attributeExtension`.
-/
builtin_initialize updateEnvAttributesRef : IO.Ref (Environment → IO Environment) ← IO.mkRef (fun env => pure env)
private partial def finalizePersistentExtensions (env : Environment) (mods : Array ModuleData) (opts : Options) : IO Environment := do
loop 0 env
where
loop (i : Nat) (env : Environment) : IO Environment := do
-- Recall that the size of the array stored `persistentEnvExtensionRef` may increase when we import user-defined environment extensions.
let pExtDescrs ← persistentEnvExtensionsRef.get
if h : i < pExtDescrs.size then
let extDescr := pExtDescrs[i]
let s := extDescr.toEnvExtension.getState env
let prevSize := (← persistentEnvExtensionsRef.get).size
let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts }
let mut env ← extDescr.toEnvExtension.setState env { s with state := newState }
env ← ensureExtensionsArraySize env
if (← persistentEnvExtensionsRef.get).size > prevSize then
-- This branch is executed when `pExtDescrs[i]` is the extension associated with the `init` attribute, and
-- a user-defined persistent extension is imported.
-- Thus, we invoke `setImportedEntries` to update the array `importedEntries` with the entries for the new extensions.
env ← setImportedEntries env mods prevSize
-- See comment at `updateEnvAttributesRef`
env ← (← updateEnvAttributesRef.get) env
loop (i + 1) env
else
return env
structure ImportState where
moduleNameSet : NameSet := {}
moduleNames : Array Name := #[]
moduleData : Array ModuleData := #[]
regions : Array CompactedRegion := #[]
@[export lean_import_modules]
partial def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" opts do
withImporting do
let (_, s) ← importMods imports |>.run {}
let mut numConsts := 0
for mod in s.moduleData do
numConsts := numConsts + mod.constants.size
-- (moduleNames, mods, regions)
let mut modIdx : Nat := 0
let mut const2ModIdx : HashMap Name ModuleIdx := Std.mkHashMap (nbuckets := numConsts)
let mut constantMap : HashMap Name ConstantInfo := Std.mkHashMap (nbuckets := numConsts)
for mod in s.moduleData do
for cinfo in mod.constants do
const2ModIdx := const2ModIdx.insert cinfo.name modIdx
match constantMap.insert' cinfo.name cinfo with
| (constantMap', replaced) =>
constantMap := constantMap'
if replaced then throw (IO.userError s!"import failed, environment already contains '{cinfo.name}'")
modIdx := modIdx + 1
let constants : ConstMap := SMap.fromHashMap constantMap false
let exts ← mkInitialExtensionStates
let env : Environment := {
const2ModIdx := const2ModIdx,
constants := constants,
extensions := exts,
header := {
quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module
trustLevel := trustLevel,
imports := imports.toArray,
regions := s.regions,
moduleNames := s.moduleNames
}
}
let env ← setImportedEntries env s.moduleData
let env ← finalizePersistentExtensions env s.moduleData opts
pure env
where
importMods : List Import → StateRefT ImportState IO Unit
| [] => pure ()
| i::is => do
if i.runtimeOnly || (← get).moduleNameSet.contains i.module then
importMods is
else do
modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module }
let mFile ← findOLean i.module
unless (← mFile.pathExists) do
throw $ IO.userError s!"object file '{mFile}' of module {i.module} does not exist"
let (mod, region) ← readModuleData mFile
importMods mod.imports.toList
modify fun s => { s with
moduleData := s.moduleData.push mod
regions := s.regions.push region
moduleNames := s.moduleNames.push i.module
}
importMods is
/--
Create environment object from imports and free compacted regions after calling `act`. No live references to the
environment object or imported objects may exist after `act` finishes. -/
unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do
let env ← importModules imports opts trustLevel
try x env finally env.freeRegions
builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSSet ←
registerSimplePersistentEnvExtension {
name := `namespaces,
addImportedFn := fun as => mkStateFromImportedEntries NameSSet.insert NameSSet.empty as |>.switch,
addEntryFn := fun s n => s.insert n
}
namespace Environment
def registerNamespace (env : Environment) (n : Name) : Environment :=
if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n
def isNamespace (env : Environment) (n : Name) : Bool :=
(namespacesExt.getState env).contains n
def getNamespaceSet (env : Environment) : NameSSet :=
namespacesExt.getState env
private def isNamespaceName : Name → Bool
| Name.str Name.anonymous _ _ => true
| Name.str p _ _ => isNamespaceName p
| _ => false
private def registerNamePrefixes : Environment → Name → Environment
| env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env
| env, _ => env
@[export lean_environment_add]
def add (env : Environment) (cinfo : ConstantInfo) : Environment :=
let env := registerNamePrefixes env cinfo.name
env.addAux cinfo
@[export lean_display_stats]
def displayStats (env : Environment) : IO Unit := do
let pExtDescrs ← persistentEnvExtensionsRef.get
let numModules := ((pExtDescrs.get! 0).toEnvExtension.getState env).importedEntries.size;
IO.println ("direct imports: " ++ toString env.header.imports);
IO.println ("number of imported modules: " ++ toString numModules);
IO.println ("number of consts: " ++ toString env.constants.size);
IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1);
IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2);
IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets);
IO.println ("trust level: " ++ toString env.header.trustLevel);
IO.println ("number of extensions: " ++ toString env.extensions.size);
pExtDescrs.forM $ fun extDescr => do
IO.println ("extension '" ++ toString extDescr.name ++ "'")
let s := extDescr.toEnvExtension.getState env
let fmt := extDescr.statsFn s.state
unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state)))
IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0))
@[extern "lean_eval_const"]
unsafe constant evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α
private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α :=
throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected")
/-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`.
This function is still unsafe because it cannot guarantee that `typeName` is in fact the name of the type `α`. -/
unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α :=
match env.find? constName with
| none => throw ("unknown constant '" ++ toString constName ++ "'")
| some info =>
match info.type with
| Expr.const c _ _ =>
if c != typeName then throwUnexpectedType typeName constName
else env.evalConst α opts constName
| _ => throwUnexpectedType typeName constName
def hasUnsafe (env : Environment) (e : Expr) : Bool :=
let c? := e.find? $ fun e => match e with
| Expr.const c _ _ =>
match env.find? c with
| some cinfo => cinfo.isUnsafe
| none => false
| _ => false;
c?.isSome
end Environment
namespace Kernel
/- Kernel API -/
/--
Kernel isDefEq predicate. We use it mainly for debugging purposes.
Recall that the Kernel type checker does not support metavariables.
When implementing automation, consider using the `MetaM` methods. -/
@[extern "lean_kernel_is_def_eq"]
constant isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool
/--
Kernel WHNF function. We use it mainly for debugging purposes.
Recall that the Kernel type checker does not support metavariables.
When implementing automation, consider using the `MetaM` methods. -/
@[extern "lean_kernel_whnf"]
constant whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Expr
end Kernel
class MonadEnv (m : Type → Type) where
getEnv : m Environment
modifyEnv : (Environment → Environment) → m Unit
export MonadEnv (getEnv modifyEnv)
instance (m n) [MonadLift m n] [MonadEnv m] : MonadEnv n where
getEnv := liftM (getEnv : m Environment)
modifyEnv := fun f => liftM (modifyEnv f : m Unit)
end Lean
|
8533bae81aa45829306fb2cf9a2cbd365c3a7785 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/monad/adjunction.lean | 8f2ee003612a8e2ba18886dbe4e9764942237879 | [
"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 | 8,782 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.adjunction.reflective
import category_theory.monad.algebra
/-!
# Adjunctions and monads
We develop the basic relationship between adjunctions and monads.
Given an adjunction `h : L ⊣ R`, we have `h.to_monad : monad C` and `h.to_comonad : comonad D`.
We then have
`monad.comparison (h : L ⊣ R) : D ⥤ h.to_monad.algebra`
sending `Y : D` to the Eilenberg-Moore algebra for `L ⋙ R` with underlying object `R.obj X`,
and dually `comonad.comparison`.
We say `R : D ⥤ C` is `monadic_right_adjoint`, if it is a right adjoint and its `monad.comparison`
is an equivalence of categories. (Similarly for `monadic_left_adjoint`.)
Finally we prove that reflective functors are `monadic_right_adjoint`.
-/
namespace category_theory
open category
universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes].
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
variables {L : C ⥤ D} {R : D ⥤ C}
namespace adjunction
/--
For a pair of functors `L : C ⥤ D`, `R : D ⥤ C`, an adjunction `h : L ⊣ R` induces a monad on
the category `C`.
-/
@[simps]
def to_monad (h : L ⊣ R) : monad C :=
{ to_functor := L ⋙ R,
η' := h.unit,
μ' := whisker_right (whisker_left L h.counit) R,
assoc' := λ X, by { dsimp, rw [←R.map_comp], simp },
right_unit' := λ X, by { dsimp, rw [←R.map_comp], simp } }
/--
For a pair of functors `L : C ⥤ D`, `R : D ⥤ C`, an adjunction `h : L ⊣ R` induces a comonad on
the category `D`.
-/
@[simps]
def to_comonad (h : L ⊣ R) : comonad D :=
{ to_functor := R ⋙ L,
ε' := h.counit,
δ' := whisker_right (whisker_left R h.unit) L,
coassoc' := λ X, by { dsimp, rw ← L.map_comp, simp },
right_counit' := λ X, by { dsimp, rw ← L.map_comp, simp } }
/-- The monad induced by the Eilenberg-Moore adjunction is the original monad. -/
@[simps]
def adj_to_monad_iso (T : monad C) : T.adj.to_monad ≅ T :=
monad_iso.mk (nat_iso.of_components (λ X, iso.refl _) (by tidy))
(λ X, by { dsimp, simp })
(λ X, by { dsimp, simp })
/-- The comonad induced by the Eilenberg-Moore adjunction is the original comonad. -/
@[simps]
def adj_to_comonad_iso (G : comonad C) : G.adj.to_comonad ≅ G :=
comonad_iso.mk (nat_iso.of_components (λ X, iso.refl _) (by tidy))
(λ X, by { dsimp, simp })
(λ X, by { dsimp, simp })
end adjunction
/--
Gven any adjunction `L ⊣ R`, there is a comparison functor `category_theory.monad.comparison R`
sending objects `Y : D` to Eilenberg-Moore algebras for `L ⋙ R` with underlying object `R.obj X`.
We later show that this is full when `R` is full, faithful when `R` is faithful,
and essentially surjective when `R` is reflective.
-/
@[simps]
def monad.comparison (h : L ⊣ R) : D ⥤ h.to_monad.algebra :=
{ obj := λ X,
{ A := R.obj X,
a := R.map (h.counit.app X),
assoc' := by { dsimp, rw [← R.map_comp, ← adjunction.counit_naturality, R.map_comp], refl } },
map := λ X Y f,
{ f := R.map f,
h' := by { dsimp, rw [← R.map_comp, adjunction.counit_naturality, R.map_comp] } } }.
/--
The underlying object of `(monad.comparison R).obj X` is just `R.obj X`.
-/
@[simps]
def monad.comparison_forget (h : L ⊣ R) :
monad.comparison h ⋙ h.to_monad.forget ≅ R :=
{ hom := { app := λ X, 𝟙 _, },
inv := { app := λ X, 𝟙 _, } }
lemma monad.left_comparison (h : L ⊣ R) : L ⋙ monad.comparison h = h.to_monad.free := rfl
instance [faithful R] (h : L ⊣ R) :
faithful (monad.comparison h) :=
{ map_injective' := λ X Y f g w, R.map_injective (congr_arg monad.algebra.hom.f w : _) }
instance (T : monad C) : full (monad.comparison T.adj) :=
{ preimage := λ X Y f, ⟨f.f, by simpa using f.h⟩ }
instance (T : monad C) : ess_surj (monad.comparison T.adj) :=
{ mem_ess_image := λ X,
⟨{ A := X.A, a := X.a, unit' := by simpa using X.unit, assoc' := by simpa using X.assoc },
⟨monad.algebra.iso_mk (iso.refl _) (by simp)⟩⟩ }
/--
Gven any adjunction `L ⊣ R`, there is a comparison functor `category_theory.comonad.comparison L`
sending objects `X : C` to Eilenberg-Moore coalgebras for `L ⋙ R` with underlying object
`L.obj X`.
-/
@[simps]
def comonad.comparison (h : L ⊣ R) : C ⥤ h.to_comonad.coalgebra :=
{ obj := λ X,
{ A := L.obj X,
a := L.map (h.unit.app X),
coassoc' := by { dsimp, rw [← L.map_comp, ← adjunction.unit_naturality, L.map_comp], refl } },
map := λ X Y f,
{ f := L.map f,
h' := by { dsimp, rw ← L.map_comp, simp } } }
/--
The underlying object of `(comonad.comparison L).obj X` is just `L.obj X`.
-/
@[simps]
def comonad.comparison_forget {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) :
comonad.comparison h ⋙ h.to_comonad.forget ≅ L :=
{ hom := { app := λ X, 𝟙 _, },
inv := { app := λ X, 𝟙 _, } }
lemma comonad.left_comparison (h : L ⊣ R) : R ⋙ comonad.comparison h = h.to_comonad.cofree := rfl
instance comonad.comparison_faithful_of_faithful [faithful L] (h : L ⊣ R) :
faithful (comonad.comparison h) :=
{ map_injective' := λ X Y f g w, L.map_injective (congr_arg comonad.coalgebra.hom.f w : _) }
instance (G : comonad C) : full (comonad.comparison G.adj) :=
{ preimage := λ X Y f, ⟨f.f, by simpa using f.h⟩ }
instance (G : comonad C) : ess_surj (comonad.comparison G.adj) :=
{ mem_ess_image := λ X,
⟨{ A := X.A, a := X.a, counit' := by simpa using X.counit, coassoc' := by simpa using X.coassoc },
⟨comonad.coalgebra.iso_mk (iso.refl _) (by simp)⟩⟩ }
/--
A right adjoint functor `R : D ⥤ C` is *monadic* if the comparison functor `monad.comparison R`
from `D` to the category of Eilenberg-Moore algebras for the adjunction is an equivalence.
-/
class monadic_right_adjoint (R : D ⥤ C) extends is_right_adjoint R :=
(eqv : is_equivalence (monad.comparison (adjunction.of_right_adjoint R)))
/--
A left adjoint functor `L : C ⥤ D` is *comonadic* if the comparison functor `comonad.comparison L`
from `C` to the category of Eilenberg-Moore algebras for the adjunction is an equivalence.
-/
class comonadic_left_adjoint (L : C ⥤ D) extends is_left_adjoint L :=
(eqv : is_equivalence (comonad.comparison (adjunction.of_left_adjoint L)))
noncomputable instance (T : monad C) : monadic_right_adjoint T.forget :=
⟨(equivalence.of_fully_faithfully_ess_surj _ : is_equivalence (monad.comparison T.adj))⟩
noncomputable instance (G : comonad C) : comonadic_left_adjoint G.forget :=
⟨(equivalence.of_fully_faithfully_ess_surj _ : is_equivalence (comonad.comparison G.adj))⟩
-- TODO: This holds more generally for idempotent adjunctions, not just reflective adjunctions.
instance μ_iso_of_reflective [reflective R] : is_iso (adjunction.of_right_adjoint R).to_monad.μ :=
by { dsimp, apply_instance }
attribute [instance] monadic_right_adjoint.eqv
attribute [instance] comonadic_left_adjoint.eqv
namespace reflective
instance [reflective R] (X : (adjunction.of_right_adjoint R).to_monad.algebra) :
is_iso ((adjunction.of_right_adjoint R).unit.app X.A) :=
⟨⟨X.a, ⟨X.unit, begin
dsimp only [functor.id_obj],
rw ← (adjunction.of_right_adjoint R).unit_naturality,
dsimp only [functor.comp_obj, adjunction.to_monad_coe],
rw [unit_obj_eq_map_unit, ←functor.map_comp, ←functor.map_comp],
erw X.unit,
simp,
end⟩⟩⟩
instance comparison_ess_surj [reflective R] :
ess_surj (monad.comparison (adjunction.of_right_adjoint R)) :=
begin
refine ⟨λ X, ⟨(left_adjoint R).obj X.A, ⟨_⟩⟩⟩,
symmetry,
refine monad.algebra.iso_mk _ _,
{ exact as_iso ((adjunction.of_right_adjoint R).unit.app X.A) },
dsimp only [functor.comp_map, monad.comparison_obj_a, as_iso_hom, functor.comp_obj,
monad.comparison_obj_A, monad_to_functor_eq_coe, adjunction.to_monad_coe],
rw [←cancel_epi ((adjunction.of_right_adjoint R).unit.app X.A), adjunction.unit_naturality_assoc,
adjunction.right_triangle_components, comp_id],
apply (X.unit_assoc _).symm,
end
instance comparison_full [full R] [is_right_adjoint R] :
full (monad.comparison (adjunction.of_right_adjoint R)) :=
{ preimage := λ X Y f, R.preimage f.f }
end reflective
-- It is possible to do this computably since the construction gives the data of the inverse, not
-- just the existence of an inverse on each object.
/-- Any reflective inclusion has a monadic right adjoint.
cf Prop 5.3.3 of [Riehl][riehl2017] -/
@[priority 100] -- see Note [lower instance priority]
noncomputable instance monadic_of_reflective [reflective R] : monadic_right_adjoint R :=
{ eqv := equivalence.of_fully_faithfully_ess_surj _ }
end category_theory
|
5f5e1945bd04966e05c66eeec3f601331a8f4d2a | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/init/algebra/field.lean | 2499816ee447d58164829dc791b4329b616d2efa | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 18,531 | lean | /-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis, Leonardo de Moura
Structures with multiplicative and additive components, including division rings and fields.
The development is modeled after Isabelle's library.
-/
prelude
import init.algebra.ring
universe u
/- Make sure instances defined in this file have lower priority than the ones
defined for concrete structures -/
set_option default_priority 100
set_option old_structure_cmd true
class division_ring (α : Type u) extends ring α, has_inv α, zero_ne_one_class α :=
(mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1)
(inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1)
variable {α : Type u}
section division_ring
variables [division_ring α]
protected definition algebra.div (a b : α) : α :=
a * b⁻¹
instance division_ring_has_div : has_div α :=
⟨algebra.div⟩
lemma division_def (a b : α) : a / b = a * b⁻¹ :=
rfl
@[simp]
lemma mul_inv_cancel {a : α} (h : a ≠ 0) : a * a⁻¹ = 1 :=
division_ring.mul_inv_cancel h
@[simp]
lemma inv_mul_cancel {a : α} (h : a ≠ 0) : a⁻¹ * a = 1 :=
division_ring.inv_mul_cancel h
@[simp]
lemma one_div_eq_inv (a : α) : 1 / a = a⁻¹ :=
one_mul a⁻¹
lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a :=
by simp
local attribute [simp]
division_def mul_comm mul_assoc
mul_left_comm mul_inv_cancel inv_mul_cancel
lemma div_eq_mul_one_div (a b : α) : a / b = a * (1 / b) :=
by simp
lemma mul_one_div_cancel {a : α} (h : a ≠ 0) : a * (1 / a) = 1 :=
by simp [h]
lemma one_div_mul_cancel {a : α} (h : a ≠ 0) : (1 / a) * a = 1 :=
by simp [h]
lemma div_self {a : α} (h : a ≠ 0) : a / a = 1 :=
by simp [h]
lemma one_div_one : 1 / 1 = (1:α) :=
div_self (ne.symm zero_ne_one)
lemma mul_div_assoc (a b c : α) : (a * b) / c = a * (b / c) :=
by simp
lemma one_div_ne_zero {a : α} (h : a ≠ 0) : 1 / a ≠ 0 :=
assume : 1 / a = 0,
have 0 = (1:α), from eq.symm (by rw [← mul_one_div_cancel h, this, mul_zero]),
absurd this zero_ne_one
lemma inv_ne_zero {a : α} (h : a ≠ 0) : a⁻¹ ≠ 0 :=
by rw inv_eq_one_div; exact one_div_ne_zero h
lemma one_inv_eq : 1⁻¹ = (1:α) :=
calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul]
... = (1:α) : by simp
local attribute [simp] one_inv_eq
lemma div_one (a : α) : a / 1 = a :=
by simp
lemma zero_div (a : α) : 0 / a = 0 :=
by simp
-- note: integral domain has a "mul_ne_zero". α commutative division ring is an integral
-- domain, but let's not define that class for now.
lemma division_ring.mul_ne_zero {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 :=
assume : a * b = 0,
have a * 1 = 0, by rw [← mul_one_div_cancel hb, ← mul_assoc, this, zero_mul],
have a = 0, by rwa mul_one at this,
absurd this ha
lemma mul_ne_zero_comm {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 :=
have h₁ : a ≠ 0, from ne_zero_of_mul_ne_zero_right h,
have h₂ : b ≠ 0, from ne_zero_of_mul_ne_zero_left h,
division_ring.mul_ne_zero h₂ h₁
lemma eq_one_div_of_mul_eq_one {a b : α} (h : a * b = 1) : b = 1 / a :=
have a ≠ 0, from
assume : a = 0,
have 0 = (1:α), by rwa [this, zero_mul] at h,
absurd this zero_ne_one,
have b = (1 / a) * a * b, by rw [one_div_mul_cancel this, one_mul],
show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this
lemma eq_one_div_of_mul_eq_one_left {a b : α} (h : b * a = 1) : b = 1 / a :=
have a ≠ 0, from
assume : a = 0,
have 0 = (1:α), by rwa [this, mul_zero] at h,
absurd this zero_ne_one,
by rw [← h, mul_div_assoc, div_self this, mul_one]
lemma division_ring.one_div_mul_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (b * a) :=
have (b * a) * ((1 / a) * (1 / b)) = 1,
by rw [mul_assoc, ← mul_assoc a, mul_one_div_cancel ha, one_mul, mul_one_div_cancel hb],
eq_one_div_of_mul_eq_one this
lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 :=
have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul],
eq.symm (eq_one_div_of_mul_eq_one this)
lemma division_ring.one_div_neg_eq_neg_one_div {a : α} (h : a ≠ 0) : 1 / (- a) = - (1 / a) :=
have -1 ≠ (0:α), from
(assume : -1 = 0, absurd (eq.symm (calc
1 = -(-1) : (neg_neg (1:α)).symm
... = -0 : by rw this
... = (0:α) : neg_zero)) zero_ne_one),
calc
1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul
... = (1 / a) * (1 / (- 1)) : by rw (division_ring.one_div_mul_one_div h this)
... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one
... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one]
lemma div_neg_eq_neg_div {a : α} (b : α) (ha : a ≠ 0) : b / (- a) = - (b / a) :=
calc
b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def]
... = b * -(1 / a) : by rw (division_ring.one_div_neg_eq_neg_one_div ha)
... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg
... = - (b * a⁻¹) : by rw inv_eq_one_div
lemma neg_div (a b : α) : (-b) / a = - (b / a) :=
by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul]
lemma division_ring.neg_div_neg_eq (a : α) {b : α} (hb : b ≠ 0) : (-a) / (-b) = a / b :=
by rw [(div_neg_eq_neg_div _ hb), neg_div, neg_neg]
lemma division_ring.one_div_one_div {a : α} (h : a ≠ 0) : 1 / (1 / a) = a :=
eq.symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel h))
lemma division_ring.inv_inv {a : α} (h : a ≠ 0) : a⁻¹⁻¹ = a :=
by rw [inv_eq_one_div, inv_eq_one_div, division_ring.one_div_one_div h]
lemma division_ring.eq_of_one_div_eq_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : 1 / a = 1 / b) : a = b :=
by rw [← division_ring.one_div_one_div ha, h, (division_ring.one_div_one_div hb)]
lemma mul_inv_eq {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (b * a)⁻¹ = a⁻¹ * b⁻¹ :=
eq.symm $ calc
a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by simp
... = (1 / (b * a)) : division_ring.one_div_mul_one_div ha hb
... = (b * a)⁻¹ : by simp
lemma division_ring.one_div_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / (a / b) = b / a :=
by rw [one_div_eq_inv, division_def, mul_inv_eq (inv_ne_zero hb) ha,
division_ring.inv_inv hb, division_def]
lemma mul_div_cancel (a : α) {b : α} (hb : b ≠ 0) : a * b / b = a :=
by simp [hb]
lemma div_mul_cancel (a : α) {b : α} (hb : b ≠ 0) : a / b * b = a :=
by simp [hb]
lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (c⁻¹)
lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c :=
by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg]
lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) :
(1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b :=
by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul,
mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm]
lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) :
(1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b :=
by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib,
one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one]
lemma div_eq_one_iff_eq (a : α) {b : α} (hb : b ≠ 0) : a / b = 1 ↔ a = b :=
iff.intro
(assume : a / b = 1, calc
a = a / b * b : by simp [hb]
... = 1 * b : by rw this
... = b : by simp)
(assume : a = b, by simp [this, hb])
lemma eq_of_div_eq_one (a : α) {b : α} (Hb : b ≠ 0) : a / b = 1 → a = b :=
iff.mp $ div_eq_one_iff_eq a Hb
lemma eq_div_iff_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a = b / c ↔ a * c = b :=
iff.intro
(assume : a = b / c, by rw [this, (div_mul_cancel _ hc)])
(assume : a * c = b, by rw [← this, mul_div_cancel _ hc])
lemma eq_div_of_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a * c = b → a = b / c :=
iff.mpr $ eq_div_iff_mul_eq a b hc
lemma mul_eq_of_eq_div (a b: α) {c : α} (hc : c ≠ 0) : a = b / c → a * c = b :=
iff.mp $ eq_div_iff_mul_eq a b hc
lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c :=
have (a + b / c) * c = a * c + b, by rw [right_distrib, (div_mul_cancel _ hc)],
(iff.mpr (eq_div_iff_mul_eq _ _ hc)) this
lemma mul_mul_div (a : α) {c : α} (hc : c ≠ 0) : a = a * c * (1 / c) :=
by simp [hc]
end division_ring
class field (α : Type u) extends division_ring α, comm_ring α
section field
variable [field α]
lemma field.one_div_mul_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rw [(division_ring.one_div_mul_one_div ha hb), mul_comm b]
lemma field.div_mul_right {a b : α} (hb : b ≠ 0) (h : a * b ≠ 0) : a / (a * b) = 1 / b :=
have a ≠ 0, from ne_zero_of_mul_ne_zero_right h,
eq.symm (calc
1 / b = a * ((1 / a) * (1 / b)) : by rw [← mul_assoc, mul_one_div_cancel this, one_mul]
... = a * (1 / (b * a)) : by rw (division_ring.one_div_mul_one_div this hb)
... = a * (a * b)⁻¹ : by rw [inv_eq_one_div, mul_comm a b])
lemma field.div_mul_left {a b : α} (ha : a ≠ 0) (h : a * b ≠ 0) : b / (a * b) = 1 / a :=
have b * a ≠ 0, from mul_ne_zero_comm h,
by rw [mul_comm a, (field.div_mul_right ha this)]
lemma mul_div_cancel_left {a : α} (b : α) (ha : a ≠ 0) : a * b / a = b :=
by rw [mul_comm a, (mul_div_cancel _ ha)]
lemma mul_div_cancel' (a : α) {b : α} (hb : b ≠ 0) : b * (a / b) = a :=
by rw [mul_comm, (div_mul_cancel _ hb)]
lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) :=
have a * b ≠ 0, from (division_ring.mul_ne_zero ha hb),
by rw [add_comm, ← field.div_mul_left ha this, ← field.div_mul_right hb this,
division_def, division_def, division_def, ← right_distrib]
local attribute [simp] mul_assoc mul_comm mul_left_comm
lemma field.div_mul_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) :
(a / b) * (c / d) = (a * c) / (b * d) :=
begin simp [division_def], rw [mul_inv_eq hd hb, mul_comm d⁻¹] end
lemma mul_div_mul_left (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) :
(c * a) / (c * b) = a / b :=
by rw [← field.div_mul_div _ _ hc hb, div_self hc, one_mul]
lemma mul_div_mul_right (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) :
(a * c) / (b * c) = a / b :=
by rw [mul_comm a, mul_comm b, mul_div_mul_left _ hb hc]
lemma div_mul_eq_mul_div (a b c : α) : (b / c) * a = (b * a) / c :=
by simp [division_def]
lemma field.div_mul_eq_mul_div_comm (a b : α) {c : α} (hc : c ≠ 0) :
(b / c) * a = b * (a / c) :=
by rw [div_mul_eq_mul_div, ← one_mul c, ← field.div_mul_div _ _ (ne.symm zero_ne_one) hc,
div_one, one_mul]
lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) :
(a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) :=
by rw [← mul_div_mul_right _ hb hd, ← mul_div_mul_left _ hd hb, div_add_div_same]
lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) :
(a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) :=
begin
simp [sub_eq_add_neg],
rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd,
← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul]
end
lemma mul_eq_mul_of_div_eq_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0)
(hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b :=
by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb,
← field.div_mul_eq_mul_div_comm _ _ hb, h, div_mul_eq_mul_div, div_mul_cancel _ hd]
lemma field.div_div_eq_mul_div (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) :
a / (b / c) = (a * c) / b :=
by rw [div_eq_mul_one_div, division_ring.one_div_div hb hc, ← mul_div_assoc]
lemma field.div_div_eq_div_mul (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) :
(a / b) / c = a / (b * c) :=
by rw [div_eq_mul_one_div, field.div_mul_div _ _ hb hc, mul_one]
lemma field.div_div_div_div_eq (a : α) {b c d : α} (hb : b ≠ 0) (hc : c ≠ 0) (hd : d ≠ 0) :
(a / b) / (c / d) = (a * d) / (b * c) :=
by rw [field.div_div_eq_mul_div _ hc hd, div_mul_eq_mul_div,
field.div_div_eq_div_mul _ hb hc]
lemma field.div_mul_eq_div_mul_one_div (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) :
a / (b * c) = (a / b) * (1 / c) :=
by rw [← field.div_div_eq_div_mul _ hb hc, ← div_eq_mul_one_div]
lemma eq_of_mul_eq_mul_of_nonzero_left {a b c : α} (h : a ≠ 0) (h₂ : a * b = a * c) : b = c :=
by rw [← one_mul b, ← div_self h, div_mul_eq_mul_div, h₂, mul_div_cancel_left _ h]
lemma eq_of_mul_eq_mul_of_nonzero_right {a b c : α} (h : c ≠ 0) (h2 : a * c = b * c) : a = b :=
by rw [← mul_one a, ← div_self h, ← mul_div_assoc, h2, mul_div_cancel _ h]
end field
class discrete_field (α : Type u) extends field α :=
(has_decidable_eq : decidable_eq α)
(inv_zero : inv zero = zero)
attribute [instance] discrete_field.has_decidable_eq
section discrete_field
variable [discrete_field α]
-- many of the lemmas in discrete_field are the same as lemmas in field or division ring,
-- but with fewer hypotheses since 0⁻¹ = 0 and equality is decidable.
lemma discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero
(a b : α) (h : a * b = 0) : a = 0 ∨ b = 0 :=
decidable.by_cases
(assume : a = 0, or.inl this)
(assume : a ≠ 0,
or.inr (by rw [← one_mul b, ← inv_mul_cancel this, mul_assoc, h, mul_zero]))
instance discrete_field.to_integral_domain [s : discrete_field α] : integral_domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero,
..s }
lemma inv_zero : 0⁻¹ = (0:α) :=
discrete_field.inv_zero α
lemma one_div_zero : 1 / 0 = (0:α) :=
calc
1 / 0 = (1:α) * 0⁻¹ : by rw division_def
... = 1 * 0 : by rw inv_zero
... = (0:α) : by rw mul_zero
lemma div_zero (a : α) : a / 0 = 0 :=
by rw [div_eq_mul_one_div, one_div_zero, mul_zero]
lemma ne_zero_of_one_div_ne_zero {a : α} (h : 1 / a ≠ 0) : a ≠ 0 :=
assume ha : a = 0, begin rw [ha, one_div_zero] at h, contradiction end
lemma eq_zero_of_one_div_eq_zero {a : α} (h : 1 / a = 0) : a = 0 :=
decidable.by_cases
(assume ha, ha)
(assume ha, false.elim ((one_div_ne_zero ha) h))
lemma one_div_mul_one_div' (a b : α) : (1 / a) * (1 / b) = 1 / (b * a) :=
decidable.by_cases
(assume : a = 0,
by rw [this, div_zero, zero_mul, mul_zero, div_zero])
(assume ha : a ≠ 0,
decidable.by_cases
(assume : b = 0,
by rw [this, div_zero, mul_zero, zero_mul, div_zero])
(assume : b ≠ 0, division_ring.one_div_mul_one_div ha this))
lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) :=
decidable.by_cases
(assume : a = 0, by rw [this, neg_zero, div_zero, neg_zero])
(assume : a ≠ 0, division_ring.one_div_neg_eq_neg_one_div this)
lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b :=
decidable.by_cases
(assume hb : b = 0, by rw [hb, neg_zero, div_zero, div_zero])
(assume hb : b ≠ 0, division_ring.neg_div_neg_eq _ hb)
lemma one_div_one_div (a : α) : 1 / (1 / a) = a :=
decidable.by_cases
(assume ha : a = 0, by rw [ha, div_zero, div_zero])
(assume ha : a ≠ 0, division_ring.one_div_one_div ha)
lemma eq_of_one_div_eq_one_div {a b : α} (h : 1 / a = 1 / b) : a = b :=
decidable.by_cases
(assume ha : a = 0,
have hb : b = 0, from eq_zero_of_one_div_eq_zero (by rw [← h, ha, div_zero]),
hb.symm ▸ ha)
(assume ha : a ≠ 0,
have hb : b ≠ 0, from ne_zero_of_one_div_ne_zero (h ▸ (one_div_ne_zero ha)),
division_ring.eq_of_one_div_eq_one_div ha hb h)
lemma mul_inv' (a b : α) : (b * a)⁻¹ = a⁻¹ * b⁻¹ :=
decidable.by_cases
(assume ha : a = 0, by rw [ha, mul_zero, inv_zero, zero_mul])
(assume ha : a ≠ 0,
decidable.by_cases
(assume hb : b = 0, by rw [hb, zero_mul, inv_zero, mul_zero])
(assume hb : b ≠ 0, mul_inv_eq ha hb))
-- the following are specifically for fields
lemma one_div_mul_one_div (a b : α) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rw [one_div_mul_one_div', mul_comm b]
lemma div_mul_right {a : α} (b : α) (ha : a ≠ 0) : a / (a * b) = 1 / b :=
decidable.by_cases
(assume hb : b = 0, by rw [hb, mul_zero, div_zero, div_zero])
(assume hb : b ≠ 0, field.div_mul_right hb (mul_ne_zero ha hb))
lemma div_mul_left (a : α) {b : α} (hb : b ≠ 0) : b / (a * b) = 1 / a :=
by rw [mul_comm a, div_mul_right _ hb]
lemma div_mul_div (a b c d : α) : (a / b) * (c / d) = (a * c) / (b * d) :=
decidable.by_cases
(assume hb : b = 0, by rw [hb, div_zero, zero_mul, zero_mul, div_zero])
(assume hb : b ≠ 0,
decidable.by_cases
(assume hd : d = 0, by rw [hd, div_zero, mul_zero, mul_zero, div_zero])
(assume hd : d ≠ 0, field.div_mul_div _ _ hb hd))
lemma mul_div_mul_left' (a b : α) {c : α} (hc : c ≠ 0) : (c * a) / (c * b) = a / b :=
decidable.by_cases
(assume hb : b = 0, by rw [hb, mul_zero, div_zero, div_zero])
(assume hb : b ≠ 0, mul_div_mul_left _ hb hc)
lemma mul_div_mul_right' (a b : α) {c : α} (hc : c ≠ 0) : (a * c) / (b * c) = a / b :=
by rw [mul_comm a, mul_comm b, (mul_div_mul_left' _ _ hc)]
lemma div_mul_eq_mul_div_comm (a b c : α) : (b / c) * a = b * (a / c) :=
decidable.by_cases
(assume hc : c = 0, by rw [hc, div_zero, zero_mul, div_zero, mul_zero])
(assume hc : c ≠ 0, field.div_mul_eq_mul_div_comm _ _ hc)
lemma one_div_div (a b : α) : 1 / (a / b) = b / a :=
decidable.by_cases
(assume ha : a = 0, by rw [ha, zero_div, div_zero, div_zero])
(assume ha : a ≠ 0,
decidable.by_cases
(assume hb : b = 0, by rw [hb, div_zero, zero_div, div_zero])
(assume hb : b ≠ 0, division_ring.one_div_div ha hb))
lemma div_div_eq_mul_div (a b c : α) : a / (b / c) = (a * c) / b :=
by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc]
lemma div_div_eq_div_mul (a b c : α) : (a / b) / c = a / (b * c) :=
by rw [div_eq_mul_one_div, div_mul_div, mul_one]
lemma div_div_div_div_eq (a b c d : α) : (a / b) / (c / d) = (a * d) / (b * c) :=
by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul]
lemma div_helper {a : α} (b : α) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b :=
by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h]
lemma div_mul_eq_div_mul_one_div (a b c : α) : a / (b * c) = (a / b) * (1 / c) :=
by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div]
end discrete_field
|
01c91a7f9cbbbaaf662f6662e2dadf49f0a122f1 | 367134ba5a65885e863bdc4507601606690974c1 | /src/order/ideal.lean | 3ae7e746dd10feaca32538a2b590980ba2f916fb | [
"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 | 10,099 | lean | /-
Copyright (c) 2020 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn
-/
import order.basic
import data.equiv.encodable.basic
/-!
# Order ideals, cofinal sets, and the Rasiowa–Sikorski lemma
## Main definitions
Throughout this file, `P` is at least a preorder, but some sections require more
structure, such as a bottom element, a top element, or a join-semilattice structure.
- `ideal P`: the type of upward directed, downward closed subsets of `P`.
Dual to the notion of a filter on a preorder.
- `cofinal P`: the type of subsets of `P` containing arbitrarily large elements.
Dual to the notion of 'dense set' used in forcing.
- `ideal_of_cofinals p 𝒟`, where `p : P`, and `𝒟` is a countable family of cofinal
subsets of P: an ideal in `P` which contains `p` and intersects every set in `𝒟`.
## References
- <https://en.wikipedia.org/wiki/Ideal_(order_theory)>
- <https://en.wikipedia.org/wiki/Cofinal_(mathematics)>
- <https://en.wikipedia.org/wiki/Rasiowa%E2%80%93Sikorski_lemma>
Note that for the Rasiowa–Sikorski lemma, Wikipedia uses the opposite ordering on `P`,
in line with most presentations of forcing.
## Tags
ideal, cofinal, dense, countable, generic
-/
namespace order
variables {P : Type*}
/-- An ideal on a preorder `P` is a subset of `P` that is
- nonempty
- upward directed
- downward closed. -/
structure ideal (P) [preorder P] :=
(carrier : set P)
(nonempty : carrier.nonempty)
(directed : directed_on (≤) carrier)
(mem_of_le : ∀ {x y : P}, x ≤ y → y ∈ carrier → x ∈ carrier)
namespace ideal
section preorder
variables [preorder P] {x : P} {I J : ideal P}
/-- The smallest ideal containing a given element. -/
def principal (p : P) : ideal P :=
{ carrier := { x | x ≤ p },
nonempty := ⟨p, le_refl _⟩,
directed := λ x hx y hy, ⟨p, le_refl _, hx, hy⟩,
mem_of_le := λ x y hxy hy, le_trans hxy hy, }
instance [inhabited P] : inhabited (ideal P) :=
⟨ideal.principal $ default P⟩
/-- An ideal of `P` can be viewed as a subset of `P`. -/
instance : has_coe (ideal P) (set P) := ⟨carrier⟩
/-- For the notation `x ∈ I`. -/
instance : has_mem P (ideal P) := ⟨λ x I, x ∈ (I : set P)⟩
/-- Two ideals are equal when their underlying sets are equal. -/
@[ext] lemma ext : ∀ (I J : ideal P), (I : set P) = J → I = J
| ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ rfl := rfl
/-- The partial ordering by subset inclusion, inherited from `set P`. -/
instance : partial_order (ideal P) := partial_order.lift coe ext
@[trans] lemma mem_of_mem_of_le : x ∈ I → I ≤ J → x ∈ J :=
@set.mem_of_mem_of_subset P x I J
@[simp] lemma principal_le_iff : principal x ≤ I ↔ x ∈ I :=
⟨λ (h : ∀ {y}, y ≤ x → y ∈ I), h (le_refl x),
λ h_mem y (h_le : y ≤ x), I.mem_of_le h_le h_mem⟩
/-- A proper ideal is one that is not the whole set.
Note that the whole set might not be an ideal. -/
class proper (I : ideal P) : Prop := (nuniv : (I : set P) ≠ set.univ)
lemma proper_of_not_mem {I : ideal P} {p : P} (nmem : p ∉ I) : proper I :=
⟨λ hp, begin
change p ∉ ↑I at nmem,
rw hp at nmem,
exact nmem (set.mem_univ p),
end⟩
end preorder
section order_bot
variables [order_bot P] {I : ideal P}
/-- A specific witness of `I.nonempty` when `P` has a bottom element. -/
@[simp] lemma bot_mem : ⊥ ∈ I :=
I.mem_of_le bot_le I.nonempty.some_mem
/-- There is a bottom ideal when `P` has a bottom element. -/
instance : order_bot (ideal P) :=
{ bot := principal ⊥,
bot_le := by simp,
.. ideal.partial_order }
end order_bot
section order_top
variables [order_top P]
/-- There is a top ideal when `P` has a top element. -/
instance : order_top (ideal P) :=
{ top := principal ⊤,
le_top := λ I x h, le_top,
.. ideal.partial_order }
@[simp] lemma top_carrier : (⊤ : ideal P).carrier = set.univ :=
set.univ_subset_iff.1 (λ p _, le_top)
lemma top_of_mem_top {I : ideal P} (topmem : ⊤ ∈ I) : I = ⊤ :=
begin
ext,
change x ∈ I.carrier ↔ x ∈ (⊤ : ideal P).carrier,
split,
{ simp [top_carrier] },
{ exact λ _, I.mem_of_le le_top topmem }
end
lemma proper_of_ne_top {I : ideal P} (ntop : I ≠ ⊤) : proper I :=
proper_of_not_mem (λ h, ntop (top_of_mem_top h))
end order_top
section semilattice_sup
variables [semilattice_sup P] {x y : P} {I : ideal P}
/-- A specific witness of `I.directed` when `P` has joins. -/
lemma sup_mem (x y ∈ I) : x ⊔ y ∈ I :=
let ⟨z, h_mem, hx, hy⟩ := I.directed x ‹_› y ‹_› in
I.mem_of_le (sup_le hx hy) h_mem
@[simp] lemma sup_mem_iff : x ⊔ y ∈ I ↔ x ∈ I ∧ y ∈ I :=
⟨λ h, ⟨I.mem_of_le le_sup_left h, I.mem_of_le le_sup_right h⟩,
λ h, sup_mem x y h.left h.right⟩
end semilattice_sup
section semilattice_sup_bot
variables [semilattice_sup_bot P] (I J K : ideal P)
/-- The intersection of two ideals is an ideal, when `P` has joins and a bottom. -/
def inf (I J : ideal P) : ideal P :=
{ carrier := I ∩ J,
nonempty := ⟨⊥, bot_mem, bot_mem⟩,
directed := λ x ⟨_, _⟩ y ⟨_, _⟩, ⟨x ⊔ y, ⟨sup_mem x y ‹_› ‹_›, sup_mem x y ‹_› ‹_›⟩, by simp⟩,
mem_of_le := λ x y h ⟨_, _⟩, ⟨mem_of_le I h ‹_›, mem_of_le J h ‹_›⟩ }
/-- There is a smallest ideal containing two ideals, when `P` has joins and a bottom. -/
def sup (I J : ideal P) : ideal P :=
{ carrier := {x | ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j},
nonempty := ⟨⊥, ⊥, bot_mem, ⊥, bot_mem, bot_le⟩,
directed := λ x ⟨xi, _, xj, _, _⟩ y ⟨yi, _, yj, _, _⟩,
⟨x ⊔ y,
⟨xi ⊔ yi, sup_mem xi yi ‹_› ‹_›,
xj ⊔ yj, sup_mem xj yj ‹_› ‹_›,
sup_le
(calc x ≤ xi ⊔ xj : ‹_›
... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_left le_sup_left)
(calc y ≤ yi ⊔ yj : ‹_›
... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_right le_sup_right)⟩,
le_sup_left, le_sup_right⟩,
mem_of_le := λ x y _ ⟨yi, _, yj, _, _⟩, ⟨yi, ‹_›, yj, ‹_›, le_trans ‹x ≤ y› ‹_›⟩ }
lemma sup_le : I ≤ K → J ≤ K → sup I J ≤ K :=
λ hIK hJK x ⟨i, hiI, j, hjJ, hxij⟩,
K.mem_of_le hxij $ sup_mem i j (mem_of_mem_of_le hiI hIK) (mem_of_mem_of_le hjJ hJK)
instance : lattice (ideal P) :=
{ sup := sup,
le_sup_left := λ I J (i ∈ I), ⟨i, ‹_›, ⊥, bot_mem, by simp only [sup_bot_eq]⟩,
le_sup_right := λ I J (j ∈ J), ⟨⊥, bot_mem, j, ‹_›, by simp only [bot_sup_eq]⟩,
sup_le := sup_le,
inf := inf,
inf_le_left := λ I J, set.inter_subset_left I J,
inf_le_right := λ I J, set.inter_subset_right I J,
le_inf := λ I J K, set.subset_inter,
.. ideal.partial_order }
@[simp] lemma mem_inf {x : P} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff_of_eq rfl
@[simp] lemma mem_sup {x : P} : x ∈ I ⊔ J ↔ ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j := iff_of_eq rfl
end semilattice_sup_bot
end ideal
/-- For a preorder `P`, `cofinal P` is the type of subsets of `P`
containing arbitrarily large elements. They are the dense sets in
the topology whose open sets are terminal segments. -/
structure cofinal (P) [preorder P] :=
(carrier : set P)
(mem_gt : ∀ x : P, ∃ y ∈ carrier, x ≤ y)
namespace cofinal
variables [preorder P]
instance : inhabited (cofinal P) :=
⟨{ carrier := set.univ, mem_gt := λ x, ⟨x, trivial, le_refl _⟩}⟩
instance : has_mem P (cofinal P) := ⟨λ x D, x ∈ D.carrier⟩
variables (D : cofinal P) (x : P)
/-- A (noncomputable) element of a cofinal set lying above a given element. -/
noncomputable def above : P := classical.some $ D.mem_gt x
lemma above_mem : D.above x ∈ D :=
exists.elim (classical.some_spec $ D.mem_gt x) $ λ a _, a
lemma le_above : x ≤ D.above x :=
exists.elim (classical.some_spec $ D.mem_gt x) $ λ _ b, b
end cofinal
section ideal_of_cofinals
variables [preorder P] (p : P) {ι : Type*} [encodable ι] (𝒟 : ι → cofinal P)
/-- Given a starting point, and a countable family of cofinal sets,
this is an increasing sequence that intersects each cofinal set. -/
noncomputable def sequence_of_cofinals : ℕ → P
| 0 := p
| (n+1) := match encodable.decode ι n with
| none := sequence_of_cofinals n
| some i := (𝒟 i).above (sequence_of_cofinals n)
end
lemma sequence_of_cofinals.monotone : monotone (sequence_of_cofinals p 𝒟) :=
by { apply monotone_of_monotone_nat, intros n, dunfold sequence_of_cofinals,
cases encodable.decode ι n, { refl }, { apply cofinal.le_above }, }
lemma sequence_of_cofinals.encode_mem (i : ι) :
sequence_of_cofinals p 𝒟 (encodable.encode i + 1) ∈ 𝒟 i :=
by { dunfold sequence_of_cofinals, rw encodable.encodek, apply cofinal.above_mem, }
/-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`,
indexed by a countable type, `ideal_of_cofinals p 𝒟` is an ideal in `P` which
- contains `p`, according to `mem_ideal_of_cofinals p 𝒟`, and
- intersects every set in `𝒟`, according to `cofinal_meets_ideal_of_cofinals p 𝒟`.
This proves the Rasiowa–Sikorski lemma. -/
def ideal_of_cofinals : ideal P :=
{ carrier := { x : P | ∃ n, x ≤ sequence_of_cofinals p 𝒟 n },
nonempty := ⟨p, 0, le_refl _⟩,
directed := λ x ⟨n, hn⟩ y ⟨m, hm⟩,
⟨_, ⟨max n m, le_refl _⟩,
le_trans hn $ sequence_of_cofinals.monotone p 𝒟 (le_max_left _ _),
le_trans hm $ sequence_of_cofinals.monotone p 𝒟 (le_max_right _ _) ⟩,
mem_of_le := λ x y hxy ⟨n, hn⟩, ⟨n, le_trans hxy hn⟩, }
lemma mem_ideal_of_cofinals : p ∈ ideal_of_cofinals p 𝒟 := ⟨0, le_refl _⟩
/-- `ideal_of_cofinals p 𝒟` is `𝒟`-generic. -/
lemma cofinal_meets_ideal_of_cofinals (i : ι) : ∃ x : P, x ∈ 𝒟 i ∧ x ∈ ideal_of_cofinals p 𝒟 :=
⟨_, sequence_of_cofinals.encode_mem p 𝒟 i, _, le_refl _⟩
end ideal_of_cofinals
end order
|
b29b5bdf5cc1e81272cd87ca1af703aff0c5236b | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/standard.lean | 637572bb7e2bb6076c6ad52a33ec8f9865e1dc82 | [
"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 | 243 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
The constructive core of Lean's library.
-/
-- import logic data
|
562d6d57c2f19b3b5f4a08191efef372cc66b8df | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/ring_hom/integral.lean | 1d96571c23f5f564f013ec651da7ca1f29bb6f36 | [
"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 | 1,324 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import ring_theory.ring_hom_properties
import ring_theory.integral_closure
/-!
# The meta properties of integral ring homomorphisms.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
namespace ring_hom
open_locale tensor_product
open tensor_product algebra.tensor_product
lemma is_integral_stable_under_composition :
stable_under_composition (λ R S _ _ f, by exactI f.is_integral) :=
by { introv R hf hg, exactI ring_hom.is_integral_trans _ _ hf hg }
lemma is_integral_respects_iso :
respects_iso (λ R S _ _ f, by exactI f.is_integral) :=
begin
apply is_integral_stable_under_composition.respects_iso,
introv x,
resetI,
rw ← e.apply_symm_apply x,
apply ring_hom.is_integral_map
end
lemma is_integral_stable_under_base_change :
stable_under_base_change (λ R S _ _ f, by exactI f.is_integral) :=
begin
refine stable_under_base_change.mk _ is_integral_respects_iso _,
introv h x,
resetI,
apply tensor_product.induction_on x,
{ apply is_integral_zero },
{ intros x y, exact is_integral.tmul x (h y) },
{ intros x y hx hy, exact is_integral_add _ hx hy }
end
end ring_hom
|
8e0414f9e584b7369d57591323ff562b105e99e8 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/group/hom.lean | 659c68c82fcc3bb2c880180ddd350333e5287469 | [] | 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 | 39,521 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes,
Johannes Hölzl, Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.group.commute
import Mathlib.algebra.group_with_zero.defs
import Mathlib.PostPort
universes u_6 u_7 l u_1 u_2 u_3 u_4 u_5
namespace Mathlib
/-!
# monoid and group homomorphisms
This file defines the bundled structures for monoid and group homomorphisms. Namely, we define
`monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp.,
additive) monoids or groups.
We also define coercion to a function, and usual operations: composition, identity homomorphism,
pointwise multiplication and pointwise inversion.
This file also defines the lesser-used (and notation-less) homomorphism types which are used as
building blocks for other homomorphisms:
* `zero_hom`
* `one_hom`
* `add_hom`
* `mul_hom`
* `monoid_with_zero_hom`
## Notations
* `→*` for bundled monoid homs (also use for group homs)
* `→+` for bundled add_monoid homs (also use for add_group homs)
## implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `group_hom` -- the idea is that `monoid_hom` is used.
The constructor for `monoid_hom` needs a proof of `map_one` as well
as `map_mul`; a separate constructor `monoid_hom.mk'` will construct
group homs (i.e. monoid homs between groups) given only a proof
that multiplication is preserved,
Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the
instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they
can be inferred from the type it is faster to use this method than to use type class inference.
Historically this file also included definitions of unbundled homomorphism classes; they were
deprecated and moved to `deprecated/group`.
## Tags
monoid_hom, add_monoid_hom
-/
-- for easy multiple inheritance
/-- Homomorphism that preserves zero -/
structure zero_hom (M : Type u_6) (N : Type u_7) [HasZero M] [HasZero N]
where
to_fun : M → N
map_zero' : to_fun 0 = 0
/-- Homomorphism that preserves addition -/
structure add_hom (M : Type u_6) (N : Type u_7) [Add M] [Add N]
where
to_fun : M → N
map_add' : ∀ (x y : M), to_fun (x + y) = to_fun x + to_fun y
/-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/
structure add_monoid_hom (M : Type u_6) (N : Type u_7) [add_monoid M] [add_monoid N]
extends zero_hom M N, add_hom M N
where
infixr:25 " →+ " => Mathlib.add_monoid_hom
/-- Homomorphism that preserves one -/
structure one_hom (M : Type u_6) (N : Type u_7) [HasOne M] [HasOne N]
where
to_fun : M → N
map_one' : to_fun 1 = 1
/-- Homomorphism that preserves multiplication -/
structure mul_hom (M : Type u_6) (N : Type u_7) [Mul M] [Mul N]
where
to_fun : M → N
map_mul' : ∀ (x y : M), to_fun (x * y) = to_fun x * to_fun y
/-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/
structure monoid_hom (M : Type u_6) (N : Type u_7) [monoid M] [monoid N]
extends one_hom M N, mul_hom M N
where
/-- Bundled monoid with zero homomorphisms; use this for bundled group with zero homomorphisms
too. -/
structure monoid_with_zero_hom (M : Type u_6) (N : Type u_7) [monoid_with_zero M] [monoid_with_zero N]
extends zero_hom M N, monoid_hom M N
where
infixr:25 " →* " => Mathlib.monoid_hom
-- completely uninteresting lemmas about coercion to function, that all homs need
/-! Bundled morphisms can be down-cast to weaker bundlings -/
protected instance monoid_hom.has_coe_to_one_hom {M : Type u_1} {N : Type u_2} {mM : monoid M} {mN : monoid N} : has_coe (M →* N) (one_hom M N) :=
has_coe.mk monoid_hom.to_one_hom
protected instance add_monoid_hom.has_coe_to_add_hom {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} : has_coe (M →+ N) (add_hom M N) :=
has_coe.mk add_monoid_hom.to_add_hom
protected instance monoid_with_zero_hom.has_coe_to_monoid_hom {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} : has_coe (monoid_with_zero_hom M N) (M →* N) :=
has_coe.mk monoid_with_zero_hom.to_monoid_hom
protected instance monoid_with_zero_hom.has_coe_to_zero_hom {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} : has_coe (monoid_with_zero_hom M N) (zero_hom M N) :=
has_coe.mk monoid_with_zero_hom.to_zero_hom
/-! The simp-normal form of morphism coercion is `f.to_..._hom`. This choice is primarily because
this is the way things were before the above coercions were introduced. Bundled morphisms defined
elsewhere in Mathlib may choose `↑f` as their simp-normal form instead. -/
@[simp] theorem monoid_hom.coe_eq_to_one_hom {M : Type u_1} {N : Type u_2} {mM : monoid M} {mN : monoid N} (f : M →* N) : ↑f = monoid_hom.to_one_hom f :=
rfl
@[simp] theorem add_monoid_hom.coe_eq_to_add_hom {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} (f : M →+ N) : ↑f = add_monoid_hom.to_add_hom f :=
rfl
@[simp] theorem monoid_with_zero_hom.coe_eq_to_monoid_hom {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} (f : monoid_with_zero_hom M N) : ↑f = monoid_with_zero_hom.to_monoid_hom f :=
rfl
@[simp] theorem monoid_with_zero_hom.coe_eq_to_zero_hom {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} (f : monoid_with_zero_hom M N) : ↑f = monoid_with_zero_hom.to_zero_hom f :=
rfl
protected instance zero_hom.has_coe_to_fun {M : Type u_1} {N : Type u_2} {mM : HasZero M} {mN : HasZero N} : has_coe_to_fun (zero_hom M N) :=
has_coe_to_fun.mk (fun (x : zero_hom M N) => M → N) zero_hom.to_fun
protected instance mul_hom.has_coe_to_fun {M : Type u_1} {N : Type u_2} {mM : Mul M} {mN : Mul N} : has_coe_to_fun (mul_hom M N) :=
has_coe_to_fun.mk (fun (x : mul_hom M N) => M → N) mul_hom.to_fun
protected instance add_monoid_hom.has_coe_to_fun {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} : has_coe_to_fun (M →+ N) :=
has_coe_to_fun.mk (fun (x : M →+ N) => M → N) add_monoid_hom.to_fun
protected instance monoid_with_zero_hom.has_coe_to_fun {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} : has_coe_to_fun (monoid_with_zero_hom M N) :=
has_coe_to_fun.mk (fun (x : monoid_with_zero_hom M N) => M → N) monoid_with_zero_hom.to_fun
-- these must come after the coe_to_fun definitions
@[simp] theorem zero_hom.to_fun_eq_coe {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] (f : zero_hom M N) : zero_hom.to_fun f = ⇑f :=
rfl
@[simp] theorem mul_hom.to_fun_eq_coe {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) : mul_hom.to_fun f = ⇑f :=
rfl
@[simp] theorem add_monoid_hom.to_fun_eq_coe {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) : add_monoid_hom.to_fun f = ⇑f :=
rfl
@[simp] theorem monoid_with_zero_hom.to_fun_eq_coe {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : monoid_with_zero_hom.to_fun f = ⇑f :=
rfl
@[simp] theorem one_hom.coe_mk {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (f : M → N) (h1 : f 1 = 1) : ⇑(one_hom.mk f h1) = f :=
rfl
@[simp] theorem add_hom.coe_mk {M : Type u_1} {N : Type u_2} [Add M] [Add N] (f : M → N) (hmul : ∀ (x y : M), f (x + y) = f x + f y) : ⇑(add_hom.mk f hmul) = f :=
rfl
@[simp] theorem add_monoid_hom.coe_mk {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M → N) (h1 : f 0 = 0) (hmul : ∀ (x y : M), f (x + y) = f x + f y) : ⇑(add_monoid_hom.mk f h1 hmul) = f :=
rfl
@[simp] theorem monoid_with_zero_hom.coe_mk {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : M → N) (h0 : f 0 = 0) (h1 : f 1 = 1) (hmul : ∀ (x y : M), f (x * y) = f x * f y) : ⇑(monoid_with_zero_hom.mk f h0 h1 hmul) = f :=
rfl
@[simp] theorem monoid_hom.to_one_hom_coe {M : Type u_1} {N : Type u_2} [monoid M] [monoid N] (f : M →* N) : ⇑(monoid_hom.to_one_hom f) = ⇑f :=
rfl
@[simp] theorem add_monoid_hom.to_add_hom_coe {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) : ⇑(add_monoid_hom.to_add_hom f) = ⇑f :=
rfl
@[simp] theorem monoid_with_zero_hom.to_zero_hom_coe {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : ⇑(monoid_with_zero_hom.to_zero_hom f) = ⇑f :=
rfl
@[simp] theorem monoid_with_zero_hom.to_monoid_hom_coe {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : ⇑(monoid_with_zero_hom.to_monoid_hom f) = ⇑f :=
rfl
theorem one_hom.congr_fun {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] {f : one_hom M N} {g : one_hom M N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x :=
congr_arg (fun (h : one_hom M N) => coe_fn h x) h
theorem add_hom.congr_fun {M : Type u_1} {N : Type u_2} [Add M] [Add N] {f : add_hom M N} {g : add_hom M N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x :=
congr_arg (fun (h : add_hom M N) => coe_fn h x) h
theorem add_monoid_hom.congr_fun {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {f : M →+ N} {g : M →+ N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x :=
congr_arg (fun (h : M →+ N) => coe_fn h x) h
theorem monoid_with_zero_hom.congr_fun {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] {f : monoid_with_zero_hom M N} {g : monoid_with_zero_hom M N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x :=
congr_arg (fun (h : monoid_with_zero_hom M N) => coe_fn h x) h
theorem one_hom.congr_arg {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (f : one_hom M N) {x : M} {y : M} (h : x = y) : coe_fn f x = coe_fn f y :=
congr_arg (fun (x : M) => coe_fn f x) h
theorem add_hom.congr_arg {M : Type u_1} {N : Type u_2} [Add M] [Add N] (f : add_hom M N) {x : M} {y : M} (h : x = y) : coe_fn f x = coe_fn f y :=
congr_arg (fun (x : M) => coe_fn f x) h
theorem add_monoid_hom.congr_arg {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) {x : M} {y : M} (h : x = y) : coe_fn f x = coe_fn f y :=
congr_arg (fun (x : M) => coe_fn f x) h
theorem monoid_with_zero_hom.congr_arg {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) {x : M} {y : M} (h : x = y) : coe_fn f x = coe_fn f y :=
congr_arg (fun (x : M) => coe_fn f x) h
theorem one_hom.coe_inj {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] {f : one_hom M N} {g : one_hom M N} (h : ⇑f = ⇑g) : f = g := sorry
theorem mul_hom.coe_inj {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] {f : mul_hom M N} {g : mul_hom M N} (h : ⇑f = ⇑g) : f = g := sorry
theorem add_monoid_hom.coe_inj {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {f : M →+ N} {g : M →+ N} (h : ⇑f = ⇑g) : f = g := sorry
theorem monoid_with_zero_hom.coe_inj {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] {f : monoid_with_zero_hom M N} {g : monoid_with_zero_hom M N} (h : ⇑f = ⇑g) : f = g := sorry
theorem zero_hom.ext {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] {f : zero_hom M N} {g : zero_hom M N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g :=
zero_hom.coe_inj (funext h)
theorem mul_hom.ext {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] {f : mul_hom M N} {g : mul_hom M N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g :=
mul_hom.coe_inj (funext h)
theorem add_monoid_hom.ext {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {f : M →+ N} {g : M →+ N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g :=
add_monoid_hom.coe_inj (funext h)
theorem monoid_with_zero_hom.ext {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] {f : monoid_with_zero_hom M N} {g : monoid_with_zero_hom M N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g :=
monoid_with_zero_hom.coe_inj (funext h)
theorem zero_hom.ext_iff {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] {f : zero_hom M N} {g : zero_hom M N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x :=
{ mp := fun (h : f = g) (x : M) => h ▸ rfl, mpr := fun (h : ∀ (x : M), coe_fn f x = coe_fn g x) => zero_hom.ext h }
theorem mul_hom.ext_iff {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] {f : mul_hom M N} {g : mul_hom M N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x :=
{ mp := fun (h : f = g) (x : M) => h ▸ rfl, mpr := fun (h : ∀ (x : M), coe_fn f x = coe_fn g x) => mul_hom.ext h }
theorem add_monoid_hom.ext_iff {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {f : M →+ N} {g : M →+ N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x :=
{ mp := fun (h : f = g) (x : M) => h ▸ rfl,
mpr := fun (h : ∀ (x : M), coe_fn f x = coe_fn g x) => add_monoid_hom.ext h }
theorem monoid_with_zero_hom.ext_iff {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] {f : monoid_with_zero_hom M N} {g : monoid_with_zero_hom M N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x :=
{ mp := fun (h : f = g) (x : M) => h ▸ rfl,
mpr := fun (h : ∀ (x : M), coe_fn f x = coe_fn g x) => monoid_with_zero_hom.ext h }
@[simp] theorem zero_hom.mk_coe {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] (f : zero_hom M N) (h1 : coe_fn f 0 = 0) : zero_hom.mk (⇑f) h1 = f :=
zero_hom.ext fun (_x : M) => rfl
@[simp] theorem mul_hom.mk_coe {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) (hmul : ∀ (x y : M), coe_fn f (x * y) = coe_fn f x * coe_fn f y) : mul_hom.mk (⇑f) hmul = f :=
mul_hom.ext fun (_x : M) => rfl
@[simp] theorem add_monoid_hom.mk_coe {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) (h1 : coe_fn f 0 = 0) (hmul : ∀ (x y : M), coe_fn f (x + y) = coe_fn f x + coe_fn f y) : add_monoid_hom.mk (⇑f) h1 hmul = f :=
add_monoid_hom.ext fun (_x : M) => rfl
@[simp] theorem monoid_with_zero_hom.mk_coe {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) (h0 : coe_fn f 0 = 0) (h1 : coe_fn f 1 = 1) (hmul : ∀ (x y : M), coe_fn f (x * y) = coe_fn f x * coe_fn f y) : monoid_with_zero_hom.mk (⇑f) h0 h1 hmul = f :=
monoid_with_zero_hom.ext fun (_x : M) => rfl
/-- If `f` is a monoid homomorphism then `f 1 = 1`. -/
@[simp] theorem one_hom.map_one {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (f : one_hom M N) : coe_fn f 1 = 1 :=
one_hom.map_one' f
@[simp] theorem monoid_hom.map_one {M : Type u_1} {N : Type u_2} [monoid M] [monoid N] (f : M →* N) : coe_fn f 1 = 1 :=
monoid_hom.map_one' f
@[simp] theorem monoid_with_zero_hom.map_one {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : coe_fn f 1 = 1 :=
monoid_with_zero_hom.map_one' f
/-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/
@[simp] theorem monoid_with_zero_hom.map_zero {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : coe_fn f 0 = 0 :=
monoid_with_zero_hom.map_zero' f
@[simp] theorem mul_hom.map_mul {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) (a : M) (b : M) : coe_fn f (a * b) = coe_fn f a * coe_fn f b :=
mul_hom.map_mul' f a b
/-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/
@[simp] theorem add_monoid_hom.map_add {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) (a : M) (b : M) : coe_fn f (a + b) = coe_fn f a + coe_fn f b :=
add_monoid_hom.map_add' f a b
@[simp] theorem monoid_with_zero_hom.map_mul {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) (a : M) (b : M) : coe_fn f (a * b) = coe_fn f a * coe_fn f b :=
monoid_with_zero_hom.map_mul' f a b
/-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/
namespace monoid_hom
theorem Mathlib.add_monoid_hom.map_add_eq_zero {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} (f : M →+ N) {a : M} {b : M} (h : a + b = 0) : coe_fn f a + coe_fn f b = 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f a + coe_fn f b = 0)) (Eq.symm (add_monoid_hom.map_add f a b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f (a + b) = 0)) h))
(eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f 0 = 0)) (add_monoid_hom.map_zero f))) (Eq.refl 0)))
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse,
then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/
theorem Mathlib.add_monoid_hom.map_exists_right_neg {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} (f : M →+ N) {x : M} (hx : ∃ (y : M), x + y = 0) : ∃ (y : N), coe_fn f x + y = 0 := sorry
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse,
then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/
theorem Mathlib.add_monoid_hom.map_exists_left_neg {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} (f : M →+ N) {x : M} (hx : ∃ (y : M), y + x = 0) : ∃ (y : N), y + coe_fn f x = 0 := sorry
end monoid_hom
/-- The identity map from a type with 1 to itself. -/
def one_hom.id (M : Type u_1) [HasOne M] : one_hom M M :=
one_hom.mk id sorry
/-- The identity map from a type with multiplication to itself. -/
def add_hom.id (M : Type u_1) [Add M] : add_hom M M :=
add_hom.mk id sorry
/-- The identity map from a monoid to itself. -/
def add_monoid_hom.id (M : Type u_1) [add_monoid M] : M →+ M :=
add_monoid_hom.mk id sorry sorry
/-- The identity map from a monoid_with_zero to itself. -/
def monoid_with_zero_hom.id (M : Type u_1) [monoid_with_zero M] : monoid_with_zero_hom M M :=
monoid_with_zero_hom.mk id sorry sorry sorry
/-- The identity map from an type with zero to itself. -/
/-- The identity map from an type with addition to itself. -/
/-- The identity map from an additive monoid to itself. -/
@[simp] theorem zero_hom.id_apply {M : Type u_1} [HasZero M] (x : M) : coe_fn (zero_hom.id M) x = x :=
rfl
@[simp] theorem mul_hom.id_apply {M : Type u_1} [Mul M] (x : M) : coe_fn (mul_hom.id M) x = x :=
rfl
@[simp] theorem monoid_hom.id_apply {M : Type u_1} [monoid M] (x : M) : coe_fn (monoid_hom.id M) x = x :=
rfl
@[simp] theorem monoid_with_zero_hom.id_apply {M : Type u_1} [monoid_with_zero M] (x : M) : coe_fn (monoid_with_zero_hom.id M) x = x :=
rfl
/-- Composition of `one_hom`s as a `one_hom`. -/
def zero_hom.comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasZero M] [HasZero N] [HasZero P] (hnp : zero_hom N P) (hmn : zero_hom M N) : zero_hom M P :=
zero_hom.mk (⇑hnp ∘ ⇑hmn) sorry
/-- Composition of `mul_hom`s as a `mul_hom`. -/
def mul_hom.comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [Mul M] [Mul N] [Mul P] (hnp : mul_hom N P) (hmn : mul_hom M N) : mul_hom M P :=
mul_hom.mk (⇑hnp ∘ ⇑hmn) sorry
/-- Composition of monoid morphisms as a monoid morphism. -/
def monoid_hom.comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [monoid N] [monoid P] (hnp : N →* P) (hmn : M →* N) : M →* P :=
monoid_hom.mk (⇑hnp ∘ ⇑hmn) sorry sorry
/-- Composition of `monoid_with_zero_hom`s as a `monoid_with_zero_hom`. -/
def monoid_with_zero_hom.comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] (hnp : monoid_with_zero_hom N P) (hmn : monoid_with_zero_hom M N) : monoid_with_zero_hom M P :=
monoid_with_zero_hom.mk (⇑hnp ∘ ⇑hmn) sorry sorry sorry
/-- Composition of `zero_hom`s as a `zero_hom`. -/
/-- Composition of `add_hom`s as a `add_hom`. -/
/-- Composition of additive monoid morphisms as an additive monoid morphism. -/
@[simp] theorem one_hom.coe_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasOne M] [HasOne N] [HasOne P] (g : one_hom N P) (f : one_hom M N) : ⇑(one_hom.comp g f) = ⇑g ∘ ⇑f :=
rfl
@[simp] theorem add_hom.coe_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [Add M] [Add N] [Add P] (g : add_hom N P) (f : add_hom M N) : ⇑(add_hom.comp g f) = ⇑g ∘ ⇑f :=
rfl
@[simp] theorem add_monoid_hom.coe_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [add_monoid M] [add_monoid N] [add_monoid P] (g : N →+ P) (f : M →+ N) : ⇑(add_monoid_hom.comp g f) = ⇑g ∘ ⇑f :=
rfl
@[simp] theorem monoid_with_zero_hom.coe_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] (g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) : ⇑(monoid_with_zero_hom.comp g f) = ⇑g ∘ ⇑f :=
rfl
theorem one_hom.comp_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasOne M] [HasOne N] [HasOne P] (g : one_hom N P) (f : one_hom M N) (x : M) : coe_fn (one_hom.comp g f) x = coe_fn g (coe_fn f x) :=
rfl
theorem add_hom.comp_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} [Add M] [Add N] [Add P] (g : add_hom N P) (f : add_hom M N) (x : M) : coe_fn (add_hom.comp g f) x = coe_fn g (coe_fn f x) :=
rfl
theorem monoid_hom.comp_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [monoid N] [monoid P] (g : N →* P) (f : M →* N) (x : M) : coe_fn (monoid_hom.comp g f) x = coe_fn g (coe_fn f x) :=
rfl
theorem monoid_with_zero_hom.comp_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] (g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) (x : M) : coe_fn (monoid_with_zero_hom.comp g f) x = coe_fn g (coe_fn f x) :=
rfl
/-- Composition of monoid homomorphisms is associative. -/
theorem zero_hom.comp_assoc {M : Type u_1} {N : Type u_2} {P : Type u_3} {Q : Type u_4} [HasZero M] [HasZero N] [HasZero P] [HasZero Q] (f : zero_hom M N) (g : zero_hom N P) (h : zero_hom P Q) : zero_hom.comp (zero_hom.comp h g) f = zero_hom.comp h (zero_hom.comp g f) :=
rfl
theorem mul_hom.comp_assoc {M : Type u_1} {N : Type u_2} {P : Type u_3} {Q : Type u_4} [Mul M] [Mul N] [Mul P] [Mul Q] (f : mul_hom M N) (g : mul_hom N P) (h : mul_hom P Q) : mul_hom.comp (mul_hom.comp h g) f = mul_hom.comp h (mul_hom.comp g f) :=
rfl
theorem add_monoid_hom.comp_assoc {M : Type u_1} {N : Type u_2} {P : Type u_3} {Q : Type u_4} [add_monoid M] [add_monoid N] [add_monoid P] [add_monoid Q] (f : M →+ N) (g : N →+ P) (h : P →+ Q) : add_monoid_hom.comp (add_monoid_hom.comp h g) f = add_monoid_hom.comp h (add_monoid_hom.comp g f) :=
rfl
theorem monoid_with_zero_hom.comp_assoc {M : Type u_1} {N : Type u_2} {P : Type u_3} {Q : Type u_4} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] [monoid_with_zero Q] (f : monoid_with_zero_hom M N) (g : monoid_with_zero_hom N P) (h : monoid_with_zero_hom P Q) : monoid_with_zero_hom.comp (monoid_with_zero_hom.comp h g) f =
monoid_with_zero_hom.comp h (monoid_with_zero_hom.comp g f) :=
rfl
theorem one_hom.cancel_right {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasOne M] [HasOne N] [HasOne P] {g₁ : one_hom N P} {g₂ : one_hom N P} {f : one_hom M N} (hf : function.surjective ⇑f) : one_hom.comp g₁ f = one_hom.comp g₂ f ↔ g₁ = g₂ := sorry
theorem add_hom.cancel_right {M : Type u_1} {N : Type u_2} {P : Type u_3} [Add M] [Add N] [Add P] {g₁ : add_hom N P} {g₂ : add_hom N P} {f : add_hom M N} (hf : function.surjective ⇑f) : add_hom.comp g₁ f = add_hom.comp g₂ f ↔ g₁ = g₂ := sorry
theorem add_monoid_hom.cancel_right {M : Type u_1} {N : Type u_2} {P : Type u_3} [add_monoid M] [add_monoid N] [add_monoid P] {g₁ : N →+ P} {g₂ : N →+ P} {f : M →+ N} (hf : function.surjective ⇑f) : add_monoid_hom.comp g₁ f = add_monoid_hom.comp g₂ f ↔ g₁ = g₂ := sorry
theorem monoid_with_zero_hom.cancel_right {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] {g₁ : monoid_with_zero_hom N P} {g₂ : monoid_with_zero_hom N P} {f : monoid_with_zero_hom M N} (hf : function.surjective ⇑f) : monoid_with_zero_hom.comp g₁ f = monoid_with_zero_hom.comp g₂ f ↔ g₁ = g₂ := sorry
theorem one_hom.cancel_left {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasOne M] [HasOne N] [HasOne P] {g : one_hom N P} {f₁ : one_hom M N} {f₂ : one_hom M N} (hg : function.injective ⇑g) : one_hom.comp g f₁ = one_hom.comp g f₂ ↔ f₁ = f₂ := sorry
theorem add_hom.cancel_left {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasZero M] [HasZero N] [HasZero P] {g : zero_hom N P} {f₁ : zero_hom M N} {f₂ : zero_hom M N} (hg : function.injective ⇑g) : zero_hom.comp g f₁ = zero_hom.comp g f₂ ↔ f₁ = f₂ := sorry
theorem monoid_hom.cancel_left {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [monoid N] [monoid P] {g : N →* P} {f₁ : M →* N} {f₂ : M →* N} (hg : function.injective ⇑g) : monoid_hom.comp g f₁ = monoid_hom.comp g f₂ ↔ f₁ = f₂ := sorry
theorem monoid_with_zero_hom.cancel_left {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] {g : monoid_with_zero_hom N P} {f₁ : monoid_with_zero_hom M N} {f₂ : monoid_with_zero_hom M N} (hg : function.injective ⇑g) : monoid_with_zero_hom.comp g f₁ = monoid_with_zero_hom.comp g f₂ ↔ f₁ = f₂ := sorry
@[simp] theorem one_hom.comp_id {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (f : one_hom M N) : one_hom.comp f (one_hom.id M) = f :=
one_hom.ext fun (x : M) => rfl
@[simp] theorem mul_hom.comp_id {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) : mul_hom.comp f (mul_hom.id M) = f :=
mul_hom.ext fun (x : M) => rfl
@[simp] theorem add_monoid_hom.comp_id {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) : add_monoid_hom.comp f (add_monoid_hom.id M) = f :=
add_monoid_hom.ext fun (x : M) => rfl
@[simp] theorem monoid_with_zero_hom.comp_id {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : monoid_with_zero_hom.comp f (monoid_with_zero_hom.id M) = f :=
monoid_with_zero_hom.ext fun (x : M) => rfl
@[simp] theorem zero_hom.id_comp {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] (f : zero_hom M N) : zero_hom.comp (zero_hom.id N) f = f :=
zero_hom.ext fun (x : M) => rfl
@[simp] theorem mul_hom.id_comp {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) : mul_hom.comp (mul_hom.id N) f = f :=
mul_hom.ext fun (x : M) => rfl
@[simp] theorem monoid_hom.id_comp {M : Type u_1} {N : Type u_2} [monoid M] [monoid N] (f : M →* N) : monoid_hom.comp (monoid_hom.id N) f = f :=
monoid_hom.ext fun (x : M) => rfl
@[simp] theorem monoid_with_zero_hom.id_comp {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : monoid_with_zero_hom.comp (monoid_with_zero_hom.id N) f = f :=
monoid_with_zero_hom.ext fun (x : M) => rfl
namespace monoid
/-- The monoid of endomorphisms. -/
protected def End (M : Type u_1) [monoid M] :=
M →* M
namespace End
protected instance monoid (M : Type u_1) [monoid M] : monoid (monoid.End M) :=
mk monoid_hom.comp sorry (monoid_hom.id M) monoid_hom.id_comp monoid_hom.comp_id
protected instance inhabited (M : Type u_1) [monoid M] : Inhabited (monoid.End M) :=
{ default := 1 }
protected instance has_coe_to_fun (M : Type u_1) [monoid M] : has_coe_to_fun (monoid.End M) :=
has_coe_to_fun.mk (fun (x : monoid.End M) => M → M) monoid_hom.to_fun
end End
@[simp] theorem coe_one (M : Type u_1) [monoid M] : ⇑1 = id :=
rfl
@[simp] theorem coe_mul (M : Type u_1) [monoid M] (f : monoid.End M) (g : monoid.End M) : ⇑(f * g) = ⇑f ∘ ⇑g :=
rfl
end monoid
namespace add_monoid
/-- The monoid of endomorphisms. -/
protected def End (A : Type u_6) [add_monoid A] :=
A →+ A
namespace End
protected instance monoid (A : Type u_6) [add_monoid A] : monoid (add_monoid.End A) :=
monoid.mk add_monoid_hom.comp sorry (add_monoid_hom.id A) add_monoid_hom.id_comp add_monoid_hom.comp_id
protected instance inhabited (A : Type u_6) [add_monoid A] : Inhabited (add_monoid.End A) :=
{ default := 1 }
protected instance has_coe_to_fun (A : Type u_6) [add_monoid A] : has_coe_to_fun (add_monoid.End A) :=
has_coe_to_fun.mk (fun (x : add_monoid.End A) => A → A) add_monoid_hom.to_fun
end End
@[simp] theorem coe_one (A : Type u_6) [add_monoid A] : ⇑1 = id :=
rfl
@[simp] theorem coe_mul (A : Type u_6) [add_monoid A] (f : add_monoid.End A) (g : add_monoid.End A) : ⇑(f * g) = ⇑f ∘ ⇑g :=
rfl
end add_monoid
/-- `1` is the homomorphism sending all elements to `1`. -/
/-- `1` is the multiplicative homomorphism sending all elements to `1`. -/
protected instance zero_hom.has_zero {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] : HasZero (zero_hom M N) :=
{ zero := zero_hom.mk (fun (_x : M) => 0) sorry }
/-- `1` is the monoid homomorphism sending all elements to `1`. -/
protected instance add_hom.has_zero {M : Type u_1} {N : Type u_2} [Add M] [add_monoid N] : HasZero (add_hom M N) :=
{ zero := add_hom.mk (fun (_x : M) => 0) sorry }
protected instance add_monoid_hom.has_zero {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] : HasZero (M →+ N) :=
{ zero := add_monoid_hom.mk (fun (_x : M) => 0) sorry sorry }
/-- `0` is the homomorphism sending all elements to `0`. -/
/-- `0` is the additive homomorphism sending all elements to `0`. -/
/-- `0` is the additive monoid homomorphism sending all elements to `0`. -/
@[simp] theorem one_hom.one_apply {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (x : M) : coe_fn 1 x = 1 :=
rfl
@[simp] theorem add_monoid_hom.zero_apply {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (x : M) : coe_fn 0 x = 0 :=
rfl
@[simp] theorem zero_hom.zero_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasZero M] [HasZero N] [HasZero P] (f : zero_hom M N) : zero_hom.comp 0 f = 0 :=
rfl
@[simp] theorem zero_hom.comp_zero {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasZero M] [HasZero N] [HasZero P] (f : zero_hom N P) : zero_hom.comp f 0 = 0 := sorry
protected instance one_hom.inhabited {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] : Inhabited (one_hom M N) :=
{ default := 1 }
protected instance add_hom.inhabited {M : Type u_1} {N : Type u_2} [Add M] [add_monoid N] : Inhabited (add_hom M N) :=
{ default := 0 }
-- unlike the other homs, `monoid_with_zero_hom` does not have a `1` or `0`
protected instance add_monoid_hom.inhabited {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] : Inhabited (M →+ N) :=
{ default := 0 }
protected instance monoid_with_zero_hom.inhabited {M : Type u_1} [monoid_with_zero M] : Inhabited (monoid_with_zero_hom M M) :=
{ default := monoid_with_zero_hom.id M }
namespace monoid_hom
/-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism
sending `x` to `f x * g x`. -/
protected instance has_mul {M : Type u_1} {N : Type u_2} {mM : monoid M} [comm_monoid N] : Mul (M →* N) :=
{ mul := fun (f g : M →* N) => mk (fun (m : M) => coe_fn f m * coe_fn g m) sorry sorry }
/-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the
additive monoid morphism sending `x` to `f x + g x`. -/
@[simp] theorem Mathlib.add_monoid_hom.add_apply {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_comm_monoid N} (f : M →+ N) (g : M →+ N) (x : M) : coe_fn (f + g) x = coe_fn f x + coe_fn g x :=
rfl
@[simp] theorem one_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [monoid N] [monoid P] (f : M →* N) : comp 1 f = 1 :=
rfl
@[simp] theorem Mathlib.add_monoid_hom.comp_zero {M : Type u_1} {N : Type u_2} {P : Type u_3} [add_monoid M] [add_monoid N] [add_monoid P] (f : N →+ P) : add_monoid_hom.comp f 0 = 0 := sorry
theorem mul_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [comm_monoid N] [comm_monoid P] (g₁ : N →* P) (g₂ : N →* P) (f : M →* N) : comp (g₁ * g₂) f = comp g₁ f * comp g₂ f :=
rfl
theorem comp_mul {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [comm_monoid N] [comm_monoid P] (g : N →* P) (f₁ : M →* N) (f₂ : M →* N) : comp g (f₁ * f₂) = comp g f₁ * comp g f₂ := sorry
/-- (M →* N) is a comm_monoid if N is commutative. -/
protected instance comm_monoid {M : Type u_1} {N : Type u_2} [monoid M] [comm_monoid N] : comm_monoid (M →* N) :=
comm_monoid.mk Mul.mul sorry 1 sorry sorry sorry
/-- `flip` arguments of `f : M →* N →* P` -/
def Mathlib.add_monoid_hom.flip {M : Type u_1} {N : Type u_2} {P : Type u_3} {mM : add_monoid M} {mN : add_monoid N} {mP : add_comm_monoid P} (f : M →+ N →+ P) : N →+ M →+ P :=
add_monoid_hom.mk (fun (y : N) => add_monoid_hom.mk (fun (x : M) => coe_fn (coe_fn f x) y) sorry sorry) sorry sorry
@[simp] theorem flip_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) (x : M) (y : N) : coe_fn (coe_fn (flip f) y) x = coe_fn (coe_fn f x) y :=
rfl
/-- Evaluation of a `monoid_hom` at a point as a monoid homomorphism. See also `monoid_hom.apply`
for the evaluation of any function at a point. -/
def Mathlib.add_monoid_hom.eval {M : Type u_1} {N : Type u_2} [add_monoid M] [add_comm_monoid N] : M →+ (M →+ N) →+ N :=
add_monoid_hom.flip (add_monoid_hom.id (M →+ N))
@[simp] theorem Mathlib.add_monoid_hom.eval_apply {M : Type u_1} {N : Type u_2} [add_monoid M] [add_comm_monoid N] (x : M) (f : M →+ N) : coe_fn (coe_fn add_monoid_hom.eval x) f = coe_fn f x :=
rfl
/-- Composition of monoid morphisms (`monoid_hom.comp`) as a monoid morphism. -/
def Mathlib.add_monoid_hom.comp_hom {M : Type u_1} {N : Type u_2} {P : Type u_3} [add_monoid M] [add_comm_monoid N] [add_comm_monoid P] : (N →+ P) →+ (M →+ N) →+ M →+ P :=
add_monoid_hom.mk (fun (g : N →+ P) => add_monoid_hom.mk (add_monoid_hom.comp g) sorry (add_monoid_hom.comp_add g))
sorry sorry
/-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/
theorem eq_on_inv {M : Type u_1} {G : Type u_2} [group G] [monoid M] {f : G →* M} {g : G →* M} {x : G} (h : coe_fn f x = coe_fn g x) : coe_fn f (x⁻¹) = coe_fn g (x⁻¹) :=
left_inv_eq_right_inv (map_mul_eq_one f (inv_mul_self x)) (Eq.subst (Eq.symm h) (map_mul_eq_one g) (mul_inv_self x))
/-- Group homomorphisms preserve inverse. -/
@[simp] theorem Mathlib.add_monoid_hom.map_neg {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G →+ H) (g : G) : coe_fn f (-g) = -coe_fn f g :=
eq_neg_of_add_eq_zero (add_monoid_hom.map_add_eq_zero f (neg_add_self g))
/-- Group homomorphisms preserve division. -/
@[simp] theorem Mathlib.add_monoid_hom.map_add_neg {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G →+ H) (g : G) (h : G) : coe_fn f (g + -h) = coe_fn f g + -coe_fn f h := sorry
/-- A homomorphism from a group to a monoid is injective iff its kernel is trivial. -/
theorem injective_iff {G : Type u_1} {H : Type u_2} [group G] [monoid H] (f : G →* H) : function.injective ⇑f ↔ ∀ (a : G), coe_fn f a = 1 → a = 1 := sorry
/-- Makes a group homomorphism from a proof that the map preserves multiplication. -/
def Mathlib.add_monoid_hom.mk' {M : Type u_1} {G : Type u_4} [mM : add_monoid M] [add_group G] (f : M → G) (map_mul : ∀ (a b : M), f (a + b) = f a + f b) : M →+ G :=
add_monoid_hom.mk f sorry map_mul
@[simp] theorem Mathlib.add_monoid_hom.coe_mk' {M : Type u_1} {G : Type u_4} [mM : add_monoid M] [add_group G] {f : M → G} (map_mul : ∀ (a b : M), f (a + b) = f a + f b) : ⇑(add_monoid_hom.mk' f map_mul) = f :=
rfl
/-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`.
-/
def of_map_mul_inv {G : Type u_4} [group G] {H : Type u_1} [group H] (f : G → H) (map_div : ∀ (a b : G), f (a * (b⁻¹)) = f a * (f b⁻¹)) : G →* H :=
mk' f sorry
@[simp] theorem Mathlib.add_monoid_hom.coe_of_map_add_neg {G : Type u_4} [add_group G] {H : Type u_1} [add_group H] (f : G → H) (map_div : ∀ (a b : G), f (a + -b) = f a + -f b) : ⇑(add_monoid_hom.of_map_add_neg f map_div) = f :=
rfl
/-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending
`x` to `(f x)⁻¹`. -/
protected instance Mathlib.add_monoid_hom.has_neg {M : Type u_1} {G : Type u_2} [add_monoid M] [add_comm_group G] : Neg (M →+ G) :=
{ neg := fun (f : M →+ G) => add_monoid_hom.mk' (fun (g : M) => -coe_fn f g) sorry }
/-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the
homomorphism sending `x` to `-(f x)`. -/
@[simp] theorem inv_apply {M : Type u_1} {G : Type u_2} {mM : monoid M} {gG : comm_group G} (f : M →* G) (x : M) : coe_fn (f⁻¹) x = (coe_fn f x⁻¹) :=
rfl
/-- If `f` and `g` are monoid homomorphisms to a commutative group, then `f / g` is the homomorphism
sending `x` to `(f x) / (g x). -/
protected instance has_div {M : Type u_1} {G : Type u_2} [monoid M] [comm_group G] : Div (M →* G) :=
{ div := fun (f g : M →* G) => mk' (fun (x : M) => coe_fn f x / coe_fn g x) sorry }
/-- If `f` and `g` are monoid homomorphisms to an additive commutative group, then `f - g`
is the homomorphism sending `x` to `(f x) - (g x). -/
@[simp] theorem Mathlib.add_monoid_hom.sub_apply {M : Type u_1} {G : Type u_2} {mM : add_monoid M} {gG : add_comm_group G} (f : M →+ G) (g : M →+ G) (x : M) : coe_fn (f - g) x = coe_fn f x - coe_fn g x :=
rfl
/-- If `G` is a commutative group, then `M →* G` a commutative group too. -/
protected instance Mathlib.add_monoid_hom.add_comm_group {M : Type u_1} {G : Type u_2} [add_monoid M] [add_comm_group G] : add_comm_group (M →+ G) :=
add_comm_group.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry Neg.neg Sub.sub sorry sorry
/-- If `G` is an additive commutative group, then `M →+ G` an additive commutative group too. -/
end monoid_hom
namespace add_monoid_hom
/-- Additive group homomorphisms preserve subtraction. -/
@[simp] theorem map_sub {G : Type u_4} {H : Type u_5} [add_group G] [add_group H] (f : G →+ H) (g : G) (h : G) : coe_fn f (g - h) = coe_fn f g - coe_fn f h := sorry
/-- Define a morphism of additive groups given a map which respects difference. -/
def of_map_sub {G : Type u_4} {H : Type u_5} [add_group G] [add_group H] (f : G → H) (hf : ∀ (x y : G), f (x - y) = f x - f y) : G →+ H :=
of_map_add_neg f sorry
@[simp] theorem coe_of_map_sub {G : Type u_4} {H : Type u_5} [add_group G] [add_group H] (f : G → H) (hf : ∀ (x y : G), f (x - y) = f x - f y) : ⇑(of_map_sub f hf) = f :=
rfl
end add_monoid_hom
@[simp] protected theorem add_semiconj_by.map {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {a : M} {x : M} {y : M} (h : add_semiconj_by a x y) (f : M →+ N) : add_semiconj_by (coe_fn f a) (coe_fn f x) (coe_fn f y) := sorry
@[simp] protected theorem add_commute.map {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {x : M} {y : M} (h : add_commute x y) (f : M →+ N) : add_commute (coe_fn f x) (coe_fn f y) :=
add_semiconj_by.map h f
|
78483ba5e917170dea1de8604c89f40ed93fb410 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/filter/germ.lean | 2a6c20199d729808225f43b9453f8f18757795fb | [
"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 | 20,804 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Abhimanyu Pallavi Sudhir
-/
import order.filter.basic
import algebra.module.pi
/-!
# Germ of a function at a filter
The germ of a function `f : α → β` at a filter `l : filter α` is the equivalence class of `f`
with respect to the equivalence relation `eventually_eq l`: `f ≈ g` means `∀ᶠ x in l, f x = g x`.
## Main definitions
We define
* `germ l β` to be the space of germs of functions `α → β` at a filter `l : filter α`;
* coercion from `α → β` to `germ l β`: `(f : germ l β)` is the germ of `f : α → β`
at `l : filter α`; this coercion is declared as `has_coe_t`, so it does not require an explicit
up arrow `↑`;
* coercion from `β` to `germ l β`: `(↑c : germ l β)` is the germ of the constant function
`λ x:α, c` at a filter `l`; this coercion is declared as `has_lift_t`, so it requires an explicit
up arrow `↑`, see [TPiL][TPiL_coe] for details.
* `map (F : β → γ) (f : germ l β)` to be the composition of a function `F` and a germ `f`;
* `map₂ (F : β → γ → δ) (f : germ l β) (g : germ l γ)` to be the germ of `λ x, F (f x) (g x)`
at `l`;
* `f.tendsto lb`: we say that a germ `f : germ l β` tends to a filter `lb` if its representatives
tend to `lb` along `l`;
* `f.comp_tendsto g hg` and `f.comp_tendsto' g hg`: given `f : germ l β` and a function
`g : γ → α` (resp., a germ `g : germ lc α`), if `g` tends to `l` along `lc`, then the composition
`f ∘ g` is a well-defined germ at `lc`;
* `germ.lift_pred`, `germ.lift_rel`: lift a predicate or a relation to the space of germs:
`(f : germ l β).lift_pred p` means `∀ᶠ x in l, p (f x)`, and similarly for a relation.
[TPiL_coe]: https://leanprover.github.io/theorem_proving_in_lean/type_classes.html#coercions-using-type-classes
We also define `map (F : β → γ) : germ l β → germ l γ` sending each germ `f` to `F ∘ f`.
For each of the following structures we prove that if `β` has this structure, then so does
`germ l β`:
* one-operation algebraic structures up to `comm_group`;
* `mul_zero_class`, `distrib`, `semiring`, `comm_semiring`, `ring`, `comm_ring`;
* `mul_action`, `distrib_mul_action`, `module`;
* `preorder`, `partial_order`, and `lattice` structures, as well as `bounded_order`;
* `ordered_cancel_comm_monoid` and `ordered_cancel_add_comm_monoid`.
## Tags
filter, germ
-/
namespace filter
variables {α β γ δ : Type*} {l : filter α} {f g h : α → β}
lemma const_eventually_eq' [ne_bot l] {a b : β} : (∀ᶠ x in l, a = b) ↔ a = b :=
eventually_const
lemma const_eventually_eq [ne_bot l] {a b : β} : ((λ _, a) =ᶠ[l] (λ _, b)) ↔ a = b :=
@const_eventually_eq' _ _ _ _ a b
lemma eventually_eq.comp_tendsto {f' : α → β} (H : f =ᶠ[l] f') {g : γ → α} {lc : filter γ}
(hg : tendsto g lc l) :
f ∘ g =ᶠ[lc] f' ∘ g :=
hg.eventually H
/-- Setoid used to define the space of germs. -/
def germ_setoid (l : filter α) (β : Type*) : setoid (α → β) :=
{ r := eventually_eq l,
iseqv := ⟨eventually_eq.refl _, λ _ _, eventually_eq.symm, λ _ _ _, eventually_eq.trans⟩ }
/-- The space of germs of functions `α → β` at a filter `l`. -/
def germ (l : filter α) (β : Type*) : Type* := quotient (germ_setoid l β)
/-- Setoid used to define the filter product. This is a dependent version of
`filter.germ_setoid`. -/
def product_setoid (l : filter α) (ε : α → Type*) : setoid (Π a, ε a) :=
{ r := λ f g, ∀ᶠ a in l, f a = g a,
iseqv := ⟨λ _, eventually_of_forall (λ _, rfl),
λ _ _ h, h.mono (λ _, eq.symm),
λ x y z h1 h2, h1.congr (h2.mono (λ x hx, hx ▸ iff.rfl))⟩ }
/-- The filter product `Π (a : α), ε a` at a filter `l`. This is a dependent version of
`filter.germ`. -/
@[protected] def product (l : filter α) (ε : α → Type*) : Type* := quotient (product_setoid l ε)
namespace product
variables {ε : α → Type*}
instance : has_coe_t (Π a, ε a) (l.product ε) := ⟨quotient.mk'⟩
instance [Π a, inhabited (ε a)] : inhabited (l.product ε) :=
⟨(↑(λ a, (default : ε a)) : l.product ε)⟩
end product
namespace germ
instance : has_coe_t (α → β) (germ l β) := ⟨quotient.mk'⟩
instance : has_lift_t β (germ l β) := ⟨λ c, ↑(λ (x : α), c)⟩
@[simp] lemma quot_mk_eq_coe (l : filter α) (f : α → β) : quot.mk _ f = (f : germ l β) := rfl
@[simp] lemma mk'_eq_coe (l : filter α) (f : α → β) : quotient.mk' f = (f : germ l β) := rfl
@[elab_as_eliminator]
lemma induction_on (f : germ l β) {p : germ l β → Prop} (h : ∀ f : α → β, p f) : p f :=
quotient.induction_on' f h
@[elab_as_eliminator]
lemma induction_on₂ (f : germ l β) (g : germ l γ) {p : germ l β → germ l γ → Prop}
(h : ∀ (f : α → β) (g : α → γ), p f g) : p f g :=
quotient.induction_on₂' f g h
@[elab_as_eliminator]
lemma induction_on₃ (f : germ l β) (g : germ l γ) (h : germ l δ)
{p : germ l β → germ l γ → germ l δ → Prop}
(H : ∀ (f : α → β) (g : α → γ) (h : α → δ), p f g h) :
p f g h :=
quotient.induction_on₃' f g h H
/-- Given a map `F : (α → β) → (γ → δ)` that sends functions eventually equal at `l` to functions
eventually equal at `lc`, returns a map from `germ l β` to `germ lc δ`. -/
def map' {lc : filter γ} (F : (α → β) → (γ → δ)) (hF : (l.eventually_eq ⇒ lc.eventually_eq) F F) :
germ l β → germ lc δ :=
quotient.map' F hF
/-- Given a germ `f : germ l β` and a function `F : (α → β) → γ` sending eventually equal functions
to the same value, returns the value `F` takes on functions having germ `f` at `l`. -/
def lift_on {γ : Sort*} (f : germ l β) (F : (α → β) → γ) (hF : (l.eventually_eq ⇒ (=)) F F) : γ :=
quotient.lift_on' f F hF
@[simp] lemma map'_coe {lc : filter γ} (F : (α → β) → (γ → δ))
(hF : (l.eventually_eq ⇒ lc.eventually_eq) F F) (f : α → β) :
map' F hF f = F f :=
rfl
@[simp, norm_cast] lemma coe_eq : (f : germ l β) = g ↔ (f =ᶠ[l] g) := quotient.eq'
alias coe_eq ↔ _ _root_.filter.eventually_eq.germ_eq
/-- Lift a function `β → γ` to a function `germ l β → germ l γ`. -/
def map (op : β → γ) : germ l β → germ l γ :=
map' ((∘) op) $ λ f g H, H.mono $ λ x H, congr_arg op H
@[simp] lemma map_coe (op : β → γ) (f : α → β) : map op (f : germ l β) = op ∘ f := rfl
@[simp] lemma map_id : map id = (id : germ l β → germ l β) := by { ext ⟨f⟩, refl }
lemma map_map (op₁ : γ → δ) (op₂ : β → γ) (f : germ l β) :
map op₁ (map op₂ f) = map (op₁ ∘ op₂) f :=
induction_on f $ λ f, rfl
/-- Lift a binary function `β → γ → δ` to a function `germ l β → germ l γ → germ l δ`. -/
def map₂ (op : β → γ → δ) : germ l β → germ l γ → germ l δ :=
quotient.map₂' (λ f g x, op (f x) (g x)) $ λ f f' Hf g g' Hg,
Hg.mp $ Hf.mono $ λ x Hf Hg, by simp only [Hf, Hg]
@[simp] lemma map₂_coe (op : β → γ → δ) (f : α → β) (g : α → γ) :
map₂ op (f : germ l β) g = λ x, op (f x) (g x) :=
rfl
/-- A germ at `l` of maps from `α` to `β` tends to `lb : filter β` if it is represented by a map
which tends to `lb` along `l`. -/
protected def tendsto (f : germ l β) (lb : filter β) : Prop :=
lift_on f (λ f, tendsto f l lb) $ λ f g H, propext (tendsto_congr' H)
@[simp, norm_cast] lemma coe_tendsto {f : α → β} {lb : filter β} :
(f : germ l β).tendsto lb ↔ tendsto f l lb :=
iff.rfl
alias coe_tendsto ↔ _ _root_.filter.tendsto.germ_tendsto
/-- Given two germs `f : germ l β`, and `g : germ lc α`, where `l : filter α`, if `g` tends to `l`,
then the composition `f ∘ g` is well-defined as a germ at `lc`. -/
def comp_tendsto' (f : germ l β) {lc : filter γ} (g : germ lc α) (hg : g.tendsto l) :
germ lc β :=
lift_on f (λ f, g.map f) $ λ f₁ f₂ hF, (induction_on g $ λ g hg, coe_eq.2 $ hg.eventually hF) hg
@[simp] lemma coe_comp_tendsto' (f : α → β) {lc : filter γ} {g : germ lc α} (hg : g.tendsto l) :
(f : germ l β).comp_tendsto' g hg = g.map f :=
rfl
/-- Given a germ `f : germ l β` and a function `g : γ → α`, where `l : filter α`, if `g` tends
to `l` along `lc : filter γ`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/
def comp_tendsto (f : germ l β) {lc : filter γ} (g : γ → α) (hg : tendsto g lc l) :
germ lc β :=
f.comp_tendsto' _ hg.germ_tendsto
@[simp] lemma coe_comp_tendsto (f : α → β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) :
(f : germ l β).comp_tendsto g hg = f ∘ g :=
rfl
@[simp] lemma comp_tendsto'_coe (f : germ l β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) :
f.comp_tendsto' _ hg.germ_tendsto = f.comp_tendsto g hg :=
rfl
@[simp, norm_cast] lemma const_inj [ne_bot l] {a b : β} : (↑a : germ l β) = ↑b ↔ a = b :=
coe_eq.trans $ const_eventually_eq
@[simp] lemma map_const (l : filter α) (a : β) (f : β → γ) :
(↑a : germ l β).map f = ↑(f a) :=
rfl
@[simp] lemma map₂_const (l : filter α) (b : β) (c : γ) (f : β → γ → δ) :
map₂ f (↑b : germ l β) ↑c = ↑(f b c) :=
rfl
@[simp] lemma const_comp_tendsto {l : filter α} (b : β) {lc : filter γ} {g : γ → α}
(hg : tendsto g lc l) :
(↑b : germ l β).comp_tendsto g hg = ↑b :=
rfl
@[simp] lemma const_comp_tendsto' {l : filter α} (b : β) {lc : filter γ} {g : germ lc α}
(hg : g.tendsto l) :
(↑b : germ l β).comp_tendsto' g hg = ↑b :=
induction_on g (λ _ _, rfl) hg
/-- Lift a predicate on `β` to `germ l β`. -/
def lift_pred (p : β → Prop) (f : germ l β) : Prop :=
lift_on f (λ f, ∀ᶠ x in l, p (f x)) $
λ f g H, propext $ eventually_congr $ H.mono $ λ x hx, hx ▸ iff.rfl
@[simp] lemma lift_pred_coe {p : β → Prop} {f : α → β} :
lift_pred p (f : germ l β) ↔ ∀ᶠ x in l, p (f x) :=
iff.rfl
lemma lift_pred_const {p : β → Prop} {x : β} (hx : p x) :
lift_pred p (↑x : germ l β) :=
eventually_of_forall $ λ y, hx
@[simp] lemma lift_pred_const_iff [ne_bot l] {p : β → Prop} {x : β} :
lift_pred p (↑x : germ l β) ↔ p x :=
@eventually_const _ _ _ (p x)
/-- Lift a relation `r : β → γ → Prop` to `germ l β → germ l γ → Prop`. -/
def lift_rel (r : β → γ → Prop) (f : germ l β) (g : germ l γ) : Prop :=
quotient.lift_on₂' f g (λ f g, ∀ᶠ x in l, r (f x) (g x)) $
λ f g f' g' Hf Hg, propext $ eventually_congr $ Hg.mp $ Hf.mono $ λ x hf hg, hf ▸ hg ▸ iff.rfl
@[simp] lemma lift_rel_coe {r : β → γ → Prop} {f : α → β} {g : α → γ} :
lift_rel r (f : germ l β) g ↔ ∀ᶠ x in l, r (f x) (g x) :=
iff.rfl
lemma lift_rel_const {r : β → γ → Prop} {x : β} {y : γ} (h : r x y) :
lift_rel r (↑x : germ l β) ↑y :=
eventually_of_forall $ λ _, h
@[simp] lemma lift_rel_const_iff [ne_bot l] {r : β → γ → Prop} {x : β} {y : γ} :
lift_rel r (↑x : germ l β) ↑y ↔ r x y :=
@eventually_const _ _ _ (r x y)
instance [inhabited β] : inhabited (germ l β) := ⟨↑(default : β)⟩
section monoid
variables {M : Type*} {G : Type*}
@[to_additive]
instance [has_mul M] : has_mul (germ l M) := ⟨map₂ (*)⟩
@[simp, norm_cast, to_additive]
lemma coe_mul [has_mul M] (f g : α → M) : ↑(f * g) = (f * g : germ l M) := rfl
@[to_additive]
instance [has_one M] : has_one (germ l M) := ⟨↑(1:M)⟩
@[simp, norm_cast, to_additive]
lemma coe_one [has_one M] : ↑(1 : α → M) = (1 : germ l M) := rfl
@[to_additive]
instance [semigroup M] : semigroup (germ l M) :=
function.surjective.semigroup coe (surjective_quot_mk _) (λ a b, coe_mul a b)
@[to_additive]
instance [comm_semigroup M] : comm_semigroup (germ l M) :=
function.surjective.comm_semigroup coe (surjective_quot_mk _) (λ a b, coe_mul a b)
@[to_additive add_left_cancel_semigroup]
instance [left_cancel_semigroup M] : left_cancel_semigroup (germ l M) :=
{ mul := (*),
mul_left_cancel := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃ H,
coe_eq.2 ((coe_eq.1 H).mono $ λ x, mul_left_cancel),
.. germ.semigroup }
@[to_additive add_right_cancel_semigroup]
instance [right_cancel_semigroup M] : right_cancel_semigroup (germ l M) :=
{ mul := (*),
mul_right_cancel := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃ H,
coe_eq.2 $ (coe_eq.1 H).mono $ λ x, mul_right_cancel,
.. germ.semigroup }
instance [has_vadd M G] : has_vadd M (germ l G) := ⟨λ n, map ((+ᵥ) n)⟩
@[to_additive] instance [has_smul M G] : has_smul M (germ l G) := ⟨λ n, map ((•) n)⟩
@[to_additive has_smul] instance [has_pow G M] : has_pow (germ l G) M := ⟨λ f n, map (^ n) f⟩
@[simp, norm_cast, to_additive]
lemma coe_smul [has_smul M G] (n : M) (f : α → G) : ↑(n • f) = (n • f : germ l G) := rfl
@[simp, norm_cast, to_additive]
lemma const_smul [has_smul M G] (n : M) (a : G) : (↑(n • a) : germ l G) = n • ↑a := rfl
@[simp, norm_cast, to_additive coe_smul]
lemma coe_pow [has_pow G M] (f : α → G) (n : M) : ↑(f ^ n) = (f ^ n : germ l G) := rfl
@[simp, norm_cast, to_additive const_smul]
lemma const_pow [has_pow G M] (a : G) (n : M) : (↑(a ^ n) : germ l G) = ↑a ^ n := rfl
@[to_additive]
instance [monoid M] : monoid (germ l M) :=
function.surjective.monoid coe (surjective_quot_mk _) rfl (λ _ _, rfl) (λ _ _, rfl)
/-- Coercion from functions to germs as a monoid homomorphism. -/
@[to_additive "Coercion from functions to germs as an additive monoid homomorphism."]
def coe_mul_hom [monoid M] (l : filter α) : (α → M) →* germ l M := ⟨coe, rfl, λ f g, rfl⟩
@[simp, to_additive]
lemma coe_coe_mul_hom [monoid M] : (coe_mul_hom l : (α → M) → germ l M) = coe := rfl
@[to_additive]
instance [comm_monoid M] : comm_monoid (germ l M) :=
{ mul := (*),
one := 1,
.. germ.comm_semigroup, .. germ.monoid }
instance [add_monoid_with_one M] : add_monoid_with_one (germ l M) :=
{ nat_cast := λ n, ↑(n : M),
nat_cast_zero := congr_arg coe nat.cast_zero,
nat_cast_succ := λ n, congr_arg coe (nat.cast_succ _),
.. germ.has_one, .. germ.add_monoid }
@[to_additive]
instance [has_inv G] : has_inv (germ l G) := ⟨map has_inv.inv⟩
@[simp, norm_cast, to_additive]
lemma coe_inv [has_inv G] (f : α → G) : ↑f⁻¹ = (f⁻¹ : germ l G) := rfl
@[simp, norm_cast, to_additive]
lemma const_inv [has_inv G] (a : G) : (↑a⁻¹ : germ l G) = (↑a)⁻¹ := rfl
@[to_additive]
instance [has_div M] : has_div (germ l M) := ⟨map₂ (/)⟩
@[simp, norm_cast, to_additive]
lemma coe_div [has_div M] (f g : α → M) : ↑(f / g) = (f / g : germ l M) := rfl
@[simp, norm_cast, to_additive]
lemma const_div [has_div M] (a b : M) : (↑(a / b) : germ l M) = ↑a / ↑b := rfl
@[to_additive sub_neg_monoid]
instance [div_inv_monoid G] : div_inv_monoid (germ l G) :=
function.surjective.div_inv_monoid coe (surjective_quot_mk _) rfl (λ _ _, rfl)
(λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
@[to_additive]
instance [group G] : group (germ l G) :=
{ mul := (*),
one := 1,
mul_left_inv := by { rintros ⟨f⟩, exact congr_arg (quot.mk _) (mul_left_inv f) },
.. germ.div_inv_monoid }
@[to_additive]
instance [comm_group G] : comm_group (germ l G) :=
{ mul := (*),
one := 1,
inv := has_inv.inv,
.. germ.group, .. germ.comm_monoid }
end monoid
section ring
variables {R : Type*}
instance nontrivial [nontrivial R] [ne_bot l] : nontrivial (germ l R) :=
let ⟨x, y, h⟩ := exists_pair_ne R in ⟨⟨↑x, ↑y, mt const_inj.1 h⟩⟩
instance [mul_zero_class R] : mul_zero_class (germ l R) :=
{ zero := 0,
mul := (*),
mul_zero := λ f, induction_on f $ λ f, by { norm_cast, rw [mul_zero] },
zero_mul := λ f, induction_on f $ λ f, by { norm_cast, rw [zero_mul] } }
instance [distrib R] : distrib (germ l R) :=
{ mul := (*),
add := (+),
left_distrib := λ f g h, induction_on₃ f g h $ λ f g h, by { norm_cast, rw [left_distrib] },
right_distrib := λ f g h, induction_on₃ f g h $ λ f g h, by { norm_cast, rw [right_distrib] } }
instance [semiring R] : semiring (germ l R) :=
{ .. germ.add_comm_monoid, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class,
.. germ.add_monoid_with_one }
/-- Coercion `(α → R) → germ l R` as a `ring_hom`. -/
def coe_ring_hom [semiring R] (l : filter α) : (α → R) →+* germ l R :=
{ to_fun := coe, .. (coe_mul_hom l : _ →* germ l R), .. (coe_add_hom l : _ →+ germ l R) }
@[simp] lemma coe_coe_ring_hom [semiring R] : (coe_ring_hom l : (α → R) → germ l R) = coe := rfl
instance [ring R] : ring (germ l R) :=
{ .. germ.add_comm_group, .. germ.semiring }
instance [comm_semiring R] : comm_semiring (germ l R) :=
{ .. germ.semiring, .. germ.comm_monoid }
instance [comm_ring R] : comm_ring (germ l R) :=
{ .. germ.ring, .. germ.comm_monoid }
end ring
section module
variables {M N R : Type*}
@[to_additive]
instance has_smul' [has_smul M β] : has_smul (germ l M) (germ l β) := ⟨map₂ (•)⟩
@[simp, norm_cast, to_additive] lemma coe_smul' [has_smul M β] (c : α → M) (f : α → β) :
↑(c • f) = (c : germ l M) • (f : germ l β) :=
rfl
@[to_additive]
instance [monoid M] [mul_action M β] : mul_action M (germ l β) :=
{ one_smul := λ f, induction_on f $ λ f, by { norm_cast, simp only [one_smul] },
mul_smul := λ c₁ c₂ f, induction_on f $ λ f, by { norm_cast, simp only [mul_smul] } }
@[to_additive]
instance mul_action' [monoid M] [mul_action M β] : mul_action (germ l M) (germ l β) :=
{ one_smul := λ f, induction_on f $ λ f, by simp only [← coe_one, ← coe_smul', one_smul],
mul_smul := λ c₁ c₂ f, induction_on₃ c₁ c₂ f $ λ c₁ c₂ f, by { norm_cast, simp only [mul_smul] } }
instance [monoid M] [add_monoid N] [distrib_mul_action M N] :
distrib_mul_action M (germ l N) :=
{ smul_add := λ c f g, induction_on₂ f g $ λ f g, by { norm_cast, simp only [smul_add] },
smul_zero := λ c, by simp only [← coe_zero, ← coe_smul, smul_zero] }
instance distrib_mul_action' [monoid M] [add_monoid N] [distrib_mul_action M N] :
distrib_mul_action (germ l M) (germ l N) :=
{ smul_add := λ c f g, induction_on₃ c f g $ λ c f g, by { norm_cast, simp only [smul_add] },
smul_zero := λ c, induction_on c $ λ c, by simp only [← coe_zero, ← coe_smul', smul_zero] }
instance [semiring R] [add_comm_monoid M] [module R M] :
module R (germ l M) :=
{ add_smul := λ c₁ c₂ f, induction_on f $ λ f, by { norm_cast, simp only [add_smul] },
zero_smul := λ f, induction_on f $ λ f, by { norm_cast, simp only [zero_smul, coe_zero] } }
instance module' [semiring R] [add_comm_monoid M] [module R M] :
module (germ l R) (germ l M) :=
{ add_smul := λ c₁ c₂ f, induction_on₃ c₁ c₂ f $ λ c₁ c₂ f, by { norm_cast, simp only [add_smul] },
zero_smul := λ f, induction_on f $ λ f, by simp only [← coe_zero, ← coe_smul', zero_smul] }
end module
instance [has_le β] : has_le (germ l β) := ⟨lift_rel (≤)⟩
lemma le_def [has_le β] : ((≤) : germ l β → germ l β → Prop) = lift_rel (≤) := rfl
@[simp] lemma coe_le [has_le β] : (f : germ l β) ≤ g ↔ f ≤ᶠ[l] g := iff.rfl
lemma coe_nonneg [has_le β] [has_zero β] {f : α → β} : 0 ≤ (f : germ l β) ↔ ∀ᶠ x in l, 0 ≤ f x :=
iff.rfl
lemma const_le [has_le β] {x y : β} : x ≤ y → (↑x : germ l β) ≤ ↑y := lift_rel_const
@[simp, norm_cast]
lemma const_le_iff [has_le β] [ne_bot l] {x y : β} : (↑x : germ l β) ≤ ↑y ↔ x ≤ y :=
lift_rel_const_iff
instance [preorder β] : preorder (germ l β) :=
{ le := (≤),
le_refl := λ f, induction_on f $ eventually_le.refl l,
le_trans := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃, eventually_le.trans }
instance [partial_order β] : partial_order (germ l β) :=
{ le := (≤),
le_antisymm := λ f g, induction_on₂ f g $ λ f g h₁ h₂, (eventually_le.antisymm h₁ h₂).germ_eq,
.. germ.preorder }
instance [has_bot β] : has_bot (germ l β) := ⟨↑(⊥ : β)⟩
instance [has_top β] : has_top (germ l β) := ⟨↑(⊤ : β)⟩
@[simp, norm_cast] lemma const_bot [has_bot β] : (↑(⊥ : β) : germ l β) = ⊥ := rfl
@[simp, norm_cast] lemma const_top [has_top β] : (↑(⊤ : β) : germ l β) = ⊤ := rfl
instance [has_le β] [order_bot β] : order_bot (germ l β) :=
{ bot := ⊥,
bot_le := λ f, induction_on f $ λ f, eventually_of_forall $ λ x, bot_le }
instance [has_le β] [order_top β] : order_top (germ l β) :=
{ top := ⊤,
le_top := λ f, induction_on f $ λ f, eventually_of_forall $ λ x, le_top }
instance [has_le β] [bounded_order β] : bounded_order (germ l β) :=
{ ..germ.order_bot, ..germ.order_top }
end germ
end filter
|
52b5d85f4a7df20a219a0be34c37e553e3e63c28 | 398b53a5e02ce35196531591f84bb2f6b034ce5a | /tpil/presentation.lean | 7cdf1acb7b0056ef99dc22b283bb902f93480e43 | [
"MIT"
] | permissive | crockeo/math-exercises | 64f07a9371a72895bbd97f49a854dcb6821b18ab | cf9150ef9e025f1b7929ba070a783e7a71f24f31 | refs/heads/master | 1,607,910,221,030 | 1,581,231,762,000 | 1,581,231,762,000 | 234,595,189 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,292 | lean | import init.data.fin
import init.data.list
import init.data.nat.basic
open nat
namespace hidden
universe u
-- Defining a list
inductive list (α : Type u) : Type (u + 1)
| nil : list
| cons : α → list → list
namespace list
def length {α : Type u} : list α → ℕ
| (nil α) := 0
| (cons _ l) := 1 + length l
def nth_le {α : Type u} : Π (l : list α) (n : ℕ), n < l.length → α
| (nil α) n h := absurd h (not_lt_zero n)
| (cons a l) 0 h := a
| (cons a l) (n + 1) h :=
nth_le
l
n
begin
rw length at h,
rw add_comm 1 (length l) at h,
repeat {rw add_one_eq_succ at h},
exact lt_of_succ_lt_succ h,
end
end list
-- Defining the fin type
structure fin (n : ℕ) :=
(val : ℕ)
(is_lt : val < n)
-- Defining a vector type, which is a list with a given length.
def vector (α : Type u) (n : ℕ) := { l : list α // l.length = n }
-- Gets an item from a vector, so long as it's within the range of the index.
def get {α : Type u} {n : ℕ} : Π (v : vector α n), fin n → α
| ⟨ l, h ⟩ i :=
l.nth_le i.1
begin
rw h,
exact i.2,
end
end hidden
|
dd5055e0333dc702fc34cf37e768826f6ccbaf0b | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/doNotation4.lean | 4987ebc142d91a94ff94188505a31d9d47a2403d | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,428 | lean | abbrev M := StateRefT Nat IO
def testM {α} [ToString α] [BEq α] (init : Nat) (expected : α) (x : M α): IO Unit := do
let v ← x.run' init
IO.println ("result " ++ toString v)
unless v == expected do
throw $ IO.userError "unexpected"
def dec (x : Nat) : M Unit := do
if (← get) == 0 then
throw $ IO.userError "value is zero"
modify (· - x)
def f1 (x : Nat) : M Nat := do
try
dec x
dec x
get
catch _ =>
pure 1000
finally
IO.println "done"
#eval testM 10 8 $ f1 1
#eval testM 1 1000 $ f1 1
def f2 (x : Nat) : M Nat := do
try
if x > 100 then
return x
dec x
pure (← get)
catch _ =>
pure 1000
finally
IO.println "done"
#eval testM 0 500 $ f2 500
#eval testM 0 1000 $ f2 50
#eval testM 200 150 $ f2 50
def f3 (x : Nat) : M Nat := do
try
dec x
pure (← get)
catch
| IO.Error.userError err => IO.println err; pure 2000
| ex => throw ex
#eval testM 0 2000 $ f3 10
def f4 (xs : List Nat) : M Nat := do
let mut y := 0
for x in xs do
IO.println s!"x: {x}"
try
dec x
y := y + x
catch _ =>
set y
break
get
#eval testM 5 6 $ f4 [1, 2, 3, 4, 5, 6]
#eval testM 40 19 $ f4 [1, 2, 3, 4, 5, 6]
def f5 (xs : List Nat) : M Nat := do
let mut y := 0
for x in xs do
IO.println s!"x: {x}"
try
dec x
y := y + x
catch _ =>
return y
IO.println "after for"
modify (· - 1)
get
#eval testM 5 6 $ f5 [1, 2, 3, 4, 5, 6]
#eval testM 40 18 $ f5 [1, 2, 3, 4, 5, 6]
|
a345598d5908f98e275d43a428d573d192024524 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /category_theory/examples/rings.lean | c2d24d5efe99617e64a364018f3752894c7c9156 | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 1,788 | lean | /- Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl
Introduce CommRing -- the category of commutative rings.
Currently only the basic setup.
-/
import category_theory.examples.monoids
import category_theory.embedding
import algebra.ring
universes u v
open category_theory
namespace category_theory.examples
/-- The category of rings. -/
@[reducible] def Ring : Type (u+1) := bundled ring
instance (x : Ring) : ring x := x.str
instance concrete_is_ring_hom : concrete_category @is_ring_hom :=
⟨by introsI α ia; apply_instance,
by introsI α β γ ia ib ic f g hf hg; apply_instance⟩
instance Ring_hom_is_ring_hom {R S : Ring} (f : R ⟶ S) : is_ring_hom (f : R → S) := f.2
/-- The category of commutative rings. -/
@[reducible] def CommRing : Type (u+1) := bundled comm_ring
instance (x : CommRing) : comm_ring x := x.str
@[reducible] def is_comm_ring_hom {α β} [comm_ring α] [comm_ring β] (f : α → β) : Prop :=
is_ring_hom f
instance concrete_is_comm_ring_hom : concrete_category @is_comm_ring_hom :=
⟨by introsI α ia; apply_instance,
by introsI α β γ ia ib ic f g hf hg; apply_instance⟩
instance CommRing_hom_is_comm_ring_hom {R S : CommRing} (f : R ⟶ S) : is_comm_ring_hom (f : R → S) := f.2
namespace CommRing
/-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/
def forget_to_CommMon : CommRing ⥤ CommMon :=
concrete_functor
(by intros _ c; exact { ..c })
(by introsI _ _ _ _ f i; exact { ..i })
instance : faithful (forget_to_CommMon) := {}
example : faithful (forget_to_CommMon ⋙ CommMon.forget_to_Mon) := by apply_instance
end CommRing
end category_theory.examples
|
bf539738c63e39d4a71a68d629acefe14a679735 | 964a8bb66c2eb89b920fe65d0ec2f77eab0d5f65 | /src/hanoiinteractive.lean | 10ba2e18c51ff96f96a1a4821a4e9f2ab0c0ddfe | [
"MIT"
] | permissive | SnobbyDragon/leanhanoi | 9990a7b586f1d843d39c3c7aab7ac0b5eefbe653 | a42811ce5ab55e0451880a8c111c75b082936d39 | refs/heads/master | 1,675,735,182,689 | 1,609,387,288,000 | 1,609,387,288,000 | 284,167,126 | 8 | 1 | MIT | 1,609,262,129,000 | 1,596,247,349,000 | Lean | UTF-8 | Lean | false | false | 711 | lean | import hanoiwidget
meta def hanoi_tactic := tactic
namespace hanoi_tactic
open tactic
local attribute [reducible] hanoi_tactic
meta instance : monad hanoi_tactic := infer_instance
meta def step {α : Type} (m : hanoi_tactic α) : hanoi_tactic unit :=
tactic.step m
meta def istep {α} (a b c d : ℕ) (t : hanoi_tactic α) : hanoi_tactic unit :=
tactic.istep a b c d t
meta def save_info (p : pos) : hanoi_tactic unit := hanoi_save_info p
meta instance : interactive.executor hanoi_tactic :=
{ config_type := unit,
execute_with := λ n tac, tac
}
/- Now that these magic methods are implemented, you can write
begin [hanoi_tactic]
...
end
-/
end hanoi_tactic
|
0e245821f7b0c979e4d9b522cc5ecfb394eb905e | 618003631150032a5676f229d13a079ac875ff77 | /src/data/pnat/intervals.lean | 197022d4cc3043108ceee1762c646fb61c747751 | [
"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 | 804 | 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⟩,
-- why can't we do this directly?
inj' := λ n m h, subtype.eq (by { replace h := congr_arg subtype.val h, exact h }) }
@[simp] lemma Ico.mem : ∀ {n m l : ℕ+}, l ∈ Ico n m ↔ n ≤ l ∧ l < m :=
by { rintro ⟨n, hn⟩ ⟨m, hm⟩ ⟨l, hl⟩, simp [pnat.Ico] }
@[simp] lemma Ico.card (l u : ℕ+) : (Ico l u).card = u - l := by simp [pnat.Ico]
end pnat
|
0815b94d5a2d4e74e9ca2fe2e603827692af9e66 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/nat/dist.lean | ab6118438f23da51a5e11424c5e26063b148e022 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 3,993 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jeremy Avigad
Distance function on the natural numbers.
-/
import data.nat.basic
namespace nat
/- distance -/
/-- Distance (absolute value of difference) between natural numbers. -/
def dist (n m : ℕ) := (n - m) + (m - n)
theorem dist.def (n m : ℕ) : dist n m = (n - m) + (m - n) := rfl
theorem dist_comm (n m : ℕ) : dist n m = dist m n :=
by simp [dist.def, add_comm]
@[simp] theorem dist_self (n : ℕ) : dist n n = 0 :=
by simp [dist.def, nat.sub_self]
theorem eq_of_dist_eq_zero {n m : ℕ} (h : dist n m = 0) : n = m :=
have n - m = 0, from eq_zero_of_add_eq_zero_right h,
have n ≤ m, from nat.le_of_sub_eq_zero this,
have m - n = 0, from eq_zero_of_add_eq_zero_left h,
have m ≤ n, from nat.le_of_sub_eq_zero this,
le_antisymm ‹n ≤ m› ‹m ≤ n›
theorem dist_eq_zero {n m : ℕ} (h : n = m) : dist n m = 0 :=
begin rw [h, dist_self] end
theorem dist_eq_sub_of_le {n m : ℕ} (h : n ≤ m) : dist n m = m - n :=
begin rw [dist.def, sub_eq_zero_of_le h, zero_add] end
theorem dist_eq_sub_of_ge {n m : ℕ} (h : n ≥ m) : dist n m = n - m :=
begin rw [dist_comm], apply dist_eq_sub_of_le h end
theorem dist_zero_right (n : ℕ) : dist n 0 = n :=
eq.trans (dist_eq_sub_of_ge (zero_le n)) (nat.sub_zero n)
theorem dist_zero_left (n : ℕ) : dist 0 n = n :=
eq.trans (dist_eq_sub_of_le (zero_le n)) (nat.sub_zero n)
theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m :=
calc
dist (n + k) (m + k) = ((n + k) - (m + k)) + ((m + k)-(n + k)) : rfl
... = (n - m) + ((m + k) - (n + k)) : by rw nat.add_sub_add_right
... = (n - m) + (m - n) : by rw nat.add_sub_add_right
theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m :=
begin rw [add_comm k n, add_comm k m], apply dist_add_add_right end
theorem dist_eq_intro {n m k l : ℕ} (h : n + m = k + l) : dist n k = dist l m :=
calc
dist n k = dist (n + m) (k + m) : by rw dist_add_add_right
... = dist (k + l) (k + m) : by rw h
... = dist l m : by rw dist_add_add_left
protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) :=
or.elim (le_total k m)
(assume : k ≤ m,
begin rw ←nat.add_sub_assoc this, apply nat.sub_le_sub_right, apply nat.le_sub_add end)
(assume : k ≥ m,
begin rw [sub_eq_zero_of_le this, add_zero], apply nat.sub_le_sub_left, exact this end)
theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k :=
have dist n m + dist m k = (n - m) + (m - k) + ((k - m) + (m - n)),
by simp [dist.def, add_comm, add_left_comm],
begin
rw [this, dist.def], apply add_le_add, repeat { apply nat.sub_lt_sub_add_sub }
end
theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k :=
by rw [dist.def, dist.def, right_distrib, nat.mul_sub_right_distrib, nat.mul_sub_right_distrib]
theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m :=
by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm]
-- TODO(Jeremy): do when we have max and minx
--theorem dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j :=
--sorry
/-
or.elim (lt_or_ge i j)
(assume : i < j,
by rw [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this])
(assume : i ≥ j,
by rw [max_eq_left this , min_eq_right this, dist_eq_sub_of_ge this])
-/
theorem dist_succ_succ {i j : nat} : dist (succ i) (succ j) = dist i j :=
by simp [dist.def, succ_sub_succ]
theorem dist_pos_of_ne {i j : nat} : i ≠ j → 0 < dist i j :=
assume hne, nat.lt_by_cases
(assume : i < j,
begin rw [dist_eq_sub_of_le (le_of_lt this)], apply nat.sub_pos_of_lt this end)
(assume : i = j, by contradiction)
(assume : i > j,
begin rw [dist_eq_sub_of_ge (le_of_lt this)], apply nat.sub_pos_of_lt this end)
end nat
|
e1cd0b4db9e3ca115b3858cd2515969067598159 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/algebra/group_power.lean | 24d2e87023246ceae2ffa4c510a23e73b3db2e3d | [
"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 | 27,180 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
The power operation on monoids and groups. We separate this from group, because it depends on
nat, which in turn depends on other parts of algebra.
We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation
a^n is used for the first, but users can locally redefine it to gpow when needed.
Note: power adopts the convention that 0^0=1.
-/
import data.int.basic
variables {M : Type*} {N : Type*} {G : Type*} {H : Type*} {A : Type*} {B : Type*}
{R : Type*} {S : Type*}
/-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/
def monoid.pow [monoid M] (a : M) : ℕ → M
| 0 := 1
| (n+1) := a * monoid.pow n
def add_monoid.smul [add_monoid A] (n : ℕ) (a : A) : A :=
@monoid.pow (multiplicative A) _ a n
precedence `•`:70
localized "infix ` • ` := add_monoid.smul" in add_monoid
@[priority 5] instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩
/-!
### (Additive) monoid
-/
section monoid
variables [monoid M] [monoid N] [add_monoid A] [add_monoid B]
@[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl
@[simp] theorem add_monoid.zero_smul (a : A) : 0 • a = 0 := rfl
theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl
theorem succ_smul (a : A) (n : ℕ) : (n+1)•a = a + n•a := rfl
@[simp] theorem pow_one (a : M) : a^1 = a := mul_one _
@[simp] theorem add_monoid.one_smul (a : A) : 1•a = a := add_zero _
@[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) :
a ^ (if P then b else c) = if P then a ^ b else a ^ c :=
by split_ifs; refl
@[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) :
(if P then a else b) ^ c = if P then a ^ c else b ^ c :=
by split_ifs; refl
-- In this lemma we need to use `congr` because
-- `if_simp_congr`, the congruence lemma `simp` uses for rewriting inside `ite`,
-- modifies the decidable instance.
@[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) :
a ^ (if P then 1 else 0) = if P then a else 1 :=
by { simp, congr }
theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n :=
by induction n with n ih; [rw [pow_zero, one_mul, mul_one],
rw [pow_succ, mul_assoc, ih]]
theorem smul_add_comm' : ∀ (a : A) (n : ℕ), n•a + a = a + n•a :=
@pow_mul_comm' (multiplicative A) _
theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a :=
by rw [pow_succ, pow_mul_comm']
theorem succ_smul' (a : A) (n : ℕ) : (n+1)•a = n•a + a :=
by rw [succ_smul, smul_add_comm']
theorem pow_two (a : M) : a^2 = a * a :=
show a*(a*1)=a*a, by rw mul_one
theorem two_smul (a : A) : 2•a = a + a :=
show a+(a+0)=a+a, by rw add_zero
theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n :=
by induction n with n ih; [rw [add_zero, pow_zero, mul_one],
rw [pow_succ, ← pow_mul_comm', ← mul_assoc, ← ih, ← pow_succ']]; refl
theorem add_monoid.add_smul : ∀ (a : A) (m n : ℕ), (m + n)•a = m•a + n•a :=
@pow_add (multiplicative A) _
@[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 :=
by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]]
@[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : A) = 0 :=
by induction n with n ih; [refl, rw [succ_smul, ih, zero_add]]
theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n :=
by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl
theorem add_monoid.mul_smul' : ∀ (a : A) (m n : ℕ), m * n • a = n•(m•a) :=
@pow_mul (multiplicative A) _
theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m :=
by rw [mul_comm, pow_mul]
theorem add_monoid.mul_smul (a : A) (m n : ℕ) : m * n • a = m•(n•a) :=
by rw [mul_comm, add_monoid.mul_smul']
@[simp] theorem add_monoid.smul_one [has_one A] : ∀ n : ℕ, n • (1 : A) = n :=
nat.eq_cast _ (add_monoid.zero_smul _) (add_monoid.one_smul _) (add_monoid.add_smul _)
theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _
theorem bit0_smul (a : A) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _
theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a :=
by rw [bit1, pow_succ', pow_bit0]
theorem bit1_smul : ∀ (a : A) (n : ℕ), bit1 n • a = n•a + n•a + a :=
@pow_bit1 (multiplicative A) _
theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m :=
by rw [←pow_add, ←pow_add, add_comm]
theorem smul_add_comm : ∀ (a : A) (m n : ℕ), m•a + n•a = n•a + m•a :=
@pow_mul_comm (multiplicative A) _
@[simp, priority 500]
theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n :=
by induction n with n ih; [refl, rw [list.repeat_succ, list.prod_cons, ih]]; refl
@[simp, priority 500]
theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n • a :=
@list.prod_repeat (multiplicative A) _
theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n
| 0 := f.map_one
| (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow]
theorem add_monoid_hom.map_smul (f : A →+ B) (a : A) (n : ℕ) : f (n • a) = n • f a :=
f.to_multiplicative.map_pow a n
theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) :
∀(n : ℕ), f (a ^ n) = (f a) ^ n :=
(monoid_hom.of f).map_pow a
theorem is_add_monoid_hom.map_smul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) :
f (n • a) = n • f a :=
(add_monoid_hom.of f).map_smul a n
@[simp] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n :=
(units.coe_hom M).map_pow u n
end monoid
@[simp] theorem nat.pow_eq_pow (p q : ℕ) :
@has_pow.pow _ _ monoid.has_pow p q = p ^ q :=
by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ, mul_comm, ih]]
@[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n :=
by induction m with m ih; [rw [add_monoid.zero_smul, zero_mul],
rw [succ_smul', ih, nat.succ_mul]]
/-!
### Commutative (additive) monoid
-/
section comm_monoid
variables [comm_monoid M] [add_comm_monoid A]
theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n :=
by induction n with n ih; [exact (mul_one _).symm,
simp only [pow_succ, ih, mul_assoc, mul_left_comm]]
theorem add_monoid.smul_add : ∀ (a b : A) (n : ℕ), n•(a + b) = n•a + n•b :=
@mul_pow (multiplicative A) _
instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) :=
{ map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ }
instance add_monoid.smul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (add_monoid.smul n : A → A) :=
{ map_add := λ _ _, add_monoid.smul_add _ _ _, map_zero := add_monoid.smul_zero _ }
end comm_monoid
section group
variables [group G] [group H] [add_group A] [add_group B]
section nat
@[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ :=
by induction n with n ih; [exact one_inv.symm,
rw [pow_succ', pow_succ, ih, mul_inv_rev]]
@[simp] theorem add_monoid.neg_smul : ∀ (a : A) (n : ℕ), n•(-a) = -(n•a) :=
@inv_pow (multiplicative A) _
theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ :=
have h1 : m - n + n = m, from nat.sub_add_cancel h,
have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1],
eq_mul_inv_of_mul_eq h2
theorem add_monoid.smul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n)•a = m•a - n•a :=
@pow_sub (multiplicative A) _
theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m :=
by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _)
theorem add_monoid.smul_neg_comm : ∀ (a : A) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) :=
@pow_inv_comm (multiplicative A) _
end nat
open int
/--
The power operation in a group. This extends `monoid.pow` to negative integers
with the definition `a^(-n) = (a^n)⁻¹`.
-/
def gpow (a : G) : ℤ → G
| (of_nat n) := a^n
| -[1+n] := (a^(nat.succ n))⁻¹
def gsmul (n : ℤ) (a : A) : A :=
@gpow (multiplicative A) _ a n
@[priority 10] instance group.has_pow : has_pow G ℤ := ⟨gpow⟩
localized "infix ` • `:70 := gsmul" in add_group
localized "infix ` •ℕ `:70 := add_monoid.smul" in smul
localized "infix ` •ℤ `:70 := gsmul" in smul
@[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl
@[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl
theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl
theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n • a = n •ℕ a := rfl
@[simp] theorem gpow_neg_succ (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl
@[simp] theorem gsmul_neg_succ (a : A) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl
local attribute [ematch] le_of_lt
open nat
@[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl
@[simp] theorem zero_gsmul (a : A) : (0:ℤ) • a = 0 := rfl
@[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := mul_one _
@[simp] theorem one_gsmul (a : A) : (1:ℤ) • a = a := add_zero _
@[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1
| (n : ℕ) := one_pow _
| -[1+ n] := show _⁻¹=(1:G), by rw [_root_.one_pow, one_inv]
@[simp] theorem gsmul_zero : ∀ (n : ℤ), n • (0 : A) = 0 :=
@one_gpow (multiplicative A) _
@[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := rfl
| 0 := one_inv.symm
| -[1+ n] := (inv_inv _).symm
@[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n • a = -(n • a) :=
@gpow_neg (multiplicative A) _
theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x
theorem neg_one_gsmul (x : A) : (-1:ℤ) • x = -x := congr_arg has_neg.neg $ add_monoid.one_smul x
theorem gsmul_one [has_one A] (n : ℤ) : n • (1 : A) = n :=
by cases n; simp
theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := inv_pow a n
| -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1)
theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a :=
@inv_gpow (multiplicative A) _ a n
private lemma gpow_add_aux (a : G) (m n : nat) :
a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] :=
or.elim (nat.lt_or_ge m (nat.succ n))
(assume h1 : m < succ n,
have h2 : m ≤ n, from le_of_lt_succ h1,
suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n],
by rwa [of_nat_add_neg_succ_of_nat_of_lt h1],
show (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n],
by rw [← succ_sub h2, pow_sub _ (le_of_lt h1), mul_inv_rev, inv_inv]; refl)
(assume : m ≥ succ n,
suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]),
by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption,
suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this,
by rw pow_sub; assumption)
theorem gpow_add (a : G) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j
| (of_nat m) (of_nat n) := pow_add _ _ _
| (of_nat m) -[1+n] := gpow_add_aux _ _ _
| -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux,
gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm]
| -[1+m] -[1+n] :=
suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this,
by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev]
theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) • a = i • a + j • a :=
@gpow_add (multiplicative A) _
theorem gpow_add_one (a : G) (i : ℤ) : a ^ (i + 1) = a ^ i * a :=
by rw [gpow_add, gpow_one]
theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) • a = i • a + a :=
@gpow_add_one (multiplicative A) _
theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [gpow_add, gpow_one]
theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) • a = a + i • a :=
@gpow_one_add (multiplicative A) _
theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i :=
by rw [← gpow_add, ← gpow_add, add_comm]
theorem gsmul_add_comm : ∀ (a : A) (i j), i • a + j • a = j • a + i • a :=
@gpow_mul_comm (multiplicative A) _
theorem gpow_mul (a : G) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n
| (m : ℕ) (n : ℕ) := pow_mul _ _ _
| (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $
show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl
| -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $
show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow]; refl
| -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $
show _ = (_⁻¹^_)⁻¹, by rw [inv_pow, inv_inv]
theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n • a = n • (m • a) :=
@gpow_mul (multiplicative A) _
theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, gpow_mul]
theorem gsmul_mul (a : A) (m n : ℤ) : m * n • a = m • (n • a) :=
by rw [mul_comm, gsmul_mul']
theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _
theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _
theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
by rw [bit1, gpow_add]; simp [gpow_bit0]
theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n • a = n • a + n • a + a :=
@gpow_bit1 (multiplicative A) _
theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n :=
by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)]
theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n • a) = n • f a :=
f.to_multiplicative.map_gpow a n
end group
open_locale smul
section comm_group
variables [comm_group G] [add_comm_group A]
theorem mul_gpow (a b : G) : ∀ n:ℤ, (a * b)^n = a^n * b^n
| (n : ℕ) := mul_pow a b n
| -[1+ n] := show _⁻¹=_⁻¹*_⁻¹, by rw [mul_pow, mul_inv_rev, mul_comm]
theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b :=
@mul_gpow (multiplicative A) _
theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b :=
by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg]
instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) :=
{ map_mul := λ _ _, mul_gpow _ _ n }
instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) :=
{ map_add := λ _ _, gsmul_add _ _ n }
end comm_group
@[simp] lemma with_bot.coe_smul [add_monoid A] (a : A) (n : ℕ) :
((add_monoid.smul n a : A) : with_bot A) = add_monoid.smul n a :=
add_monoid_hom.map_smul ⟨_, with_bot.coe_zero, with_bot.coe_add⟩ a n
theorem add_monoid.smul_eq_mul' [semiring R] (a : R) (n : ℕ) : n • a = a * n :=
by induction n with n ih; [rw [add_monoid.zero_smul, nat.cast_zero, mul_zero],
rw [succ_smul', ih, nat.cast_succ, mul_add, mul_one]]
theorem add_monoid.smul_eq_mul [semiring R] (n : ℕ) (a : R) : n • a = n * a :=
by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm]
theorem add_monoid.mul_smul_left [semiring R] (a b : R) (n : ℕ) : n • (a * b) = a * (n • b) :=
by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc]
theorem add_monoid.mul_smul_assoc [semiring R] (a b : R) (n : ℕ) : n • (a * b) = n • a * b :=
by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc]
lemma zero_pow [semiring R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0
| (n+1) _ := zero_mul _
@[simp, move_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m :=
by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]]
@[simp, move_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m :=
by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]]
theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k :=
by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]]
@[simp] lemma ring_hom.map_pow [semiring R] [semiring S] (f : R →+* S) (a) :
∀ n : ℕ, f (a ^ n) = (f a) ^ n :=
f.to_monoid_hom.map_pow a
lemma is_semiring_hom.map_pow [semiring R] [semiring S] (f : R → S) [is_semiring_hom f] (a) :
∀ n : ℕ, f (a ^ n) = (f a) ^ n :=
is_monoid_hom.map_pow f a
theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1
| 0 := or.inl rfl
| (n+1) := (neg_one_pow_eq_or n).swap.imp
(λ h, by rw [pow_succ, h, neg_one_mul, neg_neg])
(λ h, by rw [pow_succ, h, mul_one])
lemma pow_dvd_pow [comm_semiring R] (a : R) {m n : ℕ} (h : m ≤ n) :
a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩
theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a
| (n : ℕ) := add_monoid.smul_eq_mul _ _
| -[1+ n] := show -(_•_)=-_*_, by rw [neg_mul_eq_neg_mul_symm, add_monoid.smul_eq_mul, nat.cast_succ]
theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n :=
by rw [gsmul_eq_mul, int.mul_cast_comm]
theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) :=
by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc]
theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b :=
by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc]
@[simp]
lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul]
lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp
@[simp, move_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m :=
by induction m with m ih; [exact int.cast_one,
rw [pow_succ, pow_succ, int.cast_mul, ih]]
lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = -1 ^ (n % 2) :=
by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two]
theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) :=
by rw [pow_two, pow_two, mul_self_sub_mul_self]
theorem pow_eq_zero [domain R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 :=
begin
induction n with n ih,
{ rw pow_zero at H,
rw [← mul_one x, H, mul_zero] },
exact or.cases_on (mul_eq_zero.1 H) id ih
end
@[field_simps] theorem pow_ne_zero [domain R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
mt pow_eq_zero h
theorem one_div_pow [division_ring R] {a : R} (n : ℕ) : (1 / a) ^ n = 1 / a ^ n :=
by induction n with n ih; [exact (div_one _).symm,
rw [pow_succ', ih, division_ring.one_div_mul_one_div]]; refl
@[simp] theorem division_ring.inv_pow [division_ring R] {a : R} (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ :=
by simpa only [inv_eq_one_div] using one_div_pow n
@[simp] theorem div_pow [field R] (a : R) {b : R} (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n :=
by rw [div_eq_mul_one_div, mul_pow, one_div_pow, ← div_eq_mul_one_div]
theorem add_monoid.smul_nonneg [ordered_comm_monoid R] {a : R} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a
| 0 := le_refl _
| (n+1) := add_nonneg' H (add_monoid.smul_nonneg n)
lemma pow_abs [decidable_linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) :=
by induction n with n ih; [exact (abs_one).symm,
rw [pow_succ, pow_succ, ih, abs_mul]]
lemma abs_neg_one_pow [decidable_linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 :=
by rw [←pow_abs, abs_neg, abs_one, one_pow]
@[field_simps] lemma inv_pow' [field R] (a : R) (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ :=
by induction n; simp [*, pow_succ, mul_inv', mul_comm]
@[field_simps] lemma pow_div [field R] (a b : R) (n : ℕ) : (a / b)^n = a^n / b^n :=
by simp [div_eq_mul_inv, mul_pow, inv_pow']
lemma pow_inv [division_ring R] (a : R) : ∀ n : ℕ, a ≠ 0 → (a^n)⁻¹ = (a⁻¹)^n
| 0 ha := inv_one
| (n+1) ha := by rw [pow_succ, pow_succ', mul_inv', pow_inv _ ha]
namespace add_monoid
variable [ordered_comm_monoid A]
theorem smul_le_smul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a :=
let ⟨k, hk⟩ := nat.le.dest h in
calc n • a = n • a + 0 : (add_zero _).symm
... ≤ n • a + k • a : add_le_add_left' (smul_nonneg ha _)
... = m • a : by rw [← hk, add_smul]
lemma smul_le_smul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i • a ≤ i • b
| 0 := by simp
| (k+1) := add_le_add' hab (smul_le_smul_of_le_right _)
end add_monoid
namespace canonically_ordered_semiring
variable [canonically_ordered_comm_semiring R]
theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n
| 0 := canonically_ordered_semiring.zero_lt_one
| (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩
lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i
| 0 := by simp
| (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k)
theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n :=
by simpa only [one_pow] using pow_le_pow_of_le_left H n
theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:=
by simpa only [one_pow] using pow_le_pow_of_le_left H n
end canonically_ordered_semiring
section linear_ordered_semiring
variable [linear_ordered_semiring R]
theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n
| 0 := zero_lt_one
| (n+1) := mul_pos H (pow_pos _)
theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n
| 0 := zero_le_one
| (n+1) := mul_nonneg H (pow_nonneg _)
theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) :
x ^ n < y ^ n :=
begin
cases lt_or_eq_of_le Hxpos,
{ rw ←nat.sub_add_cancel Hnpos,
induction (n - 1), { simpa only [pow_one] },
rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one],
apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) },
{ rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),}
end
theorem pow_right_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n)
(Hxyn : x ^ n = y ^ n) : x = y :=
begin
rcases lt_trichotomy x y with hxy | rfl | hyx,
{ exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) },
{ refl },
{ exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) },
end
theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n
| 0 := le_refl _
| (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n)
zero_le_one (le_trans zero_le_one H)
/-- Bernoulli's inequality. This version works for semirings but requires
an additional hypothesis `0 ≤ a * a`. -/
theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) :
∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n
| 0 := le_of_eq $ add_zero _
| (n+1) :=
calc 1 + (n + 1) • a ≤ (1 + a) * (1 + n • a) :
by simpa [succ_smul, mul_add, add_mul, add_monoid.mul_smul_left, add_comm, add_left_comm]
using add_monoid.smul_nonneg Hsqr n
... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H
theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
let ⟨k, hk⟩ := nat.le.dest h in
calc a ^ n = a ^ n * 1 : (mul_one _).symm
... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left
(one_le_pow_of_one_le ha _)
(pow_nonneg (le_trans zero_le_one ha) _)
... = a ^ m : by rw [←hk, pow_add]
lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m :=
begin
have h' : 1 ≤ a := le_of_lt h,
have h'' : 0 < a := lt_trans zero_lt_one h,
cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)],
exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'')
end
lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i
| 0 := by simp
| (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab)
lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b :=
lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h
private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) :
∀ k : ℕ, a ^ (i + k + 1) < a ^ i
| 0 :=
begin
simp only [add_zero],
rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one
end
| (k+1) :=
begin
rw ←one_mul (a^i),
apply mul_lt_mul ha _ _ zero_le_one,
{ apply le_of_lt, apply pow_lt_pow_of_lt_one_aux },
{ show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h }
end
private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) :
∀ k : ℕ, a ^ (i + k) ≤ a ^ i
| 0 := by simp
| (k+1) := by rw [←add_assoc, ←one_mul (a^i)];
exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one
lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1)
{i j : ℕ} (hij : i < j) : a ^ j < a ^ i :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in
by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _
lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1)
{i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in
by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _
lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1
| 0 h0 h1 := le_refl (1 : R)
| (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1)
end linear_ordered_semiring
theorem pow_two_nonneg [linear_ordered_ring R] (a : R) : 0 ≤ a ^ 2 :=
by { rw pow_two, exact mul_self_nonneg _ }
/-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/
theorem one_add_mul_le_pow [linear_ordered_ring R] {a : R} (H : -2 ≤ a) :
∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n
| 0 := le_of_eq $ add_zero _
| 1 := by simp
| (n+2) :=
have H' : 0 ≤ 2 + a,
from neg_le_iff_add_nonneg.1 H,
have 0 ≤ n • (a * a * (2 + a)) + a * a,
from add_nonneg (add_monoid.smul_nonneg (mul_nonneg (mul_self_nonneg a) H') n)
(mul_self_nonneg a),
calc 1 + (n + 2) • a ≤ 1 + (n + 2) • a + (n • (a * a * (2 + a)) + a * a) :
(le_add_iff_nonneg_right _).2 this
... = (1 + a) * (1 + a) * (1 + n • a) :
by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_smul, add_monoid.smul_add,
add_monoid.mul_smul_assoc, (add_monoid.mul_smul_left _ _ _).symm],
ac_refl }
... ≤ (1 + a) * (1 + a) * (1 + a)^n :
mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a))
... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc]
/-- Bernoulli's inequality reformulated to estimate `a^n`. -/
theorem one_add_sub_mul_le_pow [linear_ordered_ring R]
{a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n :=
have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 },
by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n
namespace int
lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) :=
by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one]
end int
@[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 :=
by simp [pow, monoid.pow]
lemma div_sq_cancel {α} [field α] {a : α} (ha : a ≠ 0) (b : α) : a^2 * b / a = a * b :=
by rw [pow_two, mul_assoc, mul_div_cancel_left _ ha]
|
f67732cc39c1b30f25c631544074993ee2e140e0 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/topology/algebra/ordered/monotone_convergence.lean | 04f161049c5b28348e660c73b7294c7fb786484a | [
"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 | 13,977 | lean | /-
Copyright (c) 2021 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth, Yury Kudryashov
-/
import topology.algebra.ordered.basic
/-!
# Bounded monotone sequences converge
In this file we prove a few theorems of the form “if the range of a monotone function `f : ι → α`
admits a least upper bound `a`, then `f x` tends to `a` as `x → ∞`”, as well as version of this
statement for (conditionally) complete lattices that use `⨆ x, f x` instead of `is_lub`.
These theorems work for linear orders with order topologies as well as their products (both in terms
of `prod` and in terms of function types). In order to reduce code duplication, we introduce two
typeclasses (one for the property formulated above and one for the dual property), prove theorems
assuming one of these typeclasses, and provide instances for linear orders and their products.
We also prove some "inverse" results: if `f n` is a monotone sequence and `a` is its limit,
then `f n ≤ a` for all `n`.
## Tags
monotone convergence
-/
open filter set function
open_locale filter topological_space classical
variables {α β : Type*}
/-- We say that `α` is a `Sup_convergence_class` if the following holds. Let `f : ι → α` be a
monotone function, let `a : α` be a least upper bound of `set.range f`. Then `f x` tends to `𝓝 a` as
`x → ∞` (formally, at the filter `filter.at_top`). We require this for `ι = (s : set α)`, `f = coe`
in the definition, then prove it for any `f` in `tendsto_at_top_is_lub`.
This property holds for linear orders with order topology as well as their products. -/
class Sup_convergence_class (α : Type*) [preorder α] [topological_space α] : Prop :=
(tendsto_coe_at_top_is_lub : ∀ (a : α) (s : set α), is_lub s a → tendsto (coe : s → α) at_top (𝓝 a))
/-- We say that `α` is an `Inf_convergence_class` if the following holds. Let `f : ι → α` be a
monotone function, let `a : α` be a greatest lower bound of `set.range f`. Then `f x` tends to `𝓝 a`
as `x → -∞` (formally, at the filter `filter.at_bot`). We require this for `ι = (s : set α)`,
`f = coe` in the definition, then prove it for any `f` in `tendsto_at_bot_is_glb`.
This property holds for linear orders with order topology as well as their products. -/
class Inf_convergence_class (α : Type*) [preorder α] [topological_space α] : Prop :=
(tendsto_coe_at_bot_is_glb : ∀ (a : α) (s : set α), is_glb s a → tendsto (coe : s → α) at_bot (𝓝 a))
instance order_dual.Sup_convergence_class [preorder α] [topological_space α]
[Inf_convergence_class α] : Sup_convergence_class (order_dual α) :=
⟨‹Inf_convergence_class α›.1⟩
instance order_dual.Inf_convergence_class [preorder α] [topological_space α]
[Sup_convergence_class α] : Inf_convergence_class (order_dual α) :=
⟨‹Sup_convergence_class α›.1⟩
@[priority 100] -- see Note [lower instance priority]
instance linear_order.Sup_convergence_class [topological_space α] [linear_order α]
[order_topology α] : Sup_convergence_class α :=
begin
refine ⟨λ a s ha, tendsto_order.2 ⟨λ b hb, _, λ b hb, _⟩⟩,
{ rcases ha.exists_between hb with ⟨c, hcs, bc, bca⟩,
lift c to s using hcs,
refine (eventually_ge_at_top c).mono (λ x hx, bc.trans_le hx) },
{ exact eventually_of_forall (λ x, (ha.1 x.2).trans_lt hb) }
end
@[priority 100] -- see Note [lower instance priority]
instance linear_order.Inf_convergence_class [topological_space α] [linear_order α]
[order_topology α] : Inf_convergence_class α :=
show Inf_convergence_class (order_dual $ order_dual α), from order_dual.Inf_convergence_class
section
variables {ι : Type*} [preorder ι] [topological_space α]
section is_lub
variables [preorder α] [Sup_convergence_class α] {f : ι → α} {a : α}
lemma tendsto_at_top_is_lub (h_mono : monotone f) (ha : is_lub (set.range f) a) :
tendsto f at_top (𝓝 a) :=
begin
suffices : tendsto (range_factorization f) at_top at_top,
from (Sup_convergence_class.tendsto_coe_at_top_is_lub _ _ ha).comp this,
exact h_mono.range_factorization.tendsto_at_top_at_top (λ b, b.2.imp $ λ a ha, ha.ge)
end
lemma tendsto_at_bot_is_lub (h_anti : antitone f)
(ha : is_lub (set.range f) a) : tendsto f at_bot (𝓝 a) :=
@tendsto_at_top_is_lub α (order_dual ι) _ _ _ _ f a h_anti.dual ha
end is_lub
section is_glb
variables [preorder α] [Inf_convergence_class α] {f : ι → α} {a : α}
lemma tendsto_at_bot_is_glb (h_mono : monotone f) (ha : is_glb (set.range f) a) :
tendsto f at_bot (𝓝 a) :=
@tendsto_at_top_is_lub (order_dual α) (order_dual ι) _ _ _ _ f a h_mono.dual ha
lemma tendsto_at_top_is_glb (h_anti : antitone f)
(ha : is_glb (set.range f) a) :
tendsto f at_top (𝓝 a) :=
@tendsto_at_top_is_lub (order_dual α) ι _ _ _ _ f a h_anti ha
end is_glb
section csupr
variables [conditionally_complete_lattice α] [Sup_convergence_class α] {f : ι → α} {a : α}
lemma tendsto_at_top_csupr (h_mono : monotone f) (hbdd : bdd_above $ range f) :
tendsto f at_top (𝓝 (⨆i, f i)) :=
begin
casesI is_empty_or_nonempty ι,
exacts [tendsto_of_is_empty, tendsto_at_top_is_lub h_mono (is_lub_csupr hbdd)]
end
lemma tendsto_at_bot_csupr (h_anti : antitone f)
(hbdd : bdd_above $ range f) :
tendsto f at_bot (𝓝 (⨆i, f i)) :=
@tendsto_at_top_csupr α (order_dual ι) _ _ _ _ _ h_anti.dual hbdd
end csupr
section cinfi
variables [conditionally_complete_lattice α] [Inf_convergence_class α] {f : ι → α} {a : α}
lemma tendsto_at_bot_cinfi (h_mono : monotone f) (hbdd : bdd_below $ range f) :
tendsto f at_bot (𝓝 (⨅i, f i)) :=
@tendsto_at_top_csupr (order_dual α) (order_dual ι) _ _ _ _ _ h_mono.dual hbdd
lemma tendsto_at_top_cinfi (h_anti : antitone f)
(hbdd : bdd_below $ range f) :
tendsto f at_top (𝓝 (⨅i, f i)) :=
@tendsto_at_top_csupr (order_dual α) ι _ _ _ _ _ h_anti hbdd
end cinfi
section supr
variables [complete_lattice α] [Sup_convergence_class α] {f : ι → α} {a : α}
lemma tendsto_at_top_supr (h_mono : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) :=
tendsto_at_top_csupr h_mono (order_top.bdd_above _)
lemma tendsto_at_bot_supr (h_anti : antitone f) :
tendsto f at_bot (𝓝 (⨆i, f i)) :=
tendsto_at_bot_csupr h_anti (order_top.bdd_above _)
end supr
section infi
variables [complete_lattice α] [Inf_convergence_class α] {f : ι → α} {a : α}
lemma tendsto_at_bot_infi (h_mono : monotone f) : tendsto f at_bot (𝓝 (⨅i, f i)) :=
tendsto_at_bot_cinfi h_mono (order_bot.bdd_below _)
lemma tendsto_at_top_infi (h_anti : antitone f) :
tendsto f at_top (𝓝 (⨅i, f i)) :=
tendsto_at_top_cinfi h_anti (order_bot.bdd_below _)
end infi
end
instance [preorder α] [preorder β] [topological_space α] [topological_space β]
[Sup_convergence_class α] [Sup_convergence_class β] : Sup_convergence_class (α × β) :=
begin
constructor,
rintro ⟨a, b⟩ s h,
rw [is_lub_prod, ← range_restrict, ← range_restrict] at h,
have A : tendsto (λ x : s, (x : α × β).1) at_top (𝓝 a),
from tendsto_at_top_is_lub (monotone_fst.restrict s) h.1,
have B : tendsto (λ x : s, (x : α × β).2) at_top (𝓝 b),
from tendsto_at_top_is_lub (monotone_snd.restrict s) h.2,
convert A.prod_mk_nhds B,
ext1 ⟨⟨x, y⟩, h⟩, refl
end
instance [preorder α] [preorder β] [topological_space α] [topological_space β]
[Inf_convergence_class α] [Inf_convergence_class β] : Inf_convergence_class (α × β) :=
show Inf_convergence_class (order_dual $ (order_dual α × order_dual β)),
from order_dual.Inf_convergence_class
instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)]
[Π i, Sup_convergence_class (α i)] : Sup_convergence_class (Π i, α i) :=
begin
refine ⟨λ f s h, _⟩,
simp only [is_lub_pi, ← range_restrict] at h,
exact tendsto_pi_nhds.2 (λ i, tendsto_at_top_is_lub ((monotone_eval _).restrict _) (h i))
end
instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)]
[Π i, Inf_convergence_class (α i)] : Inf_convergence_class (Π i, α i) :=
show Inf_convergence_class (order_dual $ Π i, order_dual (α i)),
from order_dual.Inf_convergence_class
instance pi.Sup_convergence_class' {ι : Type*} [preorder α] [topological_space α]
[Sup_convergence_class α] : Sup_convergence_class (ι → α) :=
pi.Sup_convergence_class
instance pi.Inf_convergence_class' {ι : Type*} [preorder α] [topological_space α]
[Inf_convergence_class α] : Inf_convergence_class (ι → α) :=
pi.Inf_convergence_class
lemma tendsto_of_monotone {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) :
tendsto f at_top at_top ∨ (∃ l, tendsto f at_top (𝓝 l)) :=
if H : bdd_above (range f) then or.inr ⟨_, tendsto_at_top_csupr h_mono H⟩
else or.inl $ tendsto_at_top_at_top_of_monotone' h_mono H
lemma tendsto_iff_tendsto_subseq_of_monotone {ι₁ ι₂ α : Type*} [semilattice_sup ι₁] [preorder ι₂]
[nonempty ι₁] [topological_space α] [conditionally_complete_linear_order α] [order_topology α]
[no_max_order α] {f : ι₂ → α} {φ : ι₁ → ι₂} {l : α} (hf : monotone f)
(hg : tendsto φ at_top at_top) :
tendsto f at_top (𝓝 l) ↔ tendsto (f ∘ φ) at_top (𝓝 l) :=
begin
split; intro h,
{ exact h.comp hg },
{ rcases tendsto_of_monotone hf with h' | ⟨l', hl'⟩,
{ exact (not_tendsto_at_top_of_tendsto_nhds h (h'.comp hg)).elim },
{ rwa tendsto_nhds_unique h (hl'.comp hg) } }
end
/-! The next family of results, such as `is_lub_of_tendsto_at_top` and `supr_eq_of_tendsto`, are
converses to the standard fact that bounded monotone functions converge. They state, that if a
monotone function `f` tends to `a` along `filter.at_top`, then that value `a` is a least upper bound
for the range of `f`.
Related theorems above (`is_lub.is_lub_of_tendsto`, `is_glb.is_glb_of_tendsto` etc) cover the case
when `f x` tends to `a` as `x` tends to some point `b` in the domain. -/
lemma monotone.ge_of_tendsto [topological_space α] [preorder α] [order_closed_topology α]
[semilattice_sup β] {f : β → α} {a : α} (hf : monotone f)
(ha : tendsto f at_top (𝓝 a)) (b : β) :
f b ≤ a :=
begin
haveI : nonempty β := nonempty.intro b,
exact ge_of_tendsto ha ((eventually_ge_at_top b).mono (λ _ hxy, hf hxy))
end
lemma monotone.le_of_tendsto [topological_space α] [preorder α] [order_closed_topology α]
[semilattice_inf β] {f : β → α} {a : α} (hf : monotone f)
(ha : tendsto f at_bot (𝓝 a)) (b : β) :
a ≤ f b :=
hf.dual.ge_of_tendsto ha b
lemma antitone.le_of_tendsto [topological_space α] [preorder α] [order_closed_topology α]
[semilattice_sup β] {f : β → α} {a : α} (hf : antitone f)
(ha : tendsto f at_top (𝓝 a)) (b : β) :
a ≤ f b :=
hf.dual_right.ge_of_tendsto ha b
lemma antitone.ge_of_tendsto [topological_space α] [preorder α] [order_closed_topology α]
[semilattice_inf β] {f : β → α} {a : α} (hf : antitone f)
(ha : tendsto f at_bot (𝓝 a)) (b : β) :
f b ≤ a :=
hf.dual_right.le_of_tendsto ha b
lemma is_lub_of_tendsto_at_top [topological_space α] [preorder α] [order_closed_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f)
(ha : tendsto f at_top (𝓝 a)) :
is_lub (set.range f) a :=
begin
split,
{ rintros _ ⟨b, rfl⟩,
exact hf.ge_of_tendsto ha b },
{ exact λ _ hb, le_of_tendsto' ha (λ x, hb (set.mem_range_self x)) }
end
lemma is_glb_of_tendsto_at_bot [topological_space α] [preorder α] [order_closed_topology α]
[nonempty β] [semilattice_inf β] {f : β → α} {a : α} (hf : monotone f)
(ha : tendsto f at_bot (𝓝 a)) :
is_glb (set.range f) a :=
@is_lub_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ _ _ hf.dual ha
lemma is_lub_of_tendsto_at_bot [topological_space α] [preorder α] [order_closed_topology α]
[nonempty β] [semilattice_inf β] {f : β → α} {a : α} (hf : antitone f)
(ha : tendsto f at_bot (𝓝 a)) :
is_lub (set.range f) a :=
@is_lub_of_tendsto_at_top α (order_dual β) _ _ _ _ _ _ _ hf.dual_left ha
lemma is_glb_of_tendsto_at_top [topological_space α] [preorder α] [order_closed_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : antitone f)
(ha : tendsto f at_top (𝓝 a)) :
is_glb (set.range f) a :=
@is_glb_of_tendsto_at_bot α (order_dual β) _ _ _ _ _ _ _ hf.dual_left ha
lemma supr_eq_of_tendsto {α β} [topological_space α] [complete_linear_order α] [order_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) :
tendsto f at_top (𝓝 a) → supr f = a :=
tendsto_nhds_unique (tendsto_at_top_supr hf)
lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : antitone f) :
tendsto f at_top (𝓝 a) → infi f = a :=
tendsto_nhds_unique (tendsto_at_top_infi hf)
lemma supr_eq_supr_subseq_of_monotone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α]
{l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : monotone f)
(hφ : tendsto φ l at_top) :
(⨆ i, f i) = (⨆ i, f (φ i)) :=
le_antisymm
(supr_le_supr2 $ λ i, exists_imp_exists (λ j (hj : i ≤ φ j), hf hj)
(hφ.eventually $ eventually_ge_at_top i).exists)
(supr_le_supr2 $ λ i, ⟨φ i, le_rfl⟩)
lemma infi_eq_infi_subseq_of_monotone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α]
{l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : monotone f)
(hφ : tendsto φ l at_bot) :
(⨅ i, f i) = (⨅ i, f (φ i)) :=
supr_eq_supr_subseq_of_monotone hf.dual hφ
|
630c21fc8d8d6d880e85ba10f6ed61b7a0769fe2 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/special_functions/trigonometric/series.lean | 0665bc3e9122f309fe1822d69432618e39dfd51b | [
"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 | 4,575 | lean | /-
Copyright (c) 2023 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import analysis.special_functions.exponential
/-!
# Trigonometric functions as sums of infinite series
In this file we express trigonometric functions in terms of their series expansion.
## Main results
* `complex.has_sum_cos`, `complex.tsum_cos`: `complex.cos` as the sum of an infinite series.
* `real.has_sum_cos`, `real.tsum_cos`: `real.cos` as the sum of an infinite series.
* `complex.has_sum_sin`, `complex.tsum_sin`: `complex.sin` as the sum of an infinite series.
* `real.has_sum_sin`, `real.tsum_sin`: `real.sin` as the sum of an infinite series.
-/
open_locale nat
/-! ### `cos` and `sin` for `ℝ` and `ℂ` -/
section sin_cos
lemma complex.has_sum_cos' (z : ℂ) :
has_sum (λ n : ℕ, (z * complex.I) ^ (2 * n) / ↑(2 * n)!) (complex.cos z) :=
begin
rw [complex.cos, complex.exp_eq_exp_ℂ],
have := ((exp_series_div_has_sum_exp ℂ (z * complex.I)).add
(exp_series_div_has_sum_exp ℂ (-z * complex.I))).div_const 2,
replace := ((nat.div_mod_equiv 2)).symm.has_sum_iff.mpr this,
dsimp [function.comp] at this,
simp_rw [←mul_comm 2 _] at this,
refine this.prod_fiberwise (λ k, _),
dsimp only,
convert has_sum_fintype (_ : fin 2 → ℂ) using 1,
rw fin.sum_univ_two,
simp_rw [fin.coe_zero, fin.coe_one, add_zero, pow_succ', pow_mul,
mul_pow, neg_sq, ←two_mul, neg_mul, mul_neg, neg_div, add_right_neg, zero_div, add_zero,
mul_div_cancel_left _ (two_ne_zero : (2 : ℂ) ≠ 0)],
end
lemma complex.has_sum_sin' (z : ℂ) :
has_sum (λ n : ℕ, (z * complex.I) ^ (2 * n + 1) / ↑(2 * n + 1)! / complex.I) (complex.sin z) :=
begin
rw [complex.sin, complex.exp_eq_exp_ℂ],
have := (((exp_series_div_has_sum_exp ℂ (-z * complex.I)).sub
(exp_series_div_has_sum_exp ℂ (z * complex.I))).mul_right complex.I).div_const 2,
replace := ((nat.div_mod_equiv 2)).symm.has_sum_iff.mpr this,
dsimp [function.comp] at this,
simp_rw [←mul_comm 2 _] at this,
refine this.prod_fiberwise (λ k, _),
dsimp only,
convert has_sum_fintype (_ : fin 2 → ℂ) using 1,
rw fin.sum_univ_two,
simp_rw [fin.coe_zero, fin.coe_one, add_zero, pow_succ', pow_mul,
mul_pow, neg_sq, sub_self, zero_mul, zero_div, zero_add,
neg_mul, mul_neg, neg_div, ← neg_add', ←two_mul, neg_mul, neg_div, mul_assoc,
mul_div_cancel_left _ (two_ne_zero : (2 : ℂ) ≠ 0), complex.div_I],
end
/-- The power series expansion of `complex.cos`. -/
lemma complex.has_sum_cos (z : ℂ) :
has_sum (λ n : ℕ, ((-1) ^ n) * z ^ (2 * n) / ↑(2 * n)!) (complex.cos z) :=
begin
convert complex.has_sum_cos' z using 1,
simp_rw [mul_pow, pow_mul, complex.I_sq, mul_comm]
end
/-- The power series expansion of `complex.sin`. -/
lemma complex.has_sum_sin (z : ℂ) :
has_sum (λ n : ℕ, ((-1) ^ n) * z ^ (2 * n + 1) / ↑(2 * n + 1)!) (complex.sin z) :=
begin
convert complex.has_sum_sin' z using 1,
simp_rw [mul_pow, pow_succ', pow_mul, complex.I_sq, ←mul_assoc,
mul_div_assoc, div_right_comm, div_self complex.I_ne_zero, mul_comm _ ((-1 : ℂ)^_), mul_one_div,
mul_div_assoc, mul_assoc]
end
lemma complex.cos_eq_tsum' (z : ℂ) :
complex.cos z = ∑' n : ℕ, (z * complex.I) ^ (2 * n) / ↑(2 * n)! :=
(complex.has_sum_cos' z).tsum_eq.symm
lemma complex.sin_eq_tsum' (z : ℂ) :
complex.sin z = ∑' n : ℕ, (z * complex.I) ^ (2 * n + 1) / ↑(2 * n + 1)! / complex.I :=
(complex.has_sum_sin' z).tsum_eq.symm
lemma complex.cos_eq_tsum (z : ℂ) :
complex.cos z = ∑' n : ℕ, ((-1) ^ n) * z ^ (2 * n) / ↑(2 * n)! :=
(complex.has_sum_cos z).tsum_eq.symm
lemma complex.sin_eq_tsum (z : ℂ) :
complex.sin z = ∑' n : ℕ, ((-1) ^ n) * z ^ (2 * n + 1) / ↑(2 * n + 1)! :=
(complex.has_sum_sin z).tsum_eq.symm
/-- The power series expansion of `real.cos`. -/
lemma real.has_sum_cos (r : ℝ) :
has_sum (λ n : ℕ, ((-1) ^ n) * r ^ (2 * n) / ↑(2 * n)!) (real.cos r) :=
by exact_mod_cast complex.has_sum_cos r
/-- The power series expansion of `real.sin`. -/
lemma real.has_sum_sin (r : ℝ) :
has_sum (λ n : ℕ, ((-1) ^ n) * r ^ (2 * n + 1) / ↑(2 * n + 1)!) (real.sin r) :=
by exact_mod_cast complex.has_sum_sin r
lemma real.cos_eq_tsum (r : ℝ) :
real.cos r = ∑' n : ℕ, ((-1) ^ n) * r ^ (2 * n) / ↑(2 * n)! :=
(real.has_sum_cos r).tsum_eq.symm
lemma real.sin_eq_tsum (r : ℝ) :
real.sin r = ∑' n : ℕ, ((-1) ^ n) * r ^ (2 * n + 1) / ↑(2 * n + 1)! :=
(real.has_sum_sin r).tsum_eq.symm
end sin_cos
|
727ef5bbac8fff796e58c546805eaffd505cb0a3 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/extension/linear.lean | cd8d7fc19e2f9f780ce0363cbea0169f5a6e6c7a | [
"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 | 3,865 | lean | /-
Copyright (c) 2021 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import order.zorn
import tactic.by_contra
/-!
# Extend a partial order to a linear order
This file constructs a linear order which is an extension of the given partial order, using Zorn's
lemma.
-/
universes u
open set classical
open_locale classical
/--
Any partial order can be extended to a linear order.
-/
theorem extend_partial_order {α : Type u} (r : α → α → Prop) [is_partial_order α r] :
∃ (s : α → α → Prop) (_ : is_linear_order α s), r ≤ s :=
begin
let S := {s | is_partial_order α s},
have hS : ∀ c, c ⊆ S → is_chain (≤) c → ∀ y ∈ c, (∃ ub ∈ S, ∀ z ∈ c, z ≤ ub),
{ rintro c hc₁ hc₂ s hs,
haveI := (hc₁ hs).1,
refine ⟨Sup c, _, λ z hz, le_Sup hz⟩,
refine { refl := _, trans := _, antisymm := _ }; simp_rw binary_relation_Sup_iff,
{ intro x,
exact ⟨s, hs, refl x⟩ },
{ rintro x y z ⟨s₁, h₁s₁, h₂s₁⟩ ⟨s₂, h₁s₂, h₂s₂⟩,
haveI : is_partial_order _ _ := hc₁ h₁s₁,
haveI : is_partial_order _ _ := hc₁ h₁s₂,
cases hc₂.total h₁s₁ h₁s₂,
{ exact ⟨s₂, h₁s₂, trans (h _ _ h₂s₁) h₂s₂⟩ },
{ exact ⟨s₁, h₁s₁, trans h₂s₁ (h _ _ h₂s₂)⟩ } },
{ rintro x y ⟨s₁, h₁s₁, h₂s₁⟩ ⟨s₂, h₁s₂, h₂s₂⟩,
haveI : is_partial_order _ _ := hc₁ h₁s₁,
haveI : is_partial_order _ _ := hc₁ h₁s₂,
cases hc₂.total h₁s₁ h₁s₂,
{ exact antisymm (h _ _ h₂s₁) h₂s₂ },
{ apply antisymm h₂s₁ (h _ _ h₂s₂) } } },
obtain ⟨s, hs₁ : is_partial_order _ _, rs, hs₂⟩ := zorn_nonempty_partial_order₀ S hS r ‹_›,
resetI,
refine ⟨s, { total := _ }, rs⟩,
intros x y,
by_contra' h,
let s' := λ x' y', s x' y' ∨ s x' x ∧ s y y',
rw ←hs₂ s' _ (λ _ _, or.inl) at h,
{ apply h.1 (or.inr ⟨refl _, refl _⟩) },
{ refine
{ refl := λ x, or.inl (refl _),
trans := _,
antisymm := _ },
{ rintro a b c (ab | ⟨ax : s a x, yb : s y b⟩) (bc | ⟨bx : s b x, yc : s y c⟩),
{ exact or.inl (trans ab bc), },
{ exact or.inr ⟨trans ab bx, yc⟩ },
{ exact or.inr ⟨ax, trans yb bc⟩ },
{ exact or.inr ⟨ax, yc⟩ } },
{ rintro a b (ab | ⟨ax : s a x, yb : s y b⟩) (ba | ⟨bx : s b x, ya : s y a⟩),
{ exact antisymm ab ba },
{ exact (h.2 (trans ya (trans ab bx))).elim },
{ exact (h.2 (trans yb (trans ba ax))).elim },
{ exact (h.2 (trans yb bx)).elim } } },
end
/-- A type alias for `α`, intended to extend a partial order on `α` to a linear order. -/
def linear_extension (α : Type u) : Type u := α
noncomputable instance {α : Type u} [partial_order α] : linear_order (linear_extension α) :=
{ le := (extend_partial_order ((≤) : α → α → Prop)).some,
le_refl := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.1.1.1,
le_trans := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.1.2.1,
le_antisymm := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.2.1,
le_total := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.2.1,
decidable_le := classical.dec_rel _ }
/-- The embedding of `α` into `linear_extension α` as a relation homomorphism. -/
def to_linear_extension {α : Type u} [partial_order α] :
((≤) : α → α → Prop) →r ((≤) : linear_extension α → linear_extension α → Prop) :=
{ to_fun := λ x, x,
map_rel' := λ a b, (extend_partial_order ((≤) : α → α → Prop)).some_spec.some_spec _ _ }
instance {α : Type u} [inhabited α] : inhabited (linear_extension α) :=
⟨(default : α)⟩
|
d65ef270559bccecd59c8dc428b35b43ff4ec77a | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/analysis/normed_space/add_torsor.lean | d2bff33d488e11d7725a538780683a36f6e56b2c | [
"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 | 17,782 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Yury Kudryashov
-/
import linear_algebra.affine_space.midpoint
import topology.metric_space.isometry
import topology.instances.real_vector_space
/-!
# Torsors of additive normed group actions.
This file defines torsors of additive normed group actions, with a
metric space structure. The motivating case is Euclidean affine
spaces.
-/
noncomputable theory
open_locale nnreal topological_space
open filter
/-- A `semi_normed_add_torsor V P` is a torsor of an additive seminormed group
action by a `semi_normed_group V` on points `P`. We bundle the pseudometric space
structure and require the distance to be the same as results from the
norm (which in fact implies the distance yields a pseudometric space, but
bundling just the distance and using an instance for the pseudometric space
results in type class problems). -/
class semi_normed_add_torsor (V : out_param $ Type*) (P : Type*)
[out_param $ semi_normed_group V] [pseudo_metric_space P]
extends add_torsor V P :=
(dist_eq_norm' : ∀ (x y : P), dist x y = ∥(x -ᵥ y : V)∥)
/-- A `normed_add_torsor V P` is a torsor of an additive normed group
action by a `normed_group V` on points `P`. We bundle the metric space
structure and require the distance to be the same as results from the
norm (which in fact implies the distance yields a metric space, but
bundling just the distance and using an instance for the metric space
results in type class problems). -/
class normed_add_torsor (V : out_param $ Type*) (P : Type*)
[out_param $ normed_group V] [metric_space P]
extends add_torsor V P :=
(dist_eq_norm' : ∀ (x y : P), dist x y = ∥(x -ᵥ y : V)∥)
/-- A `normed_add_torsor` is a `semi_normed_add_torsor`. -/
@[priority 100]
instance normed_add_torsor.to_semi_normed_add_torsor {V P : Type*} [normed_group V] [metric_space P]
[β : normed_add_torsor V P] : semi_normed_add_torsor V P := { ..β }
variables {α V P : Type*} [semi_normed_group V] [pseudo_metric_space P] [semi_normed_add_torsor V P]
variables {W Q : Type*} [normed_group W] [metric_space Q] [normed_add_torsor W Q]
/-- A `semi_normed_group` is a `semi_normed_add_torsor` over itself. -/
@[priority 100]
instance semi_normed_group.normed_add_torsor : semi_normed_add_torsor V V :=
{ dist_eq_norm' := dist_eq_norm }
/-- A `normed_group` is a `normed_add_torsor` over itself. -/
@[priority 100]
instance normed_group.normed_add_torsor : normed_add_torsor W W :=
{ dist_eq_norm' := dist_eq_norm }
include V
section
variables (V W)
/-- The distance equals the norm of subtracting two points. In this
lemma, it is necessary to have `V` as an explicit argument; otherwise
`rw dist_eq_norm_vsub` sometimes doesn't work. -/
lemma dist_eq_norm_vsub (x y : P) :
dist x y = ∥(x -ᵥ y)∥ :=
semi_normed_add_torsor.dist_eq_norm' x y
end
@[simp] lemma dist_vadd_cancel_left (v : V) (x y : P) :
dist (v +ᵥ x) (v +ᵥ y) = dist x y :=
by rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, vadd_vsub_vadd_cancel_left]
@[simp] lemma dist_vadd_cancel_right (v₁ v₂ : V) (x : P) :
dist (v₁ +ᵥ x) (v₂ +ᵥ x) = dist v₁ v₂ :=
by rw [dist_eq_norm_vsub V, dist_eq_norm, vadd_vsub_vadd_cancel_right]
@[simp] lemma dist_vadd_left (v : V) (x : P) : dist (v +ᵥ x) x = ∥v∥ :=
by simp [dist_eq_norm_vsub V _ x]
@[simp] lemma dist_vadd_right (v : V) (x : P) : dist x (v +ᵥ x) = ∥v∥ :=
by rw [dist_comm, dist_vadd_left]
@[simp] lemma dist_vsub_cancel_left (x y z : P) : dist (x -ᵥ y) (x -ᵥ z) = dist y z :=
by rw [dist_eq_norm, vsub_sub_vsub_cancel_left, dist_comm, dist_eq_norm_vsub V]
@[simp] lemma dist_vsub_cancel_right (x y z : P) : dist (x -ᵥ z) (y -ᵥ z) = dist x y :=
by rw [dist_eq_norm, vsub_sub_vsub_cancel_right, dist_eq_norm_vsub V]
lemma dist_vadd_vadd_le (v v' : V) (p p' : P) :
dist (v +ᵥ p) (v' +ᵥ p') ≤ dist v v' + dist p p' :=
by simpa using dist_triangle (v +ᵥ p) (v' +ᵥ p) (v' +ᵥ p')
lemma dist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) :
dist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ dist p₁ p₃ + dist p₂ p₄ :=
by { rw [dist_eq_norm, vsub_sub_vsub_comm, dist_eq_norm_vsub V, dist_eq_norm_vsub V],
exact norm_sub_le _ _ }
lemma nndist_vadd_vadd_le (v v' : V) (p p' : P) :
nndist (v +ᵥ p) (v' +ᵥ p') ≤ nndist v v' + nndist p p' :=
by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vadd_vadd_le]
lemma nndist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) :
nndist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ nndist p₁ p₃ + nndist p₂ p₄ :=
by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vsub_vsub_le]
lemma edist_vadd_vadd_le (v v' : V) (p p' : P) :
edist (v +ᵥ p) (v' +ᵥ p') ≤ edist v v' + edist p p' :=
by { simp only [edist_nndist], apply_mod_cast nndist_vadd_vadd_le }
lemma edist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) :
edist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ edist p₁ p₃ + edist p₂ p₄ :=
by { simp only [edist_nndist], apply_mod_cast nndist_vsub_vsub_le }
omit V
/-- The pseudodistance defines a pseudometric space structure on the torsor. This
is not an instance because it depends on `V` to define a `metric_space
P`. -/
def pseudo_metric_space_of_normed_group_of_add_torsor (V P : Type*) [semi_normed_group V]
[add_torsor V P] : pseudo_metric_space P :=
{ dist := λ x y, ∥(x -ᵥ y : V)∥,
dist_self := λ x, by simp,
dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg],
dist_triangle := begin
intros x y z,
change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥,
rw ←vsub_add_vsub_cancel,
apply norm_add_le
end }
/-- The distance defines a metric space structure on the torsor. This
is not an instance because it depends on `V` to define a `metric_space
P`. -/
def metric_space_of_normed_group_of_add_torsor (V P : Type*) [normed_group V] [add_torsor V P] :
metric_space P :=
{ dist := λ x y, ∥(x -ᵥ y : V)∥,
dist_self := λ x, by simp,
eq_of_dist_eq_zero := λ x y h, by simpa using h,
dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg],
dist_triangle := begin
intros x y z,
change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥,
rw ←vsub_add_vsub_cancel,
apply norm_add_le
end }
include V
namespace isometric
/-- The map `v ↦ v +ᵥ p` as an isometric equivalence between `V` and `P`. -/
def vadd_const (p : P) : V ≃ᵢ P :=
⟨equiv.vadd_const p, isometry_emetric_iff_metric.2 $ λ x₁ x₂, dist_vadd_cancel_right x₁ x₂ p⟩
@[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const p) = λ v, v +ᵥ p := rfl
@[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const p).symm = λ p', p' -ᵥ p := rfl
@[simp] lemma vadd_const_to_equiv (p : P) : (vadd_const p).to_equiv = equiv.vadd_const p := rfl
/-- `p' ↦ p -ᵥ p'` as an equivalence. -/
def const_vsub (p : P) : P ≃ᵢ V :=
⟨equiv.const_vsub p, isometry_emetric_iff_metric.2 $ λ p₁ p₂, dist_vsub_cancel_left _ _ _⟩
@[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub p) = (-ᵥ) p := rfl
@[simp] lemma coe_const_vsub_symm (p : P) : ⇑(const_vsub p).symm = λ v, -v +ᵥ p := rfl
variables (P)
/-- The map `p ↦ v +ᵥ p` as an isometric automorphism of `P`. -/
def const_vadd (v : V) : P ≃ᵢ P :=
⟨equiv.const_vadd P v, isometry_emetric_iff_metric.2 $ dist_vadd_cancel_left v⟩
@[simp] lemma coe_const_vadd (v : V) : ⇑(const_vadd P v) = (+ᵥ) v := rfl
variable (V)
@[simp] lemma const_vadd_zero : const_vadd P (0:V) = isometric.refl P :=
isometric.to_equiv_inj $ equiv.const_vadd_zero V P
variables {P V}
/-- Point reflection in `x` as an `isometric` homeomorphism. -/
def point_reflection (x : P) : P ≃ᵢ P :=
(const_vsub x).trans (vadd_const x)
lemma point_reflection_apply (x y : P) : point_reflection x y = x -ᵥ y +ᵥ x := rfl
@[simp] lemma point_reflection_to_equiv (x : P) :
(point_reflection x).to_equiv = equiv.point_reflection x := rfl
@[simp] lemma point_reflection_self (x : P) : point_reflection x x = x :=
equiv.point_reflection_self x
lemma point_reflection_involutive (x : P) : function.involutive (point_reflection x : P → P) :=
equiv.point_reflection_involutive x
@[simp] lemma point_reflection_symm (x : P) : (point_reflection x).symm = point_reflection x :=
to_equiv_inj $ equiv.point_reflection_symm x
@[simp] lemma dist_point_reflection_fixed (x y : P) :
dist (point_reflection x y) x = dist y x :=
by rw [← (point_reflection x).dist_eq y x, point_reflection_self]
lemma dist_point_reflection_self' (x y : P) :
dist (point_reflection x y) y = ∥bit0 (x -ᵥ y)∥ :=
by rw [point_reflection_apply, dist_eq_norm_vsub V, vadd_vsub_assoc, bit0]
lemma dist_point_reflection_self (𝕜 : Type*) [normed_field 𝕜] [semi_normed_space 𝕜 V] (x y : P) :
dist (point_reflection x y) y = ∥(2:𝕜)∥ * dist x y :=
by rw [dist_point_reflection_self', ← two_smul' 𝕜 (x -ᵥ y), norm_smul, ← dist_eq_norm_vsub V]
lemma point_reflection_fixed_iff (𝕜 : Type*) [normed_field 𝕜] [semi_normed_space 𝕜 V]
[invertible (2:𝕜)] {x y : P} : point_reflection x y = y ↔ y = x :=
affine_equiv.point_reflection_fixed_iff_of_module 𝕜
variables [semi_normed_space ℝ V]
lemma dist_point_reflection_self_real (x y : P) :
dist (point_reflection x y) y = 2 * dist x y :=
by { rw [dist_point_reflection_self ℝ, real.norm_two], apply_instance }
@[simp] lemma point_reflection_midpoint_left (x y : P) :
point_reflection (midpoint ℝ x y) x = y :=
affine_equiv.point_reflection_midpoint_left x y
@[simp] lemma point_reflection_midpoint_right (x y : P) :
point_reflection (midpoint ℝ x y) y = x :=
affine_equiv.point_reflection_midpoint_right x y
end isometric
lemma lipschitz_with.vadd [pseudo_emetric_space α] {f : α → V} {g : α → P} {Kf Kg : ℝ≥0}
(hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (f +ᵥ g) :=
λ x y,
calc edist (f x +ᵥ g x) (f y +ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) :
edist_vadd_vadd_le _ _ _ _
... ≤ Kf * edist x y + Kg * edist x y :
add_le_add (hf x y) (hg x y)
... = (Kf + Kg) * edist x y :
(add_mul _ _ _).symm
lemma lipschitz_with.vsub [pseudo_emetric_space α] {f g : α → P} {Kf Kg : ℝ≥0}
(hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (f -ᵥ g) :=
λ x y,
calc edist (f x -ᵥ g x) (f y -ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) :
edist_vsub_vsub_le _ _ _ _
... ≤ Kf * edist x y + Kg * edist x y :
add_le_add (hf x y) (hg x y)
... = (Kf + Kg) * edist x y :
(add_mul _ _ _).symm
lemma uniform_continuous_vadd : uniform_continuous (λ x : V × P, x.1 +ᵥ x.2) :=
(lipschitz_with.prod_fst.vadd lipschitz_with.prod_snd).uniform_continuous
lemma uniform_continuous_vsub : uniform_continuous (λ x : P × P, x.1 -ᵥ x.2) :=
(lipschitz_with.prod_fst.vsub lipschitz_with.prod_snd).uniform_continuous
lemma continuous_vadd : continuous (λ x : V × P, x.1 +ᵥ x.2) :=
uniform_continuous_vadd.continuous
lemma continuous_vsub : continuous (λ x : P × P, x.1 -ᵥ x.2) :=
uniform_continuous_vsub.continuous
lemma filter.tendsto.vadd {l : filter α} {f : α → V} {g : α → P} {v : V} {p : P}
(hf : tendsto f l (𝓝 v)) (hg : tendsto g l (𝓝 p)) :
tendsto (f +ᵥ g) l (𝓝 (v +ᵥ p)) :=
(continuous_vadd.tendsto (v, p)).comp (hf.prod_mk_nhds hg)
lemma filter.tendsto.vsub {l : filter α} {f g : α → P} {x y : P}
(hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) :
tendsto (f -ᵥ g) l (𝓝 (x -ᵥ y)) :=
(continuous_vsub.tendsto (x, y)).comp (hf.prod_mk_nhds hg)
section
variables [topological_space α]
lemma continuous.vadd {f : α → V} {g : α → P} (hf : continuous f) (hg : continuous g) :
continuous (f +ᵥ g) :=
continuous_vadd.comp (hf.prod_mk hg)
lemma continuous.vsub {f g : α → P} (hf : continuous f) (hg : continuous g) :
continuous (f -ᵥ g) :=
continuous_vsub.comp (hf.prod_mk hg : _)
lemma continuous_at.vadd {f : α → V} {g : α → P} {x : α} (hf : continuous_at f x)
(hg : continuous_at g x) :
continuous_at (f +ᵥ g) x :=
hf.vadd hg
lemma continuous_at.vsub {f g : α → P} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) :
continuous_at (f -ᵥ g) x :=
hf.vsub hg
lemma continuous_within_at.vadd {f : α → V} {g : α → P} {x : α} {s : set α}
(hf : continuous_within_at f s x) (hg : continuous_within_at g s x) :
continuous_within_at (f +ᵥ g) s x :=
hf.vadd hg
lemma continuous_within_at.vsub {f g : α → P} {x : α} {s : set α}
(hf : continuous_within_at f s x) (hg : continuous_within_at g s x) :
continuous_within_at (f -ᵥ g) s x :=
hf.vsub hg
end
section
variables {R : Type*} [ring R] [topological_space R] [module R V] [has_continuous_smul R V]
lemma filter.tendsto.line_map {l : filter α} {f₁ f₂ : α → P} {g : α → R} {p₁ p₂ : P} {c : R}
(h₁ : tendsto f₁ l (𝓝 p₁)) (h₂ : tendsto f₂ l (𝓝 p₂)) (hg : tendsto g l (𝓝 c)) :
tendsto (λ x, affine_map.line_map (f₁ x) (f₂ x) (g x)) l (𝓝 $ affine_map.line_map p₁ p₂ c) :=
(hg.smul (h₂.vsub h₁)).vadd h₁
lemma filter.tendsto.midpoint [invertible (2:R)] {l : filter α} {f₁ f₂ : α → P} {p₁ p₂ : P}
(h₁ : tendsto f₁ l (𝓝 p₁)) (h₂ : tendsto f₂ l (𝓝 p₂)) :
tendsto (λ x, midpoint R (f₁ x) (f₂ x)) l (𝓝 $ midpoint R p₁ p₂) :=
h₁.line_map h₂ tendsto_const_nhds
end
variables {V' : Type*} {P' : Type*} [semi_normed_group V'] [pseudo_metric_space P']
[semi_normed_add_torsor V' P']
/-- The map `g` from `V1` to `V2` corresponding to a map `f` from `P1`
to `P2`, at a base point `p`, is an isometry if `f` is one. -/
lemma isometry.vadd_vsub {f : P → P'} (hf : isometry f) {p : P} {g : V → V'}
(hg : ∀ v, g v = f (v +ᵥ p) -ᵥ f p) : isometry g :=
begin
convert (isometric.vadd_const (f p)).symm.isometry.comp
(hf.comp (isometric.vadd_const p).isometry),
exact funext hg
end
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [semi_normed_space 𝕜 V]
open affine_map
/-- If `f` is an affine map, then its linear part is continuous iff `f` is continuous. -/
lemma affine_map.continuous_linear_iff [semi_normed_space 𝕜 V'] {f : P →ᵃ[𝕜] P'} :
continuous f.linear ↔ continuous f :=
begin
inhabit P,
have : (f.linear : V → V') =
(isometric.vadd_const $ f $ default P).to_homeomorph.symm ∘ f ∘
(isometric.vadd_const $ default P).to_homeomorph,
{ ext v, simp },
rw this,
simp only [homeomorph.comp_continuous_iff, homeomorph.comp_continuous_iff'],
end
@[simp] lemma dist_center_homothety (p₁ p₂ : P) (c : 𝕜) :
dist p₁ (homothety p₁ c p₂) = ∥c∥ * dist p₁ p₂ :=
by simp [homothety_def, norm_smul, ← dist_eq_norm_vsub, dist_comm]
@[simp] lemma dist_homothety_center (p₁ p₂ : P) (c : 𝕜) :
dist (homothety p₁ c p₂) p₁ = ∥c∥ * dist p₁ p₂ :=
by rw [dist_comm, dist_center_homothety]
@[simp] lemma dist_homothety_self (p₁ p₂ : P) (c : 𝕜) :
dist (homothety p₁ c p₂) p₂ = ∥1 - c∥ * dist p₁ p₂ :=
by rw [homothety_eq_line_map, ← line_map_apply_one_sub, ← homothety_eq_line_map,
dist_homothety_center, dist_comm]
@[simp] lemma dist_self_homothety (p₁ p₂ : P) (c : 𝕜) :
dist p₂ (homothety p₁ c p₂) = ∥1 - c∥ * dist p₁ p₂ :=
by rw [dist_comm, dist_homothety_self]
variables [invertible (2:𝕜)]
@[simp] lemma dist_left_midpoint (p₁ p₂ : P) :
dist p₁ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ :=
by rw [midpoint, ← homothety_eq_line_map, dist_center_homothety, inv_of_eq_inv,
← normed_field.norm_inv]
@[simp] lemma dist_midpoint_left (p₁ p₂ : P) :
dist (midpoint 𝕜 p₁ p₂) p₁ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ :=
by rw [dist_comm, dist_left_midpoint]
@[simp] lemma dist_midpoint_right (p₁ p₂ : P) :
dist (midpoint 𝕜 p₁ p₂) p₂ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ :=
by rw [midpoint_comm, dist_midpoint_left, dist_comm]
@[simp] lemma dist_right_midpoint (p₁ p₂ : P) :
dist p₂ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ :=
by rw [dist_comm, dist_midpoint_right]
lemma dist_midpoint_midpoint_le' (p₁ p₂ p₃ p₄ : P) :
dist (midpoint 𝕜 p₁ p₂) (midpoint 𝕜 p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / ∥(2 : 𝕜)∥ :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, midpoint_vsub_midpoint];
try { apply_instance },
rw [midpoint_eq_smul_add, norm_smul, inv_of_eq_inv, normed_field.norm_inv, ← div_eq_inv_mul],
exact div_le_div_of_le_of_nonneg (norm_add_le _ _) (norm_nonneg _),
end
end normed_space
variables [semi_normed_space ℝ V] [normed_space ℝ W]
lemma dist_midpoint_midpoint_le (p₁ p₂ p₃ p₄ : V) :
dist (midpoint ℝ p₁ p₂) (midpoint ℝ p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / 2 :=
by simpa using dist_midpoint_midpoint_le' p₁ p₂ p₃ p₄
include W
/-- A continuous map between two normed affine spaces is an affine map provided that
it sends midpoints to midpoints. -/
def affine_map.of_map_midpoint (f : P → Q)
(h : ∀ x y, f (midpoint ℝ x y) = midpoint ℝ (f x) (f y))
(hfc : continuous f) :
P →ᵃ[ℝ] Q :=
affine_map.mk' f
↑((add_monoid_hom.of_map_midpoint ℝ ℝ
((affine_equiv.vadd_const ℝ (f $ classical.arbitrary P)).symm ∘ f ∘
(affine_equiv.vadd_const ℝ (classical.arbitrary P))) (by simp)
(λ x y, by simp [h])).to_real_linear_map $ by apply_rules [continuous.vadd, continuous.vsub,
continuous_const, hfc.comp, continuous_id])
(classical.arbitrary P)
(λ p, by simp)
|
9f156bf7395c9dafb7cf6fe863cdc2a698deb964 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/fin_cases.lean | 6eba0f6ba4f43549301d0282302b848e70d6337c | [
"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,857 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
Case bashing:
* on `x ∈ A`, for `A : finset α` or `A : list α`, or
* on `x : A`, with `[fintype A]`.
-/
import data.fintype.basic
import tactic.norm_num
namespace tactic
open lean.parser
open interactive interactive.types expr
open conv.interactive
/-- Checks that the expression looks like `x ∈ A` for `A : finset α`, `multiset α` or `A : list α`,
and returns the type α. -/
meta def guard_mem_fin (e : expr) : tactic expr :=
do t ← infer_type e,
α ← mk_mvar,
to_expr ``(_ ∈ (_ : finset %%α)) tt ff >>= unify t <|>
to_expr ``(_ ∈ (_ : multiset %%α)) tt ff >>= unify t <|>
to_expr ``(_ ∈ (_ : list %%α)) tt ff >>= unify t,
instantiate_mvars α
/--
`expr_list_to_list_expr` converts an `expr` of type `list α`
to a list of `expr`s each with type `α`.
TODO: this should be moved, and possibly duplicates an existing definition.
-/
meta def expr_list_to_list_expr : Π (e : expr), tactic (list expr)
| `(list.cons %%h %%t) := list.cons h <$> expr_list_to_list_expr t
| `([]) := return []
| _ := failed
private meta def fin_cases_at_aux : Π (with_list : list expr) (e : expr), tactic unit
| with_list e :=
(do
result ← cases_core e,
match result with
-- We have a goal with an equation `s`, and a second goal with a smaller `e : x ∈ _`.
| [(_, [s], _), (_, [e], _)] :=
do let sn := local_pp_name s,
ng ← num_goals,
-- tidy up the new value
match with_list.nth 0 with
-- If an explicit value was specified via the `with` keyword, use that.
| (some h) := tactic.interactive.conv (some sn) none
(to_rhs >> conv.interactive.change (to_pexpr h))
-- Otherwise, call `norm_num`. We let `norm_num` unfold `max` and `min`
-- because it's helpful for the `interval_cases` tactic.
| _ := try $ tactic.interactive.conv (some sn) none $
to_rhs >> conv.interactive.norm_num
[simp_arg_type.expr ``(max), simp_arg_type.expr ``(min)]
end,
s ← get_local sn,
try `[subst %%s],
ng' ← num_goals,
when (ng = ng') (rotate_left 1),
fin_cases_at_aux with_list.tail e
-- No cases; we're done.
| [] := skip
| _ := failed
end)
/--
`fin_cases_at with_list e` performs case analysis on `e : α`, where `α` is a fintype.
The optional list of expressions `with_list` provides descriptions for the cases of `e`,
for example, to display nats as `n.succ` instead of `n+1`.
These should be defeq to and in the same order as the terms in the enumeration of `α`.
-/
meta def fin_cases_at : Π (with_list : option pexpr) (e : expr), tactic unit
| with_list e :=
do ty ← try_core $ guard_mem_fin e,
match ty with
| none := -- Deal with `x : A`, where `[fintype A]` is available:
(do
ty ← infer_type e,
i ← to_expr ``(fintype %%ty) >>= mk_instance <|> fail "Failed to find `fintype` instance.",
t ← to_expr ``(%%e ∈ @fintype.elems %%ty %%i),
v ← to_expr ``(@fintype.complete %%ty %%i %%e),
h ← assertv `h t v,
fin_cases_at with_list h)
| (some ty) := -- Deal with `x ∈ A` hypotheses:
(do
with_list ← match with_list with
| (some e) := do e ← to_expr ``(%%e : list %%ty), expr_list_to_list_expr e
| none := return []
end,
fin_cases_at_aux with_list e)
end
namespace interactive
private meta def hyp := tk "*" *> return none <|> some <$> ident
local postfix `?`:9001 := optional
/--
`fin_cases h` performs case analysis on a hypothesis of the form
`h : A`, where `[fintype A]` is available, or
`h ∈ A`, where `A : finset X`, `A : multiset X` or `A : list X`.
`fin_cases *` performs case analysis on all suitable hypotheses.
As an example, in
```
example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val :=
begin
fin_cases *; simp,
all_goals { assumption }
end
```
after `fin_cases p; simp`, there are three goals, `f 0`, `f 1`, and `f 2`.
-/
meta def fin_cases : parse hyp → parse (tk "with" *> texpr)? → tactic unit
| none none := focus1 $ do
ctx ← local_context,
ctx.mfirst (fin_cases_at none) <|>
fail "No hypothesis of the forms `x ∈ A`, where `A : finset X`, `A : list X`, or `A : multiset X`, or `x : A`, with `[fintype A]`."
| none (some _) := fail "Specify a single hypothesis when using a `with` argument."
| (some n) with_list :=
do
h ← get_local n,
focus1 $ fin_cases_at with_list h
end interactive
add_tactic_doc
{ name := "fin_cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fin_cases],
tags := ["case bashing"] }
end tactic
|
3c1d35ed476a8e7363aa89677676a24a2357bdda | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/ind5.lean | 9e3da40b1bed1b69609e298500013f5fcdf7fad3 | [
"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 | 185 | lean | prelude
definition Prop : Type.{1} := Type.{0}
inductive or (A B : Prop) : Prop :=
| intro_left : A → or A B
| intro_right : B → or A B
check or
check or.intro_left
check or.rec
|
a3a05abc3ecd60acf972d83fbc701a647224a9c5 | 80746c6dba6a866de5431094bf9f8f841b043d77 | /src/data/string.lean | 7bfbb972114166f4324606648f494083ad4d425c | [
"Apache-2.0"
] | permissive | leanprover-fork/mathlib-backup | 8b5c95c535b148fca858f7e8db75a76252e32987 | 0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0 | refs/heads/master | 1,585,156,056,139 | 1,548,864,430,000 | 1,548,864,438,000 | 143,964,213 | 0 | 0 | Apache-2.0 | 1,550,795,966,000 | 1,533,705,322,000 | Lean | UTF-8 | Lean | false | false | 2,619 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Supplementary theorems about the `string` type.
-/
import data.list.basic data.char
namespace string
def ltb : iterator → iterator → bool
| s₁ s₂ := begin
cases s₂.has_next, {exact ff},
cases h₁ : s₁.has_next, {exact tt},
exact if s₁.curr = s₂.curr then
have s₁.next.2.length < s₁.2.length, from
match s₁, h₁ with ⟨_, a::l⟩, h := nat.lt_succ_self _ end,
ltb s₁.next s₂.next
else s₁.curr < s₂.curr,
end
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ s, s.1.2.length)⟩]}
instance has_lt' : has_lt string :=
⟨λ s₁ s₂, ltb s₁.mk_iterator s₂.mk_iterator⟩
instance decidable_lt : @decidable_rel string (<) := by apply_instance
@[simp] theorem lt_iff_to_list_lt :
∀ {s₁ s₂ : string}, s₁ < s₂ ↔ s₁.to_list < s₂.to_list
| ⟨i₁⟩ ⟨i₂⟩ :=
suffices ∀ {p₁ p₂ s₁ s₂}, ltb ⟨p₁, s₁⟩ ⟨p₂, s₂⟩ ↔ s₁ < s₂, from this,
begin
intros,
induction s₁ with a s₁ IH generalizing p₁ p₂ s₂;
cases s₂ with b s₂; rw ltb; simp [iterator.has_next],
{ exact iff_of_false bool.ff_ne_tt (lt_irrefl _) },
{ exact iff_of_true rfl list.lex.nil },
{ exact iff_of_false bool.ff_ne_tt (not_lt_of_lt list.lex.nil) },
{ dsimp [iterator.has_next,
iterator.curr, iterator.next],
split_ifs,
{ subst b, exact IH.trans list.lex.cons_iff.symm },
{ simp, refine ⟨list.lex.rel, λ e, _⟩,
cases e, {cases h rfl}, assumption } }
end
instance has_le : has_le string := ⟨λ s₁ s₂, ¬ s₂ < s₁⟩
instance decidable_le : @decidable_rel string (≤) := by apply_instance
@[simp] theorem le_iff_to_list_le
{s₁ s₂ : string} : s₁ ≤ s₂ ↔ s₁.to_list ≤ s₂.to_list :=
(not_congr lt_iff_to_list_lt).trans not_lt
theorem to_list_inj : ∀ {s₁ s₂}, to_list s₁ = to_list s₂ ↔ s₁ = s₂
| ⟨s₁⟩ ⟨s₂⟩ := ⟨congr_arg _, congr_arg _⟩
instance : decidable_linear_order string :=
by refine_struct {
lt := (<), le := (≤),
le_antisymm := by simp; exact
λ a b h₁ h₂, to_list_inj.1 (le_antisymm h₁ h₂),
decidable_lt := by apply_instance,
decidable_le := string.decidable_le,
decidable_eq := by apply_instance, .. };
{ simp [-not_le], introv, apply_field }
def map_tokens (c : char) (f : list string → list string) : string → string :=
intercalate (singleton c) ∘ f ∘ split (= c)
end string
|
30c4d69c5c75df8ea97402e002bbf19d2ece452e | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/number_theory/diophantine_approximation.lean | 772f7e19881e2cbb14bd0256acb1c0af4442148a | [
"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 | 27,924 | lean | /-
Copyright (c) 2022 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Geißer, Michael Stoll
-/
import algebra.continued_fractions.computation.approximation_corollaries
import algebra.continued_fractions.computation.translations
import combinatorics.pigeonhole
import data.int.units
import data.real.irrational
import ring_theory.coprime.lemmas
import tactic.basic
/-!
# Diophantine Approximation
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The first part of this file gives proofs of various versions of
**Dirichlet's approximation theorem** and its important consequence that when $\xi$ is an
irrational real number, then there are infinitely many rationals $x/y$ (in lowest terms)
such that
$$\left|\xi - \frac{x}{y}\right| < \frac{1}{y^2} \,.$$
The proof is based on the pigeonhole principle.
The second part of the file gives a proof of **Legendre's Theorem** on rational approximation,
which states that if $\xi$ is a real number and $x/y$ is a rational number such that
$$\left|\xi - \frac{x}{y}\right| < \frac{1}{2y^2} \,,$$
then $x/y$ must be a convergent of the continued fraction expansion of $\xi$.
## Main statements
The main results are three variants of Dirichlet's approximation theorem:
* `real.exists_int_int_abs_mul_sub_le`, which states that for all real `ξ` and natural `0 < n`,
there are integers `j` and `k` with `0 < k ≤ n` and `|k*ξ - j| ≤ 1/(n+1)`,
* `real.exists_nat_abs_mul_sub_round_le`, which replaces `j` by `round(k*ξ)` and uses
a natural number `k`,
* `real.exists_rat_abs_sub_le_and_denom_le`, which says that there is a rational number `q`
satisfying `|ξ - q| ≤ 1/((n+1)*q.denom)` and `q.denom ≤ n`,
and
* `real.infinite_rat_abs_sub_lt_one_div_denom_sq_of_irrational`, which states that
for irrational `ξ`, the set `{q : ℚ | |ξ - q| < 1/q.denom^2}` is infinite.
We also show a converse,
* `rat.finite_rat_abs_sub_lt_one_div_denom_sq`, which states that the set above is finite
when `ξ` is a rational number.
Both statements are combined to give an equivalence,
`real.infinite_rat_abs_sub_lt_one_div_denom_sq_iff_irrational`.
There are two versions of Legendre's Theorem. One, `real.exists_rat_eq_convergent`, uses
`real.convergent`, a simple recursive definition of the convergents that is also defined
in this file, whereas the other, `real.exists_continued_fraction_convergent_eq_rat`, uses
`generalized_continued_fraction.convergents` of `generalized_continued_fraction.of ξ`.
## Implementation notes
We use the namespace `real` for the results on real numbers and `rat` for the results
on rational numbers. We introduce a secondary namespace `real.contfrac_legendre`
to separate off a definition and some technical auxiliary lemmas used in the proof
of Legendre's Theorem. For remarks on the proof of Legendre's Theorem, see below.
## References
<https://en.wikipedia.org/wiki/Dirichlet%27s_approximation_theorem>
<https://de.wikipedia.org/wiki/Kettenbruch> (The German Wikipedia page on continued
fractions is much more extensive than the English one.)
## Tags
Diophantine approximation, Dirichlet's approximation theorem, continued fraction
-/
namespace real
section dirichlet
/-!
### Dirichlet's approximation theorem
We show that for any real number `ξ` and positive natural `n`, there is a fraction `q`
such that `q.denom ≤ n` and `|ξ - q| ≤ 1/((n+1)*q.denom)`.
-/
open finset int
/-- *Dirichlet's approximation theorem:*
For any real number `ξ` and positive natural `n`, there are integers `j` and `k`,
with `0 < k ≤ n` and `|k*ξ - j| ≤ 1/(n+1)`.
See also `real.exists_nat_abs_mul_sub_round_le`. -/
lemma exists_int_int_abs_mul_sub_le (ξ : ℝ) {n : ℕ} (n_pos : 0 < n) :
∃ j k : ℤ, 0 < k ∧ k ≤ n ∧ |↑k * ξ - j| ≤ 1 / (n + 1) :=
begin
let f : ℤ → ℤ := λ m, ⌊fract (ξ * m) * (n + 1)⌋,
have hn : 0 < (n : ℝ) + 1 := by exact_mod_cast nat.succ_pos _,
have hfu := λ m : ℤ, mul_lt_of_lt_one_left hn $ fract_lt_one (ξ * ↑m),
conv in (|_| ≤ _) { rw [mul_comm, le_div_iff hn, ← abs_of_pos hn, ← abs_mul], },
let D := Icc (0 : ℤ) n,
by_cases H : ∃ m ∈ D, f m = n,
{ obtain ⟨m, hm, hf⟩ := H,
have hf' : ((n : ℤ) : ℝ) ≤ fract (ξ * m) * (n + 1) := hf ▸ floor_le (fract (ξ * m) * (n + 1)),
have hm₀ : 0 < m,
{ have hf₀ : f 0 = 0,
{ simp only [floor_eq_zero_iff, algebra_map.coe_zero, mul_zero, fract_zero, zero_mul,
set.left_mem_Ico, zero_lt_one], },
refine ne.lt_of_le (λ h, n_pos.ne _) (mem_Icc.mp hm).1,
exact_mod_cast hf₀.symm.trans (h.symm ▸ hf : f 0 = n), },
refine ⟨⌊ξ * m⌋ + 1, m, hm₀, (mem_Icc.mp hm).2, _⟩,
rw [cast_add, ← sub_sub, sub_mul, cast_one, one_mul, abs_le],
refine ⟨le_sub_iff_add_le.mpr _,
sub_le_iff_le_add.mpr $ le_of_lt $ (hfu m).trans $ lt_one_add _⟩,
simpa only [neg_add_cancel_comm_assoc] using hf', },
{ simp_rw [not_exists] at H,
have hD : (Ico (0 : ℤ) n).card < D.card,
{ rw [card_Icc, card_Ico], exact lt_add_one n, },
have hfu' : ∀ m, f m ≤ n := λ m, lt_add_one_iff.mp (floor_lt.mpr (by exact_mod_cast hfu m)),
have hwd : ∀ m : ℤ, m ∈ D → f m ∈ Ico (0 : ℤ) n :=
λ x hx, mem_Ico.mpr ⟨floor_nonneg.mpr (mul_nonneg (fract_nonneg (ξ * x)) hn.le),
ne.lt_of_le (H x hx) (hfu' x)⟩,
have : ∃ (x : ℤ) (hx : x ∈ D) (y : ℤ) (hy : y ∈ D), x < y ∧ f x = f y,
{ obtain ⟨x, hx, y, hy, x_ne_y, hxy⟩ := exists_ne_map_eq_of_card_lt_of_maps_to hD hwd,
rcases lt_trichotomy x y with h | h | h,
exacts [⟨x, hx, y, hy, h, hxy⟩, false.elim (x_ne_y h), ⟨y, hy, x, hx, h, hxy.symm⟩], },
obtain ⟨x, hx, y, hy, x_lt_y, hxy⟩ := this,
refine ⟨⌊ξ * y⌋ - ⌊ξ * x⌋, y - x, sub_pos_of_lt x_lt_y,
sub_le_iff_le_add.mpr $ le_add_of_le_of_nonneg (mem_Icc.mp hy).2 (mem_Icc.mp hx).1, _⟩,
convert_to |fract (ξ * y) * (n + 1) - fract (ξ * x) * (n + 1)| ≤ 1,
{ congr, push_cast, simp only [fract], ring, },
exact (abs_sub_lt_one_of_floor_eq_floor hxy.symm).le, }
end
/-- *Dirichlet's approximation theorem:*
For any real number `ξ` and positive natural `n`, there is a natural number `k`,
with `0 < k ≤ n` such that `|k*ξ - round(k*ξ)| ≤ 1/(n+1)`.
-/
lemma exists_nat_abs_mul_sub_round_le (ξ : ℝ) {n : ℕ} (n_pos : 0 < n) :
∃ k : ℕ, 0 < k ∧ k ≤ n ∧ |↑k * ξ - round (↑k * ξ)| ≤ 1 / (n + 1) :=
begin
obtain ⟨j, k, hk₀, hk₁, h⟩ := exists_int_int_abs_mul_sub_le ξ n_pos,
have hk := to_nat_of_nonneg hk₀.le,
rw [← hk] at hk₀ hk₁ h,
exact ⟨k.to_nat, coe_nat_pos.mp hk₀, nat.cast_le.mp hk₁, (round_le (↑k.to_nat * ξ) j).trans h⟩,
end
/-- *Dirichlet's approximation theorem:*
For any real number `ξ` and positive natural `n`, there is a fraction `q`
such that `q.denom ≤ n` and `|ξ - q| ≤ 1/((n+1)*q.denom)`. -/
lemma exists_rat_abs_sub_le_and_denom_le (ξ : ℝ) {n : ℕ} (n_pos : 0 < n) :
∃ q : ℚ, |ξ - q| ≤ 1 / ((n + 1) * q.denom) ∧ q.denom ≤ n :=
begin
obtain ⟨j, k, hk₀, hk₁, h⟩ := exists_int_int_abs_mul_sub_le ξ n_pos,
have hk₀' : (0 : ℝ) < k := int.cast_pos.mpr hk₀,
have hden : ((j / k : ℚ).denom : ℤ) ≤ k,
{ convert le_of_dvd hk₀ (rat.denom_dvd j k), exact rat.coe_int_div_eq_mk, },
refine ⟨j / k, _, nat.cast_le.mp (hden.trans hk₁)⟩,
rw [← div_div, le_div_iff (nat.cast_pos.mpr $ rat.pos _ : (0 : ℝ) < _)],
refine (mul_le_mul_of_nonneg_left (int.cast_le.mpr hden : _ ≤ (k : ℝ)) (abs_nonneg _)).trans _,
rwa [← abs_of_pos hk₀', rat.cast_div, rat.cast_coe_int, rat.cast_coe_int,
← abs_mul, sub_mul, div_mul_cancel _ hk₀'.ne', mul_comm],
end
end dirichlet
section rat_approx
/-!
### Infinitely many good approximations to irrational numbers
We show that an irrational real number `ξ` has infinitely many "good rational approximations",
i.e., fractions `x/y` in lowest terms such that `|ξ - x/y| < 1/y^2`.
-/
open set
/-- Given any rational approximation `q` to the irrational real number `ξ`, there is
a good rational approximation `q'` such that `|ξ - q'| < |ξ - q|`. -/
lemma exists_rat_abs_sub_lt_and_lt_of_irrational {ξ : ℝ} (hξ : irrational ξ) (q : ℚ) :
∃ q' : ℚ, |ξ - q'| < 1 / q'.denom ^ 2 ∧ |ξ - q'| < |ξ - q| :=
begin
have h := abs_pos.mpr (sub_ne_zero.mpr $ irrational.ne_rat hξ q),
obtain ⟨m, hm⟩ := exists_nat_gt (1 / |ξ - q|),
have m_pos : (0 : ℝ) < m := (one_div_pos.mpr h).trans hm,
obtain ⟨q', hbd, hden⟩ := exists_rat_abs_sub_le_and_denom_le ξ (nat.cast_pos.mp m_pos),
have den_pos : (0 : ℝ) < q'.denom := nat.cast_pos.mpr q'.pos,
have md_pos := mul_pos (add_pos m_pos zero_lt_one) den_pos,
refine ⟨q', lt_of_le_of_lt hbd _,
lt_of_le_of_lt hbd $ (one_div_lt md_pos h).mpr $ hm.trans $
lt_of_lt_of_le (lt_add_one _) $ (le_mul_iff_one_le_right $
add_pos m_pos zero_lt_one).mpr $ by exact_mod_cast (q'.pos : 1 ≤ q'.denom)⟩,
rw [sq, one_div_lt_one_div md_pos (mul_pos den_pos den_pos), mul_lt_mul_right den_pos],
exact lt_add_of_le_of_pos (nat.cast_le.mpr hden) zero_lt_one,
end
/-- If `ξ` is an irrational real number, then there are infinitely many good
rational approximations to `ξ`. -/
lemma infinite_rat_abs_sub_lt_one_div_denom_sq_of_irrational {ξ : ℝ} (hξ : irrational ξ) :
{q : ℚ | |ξ - q| < 1 / q.denom ^ 2}.infinite :=
begin
refine or.resolve_left (set.finite_or_infinite _) (λ h, _),
obtain ⟨q, _, hq⟩ := exists_min_image {q : ℚ | |ξ - q| < 1 / q.denom ^ 2} (λ q, |ξ - q|) h
⟨⌊ξ⌋, by simp [abs_of_nonneg, int.fract_lt_one]⟩,
obtain ⟨q', hmem, hbetter⟩ := exists_rat_abs_sub_lt_and_lt_of_irrational hξ q,
exact lt_irrefl _ (lt_of_le_of_lt (hq q' hmem) hbetter),
end
end rat_approx
end real
namespace rat
/-!
### Finitely many good approximations to rational numbers
We now show that a rational number `ξ` has only finitely many good rational
approximations.
-/
open set
/-- If `ξ` is rational, then the good rational approximations to `ξ` have bounded
numerator and denominator. -/
lemma denom_le_and_le_num_le_of_sub_lt_one_div_denom_sq {ξ q : ℚ} (h : |ξ - q| < 1 / q.denom ^ 2) :
q.denom ≤ ξ.denom ∧ ⌈ξ * q.denom⌉ - 1 ≤ q.num ∧ q.num ≤ ⌊ξ * q.denom⌋ + 1 :=
begin
have hq₀ : (0 : ℚ) < q.denom := nat.cast_pos.mpr q.pos,
replace h : |ξ * q.denom - q.num| < 1 / q.denom,
{ rw ← mul_lt_mul_right hq₀ at h,
conv_lhs at h { rw [← abs_of_pos hq₀, ← abs_mul, sub_mul, mul_denom_eq_num], },
rwa [sq, div_mul, mul_div_cancel_left _ hq₀.ne'] at h, },
split,
{ rcases eq_or_ne ξ q with rfl | H,
{ exact le_rfl, },
{ have hξ₀ : (0 : ℚ) < ξ.denom := nat.cast_pos.mpr ξ.pos,
rw [← rat.num_div_denom ξ, div_mul_eq_mul_div, div_sub' _ _ _ hξ₀.ne', abs_div,
abs_of_pos hξ₀, div_lt_iff hξ₀, div_mul_comm, mul_one] at h,
refine nat.cast_le.mp (((one_lt_div hq₀).mp $ lt_of_le_of_lt _ h).le),
norm_cast,
rw [mul_comm _ q.num],
exact int.one_le_abs (sub_ne_zero_of_ne $ mt rat.eq_iff_mul_eq_mul.mpr H), } },
{ obtain ⟨h₁, h₂⟩ := abs_sub_lt_iff.mp (h.trans_le $ (one_div_le zero_lt_one hq₀).mp $
(@one_div_one ℚ _).symm ▸ nat.cast_le.mpr q.pos),
rw [sub_lt_iff_lt_add, add_comm] at h₁ h₂,
rw [← sub_lt_iff_lt_add] at h₂,
norm_cast at h₁ h₂,
exact ⟨sub_le_iff_le_add.mpr (int.ceil_le.mpr h₁.le),
sub_le_iff_le_add.mp (int.le_floor.mpr h₂.le)⟩, }
end
/-- A rational number has only finitely many good rational approximations. -/
lemma finite_rat_abs_sub_lt_one_div_denom_sq (ξ : ℚ) :
{q : ℚ | |ξ - q| < 1 / q.denom ^ 2}.finite :=
begin
let f : ℚ → ℤ × ℕ := λ q, (q.num, q.denom),
set s := {q : ℚ | |ξ - q| < 1 / q.denom ^ 2},
have hinj : function.injective f,
{ intros a b hab,
simp only [prod.mk.inj_iff] at hab,
rw [← rat.num_div_denom a, ← rat.num_div_denom b, hab.1, hab.2], },
have H : f '' s ⊆ ⋃ (y : ℕ) (hy : y ∈ Ioc 0 ξ.denom), Icc (⌈ξ * y⌉ - 1) (⌊ξ * y⌋ + 1) ×ˢ {y},
{ intros xy hxy,
simp only [mem_image, mem_set_of_eq] at hxy,
obtain ⟨q, hq₁, hq₂⟩ := hxy,
obtain ⟨hd, hn⟩ := denom_le_and_le_num_le_of_sub_lt_one_div_denom_sq hq₁,
simp_rw [mem_Union],
refine ⟨q.denom, set.mem_Ioc.mpr ⟨q.pos, hd⟩, _⟩,
simp only [prod_singleton, mem_image, mem_Icc, (congr_arg prod.snd (eq.symm hq₂)).trans rfl],
exact ⟨q.num, hn, hq₂⟩, },
refine finite.of_finite_image (finite.subset _ H) (inj_on_of_injective hinj s),
exact finite.bUnion (finite_Ioc _ _) (λ x hx, finite.prod (finite_Icc _ _) (finite_singleton _)),
end
end rat
/-- The set of good rational approximations to a real number `ξ` is infinite if and only if
`ξ` is irrational. -/
lemma real.infinite_rat_abs_sub_lt_one_div_denom_sq_iff_irrational (ξ : ℝ) :
{q : ℚ | |ξ - q| < 1 / q.denom ^ 2}.infinite ↔ irrational ξ :=
begin
refine ⟨λ h, (irrational_iff_ne_rational ξ).mpr (λ a b H, set.not_infinite.mpr _ h),
real.infinite_rat_abs_sub_lt_one_div_denom_sq_of_irrational⟩,
convert rat.finite_rat_abs_sub_lt_one_div_denom_sq ((a : ℚ) / b),
ext q,
rw [H, (by push_cast : (1 : ℝ) / q.denom ^ 2 = (1 / q.denom ^ 2 : ℚ))],
norm_cast,
end
/-!
### Legendre's Theorem on Rational Approximation
We prove **Legendre's Theorem** on rational approximation: If $\xi$ is a real number and
$x/y$ is a rational number such that $|\xi - x/y| < 1/(2y^2)$,
then $x/y$ is a convergent of the continued fraction expansion of $\xi$.
The proof is by induction. However, the induction proof does not work with the
statement as given, since the assumption is too weak to imply the corresponding
statement for the application of the induction hypothesis. This can be remedied
by making the statement slightly stronger. Namely, we assume that $|\xi - x/y| < 1/(y(2y-1))$
when $y \ge 2$ and $-\frac{1}{2} < \xi - x < 1$ when $y = 1$.
-/
section convergent
namespace real
open int
/-!
### Convergents: definition and API lemmas
-/
/-- We give a direct recursive definition of the convergents of the continued fraction
expansion of a real number `ξ`. The main reason for that is that we want to have the
convergents as rational numbers; the versions
`(generalized_continued_fraction.of ξ).convergents` and
`(generalized_continued_fraction.of ξ).convergents'` always give something of the
same type as `ξ`. We can then also use dot notation `ξ.convergent n`.
Another minor reason is that this demonstrates that the proof
of Legendre's theorem does not need anything beyond this definition.
We provide a proof that this definition agrees with the other one;
see `real.continued_fraction_convergent_eq_convergent`.
(Note that we use the fact that `1/0 = 0` here to make it work for rational `ξ`.) -/
noncomputable def convergent : ℝ → ℕ → ℚ
| ξ 0 := ⌊ξ⌋
| ξ (n + 1) := ⌊ξ⌋ + (convergent (fract ξ)⁻¹ n)⁻¹
/-- The zeroth convergent of `ξ` is `⌊ξ⌋`. -/
@[simp]
lemma convergent_zero (ξ : ℝ) : ξ.convergent 0 = ⌊ξ⌋ := rfl
/-- The `(n+1)`th convergent of `ξ` is the `n`th convergent of `1/(fract ξ)`. -/
@[simp]
lemma convergent_succ (ξ : ℝ) (n : ℕ) :
ξ.convergent (n + 1) = ⌊ξ⌋ + ((fract ξ)⁻¹.convergent n)⁻¹ :=
by simp only [convergent]
/-- All convergents of `0` are zero. -/
@[simp]
lemma convergent_of_zero (n : ℕ) : convergent 0 n = 0 :=
begin
induction n with n ih,
{ simp only [convergent_zero, floor_zero, cast_zero], },
{ simp only [ih, convergent_succ, floor_zero, cast_zero, fract_zero, add_zero, inv_zero], }
end
/-- If `ξ` is an integer, all its convergents equal `ξ`. -/
@[simp]
lemma convergent_of_int {ξ : ℤ} (n : ℕ) : convergent ξ n = ξ :=
begin
cases n,
{ simp only [convergent_zero, floor_int_cast], },
{ simp only [convergent_succ, floor_int_cast, fract_int_cast, convergent_of_zero, add_zero,
inv_zero], }
end
/-!
Our `convergent`s agree with `generalized_continued_fraction.convergents`.
-/
open generalized_continued_fraction
/-- The `n`th convergent of the `generalized_continued_fraction.of ξ`
agrees with `ξ.convergent n`. -/
lemma continued_fraction_convergent_eq_convergent (ξ : ℝ) (n : ℕ) :
(generalized_continued_fraction.of ξ).convergents n = ξ.convergent n :=
begin
induction n with n ih generalizing ξ,
{ simp only [zeroth_convergent_eq_h, of_h_eq_floor, convergent_zero, rat.cast_coe_int], },
{ rw [convergents_succ, ih (fract ξ)⁻¹, convergent_succ, one_div],
norm_cast, }
end
end real
end convergent
/-!
### The key technical condition for the induction proof
-/
namespace real
open int
/-- Define the technical condition to be used as assumption in the inductive proof. -/
-- this is not `private`, as it is used in the public `exists_rat_eq_convergent'` below.
def contfrac_legendre.ass (ξ : ℝ) (u v : ℤ) : Prop :=
is_coprime u v ∧ (v = 1 → (-(1 / 2) : ℝ) < ξ - u) ∧ |ξ - u / v| < (v * (2 * v - 1))⁻¹
-- ### Auxiliary lemmas
-- This saves a few lines below, as it is frequently needed.
private lemma aux₀ {v : ℤ} (hv : 0 < v) : (0 : ℝ) < v ∧ (0 : ℝ) < 2 * v - 1 :=
⟨cast_pos.mpr hv, by {norm_cast, linarith}⟩
-- In the following, we assume that `ass ξ u v` holds and `v ≥ 2`.
variables {ξ : ℝ} {u v : ℤ} (hv : 2 ≤ v) (h : contfrac_legendre.ass ξ u v)
include hv h
-- The fractional part of `ξ` is positive.
private lemma aux₁ : 0 < fract ξ :=
begin
have hv₀ : (0 : ℝ) < v := cast_pos.mpr (zero_lt_two.trans_le hv),
obtain ⟨hv₁, hv₂⟩ := aux₀ (zero_lt_two.trans_le hv),
obtain ⟨hcop, _, h⟩ := h,
refine fract_pos.mpr (λ hf, _),
rw [hf] at h,
have H : (2 * v - 1 : ℝ) < 1,
{ refine (mul_lt_iff_lt_one_right hv₀).mp
((inv_lt_inv hv₀ (mul_pos hv₁ hv₂)).mp (lt_of_le_of_lt _ h)),
have h' : (⌊ξ⌋ : ℝ) - u / v = (⌊ξ⌋ * v - u) / v := by field_simp [hv₀.ne'],
rw [h', abs_div, abs_of_pos hv₀, ← one_div, div_le_div_right hv₀],
norm_cast,
rw [← zero_add (1 : ℤ), add_one_le_iff, abs_pos, sub_ne_zero],
rintro rfl,
cases is_unit_iff.mp (is_coprime_self.mp (is_coprime.mul_left_iff.mp hcop).2); linarith, },
norm_cast at H,
linarith only [hv, H],
end
-- An auxiliary lemma for the inductive step.
private lemma aux₂ : 0 < u - ⌊ξ⌋ * v ∧ u - ⌊ξ⌋ * v < v :=
begin
obtain ⟨hcop, _, h⟩ := h,
obtain ⟨hv₀, hv₀'⟩ := aux₀ (zero_lt_two.trans_le hv),
have hv₁ : 0 < 2 * v - 1 := by linarith only [hv],
rw [← one_div, lt_div_iff (mul_pos hv₀ hv₀'), ← abs_of_pos (mul_pos hv₀ hv₀'), ← abs_mul,
sub_mul, ← mul_assoc, ← mul_assoc, div_mul_cancel _ hv₀.ne', abs_sub_comm, abs_lt,
lt_sub_iff_add_lt, sub_lt_iff_lt_add, mul_assoc] at h,
have hu₀ : 0 ≤ u - ⌊ξ⌋ * v,
{ refine (zero_le_mul_right hv₁).mp ((lt_iff_add_one_le (-1 : ℤ) _).mp _),
replace h := h.1,
rw [← lt_sub_iff_add_lt, ← mul_assoc, ← sub_mul] at h,
exact_mod_cast h.trans_le ((mul_le_mul_right $ hv₀').mpr $
(sub_le_sub_iff_left (u : ℝ)).mpr ((mul_le_mul_right hv₀).mpr (floor_le ξ))), },
have hu₁ : u - ⌊ξ⌋ * v ≤ v,
{ refine le_of_mul_le_mul_right (le_of_lt_add_one _) hv₁,
replace h := h.2,
rw [← sub_lt_iff_lt_add, ← mul_assoc, ← sub_mul,
← add_lt_add_iff_right (v * (2 * v - 1) : ℝ), add_comm (1 : ℝ)] at h,
have := (mul_lt_mul_right $ hv₀').mpr ((sub_lt_sub_iff_left (u : ℝ)).mpr $
(mul_lt_mul_right hv₀).mpr $ sub_right_lt_of_lt_add $ lt_floor_add_one ξ),
rw [sub_mul ξ, one_mul, ← sub_add, add_mul] at this,
exact_mod_cast this.trans h, },
have huv_cop : is_coprime (u - ⌊ξ⌋ * v) v,
{ rwa [sub_eq_add_neg, ← neg_mul, is_coprime.add_mul_right_left_iff], },
refine ⟨lt_of_le_of_ne' hu₀ (λ hf, _), lt_of_le_of_ne hu₁ (λ hf, _)⟩;
{ rw hf at huv_cop,
simp only [is_coprime_zero_left, is_coprime_self, is_unit_iff] at huv_cop,
cases huv_cop; linarith only [hv, huv_cop], },
end
-- The key step: the relevant inequality persists in the inductive step.
private
lemma aux₃ : |(fract ξ)⁻¹ - v / (u - ⌊ξ⌋ * v)| < ((u - ⌊ξ⌋ * v) * (2 * (u - ⌊ξ⌋ * v) - 1))⁻¹ :=
begin
obtain ⟨hu₀, huv⟩ := aux₂ hv h,
have hξ₀ := aux₁ hv h,
set u' := u - ⌊ξ⌋ * v with hu',
have hu'ℝ : (u' : ℝ) = u - ⌊ξ⌋ * v := by exact_mod_cast hu',
rw ← hu'ℝ,
replace hu'ℝ := (eq_sub_iff_add_eq.mp hu'ℝ).symm,
obtain ⟨Hu, Hu'⟩ := aux₀ hu₀,
obtain ⟨Hv, Hv'⟩ := aux₀ (zero_lt_two.trans_le hv),
have H₁ := div_pos (div_pos Hv Hu) hξ₀,
replace h := h.2.2,
have h' : |fract ξ - u' / v| < (v * (2 * v - 1))⁻¹,
{ rwa [hu'ℝ, add_div, mul_div_cancel _ Hv.ne', ← sub_sub, sub_right_comm] at h, },
have H : (2 * u' - 1 : ℝ) ≤ (2 * v - 1) * fract ξ,
{ replace h := (abs_lt.mp h).1,
have : (2 * (v : ℝ) - 1) * (-(v * (2 * v - 1))⁻¹ + u' / v) = 2 * u' - (1 + u') / v,
{ field_simp [Hv.ne', Hv'.ne'], ring, },
rw [hu'ℝ, add_div, mul_div_cancel _ Hv.ne', ← sub_sub, sub_right_comm, self_sub_floor,
lt_sub_iff_add_lt, ← mul_lt_mul_left Hv', this] at h,
refine has_le.le.trans _ h.le,
rw [sub_le_sub_iff_left, div_le_one Hv, add_comm],
exact_mod_cast huv, },
have help₁ : ∀ {a b c : ℝ}, a ≠ 0 → b ≠ 0 → c ≠ 0 →
|a⁻¹ - b / c| = |(a - c / b) * (b / c / a)|,
{ intros, rw abs_sub_comm, congr' 1, field_simp, ring },
have help₂ : ∀ {a b c d : ℝ}, a ≠ 0 → b ≠ 0 → c ≠ 0 → d ≠ 0 →
(b * c)⁻¹ * (b / d / a) = (d * c * a)⁻¹,
{ intros, field_simp, ring },
calc
|(fract ξ)⁻¹ - v / u'|
= |(fract ξ - u' / v) * (v / u' / fract ξ)| : help₁ hξ₀.ne' Hv.ne' Hu.ne'
... = |fract ξ - u' / v| * (v / u' / fract ξ) : by rw [abs_mul, abs_of_pos H₁, abs_sub_comm]
... < (v * (2 * v - 1))⁻¹ * (v / u' / fract ξ) : (mul_lt_mul_right H₁).mpr h'
... = (u' * (2 * v - 1) * fract ξ)⁻¹ : help₂ hξ₀.ne' Hv.ne' Hv'.ne' Hu.ne'
... ≤ (u' * (2 * u' - 1))⁻¹ : by rwa [inv_le_inv (mul_pos (mul_pos Hu Hv') hξ₀) $
mul_pos Hu Hu', mul_assoc, mul_le_mul_left Hu],
end
-- The conditions `ass ξ u v` persist in the inductive step.
private lemma invariant : contfrac_legendre.ass (fract ξ)⁻¹ v (u - ⌊ξ⌋ * v) :=
begin
refine ⟨_, λ huv, _, by exact_mod_cast aux₃ hv h⟩,
{ rw [sub_eq_add_neg, ← neg_mul, is_coprime_comm, is_coprime.add_mul_right_left_iff],
exact h.1, },
{ obtain ⟨hv₀, hv₀'⟩ := aux₀ (zero_lt_two.trans_le hv),
have Hv : (v * (2 * v - 1) : ℝ)⁻¹ + v⁻¹ = 2 / (2 * v - 1),
{ field_simp [hv₀.ne', hv₀'.ne'], ring, },
have Huv : (u / v : ℝ) = ⌊ξ⌋ + v⁻¹,
{ rw [sub_eq_iff_eq_add'.mp huv], field_simp [hv₀.ne'], },
have h' := (abs_sub_lt_iff.mp h.2.2).1,
rw [Huv, ← sub_sub, sub_lt_iff_lt_add, self_sub_floor, Hv] at h',
rwa [lt_sub_iff_add_lt', (by ring : (v : ℝ) + -(1 / 2) = (2 * v - 1) / 2),
lt_inv (div_pos hv₀' zero_lt_two) (aux₁ hv h), inv_div], }
end
omit h hv
/-!
### The main result
-/
/-- The technical version of *Legendre's Theorem*. -/
lemma exists_rat_eq_convergent' {v : ℕ} (h : contfrac_legendre.ass ξ u v) :
∃ n, (u / v : ℚ) = ξ.convergent n :=
begin
induction v using nat.strong_induction_on with v ih generalizing ξ u,
rcases lt_trichotomy v 1 with ht | rfl | ht,
{ replace h := h.2.2,
simp only [nat.lt_one_iff.mp ht, nat.cast_zero, div_zero, tsub_zero, zero_mul, cast_zero,
inv_zero] at h,
exact false.elim (lt_irrefl _ $ (abs_nonneg ξ).trans_lt h), },
{ rw [nat.cast_one, div_one],
obtain ⟨_, h₁, h₂⟩ := h,
cases le_or_lt (u : ℝ) ξ with ht ht,
{ use 0,
rw [convergent_zero, rat.coe_int_inj, eq_comm, floor_eq_iff],
convert and.intro ht (sub_lt_iff_lt_add'.mp (abs_lt.mp h₂).2); norm_num, },
{ replace h₁ := lt_sub_iff_add_lt'.mp (h₁ rfl),
have hξ₁ : ⌊ξ⌋ = u - 1,
{ rw [floor_eq_iff, cast_sub, cast_one, sub_add_cancel],
exact ⟨(((sub_lt_sub_iff_left _).mpr one_half_lt_one).trans h₁).le, ht⟩, },
cases eq_or_ne ξ ⌊ξ⌋ with Hξ Hξ,
{ rw [Hξ, hξ₁, cast_sub, cast_one, ← sub_eq_add_neg, sub_lt_sub_iff_left] at h₁,
exact false.elim (lt_irrefl _ $ h₁.trans one_half_lt_one), },
{ have hξ₂ : ⌊(fract ξ)⁻¹⌋ = 1,
{ rw [floor_eq_iff, cast_one, le_inv zero_lt_one (fract_pos.mpr Hξ), inv_one,
one_add_one_eq_two, inv_lt (fract_pos.mpr Hξ) zero_lt_two],
refine ⟨(fract_lt_one ξ).le, _⟩,
rw [fract, hξ₁, cast_sub, cast_one, lt_sub_iff_add_lt', sub_add],
convert h₁,
norm_num, },
use 1,
simp [convergent, hξ₁, hξ₂, cast_sub, cast_one], } } },
{ obtain ⟨huv₀, huv₁⟩ := aux₂ (nat.cast_le.mpr ht) h,
have Hv : (v : ℚ) ≠ 0 := (nat.cast_pos.mpr (zero_lt_one.trans ht)).ne',
have huv₁' : (u - ⌊ξ⌋ * v).to_nat < v := by { zify, rwa to_nat_of_nonneg huv₀.le, },
have inv : contfrac_legendre.ass (fract ξ)⁻¹ v (u - ⌊ξ⌋ * ↑v).to_nat :=
(to_nat_of_nonneg huv₀.le).symm ▸ invariant (nat.cast_le.mpr ht) h,
obtain ⟨n, hn⟩ := ih (u - ⌊ξ⌋ * v).to_nat huv₁' inv,
use (n + 1),
rw [convergent_succ, ← hn,
(by exact_mod_cast to_nat_of_nonneg huv₀.le : ((u - ⌊ξ⌋ * v).to_nat : ℚ) = u - ⌊ξ⌋ * v),
← coe_coe, inv_div, sub_div, mul_div_cancel _ Hv, add_sub_cancel'_right], }
end
/-- The main result, *Legendre's Theorem* on rational approximation:
if `ξ` is a real number and `q` is a rational number such that `|ξ - q| < 1/(2*q.denom^2)`,
then `q` is a convergent of the continued fraction expansion of `ξ`.
This version uses `real.convergent`. -/
lemma exists_rat_eq_convergent {q : ℚ} (h : |ξ - q| < 1 / (2 * q.denom ^ 2)) :
∃ n, q = ξ.convergent n :=
begin
refine q.num_div_denom ▸ exists_rat_eq_convergent' ⟨_, λ hd, _, _⟩,
{ exact coprime_iff_nat_coprime.mpr (nat_abs_of_nat q.denom ▸ q.cop), },
{ rw ← q.denom_eq_one_iff.mp (nat.cast_eq_one.mp hd) at h,
simpa only [rat.coe_int_denom, nat.cast_one, one_pow, mul_one] using (abs_lt.mp h).1 },
{ obtain ⟨hq₀, hq₁⟩ := aux₀ (nat.cast_pos.mpr q.pos),
replace hq₁ := mul_pos hq₀ hq₁,
have hq₂ : (0 : ℝ) < 2 * (q.denom * q.denom) := mul_pos zero_lt_two (mul_pos hq₀ hq₀),
rw ← coe_coe at *,
rw [(by norm_cast : (q.num / q.denom : ℝ) = (q.num / q.denom : ℚ)), rat.num_div_denom],
exact h.trans
(by {rw [← one_div, sq, one_div_lt_one_div hq₂ hq₁, ← sub_pos], ring_nf, exact hq₀}), }
end
/-- The main result, *Legendre's Theorem* on rational approximation:
if `ξ` is a real number and `q` is a rational number such that `|ξ - q| < 1/(2*q.denom^2)`,
then `q` is a convergent of the continued fraction expansion of `ξ`.
This is the version using `generalized_contined_fraction.convergents`. -/
lemma exists_continued_fraction_convergent_eq_rat {q : ℚ} (h : |ξ - q| < 1 / (2 * q.denom ^ 2)) :
∃ n, (generalized_continued_fraction.of ξ).convergents n = q :=
begin
obtain ⟨n, hn⟩ := exists_rat_eq_convergent h,
exact ⟨n, hn.symm ▸ continued_fraction_convergent_eq_convergent ξ n⟩,
end
end real
|
6fc839ed88c9549ea1b8e8d514308271602d6041 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Elab/StructInst.lean | 794257e8547b36254f0c198e1e2d282e6c64abbd | [
"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 | 33,660 | 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.FindExpr
import Lean.Elab.App
import Lean.Elab.Binders
import Lean.Elab.Quotation
namespace Lean
namespace Elab
namespace Term
namespace StructInst
open Std (HashMap)
open Meta
/- parser! "{" >> optional (try (termParser >> "with")) >> sepBy structInstField ", " true >> optional ".." >> optional (" : " >> termParser) >> "}" -/
@[builtinMacro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro :=
fun stx =>
let expectedArg := stx.getArg 4;
if expectedArg.isNone
then Macro.throwUnsupported
else
let expected := expectedArg.getArg 1;
let stxNew := stx.setArg 4 mkNullNode;
`(($stxNew : $expected))
/-
If `stx` is of the form `{ s with ... }` and `s` is not a local variable, expand into `let src := s; { src with ... }`.
Note that this one is not a `Macro` because we need to access the local context.
-/
private def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) :=
withFreshMacroScope $
let sourceOpt := stx.getArg 1;
if sourceOpt.isNone then pure none else do
let source := sourceOpt.getArg 0;
fvar? ← isLocalIdent? source;
match fvar? with
| some _ => pure none
| none => do
src ← `(src);
let sourceOpt := sourceOpt.setArg 0 src;
let stxNew := stx.setArg 1 sourceOpt;
`(let src := $source; $stxNew)
inductive Source
| none -- structure instance source has not been provieded
| implicit (stx : Syntax) -- `..`
| explicit (stx : Syntax) (src : Expr) -- `src with`
instance Source.inhabited : Inhabited Source := ⟨Source.none⟩
def Source.isNone : Source → Bool
| Source.none => true
| _ => false
def setStructSourceSyntax (structStx : Syntax) : Source → Syntax
| Source.none => (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode
| Source.implicit stx => (structStx.setArg 1 mkNullNode).setArg 3 stx
| Source.explicit stx _ => (structStx.setArg 1 stx).setArg 3 mkNullNode
private def getStructSource (stx : Syntax) : TermElabM Source :=
withRef stx $
let explicitSource := stx.getArg 1;
let implicitSource := stx.getArg 3;
if explicitSource.isNone && implicitSource.isNone then
pure Source.none
else if explicitSource.isNone then
pure $ Source.implicit implicitSource
else if implicitSource.isNone then do
fvar? ← isLocalIdent? (explicitSource.getArg 0);
match fvar? with
| none => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here
| some src => pure $ Source.explicit explicitSource src
else
throwError "invalid structure instance `with` and `..` cannot be used together"
/-
We say a `{ ... }` notation is a `modifyOp` if it contains only one
```
def structInstArrayRef := parser! "[" >> termParser >>"]"
``` -/
private def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do
let args := (stx.getArg 2).getArgs;
s? ← args.foldSepByM
(fun arg s? =>
/- Remark: the syntax for `structInstField` is
```
def structInstLVal := (ident <|> numLit <|> structInstArrayRef) >> many (group ("." >> (ident <|> numLit)) <|> structInstArrayRef)
def structInstField := parser! structInstLVal >> " := " >> termParser
``` -/
let lval := arg.getArg 0;
let k := lval.getKind;
if k == `Lean.Parser.Term.structInstArrayRef then
match s? with
| none => pure (some arg)
| some s =>
if s.getKind == `Lean.Parser.Term.structInstArrayRef then
throwErrorAt arg "invalid {...} notation, at most one `[..]` at a given level"
else
throwErrorAt arg "invalid {...} notation, can't mix field and `[..]` at a given level"
else
match s? with
| none => pure (some arg)
| some s =>
if s.getKind == `Lean.Parser.Term.structInstArrayRef then
throwErrorAt arg "invalid {...} notation, can't mix field and `[..]` at a given level"
else
pure s?)
none;
match s? with
| none => pure none
| some s => if (s.getArg 0).getKind == `Lean.Parser.Term.structInstArrayRef then pure s? else pure none
private def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr :=
let continue (val : Syntax) : TermElabM Expr := do {
let lval := modifyOp.getArg 0;
let idx := lval.getArg 1;
let self := source.getArg 0;
stxNew ← `($(self).modifyOp (idx := $idx) (fun s => $val));
trace `Elab.struct.modifyOp fun _ => stx ++ "\n===>\n" ++ stxNew;
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
}; do
trace `Elab.struct.modifyOp fun _ => modifyOp ++ "\nSource: " ++ source;
let rest := modifyOp.getArg 1;
if rest.isNone then do
continue (modifyOp.getArg 3)
else do
s ← `(s);
let valFirst := rest.getArg 0;
let valFirst := if valFirst.getKind == `Lean.Parser.Term.structInstArrayRef then valFirst else valFirst.getArg 1;
let restArgs := rest.getArgs;
let valRest := mkNullNode (restArgs.extract 1 restArgs.size);
let valField := modifyOp.setArg 0 valFirst;
let valField := valField.setArg 1 valRest;
let valSource := source.modifyArg 0 $ fun _ => s;
let val := stx.setArg 1 valSource;
let val := val.setArg 2 $ mkNullNode #[valField];
trace `Elab.struct.modifyOp fun _ => stx ++ "\nval: " ++ val;
continue val
/- Get structure name and elaborate explicit source (if available) -/
private def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM Name := do
tryPostponeIfNoneOrMVar expectedType?;
let useSource : Unit → TermElabM Name := fun _ =>
match sourceView, expectedType? with
| Source.explicit _ src, _ => do
srcType ← inferType src;
srcType ← whnf srcType;
tryPostponeIfMVar srcType;
match srcType.getAppFn with
| Expr.const constName _ _ => pure constName
| _ => throwError ("invalid {...} notation, source type is not of the form (C ...)" ++ indentExpr srcType)
| _, some expectedType => throwError ("invalid {...} notation, expected type is not of the form (C ...)" ++ indentExpr expectedType)
| _, none => throwError ("invalid {...} notation, expected type must be known");
match expectedType? with
| none => useSource ()
| some expectedType => do
expectedType ← whnf expectedType;
match expectedType.getAppFn with
| Expr.const constName _ _ => pure constName
| _ => useSource ()
inductive FieldLHS
| fieldName (ref : Syntax) (name : Name)
| fieldIndex (ref : Syntax) (idx : Nat)
| modifyOp (ref : Syntax) (index : Syntax)
instance FieldLHS.inhabited : Inhabited FieldLHS := ⟨FieldLHS.fieldName (arbitrary _) (arbitrary _)⟩
instance FieldLHS.hasFormat : HasFormat FieldLHS :=
⟨fun lhs => match lhs with
| FieldLHS.fieldName _ n => fmt n
| FieldLHS.fieldIndex _ i => fmt i
| FieldLHS.modifyOp _ i => "[" ++ i.prettyPrint ++ "]"⟩
inductive FieldVal (σ : Type)
| term (stx : Syntax) : FieldVal
| nested (s : σ) : FieldVal
| default : FieldVal -- mark that field must be synthesized using default value
structure Field (σ : Type) :=
(ref : Syntax) (lhs : List FieldLHS) (val : FieldVal σ) (expr? : Option Expr := none)
instance Field.inhabited {σ} : Inhabited (Field σ) := ⟨⟨arbitrary _, [], FieldVal.term (arbitrary _), arbitrary _⟩⟩
def Field.isSimple {σ} : Field σ → Bool
| { lhs := [_], .. } => true
| _ => false
inductive Struct
| mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source)
instance Struct.inhabited : Inhabited Struct := ⟨⟨arbitrary _, arbitrary _, [], arbitrary _⟩⟩
abbrev Fields := List (Field Struct)
/- true if all fields of the given structure are marked as `default` -/
partial def Struct.allDefault : Struct → Bool
| ⟨_, _, fields, _⟩ => fields.all fun ⟨_, _, val, _⟩ => match val with
| FieldVal.term _ => false
| FieldVal.default => true
| FieldVal.nested s => Struct.allDefault s
def Struct.ref : Struct → Syntax
| ⟨ref, _, _, _⟩ => ref
def Struct.structName : Struct → Name
| ⟨_, structName, _, _⟩ => structName
def Struct.fields : Struct → Fields
| ⟨_, _, fields, _⟩ => fields
def Struct.source : Struct → Source
| ⟨_, _, _, s⟩ => s
def formatField (formatStruct : Struct → Format) (field : Field Struct) : Format :=
Format.joinSep field.lhs " . " ++ " := " ++
match field.val with
| FieldVal.term v => v.prettyPrint
| FieldVal.nested s => formatStruct s
| FieldVal.default => "<default>"
partial def formatStruct : Struct → Format
| ⟨_, structName, fields, source⟩ =>
let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) ", ";
match source with
| Source.none => "{" ++ fieldsFmt ++ "}"
| Source.implicit _ => "{" ++ fieldsFmt ++ " .. }"
| Source.explicit _ src => "{" ++ format src ++ " with " ++ fieldsFmt ++ "}"
instance Struct.hasFormat : HasFormat Struct := ⟨formatStruct⟩
instance Struct.hasToString : HasToString Struct := ⟨toString ∘ format⟩
instance Field.hasFormat : HasFormat (Field Struct) := ⟨formatField formatStruct⟩
instance Field.hasToString : HasToString (Field Struct) := ⟨toString ∘ format⟩
/-
Recall that `structInstField` elements have the form
```
def structInstField := parser! structInstLVal >> " := " >> termParser
def structInstLVal := (ident <|> numLit <|> structInstArrayRef) >> many (("." >> (ident <|> numLit)) <|> structInstArrayRef)
def structInstArrayRef := parser! "[" >> termParser >>"]"
-/
-- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName`
def FieldLHS.toSyntax (first : Bool) : FieldLHS → Syntax
| FieldLHS.modifyOp stx _ => stx
| FieldLHS.fieldName stx name => if first then mkIdentFrom stx name else mkNullNode #[mkAtomFrom stx ".", mkIdentFrom stx name]
| FieldLHS.fieldIndex stx _ => if first then stx else mkNullNode #[mkAtomFrom stx ".", stx]
def FieldVal.toSyntax : FieldVal Struct → Syntax
| FieldVal.term stx => stx
| _ => unreachable!
def Field.toSyntax : Field Struct → Syntax
| field =>
let stx := field.ref;
let stx := stx.setArg 3 field.val.toSyntax;
match field.lhs with
| first::rest =>
let stx := stx.setArg 0 $ first.toSyntax true;
let stx := stx.setArg 1 $ mkNullNode $ rest.toArray.map (FieldLHS.toSyntax false);
stx
| _ => unreachable!
private def toFieldLHS (stx : Syntax) : Except String FieldLHS :=
if stx.getKind == `Lean.Parser.Term.structInstArrayRef then
pure $ FieldLHS.modifyOp stx (stx.getArg 1)
else
-- Note that the representation of the first field is different.
let stx := if stx.getKind == nullKind then stx.getArg 1 else stx;
if stx.isIdent then pure $ FieldLHS.fieldName stx stx.getId.eraseMacroScopes
else match stx.isFieldIdx? with
| some idx => pure $ FieldLHS.fieldIndex stx idx
| none => throw "unexpected structure syntax"
private def mkStructView (stx : Syntax) (structName : Name) (source : Source) : Except String Struct := do
let args := (stx.getArg 2).getArgs;
let fieldsStx := args.filter $ fun arg => arg.getKind == `Lean.Parser.Term.structInstField;
fields ← fieldsStx.toList.mapM $ fun fieldStx => do {
let val := fieldStx.getArg 3;
first ← toFieldLHS (fieldStx.getArg 0);
rest ← (fieldStx.getArg 1).getArgs.toList.mapM toFieldLHS;
pure $ ({ref := fieldStx, lhs := first :: rest, val := FieldVal.term val } : Field Struct)
};
pure ⟨stx, structName, fields, source⟩
def Struct.modifyFieldsM {m : Type → Type} [Monad m] (s : Struct) (f : Fields → m Fields) : m Struct :=
match s with
| ⟨ref, structName, fields, source⟩ => do fields ← f fields; pure ⟨ref, structName, fields, source⟩
@[inline] def Struct.modifyFields (s : Struct) (f : Fields → Fields) : Struct :=
Id.run $ s.modifyFieldsM f
def Struct.setFields (s : Struct) (fields : Fields) : Struct :=
s.modifyFields $ fun _ => fields
private def expandCompositeFields (s : Struct) : Struct :=
s.modifyFields $ fun fields => fields.map $ fun field => match field with
| { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field
| { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } =>
let newEntries := n.components.map $ FieldLHS.fieldName ref;
{ field with lhs := newEntries ++ rest }
| _ => field
private def expandNumLitFields (s : Struct) : TermElabM Struct :=
s.modifyFieldsM $ fun fields => do
env ← getEnv;
let fieldNames := getStructureFields env s.structName;
fields.mapM $ fun field => match field with
| { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } =>
if idx == 0 then throwErrorAt ref "invalid field index, index must be greater than 0"
else if idx > fieldNames.size then throwErrorAt ref ("invalid field index, structure has only #" ++ toString fieldNames.size ++ " fields")
else pure { field with lhs := FieldLHS.fieldName ref (fieldNames.get! $ idx - 1) :: rest }
| _ => pure field
/- For example, consider the following structures:
```
structure A := (x : Nat)
structure B extends A := (y : Nat)
structure C extends B := (z : Bool)
```
This method expands parent structure fields using the path to the parent structure.
For example,
```
{ x := 0, y := 0, z := true : C }
```
is expanded into
```
{ toB.toA.x := 0, toB.y := 0, z := true : C }
``` -/
private def expandParentFields (s : Struct) : TermElabM Struct := do
env ← getEnv;
s.modifyFieldsM $ fun fields => fields.mapM $ fun field => match field with
| { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } =>
match findField? env s.structName fieldName with
| none => throwErrorAt ref ("'" ++ fieldName ++ "' is not a field of structure '" ++ s.structName ++ "'")
| some baseStructName =>
if baseStructName == s.structName then pure field
else match getPathToBaseStructure? env baseStructName s.structName with
| some path => do
let path := path.map $ fun funName => match funName with
| Name.str _ s _ => FieldLHS.fieldName ref (mkNameSimple s)
| _ => unreachable!;
pure { field with lhs := path ++ field.lhs }
| _ => throwErrorAt ref ("failed to access field '" ++ fieldName ++ "' in parent structure")
| _ => pure field
private abbrev FieldMap := HashMap Name Fields
private def mkFieldMap (fields : Fields) : TermElabM FieldMap :=
fields.foldlM
(fun fieldMap field =>
match field.lhs with
| FieldLHS.fieldName _ fieldName :: rest =>
match fieldMap.find? fieldName with
| some (prevField::restFields) =>
if field.isSimple || prevField.isSimple then
throwErrorAt field.ref ("field '" ++ fieldName ++ "' has already beed specified")
else
pure $ fieldMap.insert fieldName (field::prevField::restFields)
| _ => pure $ fieldMap.insert fieldName [field]
| _ => unreachable!)
{}
private def isSimpleField? : Fields → Option (Field Struct)
| [field] => if field.isSimple then some field else none
| _ => none
private def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do
match fieldNames.findIdx? $ fun n => n == fieldName with
| some idx => pure idx
| none => throwError ("field '" ++ fieldName ++ "' is not a valid field of '" ++ structName ++ "'")
private def mkProjStx (s : Syntax) (fieldName : Name) : Syntax :=
Syntax.node `Lean.Parser.Term.proj #[s, mkAtomFrom s ".", mkIdentFrom s fieldName]
private def mkSubstructSource (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source :=
match src with
| Source.explicit stx src => do
idx ← getFieldIdx structName fieldNames fieldName;
let stx := stx.modifyArg 0 $ fun stx => mkProjStx stx fieldName;
pure $ Source.explicit stx (mkProj structName idx src)
| s => pure s
@[specialize] private def groupFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do
env ← getEnv;
let fieldNames := getStructureFields env s.structName;
withRef s.ref $
s.modifyFieldsM $ fun fields => do
fieldMap ← mkFieldMap fields;
fieldMap.toList.mapM $ fun ⟨fieldName, fields⟩ =>
match isSimpleField? fields with
| some field => pure field
| none => do
let substructFields := fields.map $ fun field => { field with lhs := field.lhs.tail! };
substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source;
let field := fields.head!;
match Lean.isSubobjectField? env s.structName fieldName with
| some substructName => do
let substruct := Struct.mk s.ref substructName substructFields substructSource;
substruct ← expandStruct substruct;
pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct }
| none => do
-- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them.
let valStx := s.ref; -- construct substructure syntax using s.ref as template
let valStx := valStx.setArg 4 mkNullNode; -- erase optional expected type
let args := substructFields.toArray.map $ Field.toSyntax;
let valStx := valStx.setArg 2 (mkSepStx args (mkAtomFrom s.ref ","));
let valStx := setStructSourceSyntax valStx substructSource;
pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx }
def findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) :=
fields.find? $ fun field =>
match field.lhs with
| [FieldLHS.fieldName _ n] => n == fieldName
| _ => false
@[specialize] private def addMissingFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do
env ← getEnv;
let fieldNames := getStructureFields env s.structName;
let ref := s.ref;
withRef ref do
fields ← fieldNames.foldlM
(fun fields fieldName => do
match findField? s.fields fieldName with
| some field => pure $ field::fields
| none =>
let addField (val : FieldVal Struct) : TermElabM Fields := do {
pure $ { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields
};
match Lean.isSubobjectField? env s.structName fieldName with
| some substructName => do
substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source;
let substruct := Struct.mk s.ref substructName [] substructSource;
substruct ← expandStruct substruct;
addField (FieldVal.nested substruct)
| none =>
match s.source with
| Source.none => addField FieldVal.default
| Source.implicit _ => addField (FieldVal.term (mkHole s.ref))
| Source.explicit stx _ =>
-- stx is of the form `optional (try (termParser >> "with"))`
let src := stx.getArg 0;
let val := mkProjStx src fieldName;
addField (FieldVal.term val))
[];
pure $ s.setFields fields.reverse
private partial def expandStruct : Struct → TermElabM Struct
| s => do
let s := expandCompositeFields s;
s ← expandNumLitFields s;
s ← expandParentFields s;
s ← groupFields expandStruct s;
addMissingFields expandStruct s
structure CtorHeaderResult :=
(ctorFn : Expr)
(ctorFnType : Expr)
(instMVars : Array MVarId := #[])
private def mkCtorHeaderAux : Nat → Expr → Expr → Array MVarId → TermElabM CtorHeaderResult
| 0, type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars }
| n+1, type, ctorFn, instMVars => do
type ← whnfForall type;
match type with
| Expr.forallE _ d b c =>
match c.binderInfo with
| BinderInfo.instImplicit => do
a ← mkFreshExprMVar d MetavarKind.synthetic;
mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!)
| _ => do
a ← mkFreshExprMVar d;
mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars
| _ => throwError "unexpected constructor type"
private partial def getForallBody : Nat → Expr → Option Expr
| i+1, Expr.forallE _ _ b _ => getForallBody i b
| i+1, _ => none
| 0, type => type
private def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit :=
match expectedType? with
| none => pure ()
| some expectedType =>
match getForallBody numFields type with
| none => pure ()
| some typeBody =>
unless typeBody.hasLooseBVars $ do
_ ← isDefEq expectedType typeBody;
pure ()
private def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do
lvls ← ctorVal.lparams.mapM $ fun _ => mkFreshLevelMVar;
let val := Lean.mkConst ctorVal.name lvls;
let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams lvls;
r ← mkCtorHeaderAux ctorVal.nparams type val #[];
propagateExpectedType r.ctorFnType ctorVal.nfields expectedType?;
synthesizeAppInstMVars r.instMVars;
pure r
def markDefaultMissing (e : Expr) : Expr :=
mkAnnotation `structInstDefault e
def defaultMissing? (e : Expr) : Option Expr :=
annotation? `structInstDefault e
def throwFailedToElabField {α} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM α :=
throwError ("failed to elaborate field '" ++ fieldName ++ "' of '" ++ structName ++ ", " ++ msgData)
def trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) :=
if !s.allDefault then pure none
else
catch (synthInstance? expectedType) (fun _ => pure none)
private partial def elabStruct : Struct → Option Expr → TermElabM (Expr × Struct)
| s, expectedType? => withRef s.ref do
env ← getEnv;
let ctorVal := getStructureCtor env s.structName;
{ ctorFn := ctorFn, ctorFnType := ctorFnType, .. } ← mkCtorHeader ctorVal expectedType?;
(e, _, fields) ← s.fields.foldlM
(fun (acc : Expr × Expr × Fields) field =>
let (e, type, fields) := acc;
match field.lhs with
| [FieldLHS.fieldName ref fieldName] => do
type ← whnfForall type;
match type with
| Expr.forallE _ d b c =>
let continue (val : Expr) (field : Field Struct) : TermElabM (Expr × Expr × Fields) := do {
let e := mkApp e val;
let type := b.instantiate1 val;
let field := { field with expr? := some val };
pure (e, type, field::fields)
};
match field.val with
| FieldVal.term stx => do val ← elabTermEnsuringType stx d; continue val field
| FieldVal.nested s => do
val? ← trySynthStructInstance? s d; -- if all fields of `s` are marked as `default`, then try to synthesize instance
match val? with
| some val => continue val { field with val := FieldVal.term (mkHole field.ref) }
| none => do(val, sNew) ← elabStruct s (some d); val ← ensureHasType d val; continue val { field with val := FieldVal.nested sNew }
| FieldVal.default => do val ← withRef field.ref $ mkFreshExprMVar (some d); continue (markDefaultMissing val) field
| _ => withRef field.ref $ throwFailedToElabField fieldName s.structName ("unexpected constructor type" ++ indentExpr type)
| _ => throwErrorAt field.ref "unexpected unexpanded structure field")
(ctorFn, ctorFnType, []);
pure (e, s.setFields fields.reverse)
namespace DefaultFields
structure Context :=
-- We must search for default values overriden in derived structures
(structs : Array Struct := #[])
(allStructNames : Array Name := #[])
/-
Consider the following example:
```
structure A :=
(x : Nat := 1)
structure B extends A :=
(y : Nat := x + 1) (x := y + 1)
structure C extends B :=
(z : Nat := 2*y) (x := z + 3)
```
And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`.
We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2.
The field `maxDistance` specifies the maximum distance considered in a round of Default field computation.
Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0.
The fixpoint for setting default values works in the following way.
- Keep computing default values using `maxDistance == 0`.
- We increase `maxDistance` whenever we failed to compute a new default value in a round.
- If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value.
We use depth-first search.
- We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above).
-/
(maxDistance : Nat := 0)
structure State :=
(progress : Bool := false)
partial def collectStructNames : Struct → Array Name → Array Name
| struct, names =>
let names := names.push struct.structName;
struct.fields.foldl
(fun names field =>
match field.val with
| FieldVal.nested struct => collectStructNames struct names
| _ => names)
names
partial def getHierarchyDepth : Struct → Nat
| struct =>
struct.fields.foldl
(fun max field =>
match field.val with
| FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1)
| _ => max)
0
partial def findDefaultMissing? (mctx : MetavarContext) : Struct → Option (Field Struct)
| struct =>
struct.fields.findSome? $ fun field =>
match field.val with
| FieldVal.nested struct => findDefaultMissing? struct
| _ => match field.expr? with
| none => unreachable!
| some expr => match defaultMissing? expr with
| some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field
| _ => none
def getFieldName (field : Field Struct) : Name :=
match field.lhs with
| [FieldLHS.fieldName _ fieldName] => fieldName
| _ => unreachable!
abbrev M := ReaderT Context (StateRefT State TermElabM)
def isRoundDone : M Bool := do
ctx ← read;
s ← get;
pure (s.progress && ctx.maxDistance > 0)
def getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr :=
struct.fields.findSome? $ fun field =>
if getFieldName field == fieldName then
field.expr?
else
none
partial def mkDefaultValueAux? (struct : Struct) : Expr → TermElabM (Option Expr)
| Expr.lam n d b c => withRef struct.ref $
if c.binderInfo.isExplicit then
let fieldName := n;
match getFieldValue? struct fieldName with
| none => pure none
| some val => do
valType ← inferType val;
condM (isDefEq valType d)
(mkDefaultValueAux? (b.instantiate1 val))
(pure none)
else do
arg ← mkFreshExprMVar d;
mkDefaultValueAux? (b.instantiate1 arg)
| e =>
if e.isAppOfArity `id 2 then
pure (some e.appArg!)
else
pure (some e)
def mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) :=
withRef struct.ref do
us ← cinfo.lparams.mapM $ fun _ => mkFreshLevelMVar;
mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us)
/-- If `e` is a projection function of one of the given structures, then reduce it -/
def reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do
if !e.isApp then pure none
else match e.getAppFn with
| Expr.const name _ _ => do
env ← getEnv;
match env.getProjectionStructureName? name with
| some structName =>
if structNames.contains structName then
Meta.unfoldDefinition? e
else
pure none
| none => pure none
| _ => pure none
/-- Reduce default value. It performs beta reduction and projections of the given structures. -/
partial def reduce (structNames : Array Name) : Expr → MetaM Expr
| e@(Expr.lam _ _ _ _) => lambdaLetTelescope e $ fun xs b => do b ← reduce b; mkLambdaFVars xs b
| e@(Expr.forallE _ _ _ _) => forallTelescope e $ fun xs b => do b ← reduce b; mkForallFVars xs b
| e@(Expr.letE _ _ _ _ _) => lambdaLetTelescope e $ fun xs b => do b ← reduce b; mkLetFVars xs b
| e@(Expr.proj _ i b _) => do
r? ← Meta.reduceProj? b i;
match r? with
| some r => reduce r
| none => do b ← reduce b; pure $ e.updateProj! b
| e@(Expr.app f _ _) => do
r? ← reduceProjOf? structNames e;
match r? with
| some r => reduce r
| none => do
let f := f.getAppFn;
f' ← reduce f;
if f'.isLambda then
let revArgs := e.getAppRevArgs;
reduce $ f'.betaRev revArgs
else do
args ← e.getAppArgs.mapM reduce;
pure (mkAppN f' args)
| e@(Expr.mdata _ b _) => do
b ← reduce b;
if (defaultMissing? e).isSome && !b.isMVar then
pure b
else
pure $ e.updateMData! b
| e@(Expr.mvar mvarId _) => do
val? ← getExprMVarAssignment? mvarId;
match val? with
| some val => if val.isMVar then reduce val else pure val
| none => pure e
| e => pure e
partial def tryToSynthesizeDefaultAux (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat)
(fieldName : Name) (mvarId : MVarId) : Nat → Nat → TermElabM Bool
| i, dist =>
if dist > maxDistance then pure false
else if h : i < structs.size then do
let struct := structs.get ⟨i, h⟩;
let defaultName := struct.structName ++ fieldName ++ `_default;
env ← getEnv;
match env.find? defaultName with
| some cinfo@(ConstantInfo.defnInfo defVal) => do
mctx ← getMCtx;
val? ← mkDefaultValue? struct cinfo;
match val? with
| none => do setMCtx mctx; tryToSynthesizeDefaultAux (i+1) (dist+1)
| some val => do
val ← liftMetaM $ reduce allStructNames val;
match val.find? $ fun e => (defaultMissing? e).isSome with
| some _ => do setMCtx mctx; tryToSynthesizeDefaultAux (i+1) (dist+1)
| none => do
mvarDecl ← getMVarDecl mvarId;
val ← ensureHasType mvarDecl.type val;
assignExprMVar mvarId val;
pure true
| _ => tryToSynthesizeDefaultAux (i+1) dist
else
pure false
def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name)
(maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool :=
tryToSynthesizeDefaultAux structs allStructNames maxDistance fieldName mvarId 0 0
partial def step : Struct → M Unit
| struct => unlessM isRoundDone $ adaptReader (fun (ctx : Context) => { ctx with structs := ctx.structs.push struct }) $ do
struct.fields.forM $ fun field =>
match field.val with
| FieldVal.nested struct => step struct
| _ => match field.expr? with
| none => unreachable!
| some expr => match defaultMissing? expr with
| some (Expr.mvar mvarId _) =>
unlessM (liftM $ isExprMVarAssigned mvarId) $ do
ctx ← read;
whenM (liftM $ withRef field.ref $ tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) $ do
modify $ fun s => { s with progress := true }
| _ => pure ()
partial def propagateLoop (hierarchyDepth : Nat) : Nat → Struct → M Unit
| d, struct => do
mctx ← getMCtx;
match findDefaultMissing? mctx struct with
| none => pure () -- Done
| some field =>
if d > hierarchyDepth then
throwErrorAt field.ref ("field '" ++ getFieldName field ++ "' is missing")
else adaptReader (fun (ctx : Context) => { ctx with maxDistance := d }) $ do
modify $ fun (s : State) => { s with progress := false };
step struct;
s ← get;
if s.progress then do
propagateLoop 0 struct
else
propagateLoop (d+1) struct
def propagate (struct : Struct) : TermElabM Unit :=
let hierarchyDepth := getHierarchyDepth struct;
let structNames := collectStructNames struct #[];
(propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {}
end DefaultFields
private def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do
structName ← getStructName stx expectedType? source;
env ← getEnv;
unless (isStructureLike env structName) $
throwError ("invalid {...} notation, '" ++ structName ++ "' is not a structure");
match mkStructView stx structName source with
| Except.error ex => throwError ex
| Except.ok struct => do
struct ← expandStruct struct;
trace `Elab.struct fun _ => toString struct;
(r, struct) ← elabStruct struct expectedType?;
DefaultFields.propagate struct;
pure r
@[builtinTermElab structInst] def elabStructInst : TermElab :=
fun stx expectedType? => do
stxNew? ← expandNonAtomicExplicitSource stx;
match stxNew? with
| some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| none => do
sourceView ← getStructSource stx;
modifyOp? ← isModifyOp? stx;
match modifyOp?, sourceView with
| some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType?
| some _, _ => throwError ("invalid {...} notation, explicit source is required when using '[<index>] := <value>'")
| _, _ => elabStructInstAux stx expectedType? sourceView
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Elab.struct;
pure ()
end StructInst
end Term
end Elab
end Lean
|
ef9380cd7228c0e8c218bbe49a57eaa8e2a27828 | a5e2e6395319779f21675263bc0e486be5bc03bd | /bench/stlc_lessimpl.lean | 92a987128918756efb0ea11313d59d095b1cc056 | [
"MIT"
] | permissive | AndrasKovacs/smalltt | 10f0ec55fb3f487e9dd21a740fe1a899e0cdb790 | c306f727ba3c92abe6ef75013da5a5dade6b15c8 | refs/heads/master | 1,689,497,785,394 | 1,680,893,106,000 | 1,680,893,106,000 | 112,098,494 | 483 | 26 | MIT | 1,640,720,815,000 | 1,511,713,805,000 | Lean | UTF-8 | Lean | false | false | 6,912 | lean |
def Ty6 : Type 1
:= ∀ (Ty6 : Type)
(nat top bot : Ty6)
(arr prod sum : Ty6 → Ty6 → Ty6)
, Ty6
def nat6 : Ty6 := λ _ nat6 _ _ _ _ _ => nat6
def top6 : Ty6 := λ _ _ top6 _ _ _ _ => top6
def bot6 : Ty6 := λ _ _ _ bot6 _ _ _ => bot6
def arr6 : Ty6 → Ty6 → Ty6
:= λ A B Ty6 nat6 top6 bot6 arr6 prod sum =>
arr6 (A Ty6 nat6 top6 bot6 arr6 prod sum) (B Ty6 nat6 top6 bot6 arr6 prod sum)
def prod6 : Ty6 → Ty6 → Ty6
:= λ A B Ty6 nat6 top6 bot6 arr6 prod6 sum =>
prod6 (A Ty6 nat6 top6 bot6 arr6 prod6 sum) (B Ty6 nat6 top6 bot6 arr6 prod6 sum)
def sum6 : Ty6 → Ty6 → Ty6
:= λ A B Ty6 nat6 top6 bot6 arr6 prod6 sum6 =>
sum6 (A Ty6 nat6 top6 bot6 arr6 prod6 sum6) (B Ty6 nat6 top6 bot6 arr6 prod6 sum6)
def Con6 : Type 1
:= ∀ (Con6 : Type)
(nil : Con6)
(snoc : Con6 → Ty6 → Con6)
, Con6
def nil6 : Con6
:= λ Con6 nil6 snoc => nil6
def snoc6 : Con6 → Ty6 → Con6
:= λ Γ A Con6 nil6 snoc6 => snoc6 (Γ Con6 nil6 snoc6) A
def Var6 : Con6 → Ty6 → Type 1
:= λ Γ A =>
∀ (Var6 : Con6 → Ty6 → Type)
(vz : ∀ Γ A, Var6 (snoc6 Γ A) A)
(vs : ∀ Γ B A, Var6 Γ A → Var6 (snoc6 Γ B) A)
, Var6 Γ A
def vz6 : ∀ {Γ A}, Var6 (snoc6 Γ A) A
:= λ Var6 vz6 vs => vz6 _ _
def vs6 : ∀ {Γ B A}, Var6 Γ A → Var6 (snoc6 Γ B) A
:= λ x Var6 vz6 vs6 => vs6 _ _ _ (x Var6 vz6 vs6)
def Tm6 : Con6 → Ty6 → Type 1
:= λ Γ A =>
∀ (Tm6 : Con6 → Ty6 → Type)
(var : ∀ Γ A , Var6 Γ A → Tm6 Γ A)
(lam : ∀ Γ A B , Tm6 (snoc6 Γ A) B → Tm6 Γ (arr6 A B))
(app : ∀ Γ A B , Tm6 Γ (arr6 A B) → Tm6 Γ A → Tm6 Γ B)
(tt : ∀ Γ , Tm6 Γ top6)
(pair : ∀ Γ A B , Tm6 Γ A → Tm6 Γ B → Tm6 Γ (prod6 A B))
(fst : ∀ Γ A B , Tm6 Γ (prod6 A B) → Tm6 Γ A)
(snd : ∀ Γ A B , Tm6 Γ (prod6 A B) → Tm6 Γ B)
(left : ∀ Γ A B , Tm6 Γ A → Tm6 Γ (sum6 A B))
(right : ∀ Γ A B , Tm6 Γ B → Tm6 Γ (sum6 A B))
(case : ∀ Γ A B C , Tm6 Γ (sum6 A B) → Tm6 Γ (arr6 A C) → Tm6 Γ (arr6 B C) → Tm6 Γ C)
(zero : ∀ Γ , Tm6 Γ nat6)
(suc : ∀ Γ , Tm6 Γ nat6 → Tm6 Γ nat6)
(rec : ∀ Γ A , Tm6 Γ nat6 → Tm6 Γ (arr6 nat6 (arr6 A A)) → Tm6 Γ A → Tm6 Γ A)
, Tm6 Γ A
def var6 : ∀ {Γ A}, Var6 Γ A → Tm6 Γ A
:= λ x Tm6 var6 lam app tt pair fst snd left right case zero suc rec =>
var6 _ _ x
def lam6 : ∀ {Γ A B} , Tm6 (snoc6 Γ A) B → Tm6 Γ (arr6 A B)
:= λ t Tm6 var6 lam6 app tt pair fst snd left right case zero suc rec =>
lam6 _ _ _ (t Tm6 var6 lam6 app tt pair fst snd left right case zero suc rec)
def app6 : ∀ {Γ A B} , Tm6 Γ (arr6 A B) → Tm6 Γ A → Tm6 Γ B
:= λ t u Tm6 var6 lam6 app6 tt pair fst snd left right case zero suc rec =>
app6 _ _ _
(t Tm6 var6 lam6 app6 tt pair fst snd left right case zero suc rec)
(u Tm6 var6 lam6 app6 tt pair fst snd left right case zero suc rec)
def tt6 : ∀ {Γ} , Tm6 Γ top6
:= λ Tm6 var6 lam6 app6 tt6 pair fst snd left right case zero suc rec => tt6 _
def pair6 : ∀ {Γ A B} , Tm6 Γ A → Tm6 Γ B → Tm6 Γ (prod6 A B)
:= λ t u Tm6 var6 lam6 app6 tt6 pair6 fst snd left right case zero suc rec =>
pair6 _ _ _
(t Tm6 var6 lam6 app6 tt6 pair6 fst snd left right case zero suc rec)
(u Tm6 var6 lam6 app6 tt6 pair6 fst snd left right case zero suc rec)
def fst6 : ∀ {Γ A B} , Tm6 Γ (prod6 A B) → Tm6 Γ A
:= λ t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd left right case zero suc rec =>
fst6 _ _ _
(t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd left right case zero suc rec)
def snd6 : ∀ {Γ A B} , Tm6 Γ (prod6 A B) → Tm6 Γ B
:= λ t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left right case zero suc rec =>
snd6 _ _ _
(t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left right case zero suc rec)
def left6 : ∀ {Γ A B} , Tm6 Γ A → Tm6 Γ (sum6 A B)
:= λ t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right case zero suc rec =>
left6 _ _ _
(t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right case zero suc rec)
def right6 : ∀ {Γ A B} , Tm6 Γ B → Tm6 Γ (sum6 A B)
:= λ t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case zero suc rec =>
right6 _ _ _
(t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case zero suc rec)
def case6 : ∀ {Γ A B C} , Tm6 Γ (sum6 A B) → Tm6 Γ (arr6 A C) → Tm6 Γ (arr6 B C) → Tm6 Γ C
:= λ t u v Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero suc rec =>
case6 _ _ _ _
(t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero suc rec)
(u Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero suc rec)
(v Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero suc rec)
def zero6 : ∀ {Γ} , Tm6 Γ nat6
:= λ Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero6 suc rec => zero6 _
def suc6 : ∀ {Γ} , Tm6 Γ nat6 → Tm6 Γ nat6
:= λ t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero6 suc6 rec =>
suc6 _ (t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero6 suc6 rec)
def rec6 : ∀ {Γ A} , Tm6 Γ nat6 → Tm6 Γ (arr6 nat6 (arr6 A A)) → Tm6 Γ A → Tm6 Γ A
:= λ t u v Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero6 suc6 rec6 =>
rec6 _ _
(t Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero6 suc6 rec6)
(u Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero6 suc6 rec6)
(v Tm6 var6 lam6 app6 tt6 pair6 fst6 snd6 left6 right6 case6 zero6 suc6 rec6)
def v06 : ∀ {Γ A}, Tm6 (snoc6 Γ A) A
:= var6 vz6
def v16 : ∀ {Γ A B}, Tm6 (snoc6 (snoc6 Γ A) B) A
:= var6 (vs6 vz6)
def v26 : ∀ {Γ A B C}, Tm6 (snoc6 (snoc6 (snoc6 Γ A) B) C) A
:= var6 (vs6 (vs6 vz6))
def v36 : ∀ {Γ A B C D}, Tm6 (snoc6 (snoc6 (snoc6 (snoc6 Γ A) B) C) D) A
:= var6 (vs6 (vs6 (vs6 vz6)))
def tbool6 : Ty6
:= sum6 top6 top6
def ttrue6 : ∀ {Γ}, Tm6 Γ tbool6
:= left6 tt6
def tfalse6 : ∀ {Γ}, Tm6 Γ tbool6
:= right6 tt6
def ifthenelse6 : ∀ {Γ A}, Tm6 Γ (arr6 tbool6 (arr6 A (arr6 A A)))
:= lam6 (lam6 (lam6 (case6 v26 (lam6 v26) (lam6 v16))))
def times46 : ∀ {Γ A}, Tm6 Γ (arr6 (arr6 A A) (arr6 A A))
:= lam6 (lam6 (app6 v16 (app6 v16 (app6 v16 (app6 v16 v06)))))
def add6 : ∀ {Γ}, Tm6 Γ (arr6 nat6 (arr6 nat6 nat6))
:= lam6 (rec6 v06
(lam6 (lam6 (lam6 (suc6 (app6 v16 v06)))))
(lam6 v06))
def mul6 : ∀ {Γ}, Tm6 Γ (arr6 nat6 (arr6 nat6 nat6))
:= lam6 (rec6 v06
(lam6 (lam6 (lam6 (app6 (app6 add6 (app6 v16 v06)) v06))))
(lam6 zero6))
def fact6 : ∀ {Γ}, Tm6 Γ (arr6 nat6 nat6)
:= lam6 (rec6 v06 (lam6 (lam6 (app6 (app6 mul6 (suc6 v16)) v06)))
(suc6 zero6)) |
12cc177e4389fe9ce22ae1ac1e0a126c59ebf09b | de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41 | /old/eval/measurementEval.lean | fb71d95015e3ed6813f46e7ccfc2c8bbc5eac1e4 | [] | no_license | kevinsullivan/lang | d3e526ba363dc1ddf5ff1c2f36607d7f891806a7 | e9d869bff94fb13ad9262222a6f3c4aafba82d5e | refs/heads/master | 1,687,840,064,795 | 1,628,047,969,000 | 1,628,047,969,000 | 282,210,749 | 0 | 1 | null | 1,608,153,830,000 | 1,595,592,637,000 | Lean | UTF-8 | Lean | false | false | 302 | lean | import ..imperative_DSL.environment
open lang.measurementSystem
def measurementSystemEval : lang.measurementSystem.measureExpr → environment.env → measurementSystem.MeasurementSystem
| (lang.measurementSystem.measureExpr.lit V) i := V
| (lang.measurementSystem.measureExpr.var v) i := i.ms.ms v
|
98c5f2bf6b2ad202bccd3ebdee68a319967e1e4c | 94e33a31faa76775069b071adea97e86e218a8ee | /test/congrm.lean | f4485e5d9a70e97a4901f17adb5198923570aff8 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 1,598 | lean | import tactic.congrm
variables {X : Type*} [has_add X] [has_mul X] (a b c d : X) (f : X → X)
example (H : a = b) : f a + f a = f b + f b :=
by congrm f _ + f _; exact H
example {g : X → X} (H : a = b) (H' : c + f a = c + f d) (H'' : f d = f b) :
f (g a) * (f d + (c + f a)) = f (g b) * (f b + (c + f d)) :=
begin
congrm f (g _) * (_ + _),
{ exact H },
{ exact H'' },
{ exact H' },
end
example (H' : c + (f a) = c + (f d)) (H'' : f d = f b) :
f (f a) * (f d + (c + f a)) = f (f a) * (f b + (c + f d)) :=
begin
congrm f (f _) * (_ + _),
{ exact H'' },
{ exact H' },
end
example (H' : c + (f a) = c + (f d)) (H'' : f d = f b) :
f (f a) * (f d + (c + f a)) = f (f a) * (f b + (c + f d)) :=
begin
congrm f (f _) * (_ + _),
{ exact H'' },
{ exact H' },
end
example {p q} [decidable p] [decidable q] (h : p ↔ q) :
ite p 0 1 = ite q 0 1 :=
begin
congrm ite _ 0 1,
exact h,
end
example {p q} [decidable p] [decidable q] (h : p ↔ q) :
ite p 0 1 = ite q 0 1 :=
begin
congrm ite _ 0 1,
exact h,
end
example {a b : ℕ} (h : a = b) : (λ y : ℕ, ∀ z, a + a = z) = (λ x, ∀ z, b + a = z) :=
begin
congrm λ x, ∀ w, _ + a = w,
exact h,
end
example (h : 5 = 3) : (⟨5 + 1, dec_trivial⟩ : fin 10) = ⟨3 + 1, dec_trivial⟩ :=
begin
congrm ⟨_ + 1, _⟩,
exact h,
end
example : true ∧ false ↔ (true ∧ true) ∧ false :=
begin
congrm _ ∧ _,
exact (true_and true).symm,
end
example {f g : ℕ → ℕ → ℕ} (h : f = g) : (λ i j, f i j) = (λ i j, g i j) :=
begin
congrm λ i j, _,
guard_target f i j = g i j,
rw h,
end
|
380d362458c0f39cf86b8759d099c6c5a3157e0a | 92b50235facfbc08dfe7f334827d47281471333b | /library/algebra/ring.lean | e0fa6fe628a957f06f995f91a1eaaec6246e9f2d | [
"Apache-2.0"
] | permissive | htzh/lean | 24f6ed7510ab637379ec31af406d12584d31792c | d70c79f4e30aafecdfc4a60b5d3512199200ab6e | refs/heads/master | 1,607,677,731,270 | 1,437,089,952,000 | 1,437,089,952,000 | 37,078,816 | 0 | 0 | null | 1,433,780,956,000 | 1,433,780,955,000 | null | UTF-8 | Lean | false | false | 13,391 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
Structures with multiplicative and additive components, including semirings, rings, and fields.
The development is modeled after Isabelle's library.
-/
import logic.eq logic.connectives data.unit data.sigma data.prod
import algebra.binary algebra.group
open eq eq.ops
namespace algebra
variable {A : Type}
/- auxiliary classes -/
structure distrib [class] (A : Type) extends has_mul A, has_add A :=
(left_distrib : ∀a b c, mul a (add b c) = add (mul a b) (mul a c))
(right_distrib : ∀a b c, mul (add a b) c = add (mul a c) (mul b c))
theorem left_distrib [s : distrib A] (a b c : A) : a * (b + c) = a * b + a * c :=
!distrib.left_distrib
theorem right_distrib [s: distrib A] (a b c : A) : (a + b) * c = a * c + b * c :=
!distrib.right_distrib
structure mul_zero_class [class] (A : Type) extends has_mul A, has_zero A :=
(zero_mul : ∀a, mul zero a = zero)
(mul_zero : ∀a, mul a zero = zero)
theorem zero_mul [s : mul_zero_class A] (a : A) : 0 * a = 0 := !mul_zero_class.zero_mul
theorem mul_zero [s : mul_zero_class A] (a : A) : a * 0 = 0 := !mul_zero_class.mul_zero
structure zero_ne_one_class [class] (A : Type) extends has_zero A, has_one A :=
(zero_ne_one : zero ≠ one)
theorem zero_ne_one [s: zero_ne_one_class A] : 0 ≠ (1:A) := @zero_ne_one_class.zero_ne_one A s
/- semiring -/
structure semiring [class] (A : Type) extends add_comm_monoid A, monoid A, distrib A,
mul_zero_class A
section semiring
variables [s : semiring A] (a b c : A)
include s
theorem ne_zero_of_mul_ne_zero_right {a b : A} (H : a * b ≠ 0) : a ≠ 0 :=
assume H1 : a = 0,
have H2 : a * b = 0, from H1⁻¹ ▸ zero_mul b,
H H2
theorem ne_zero_of_mul_ne_zero_left {a b : A} (H : a * b ≠ 0) : b ≠ 0 :=
assume H1 : b = 0,
have H2 : a * b = 0, from H1⁻¹ ▸ mul_zero a,
H H2
theorem distrib_three_right (a b c d : A) : (a + b + c) * d = a * d + b * d + c * d :=
by rewrite *right_distrib
end semiring
/- comm semiring -/
structure comm_semiring [class] (A : Type) extends semiring A, comm_monoid A
-- TODO: we could also define a cancelative comm_semiring, i.e. satisfying
-- c ≠ 0 → c * a = c * b → a = b.
section comm_semiring
variables [s : comm_semiring A] (a b c : A)
include s
definition dvd (a b : A) : Prop := ∃c, b = a * c
notation [priority algebra.prio] a ∣ b := dvd a b
theorem dvd.intro {a b c : A} (H : a * c = b) : a ∣ b :=
exists.intro _ H⁻¹
theorem dvd.intro_left {a b c : A} (H : c * a = b) : a ∣ b :=
dvd.intro (!mul.comm ▸ H)
theorem exists_eq_mul_right_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = a * c := H
theorem dvd.elim {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = a * c → P) : P :=
exists.elim H₁ H₂
theorem exists_eq_mul_left_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = c * a :=
dvd.elim H (take c, assume H1 : b = a * c, exists.intro c (H1 ⬝ !mul.comm))
theorem dvd.elim_left {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = c * a → P) : P :=
exists.elim (exists_eq_mul_left_of_dvd H₁) (take c, assume H₃ : b = c * a, H₂ c H₃)
theorem dvd.refl : a ∣ a := dvd.intro !mul_one
theorem dvd.trans {a b c : A} (H₁ : a ∣ b) (H₂ : b ∣ c) : a ∣ c :=
dvd.elim H₁
(take d, assume H₃ : b = a * d,
dvd.elim H₂
(take e, assume H₄ : c = b * e,
dvd.intro
(show a * (d * e) = c, by rewrite [-mul.assoc, -H₃, H₄])))
theorem eq_zero_of_zero_dvd {a : A} (H : 0 ∣ a) : a = 0 :=
dvd.elim H (take c, assume H' : a = 0 * c, H' ⬝ !zero_mul)
theorem dvd_zero : a ∣ 0 := dvd.intro !mul_zero
theorem one_dvd : 1 ∣ a := dvd.intro !one_mul
theorem dvd_mul_right : a ∣ a * b := dvd.intro rfl
theorem dvd_mul_left : a ∣ b * a := mul.comm a b ▸ dvd_mul_right a b
theorem dvd_mul_of_dvd_left {a b : A} (H : a ∣ b) (c : A) : a ∣ b * c :=
dvd.elim H
(take d,
assume H₁ : b = a * d,
dvd.intro
(show a * (d * c) = b * c, from by rewrite [-mul.assoc, H₁]))
theorem dvd_mul_of_dvd_right {a b : A} (H : a ∣ b) (c : A) : a ∣ c * b :=
!mul.comm ▸ (dvd_mul_of_dvd_left H _)
theorem mul_dvd_mul {a b c d : A} (dvd_ab : a ∣ b) (dvd_cd : c ∣ d) : a * c ∣ b * d :=
dvd.elim dvd_ab
(take e, assume Haeb : b = a * e,
dvd.elim dvd_cd
(take f, assume Hcfd : d = c * f,
dvd.intro
(show a * c * (e * f) = b * d,
by rewrite [mul.assoc, {c*_}mul.left_comm, -mul.assoc, Haeb, Hcfd])))
theorem dvd_of_mul_right_dvd {a b c : A} (H : a * b ∣ c) : a ∣ c :=
dvd.elim H (take d, assume Habdc : c = a * b * d, dvd.intro (!mul.assoc⁻¹ ⬝ Habdc⁻¹))
theorem dvd_of_mul_left_dvd {a b c : A} (H : a * b ∣ c) : b ∣ c :=
dvd_of_mul_right_dvd (mul.comm a b ▸ H)
theorem dvd_add {a b c : A} (Hab : a ∣ b) (Hac : a ∣ c) : a ∣ b + c :=
dvd.elim Hab
(take d, assume Hadb : b = a * d,
dvd.elim Hac
(take e, assume Haec : c = a * e,
dvd.intro (show a * (d + e) = b + c,
by rewrite [left_distrib, -Hadb, -Haec])))
end comm_semiring
/- ring -/
structure ring [class] (A : Type) extends add_comm_group A, monoid A, distrib A
theorem ring.mul_zero [s : ring A] (a : A) : a * 0 = 0 :=
have H : a * 0 + 0 = a * 0 + a * 0, from calc
a * 0 + 0 = a * 0 : by rewrite add_zero
... = a * (0 + 0) : by rewrite add_zero
... = a * 0 + a * 0 : by rewrite {a*_}ring.left_distrib,
show a * 0 = 0, from (add.left_cancel H)⁻¹
theorem ring.zero_mul [s : ring A] (a : A) : 0 * a = 0 :=
have H : 0 * a + 0 = 0 * a + 0 * a, from calc
0 * a + 0 = 0 * a : by rewrite add_zero
... = (0 + 0) * a : by rewrite add_zero
... = 0 * a + 0 * a : by rewrite {_*a}ring.right_distrib,
show 0 * a = 0, from (add.left_cancel H)⁻¹
definition ring.to_semiring [trans-instance] [coercion] [reducible] [s : ring A] : semiring A :=
⦃ semiring, s,
mul_zero := ring.mul_zero,
zero_mul := ring.zero_mul ⦄
section
variables [s : ring A] (a b c d e : A)
include s
theorem neg_mul_eq_neg_mul : -(a * b) = -a * b :=
neg_eq_of_add_eq_zero
begin
rewrite [-right_distrib, add.right_inv, zero_mul]
end
theorem neg_mul_eq_mul_neg : -(a * b) = a * -b :=
neg_eq_of_add_eq_zero
begin
rewrite [-left_distrib, add.right_inv, mul_zero]
end
theorem neg_mul_neg : -a * -b = a * b :=
calc
-a * -b = -(a * -b) : by rewrite -neg_mul_eq_neg_mul
... = - -(a * b) : by rewrite -neg_mul_eq_mul_neg
... = a * b : by rewrite neg_neg
theorem neg_mul_comm : -a * b = a * -b := !neg_mul_eq_neg_mul⁻¹ ⬝ !neg_mul_eq_mul_neg
theorem neg_eq_neg_one_mul : -a = -1 * a :=
calc
-a = -(1 * a) : by rewrite one_mul
... = -1 * a : by rewrite neg_mul_eq_neg_mul
theorem mul_sub_left_distrib : a * (b - c) = a * b - a * c :=
calc
a * (b - c) = a * b + a * -c : left_distrib
... = a * b + - (a * c) : by rewrite -neg_mul_eq_mul_neg
... = a * b - a * c : rfl
theorem mul_sub_right_distrib : (a - b) * c = a * c - b * c :=
calc
(a - b) * c = a * c + -b * c : right_distrib
... = a * c + - (b * c) : by rewrite neg_mul_eq_neg_mul
... = a * c - b * c : rfl
-- TODO: can calc mode be improved to make this easier?
-- TODO: there is also the other direction. It will be easier when we
-- have the simplifier.
theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d :=
calc
a * e + c = b * e + d ↔ a * e + c = d + b * e : by rewrite {b*e+_}add.comm
... ↔ a * e + c - b * e = d : iff.symm !sub_eq_iff_eq_add
... ↔ a * e - b * e + c = d : by rewrite sub_add_eq_add_sub
... ↔ (a - b) * e + c = d : by rewrite mul_sub_right_distrib
theorem mul_neg_one_eq_neg : a * (-1) = -a :=
have H : a + a * -1 = 0, from calc
a + a * -1 = a * 1 + a * -1 : mul_one
... = a * (1 + -1) : left_distrib
... = a * 0 : add.right_inv
... = 0 : mul_zero,
symm (neg_eq_of_add_eq_zero H)
theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : A} (H : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
have Ha : a ≠ 0, from
(assume Ha1 : a = 0,
have H1 : a * b = 0, by rewrite [Ha1, zero_mul],
absurd H1 H),
have Hb : b ≠ 0, from
(assume Hb1 : b = 0,
have H1 : a * b = 0, by rewrite [Hb1, mul_zero],
absurd H1 H),
and.intro Ha Hb
end
structure comm_ring [class] (A : Type) extends ring A, comm_semigroup A
definition comm_ring.to_comm_semiring [trans-instance] [coercion] [reducible] [s : comm_ring A] : comm_semiring A :=
⦃ comm_semiring, s,
mul_zero := mul_zero,
zero_mul := zero_mul ⦄
section
variables [s : comm_ring A] (a b c d e : A)
include s
theorem mul_self_sub_mul_self_eq : a * a - b * b = (a + b) * (a - b) :=
begin
krewrite [left_distrib, *right_distrib, add.assoc],
rewrite [-{b*a + _}add.assoc,
-*neg_mul_eq_mul_neg, {a*b}mul.comm, add.right_inv, zero_add]
end
theorem mul_self_sub_one_eq : a * a - 1 = (a + 1) * (a - 1) :=
by rewrite [-mul_self_sub_mul_self_eq, mul_one]
theorem dvd_neg_iff_dvd : (a ∣ -b) ↔ (a ∣ b) :=
iff.intro
(assume H : (a ∣ -b),
dvd.elim H
(take c, assume H' : -b = a * c,
dvd.intro
(show a * -c = b,
by rewrite [-neg_mul_eq_mul_neg, -H', neg_neg])))
(assume H : (a ∣ b),
dvd.elim H
(take c, assume H' : b = a * c,
dvd.intro
(show a * -c = -b,
by rewrite [-neg_mul_eq_mul_neg, -H'])))
theorem neg_dvd_iff_dvd : (-a ∣ b) ↔ (a ∣ b) :=
iff.intro
(assume H : (-a ∣ b),
dvd.elim H
(take c, assume H' : b = -a * c,
dvd.intro
(show a * -c = b, by rewrite [-neg_mul_comm, H'])))
(assume H : (a ∣ b),
dvd.elim H
(take c, assume H' : b = a * c,
dvd.intro
(show -a * -c = b, by rewrite [neg_mul_neg, H'])))
theorem dvd_sub (H₁ : (a ∣ b)) (H₂ : (a ∣ c)) : (a ∣ b - c) :=
dvd_add H₁ (iff.elim_right !dvd_neg_iff_dvd H₂)
end
/- integral domains -/
structure no_zero_divisors [class] (A : Type) extends has_mul A, has_zero A :=
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀a b, mul a b = zero → a = zero ∨ b = zero)
theorem eq_zero_or_eq_zero_of_mul_eq_zero {A : Type} [s : no_zero_divisors A] {a b : A}
(H : a * b = 0) :
a = 0 ∨ b = 0 := !no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero H
structure integral_domain [class] (A : Type) extends comm_ring A, no_zero_divisors A
section
variables [s : integral_domain A] (a b c d e : A)
include s
theorem mul_ne_zero {a b : A} (H1 : a ≠ 0) (H2 : b ≠ 0) : a * b ≠ 0 :=
assume H : a * b = 0,
or.elim (eq_zero_or_eq_zero_of_mul_eq_zero H) (assume H3, H1 H3) (assume H4, H2 H4)
theorem eq_of_mul_eq_mul_right {a b c : A} (Ha : a ≠ 0) (H : b * a = c * a) : b = c :=
have H1 : b * a - c * a = 0, from iff.mp !eq_iff_sub_eq_zero H,
have H2 : (b - c) * a = 0, using H1, by rewrite [mul_sub_right_distrib, H1],
have H3 : b - c = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H2) Ha,
iff.elim_right !eq_iff_sub_eq_zero H3
theorem eq_of_mul_eq_mul_left {a b c : A} (Ha : a ≠ 0) (H : a * b = a * c) : b = c :=
have H1 : a * b - a * c = 0, from iff.mp !eq_iff_sub_eq_zero H,
have H2 : a * (b - c) = 0, using H1, by rewrite [mul_sub_left_distrib, H1],
have H3 : b - c = 0, from or_resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero H2) Ha,
iff.elim_right !eq_iff_sub_eq_zero H3
-- TODO: do we want the iff versions?
theorem mul_self_eq_mul_self_iff (a b : A) : a * a = b * b ↔ a = b ∨ a = -b :=
iff.intro
(λ H : a * a = b * b,
have aux₁ : (a - b) * (a + b) = 0,
by rewrite [mul.comm, -mul_self_sub_mul_self_eq, H, sub_self],
assert aux₂ : a - b = 0 ∨ a + b = 0, from !eq_zero_or_eq_zero_of_mul_eq_zero aux₁,
or.elim aux₂
(λ H : a - b = 0, or.inl (eq_of_sub_eq_zero H))
(λ H : a + b = 0, or.inr (eq_neg_of_add_eq_zero H)))
(λ H : a = b ∨ a = -b, or.elim H
(λ a_eq_b, by rewrite a_eq_b)
(λ a_eq_mb, by rewrite [a_eq_mb, neg_mul_neg]))
theorem mul_self_eq_one_iff (a : A) : a * a = 1 ↔ a = 1 ∨ a = -1 :=
assert aux : a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1,
by rewrite mul_one at aux; exact aux
-- TODO: c - b * c → c = 0 ∨ b = 1 and variants
theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) :=
dvd.elim Hdvd
(take d,
assume H : a * c = a * b * d,
have H1 : b * d = c, from eq_of_mul_eq_mul_left Ha (mul.assoc a b d ▸ H⁻¹),
dvd.intro H1)
theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) :=
dvd.elim Hdvd
(take d,
assume H : c * a = b * a * d,
have H1 : b * d * a = c * a, from by rewrite [mul.right_comm, -H],
have H2 : b * d = c, from eq_of_mul_eq_mul_right Ha H1,
dvd.intro H2)
end
end algebra
|
47a63ed550c9e0b4a1d6b28bebb2f1444fc22879 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/reserve.lean | 4ec99809f9fc3bb193b855273e78b3039965ca92 | [
"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 | 191 | lean | import logic
reserve infix `=?=`:50
reserve infixr `&&&`:25
notation a `=?=` b := eq a b
notation a `&&&` b := and a b
set_option pp.notation false
check λ a b : num, a =?= b &&& b =?= a
|
271d10f18c762188c1be050910e414359bdf9802 | fe208a542cea7b2d6d7ff79f94d535f6d11d814a | /src/Dedekind_cuts/challenge.lean | 381efdd05acfaa9e40c03348a1377fd6214eaad6 | [] | no_license | ImperialCollegeLondon/M1F_room_342_questions | c4b98b14113fe900a7f388762269305faff73e63 | 63de9a6ab9c27a433039dd5530bc9b10b1d227f7 | refs/heads/master | 1,585,807,312,561 | 1,545,232,972,000 | 1,545,232,972,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 471 | lean | import algebra.archimedean
import data.real.basic
definition completeness_axiom (k : Type*) [preorder k] : Prop :=
∀ (S : set k), (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) →
∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y
open function
theorem characterisation_of_reals (k : Type*) [discrete_linear_ordered_field k] [archimedean k] :
completeness_axiom k → ∃ f : k → ℝ, is_ring_hom f ∧ bijective f ∧ ∀ x y : k, x < y → f x < f y := sorry
|
1bec275832d5cc4332eb903466f55b43203b3993 | cbb1957fc3e28e502582c54cbce826d666350eda | /fabstract/Hales_T_et_al_Kepler_conj/fabstract.lean | 434478b007052470e2a7230a3ae77346b9fabc07 | [
"CC-BY-4.0"
] | permissive | andrejbauer/formalabstracts | 9040b172da080406448ad1b0260d550122dcad74 | a3b84fd90901ccf4b63eb9f95d4286a8775864d0 | refs/heads/master | 1,609,476,417,918 | 1,501,541,742,000 | 1,501,541,760,000 | 97,241,872 | 1 | 0 | null | 1,500,042,191,000 | 1,500,042,191,000 | null | UTF-8 | Lean | false | false | 3,283 | lean | import meta_data
...folklore.real_axiom
namespace Hales_T_et_al_Kepler_conj
noncomputable theory
open classical nat set list vector real_axiom
-- cardinality of finite sets.
-- Surely this must exist somewhere. But where?
universe u
def set_of_list {α : Type u} : (list α) → set α
| [] y := false
| (x :: rest) y := (x = y) ∨ set_of_list rest y
def finite {α : Type u} (P : set α) :=
(∃ l, P = set_of_list l)
unfinished least : set ℕ → ℕ :=
{ description := "every subset of natural numbers has a least element" }
unfinished least_empty : least ∅ = 0 :=
{ description := "the least element of the empty set is 0 by convention" }
unfinished least_nonempty :
∀ (P : set ℕ),
P ≠ ∅ → (least P ∈ P ∧ ∀ m, m ∈ P → least P ≤ m) :=
{ description := "the defining property of the least element of a subset" }
-- defaults to zero if the set is not finite:
def card {α : Type u} (P : set α) : ℕ :=
least (λ n, ∃ xs, set_of_list xs = P ∧ list.length xs = n)
/-
Here are some Euclidean vector space definitions that
should eventually be part of a general library
-/
local infix `^` := real_pow
def euclid_metric {n : ℕ} (u : vector ℝ n) (v : vector ℝ n) : ℝ :=
let subsquare (x : ℝ) (y : ℝ) : ℝ := (x-y)^2,
d := to_list (map₂ subsquare u v) in real_sqrt (list.sum d)
def packing {n : ℕ} (V : set (vector ℝ n)) :=
(∀ u v, V u ∧ v ∈ V ∧ euclid_metric u v < 2 → (u = v))
-- Todo: check that open balls are used (not that it matters)
def open_ball {n : ℕ} (x0 : vector ℝ n) (r : ℝ) : (set (vector ℝ n)) :=
{ u | euclid_metric x0 u < r}
-- this is a temporary workaround (https://github.com/leanprover/lean/commit/16e7976b1a7e2ce9624ad2df363c007b70d70096)
def origin₃ : vector ℝ 3 := 0::0::0::nil--[0,0,0]
-- TODO: provide the theorem number from the paper
unfinished Kepler_conjecture :
(∀ (V : set (vector ℝ 3)), packing V →
(∃ (c : ℝ), ∀ (r : ℝ), (r ≥ 1) ->
(↑(card(V ∩ open_ball origin₃ r)) ≤ pi* r^3/real_sqrt(18) + c*r^2))) :=
{ description := "Proof of Kepler conjecture",
references := [cite.Item cite.Ibidem "Theorem X.Y"] }
def fabstract : meta_data := {
description := "This article announces the formal proof of the Kepler conjecture on dense sphere packings in a combination of the HOL Light and Isabelle/HOL proof assistants. It represents the primary result of the now completed Flyspeck project.",
authors := [
{name := "Thomas Hales"},
{name := "Mark Adams"},
{name := "Gertrud Bauer"},
{name := "Tat Dat Dang"},
{name := "John Harrison"},
{name := "Le Truong Hoang"},
{name := "Cezary Kaliszyk"},
{name := "Victor Magron"},
{name := "Sean McLaughlin"},
{name := "Tat Thang Nguyen"},
{name := "Quang Truong Nguyen"},
{name := "Tobias Nipkow"},
{name := "Steven Obua"},
{name := "Joseph Pleso"},
{name := "Jason Rute"},
{name := "Alexey Solovyev"},
{name := "Thi Hoai An Ta"},
{name := "Nam Trung Tran"},
{name := "Thi Diep Trieu"},
{name := "Josef Urban"},
{name := "Ky Vu"},
{name := "Roland Zumkelle"}
],
primary := cite.DOI "/10.1017/fmp.2017.1",
results := [result.Proof Kepler_conjecture]
}
end Hales_T_et_al_Kepler_conj
|
99ce9c65be9b364f7fbf980f52c485360123bdec | abd85493667895c57a7507870867b28124b3998f | /src/data/fintype/basic.lean | fa253e2e7ac74871df0a572dcc84c4e5edf3ab8b | [
"Apache-2.0"
] | permissive | pechersky/mathlib | d56eef16bddb0bfc8bc552b05b7270aff5944393 | f1df14c2214ee114c9738e733efd5de174deb95d | refs/heads/master | 1,666,714,392,571 | 1,591,747,567,000 | 1,591,747,567,000 | 270,557,274 | 0 | 0 | Apache-2.0 | 1,591,597,975,000 | 1,591,597,974,000 | null | UTF-8 | Lean | false | false | 42,127 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Finite types.
-/
import data.finset
import data.array.lemmas
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class fintype (α : Type*) :=
(elems [] : finset α)
(complete : ∀ x : α, x ∈ elems)
namespace finset
variable [fintype α]
/-- `univ` is the universal finite set of type `finset α` implied from
the assumption `fintype α`. -/
def univ : finset α := fintype.elems α
@[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) :=
fintype.complete x
@[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ
@[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) :=
by ext; simp
theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a
theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s :=
by simp [ext]
@[simp] lemma univ_inter [decidable_eq α] (s : finset α) :
univ ∩ s = s := ext' $ λ a, by simp
@[simp] lemma inter_univ [decidable_eq α] (s : finset α) :
s ∩ univ = s :=
by rw [inter_comm, univ_inter]
@[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))]
{δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f :=
by { ext i, simp [piecewise] }
lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) :
univ.map e.to_embedding = univ :=
begin
apply eq_univ_iff_forall.mpr,
intro b,
rw [mem_map],
use e.symm b,
simp,
end
end finset
open finset function
namespace fintype
instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] :
decidable_eq (Πa, β a) :=
assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a)
(by simp [function.funext_iff, fintype.complete])
instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] :
decidable (∀ a, p a) :=
decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp)
instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] :
decidable (∃ a, p a) :=
decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp)
instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] :
decidable_eq (α ≃ β) :=
λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext (congr_fun h), congr_arg _⟩
instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] :
decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance
instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] :
decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance
instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] :
decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance
instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) :
decidable (function.right_inverse f g) :=
show decidable (∀ x, g (f x) = x), by apply_instance
instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) :
decidable (function.left_inverse f g) :=
show decidable (∀ x, f (g x) = x), by apply_instance
/-- Construct a proof of `fintype α` from a universal multiset -/
def of_multiset [decidable_eq α] (s : multiset α)
(H : ∀ x : α, x ∈ s) : fintype α :=
⟨s.to_finset, by simpa using H⟩
/-- Construct a proof of `fintype α` from a universal list -/
def of_list [decidable_eq α] (l : list α)
(H : ∀ x : α, x ∈ l) : fintype α :=
⟨l.to_finset, by simpa using H⟩
theorem exists_univ_list (α) [fintype α] :
∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l :=
let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in
by have := and.intro univ.2 mem_univ_val;
exact ⟨_, by rwa ← e at this⟩
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α) [fintype α] : ℕ := (@univ α _).card
/-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/
def equiv_fin_of_forall_mem_list {α} [decidable_eq α]
{l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) :=
⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩,
λ i, l.nth_le i.1 i.2,
λ a, by simp,
λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _
(list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩
/-- There is (computably) a bijection between `α` and `fin n` where
`n = card α`. Since it is not unique, and depends on which permutation
of the universe list is used, the bijection is wrapped in `trunc` to
preserve computability. -/
def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) :=
by unfold card finset.card; exact
quot.rec_on_subsingleton (@univ α _).1
(λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd))
mem_univ_val univ.2
theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) :=
by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩
/-- Given a linearly ordered fintype `α` of cardinal `k`, the equiv `mono_equiv_of_fin α h`
is the increasing bijection between `fin k` and `α`. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid
casting issues in further uses of this function. -/
noncomputable def mono_equiv_of_fin (α) [fintype α] [decidable_linear_order α] {k : ℕ}
(h : fintype.card α = k) : fin k ≃ α :=
have A : bijective (mono_of_fin univ h) := begin
apply set.bijective_iff_bij_on_univ.2,
rw ← @coe_univ α _,
exact mono_of_fin_bij_on (univ : finset α) h
end,
equiv.of_bijective A
instance (α : Type*) : subsingleton (fintype α) :=
⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩
protected def subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} :=
⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1),
multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩,
λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩
theorem subtype_card {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) :
@card {x // p x} (fintype.subtype s H) = s.card :=
multiset.card_pmap _ _ _
theorem card_of_subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] :
card {x // p x} = s.card :=
by rw ← subtype_card s H; congr
/-- Construct a fintype from a finset with the same elements. -/
def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p :=
fintype.subtype s H
@[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) :
@fintype.card p (of_finset s H) = s.card :=
fintype.subtype_card s H
theorem card_of_finset' {p : set α} (s : finset α)
(H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card :=
by rw ← card_of_finset s H; congr
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β :=
⟨univ.map ⟨f, H.1⟩,
λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β :=
⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩
noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α :=
by letI := classical.dec; exact
if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα;
exact of_surjective (inv_fun f) (inv_fun_surjective H)
else ⟨∅, λ x, (hα ⟨x⟩).elim⟩
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective
theorem of_equiv_card [fintype α] (f : α ≃ β) :
@card β (of_equiv α f) = card α :=
multiset.card_map _ _
theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β :=
by rw ← of_equiv_card f; congr
theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) :=
⟨λ h, ⟨by classical;
calc α ≃ fin (card α) : trunc.out (equiv_fin α)
... ≃ fin (card β) : by rw h
... ≃ β : (trunc.out (equiv_fin β)).symm⟩,
λ ⟨f⟩, card_congr f⟩
def of_subsingleton (a : α) [subsingleton α] : fintype α :=
⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩
@[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] :
@univ _ (of_subsingleton a) = {a} := rfl
@[simp] theorem card_of_subsingleton (a : α) [subsingleton α] :
@fintype.card _ (of_subsingleton a) = 1 := rfl
end fintype
namespace set
/-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/
def to_finset (s : set α) [fintype s] : finset α :=
⟨(@finset.univ s _).1.map subtype.val,
multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩
@[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s :=
by simp [to_finset]
@[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s :=
mem_to_finset
@[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s :=
set.ext $ λ _, mem_to_finset
@[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t :=
⟨λ h, by rw [← s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩
end set
lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α :=
rfl
lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) :
(finset.univ \ s).card = fintype.card α - s.card :=
finset.card_sdiff (subset_univ s)
instance (n : ℕ) : fintype (fin n) :=
⟨⟨list.fin_range n, list.nodup_fin_range n⟩, list.mem_fin_range⟩
@[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n :=
list.length_fin_range n
@[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n :=
by rw [finset.card_univ, fintype.card_fin]
lemma fin.univ_succ (n : ℕ) :
(univ : finset (fin $ n+1)) = insert 0 (univ.image fin.succ) :=
begin
ext m,
simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop],
exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m
end
lemma fin.univ_cast_succ (n : ℕ) :
(univ : finset (fin $ n+1)) = insert (fin.last n) (univ.image fin.cast_succ) :=
begin
ext m,
simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and],
by_cases h : m.val < n,
{ right,
use fin.cast_lt m h,
rw fin.cast_succ_cast_lt },
{ left,
exact fin.eq_last_of_not_lt h }
end
/-- Any increasing map between `fin k` and a finset of cardinality `k` has to coincide with
the increasing bijection `mono_of_fin s h`. -/
lemma finset.mono_of_fin_unique' [decidable_linear_order α] {s : finset α} {k : ℕ} (h : s.card = k)
{f : fin k → α} (fmap : set.maps_to f set.univ ↑s) (hmono : strict_mono f) :
f = s.mono_of_fin h :=
begin
have finj : set.inj_on f set.univ := hmono.injective.inj_on _,
apply mono_of_fin_unique h (set.bij_on.mk fmap finj (λ y hy, _)) hmono,
simp only [set.image_univ, set.mem_range],
rcases surj_on_of_inj_on_of_card_le (λ i (hi : i ∈ finset.univ), f i)
(λ i hi, fmap (set.mem_univ i)) (λ i j hi hj hij, finj (set.mem_univ i) (set.mem_univ j) hij)
(by simp [h]) y hy with ⟨x, _, hx⟩,
exact ⟨x, hx.symm⟩
end
@[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α :=
fintype.of_subsingleton (default α)
@[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} :=
by rw [subsingleton.elim f (@unique.fintype α _)]; refl
instance : fintype empty := ⟨∅, empty.rec _⟩
@[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl
@[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl
instance : fintype pempty := ⟨∅, pempty.rec _⟩
@[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl
@[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl
instance : fintype unit := fintype.of_subsingleton ()
theorem fintype.univ_unit : @univ unit _ = {()} := rfl
theorem fintype.card_unit : fintype.card unit = 1 := rfl
instance : fintype punit := fintype.of_subsingleton punit.star
@[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl
@[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl
instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩
@[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl
instance units_int.fintype : fintype (units ℤ) :=
⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩
instance additive.fintype : Π [fintype α], fintype (additive α) := id
instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id
@[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl
noncomputable instance [monoid α] [fintype α] : fintype (units α) :=
by classical; exact fintype.of_injective units.val units.ext
@[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl
def finset.insert_none (s : finset α) : finset (option α) :=
⟨none :: s.1.map some, multiset.nodup_cons.2
⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩
@[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α},
o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s
| none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h)
| (some a) := multiset.mem_cons.trans $ by simp; refl
theorem finset.some_mem_insert_none {s : finset α} {a : α} :
some a ∈ s.insert_none ↔ a ∈ s := by simp
instance {α : Type*} [fintype α] : fintype (option α) :=
⟨univ.insert_none, λ a, by simp⟩
@[simp] theorem fintype.card_option {α : Type*} [fintype α] :
fintype.card (option α) = fintype.card α + 1 :=
(multiset.card_cons _ _).trans (by rw multiset.card_map; refl)
instance {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] : fintype (sigma β) :=
⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩
@[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] :
(univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl
instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) :=
⟨univ.product univ, λ ⟨a, b⟩, by simp⟩
@[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] :
fintype.card (α × β) = fintype.card α * fintype.card β :=
card_product _ _
def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α :=
⟨(fintype.elems (α × β)).image prod.fst,
assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩
def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β :=
⟨(fintype.elems (α × β)).image prod.snd,
assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩
instance (α : Type*) [fintype α] : fintype (ulift α) :=
fintype.of_equiv _ equiv.ulift.symm
@[simp] theorem fintype.card_ulift (α : Type*) [fintype α] :
fintype.card (ulift α) = fintype.card α :=
fintype.of_equiv_card _
instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) :=
@fintype.of_equiv _ _ (@sigma.fintype _
(λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _
(λ b, by cases b; apply ulift.fintype))
((equiv.sum_equiv_sigma_bool _ _).symm.trans
(equiv.sum_congr equiv.ulift equiv.ulift))
lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β)
(hf : function.injective f) : fintype.card α ≤ fintype.card β :=
by haveI := classical.prop_decidable; exact
finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h)
lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) :=
by rw [← fintype.card_unit, fintype.card_eq]; exact
⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩,
λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm,
λ _, subsingleton.elim _ _⟩⟩⟩
lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) :=
⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim,
λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩,
by simp [fintype.card_congr e]⟩
lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α :=
⟨λ h, classical.by_contradiction (λ h₁,
have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩),
lt_irrefl 0 $ by rwa this at h),
λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩
lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) :=
let n := fintype.card α in
have hn : n = fintype.card α := rfl,
match n, hn with
| 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩
| 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in
by rw [hx a, hx b],
λ _, ha ▸ le_refl _⟩
| (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial,
(λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ())
(λ _ _ _, h _ _))⟩
end
lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) :
∃ b : α, b ≠ a :=
let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in
let ⟨c, hc⟩ := classical.not_forall.1 hb in
by haveI := classical.dec_eq α; exact
if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩
lemma fintype.exists_pair_of_one_lt_card [fintype α] (h : 1 < fintype.card α) :
∃ (a b : α), b ≠ a :=
begin
rcases fintype.card_pos_iff.1 (nat.lt_of_succ_lt h) with a,
exact ⟨a, fintype.exists_ne_of_one_lt_card h a⟩,
end
lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f :=
by haveI := classical.prop_decidable; exact
have ∀ {f : α → α}, injective f → surjective f,
from λ f hinj x,
have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _)
((card_image_of_injective univ hinj).symm ▸ le_refl _),
have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _,
exists_of_bex (mem_image.1 h₂),
⟨this,
λ hsurj, has_left_inverse.injective
⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse
(this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩
lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f :=
by simp [bijective, fintype.injective_iff_surjective]
lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f :=
by simp [bijective, fintype.injective_iff_surjective]
lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) :
injective f ↔ surjective f :=
have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective,
⟨λ hinj, by simpa [function.comp] using
e.surjective.comp (this.1 (e.symm.injective.comp hinj)),
λ hsurj, by simpa [function.comp] using
e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩
lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} :
↑(finset.image f finset.univ) = set.range f :=
by { ext x, simp }
instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} :=
fintype.of_list l.attach l.mem_attach
instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} :=
fintype.of_multiset s.attach s.mem_attach
instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} :=
⟨s.attach, s.mem_attach⟩
instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) :=
finset.subtype.fintype s
@[simp] lemma fintype.card_coe (s : finset α) :
fintype.card (↑s : set α) = s.card := card_attach
lemma finset.card_le_one_iff {s : finset α} :
s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y :=
begin
let t : set α := ↑s,
letI : fintype t := finset_coe.fintype s,
have : fintype.card t = s.card := fintype.card_coe s,
rw [← this, fintype.card_le_one_iff],
split,
{ assume H x y hx hy,
exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) },
{ assume H x y,
exact subtype.eq (H x.2 y.2) }
end
lemma finset.one_lt_card_iff {s : finset α} :
1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y :=
begin
classical,
rw ← not_iff_not,
push_neg,
simpa [classical.or_iff_not_imp_left] using finset.card_le_one_iff
end
instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) :=
⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩
instance Prop.fintype : fintype Prop :=
⟨⟨true::false::0, by simp [true_ne_false]⟩,
classical.cases (by simp) (by simp)⟩
def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s :=
fintype.subtype (univ.filter (∈ s)) (by simp)
namespace function.embedding
/-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/
noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α :=
equiv.of_bijective (fintype.injective_iff_bijective.1 e.2)
@[simp]
lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) :
e.equiv_of_fintype_self_embedding.to_embedding = e :=
by { ext, refl, }
end function.embedding
@[simp]
lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) :
univ.map e = univ :=
by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding]
namespace fintype
variables [fintype α] [decidable_eq α] {δ : α → Type*}
/-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the
analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as
there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/
def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) :=
(finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩
@[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} :
f ∈ pi_finset t ↔ (∀a, f a ∈ t a) :=
begin
split,
{ simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ,
exists_imp_distrib, mem_pi],
assume g hg hgf a,
rw ← hgf,
exact hg a },
{ simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi],
assume hf,
exact ⟨λ a ha, f a, hf, rfl⟩ }
end
lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) :
pi_finset t₁ ⊆ pi_finset t₂ :=
λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a
lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)]
(t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) :
disjoint (pi_finset t₁) (pi_finset t₂) :=
disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂,
disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a)
end fintype
/-! ### pi -/
/-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/
instance pi.fintype {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) :=
⟨fintype.pi_finset (λ _, univ), by simp⟩
@[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀a, fintype (β a)] :
fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) :=
rfl
instance d_array.fintype {n : ℕ} {α : fin n → Type*}
[∀n, fintype (α n)] : fintype (d_array n α) :=
fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm
instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) :=
d_array.fintype
instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) :=
fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm
instance quotient.fintype [fintype α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) :=
fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
instance finset.fintype [fintype α] : fintype (finset α) :=
⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩
@[simp] lemma fintype.card_finset [fintype α] :
fintype.card (finset α) = 2 ^ (fintype.card α) :=
finset.card_powerset finset.univ
instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} :=
set_fintype _
@[simp] lemma set.to_finset_univ [fintype α] :
(set.univ : set α).to_finset = finset.univ :=
by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] }
theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] :
fintype.card {x // p x} ≤ fintype.card α :=
by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _)
theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p]
{x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α :=
by rw [fintype.subtype_card]; exact finset.card_lt_card
⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩
instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] :
fintype (Σ' a, β a) :=
fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm
instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] :
fintype (Σ' a, β a) :=
if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩
else ⟨∅, λ x, h x.1⟩
instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] :
fintype (Σ' a, β a) :=
fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩
instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] :
fintype (Σ' a, β a) :=
if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩
instance set.fintype [fintype α] : fintype (set α) :=
⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin
classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩,
apply (coe_filter _).trans, rw [coe_univ, set.sep_univ], refl
end⟩
instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) :=
if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩
else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩
lemma mem_image_univ_iff_mem_range
{α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} :
b ∈ univ.image f ↔ b ∈ set.range f :=
by simp
lemma card_lt_card_of_injective_of_not_mem
{α β : Type*} [fintype α] [fintype β] (f : α → β) (h : function.injective f)
{b : β} (w : b ∉ set.range f) : fintype.card α < fintype.card β :=
begin
classical,
calc
fintype.card α = (univ : finset α).card : rfl
... = (image f univ).card : (card_image_of_injective univ h).symm
... < (insert b (image f univ)).card :
card_lt_card (ssubset_insert (mt mem_image_univ_iff_mem_range.mp w))
... ≤ (univ : finset β).card : card_le_of_subset (subset_univ _)
... = fintype.card β : rfl
end
def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance)
| [] f := ⟦λ i, false.elim⟧
| (i::l) f := begin
refine quotient.lift_on₂ (f i (list.mem_cons_self _ _))
(quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h)))
_ _,
exact λ a l, ⟦λ j h,
if e : j = i then by rw e; exact a else
l _ (h.resolve_left e)⟧,
refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
{ subst j, exact h₁ },
{ exact h₂ _ _ }
end
theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧
| [] f := quotient.sound (λ i h, h.elim)
| (i::l) f := begin
simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l],
refine quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
subst j, refl
end
def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι,
@quotient (Π i ∈ l, α i) (by apply_instance))
finset.univ.1
(λ l, quotient.fin_choice_aux l (λ i _, f i))
(λ a b h, begin
have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)),
simp [quotient.out_eq] at this,
simp [this],
let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧,
refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)),
congr' 1, exact quotient.sound h,
end))
(λ f, ⟦λ i, f i (finset.mem_univ _)⟧)
(λ a b h, quotient.sound $ λ i, h _ _)
theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι]
{α : ι → Type*} [∀ i, setoid (α i)]
(f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
begin
let q, swap, change quotient.lift_on q _ _ = _,
have : q = ⟦λ i h, f i⟧,
{ dsimp [q],
exact quotient.induction_on
(@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) },
simp [this], exact setoid.refl _
end
section equiv
open list equiv equiv.perm
variables [decidable_eq α] [decidable_eq β]
def perms_of_list : list α → list (perm α)
| [] := [1]
| (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f))
lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact
| [] := rfl
| (a :: l) :=
begin
rw [length_cons, nat.fact_succ],
simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul],
cc
end
lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l
| [] f h := list.mem_singleton.2 $ equiv.ext $ λ x, by simp [imp_false, *] at *
| (a::l) f h :=
if hfa : f a = a
then
mem_append_left _ $ mem_perms_of_list_of_mem
(λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx))
else
have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa,
have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l,
from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx,
have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa,
list.mem_of_ne_of_mem hxa
(h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)),
suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f,
by simpa [perms_of_list],
(@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2
(λ hfl, ⟨f a,
if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa))
else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc,
⟨swap a (f a) * f, mem_perms_of_list_of_mem this,
by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩)
lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l
| [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp
| (a::l) f h :=
(mem_append.1 h).elim
(λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx))
(λ h x hx,
let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in
let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in
if hxa : x = a then by simp [hxa]
else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy
else mem_cons_of_mem _ $
mem_of_mem_perms_of_list hg₁ $
by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def];
split_ifs; cc)
lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩
lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup
| [] hl := by simp [perms_of_list]
| (a::l) hl :=
have hl' : l.nodup, from nodup_of_nodup_cons hl,
have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl',
have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a,
from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1),
by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact
⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_right_inj _).1) hln',
λ i j hj hij x hx₁ hx₂,
let ⟨f, hf⟩ := list.mem_map.1 hx₁ in
let ⟨g, hg⟩ := list.mem_map.1 hx₂ in
have hix : x a = nth_le l i (lt_trans hij hj),
by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left],
have hiy : x a = nth_le l j hj,
by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left],
absurd (hf.2.trans (hg.2.symm)) $
λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $
by rw [← hix, hiy]⟩,
λ f hf₁ hf₂,
let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in
let ⟨g, hg⟩ := list.mem_map.1 hx' in
have hgxa : g⁻¹ x = a, from f.injective $
by rw [hmeml hf₁, ← hg.2]; simp,
have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx),
(list.nodup_cons.1 hl).1 $
hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩
def perms_of_finset (s : finset α) : finset (perm α) :=
quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩)
(λ a b hab, hfunext (congr_arg _ (quotient.sound hab))
(λ ha hb _, heq_of_eq $ finset.ext.2 $
by simp [mem_perms_of_list_iff, hab.mem_iff]))
s.2
lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α},
f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s :=
by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff
lemma card_perms_of_finset : ∀ (s : finset α),
(perms_of_finset s).card = s.card.fact :=
by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l
def fintype_perm [fintype α] : fintype (perm α) :=
⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
instance [fintype α] [fintype β] : fintype (α ≃ β) :=
if h : fintype.card β = fintype.card α
then trunc.rec_on_subsingleton (fintype.equiv_fin α)
(λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β)
(λ eβ, @fintype.of_equiv _ (perm α) fintype_perm
(equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β))))
else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩
lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact :=
subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸
card_perms_of_finset _
lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) :
fintype.card (α ≃ β) = (fintype.card α).fact :=
fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) :
(univ : finset α) = {x} :=
begin
apply symm,
apply eq_of_subset_of_card_le (subset_univ ({x})),
apply le_of_eq,
simp [h, finset.card_univ]
end
end equiv
namespace fintype
section choose
open fintype
open equiv
variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p]
def choose_x (hp : ∃! a : α, p a) : {a // p a} :=
⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩
def choose (hp : ∃! a, p a) : α := choose_x p hp
lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) :=
(choose_x p hp).property
end choose
section bijection_inverse
open function
variables [fintype α] [decidable_eq α]
variables [fintype β] [decidable_eq β]
variables {f : α → β}
/-- `
`bij_inv f` is the unique inverse to a bijection `f`. This acts
as a computable alternative to `function.inv_fun`. -/
def bij_inv (f_bij : bijective f) (b : β) : α :=
fintype.choose (λ a, f a = b)
begin
rcases f_bij.right b with ⟨a', fa_eq_b⟩,
rw ← fa_eq_b,
exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩
end
lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f :=
λ a, f_bij.left (choose_spec (λ a', f a' = f a) _)
lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f :=
λ b, choose_spec (λ a', f a' = b) _
lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) :=
⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩
end bijection_inverse
lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop)
[is_trans α r] [is_irrefl α r] : well_founded r :=
by classical; exact
have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card,
from λ x y hxy, finset.card_lt_card $
by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le,
finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy];
exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩,
subrelation.wf this (measure_wf _)
lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) :=
well_founded_of_trans_of_irrefl _
@[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] :
is_well_order α (<) :=
{ wf := preorder.well_founded }
end fintype
class infinite (α : Type*) : Prop :=
(not_fintype : fintype α → false)
@[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α :=
⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩
namespace infinite
lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s :=
classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩
@[priority 100] -- see Note [lower instance priority]
instance nonempty (α : Type*) [infinite α] : nonempty α :=
nonempty_of_exists (exists_not_mem_finset (∅ : finset α))
lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α :=
⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩
lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α :=
⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩
private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α
| n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset
((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m)
(λ _, multiset.mem_range.1)).to_finset)
private lemma nat_embedding_aux_injective (α : Type*) [infinite α] :
function.injective (nat_embedding_aux α) :=
begin
assume m n h,
letI := classical.dec_eq α,
wlog hmlen : m ≤ n using m n,
by_contradiction hmn,
have hmn : m < n, from lt_of_le_of_ne hmlen hmn,
refine (classical.some_spec (exists_not_mem_finset
((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m)
(λ _, multiset.mem_range.1)).to_finset)) _,
refine multiset.mem_to_finset.2 (multiset.mem_pmap.2
⟨m, multiset.mem_range.2 hmn, _⟩),
rw [h, nat_embedding_aux]
end
noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α :=
⟨_, nat_embedding_aux_injective α⟩
end infinite
lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) :
¬ injective f :=
assume (hf : injective f),
have H : fintype α := fintype.of_injective f hf,
infinite.not_fintype H
lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) :
¬ surjective f :=
assume (hf : surjective f),
have H : infinite α := infinite.of_surjective f hf,
@infinite.not_fintype _ H infer_instance
instance nat.infinite : infinite ℕ :=
⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩
instance int.infinite : infinite ℤ :=
infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
|
9c45b5be2628212958ff1187452d0c84e83f15da | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/tactic23.lean | 2c5e0b52686c5bd659ac40b2f8bbd0f162956ce6 | [
"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 | 989 | lean | import logic
namespace experiment
inductive nat : Type :=
zero : nat,
succ : nat → nat
namespace nat
definition add (a b : nat) : nat
:= nat.rec a (λ n r, succ r) b
infixl `+` := add
definition one := succ zero
-- Define coercion from num -> nat
-- By default the parser converts numerals into a binary representation num
definition pos_num_to_nat (n : pos_num) : nat
:= pos_num.rec one (λ n r, r + r) (λ n r, r + r + one) n
definition num_to_nat (n : num) : nat
:= num.rec zero (λ n, pos_num_to_nat n) n
coercion num_to_nat
-- Now we can write 2 + 3, the coercion will be applied
check 2 + 3
-- Define an assump as an alias for the eassumption tactic
definition assump : tactic := tactic.eassumption
theorem T1 {p : nat → Prop} {a : nat } (H : p (a+2)) : ∃ x, p (succ x)
:= by apply exists_intro; assump
definition is_zero (n : nat)
:= nat.rec true (λ n r, false) n
theorem T2 : ∃ a, (is_zero a) = true
:= by apply exists_intro; apply eq.refl
end nat
end experiment
|
6aa5b5a8fd03d4c406cab1d0ec7715fed418208e | c777c32c8e484e195053731103c5e52af26a25d1 | /src/model_theory/quotients.lean | 60ccfe0151a5eec3f7919f2395ad17ab46a4eb50 | [
"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 | 2,554 | lean | /-
Copyright (c) 2022 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import data.fintype.quotient
import model_theory.semantics
/-!
# Quotients of First-Order Structures
This file defines prestructures and quotients of first-order structures.
## Main Definitions
* If `s` is a setoid (equivalence relation) on `M`, a `first_order.language.prestructure s` is the
data for a first-order structure on `M` that will still be a structure when modded out by `s`.
* The structure `first_order.language.quotient_structure s` is the resulting structure on
`quotient s`.
-/
namespace first_order
namespace language
variables (L : language) {M : Type*}
open_locale first_order
open Structure
/-- A prestructure is a first-order structure with a `setoid` equivalence relation on it,
such that quotienting by that equivalence relation is still a structure. -/
class prestructure (s : setoid M) :=
(to_structure : L.Structure M)
(fun_equiv : ∀{n} {f : L.functions n} (x y : fin n → M),
x ≈ y → fun_map f x ≈ fun_map f y)
(rel_equiv : ∀{n} {r : L.relations n} (x y : fin n → M) (h : x ≈ y),
(rel_map r x = rel_map r y))
variables {L} {s : setoid M} [ps : L.prestructure s]
instance quotient_structure :
L.Structure (quotient s) :=
{ fun_map := λ n f x, quotient.map (@fun_map L M ps.to_structure n f) prestructure.fun_equiv
(quotient.fin_choice x),
rel_map := λ n r x, quotient.lift (@rel_map L M ps.to_structure n r) prestructure.rel_equiv
(quotient.fin_choice x) }
variables [s]
include s
lemma fun_map_quotient_mk {n : ℕ} (f : L.functions n) (x : fin n → M) :
fun_map f (λ i, ⟦x i⟧) = ⟦@fun_map _ _ ps.to_structure _ f x⟧ :=
begin
change quotient.map (@fun_map L M ps.to_structure n f) prestructure.fun_equiv
(quotient.fin_choice _) = _,
rw [quotient.fin_choice_eq, quotient.map_mk],
end
lemma rel_map_quotient_mk {n : ℕ} (r : L.relations n) (x : fin n → M) :
rel_map r (λ i, ⟦x i⟧) ↔ @rel_map _ _ ps.to_structure _ r x :=
begin
change quotient.lift (@rel_map L M ps.to_structure n r) prestructure.rel_equiv
(quotient.fin_choice _) ↔ _,
rw [quotient.fin_choice_eq, quotient.lift_mk],
end
lemma term.realize_quotient_mk {β : Type*} (t : L.term β) (x : β → M) :
t.realize (λ i, ⟦x i⟧) = ⟦@term.realize _ _ ps.to_structure _ x t⟧ :=
begin
induction t with _ _ _ _ ih,
{ refl },
{ simp only [ih, fun_map_quotient_mk, term.realize] },
end
end language
end first_order
|
b33e44a9f872f20ad945ed769f572f9ae39a4e18 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/LCNF/AlphaEqv.lean | 476df24ebdf2351a4fd7841fa552b87f9df4e508 | [
"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,740 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.LCNF.Basic
namespace Lean.Compiler.LCNF
/-!
Alpha equivalence for LCNF Code
-/
namespace AlphaEqv
abbrev EqvM := ReaderM (FVarIdMap FVarId)
def eqvFVar (fvarId₁ fvarId₂ : FVarId) : EqvM Bool := do
let fvarId₂ := (← read).find? fvarId₂ |>.getD fvarId₂
return fvarId₁ == fvarId₂
def eqvType (e₁ e₂ : Expr) : EqvM Bool := do
match e₁, e₂ with
| .app f₁ a₁, .app f₂ a₂ => eqvType a₁ a₂ <&&> eqvType f₁ f₂
| .fvar fvarId₁, .fvar fvarId₂ => eqvFVar fvarId₁ fvarId₂
| .forallE _ d₁ b₁ _, .forallE _ d₂ b₂ _ => eqvType d₁ d₂ <&&> eqvType b₁ b₂
| _, _ => return e₁ == e₂
def eqvTypes (es₁ es₂ : Array Expr) : EqvM Bool := do
if es₁.size = es₂.size then
for e₁ in es₁, e₂ in es₂ do
unless (← eqvType e₁ e₂) do
return false
return true
else
return false
def eqvArg (a₁ a₂ : Arg) : EqvM Bool := do
match a₁, a₂ with
| .type e₁, .type e₂ => eqvType e₁ e₂
| .fvar x₁, .fvar x₂ => eqvFVar x₁ x₂
| .erased, .erased => return true
| _, _ => return false
def eqvArgs (as₁ as₂ : Array Arg) : EqvM Bool := do
if as₁.size = as₂.size then
for a₁ in as₁, a₂ in as₂ do
unless (← eqvArg a₁ a₂) do
return false
return true
else
return false
def eqvLetValue (e₁ e₂ : LetValue) : EqvM Bool := do
match e₁, e₂ with
| .value v₁, .value v₂ => return v₁ == v₂
| .erased, .erased => return true
| .proj s₁ i₁ x₁, .proj s₂ i₂ x₂ => pure (s₁ == s₂ && i₁ == i₂) <&&> eqvFVar x₁ x₂
| .const n₁ us₁ as₁, .const n₂ us₂ as₂ => pure (n₁ == n₂ && us₁ == us₂) <&&> eqvArgs as₁ as₂
| .fvar f₁ as₁, .fvar f₂ as₂ => eqvFVar f₁ f₂ <&&> eqvArgs as₁ as₂
| _, _ => return false
@[inline] def withFVar (fvarId₁ fvarId₂ : FVarId) (x : EqvM α) : EqvM α :=
withReader (·.insert fvarId₂ fvarId₁) x
@[inline] def withParams (params₁ params₂ : Array Param) (x : EqvM Bool) : EqvM Bool := do
if h : params₂.size = params₁.size then
let rec @[specialize] go (i : Nat) : EqvM Bool := do
if h : i < params₁.size then
let p₁ := params₁[i]
have : i < params₂.size := by simp_all_arith
let p₂ := params₂[i]
unless (← eqvType p₁.type p₂.type) do return false
withFVar p₁.fvarId p₂.fvarId do
go (i+1)
else
x
go 0
else
return false
termination_by go i => params₁.size - i
def sortAlts (alts : Array Alt) : Array Alt :=
alts.qsort fun
| .alt .., .default .. => true
| .alt ctorName₁ .., .alt ctorName₂ .. => Name.lt ctorName₁ ctorName₂
| _, _ => false
mutual
partial def eqvAlts (alts₁ alts₂ : Array Alt) : EqvM Bool := do
if alts₁.size = alts₂.size then
let alts₁ := sortAlts alts₁
let alts₂ := sortAlts alts₂
for alt₁ in alts₁, alt₂ in alts₂ do
match alt₁, alt₂ with
| .alt ctorName₁ ps₁ k₁, .alt ctorName₂ ps₂ k₂ =>
unless ctorName₁ == ctorName₂ do return false
unless (← withParams ps₁ ps₂ (eqv k₁ k₂)) do return false
| .default k₁, .default k₂ => unless (← eqv k₁ k₂) do return false
| _, _ => return false
return true
else
return false
partial def eqv (code₁ code₂ : Code) : EqvM Bool := do
match code₁, code₂ with
| .let decl₁ k₁, .let decl₂ k₂ =>
eqvType decl₁.type decl₂.type <&&>
eqvLetValue decl₁.value decl₂.value <&&>
withFVar decl₁.fvarId decl₂.fvarId (eqv k₁ k₂)
| .fun decl₁ k₁, .fun decl₂ k₂
| .jp decl₁ k₁, .jp decl₂ k₂ =>
eqvType decl₁.type decl₂.type <&&>
withParams decl₁.params decl₂.params (eqv decl₁.value decl₂.value) <&&>
withFVar decl₁.fvarId decl₂.fvarId (eqv k₁ k₂)
| .return fvarId₁, .return fvarId₂ => eqvFVar fvarId₁ fvarId₂
| .unreach type₁, .unreach type₂ => eqvType type₁ type₂
| .jmp fvarId₁ args₁, .jmp fvarId₂ args₂ => eqvFVar fvarId₁ fvarId₂ <&&> eqvArgs args₁ args₂
| .cases c₁, .cases c₂ =>
eqvFVar c₁.discr c₂.discr <&&>
eqvType c₁.resultType c₂.resultType <&&>
eqvAlts c₁.alts c₂.alts
| _, _ => return false
end
end AlphaEqv
/--
Return `true` if `c₁` and `c₂` are alpha equivalent.
-/
def Code.alphaEqv (c₁ c₂ : Code) : Bool :=
AlphaEqv.eqv c₁ c₂ |>.run {}
end Lean.Compiler.LCNF |
4e19709c932f85b3d4b4043e3704ccfa4cba707f | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/system_of_complexes/double.lean | 12a61c6e8f4ca7f5f6b82f8ebe36b59d999c850d | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,348 | lean | import hacks_and_tricks.by_exactI_hack
import system_of_complexes.basic
import facts
universe variables v u
noncomputable theory
open opposite category_theory
open_locale nnreal
/-!
# Systems of double complexes of seminormed groups
In this file we define systems of double complexes of seminormed groups,
as needed for Definition 9.6 of [Analytic].
## Main declarations
* `system_of_double_complexes`: a system of complexes of seminormed groups.
* `admissible`: such a system is *admissible* if all maps that occur in the system
are norm-nonincreasing.
-/
/-- A system of double complexes of seminormed groups, indexed by `ℝ≥0`.
See also Definition 9.3 of [Analytic]. -/
@[derive category_theory.category]
def system_of_double_complexes : Type (u+1) :=
ℝ≥0ᵒᵖ ⥤ (cochain_complex (cochain_complex SemiNormedGroup.{u} ℕ) ℕ)
namespace system_of_double_complexes
variables (C : system_of_double_complexes)
/-- `C.X c p q` is the object $C_c^{p,q}$ in a system of double complexes `C`. -/
def X (c : ℝ≥0) (p q : ℕ) : SemiNormedGroup :=
((C.obj $ op c).X p).X q
/-- `C.res` is the restriction map `C.X c' p q ⟶ C.X c p q` for a system of complexes `C`,
and nonnegative reals `c ≤ c'`. -/
def res {c' c : ℝ≥0} {p q : ℕ} [h : fact (c ≤ c')] :
C.X c' p q ⟶ C.X c p q :=
((C.map (hom_of_le h.out).op).f p).f q
variables (c : ℝ≥0) {c₁ c₂ c₃ : ℝ≥0} (p p' q q' : ℕ)
@[simp] lemma res_refl : @res C c c p q _ = 𝟙 _ :=
begin
have := (category_theory.functor.map_id C (op $ c)),
delta res, erw this, refl
end
@[simp] lemma norm_res_of_eq (h : c₂ = c₁) (x : C.X c₁ p q) : ∥@res C _ _ p q ⟨h.le⟩ x∥ = ∥x∥ :=
by { cases h, rw res_refl, refl }
@[simp] lemma res_comp_res (h₁ : fact (c₂ ≤ c₁)) (h₂ : fact (c₃ ≤ c₂)) :
@res C _ _ p q h₁ ≫ @res C _ _ p q h₂ = @res C _ _ p q ⟨h₂.out.trans h₁.out⟩ :=
begin
have := (category_theory.functor.map_comp C (hom_of_le h₁.out).op (hom_of_le h₂.out).op),
rw [← op_comp] at this,
delta res, erw this, refl,
end
@[simp] lemma res_res (h₁ : fact (c₂ ≤ c₁)) (h₂ : fact (c₃ ≤ c₂)) (x : C.X c₁ p q) :
@res C _ _ p q h₂ (@res C _ _ p q h₁ x) = @res C _ _ p q ⟨h₂.out.trans h₁.out⟩ x :=
by { rw ← (C.res_comp_res p q h₁ h₂), refl }
/-- `C.d` is the differential `C.X c p q ⟶ C.X c (p+1) q` for a system of double complexes `C`. -/
def d {c : ℝ≥0} (p p' : ℕ) {q : ℕ} : C.X c p q ⟶ C.X c p' q :=
((C.obj $ op c).d p p').f q
lemma d_eq_zero (c : ℝ≥0) (h : p + 1 ≠ p') : (C.d p p' : C.X c p q ⟶ _) = 0 :=
by { have : (C.obj (op c)).d p p' = 0 := (C.obj $ op c).shape _ _ h, rw [d, this], refl }
lemma d_eq_zero_apply (c : ℝ≥0) (h : p + 1 ≠ p') (x : C.X c p q) : (C.d p p' x) = 0 :=
by { rw [d_eq_zero C p p' q c h], refl }
@[simp] lemma d_self_apply (c : ℝ≥0) (x : C.X c p q) : (C.d p p x) = 0 :=
d_eq_zero_apply _ _ _ _ _ p.succ_ne_self _
lemma d_comp_res (h : fact (c₂ ≤ c₁)) :
C.d p p' ≫ @res C _ _ _ q h = @res C _ _ p q _ ≫ C.d p p' :=
congr_fun (congr_arg homological_complex.hom.f ((C.map (hom_of_le h.out).op).comm p p')).symm q
lemma d_res (h : fact (c₂ ≤ c₁)) (x) :
@d C c₂ p p' q (@res C _ _ p q _ x) = @res C _ _ _ _ h (@d C c₁ p p' q x) :=
show (@res C _ _ p q _ ≫ C.d p p') x = (C.d p p' ≫ @res C _ _ _ _ h) x,
by rw d_comp_res
@[simp] lemma d_comp_d {c : ℝ≥0} {p p' p'' q : ℕ} :
@d C c p p' q ≫ C.d p' p'' = 0 :=
congr_fun (congr_arg homological_complex.hom.f ((C.obj $ op c).d_comp_d p p' p'')) q
@[simp] lemma d_d {c : ℝ≥0} {p p' p'' q : ℕ} (x : C.X c p q) :
C.d p' p'' (C.d p p' x) = 0 :=
show (C.d _ _ ≫ C.d _ _) x = 0, by { rw d_comp_d, refl }
/-- `C.d'` is the differential `C.X c p q ⟶ C.X c p (q+1)` for a system of double complexes `C`. -/
def d' {c : ℝ≥0} {p : ℕ} (q q' : ℕ) : C.X c p q ⟶ C.X c p q' :=
((C.obj $ op c).X p).d q q'
lemma d'_eq_zero (c : ℝ≥0) (h : q + 1 ≠ q') : (C.d' q q' : C.X c p q ⟶ _) = 0 :=
((C.obj $ op c).X p).shape _ _ h
lemma d'_eq_zero_apply (c : ℝ≥0) (h : q + 1 ≠ q') (x : C.X c p q) : (C.d' q q' x) = 0 :=
by { rw [d'_eq_zero C p q q' c h], refl }
@[simp] lemma d'_self_apply (c : ℝ≥0) (x : C.X c p q) : (C.d' q q x) = 0 :=
d'_eq_zero_apply _ _ _ _ _ q.succ_ne_self _
lemma d'_comp_res (h : fact (c₂ ≤ c₁)) :
@d' C c₁ p q q' ≫ @res C _ _ _ _ h = @res C _ _ p q _ ≫ @d' C c₂ p q q' :=
(((C.map (hom_of_le h.out).op).f p).comm q q').symm
lemma d'_res (h : fact (c₂ ≤ c₁)) (x) :
C.d' q q' (@res C _ _ p q _ x) = @res C _ _ _ _ h (C.d' q q' x) :=
show (@res C _ _ p q _ ≫ C.d' q q') x = (C.d' q q' ≫ @res C _ _ _ _ h) x,
by rw d'_comp_res
@[simp] lemma d'_comp_d' {c : ℝ≥0} {p q q' q'' : ℕ} :
@d' C c p q q' ≫ C.d' q' q'' = 0 :=
((C.obj $ op c).X p).d_comp_d q q' q''
@[simp] lemma d'_d' {c : ℝ≥0} {p q q' q'' : ℕ} (x : C.X c p q) :
C.d' q' q'' (C.d' q q' x) = 0 :=
show (C.d' _ _ ≫ C.d' _ _) x = 0, by { rw d'_comp_d', refl }
lemma d'_comp_d (c : ℝ≥0) (p p' q q' : ℕ) :
C.d' q q' ≫ C.d p p' = C.d p p' ≫ (C.d' q q' : C.X c p' q ⟶ _) :=
(((C.obj $ op c).d p p').comm q q').symm
lemma d'_d (c : ℝ≥0) (p p' q q' : ℕ) (x : C.X c p q) :
C.d' q q' (C.d p p' x) = C.d p p' (C.d' q q' x) :=
show (C.d p p' ≫ C.d' q q') x = (C.d' q q' ≫ C.d p p') x,
by rw [d'_comp_d]
/-- Convenience definition:
The identity morphism of an object in the system of double complexes
when it is given by different indices that are not
definitionally equal. -/
def congr {c c' : ℝ≥0} {p p' q q' : ℕ} (hc : c = c') (hp : p = p') (hq : q = q') :
C.X c p q ⟶ C.X c' p' q' :=
eq_to_hom $ by { subst hc, subst hp, subst hq, }
/-- The `p`-th row in a system of double complexes, as system of complexes.
It has object `(C.obj c).X p`over `c`. -/
def row (C : system_of_double_complexes.{u}) (p : ℕ) : system_of_complexes.{u} :=
C ⋙ homological_complex.forget _ _ ⋙ pi.eval _ p
@[simp] lemma row_X (C : system_of_double_complexes) (p q : ℕ) (c : ℝ≥0) :
C.row p c q = C.X c p q :=
rfl
@[simp] lemma row_res (C : system_of_double_complexes) (p q : ℕ) {c' c : ℝ≥0} [h : fact (c ≤ c')] :
@system_of_complexes.res (C.row p) _ _ q h = @res C _ _ p q h :=
rfl
@[simp] lemma row_d (C : system_of_double_complexes) (c : ℝ≥0) (p : ℕ) :
(C.row p).d = @d' C c p :=
rfl
/-- The differential between rows in a system of double complexes,
as map of system of complexes. -/
@[simps app_f]
def row_map (C : system_of_double_complexes.{u}) (p p' : ℕ) :
C.row p ⟶ C.row p' :=
{ app := λ c,
{ f := λ q, (C.d p p' : C.X c.unop p q ⟶ C.X c.unop p' q),
comm' := λ q q' _, (C.d'_comp_d _ p p' q q').symm },
naturality' := λ c₁ c₂ h, (C.map h).comm p p' }
@[simp] lemma row_map_apply (C : system_of_double_complexes.{u})
(c : ℝ≥0) (p p' q : ℕ) (x : C.X c p q) :
C.row_map p p' x = C.d p p' x := rfl
-- -- this should be found by TC, but we first need to make `pi.eval` and `graded_object` additive
-- instance aux : (homological_complex.forget SemiNormedGroup (complex_shape.up ℕ) ⋙
-- pi.eval (λ (_ : ℕ), SemiNormedGroup) q).additive :=
-- { map_zero' := λ C₁ C₂, by { dsimp, refl },
-- map_add' := by { intros, dsimp, refl } }
/-- The `q`-th column in a system of double complexes, as system of complexes. -/
@[simps]
def col (C : system_of_double_complexes.{u}) (q : ℕ) : system_of_complexes.{u} :=
C ⋙ functor.map_homological_complex (homological_complex.eval _ _ q) _
@[simp] lemma col_X (C : system_of_double_complexes) (p q : ℕ) (c : ℝ≥0) :
C.col q c p = C.X c p q :=
rfl
@[simp] lemma col_res (C : system_of_double_complexes) (p q : ℕ) {c' c : ℝ≥0} [h : fact (c ≤ c')] :
(@system_of_complexes.res (C.col q) _ _ p h : C.col q c' p ⟶ C.col q c p) =
-- (@res C _ _ p q h : C.X c' p q ⟶ C.X c p q) :=
by dsimp_result { dsimp, exact (@res C _ _ p q h : C.X c' p q ⟶ C.X c p q) } :=
rfl
@[simp] lemma col_d (C : system_of_double_complexes) (c : ℝ≥0) (p p' q : ℕ) :
@system_of_complexes.d (C.col q) c p p' =
by dsimp_result { dsimp, exact @d C c p p' q } :=
rfl
/-- The differential between columns in a system of double complexes,
as map of system of complexes. -/
def col_map (C : system_of_double_complexes.{u}) (q q' : ℕ) :
C.col q ⟶ C.col q' :=
{ app := λ c,
{ f := λ p, (C.d' q q' : C.X c.unop p q ⟶ C.X c.unop p q'),
comm' := λ p p' _, (C.d'_comp_d _ p p' q q') },
naturality' := λ c₁ c₂ h, by { ext p : 2, exact ((C.map h).f p).comm q q' } }
/-- A system of double complexes is *admissible*
if all the differentials and restriction maps are norm-nonincreasing.
See Definition 9.3 of [Analytic]. -/
structure admissible (C : system_of_double_complexes) : Prop :=
(d_norm_noninc' : ∀ c p p' q (h : p + 1 = p'), (@d C c p p' q).norm_noninc)
(d'_norm_noninc' : ∀ c p q q' (h : q + 1 = q'), (@d' C c p q q').norm_noninc)
(res_norm_noninc : ∀ c' c p q h, (@res C c' c p q h).norm_noninc)
namespace admissible
variables {C}
lemma d_norm_noninc (hC : C.admissible) (c : ℝ≥0) (p p' q : ℕ) :
(C.d p p' : C.X c p q ⟶ _).norm_noninc :=
begin
by_cases h : p + 1 = p',
{ exact hC.d_norm_noninc' c p p' q h },
{ rw C.d_eq_zero p p' q c h, intro v, simp }
end
lemma d'_norm_noninc (hC : C.admissible) (c : ℝ≥0) (p q q' : ℕ) :
(C.d' q q' : C.X c p q ⟶ _).norm_noninc :=
begin
by_cases h : q + 1 = q',
{ exact hC.d'_norm_noninc' c p q q' h },
{ rw C.d'_eq_zero p q q' c h, intro v, simp }
end
lemma col (hC : C.admissible) (q : ℕ) : (C.col q).admissible :=
{ d_norm_noninc' := λ c i j h, hC.d_norm_noninc _ _ _ _,
res_norm_noninc := λ c i j h, hC.res_norm_noninc _ _ _ _ _ }
lemma row (hC : C.admissible) (p : ℕ) : (C.row p).admissible :=
{ d_norm_noninc' := λ c i j h, hC.d'_norm_noninc _ _ _ _,
res_norm_noninc := λ c i j h, hC.res_norm_noninc _ _ _ _ _ }
lemma mk' (h : ∀ p, (C.row p).admissible)
(hd : ∀ c p p' q (h : p + 1 = p'), (@d C c p p' q).norm_noninc) :
C.admissible :=
{ d_norm_noninc' := λ c p p' q h', hd c p p' q h',
d'_norm_noninc' := λ c p q q' h', (h p).d_norm_noninc' _ _ _ h',
res_norm_noninc := λ c₁ c₂ p q h', by { resetI, apply (h p).res_norm_noninc } }
end admissible
end system_of_double_complexes
|
7891cea4939dccbd9dbd3a6d0e76e662cac3d124 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Linter/UnusedVariables.lean | cad32754e74dccf07a2717fe12ca9f90db15bd6e | [
"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 | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 10,639 | lean | import Lean.Elab.Command
import Lean.Linter.Util
import Lean.Server.References
namespace Lean.Linter
open Lean.Elab.Command Lean.Server Std
register_builtin_option linter.unusedVariables : Bool := {
defValue := true,
descr := "enable the 'unused variables' linter"
}
register_builtin_option linter.unusedVariables.funArgs : Bool := {
defValue := true,
descr := "enable the 'unused variables' linter to mark unused function arguments"
}
register_builtin_option linter.unusedVariables.patternVars : Bool := {
defValue := true,
descr := "enable the 'unused variables' linter to mark unused pattern variables"
}
def getLinterUnusedVariables (o : Options) : Bool := getLinterValue linter.unusedVariables o
def getLinterUnusedVariablesFunArgs (o : Options) : Bool := o.get linter.unusedVariables.funArgs.name (getLinterUnusedVariables o)
def getLinterUnusedVariablesPatternVars (o : Options) : Bool := o.get linter.unusedVariables.patternVars.name (getLinterUnusedVariables o)
abbrev IgnoreFunction := Syntax → Syntax.Stack → Options → Bool
builtin_initialize builtinUnusedVariablesIgnoreFnsRef : IO.Ref <| Array IgnoreFunction ← IO.mkRef #[]
def addBuiltinUnusedVariablesIgnoreFn (ignoreFn : IgnoreFunction) : IO Unit := do
(← builtinUnusedVariablesIgnoreFnsRef.get) |> (·.push ignoreFn) |> builtinUnusedVariablesIgnoreFnsRef.set
-- matches builtinUnused variable pattern
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun stx _ _ =>
stx.getId.toString.startsWith "_")
-- is variable
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ =>
stack.matches [`null, none, `null, ``Lean.Parser.Command.variable])
-- is in structure
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ =>
stack.matches [`null, none, `null, ``Lean.Parser.Command.structure])
-- is in inductive
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ =>
stack.matches [`null, none, `null, none, ``Lean.Parser.Command.inductive] &&
(stack.get? 3 |>.any fun (stx, pos) =>
pos == 0 &&
[``Lean.Parser.Command.optDeclSig, ``Lean.Parser.Command.declSig].any (stx.isOfKind ·)))
-- in in constructor or structure binder
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ =>
stack.matches [`null, none, `null, ``Lean.Parser.Command.optDeclSig, none] &&
(stack.get? 4 |>.any fun (stx, _) =>
[``Lean.Parser.Command.ctor, ``Lean.Parser.Command.structSimpleBinder].any (stx.isOfKind ·)))
-- is in opaque or axiom
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ =>
stack.matches [`null, none, `null, ``Lean.Parser.Command.declSig, none] &&
(stack.get? 4 |>.any fun (stx, _) =>
[``Lean.Parser.Command.opaque, ``Lean.Parser.Command.axiom].any (stx.isOfKind ·)))
-- is in definition with foreign definition
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ =>
stack.matches [`null, none, `null, none, none, ``Lean.Parser.Command.declaration] &&
(stack.get? 3 |>.any fun (stx, _) =>
stx.isOfKind ``Lean.Parser.Command.optDeclSig ||
stx.isOfKind ``Lean.Parser.Command.declSig) &&
(stack.get? 5 |>.any fun (stx, _) => match stx[0] with
| `(Lean.Parser.Command.declModifiersT| $[$_:docComment]? @[$[$attrs:attr],*] $[$vis]? $[noncomputable]?) =>
attrs.any (fun attr => attr.raw.isOfKind ``Parser.Attr.extern || attr matches `(attr| implemented_by $_))
| _ => false))
-- is in dependent arrow
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ =>
stack.matches [`null, ``Lean.Parser.Term.explicitBinder, ``Lean.Parser.Term.depArrow])
-- is in let declaration
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack opts =>
!getLinterUnusedVariablesFunArgs opts &&
stack.matches [`null, none, `null, ``Lean.Parser.Term.letIdDecl, none] &&
(stack.get? 3 |>.any fun (_, pos) => pos == 1) &&
(stack.get? 5 |>.any fun (stx, _) => !stx.isOfKind ``Lean.Parser.Command.whereStructField))
-- is in declaration signature
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack opts =>
!getLinterUnusedVariablesFunArgs opts &&
stack.matches [`null, none, `null, none] &&
(stack.get? 3 |>.any fun (stx, pos) =>
pos == 0 &&
[``Lean.Parser.Command.optDeclSig, ``Lean.Parser.Command.declSig].any (stx.isOfKind ·)))
-- is in function definition
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack opts =>
!getLinterUnusedVariablesFunArgs opts &&
(stack.matches [`null, ``Lean.Parser.Term.basicFun] ||
stack.matches [``Lean.Parser.Term.typeAscription, `null, ``Lean.Parser.Term.basicFun]))
-- is pattern variable
builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack opts =>
!getLinterUnusedVariablesPatternVars opts &&
stack.any fun (stx, pos) =>
(stx.isOfKind ``Lean.Parser.Term.matchAlt && pos == 1) ||
(stx.isOfKind ``Lean.Parser.Tactic.inductionAltLHS && pos == 2))
builtin_initialize unusedVariablesIgnoreFnsExt : SimplePersistentEnvExtension Name Unit ←
registerSimplePersistentEnvExtension {
addEntryFn := fun _ _ => ()
addImportedFn := fun _ => ()
}
builtin_initialize
registerBuiltinAttribute {
name := `unused_variables_ignore_fn
descr := "Marks a function of type `Lean.Linter.IgnoreFunction` for suppressing unused variable warnings"
add := fun decl stx kind => do
Attribute.Builtin.ensureNoArgs stx
unless kind == AttributeKind.global do throwError "invalid attribute 'unused_variables_ignore_fn', must be global"
unless (← getConstInfo decl).type.isConstOf ``IgnoreFunction do
throwError "invalid attribute 'unused_variables_ignore_fn', must be of type `Lean.Linter.IgnoreFunction`"
let env ← getEnv
setEnv <| unusedVariablesIgnoreFnsExt.addEntry env decl
}
unsafe def getUnusedVariablesIgnoreFnsImpl : CommandElabM (Array IgnoreFunction) := do
let ents := unusedVariablesIgnoreFnsExt.getEntries (← getEnv)
let ents ← ents.mapM (evalConstCheck IgnoreFunction ``IgnoreFunction)
return (← builtinUnusedVariablesIgnoreFnsRef.get) ++ ents
@[implemented_by getUnusedVariablesIgnoreFnsImpl]
opaque getUnusedVariablesIgnoreFns : CommandElabM (Array IgnoreFunction)
def unusedVariables : Linter := fun cmdStx => do
unless getLinterUnusedVariables (← getOptions) do
return
-- NOTE: `messages` is local to the current command
if (← get).messages.hasErrors then
return
let some cmdStxRange := cmdStx.getRange?
| pure ()
let infoTrees := (← get).infoState.trees.toArray
let fileMap := (← read).fileMap
if (← infoTrees.anyM (·.hasSorry)) then
return
-- collect references
let refs := findModuleRefs fileMap infoTrees (allowSimultaneousBinderUse := true)
let mut vars : HashMap FVarId RefInfo := .empty
let mut constDecls : HashSet String.Range := .empty
for (ident, info) in refs.toList do
match ident with
| .fvar id =>
vars := vars.insert id info
| .const _ =>
if let some definition := info.definition then
if let some range := definition.stx.getRange? then
constDecls := constDecls.insert range
-- collect uses from tactic infos
let tacticMVarAssignments : HashMap MVarId Expr :=
infoTrees.foldr (init := .empty) fun tree assignments =>
tree.foldInfo (init := assignments) (fun _ i assignments => match i with
| .ofTacticInfo ti =>
ti.mctxAfter.eAssignment.foldl (init := assignments) fun assignments mvar expr =>
if assignments.contains mvar then
assignments
else
assignments.insert mvar expr
| _ =>
assignments)
let tacticFVarUses : HashSet FVarId ←
tacticMVarAssignments.foldM (init := .empty) fun uses _ expr => do
let (_, s) ← StateT.run (s := uses) <| expr.forEach fun
| .fvar id => modify (·.insert id)
| _ => pure ()
return s
-- collect ignore functions
let ignoreFns := (← getUnusedVariablesIgnoreFns)
|>.insertAt! 0 (isTopLevelDecl constDecls)
-- determine unused variables
let mut unused := #[]
for (id, ⟨decl?, uses⟩) in vars.toList do
-- process declaration
let some decl := decl?
| continue
let declStx := skipDeclIdIfPresent decl.stx
let some range := declStx.getRange?
| continue
let some localDecl := decl.info.lctx.find? id
| continue
if !cmdStxRange.contains range.start || localDecl.userName.hasMacroScopes then
continue
-- check if variable is used
if !uses.isEmpty || tacticFVarUses.contains id || decl.aliases.any (match · with | .fvar id => tacticFVarUses.contains id | _ => false) then
continue
-- check linter options
let opts := decl.ci.options
if !getLinterUnusedVariables opts then
continue
-- evaluate ignore functions on original syntax
if let some ((id', _) :: stack) := cmdStx.findStack? (·.getRange?.any (·.includes range)) then
if id'.isIdent && ignoreFns.any (· declStx stack opts) then
continue
else
continue
-- evaluate ignore functions on macro expansion outputs
if ← infoTrees.anyM fun tree => do
if let some macroExpansions ← collectMacroExpansions? range tree then
return macroExpansions.any fun expansion =>
-- in a macro expansion, there may be multiple leafs whose (synthetic) range includes `range`, so accept strict matches only
if let some (_ :: stack) := expansion.output.findStack? (·.getRange?.any (·.includes range)) (fun stx => stx.isIdent && stx.getRange?.any (· == range)) then
ignoreFns.any (· declStx stack opts)
else
false
else
return false
then
continue
-- publish warning if variable is unused and not ignored
unused := unused.push (declStx, localDecl)
for (declStx, localDecl) in unused.qsort (·.1.getPos?.get! < ·.1.getPos?.get!) do
logLint linter.unusedVariables declStx m!"unused variable `{localDecl.userName}`"
return ()
where
skipDeclIdIfPresent (stx : Syntax) : Syntax :=
if stx.isOfKind ``Lean.Parser.Command.declId then
stx[0]
else
stx
isTopLevelDecl (constDecls : HashSet String.Range) : IgnoreFunction := fun stx stack _ => Id.run <| do
let some declRange := stx.getRange?
| false
constDecls.contains declRange &&
!stack.matches [``Lean.Parser.Term.letIdDecl]
builtin_initialize addLinter unusedVariables
end Linter
def MessageData.isUnusedVariableWarning (msg : MessageData) : Bool :=
msg.hasTag (· == Linter.linter.unusedVariables.name)
|
016125aa3c8822926c0a0c49f387a9c06a5cef97 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/linear_algebra/basis.lean | f32ebb284f918ead4de5fb2068479883ca13992e | [
"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 | 52,204 | 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, Alexander Bentkamp
-/
import algebra.big_operators.finsupp
import algebra.big_operators.finprod
import data.fintype.card
import linear_algebra.finsupp
import linear_algebra.linear_independent
import linear_algebra.linear_pmap
import linear_algebra.projection
/-!
# Bases
This file defines bases in a module or vector space.
It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light.
## Main definitions
All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or
vector space and `ι : Type*` is an arbitrary indexing type.
* `basis ι R M` is the type of `ι`-indexed `R`-bases for a module `M`,
represented by a linear equiv `M ≃ₗ[R] ι →₀ R`.
* the basis vectors of a basis `b : basis ι R M` are available as `b i`, where `i : ι`
* `basis.repr` is the isomorphism sending `x : M` to its coordinates `basis.repr x : ι →₀ R`.
The converse, turning this isomorphism into a basis, is called `basis.of_repr`.
* If `ι` is finite, there is a variant of `repr` called `basis.equiv_fun b : M ≃ₗ[R] ι → R`
(saving you from having to work with `finsupp`). The converse, turning this isomorphism into
a basis, is called `basis.of_equiv_fun`.
* `basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the
basis elements `⇑b : ι → M₁`.
* `basis.reindex` uses an equiv to map a basis to a different indexing set.
* `basis.map` uses a linear equiv to map a basis to a different module.
## Main statements
* `basis.mk`: a linear independent set of vectors spanning the whole module determines a basis
* `basis.ext` states that two linear maps are equal if they coincide on a basis.
Similar results are available for linear equivs (if they coincide on the basis vectors),
elements (if their coordinates coincide) and the functions `b.repr` and `⇑b`.
* `basis.of_vector_space` states that every vector space has a basis.
## Implementation notes
We use families instead of sets because it allows us to say that two identical vectors are linearly
dependent. For bases, this is useful as well because we can easily derive ordered bases by using an
ordered index type `ι`.
## Tags
basis, bases
-/
noncomputable theory
universe u
open function set submodule
open_locale classical big_operators
variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*}
variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*}
section module
variables [semiring R]
variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M']
section
variables (ι) (R) (M)
/-- A `basis ι R M` for a module `M` is the type of `ι`-indexed `R`-bases of `M`.
The basis vectors are available as `coe_fn (b : basis ι R M) : ι → M`.
To turn a linear independent family of vectors spanning `M` into a basis, use `basis.mk`.
They are internally represented as linear equivs `M ≃ₗ[R] (ι →₀ R)`,
available as `basis.repr`.
-/
structure basis := of_repr :: (repr : M ≃ₗ[R] (ι →₀ R))
end
namespace basis
instance : inhabited (basis ι R (ι →₀ R)) := ⟨basis.of_repr (linear_equiv.refl _ _)⟩
variables (b b₁ : basis ι R M) (i : ι) (c : R) (x : M)
section repr
/-- `b i` is the `i`th basis vector. -/
instance : has_coe_to_fun (basis ι R M) (λ _, ι → M) :=
{ coe := λ b i, b.repr.symm (finsupp.single i 1) }
@[simp] lemma coe_of_repr (e : M ≃ₗ[R] (ι →₀ R)) :
⇑(of_repr e) = λ i, e.symm (finsupp.single i 1) :=
rfl
protected lemma injective [nontrivial R] : injective b :=
b.repr.symm.injective.comp (λ _ _, (finsupp.single_left_inj (one_ne_zero : (1 : R) ≠ 0)).mp)
lemma repr_symm_single_one : b.repr.symm (finsupp.single i 1) = b i := rfl
lemma repr_symm_single : b.repr.symm (finsupp.single i c) = c • b i :=
calc b.repr.symm (finsupp.single i c)
= b.repr.symm (c • finsupp.single i 1) : by rw [finsupp.smul_single', mul_one]
... = c • b i : by rw [linear_equiv.map_smul, repr_symm_single_one]
@[simp] lemma repr_self : b.repr (b i) = finsupp.single i 1 :=
linear_equiv.apply_symm_apply _ _
lemma repr_self_apply (j) [decidable (i = j)] :
b.repr (b i) j = if i = j then 1 else 0 :=
by rw [repr_self, finsupp.single_apply]
@[simp] lemma repr_symm_apply (v) : b.repr.symm v = finsupp.total ι M R b v :=
calc b.repr.symm v = b.repr.symm (v.sum finsupp.single) : by simp
... = ∑ i in v.support, b.repr.symm (finsupp.single i (v i)) :
by rw [finsupp.sum, linear_equiv.map_sum]
... = finsupp.total ι M R b v :
by simp [repr_symm_single, finsupp.total_apply, finsupp.sum]
@[simp] lemma coe_repr_symm : ↑b.repr.symm = finsupp.total ι M R b :=
linear_map.ext (λ v, b.repr_symm_apply v)
@[simp] lemma repr_total (v) : b.repr (finsupp.total _ _ _ b v) = v :=
by { rw ← b.coe_repr_symm, exact b.repr.apply_symm_apply v }
@[simp] lemma total_repr : finsupp.total _ _ _ b (b.repr x) = x :=
by { rw ← b.coe_repr_symm, exact b.repr.symm_apply_apply x }
lemma repr_range : (b.repr : M →ₗ[R] (ι →₀ R)).range = finsupp.supported R R univ :=
by rw [linear_equiv.range, finsupp.supported_univ]
lemma mem_span_repr_support {ι : Type*} (b : basis ι R M) (m : M) :
m ∈ span R (b '' (b.repr m).support) :=
(finsupp.mem_span_image_iff_total _).2 ⟨b.repr m, (by simp [finsupp.mem_supported_support])⟩
lemma repr_support_subset_of_mem_span {ι : Type*}
(b : basis ι R M) (s : set ι) {m : M} (hm : m ∈ span R (b '' s)) : ↑(b.repr m).support ⊆ s :=
begin
rcases (finsupp.mem_span_image_iff_total _).1 hm with ⟨l, hl, hlm⟩,
rwa [←hlm, repr_total, ←finsupp.mem_supported R l]
end
end repr
section coord
/-- `b.coord i` is the linear function giving the `i`'th coordinate of a vector
with respect to the basis `b`.
`b.coord i` is an element of the dual space. In particular, for
finite-dimensional spaces it is the `ι`th basis vector of the dual space.
-/
@[simps]
def coord : M →ₗ[R] R := (finsupp.lapply i) ∘ₗ ↑b.repr
lemma forall_coord_eq_zero_iff {x : M} :
(∀ i, b.coord i x = 0) ↔ x = 0 :=
iff.trans
(by simp only [b.coord_apply, finsupp.ext_iff, finsupp.zero_apply])
b.repr.map_eq_zero_iff
/-- The sum of the coordinates of an element `m : M` with respect to a basis. -/
noncomputable def sum_coords : M →ₗ[R] R :=
finsupp.lsum ℕ (λ i, linear_map.id) ∘ₗ (b.repr : M →ₗ[R] ι →₀ R)
@[simp] lemma coe_sum_coords : (b.sum_coords : M → R) = λ m, (b.repr m).sum (λ i, id) :=
rfl
lemma coe_sum_coords_eq_finsum : (b.sum_coords : M → R) = λ m, ∑ᶠ i, b.coord i m :=
begin
ext m,
simp only [basis.sum_coords, basis.coord, finsupp.lapply_apply, linear_map.id_coe,
linear_equiv.coe_coe, function.comp_app, finsupp.coe_lsum, linear_map.coe_comp,
finsum_eq_sum _ (b.repr m).finite_support, finsupp.sum, finset.finite_to_set_to_finset,
id.def, finsupp.fun_support_eq],
end
@[simp] lemma coe_sum_coords_of_fintype [fintype ι] : (b.sum_coords : M → R) = ∑ i, b.coord i :=
begin
ext m,
simp only [sum_coords, finsupp.sum_fintype, linear_map.id_coe, linear_equiv.coe_coe, coord_apply,
id.def, fintype.sum_apply, implies_true_iff, eq_self_iff_true, finsupp.coe_lsum,
linear_map.coe_comp],
end
@[simp] lemma sum_coords_self_apply : b.sum_coords (b i) = 1 :=
by simp only [basis.sum_coords, linear_map.id_coe, linear_equiv.coe_coe, id.def, basis.repr_self,
function.comp_app, finsupp.coe_lsum, linear_map.coe_comp, finsupp.sum_single_index]
end coord
section ext
variables {R₁ : Type*} [semiring R₁] {σ : R →+* R₁} {σ' : R₁ →+* R}
variables [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ]
variables {M₁ : Type*} [add_comm_monoid M₁] [module R₁ M₁]
/-- Two linear maps are equal if they are equal on basis vectors. -/
theorem ext {f₁ f₂ : M →ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ :=
by { ext x,
rw [← b.total_repr x, finsupp.total_apply, finsupp.sum],
simp only [linear_map.map_sum, linear_map.map_smulₛₗ, h] }
include σ'
/-- Two linear equivs are equal if they are equal on basis vectors. -/
theorem ext' {f₁ f₂ : M ≃ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ :=
by { ext x,
rw [← b.total_repr x, finsupp.total_apply, finsupp.sum],
simp only [linear_equiv.map_sum, linear_equiv.map_smulₛₗ, h] }
omit σ'
/-- Two elements are equal if their coordinates are equal. -/
theorem ext_elem {x y : M}
(h : ∀ i, b.repr x i = b.repr y i) : x = y :=
by { rw [← b.total_repr x, ← b.total_repr y], congr' 1, ext i, exact h i }
lemma repr_eq_iff {b : basis ι R M} {f : M →ₗ[R] ι →₀ R} :
↑b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 :=
⟨λ h i, h ▸ b.repr_self i,
λ h, b.ext (λ i, (b.repr_self i).trans (h i).symm)⟩
lemma repr_eq_iff' {b : basis ι R M} {f : M ≃ₗ[R] ι →₀ R} :
b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 :=
⟨λ h i, h ▸ b.repr_self i,
λ h, b.ext' (λ i, (b.repr_self i).trans (h i).symm)⟩
lemma apply_eq_iff {b : basis ι R M} {x : M} {i : ι} :
b i = x ↔ b.repr x = finsupp.single i 1 :=
⟨λ h, h ▸ b.repr_self i,
λ h, b.repr.injective ((b.repr_self i).trans h.symm)⟩
/-- An unbundled version of `repr_eq_iff` -/
lemma repr_apply_eq (f : M → ι → R)
(hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x)
(f_eq : ∀ i, f (b i) = finsupp.single i 1) (x : M) (i : ι) :
b.repr x i = f x i :=
begin
let f_i : M →ₗ[R] R :=
{ to_fun := λ x, f x i,
map_add' := λ _ _, by rw [hadd, pi.add_apply],
map_smul' := λ _ _, by { simp [hsmul, pi.smul_apply] } },
have : (finsupp.lapply i) ∘ₗ ↑b.repr = f_i,
{ refine b.ext (λ j, _),
show b.repr (b j) i = f (b j) i,
rw [b.repr_self, f_eq] },
calc b.repr x i = f_i x : by { rw ← this, refl }
... = f x i : rfl
end
/-- Two bases are equal if they assign the same coordinates. -/
lemma eq_of_repr_eq_repr {b₁ b₂ : basis ι R M} (h : ∀ x i, b₁.repr x i = b₂.repr x i) :
b₁ = b₂ :=
have b₁.repr = b₂.repr, by { ext, apply h },
by { cases b₁, cases b₂, simpa }
/-- Two bases are equal if their basis vectors are the same. -/
@[ext] lemma eq_of_apply_eq {b₁ b₂ : basis ι R M} (h : ∀ i, b₁ i = b₂ i) : b₁ = b₂ :=
suffices b₁.repr = b₂.repr, by { cases b₁, cases b₂, simpa },
repr_eq_iff'.mpr (λ i, by rw [h, b₂.repr_self])
end ext
section map
variables (f : M ≃ₗ[R] M')
/-- Apply the linear equivalence `f` to the basis vectors. -/
@[simps] protected def map : basis ι R M' :=
of_repr (f.symm.trans b.repr)
@[simp] lemma map_apply (i) : b.map f i = f (b i) := rfl
end map
section map_coeffs
variables {R' : Type*} [semiring R'] [module R' M] (f : R ≃+* R') (h : ∀ c (x : M), f c • x = c • x)
include f h b
local attribute [instance] has_smul.comp.is_scalar_tower
/-- If `R` and `R'` are isomorphic rings that act identically on a module `M`,
then a basis for `M` as `R`-module is also a basis for `M` as `R'`-module.
See also `basis.algebra_map_coeffs` for the case where `f` is equal to `algebra_map`.
-/
@[simps {simp_rhs := tt}]
def map_coeffs : basis ι R' M :=
begin
letI : module R' R := module.comp_hom R (↑f.symm : R' →+* R),
haveI : is_scalar_tower R' R M :=
{ smul_assoc := λ x y z, begin dsimp [(•)], rw [mul_smul, ←h, f.apply_symm_apply], end },
exact (of_repr $ (b.repr.restrict_scalars R').trans $
finsupp.map_range.linear_equiv (module.comp_hom.to_linear_equiv f.symm).symm )
end
lemma map_coeffs_apply (i : ι) : b.map_coeffs f h i = b i :=
apply_eq_iff.mpr $ by simp [f.to_add_equiv_eq_coe]
@[simp] lemma coe_map_coeffs : (b.map_coeffs f h : ι → M) = b :=
funext $ b.map_coeffs_apply f h
end map_coeffs
section reindex
variables (b' : basis ι' R M')
variables (e : ι ≃ ι')
/-- `b.reindex (e : ι ≃ ι')` is a basis indexed by `ι'` -/
def reindex : basis ι' R M :=
basis.of_repr (b.repr.trans (finsupp.dom_lcongr e))
lemma reindex_apply (i' : ι') : b.reindex e i' = b (e.symm i') :=
show (b.repr.trans (finsupp.dom_lcongr e)).symm (finsupp.single i' 1) =
b.repr.symm (finsupp.single (e.symm i') 1),
by rw [linear_equiv.symm_trans_apply, finsupp.dom_lcongr_symm, finsupp.dom_lcongr_single]
@[simp] lemma coe_reindex : (b.reindex e : ι' → M) = b ∘ e.symm :=
funext (b.reindex_apply e)
@[simp] lemma coe_reindex_repr : ((b.reindex e).repr x : ι' → R) = b.repr x ∘ e.symm :=
funext $ λ i',
show (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (b.repr x) i' = _,
by simp
@[simp] lemma reindex_repr (i' : ι') : (b.reindex e).repr x i' = b.repr x (e.symm i') :=
by rw coe_reindex_repr
@[simp] lemma reindex_refl : b.reindex (equiv.refl ι) = b :=
eq_of_apply_eq $ λ i, by simp
/-- `simp` normal form version of `range_reindex` -/
@[simp] lemma range_reindex' : set.range (b ∘ e.symm) = set.range b :=
by rw [range_comp, equiv.range_eq_univ, set.image_univ]
lemma range_reindex : set.range (b.reindex e) = set.range b :=
by rw [coe_reindex, range_reindex']
/-- `b.reindex_range` is a basis indexed by `range b`, the basis vectors themselves. -/
def reindex_range : basis (range b) R M :=
if h : nontrivial R then
by letI := h; exact b.reindex (equiv.of_injective b (basis.injective b))
else
by letI : subsingleton R := not_nontrivial_iff_subsingleton.mp h; exact
basis.of_repr (module.subsingleton_equiv R M (range b))
lemma finsupp.single_apply_left {α β γ : Type*} [has_zero γ]
{f : α → β} (hf : function.injective f)
(x z : α) (y : γ) :
finsupp.single (f x) y (f z) = finsupp.single x y z :=
by simp [finsupp.single_apply, hf.eq_iff]
lemma reindex_range_self (i : ι) (h := set.mem_range_self i) :
b.reindex_range ⟨b i, h⟩ = b i :=
begin
by_cases htr : nontrivial R,
{ letI := htr,
simp [htr, reindex_range, reindex_apply, equiv.apply_of_injective_symm b.injective,
subtype.coe_mk] },
{ letI : subsingleton R := not_nontrivial_iff_subsingleton.mp htr,
letI := module.subsingleton R M,
simp [reindex_range] }
end
lemma reindex_range_repr_self (i : ι) :
b.reindex_range.repr (b i) = finsupp.single ⟨b i, mem_range_self i⟩ 1 :=
calc b.reindex_range.repr (b i) = b.reindex_range.repr (b.reindex_range ⟨b i, mem_range_self i⟩) :
congr_arg _ (b.reindex_range_self _ _).symm
... = finsupp.single ⟨b i, mem_range_self i⟩ 1 : b.reindex_range.repr_self _
@[simp] lemma reindex_range_apply (x : range b) : b.reindex_range x = x :=
by { rcases x with ⟨bi, ⟨i, rfl⟩⟩, exact b.reindex_range_self i, }
lemma reindex_range_repr' (x : M) {bi : M} {i : ι} (h : b i = bi) :
b.reindex_range.repr x ⟨bi, ⟨i, h⟩⟩ = b.repr x i :=
begin
nontriviality,
subst h,
refine (b.repr_apply_eq (λ x i, b.reindex_range.repr x ⟨b i, _⟩) _ _ _ x i).symm,
{ intros x y,
ext i,
simp only [pi.add_apply, linear_equiv.map_add, finsupp.coe_add] },
{ intros c x,
ext i,
simp only [pi.smul_apply, linear_equiv.map_smul, finsupp.coe_smul] },
{ intros i,
ext j,
simp only [reindex_range_repr_self],
refine @finsupp.single_apply_left _ _ _ _ (λ i, (⟨b i, _⟩ : set.range b)) _ _ _ _,
exact λ i j h, b.injective (subtype.mk.inj h) }
end
@[simp] lemma reindex_range_repr (x : M) (i : ι) (h := set.mem_range_self i) :
b.reindex_range.repr x ⟨b i, h⟩ = b.repr x i :=
b.reindex_range_repr' _ rfl
section fintype
variables [fintype ι]
/-- `b.reindex_finset_range` is a basis indexed by `finset.univ.image b`,
the finite set of basis vectors themselves. -/
def reindex_finset_range : basis (finset.univ.image b) R M :=
b.reindex_range.reindex ((equiv.refl M).subtype_equiv (by simp))
lemma reindex_finset_range_self (i : ι) (h := finset.mem_image_of_mem b (finset.mem_univ i)) :
b.reindex_finset_range ⟨b i, h⟩ = b i :=
by { rw [reindex_finset_range, reindex_apply, reindex_range_apply], refl }
@[simp] lemma reindex_finset_range_apply (x : finset.univ.image b) :
b.reindex_finset_range x = x :=
by { rcases x with ⟨bi, hbi⟩, rcases finset.mem_image.mp hbi with ⟨i, -, rfl⟩,
exact b.reindex_finset_range_self i }
lemma reindex_finset_range_repr_self (i : ι) :
b.reindex_finset_range.repr (b i) =
finsupp.single ⟨b i, finset.mem_image_of_mem b (finset.mem_univ i)⟩ 1 :=
begin
ext ⟨bi, hbi⟩,
rw [reindex_finset_range, reindex_repr, reindex_range_repr_self],
convert finsupp.single_apply_left ((equiv.refl M).subtype_equiv _).symm.injective _ _ _,
refl
end
@[simp] lemma reindex_finset_range_repr (x : M) (i : ι)
(h := finset.mem_image_of_mem b (finset.mem_univ i)) :
b.reindex_finset_range.repr x ⟨b i, h⟩ = b.repr x i :=
by simp [reindex_finset_range]
end fintype
end reindex
protected lemma linear_independent : linear_independent R b :=
linear_independent_iff.mpr $ λ l hl,
calc l = b.repr (finsupp.total _ _ _ b l) : (b.repr_total l).symm
... = 0 : by rw [hl, linear_equiv.map_zero]
protected lemma ne_zero [nontrivial R] (i) : b i ≠ 0 :=
b.linear_independent.ne_zero i
protected lemma mem_span (x : M) : x ∈ span R (range b) :=
by { rw [← b.total_repr x, finsupp.total_apply, finsupp.sum],
exact submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (submodule.subset_span ⟨i, rfl⟩)) }
protected lemma span_eq : span R (range b) = ⊤ :=
eq_top_iff.mpr $ λ x _, b.mem_span x
lemma index_nonempty (b : basis ι R M) [nontrivial M] : nonempty ι :=
begin
obtain ⟨x, y, ne⟩ : ∃ (x y : M), x ≠ y := nontrivial.exists_pair_ne,
obtain ⟨i, _⟩ := not_forall.mp (mt b.ext_elem ne),
exact ⟨i⟩
end
section constr
variables (S : Type*) [semiring S] [module S M']
variables [smul_comm_class R S M']
/-- Construct a linear map given the value at the basis.
This definition is parameterized over an extra `semiring S`,
such that `smul_comm_class R S M'` holds.
If `R` is commutative, you can set `S := R`; if `R` is not commutative,
you can recover an `add_equiv` by setting `S := ℕ`.
See library note [bundled maps over different rings].
-/
def constr : (ι → M') ≃ₗ[S] (M →ₗ[R] M') :=
{ to_fun := λ f, (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f) ∘ₗ ↑b.repr,
inv_fun := λ f i, f (b i),
left_inv := λ f, by { ext, simp },
right_inv := λ f, by { refine b.ext (λ i, _), simp },
map_add' := λ f g, by { refine b.ext (λ i, _), simp },
map_smul' := λ c f, by { refine b.ext (λ i, _), simp } }
theorem constr_def (f : ι → M') :
b.constr S f = (finsupp.total M' M' R id) ∘ₗ ((finsupp.lmap_domain R R f) ∘ₗ ↑b.repr) :=
rfl
theorem constr_apply (f : ι → M') (x : M) :
b.constr S f x = (b.repr x).sum (λ b a, a • f b) :=
by { simp only [constr_def, linear_map.comp_apply, finsupp.lmap_domain_apply, finsupp.total_apply],
rw finsupp.sum_map_domain_index; simp [add_smul] }
@[simp] lemma constr_basis (f : ι → M') (i : ι) :
(b.constr S f : M → M') (b i) = f i :=
by simp [basis.constr_apply, b.repr_self]
lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'}
(h : ∀i, g i = f (b i)) : b.constr S g = f :=
b.ext $ λ i, (b.constr_basis S g i).trans (h i)
lemma constr_self (f : M →ₗ[R] M') : b.constr S (λ i, f (b i)) = f :=
b.constr_eq S $ λ x, rfl
lemma constr_range [nonempty ι] {f : ι → M'} :
(b.constr S f).range = span R (range f) :=
by rw [b.constr_def S f, linear_map.range_comp, linear_map.range_comp, linear_equiv.range,
← finsupp.supported_univ, finsupp.lmap_domain_supported, ←set.image_univ,
← finsupp.span_image_eq_map_total, set.image_id]
@[simp]
lemma constr_comp (f : M' →ₗ[R] M') (v : ι → M') :
b.constr S (f ∘ v) = f.comp (b.constr S v) :=
b.ext (λ i, by simp only [basis.constr_basis, linear_map.comp_apply])
end constr
section equiv
variables (b' : basis ι' R M') (e : ι ≃ ι')
variables [add_comm_monoid M''] [module R M'']
/-- If `b` is a basis for `M` and `b'` a basis for `M'`, and the index types are equivalent,
`b.equiv b' e` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `b' (e i)`. -/
protected def equiv : M ≃ₗ[R] M' :=
b.repr.trans (b'.reindex e.symm).repr.symm
@[simp] lemma equiv_apply : b.equiv b' e (b i) = b' (e i) :=
by simp [basis.equiv]
@[simp] lemma equiv_refl :
b.equiv b (equiv.refl ι) = linear_equiv.refl R M :=
b.ext' (λ i, by simp)
@[simp] lemma equiv_symm : (b.equiv b' e).symm = b'.equiv b e.symm :=
b'.ext' $ λ i, (b.equiv b' e).injective (by simp)
@[simp] lemma equiv_trans {ι'' : Type*} (b'' : basis ι'' R M'')
(e : ι ≃ ι') (e' : ι' ≃ ι'') :
(b.equiv b' e).trans (b'.equiv b'' e') = b.equiv b'' (e.trans e') :=
b.ext' (λ i, by simp)
@[simp]
lemma map_equiv (b : basis ι R M) (b' : basis ι' R M') (e : ι ≃ ι') :
b.map (b.equiv b' e) = b'.reindex e.symm :=
by { ext i, simp }
end equiv
section prod
variables (b' : basis ι' R M')
/-- `basis.prod` maps a `ι`-indexed basis for `M` and a `ι'`-indexed basis for `M'`
to a `ι ⊕ ι'`-index basis for `M × M'`.
For the specific case of `R × R`, see also `basis.fin_two_prod`. -/
protected def prod : basis (ι ⊕ ι') R (M × M') :=
of_repr ((b.repr.prod b'.repr).trans (finsupp.sum_finsupp_lequiv_prod_finsupp R).symm)
@[simp]
lemma prod_repr_inl (x) (i) : (b.prod b').repr x (sum.inl i) = b.repr x.1 i := rfl
@[simp]
lemma prod_repr_inr (x) (i) : (b.prod b').repr x (sum.inr i) = b'.repr x.2 i := rfl
lemma prod_apply_inl_fst (i) :
(b.prod b' (sum.inl i)).1 = b i :=
b.repr.injective $ by
{ ext j,
simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm,
linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self,
equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp],
apply finsupp.single_apply_left sum.inl_injective }
lemma prod_apply_inr_fst (i) :
(b.prod b' (sum.inr i)).1 = 0 :=
b.repr.injective $ by
{ ext i,
simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm,
linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self,
equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero,
finsupp.zero_apply],
apply finsupp.single_eq_of_ne sum.inr_ne_inl }
lemma prod_apply_inl_snd (i) :
(b.prod b' (sum.inl i)).2 = 0 :=
b'.repr.injective $ by
{ ext j,
simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm,
linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self,
equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero,
finsupp.zero_apply],
apply finsupp.single_eq_of_ne sum.inl_ne_inr }
lemma prod_apply_inr_snd (i) :
(b.prod b' (sum.inr i)).2 = b' i :=
b'.repr.injective $ by
{ ext i,
simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm,
linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self,
equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp],
apply finsupp.single_apply_left sum.inr_injective }
@[simp]
lemma prod_apply (i) :
b.prod b' i = sum.elim (linear_map.inl R M M' ∘ b) (linear_map.inr R M M' ∘ b') i :=
by { ext; cases i; simp only [prod_apply_inl_fst, sum.elim_inl, linear_map.inl_apply,
prod_apply_inr_fst, sum.elim_inr, linear_map.inr_apply,
prod_apply_inl_snd, prod_apply_inr_snd, comp_app] }
end prod
section no_zero_smul_divisors
-- Can't be an instance because the basis can't be inferred.
protected lemma no_zero_smul_divisors [no_zero_divisors R] (b : basis ι R M) :
no_zero_smul_divisors R M :=
⟨λ c x hcx, or_iff_not_imp_right.mpr (λ hx, begin
rw [← b.total_repr x, ← linear_map.map_smul] at hcx,
have := linear_independent_iff.mp b.linear_independent (c • b.repr x) hcx,
rw smul_eq_zero at this,
exact this.resolve_right (λ hr, hx (b.repr.map_eq_zero_iff.mp hr))
end)⟩
protected lemma smul_eq_zero [no_zero_divisors R] (b : basis ι R M) {c : R} {x : M} :
c • x = 0 ↔ c = 0 ∨ x = 0 :=
@smul_eq_zero _ _ _ _ _ b.no_zero_smul_divisors _ _
lemma _root_.eq_bot_of_rank_eq_zero [no_zero_divisors R] (b : basis ι R M) (N : submodule R M)
(rank_eq : ∀ {m : ℕ} (v : fin m → N),
linear_independent R (coe ∘ v : fin m → M) → m = 0) :
N = ⊥ :=
begin
rw submodule.eq_bot_iff,
intros x hx,
contrapose! rank_eq with x_ne,
refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩,
rw fintype.linear_independent_iff,
rintros g sum_eq i,
cases i,
simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, finset.univ_unique,
function.comp_const, finset.sum_singleton] at sum_eq,
convert (b.smul_eq_zero.mp sum_eq).resolve_right x_ne
end
end no_zero_smul_divisors
section singleton
/-- `basis.singleton ι R` is the basis sending the unique element of `ι` to `1 : R`. -/
protected def singleton (ι R : Type*) [unique ι] [semiring R] :
basis ι R R :=
of_repr
{ to_fun := λ x, finsupp.single default x,
inv_fun := λ f, f default,
left_inv := λ x, by simp,
right_inv := λ f, finsupp.unique_ext (by simp),
map_add' := λ x y, by simp,
map_smul' := λ c x, by simp }
@[simp] lemma singleton_apply (ι R : Type*) [unique ι] [semiring R] (i) :
basis.singleton ι R i = 1 :=
apply_eq_iff.mpr (by simp [basis.singleton])
@[simp] lemma singleton_repr (ι R : Type*) [unique ι] [semiring R] (x i) :
(basis.singleton ι R).repr x i = x :=
by simp [basis.singleton, unique.eq_default i]
lemma basis_singleton_iff
{R M : Type*} [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M]
(ι : Type*) [unique ι] :
nonempty (basis ι R M) ↔ ∃ x ≠ 0, ∀ y : M, ∃ r : R, r • x = y :=
begin
fsplit,
{ rintro ⟨b⟩,
refine ⟨b default, b.linear_independent.ne_zero _, _⟩,
simpa [span_singleton_eq_top_iff, set.range_unique] using b.span_eq },
{ rintro ⟨x, nz, w⟩,
refine ⟨of_repr $ linear_equiv.symm
{ to_fun := λ f, f default • x,
inv_fun := λ y, finsupp.single default (w y).some,
left_inv := λ f, finsupp.unique_ext _,
right_inv := λ y, _,
map_add' := λ y z, _,
map_smul' := λ c y, _ }⟩,
{ rw [finsupp.add_apply, add_smul] },
{ rw [finsupp.smul_apply, smul_assoc], simp },
{ refine smul_left_injective _ nz _,
simp only [finsupp.single_eq_same],
exact (w (f default • x)).some_spec },
{ simp only [finsupp.single_eq_same],
exact (w y).some_spec } }
end
end singleton
section empty
variables (M)
/-- If `M` is a subsingleton and `ι` is empty, this is the unique `ι`-indexed basis for `M`. -/
protected def empty [subsingleton M] [is_empty ι] : basis ι R M :=
of_repr 0
instance empty_unique [subsingleton M] [is_empty ι] : unique (basis ι R M) :=
{ default := basis.empty M, uniq := λ ⟨x⟩, congr_arg of_repr $ subsingleton.elim _ _ }
end empty
end basis
section fintype
open basis
open fintype
variables [fintype ι] (b : basis ι R M)
/-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`.
-/
def basis.equiv_fun : M ≃ₗ[R] (ι → R) :=
linear_equiv.trans b.repr
({ to_fun := coe_fn,
map_add' := finsupp.coe_add,
map_smul' := finsupp.coe_smul,
..finsupp.equiv_fun_on_fintype } : (ι →₀ R) ≃ₗ[R] (ι → R))
/-- A module over a finite ring that admits a finite basis is finite. -/
def module.fintype_of_fintype [fintype R] : fintype M :=
fintype.of_equiv _ b.equiv_fun.to_equiv.symm
theorem module.card_fintype [fintype R] [fintype M] :
card M = (card R) ^ (card ι) :=
calc card M = card (ι → R) : card_congr b.equiv_fun.to_equiv
... = card R ^ card ι : card_fun
/-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps
a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/
@[simp] lemma basis.equiv_fun_symm_apply (x : ι → R) :
b.equiv_fun.symm x = ∑ i, x i • b i :=
by simp [basis.equiv_fun, finsupp.total_apply, finsupp.sum_fintype]
@[simp]
lemma basis.equiv_fun_apply (u : M) : b.equiv_fun u = b.repr u := rfl
@[simp] lemma basis.map_equiv_fun (f : M ≃ₗ[R] M') :
(b.map f).equiv_fun = f.symm.trans b.equiv_fun :=
rfl
lemma basis.sum_equiv_fun (u : M) : ∑ i, b.equiv_fun u i • b i = u :=
begin
conv_rhs { rw ← b.total_repr u },
simp [finsupp.total_apply, finsupp.sum_fintype, b.equiv_fun_apply]
end
lemma basis.sum_repr (u : M) : ∑ i, b.repr u i • b i = u :=
b.sum_equiv_fun u
@[simp]
lemma basis.equiv_fun_self (i j : ι) : b.equiv_fun (b i) j = if i = j then 1 else 0 :=
by { rw [b.equiv_fun_apply, b.repr_self_apply] }
/-- Define a basis by mapping each vector `x : M` to its coordinates `e x : ι → R`,
as long as `ι` is finite. -/
def basis.of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : basis ι R M :=
basis.of_repr $ e.trans $ linear_equiv.symm $ finsupp.linear_equiv_fun_on_fintype R R ι
@[simp] lemma basis.of_equiv_fun_repr_apply (e : M ≃ₗ[R] (ι → R)) (x : M) (i : ι) :
(basis.of_equiv_fun e).repr x i = e x i := rfl
@[simp] lemma basis.coe_of_equiv_fun (e : M ≃ₗ[R] (ι → R)) :
(basis.of_equiv_fun e : ι → M) = λ i, e.symm (function.update 0 i 1) :=
funext $ λ i, e.injective $ funext $ λ j,
by simp [basis.of_equiv_fun, ←finsupp.single_eq_pi_single, finsupp.single_eq_update]
@[simp] lemma basis.of_equiv_fun_equiv_fun
(v : basis ι R M) : basis.of_equiv_fun v.equiv_fun = v :=
begin
ext j,
simp only [basis.equiv_fun_symm_apply, basis.coe_of_equiv_fun],
simp_rw [function.update_apply, ite_smul],
simp only [finset.mem_univ, if_true, pi.zero_apply, one_smul, finset.sum_ite_eq', zero_smul],
end
variables (S : Type*) [semiring S] [module S M']
variables [smul_comm_class R S M']
@[simp] theorem basis.constr_apply_fintype (f : ι → M') (x : M) :
(b.constr S f : M → M') x = ∑ i, (b.equiv_fun x i) • f i :=
by simp [b.constr_apply, b.equiv_fun_apply, finsupp.sum_fintype]
end fintype
end module
section comm_semiring
namespace basis
variables [comm_semiring R]
variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M']
variables (b : basis ι R M) (b' : basis ι' R M')
/-- If `b` is a basis for `M` and `b'` a basis for `M'`,
and `f`, `g` form a bijection between the basis vectors,
`b.equiv' b' f g hf hg hgf hfg` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `f (b i)`.
-/
def equiv' (f : M → M') (g : M' → M)
(hf : ∀ i, f (b i) ∈ range b') (hg : ∀ i, g (b' i) ∈ range b)
(hgf : ∀i, g (f (b i)) = b i) (hfg : ∀i, f (g (b' i)) = b' i) :
M ≃ₗ[R] M' :=
{ inv_fun := b'.constr R (g ∘ b'),
left_inv :=
have (b'.constr R (g ∘ b')).comp (b.constr R (f ∘ b)) = linear_map.id,
from (b.ext $ λ i, exists.elim (hf i)
(λ i' hi', by rw [linear_map.comp_apply, b.constr_basis, function.comp_apply, ← hi',
b'.constr_basis, function.comp_apply, hi', hgf, linear_map.id_apply])),
λ x, congr_arg (λ (h : M →ₗ[R] M), h x) this,
right_inv :=
have (b.constr R (f ∘ b)).comp (b'.constr R (g ∘ b')) = linear_map.id,
from (b'.ext $ λ i, exists.elim (hg i)
(λ i' hi', by rw [linear_map.comp_apply, b'.constr_basis, function.comp_apply, ← hi',
b.constr_basis, function.comp_apply, hi', hfg, linear_map.id_apply])),
λ x, congr_arg (λ (h : M' →ₗ[R] M'), h x) this,
.. b.constr R (f ∘ b) }
@[simp] lemma equiv'_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι) :
b.equiv' b' f g hf hg hgf hfg (b i) = f (b i) :=
b.constr_basis R _ _
@[simp] lemma equiv'_symm_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι') :
(b.equiv' b' f g hf hg hgf hfg).symm (b' i) = g (b' i) :=
b'.constr_basis R _ _
lemma sum_repr_mul_repr {ι'} [fintype ι'] (b' : basis ι' R M) (x : M) (i : ι) :
∑ (j : ι'), b.repr (b' j) i * b'.repr x j = b.repr x i :=
begin
conv_rhs { rw [← b'.sum_repr x] },
simp_rw [linear_equiv.map_sum, linear_equiv.map_smul, finset.sum_apply'],
refine finset.sum_congr rfl (λ j _, _),
rw [finsupp.smul_apply, smul_eq_mul, mul_comm]
end
end basis
end comm_semiring
section module
open linear_map
variables {v : ι → M}
variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M'']
variables [module R M] [module R M'] [module R M'']
variables {c d : R} {x y : M}
variables (b : basis ι R M)
namespace basis
/--
Any basis is a maximal linear independent set.
-/
lemma maximal [nontrivial R] (b : basis ι R M) : b.linear_independent.maximal :=
λ w hi h,
begin
-- If `range w` is strictly bigger than `range b`,
apply le_antisymm h,
-- then choose some `x ∈ range w \ range b`,
intros x p,
by_contradiction q,
-- and write it in terms of the basis.
have e := b.total_repr x,
-- This then expresses `x` as a linear combination
-- of elements of `w` which are in the range of `b`,
let u : ι ↪ w := ⟨λ i, ⟨b i, h ⟨i, rfl⟩⟩, λ i i' r,
b.injective (by simpa only [subtype.mk_eq_mk] using r)⟩,
have r : ∀ i, b i = u i := λ i, rfl,
simp_rw [finsupp.total_apply, r] at e,
change (b.repr x).sum (λ (i : ι) (a : R), (λ (x : w) (r : R), r • (x : M)) (u i) a) =
((⟨x, p⟩ : w) : M) at e,
rw [←finsupp.sum_emb_domain, ←finsupp.total_apply] at e,
-- Now we can contradict the linear independence of `hi`
refine hi.total_ne_of_not_mem_support _ _ e,
simp only [finset.mem_map, finsupp.support_emb_domain],
rintro ⟨j, -, W⟩,
simp only [embedding.coe_fn_mk, subtype.mk_eq_mk, ←r] at W,
apply q ⟨j, W⟩,
end
section mk
variables (hli : linear_independent R v) (hsp : ⊤ ≤ span R (range v))
/-- A linear independent family of vectors spanning the whole module is a basis. -/
protected noncomputable def mk : basis ι R M :=
basis.of_repr
{ inv_fun := finsupp.total _ _ _ v,
left_inv := λ x, hli.total_repr ⟨x, _⟩,
right_inv := λ x, hli.repr_eq rfl,
.. hli.repr.comp (linear_map.id.cod_restrict _ (λ h, hsp submodule.mem_top)) }
@[simp] lemma mk_repr :
(basis.mk hli hsp).repr x = hli.repr ⟨x, hsp submodule.mem_top⟩ :=
rfl
lemma mk_apply (i : ι) : basis.mk hli hsp i = v i :=
show finsupp.total _ _ _ v _ = v i, by simp
@[simp] lemma coe_mk : ⇑(basis.mk hli hsp) = v :=
funext (mk_apply _ _)
variables {hli hsp}
/-- Given a basis, the `i`th element of the dual basis evaluates to 1 on the `i`th element of the
basis. -/
lemma mk_coord_apply_eq (i : ι) :
(basis.mk hli hsp).coord i (v i) = 1 :=
show hli.repr ⟨v i, submodule.subset_span (mem_range_self i)⟩ i = 1,
by simp [hli.repr_eq_single i]
/-- Given a basis, the `i`th element of the dual basis evaluates to 0 on the `j`th element of the
basis if `j ≠ i`. -/
lemma mk_coord_apply_ne {i j : ι} (h : j ≠ i) :
(basis.mk hli hsp).coord i (v j) = 0 :=
show hli.repr ⟨v j, submodule.subset_span (mem_range_self j)⟩ i = 0,
by simp [hli.repr_eq_single j, h]
/-- Given a basis, the `i`th element of the dual basis evaluates to the Kronecker delta on the
`j`th element of the basis. -/
lemma mk_coord_apply {i j : ι} :
(basis.mk hli hsp).coord i (v j) = if j = i then 1 else 0 :=
begin
cases eq_or_ne j i,
{ simp only [h, if_true, eq_self_iff_true, mk_coord_apply_eq i], },
{ simp only [h, if_false, mk_coord_apply_ne h], },
end
end mk
section span
variables (hli : linear_independent R v)
/-- A linear independent family of vectors is a basis for their span. -/
protected noncomputable def span : basis ι R (span R (range v)) :=
basis.mk (linear_independent_span hli) $
begin
intros x _,
have h₁ : (coe : span R (range v) → M) '' set.range (λ i, subtype.mk (v i) _) = range v,
{ rw ← set.range_comp,
refl },
have h₂ : map (submodule.subtype (span R (range v)))
(span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v),
{ rw [← span_image, submodule.coe_subtype, h₁] },
have h₃ : (x : M) ∈ map (submodule.subtype (span R (range v)))
(span R (set.range (λ i, subtype.mk (v i) _))),
{ rw h₂, apply subtype.mem x },
rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩,
have h_x_eq_y : x = y,
{ rw [subtype.ext_iff, ← hy₂], simp },
rwa h_x_eq_y
end
protected lemma span_apply (i : ι) : (basis.span hli i : M) = v i :=
congr_arg (coe : span R (range v) → M) $ basis.mk_apply (linear_independent_span hli) _ i
end span
lemma group_smul_span_eq_top
{G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M]
[is_scalar_tower G R M] {v : ι → M} (hv : submodule.span R (set.range v) = ⊤) {w : ι → G} :
submodule.span R (set.range (w • v)) = ⊤ :=
begin
rw eq_top_iff,
intros j hj,
rw ← hv at hj,
rw submodule.mem_span at hj ⊢,
refine λ p hp, hj p (λ u hu, _),
obtain ⟨i, rfl⟩ := hu,
have : ((w i)⁻¹ • 1 : R) • w i • v i ∈ p := p.smul_mem ((w i)⁻¹ • 1 : R) (hp ⟨i, rfl⟩),
rwa [smul_one_smul, inv_smul_smul] at this,
end
/-- Given a basis `v` and a map `w` such that for all `i`, `w i` are elements of a group,
`group_smul` provides the basis corresponding to `w • v`. -/
def group_smul {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M]
[is_scalar_tower G R M] [smul_comm_class G R M] (v : basis ι R M) (w : ι → G) :
basis ι R M :=
@basis.mk ι R M (w • v) _ _ _
(v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq).ge
lemma group_smul_apply {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M]
[is_scalar_tower G R M] [smul_comm_class G R M] {v : basis ι R M} {w : ι → G} (i : ι) :
v.group_smul w i = (w • v : ι → M) i :=
mk_apply
(v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq).ge i
lemma units_smul_span_eq_top {v : ι → M} (hv : submodule.span R (set.range v) = ⊤)
{w : ι → Rˣ} : submodule.span R (set.range (w • v)) = ⊤ :=
group_smul_span_eq_top hv
/-- Given a basis `v` and a map `w` such that for all `i`, `w i` is a unit, `smul_of_is_unit`
provides the basis corresponding to `w • v`. -/
def units_smul (v : basis ι R M) (w : ι → Rˣ) :
basis ι R M :=
@basis.mk ι R M (w • v) _ _ _
(v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq).ge
lemma units_smul_apply {v : basis ι R M} {w : ι → Rˣ} (i : ι) :
v.units_smul w i = w i • v i :=
mk_apply
(v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq).ge i
/-- A version of `smul_of_units` that uses `is_unit`. -/
def is_unit_smul (v : basis ι R M) {w : ι → R} (hw : ∀ i, is_unit (w i)):
basis ι R M :=
units_smul v (λ i, (hw i).unit)
lemma is_unit_smul_apply {v : basis ι R M} {w : ι → R} (hw : ∀ i, is_unit (w i)) (i : ι) :
v.is_unit_smul hw i = w i • v i :=
units_smul_apply i
section fin
/-- Let `b` be a basis for a submodule `N` of `M`. If `y : M` is linear independent of `N`
and `y` and `N` together span the whole of `M`, then there is a basis for `M`
whose basis vectors are given by `fin.cons y b`. -/
noncomputable def mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N)
(hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0)
(hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) :
basis (fin (n + 1)) R M :=
have span_b : submodule.span R (set.range (N.subtype ∘ b)) = N,
{ rw [set.range_comp, submodule.span_image, b.span_eq, submodule.map_subtype_top] },
@basis.mk _ _ _ (fin.cons y (N.subtype ∘ b) : fin (n + 1) → M) _ _ _
((b.linear_independent.map' N.subtype (submodule.ker_subtype _)) .fin_cons' _ _ $
by { rintros c ⟨x, hx⟩ hc, rw span_b at hx, exact hli c x hx hc })
(λ x _, by { rw [fin.range_cons, submodule.mem_span_insert', span_b], exact hsp x })
@[simp] lemma coe_mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N)
(hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0)
(hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) :
(mk_fin_cons y b hli hsp : fin (n + 1) → M) = fin.cons y (coe ∘ b) :=
coe_mk _ _
/-- Let `b` be a basis for a submodule `N ≤ O`. If `y ∈ O` is linear independent of `N`
and `y` and `N` together span the whole of `O`, then there is a basis for `O`
whose basis vectors are given by `fin.cons y b`. -/
noncomputable def mk_fin_cons_of_le {n : ℕ} {N O : submodule R M}
(y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O)
(hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0)
(hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) :
basis (fin (n + 1)) R O :=
mk_fin_cons ⟨y, yO⟩ (b.map (submodule.comap_subtype_equiv_of_le hNO).symm)
(λ c x hc hx, hli c x (submodule.mem_comap.mp hc) (congr_arg coe hx))
(λ z, hsp z z.2)
@[simp] lemma coe_mk_fin_cons_of_le {n : ℕ} {N O : submodule R M}
(y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O)
(hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0)
(hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) :
(mk_fin_cons_of_le y yO b hNO hli hsp : fin (n + 1) → O) =
fin.cons ⟨y, yO⟩ (submodule.of_le hNO ∘ b) :=
coe_mk_fin_cons _ _ _ _
/-- The basis of `R × R` given by the two vectors `(1, 0)` and `(0, 1)`. -/
protected def fin_two_prod (R : Type*) [semiring R] : basis (fin 2) R (R × R) :=
basis.of_equiv_fun (linear_equiv.fin_two_arrow R R).symm
@[simp] lemma fin_two_prod_zero (R : Type*) [semiring R] : basis.fin_two_prod R 0 = (1, 0) :=
by simp [basis.fin_two_prod]
@[simp] lemma fin_two_prod_one (R : Type*) [semiring R] : basis.fin_two_prod R 1 = (0, 1) :=
by simp [basis.fin_two_prod]
@[simp] lemma coe_fin_two_prod_repr {R : Type*} [semiring R] (x : R × R) :
⇑((basis.fin_two_prod R).repr x) = ![x.fst, x.snd] :=
rfl
end fin
end basis
end module
section induction
variables [ring R] [is_domain R]
variables [add_comm_group M] [module R M] {b : ι → M}
/-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent
element to a submodule. -/
def submodule.induction_on_rank_aux (b : basis ι R M) (P : submodule R M → Sort*)
(ih : ∀ (N : submodule R M),
(∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N)
(n : ℕ) (N : submodule R M)
(rank_le : ∀ {m : ℕ} (v : fin m → N),
linear_independent R (coe ∘ v : fin m → M) → m ≤ n) :
P N :=
begin
haveI : decidable_eq M := classical.dec_eq M,
have Pbot : P ⊥,
{ apply ih,
intros N N_le x x_mem x_ortho,
exfalso,
simpa using x_ortho 1 0 N.zero_mem },
induction n with n rank_ih generalizing N,
{ suffices : N = ⊥,
{ rwa this },
apply eq_bot_of_rank_eq_zero b _ (λ m v hv, le_zero_iff.mp (rank_le v hv)) },
apply ih,
intros N' N'_le x x_mem x_ortho,
apply rank_ih,
intros m v hli,
refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _),
convert hli.fin_cons' x _ _,
{ ext i, refine fin.cases _ _ i; simp },
{ intros c y hcy,
refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy,
rintros _ ⟨z, rfl⟩,
exact (v z).2 }
end
end induction
section division_ring
variables [division_ring K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V']
variables {v : ι → V} {s t : set V} {x y z : V}
include K
open submodule
namespace basis
section exists_basis
/-- If `s` is a linear independent set of vectors, we can extend it to a basis. -/
noncomputable def extend (hs : linear_independent K (coe : s → V)) :
basis _ K V :=
basis.mk
(@linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ (hs.linear_independent_extend _))
(set_like.coe_subset_coe.mp $ by simpa using hs.subset_span_extend (subset_univ s))
lemma extend_apply_self (hs : linear_independent K (coe : s → V))
(x : hs.extend _) :
basis.extend hs x = x :=
basis.mk_apply _ _ _
@[simp] lemma coe_extend (hs : linear_independent K (coe : s → V)) :
⇑(basis.extend hs) = coe :=
funext (extend_apply_self hs)
lemma range_extend (hs : linear_independent K (coe : s → V)) :
range (basis.extend hs) = hs.extend (subset_univ _) :=
by rw [coe_extend, subtype.range_coe_subtype, set_of_mem_eq]
/-- If `v` is a linear independent family of vectors, extend it to a basis indexed by a sum type. -/
noncomputable def sum_extend (hs : linear_independent K v) :
basis (ι ⊕ _) K V :=
let s := set.range v,
e : ι ≃ s := equiv.of_injective v hs.injective,
b := hs.to_subtype_range.extend (subset_univ (set.range v)) in
(basis.extend hs.to_subtype_range).reindex $ equiv.symm $
calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _)
... ≃ b : equiv.set.sum_diff_subset (hs.to_subtype_range.subset_extend _)
lemma subset_extend {s : set V} (hs : linear_independent K (coe : s → V)) :
s ⊆ hs.extend (set.subset_univ _) :=
hs.subset_extend _
section
variables (K V)
/-- A set used to index `basis.of_vector_space`. -/
noncomputable def of_vector_space_index : set V :=
(linear_independent_empty K V).extend (subset_univ _)
/-- Each vector space has a basis. -/
noncomputable def of_vector_space : basis (of_vector_space_index K V) K V :=
basis.extend (linear_independent_empty K V)
lemma of_vector_space_apply_self (x : of_vector_space_index K V) :
of_vector_space K V x = x :=
basis.mk_apply _ _ _
@[simp] lemma coe_of_vector_space :
⇑(of_vector_space K V) = coe :=
funext (λ x, of_vector_space_apply_self K V x)
lemma of_vector_space_index.linear_independent :
linear_independent K (coe : of_vector_space_index K V → V) :=
by { convert (of_vector_space K V).linear_independent, ext x, rw of_vector_space_apply_self }
lemma range_of_vector_space :
range (of_vector_space K V) = of_vector_space_index K V :=
range_extend _
lemma exists_basis : ∃ s : set V, nonempty (basis s K V) :=
⟨of_vector_space_index K V, ⟨of_vector_space K V⟩⟩
end
end exists_basis
end basis
open fintype
variables (K V)
theorem vector_space.card_fintype [fintype K] [fintype V] :
∃ n : ℕ, card V = (card K) ^ n :=
⟨card (basis.of_vector_space_index K V), module.card_fintype (basis.of_vector_space K V)⟩
section atoms_of_submodule_lattice
variables {K V}
/-- For a module over a division ring, the span of a nonzero element is an atom of the
lattice of submodules. -/
lemma nonzero_span_atom (v : V) (hv : v ≠ 0) : is_atom (span K {v} : submodule K V) :=
begin
split,
{ rw submodule.ne_bot_iff, exact ⟨v, ⟨mem_span_singleton_self v, hv⟩⟩ },
{ intros T hT, by_contra, apply hT.2,
change (span K {v}) ≤ T,
simp_rw [span_singleton_le_iff_mem, ← ne.def, submodule.ne_bot_iff] at *,
rcases h with ⟨s, ⟨hs, hz⟩⟩,
cases (mem_span_singleton.1 (hT.1 hs)) with a ha,
have h : a ≠ 0, by { intro h, rw [h, zero_smul] at ha, exact hz ha.symm },
apply_fun (λ x, a⁻¹ • x) at ha,
simp_rw [← mul_smul, inv_mul_cancel h, one_smul, ha] at *, exact smul_mem T _ hs},
end
/-- The atoms of the lattice of submodules of a module over a division ring are the
submodules equal to the span of a nonzero element of the module. -/
lemma atom_iff_nonzero_span (W : submodule K V) :
is_atom W ↔ ∃ (v : V) (hv : v ≠ 0), W = span K {v} :=
begin
refine ⟨λ h, _, λ h, _ ⟩,
{ cases h with hbot h,
rcases ((submodule.ne_bot_iff W).1 hbot) with ⟨v, ⟨hW, hv⟩⟩,
refine ⟨v, ⟨hv, _⟩⟩,
by_contra heq,
specialize h (span K {v}),
rw [span_singleton_eq_bot, lt_iff_le_and_ne] at h,
exact hv (h ⟨(span_singleton_le_iff_mem v W).2 hW, ne.symm heq⟩) },
{ rcases h with ⟨v, ⟨hv, rfl⟩⟩, exact nonzero_span_atom v hv },
end
/-- The lattice of submodules of a module over a division ring is atomistic. -/
instance : is_atomistic (submodule K V) :=
{ eq_Sup_atoms :=
begin
intro W,
use {T : submodule K V | ∃ (v : V) (hv : v ∈ W) (hz : v ≠ 0), T = span K {v}},
refine ⟨submodule_eq_Sup_le_nonzero_spans W, _⟩,
rintros _ ⟨w, ⟨_, ⟨hw, rfl⟩⟩⟩, exact nonzero_span_atom w hw
end }
end atoms_of_submodule_lattice
end division_ring
section field
variables [field K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V']
variables {v : ι → V} {s t : set V} {x y z : V}
lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V')
(hf_inj : f.ker = ⊥) : ∃g:V' →ₗ[K] V, g.comp f = linear_map.id :=
begin
let B := basis.of_vector_space_index K V,
let hB := basis.of_vector_space K V,
have hB₀ : _ := hB.linear_independent.to_subtype_range,
have : linear_independent K (λ x, x : f '' B → V'),
{ have h₁ : linear_independent K (λ (x : ↥(⇑f '' range (basis.of_vector_space _ _))), ↑x) :=
@linear_independent.image_subtype _ _ _ _ _ _ _ _ _ f hB₀
(show disjoint _ _, by simp [hf_inj]),
rwa [basis.range_of_vector_space K V] at h₁ },
let C := this.extend (subset_univ _),
have BC := this.subset_extend (subset_univ _),
let hC := basis.extend this,
haveI : inhabited V := ⟨0⟩,
refine ⟨hC.constr K (C.restrict (inv_fun f)), hB.ext (λ b, _)⟩,
rw image_subset_iff at BC,
have fb_eq : f b = hC ⟨f b, BC b.2⟩,
{ change f b = basis.extend this _,
rw [basis.extend_apply_self, subtype.coe_mk] },
dsimp [hB],
rw [basis.of_vector_space_apply_self, fb_eq, hC.constr_basis],
exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _
end
lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q :=
let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
instance module.submodule.complemented_lattice : complemented_lattice (submodule K V) :=
⟨submodule.exists_is_compl⟩
lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V')
(hf_surj : f.range = ⊤) : ∃g:V' →ₗ[K] V, f.comp g = linear_map.id :=
begin
let C := basis.of_vector_space_index K V',
let hC := basis.of_vector_space K V',
haveI : inhabited V := ⟨0⟩,
use hC.constr K (C.restrict (inv_fun f)),
refine hC.ext (λ c, _),
rw [linear_map.comp_apply, hC.constr_basis],
simp [right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c]
end
/-- Any linear map `f : p →ₗ[K] V'` defined on a subspace `p` can be extended to the whole
space. -/
lemma linear_map.exists_extend {p : submodule K V} (f : p →ₗ[K] V') :
∃ g : V →ₗ[K] V', g.comp p.subtype = f :=
let ⟨g, hg⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in
⟨f.comp g, by rw [linear_map.comp_assoc, hg, f.comp_id]⟩
open submodule linear_map
/-- If `p < ⊤` is a subspace of a vector space `V`, then there exists a nonzero linear map
`f : V →ₗ[K] K` such that `p ≤ ker f`. -/
lemma submodule.exists_le_ker_of_lt_top (p : submodule K V) (hp : p < ⊤) :
∃ f ≠ (0 : V →ₗ[K] K), p ≤ ker f :=
begin
rcases set_like.exists_of_lt hp with ⟨v, -, hpv⟩, clear hp,
rcases (linear_pmap.sup_span_singleton ⟨p, 0⟩ v (1 : K) hpv).to_fun.exists_extend with ⟨f, hf⟩,
refine ⟨f, _, _⟩,
{ rintro rfl, rw [linear_map.zero_comp] at hf,
have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv 0 p.zero_mem 1,
simpa using (linear_map.congr_fun hf _).trans this },
{ refine λ x hx, mem_ker.2 _,
have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv x hx 0,
simpa using (linear_map.congr_fun hf _).trans this }
end
theorem quotient_prod_linear_equiv (p : submodule K V) :
nonempty (((V ⧸ p) × p) ≃ₗ[K] V) :=
let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $
((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans
(prod_equiv_of_is_compl q p hq.symm)
end field
|
2398ef39f535845d11dbeb462c4f6e7536fba725 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/matrix/hadamard.lean | b93f500f0de783819d76318a915773b2c3dfb380 | [
"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 | 3,409 | lean | /-
Copyright (c) 2021 Lu-Ming Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lu-Ming Zhang
-/
import linear_algebra.matrix.trace
/-!
# Hadamard product of matrices
This file defines the Hadamard product `matrix.hadamard`
and contains basic properties about them.
## Main definition
- `matrix.hadamard`: defines the Hadamard product,
which is the pointwise product of two matrices of the same size.
## Notation
* `⊙`: the Hadamard product `matrix.hadamard`;
## References
* <https://en.wikipedia.org/wiki/hadamard_product_(matrices)>
## Tags
hadamard product, hadamard
-/
variables {α β γ m n : Type*}
variables {R : Type*}
namespace matrix
open_locale matrix big_operators
/-- `matrix.hadamard` defines the Hadamard product,
which is the pointwise product of two matrices of the same size.-/
@[simp]
def hadamard [has_mul α] (A : matrix m n α) (B : matrix m n α) : matrix m n α
| i j := A i j * B i j
localized "infix (name := matrix.hadamard) ` ⊙ `:100 := matrix.hadamard" in matrix
section basic_properties
variables (A : matrix m n α) (B : matrix m n α) (C : matrix m n α)
/- commutativity -/
lemma hadamard_comm [comm_semigroup α] : A ⊙ B = B ⊙ A :=
ext $ λ _ _, mul_comm _ _
/- associativity -/
lemma hadamard_assoc [semigroup α] : A ⊙ B ⊙ C = A ⊙ (B ⊙ C) :=
ext $ λ _ _, mul_assoc _ _ _
/- distributivity -/
lemma hadamard_add [distrib α] : A ⊙ (B + C) = A ⊙ B + A ⊙ C :=
ext $ λ _ _, left_distrib _ _ _
lemma add_hadamard [distrib α] : (B + C) ⊙ A = B ⊙ A + C ⊙ A :=
ext $ λ _ _, right_distrib _ _ _
/- scalar multiplication -/
section scalar
@[simp] lemma smul_hadamard [has_mul α] [has_smul R α] [is_scalar_tower R α α] (k : R) :
(k • A) ⊙ B = k • A ⊙ B :=
ext $ λ _ _, smul_mul_assoc _ _ _
@[simp] lemma hadamard_smul [has_mul α] [has_smul R α] [smul_comm_class R α α] (k : R):
A ⊙ (k • B) = k • A ⊙ B :=
ext $ λ _ _, mul_smul_comm _ _ _
end scalar
section zero
variables [mul_zero_class α]
@[simp] lemma hadamard_zero : A ⊙ (0 : matrix m n α) = 0 :=
ext $ λ _ _, mul_zero _
@[simp] lemma zero_hadamard : (0 : matrix m n α) ⊙ A = 0 :=
ext $ λ _ _, zero_mul _
end zero
section one
variables [decidable_eq n] [mul_zero_one_class α]
variables (M : matrix n n α)
lemma hadamard_one : M ⊙ (1 : matrix n n α) = diagonal (λ i, M i i) :=
by { ext, by_cases h : i = j; simp [h] }
lemma one_hadamard : (1 : matrix n n α) ⊙ M = diagonal (λ i, M i i) :=
by { ext, by_cases h : i = j; simp [h] }
end one
section diagonal
variables [decidable_eq n] [mul_zero_class α]
lemma diagonal_hadamard_diagonal (v : n → α) (w : n → α) :
diagonal v ⊙ diagonal w = diagonal (v * w) :=
ext $ λ _ _, (apply_ite2 _ _ _ _ _ _).trans (congr_arg _ $ zero_mul 0)
end diagonal
section trace
variables [fintype m] [fintype n]
variables (R) [semiring α] [semiring R] [module R α]
lemma sum_hadamard_eq : ∑ (i : m) (j : n), (A ⊙ B) i j = trace (A ⬝ Bᵀ) :=
rfl
lemma dot_product_vec_mul_hadamard [decidable_eq m] [decidable_eq n] (v : m → α) (w : n → α) :
dot_product (vec_mul v (A ⊙ B)) w = trace (diagonal v ⬝ A ⬝ (B ⬝ diagonal w)ᵀ) :=
begin
rw [←sum_hadamard_eq, finset.sum_comm],
simp [dot_product, vec_mul, finset.sum_mul, mul_assoc],
end
end trace
end basic_properties
end matrix
|
363d58dd117ddb9ed8987e990710d5c87c1dc349 | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/data/finsupp.lean | 57743f72ad10ceda6dd49f32a4a3e7e75c1e0b65 | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 71,380 | 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, Scott Morrison
-/
import algebra.module
import data.fintype.card
import data.multiset.antidiagonal
/-!
# Type of functions with finite support
For any type `α` and a type `β` with zero, we define the type `finsupp α β` of finitely supported
functions from `α` to `β`, i.e. the functions which are zero everywhere on `α` except on a finite
set. We write this in infix notation as `α →₀ β`.
Functions with finite support provide the basis for the following concrete instances:
* `ℕ →₀ α`: Polynomials (where `α` is a ring)
* `(σ →₀ ℕ) →₀ α`: Multivariate Polynomials (again `α` is a ring, and `σ` are variable names)
* `α →₀ ℕ`: Multisets
* `α →₀ ℤ`: Abelian groups freely generated by `α`
* `β →₀ α`: Linear combinations over `β` where `α` is the scalar ring
Most of the theory assumes that the range is a commutative monoid. This gives us the big sum
operator as a powerful way to construct `finsupp` elements.
A general piece of advice is to not use `α →₀ β` directly, as the type class setup might not be a
good fit. Defining a copy and selecting the instances that are best suited for the application works
better.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
## Notation
This file defines `α →₀ β` as notation for `finsupp α β`.
-/
noncomputable theory
open_locale classical big_operators
open finset
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*}
{α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
/-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (β : Type*) [has_zero β] :=
(support : finset α)
(to_fun : α → β)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infixr ` →₀ `:25 := finsupp
namespace finsupp
/-! ### Basic declarations about `finsupp` -/
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, to_fun⟩
instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 :=
rfl
@[simp] lemma support_zero : (0 : α →₀ β).support = ∅ :=
rfl
instance : inhabited (α →₀ β) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 :=
not_iff_comm.1 mem_support_iff.symm
@[ext]
lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
have : f = g, { funext a, exact h a },
subst this,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
@[simp] lemma support_eq_empty {f : α →₀ β} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext_iff.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
instance finsupp.decidable_eq [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a))
⟨assume ⟨h₁, h₂⟩, ext $ assume a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, by rwa [mem_support_iff, not_not] at h,
have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h,
by rw [hf, hg],
by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩
lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} :=
⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ β} :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
/-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`.
(All functions on a finite type are finitely supported.) -/
def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ,
iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
/-! ### Declarations about `single` -/
section single
variables [has_zero β] {a a' : α} {b : β}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : β) : α →₀ β :=
⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 :=
rfl
@[simp] lemma single_eq_same : (single a b : α →₀ β) a = b :=
if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 :=
if_neg h
@[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, single_eq_same, zero_apply] },
{ rw [single_eq_of_ne h, zero_apply] }
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma single_injective (a : α) : function.injective (single a : β → α →₀ β) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) :=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (single_injective a₂).eq_iff] at eq },
{ rw [ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
lemma single_left_inj (h : b ≠ 0) :
single a b = single a' b ↔ a = a' :=
⟨λ H, by simpa only [h, single_eq_single_iff,
and_false, or_false, eq_self_iff_true, and_true] using H,
λ H, by rw [H]⟩
lemma single_eq_zero : single a b = 0 ↔ b = 0 :=
⟨λ h, by { rw ext_iff at h, simpa only [single_eq_same, zero_apply] using h a },
λ h, by rw [h, single_zero]⟩
lemma single_swap {α β : Type*} [has_zero β] (a₁ a₂ : α) (b : β) :
(single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ :=
by simp only [single_apply]; ac_refl
lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) :=
by ext i; simp only [unique.eq_default i, single_eq_same]
@[simp] lemma unique_single_eq_iff [unique α] {b' : β} :
single a b = single a' b' ↔ b = b' :=
begin
rw [single_eq_single_iff],
split,
{ rintros (⟨_, rfl⟩ | ⟨rfl, rfl⟩); refl },
{ intro h, left, exact ⟨subsingleton.elim _ _, h⟩ }
end
end single
/-! ### Declarations about `on_finset` -/
section on_finset
variables [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`.
The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways,
otherwise a better set representation is often available. -/
def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β :=
⟨s.filter (λa, f a ≠ 0), f,
assume a, classical.by_cases
(assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩)
(assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} :
(on_finset s f hf : α →₀ β) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} :
(on_finset s f hf).support ⊆ s :=
filter_subset _
end on_finset
/-! ### Declarations about `map_range` -/
section map_range
variables [has_zero β₁] [has_zero β₂]
/-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is
`map_range f hf g : α →₀ β₂`, well-defined when `f 0 = 0`. -/
def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 :=
ext $ λ a, by simp only [hf, zero_apply, map_range_apply]
lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
@[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} :
map_range f hf (single a b) = single a (f b) :=
ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
/-! ### Declarations about `emb_domain` -/
section emb_domain
variables [has_zero β]
/-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `f a : α₂` is `v a`.
For a `b : α₂` outside the range of `f`, it is zero. -/
def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) },
{ assume a₂,
split_ifs,
{ simp only [h, true_iff, ne.def],
rw [← not_mem_support_iff, not_not],
apply finset.choose_mem },
{ simp only [h, ne.def, ne_self_iff_false] } }
end
lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
(emb_domain f v).support = v.support.map f :=
rfl
lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 :=
rfl
lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α₁ → β) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} :
emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ :=
⟨λ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a),
λ h, by rw h⟩
lemma emb_domain_map_range
{β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂]
(f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
lemma single_of_emb_domain_single
(l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0)
(h : l.emb_domain f = single a b) :
∃ x, l = single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = {a},
by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp only [h_map_support, finset.mem_singleton],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp only [eq.symm h_cases, hc₂, single_eq_same] },
{ rw [single_apply, single_apply, if_neg, if_neg h_cases],
by_contra hfd,
exact h_cases (f.injective (hc₂.trans hfd)) } },
{ exact hc₂ }
end
end emb_domain
/-! ### Declarations about `zip_with` -/
section zip_with
variables [has_zero β] [has_zero β₁] [has_zero β₂]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/
def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H,
begin
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) :=
rfl
lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
/-! ### Declarations about `erase` -/
section erase
/-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to
`0`. -/
def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
@[simp] lemma erase_single [has_zero β] {a : α} {b : β} : (erase a (single a b)) = 0 := begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same], refl },
{ rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) }
end
lemma erase_single_ne [has_zero β] {a a' : α} {b : β} (h : a ≠ a') : (erase a (single a' b)) = single a' b :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same, single_eq_of_ne (h.symm)] },
{ rw [erase_ne hs] }
end
end erase
/-!
### Declarations about `sum` and `prod`
In most of this section, the domain `β` is assumed to be an `add_monoid`.
-/
-- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
∑ a in f.support, g a (f a)
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive]
def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
∏ a in f.support, g a (f a)
@[to_additive]
lemma prod_fintype [fintype α] [has_zero β] [comm_monoid γ]
(f : α →₀ β) (g : α → β → γ) (h : ∀ i, g i 0 = 1) :
f.prod g = ∏ i, g i (f i) :=
begin
classical,
rw [finsupp.prod, ← fintype.prod_extend_by_one, finset.prod_congr rfl],
intros i hi,
split_ifs with hif hif,
{ refl },
{ rw finsupp.not_mem_support_iff at hif,
rw [hif, h] }
end
@[to_additive]
lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ]
{f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) :
(map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[to_additive]
lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} :
(0 : α →₀ β).prod h = 1 :=
rfl
@[to_additive]
lemma prod_comm {α' : Type*} [has_zero β] {β' : Type*} [has_zero β'] (f : α →₀ β) (g : α' →₀ β')
[comm_monoid γ] (h : α → β → α' → β' → γ) :
f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) :=
begin
dsimp [finsupp.prod],
rw finset.prod_comm,
end
@[simp, to_additive]
lemma prod_ite_eq [has_zero β] [comm_monoid γ] (f : α →₀ β) (a : α) (b : α → β → γ) :
f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, }
/-- A restatement of `prod_ite_eq` with the equality test reversed. -/
@[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."]
lemma prod_ite_eq' [has_zero β] [comm_monoid γ] (f : α →₀ β) (a : α) (b : α → β → γ) :
f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', }
@[simp] lemma prod_pow [fintype α] [comm_monoid γ] (f : α →₀ ℕ) (g : α → γ) :
f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) :=
begin
apply prod_subset (finset.subset_univ _),
intros a _ ha,
simp only [finsupp.not_mem_support_iff.mp ha, pow_zero]
end
section add_monoid
variables [add_monoid β]
@[to_additive]
lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
begin
by_cases h : b = 0,
{ simp only [h, h_zero, single_zero]; refl },
{ simp only [finsupp.prod, support_single_ne_zero h, prod_singleton, single_eq_same] }
end
instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a :=
rfl
lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) :
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ β) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
/-- Evaluation of a function `f : α →₀ β` at a point as an additive monoid homomorphism. -/
def eval_add_hom (a : α) : (α →₀ β) →+ β := ⟨λ g, g a, zero_apply, λ _ _, add_apply⟩
@[simp] lemma eval_add_hom_apply (a : α) (g : α →₀ β) : eval_add_hom a g = g a := rfl
lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[simp] lemma erase_add (a : α) (f f' : α →₀ β) : erase a (f + f') = erase a f + erase a f' :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] },
rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply],
end
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma map_range_add [add_monoid β₁] [add_monoid β₂]
{f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
ext $ λ a, by simp only [hf', add_apply, map_range_apply]
end add_monoid
section nat_sub
instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩
@[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} :
(g₁ - g₂) a = g₁ a - g₂ a :=
rfl
@[simp] lemma single_sub {a : α} {n₁ n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ :=
begin
ext f,
by_cases h : (a = f),
{ rw [h, nat_sub_apply, single_eq_same, single_eq_same, single_eq_same] },
rw [nat_sub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h]
end
-- These next two lemmas are used in developing
-- the partial derivative on `mv_polynomial`.
lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) :
u - single a 1 + u' = u + u' - single a 1 :=
begin
ext b,
rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply],
by_cases h : a = b,
{ rw [←h, single_eq_same], cases (u a), { contradiction }, { simp }, },
{ simp [h], }
end
lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) :
u + (u' - single a 1) = u + u' - single a 1 :=
begin
ext b,
rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply],
by_cases h : a = b,
{ rw [←h, single_eq_same], cases (u' a), { contradiction }, { simp }, },
{ simp [h], }
end
end nat_sub
instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group β] : add_group (α →₀ β) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
lemma single_multiset_sum [add_comm_monoid β] (s : multiset β) (a : α) :
single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid β] (s : finset γ) (f : γ → β) (a : α) :
single a (∑ b in s, f b) = ∑ b in s, single a (f b) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero γ] [add_comm_monoid β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) :
single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive]
lemma prod_neg_index [add_group β] [comm_monoid γ]
{g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a :=
rfl
@[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a :=
rfl
@[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
instance [add_comm_group β] : add_comm_group (α →₀ β) :=
{ add_comm := add_comm, ..finsupp.add_group }
@[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(eval_add_hom a₂ : (α →₀ β) →+ _).map_sum _ _
lemma support_sum [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 →
(∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop]
using this
@[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} :
f.sum (λa b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h :=
f.support.sum_hom (@has_neg.neg γ _)
@[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl
@[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) :
f.sum single = f :=
have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) =
∑ a' in {a}, ite (a' = a) (f a') 0,
begin
intro a,
by_cases h : a ∈ f.support,
{ have : ({a} : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, mem_singleton, forall_eq] },
refine (finset.sum_subset this (λ _ _ H, _)).symm,
exact if_neg (mt mem_singleton.2 H) },
{ transitivity (∑ a in f.support, (0 : β)),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, sum_singleton, if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this, sum_singleton, if_pos]
@[to_additive]
lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : ∏ a in f.support ∪ g.support, h a (f a) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
have g_eq : ∏ a in f.support ∪ g.support, h a (g a) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
calc ∏ a in (f + g).support, h a ((f + g) a) =
∏ a in f.support ∪ g.support, h a ((f + g) a) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (∏ a in f.support ∪ g.support, h a (f a)) *
(∏ a in f.support ∪ g.support, h a (g a)) :
by simp only [add_apply, h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀a, h a 0 = 0,
from assume a,
have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0,
by simpa only [sub_self] using this,
have h_neg : ∀a b, h a (- b) = - h a b,
from assume a b,
have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b,
by simpa only [h_zero, zero_sub] using this,
have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂,
from assume a b₁ b₂,
have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂),
by simpa only [h_neg, sub_neg_eq_add] using this,
calc (f - g).sum h = (f + - g).sum h : rfl
... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero,
h_neg, sum_neg]
... = f.sum h - g.sum h : rfl
@[to_additive]
lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ]
{s : finset ι} {g : ι → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
∏ i in s, (g i).prod h = (∑ i in s, g i).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive]
lemma prod_sum_index
[add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[add_comm_monoid β] [add_comm_monoid γ]
(f : multiset (α →₀ β)) (h : α → β → γ)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(f.support.sum_hom _).symm
lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(f.support.sum_hom multiset.sum).symm
section map_range
variables
[add_comm_monoid β₁] [add_comm_monoid β₂]
(f : β₁ →+ β₂)
/--
Composition with a fixed additive homomorphism is itself an additive homomorphism on functions.
-/
def map_range.add_monoid_hom : (α →₀ β₁) →+ (α →₀ β₂) :=
{ to_fun := (map_range f f.map_zero : (α →₀ β₁) → (α →₀ β₂)),
map_zero' := map_range_zero,
map_add' := λ a b, map_range_add f.map_add _ _ }
lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) :
map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum :=
(m.sum_hom (map_range.add_monoid_hom f)).symm
lemma map_range_finset_sum {ι : Type*} (s : finset ι) (g : ι → (α →₀ β₁)) :
map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
/-! ### Declarations about `map_domain` -/
section map_domain
variables [add_comm_monoid β] {v v₁ v₂ : α →₀ β}
/-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `a : α₂` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ simp only [(∉), (≠), not_not, mem_support_iff],
assume h,
rw [h, single_zero],
refl }
end
lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v :=
sum_single _
lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) :=
sum_zero_index
lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} :
map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → α₂} {s : α →₀ β} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive]
lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β}
{h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
emb_domain f v = map_domain f v :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply f.injective, emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
lemma map_domain_injective {f : α₁ → α₂} (hf : function.injective f) :
function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
end map_domain
/-! ### Declarations about `comap_domain` -/
section comap_domain
/-- Given `f : α₁ → α₂`, `l : α₂ →₀ γ` and a proof `hf` that `f` is injective on
the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function
from `α₁` to `γ` given by composing `l` with `f`. -/
def comap_domain {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α₁ →₀ γ :=
{ support := l.support.preimage hf,
to_fun := (λ a, l (f a)),
mem_support_to_fun :=
begin
intros a,
simp only [finset.mem_def.symm, finset.mem_preimage],
exact l.mem_support_to_fun (f a),
end }
@[simp]
lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α₁) :
comap_domain f l hf a = l (f a) :=
rfl
lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ)
(hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) :
(comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g :=
begin
simp [sum],
simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ (x : α₂), g x (l x))]
end
lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) :
comap_domain f l hf.inj_on = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage],
assume h a ha,
cases hf.2.2 ha with b hb,
exact h b (hb.2.symm ▸ ha)
end
lemma map_domain_comap_domain {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ)
(hf : function.injective f) (hl : ↑l.support ⊆ set.range f):
map_domain f (comap_domain f l (hf.inj_on _)) = l :=
begin
ext a,
by_cases h_cases: a ∈ set.range f,
{ rcases set.mem_range.1 h_cases with ⟨b, hb⟩,
rw [hb.symm, map_domain_apply hf, comap_domain_apply] },
{ rw map_domain_notin_range _ _ h_cases,
by_contra h_contr,
apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) }
end
end comap_domain
/-! ### Declarations about `filter` -/
section filter
section has_zero
variables [has_zero β] (p : α → Prop) (f : α →₀ β)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) (f : α →₀ β) : α →₀ β :=
on_finset f.support (λa, if p a then f a else 0) $ λ a H,
mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p :=
finset.ext $ assume a, if H : p a
then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true]
else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def,
ne_self_iff_false]
lemma filter_zero : (0 : α →₀ β).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : β} (h : p a) : (single a b).filter p = single a b :=
ext $ λ x, begin
by_cases h' : p x,
{ simp only [h', filter_apply_pos] },
{ simp only [h', filter_apply_neg, not_false_iff],
rw single_eq_of_ne, rintro rfl, exact h' h }
end
@[simp] lemma filter_single_of_neg
{a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 :=
ext $ λ x, begin
by_cases h' : p x,
{ simp only [h', filter_apply_pos, zero_apply], rw single_eq_of_ne, rintro rfl, exact h h' },
{ simp only [h', finsupp.zero_apply, not_false_iff, filter_apply_neg] }
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
ext $ assume a, if H : p a
then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero]
else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add]
end filter
/-! ### Declarations about `frange` -/
section frange
variables [has_zero β]
/-- `frange f` is the image of `f` on the support of `f`. -/
def frange (f : α →₀ β) : finset β := finset.image f f.support
theorem mem_frange {f : α →₀ β} {y : β} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
/-! ### Declarations about `subtype_domain` -/
section subtype_domain
variables {α' : Type*} [has_zero δ] {p : α → Prop}
section zero
variables [has_zero β] {v v' : α' →₀ β}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) (f : α →₀ β) : (subtype p →₀ β) :=
⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ β} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 :=
rfl
@[to_additive]
lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β}
{h : α → β → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_add {v v' : α →₀ β} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom :
is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma filter_add {v v' : α →₀ β} :
(v + v').filter p = v.filter p + v'.filter p :=
ext $ λ a, begin
by_cases p a,
{ simp only [h, filter_apply_pos, add_apply] },
{ simp only [h, add_zero, add_apply, not_false_iff, filter_apply_neg] }
end
instance filter.is_add_monoid_hom (p : α → Prop) :
is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) :=
{ map_zero := filter_zero p, map_add := λ x y, filter_add }
end monoid
section comm_monoid
variables [add_comm_monoid β]
lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} :
(∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p :=
eq.symm (s.sum_hom _)
lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset γ) (f : γ → α →₀ β) :
(∑ a in s, f a).filter p = ∑ a in s, filter p (f a) :=
(s.sum_hom (filter p)).symm
end comm_monoid
section group
variables [add_group β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_neg {v : α →₀ β} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub {v v' : α →₀ β} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
/-! ### Declarations relating `finsupp` to `multiset` -/
section multiset
/-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of
`f` on the elements of `α`. -/
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, n •ℕ {a})
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
sum_add_index (assume a, zero_nsmul _) (assume a b₁ b₂, add_nsmul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n •ℕ {a} :=
by rw [to_multiset, sum_single_index]; apply zero_nsmul
instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) :=
{ map_zero := to_multiset_zero, map_add := to_multiset_add }
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.card_zero, sum_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single,
sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton,
multiset.card_singleton, mul_one]; intros; refl }
end
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_nsmul (multiset.map g)],
refl }
end
lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint.mono_left support_single_subset _,
rwa [finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (n •ℕ {x} : multiset α).count a) :
(f.support.sum_hom $ multiset.count a).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl
... = f a * (a :: 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
/-- Given `m : multiset α`, `of_multiset m` is the finitely supported function from `α` to `ℕ`
given by the multiplicities of the elements of `α` in `m`. -/
def of_multiset (m : multiset α) : α →₀ ℕ :=
on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $
by_contradiction (mt multiset.count_eq_zero.2 H)
@[simp] lemma of_multiset_apply (m : multiset α) (a : α) :
of_multiset m a = m.count a :=
rfl
/-- `equiv_multiset` defines an `equiv` between finitely supported functions
from `α` to `ℕ` and multisets on `α`. -/
def equiv_multiset : (α →₀ ℕ) ≃ (multiset α) :=
⟨ to_multiset, of_multiset,
assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset],
assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩
lemma mem_support_multiset_sum [add_comm_monoid β]
{s : multiset (α →₀ β)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [add_comm_monoid β]
{s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃c∈s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
lemma mem_support_single [has_zero β] (a a' : α) (b : β) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
⟨λ H : (a ∈ ite _ _ _), if h : b = 0
then by rw if_pos h at H; exact H.elim
else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩,
λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩
end multiset
/-! ### Declarations about `curry` and `uncurry` -/
section curry_uncurry
/-- Given a finitely supported function `f` from a product type `α × β` to `γ`,
`curry f` is the "curried" finitely supported function from `α` to the type of
finitely supported functions from `β` to `γ`. -/
protected def curry [add_comm_monoid γ]
(f : (α × β) →₀ γ) : α →₀ (β →₀ γ) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index
[add_comm_monoid γ] [add_comm_monoid δ]
(f : (α × β) →₀ γ) (g : α → β → γ → δ)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
/-- Given a finitely supported function `f` from `α` to the type of
finitely supported functions from `β` to `γ`,
`uncurry f` is the "uncurried" finitely supported function from `α × β` to `γ`. -/
protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
/-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ γ)` and `(α →₀ (β →₀ γ))` given by
currying and uncurrying. -/
def finsupp_prod_equiv [add_comm_monoid γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) (p : α₁ → Prop) :
(f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum,
@filter_sum _ (α₂ →₀ β) _ p _ f.support _],
rw [support_filter, sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
variables [group γ] [mul_action γ α] [add_comm_monoid β]
/--
Scalar multiplication by a group element g,
given by precomposition with the action of g⁻¹ on the domain.
-/
def comap_has_scalar : has_scalar γ (α →₀ β) :=
{ smul := λ g f, f.comap_domain (λ a, g⁻¹ • a)
(λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) }
local attribute [instance] comap_has_scalar
/--
Scalar multiplication by a group element,
given by precomposition with the action of g⁻¹ on the domain,
is multiplicative in g.
-/
def comap_mul_action : mul_action γ (α →₀ β) :=
{ one_smul := λ f, by { ext, dsimp [(•)], simp, },
mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, }
local attribute [instance] comap_mul_action
/--
Scalar multiplication by a group element,
given by precomposition with the action of g⁻¹ on the domain,
is additive in the second argument.
-/
def comap_distrib_mul_action :
distrib_mul_action γ (α →₀ β) :=
{ smul_zero := λ g, by { ext, dsimp [(•)], simp, },
smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, }
/--
Scalar multiplication by a group element on finitely supported functions on a group,
given by precomposition with the action of g⁻¹. -/
def comap_distrib_mul_action_self :
distrib_mul_action γ (γ →₀ β) :=
@finsupp.comap_distrib_mul_action γ β γ _ (mul_action.regular γ) _
@[simp]
lemma comap_smul_single (g : γ) (a : α) (b : β) :
g • single a b = single (g • a) b :=
begin
ext a',
dsimp [(•)],
by_cases h : g • a = a',
{ subst h, simp [←mul_smul], },
{ simp [single_eq_of_ne h], rw [single_eq_of_ne],
rintro rfl, simpa [←mul_smul] using h, }
end
@[simp]
lemma comap_smul_apply (g : γ) (f : α →₀ β) (a : α) :
(g • f) a = f (g⁻¹ • a) := rfl
end
section
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) :=
⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
variables (α β)
@[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) :=
rfl
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) :=
{ smul := (•),
smul_add := λ a x y, ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, ext $ λ _, add_smul _ _ _,
one_smul := λ x, ext $ λ _, one_smul _ _,
mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, ext $ λ _, zero_smul _ _,
smul_zero := λ x, ext $ λ _, smul_zero _ }
variables {α β} (γ)
/-- Evaluation at point as a linear map. This version assumes that the codomain is a semimodule
over some semiring. See also `leval`. -/
def leval' [semiring γ] [add_comm_monoid β] [semimodule γ β] (a : α) :
(α →₀ β) →ₗ[γ] β :=
⟨λ g, g a, λ _ _, add_apply, λ _ _, rfl⟩
@[simp] lemma coe_leval' [semiring γ] [add_comm_monoid β] [semimodule γ β] (a : α) (g : α →₀ β) :
leval' γ a g = g a :=
rfl
variable {γ}
/-- Evaluation at point as a linear map. This version assumes that the codomain is a semiring. -/
def leval [semiring β] (a : α) : (α →₀ β) →ₗ[β] β := leval' β a
@[simp] lemma coe_leval [semiring β] (a : α) (g : α →₀ β) : leval a g = g a := rfl
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp only [smul_apply', mem_support_iff, ne.def]; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {α' : Type*} [has_zero δ] {p : α → Prop}
@[simp] lemma filter_smul {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p :=
ext $ λ a, begin
by_cases p a,
{ simp only [h, smul_apply', filter_apply_pos] },
{ simp only [h, smul_apply', not_false_iff, filter_apply_neg, smul_zero] }
end
end
lemma map_domain_smul {α'} {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] },
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
(c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) :=
ext $ λ a', by by_cases a = a';
[{ subst h, simp only [smul_apply', single_eq_same] },
simp only [h, smul_apply', ne.def, not_false_iff, single_eq_of_ne, smul_zero]]
@[simp] lemma smul_single' {R : semiring γ}
(c : γ) (a : α) (b : γ) : c • finsupp.single a b = finsupp.single a (c * b) :=
smul_single _ _ _
end
@[simp] lemma smul_apply [semiring β] {a : α} {b : β} {v : α →₀ β} :
(b • v) a = b • (v a) :=
rfl
lemma sum_smul_index [semiring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
lemma sum_smul_index' [semiring β] [add_comm_monoid γ] [semimodule β γ] [add_comm_monoid δ]
{g : α →₀ γ} {b : β} {h : α → γ → δ} (h0 : ∀i, h i 0 = 0) :
(b • g).sum h = g.sum (λi c, h i (b • c)) :=
finsupp.sum_map_range_index h0
section
variables [semiring β] [semiring γ]
lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} :
(s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} :
b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) :=
by simp only [finsupp.sum, finset.mul_sum]
protected lemma eq_zero_of_zero_eq_one
(zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 :=
by ext i; simp only [eq_zero_of_zero_eq_one zero_eq_one (l i), finsupp.zero_apply]
end
/-- Given an `add_comm_monoid β` and `s : set α`, `restrict_support_equiv s β` is the `equiv`
between the subtype of finitely supported functions with support contained in `s` and
the type of finitely supported functions from `s`. -/
def restrict_support_equiv (s : set α) (β : Type*) [add_comm_monoid β] :
{f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
/-- Given `add_comm_monoid β` and `e : α₁ ≃ α₂`, `dom_congr e` is the corresponding `equiv` between
`α₁ →₀ β` and `α₂ →₀ β`. -/
protected def dom_congr [add_comm_monoid β] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) :=
⟨map_domain e, map_domain e.symm,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end⟩
/-! ### Declarations about sigma types -/
section sigma
variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β)
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β` and
an index element `i : ι`, `split l i` is the `i`th component of `l`,
a finitely supported function from `as i` to `β`. -/
def split (i : ι) : αs i →₀ β :=
l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2)
lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ :=
begin
dunfold split,
rw comap_domain_apply
end
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`,
`split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/
def split_support : finset ι := l.support.image sigma.fst
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def,
← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty],
simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right,
mem_support_iff, sigma.exists, ne.def]
end
/-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and
an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a
finitely supported function from the index type `ι` to `γ` given by composing `g i` with
`split l i`. -/
def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ :=
{ support := split_support l,
to_fun := λ i, g i (split l i),
mem_support_to_fun :=
begin
intros i,
rw [mem_split_support_iff_nonzero, not_iff_not, hg],
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image,
mem_preimage, sigma.forall, mem_sigma]; tauto
lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) :
l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) :=
by simp only [sum, sigma_support, sum_sigma, split_apply]
end sigma
end finsupp
/-! ### Declarations relating `multiset` to `finsupp` -/
namespace multiset
/-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by
the multiplicities of the elements of `s`. -/
def to_finsupp (s : multiset α) : α →₀ ℕ :=
{ support := s.to_finset,
to_fun := λ a, s.count a,
mem_support_to_fun := λ a,
begin
rw mem_to_finset,
convert not_iff_not_of_iff (count_eq_zero.symm),
rw not_not
end }
@[simp] lemma to_finsupp_support (s : multiset α) :
s.to_finsupp.support = s.to_finset :=
rfl
@[simp] lemma to_finsupp_apply (s : multiset α) (a : α) :
s.to_finsupp a = s.count a :=
rfl
@[simp] lemma to_finsupp_zero :
to_finsupp (0 : multiset α) = 0 :=
finsupp.ext $ λ a, count_zero a
@[simp] lemma to_finsupp_add (s t : multiset α) :
to_finsupp (s + t) = to_finsupp s + to_finsupp t :=
finsupp.ext $ λ a, count_add a s t
lemma to_finsupp_singleton (a : α) :
to_finsupp {a} = finsupp.single a 1 :=
finsupp.ext $ λ b,
if h : a = b then by rw [to_finsupp_apply, finsupp.single_apply, h, if_pos rfl,
singleton_eq_singleton, count_singleton] else
begin
rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero,
singleton_eq_singleton, mem_singleton],
rintro rfl, exact h rfl
end
namespace to_finsupp
instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) :=
{ map_zero := to_finsupp_zero,
map_add := to_finsupp_add }
end to_finsupp
@[simp] lemma to_finsupp_to_multiset (s : multiset α) :
s.to_finsupp.to_multiset = s :=
ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply]
end multiset
/-! ### Declarations about order(ed) instances on `finsupp` -/
namespace finsupp
variables {σ : Type*}
instance [preorder α] [has_zero α] : preorder (σ →₀ α) :=
{ le := λ f g, ∀ s, f s ≤ g s,
le_refl := λ f s, le_refl _,
le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) }
instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) :=
{ le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_cancel_add_comm_monoid α] :
add_left_cancel_semigroup (σ →₀ α) :=
{ add_left_cancel := λ a b c h, ext $ λ s,
by { rw ext_iff at h, exact add_left_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_add_comm_monoid α] :
add_right_cancel_semigroup (σ →₀ α) :=
{ add_right_cancel := λ a b c h, ext $ λ s,
by { rw ext_iff at h, exact add_right_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_add_comm_monoid α] :
ordered_cancel_add_comm_monoid (σ →₀ α) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order,
.. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup }
lemma le_iff [canonically_ordered_add_monoid α] (f g : σ →₀ α) :
f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s :=
⟨λ h s hs, h s,
λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩
@[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid α] (f g : σ →₀ α) :
f + g = 0 ↔ f = 0 ∧ g = 0 :=
begin
split,
{ assume h,
split,
all_goals
{ ext s,
suffices H : f s + g s = 0,
{ rw add_eq_zero_iff at H, cases H, assumption },
show (f + g) s = 0,
rw h, refl } },
{ rintro ⟨rfl, rfl⟩, rw add_zero }
end
attribute [simp] to_multiset_zero to_multiset_add
@[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) :
f.to_multiset.to_finsupp = f :=
ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset]
lemma to_multiset_strict_mono : strict_mono (@to_multiset σ) :=
λ m n h,
begin
rw lt_iff_le_and_ne at h ⊢, cases h with h₁ h₂,
split,
{ rw multiset.le_iff_count, intro s, erw [count_to_multiset m s, count_to_multiset], exact h₁ s },
{ intro H, apply h₂, replace H := congr_arg multiset.to_finsupp H,
simpa only [to_multiset_to_finsupp] using H }
end
lemma sum_id_lt_of_lt (m n : σ →₀ ℕ) (h : m < n) :
m.sum (λ _, id) < n.sum (λ _, id) :=
begin
rw [← card_to_multiset, ← card_to_multiset],
apply multiset.card_lt_of_lt,
exact to_multiset_strict_mono h
end
variable (σ)
/-- The order on `σ →₀ ℕ` is well-founded.-/
lemma lt_wf : well_founded (@has_lt.lt (σ →₀ ℕ) _) :=
subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf
instance decidable_le : decidable_rel (@has_le.le (σ →₀ ℕ) _) :=
λ m n, by rw le_iff; apply_instance
variable {σ}
/-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of
`s : σ →₀ ℕ` consists of all pairs `(t₁, t₂) : (σ →₀ ℕ) × (σ →₀ ℕ)` such that `t₁ + t₂ = s`.
The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/
def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ :=
(f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp
lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} :
p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f :=
begin
erw [multiset.mem_to_finset, multiset.mem_map],
split,
{ rintros ⟨⟨a, b⟩, h, rfl⟩,
rw multiset.mem_antidiagonal at h,
simpa only [to_multiset_to_finsupp, multiset.to_finsupp_add]
using congr_arg multiset.to_finsupp h},
{ intro h,
refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩,
{ simpa only [multiset.mem_antidiagonal, to_multiset_add]
using congr_arg to_multiset h},
{ rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } }
end
@[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 :=
by rw [← multiset.to_finsupp_singleton]; refl
lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) :
f.swap ∈ (antidiagonal n).support :=
by simpa only [mem_antidiagonal_support, add_comm, prod.swap] using hf
/-- Let `n : σ →₀ ℕ` be a finitely supported function.
The set of `m : σ →₀ ℕ` that are coordinatewise less than or equal to `n`,
is a finite set. -/
lemma finite_le_nat (n : σ →₀ ℕ) : set.finite {m | m ≤ n} :=
begin
let I := {i // i ∈ n.support},
let k : ℕ := ∑ i in n.support, n i,
let f : (σ →₀ ℕ) → (I → fin (k + 1)) := λ m i, m i,
have hf : ∀ m ≤ n, ∀ i, (f m i : ℕ) = m i,
{ intros m hm i,
apply fin.coe_coe_of_lt,
calc m i ≤ n i : hm i
... < k + 1 : nat.lt_succ_iff.mpr (single_le_sum (λ _ _, nat.zero_le _) i.2) },
have f_im : set.finite (f '' {m | m ≤ n}) := set.finite.of_fintype _,
suffices f_inj : set.inj_on f {m | m ≤ n},
{ exact set.finite_of_finite_image f_inj f_im },
intros m₁ h₁ m₂ h₂ h,
ext i,
by_cases hi : i ∈ n.support,
{ replace h := congr_fun h ⟨i, hi⟩,
rwa [fin.ext_iff, ← fin.coe_eq_val, ← fin.coe_eq_val, hf m₁ h₁, hf m₂ h₂] at h },
{ rw not_mem_support_iff at hi,
specialize h₁ i,
specialize h₂ i,
rw [hi, nat.le_zero_iff] at h₁ h₂,
rw [h₁, h₂] }
end
/-- Let `n : σ →₀ ℕ` be a finitely supported function.
The set of `m : σ →₀ ℕ` that are coordinatewise less than or equal to `n`,
but not equal to `n` everywhere, is a finite set. -/
lemma finite_lt_nat (n : σ →₀ ℕ) : set.finite {m | m < n} :=
(finite_le_nat n).subset $ λ m, le_of_lt
end finsupp
|
e9ee129701da17e9ac3e3d5f1fcef7aa2ac46f02 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/principal_ideal_domain.lean | 020cd87e5d01ad67491b8b68bcdfd194fb3fdc36 | [
"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 | 11,532 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Morenikeji Neri
-/
import ring_theory.unique_factorization_domain
/-!
# Principal ideal rings and principal ideal domains
A principal ideal ring (PIR) is a ring in which all left ideals are principal. A
principal ideal domain (PID) is an integral domain which is a principal ideal ring.
# Main definitions
Note that for principal ideal domains, one should use
`[integral_domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID.
Theorems about PID's are in the `principal_ideal_ring` namespace.
- `is_principal_ideal_ring`: a predicate on rings, saying that every left ideal is principal.
- `generator`: a generator of a principal ideal (or more generally submodule)
- `to_unique_factorization_monoid`: a PID is a unique factorization domain
# Main results
- `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal.
- `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID.
-/
universes u v
variables {R : Type u} {M : Type v}
open set function
open submodule
open_locale classical
section
variables [ring R] [add_comm_group M] [module R M]
/-- An `R`-submodule of `M` is principal if it is generated by one element. -/
class submodule.is_principal (S : submodule R M) : Prop :=
(principal [] : ∃ a, S = span R {a})
instance bot_is_principal : (⊥ : submodule R M).is_principal :=
⟨⟨0, by simp⟩⟩
instance top_is_principal : (⊤ : submodule R R).is_principal :=
⟨⟨1, ideal.span_singleton_one.symm⟩⟩
variables (R)
/-- A ring is a principal ideal ring if all (left) ideals are principal. -/
class is_principal_ideal_ring (R : Type u) [ring R] : Prop :=
(principal : ∀ (S : ideal R), S.is_principal)
attribute [instance] is_principal_ideal_ring.principal
@[priority 100]
instance division_ring.is_principal_ideal_ring (K : Type u) [division_ring K] :
is_principal_ideal_ring K :=
{ principal := λ S, by rcases ideal.eq_bot_or_top S with (rfl|rfl); apply_instance }
end
namespace submodule.is_principal
variables [add_comm_group M]
section ring
variables [ring R] [module R M]
/-- `generator I`, if `I` is a principal submodule, is an `x ∈ M` such that `span R {x} = I` -/
noncomputable def generator (S : submodule R M) [S.is_principal] : M :=
classical.some (principal S)
lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S :=
eq.symm (classical.some_spec (principal S))
lemma _root_.ideal.span_singleton_generator (I : ideal R) [I.is_principal] :
ideal.span ({generator I} : set R) = I :=
eq.symm (classical.some_spec (principal I))
@[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S :=
by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) }
lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} :
x ∈ S ↔ ∃ s : R, x = s • generator S :=
by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator]
lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] :
S = ⊥ ↔ generator S = 0 :=
by rw [← @span_singleton_eq_bot R M, span_singleton_generator]
end ring
section comm_ring
variables [comm_ring R] [module R M]
lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x :=
(mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul]))
lemma prime_generator_of_is_prime (S : ideal R) [submodule.is_principal S] [is_prime : S.is_prime]
(ne_bot : S ≠ ⊥) :
prime (generator S) :=
⟨λ h, ne_bot ((eq_bot_iff_generator_eq_zero S).2 h),
λ h, is_prime.ne_top (S.eq_top_of_is_unit_mem (generator_mem S) h),
by simpa only [← mem_iff_generator_dvd S] using is_prime.2⟩
end comm_ring
end submodule.is_principal
namespace is_prime
open submodule.is_principal ideal
-- TODO -- for a non-ID one could perhaps prove that if p < q are prime then q maximal;
-- 0 isn't prime in a non-ID PIR but the Krull dimension is still <= 1.
-- The below result follows from this, but we could also use the below result to
-- prove this (quotient out by p).
lemma to_maximal_ideal [comm_ring R] [integral_domain R] [is_principal_ideal_ring R] {S : ideal R}
[hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S :=
is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin
assume T x hST hxS hxT,
cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz,
cases hpi.mem_or_mem (show generator T * z ∈ S, from hz ▸ generator_mem S),
{ have hTS : T ≤ S, rwa [← T.span_singleton_generator, ideal.span_le, singleton_subset_iff],
exact (hxS $ hTS hxT).elim },
cases (mem_iff_generator_dvd _).1 h with y hy,
have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS,
rw [← mul_one (generator S), hy, mul_left_comm, mul_right_inj' this] at hz,
exact hz.symm ▸ T.mul_mem_right _ (generator_mem T)
end⟩
end is_prime
section
open euclidean_domain
variable [euclidean_domain R]
lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S :=
⟨λ hxy, div_add_mod x y ▸ S.add_mem (S.mul_mem_right _ hy) hxy,
λ hx, (mod_eq_sub_mul_div x y).symm ▸ S.sub_mem hx (S.mul_mem_right _ hy)⟩
@[priority 100] -- see Note [lower instance priority]
instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R :=
{ principal := λ S, by exactI
⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty
then
have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded,
have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧
well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0,
from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h,
⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h,
submodule.ext $ λ x,
⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸
(ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $
have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}),
from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2),
have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0,
by finish [(mod_mem_iff hmin.1).2 hx],
by simp *),
λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ S.mul_mem_right _ hmin.1⟩⟩
else ⟨0, submodule.ext $ λ a,
by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot];
exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ }
end
lemma is_field.is_principal_ideal_ring
{R : Type*} [comm_ring R] (h : is_field R) :
is_principal_ideal_ring R :=
@euclidean_domain.to_principal_ideal_domain R (@field.to_euclidean_domain R (h.to_field R))
namespace principal_ideal_ring
open is_principal_ideal_ring
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian_ring [ring R] [is_principal_ideal_ring R] :
is_noetherian_ring R :=
is_noetherian_ring_iff.2 ⟨assume s : ideal R,
begin
rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩,
rw [← finset.coe_singleton],
exact ⟨{a}, set_like.coe_injective rfl⟩
end⟩
lemma is_maximal_of_irreducible [comm_ring R] [is_principal_ideal_ring R]
{p : R} (hp : irreducible p) :
ideal.is_maximal (span R ({p} : set R)) :=
⟨⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin
rcases principal I with ⟨a, rfl⟩,
erw ideal.span_singleton_eq_top,
unfreezingI { rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩ },
refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)),
erw [ideal.span_singleton_le_span_singleton, is_unit.mul_right_dvd hb]
end⟩⟩
variables [comm_ring R] [integral_domain R] [is_principal_ideal_ring R]
lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p :=
⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $
(is_maximal_of_irreducible hp).is_prime,
prime.irreducible⟩
lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ prime p :=
associates.irreducible_iff_prime_iff.1 (λ _, irreducible_iff_prime)
section
open_locale classical
/-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/
noncomputable def factors (a : R) : multiset R :=
if h : a = 0 then ∅ else classical.some (wf_dvd_monoid.exists_factors a h)
lemma factors_spec (a : R) (h : a ≠ 0) :
(∀b∈factors a, irreducible b) ∧ associated (factors a).prod a :=
begin
unfold factors, rw [dif_neg h],
exact classical.some_spec (wf_dvd_monoid.exists_factors a h)
end
lemma ne_zero_of_mem_factors
{R : Type v} [comm_ring R] [integral_domain R] [is_principal_ideal_ring R] {a b : R}
(ha : a ≠ 0) (hb : b ∈ factors a) : b ≠ 0 := irreducible.ne_zero ((factors_spec a ha).1 b hb)
lemma mem_submonoid_of_factors_subset_of_units_subset (s : submonoid R)
{a : R} (ha : a ≠ 0) (hfac : ∀ b ∈ factors a, b ∈ s) (hunit : ∀ c : units R, (c : R) ∈ s) :
a ∈ s :=
begin
rcases ((factors_spec a ha).2) with ⟨c, hc⟩,
rw [← hc],
exact submonoid.mul_mem _ (submonoid.multiset_prod_mem _ _ hfac) (hunit _),
end
/-- If a `ring_hom` maps all units and all factors of an element `a` into a submonoid `s`, then it
also maps `a` into that submonoid. -/
lemma ring_hom_mem_submonoid_of_factors_subset_of_units_subset {R S : Type*}
[comm_ring R] [integral_domain R] [is_principal_ideal_ring R] [semiring S]
(f : R →+* S) (s : submonoid S) (a : R) (ha : a ≠ 0)
(h : ∀ b ∈ factors a, f b ∈ s) (hf: ∀ c : units R, f c ∈ s) :
f a ∈ s :=
mem_submonoid_of_factors_subset_of_units_subset (s.comap f.to_monoid_hom) ha h hf
/-- A principal ideal domain has unique factorization -/
@[priority 100] -- see Note [lower instance priority]
instance to_unique_factorization_monoid : unique_factorization_monoid R :=
{ irreducible_iff_prime := λ _, principal_ideal_ring.irreducible_iff_prime
.. (is_noetherian_ring.wf_dvd_monoid : wf_dvd_monoid R) }
end
end principal_ideal_ring
section surjective
open submodule
variables {S N : Type*} [ring R] [add_comm_group M] [add_comm_group N] [ring S]
variables [module R M] [module R N]
lemma submodule.is_principal.of_comap (f : M →ₗ[R] N) (hf : function.surjective f)
(S : submodule R N) [hI : is_principal (S.comap f)] :
is_principal S :=
⟨⟨f (is_principal.generator (S.comap f)),
by rw [← set.image_singleton, ← submodule.map_span,
is_principal.span_singleton_generator, submodule.map_comap_eq_of_surjective hf]⟩⟩
lemma ideal.is_principal.of_comap (f : R →+* S) (hf : function.surjective f)
(I : ideal S) [hI : is_principal (I.comap f)] :
is_principal I :=
⟨⟨f (is_principal.generator (I.comap f)),
by rw [ideal.submodule_span_eq, ← set.image_singleton, ← ideal.map_span,
ideal.span_singleton_generator, ideal.map_comap_of_surjective f hf]⟩⟩
/-- The surjective image of a principal ideal ring is again a principal ideal ring. -/
lemma is_principal_ideal_ring.of_surjective [is_principal_ideal_ring R]
(f : R →+* S) (hf : function.surjective f) :
is_principal_ideal_ring S :=
⟨λ I, ideal.is_principal.of_comap f hf I⟩
end surjective
|
4f41feb64e314a163439a327bd27e426b38a33db | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/category/Group/colimits.lean | c5e9b2e144e3693bda70a6d52703c2c3ff4d7373 | [
"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 | 9,742 | 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 algebra.category.Group.preadditive
import group_theory.quotient_group
import category_theory.limits.concrete_category
import category_theory.limits.shapes.kernels
import category_theory.limits.shapes.concrete_category
/-!
# The category of additive commutative groups has all colimits.
This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`.
It is a very uniform approach, that conceivably could be synthesised directly
by a tactic that analyses the shape of `add_comm_group` and `monoid_hom`.
TODO:
In fact, in `AddCommGroup` there is a much nicer model of colimits as quotients
of finitely supported functions, and we really should implement this as well (or instead).
-/
universes u v
open category_theory
open category_theory.limits
-- [ROBOT VOICE]:
-- You should pretend for now that this file was automatically generated.
-- It follows the same template as colimits in Mon.
namespace AddCommGroup.colimits
/-!
We build the colimit of a diagram in `AddCommGroup` by constructing the
free group on the disjoint union of all the abelian groups in the diagram,
then taking the quotient by the abelian group laws within each abelian group,
and the identifications given by the morphisms in the diagram.
-/
variables {J : Type v} [small_category J] (F : J ⥤ AddCommGroup.{v})
/--
An inductive type representing all group expressions (without relations)
on a collection of types indexed by the objects of `J`.
-/
inductive prequotient
-- There's always `of`
| of : Π (j : J) (x : F.obj j), prequotient
-- Then one generator for each operation
| zero : prequotient
| neg : prequotient → prequotient
| add : prequotient → prequotient → prequotient
instance : inhabited (prequotient F) := ⟨prequotient.zero⟩
open prequotient
/--
The relation on `prequotient` saying when two expressions are equal
because of the abelian group laws, or
because one element is mapped to another by a morphism in the diagram.
-/
inductive relation : prequotient F → prequotient F → Prop
-- Make it an equivalence relation:
| refl : Π (x), relation x x
| symm : Π (x y) (h : relation x y), relation y x
| trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z
-- There's always a `map` relation
| map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x)
-- Then one relation per operation, describing the interaction with `of`
| zero : Π (j), relation (of j 0) zero
| neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x))
| add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y))
-- Then one relation per argument of each operation
| neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x')
| add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y)
| add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y')
-- And one relation per axiom
| zero_add : Π (x), relation (add zero x) x
| add_zero : Π (x), relation (add x zero) x
| add_left_neg : Π (x), relation (add (neg x) x) zero
| add_comm : Π (x y), relation (add x y) (add y x)
| add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z))
/--
The setoid corresponding to group expressions modulo abelian group relations and identifications.
-/
def colimit_setoid : setoid (prequotient F) :=
{ r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ }
attribute [instance] colimit_setoid
/--
The underlying type of the colimit of a diagram in `AddCommGroup`.
-/
@[derive inhabited]
def colimit_type : Type v := quotient (colimit_setoid F)
instance : add_comm_group (colimit_type F) :=
{ zero :=
begin
exact quot.mk _ zero
end,
neg :=
begin
fapply @quot.lift,
{ intro x,
exact quot.mk _ (neg x) },
{ intros x x' r,
apply quot.sound,
exact relation.neg_1 _ _ r },
end,
add :=
begin
fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)),
{ intro x,
fapply @quot.lift,
{ intro y,
exact quot.mk _ (add x y) },
{ intros y y' r,
apply quot.sound,
exact relation.add_2 _ _ _ r } },
{ intros x x' r,
funext y,
induction y,
dsimp,
apply quot.sound,
{ exact relation.add_1 _ _ _ r },
{ refl } },
end,
zero_add := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.zero_add,
refl,
end,
add_zero := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.add_zero,
refl,
end,
add_left_neg := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.add_left_neg,
refl,
end,
add_comm := λ x y,
begin
induction x,
induction y,
dsimp,
apply quot.sound,
apply relation.add_comm,
refl,
refl,
end,
add_assoc := λ x y z,
begin
induction x,
induction y,
induction z,
dsimp,
apply quot.sound,
apply relation.add_assoc,
refl,
refl,
refl,
end, }
@[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl
@[simp] lemma quot_neg (x) :
quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl
@[simp] lemma quot_add (x y) :
quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl
/-- The bundled abelian group giving the colimit of a diagram. -/
def colimit : AddCommGroup := AddCommGroup.of (colimit_type F)
/-- The function from a given abelian group in the diagram to the colimit abelian group. -/
def cocone_fun (j : J) (x : F.obj j) : colimit_type F :=
quot.mk _ (of j x)
/-- The group homomorphism from a given abelian group in the diagram to the colimit abelian
group. -/
def cocone_morphism (j : J) : F.obj j ⟶ colimit F :=
{ to_fun := cocone_fun F j,
map_zero' := by apply quot.sound; apply relation.zero,
map_add' := by intros; apply quot.sound; apply relation.add }
@[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') :
F.map f ≫ (cocone_morphism F j') = cocone_morphism F j :=
begin
ext,
apply quot.sound,
apply relation.map,
end
@[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j):
(cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x :=
by { rw ←cocone_naturality F f, refl }
/-- The cocone over the proposed colimit abelian group. -/
def colimit_cocone : cocone F :=
{ X := colimit F,
ι :=
{ app := cocone_morphism F } }.
/-- The function from the free abelian group on the diagram to the cone point of any other
cocone. -/
@[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X
| (of j x) := (s.ι.app j) x
| zero := 0
| (neg x) := -(desc_fun_lift x)
| (add x y) := desc_fun_lift x + desc_fun_lift y
/-- The function from the colimit abelian group to the cone point of any other cocone. -/
def desc_fun (s : cocone F) : colimit_type F → s.X :=
begin
fapply quot.lift,
{ exact desc_fun_lift F s },
{ intros x y r,
induction r; try { dsimp },
-- refl
{ refl },
-- symm
{ exact r_ih.symm },
-- trans
{ exact eq.trans r_ih_h r_ih_k },
-- map
{ simp, },
-- zero
{ simp, },
-- neg
{ simp, },
-- add
{ simp, },
-- neg_1
{ rw r_ih, },
-- add_1
{ rw r_ih, },
-- add_2
{ rw r_ih, },
-- zero_add
{ rw zero_add, },
-- add_zero
{ rw add_zero, },
-- add_left_neg
{ rw add_left_neg, },
-- add_comm
{ rw add_comm, },
-- add_assoc
{ rw add_assoc, },
}
end
/-- The group homomorphism from the colimit abelian group to the cone point of any other cocone. -/
def desc_morphism (s : cocone F) : colimit F ⟶ s.X :=
{ to_fun := desc_fun F s,
map_zero' := rfl,
map_add' := λ x y, by { induction x; induction y; refl }, }
/-- Evidence that the proposed colimit is the colimit. -/
def colimit_cocone_is_colimit : is_colimit (colimit_cocone F) :=
{ desc := λ s, desc_morphism F s,
uniq' := λ s m w,
begin
ext,
induction x,
induction x,
{ have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x,
erw w',
refl, },
{ simp *, },
{ simp *, },
{ simp *, },
refl
end }.
instance has_colimits_AddCommGroup : has_colimits AddCommGroup :=
{ has_colimits_of_shape := λ J 𝒥, by exactI
{ has_colimit := λ F, has_colimit.mk
{ cocone := colimit_cocone F,
is_colimit := colimit_cocone_is_colimit F } } }
end AddCommGroup.colimits
namespace AddCommGroup
open quotient_add_group
/--
The categorical cokernel of a morphism in `AddCommGroup`
agrees with the usual group-theoretical quotient.
-/
noncomputable def cokernel_iso_quotient {G H : AddCommGroup} (f : G ⟶ H) :
cokernel f ≅ AddCommGroup.of (quotient (add_monoid_hom.range f)) :=
{ hom := cokernel.desc f (mk' _)
(by { ext, apply quotient.sound, fsplit, exact -x,
simp only [add_zero, add_monoid_hom.map_neg], }),
inv := add_monoid_hom.of (quotient_add_group.lift _ (cokernel.π f)
(by { intros x H_1, cases H_1, induction H_1_h,
simp only [cokernel.condition_apply, zero_apply]})),
-- obviously can take care of the next goals, but it is really slow
hom_inv_id' := begin
ext1, simp only [coequalizer_as_cokernel, category.comp_id, cokernel.π_desc_assoc], ext1, refl,
end,
inv_hom_id' := begin
ext1, induction x,
{ simp only [colimit.ι_desc_apply, id_apply, add_monoid_hom.coe_of, lift_quot_mk,
cofork.of_π_ι_app, comp_apply], refl },
{ refl }
end, }
end AddCommGroup
|
02d218a171b03fcb76d6c2847e20f0a401ade359 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/algebra/category/functor.lean | 43ef2cc09d1d7e83ed6e9ea4741266d268f28321 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,207 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: algebra.category.functor
Author: Floris van Doorn
-/
import .basic
import logic.cast logic.funext
open function
open category eq eq.ops heq
structure functor (C D : Category) : Type :=
(object : C → D)
(morphism : Π⦃a b : C⦄, hom a b → hom (object a) (object b))
(respect_id : Π (a : C), morphism (ID a) = ID (object a))
(respect_comp : Π ⦃a b c : C⦄ (g : hom b c) (f : hom a b),
morphism (g ∘ f) = morphism g ∘ morphism f)
infixl `⇒`:25 := functor
namespace functor
attribute object [coercion]
attribute morphism [coercion]
attribute respect_id [irreducible]
attribute respect_comp [irreducible]
variables {A B C D : Category}
protected definition compose [reducible] (G : functor B C) (F : functor A B) : functor A C :=
functor.mk
(λx, G (F x))
(λ a b f, G (F f))
(λ a, proof calc
G (F (ID a)) = G id : {respect_id F a}
--not giving the braces explicitly makes the elaborator compute a couple more seconds
... = id : respect_id G (F a) qed)
(λ a b c g f, proof calc
G (F (g ∘ f)) = G (F g ∘ F f) : respect_comp F g f
... = G (F g) ∘ G (F f) : respect_comp G (F g) (F f) qed)
infixr `∘f`:60 := compose
protected theorem assoc (H : functor C D) (G : functor B C) (F : functor A B) :
H ∘f (G ∘f F) = (H ∘f G) ∘f F :=
rfl
protected definition id [reducible] {C : Category} : functor C C :=
mk (λa, a) (λ a b f, f) (λ a, rfl) (λ a b c f g, rfl)
protected definition ID [reducible] (C : Category) : functor C C := id
protected theorem id_left (F : functor C D) : id ∘f F = F :=
functor.rec (λ obF homF idF compF, dcongr_arg4 mk rfl rfl !proof_irrel !proof_irrel) F
protected theorem id_right (F : functor C D) : F ∘f id = F :=
functor.rec (λ obF homF idF compF, dcongr_arg4 mk rfl rfl !proof_irrel !proof_irrel) F
end functor
namespace category
open functor
definition category_of_categories [reducible] : category Category :=
mk (λ a b, functor a b)
(λ a b c g f, functor.compose g f)
(λ a, functor.id)
(λ a b c d h g f, !functor.assoc)
(λ a b f, !functor.id_left)
(λ a b f, !functor.id_right)
definition Category_of_categories [reducible] := Mk category_of_categories
namespace ops
notation `Cat`:max := Category_of_categories
attribute category_of_categories [instance]
end ops
end category
namespace functor
variables {C D : Category}
theorem mk_heq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x)
(Hmor : ∀(a b : C) (f : a ⟶ b), homF a b f == homG a b f)
: mk obF homF idF compF = mk obG homG idG compG :=
hddcongr_arg4 mk
(funext Hob)
(hfunext (λ a, hfunext (λ b, hfunext (λ f, !Hmor))))
!proof_irrel
!proof_irrel
protected theorem hequal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x)
(Hmor : ∀a b (f : a ⟶ b), F f == G f), F = G :=
functor.rec
(λ obF homF idF compF,
functor.rec
(λ obG homG idG compG Hob Hmor, mk_heq Hob Hmor)
G)
F
-- theorem mk_eq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x)
-- (Hmor : ∀(a b : C) (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (homF a b f)
-- = homG a b f)
-- : mk obF homF idF compF = mk obG homG idG compG :=
-- dcongr_arg4 mk
-- (funext Hob)
-- (funext (λ a, funext (λ b, funext (λ f, sorry ⬝ Hmor a b f))))
-- -- to fill this sorry use (a generalization of) cast_pull
-- !proof_irrel
-- !proof_irrel
-- protected theorem equal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x)
-- (Hmor : ∀a b (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (F f) = G f), F = G :=
-- functor.rec
-- (λ obF homF idF compF,
-- functor.rec
-- (λ obG homG idG compG Hob Hmor, mk_eq Hob Hmor)
-- G)
-- F
end functor
|
3f980f4396a1683a8a7f90a154944e09b920caa9 | 7c4610454cf55b49f0c3cdaeb6b856eb3249cb2d | /src/general.lean | 33610e1b691e8a7fed2deb7bedea2eda276dd12b | [] | no_license | 101damnations/fg_over_pid | 097be43e11c3680a3fd4b6de2265de393cf4d4ef | a1a587c455a54a802f6ff61b07bb033701e451a7 | refs/heads/master | 1,669,708,904,636 | 1,597,259,770,000 | 1,597,259,770,000 | 287,097,363 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,594 | lean | import linear_algebra.basis
variables {R : Type*} [ring R] {M : Type*} [add_comm_group M] [module R M] {N : Type*}
[add_comm_group N] [module R N] {M' : Type*} [add_comm_group M'] [module R M']
theorem map_inf (p p' : submodule R M) (f : M →ₗ[R] M') (hf : function.injective f) :
p.map f ⊓ p'.map f = (p ⊓ p').map f :=
submodule.coe_injective $ set.image_inter hf
/-- We have R-submodules of M, S, T ⊆ A, where S, T are thought of as submodules of A.
Given sets s, t ⊆ M, if the submodule s generates equals 'S as a submodule of M' and the submodule
t generates equals 'T as a submodule of M', and s & t are linearly independent, and S, T are complementary
submodules of A, then s ∪ t is linearly independent and generates A. -/
theorem union_is_basis_of_gen_compl (A : submodule R M) (S : submodule R A) (s : set M)
(T : submodule R A) (t : set M)
(hss : submodule.span R s = S.map A.subtype) (hts : submodule.span R t = T.map A.subtype)
(hsl : linear_independent R (λ x, x : s → M))
(htl : linear_independent R (λ x, x : t → M))
(h1 : S ⊓ T = ⊥) (h2 : S ⊔ T = ⊤) : linear_independent R (λ x, x : s ∪ t → M)
∧ submodule.span R (set.range (λ x, x : s ∪ t → M)) = A :=
begin
split,
apply linear_independent.union hsl htl,
rw hss, rw hts,
rw disjoint_iff,
rw map_inf, rw h1, rw submodule.map_bot, exact subtype.val_injective,
have := submodule.map_sup S T A.subtype,
rw h2 at this,
rw submodule.map_subtype_top at this, rw this,
erw subtype.range_coe_subtype, rw ←hss, rw ←hts, exact submodule.span_union _ _,
end |
83d184244b0133c9de19ceef25d1bf5fe9ceff7d | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /tests/lean/num.lean | 33c2dddf0d20bb15aec026226dafc7366191a140 | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 126 | lean | --
#check 10
#check 20
#check 3
#check 1
#check 0
#check 12
#check 13
#check 12138
#check 1221
#check 11
#check 5
#check 21
|
1ba875e834648f884c867325bf87b562d6304d56 | 618003631150032a5676f229d13a079ac875ff77 | /test/trunc_cases.lean | 22d3c6dbb452b616c75906565cfdc95dce0e0571 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 2,389 | lean | import tactic.trunc_cases
import tactic.interactive
import data.quot
example (t : trunc ℕ) : punit :=
begin
trunc_cases t,
exact (),
-- no more goals, because `trunc_cases` used the correct `trunc.rec_on_subsingleton` recursor
end
example (t : trunc ℕ) : ℕ :=
begin
trunc_cases t,
guard_hyp t := ℕ, -- verify that the new hypothesis is still called `t`.
exact 0,
-- verify that we don't even need to use `simp`,
-- because `trunc_cases` has already removed the `eq.rec`.
refl,
end
example {α : Type} [subsingleton α] (I : trunc (has_zero α)) : α :=
begin
trunc_cases I,
exact 0,
end
/-- A mock typeclass, set up so that it's possible to extract data from `trunc (has_unit α)`. -/
class has_unit (α : Type) [has_one α] :=
(unit : α)
(unit_eq_one : unit = 1)
def u {α : Type} [has_one α] [has_unit α] : α := has_unit.unit
attribute [simp] has_unit.unit_eq_one
example {α : Type} [has_one α] (I : trunc (has_unit α)) : α :=
begin
trunc_cases I,
exact u, -- Verify that the typeclass is immediately available
-- Verify that there's no `eq.rec` in the goal.
(do tgt ← tactic.target, eq_rec ← tactic.mk_const `eq.rec, guard $ ¬ eq_rec.occurs tgt),
simp [u],
end
universes v w z
/-- Transport through a product is given by individually transporting each component. -/
-- It's a pity that this is no good as a `simp` lemma.
-- (It seems the unification problem with `λ a, W a × Z a` is too hard.)
-- (One could write a tactic to syntactically analyse `eq.rec` expressions
-- and simplify more of them!)
lemma eq_rec_prod {α : Sort v} (W : α → Type w) (Z : α → Type z) {a b : α} (p : W a × Z a) (h : a = b) :
@eq.rec α a (λ a, W a × Z a) p b h = (@eq.rec α a W p.1 b h, @eq.rec α a Z p.2 b h) :=
begin
cases h,
simp only [prod.mk.eta],
end
-- This time, we make a goal that (quite artificially) depends on the `trunc`.
example {α : Type} [has_one α] (I : trunc (has_unit α)) : α × plift (I = I) :=
begin
-- This time `trunc_cases` has no choice but to use `trunc.rec_on`.
trunc_cases I,
{ exact ⟨u, plift.up rfl⟩, },
{ -- And so we get an `eq.rec` in the invariance goal.
-- Since `simp` can't handle it because of the unification problem,
-- for now we have to handle it by hand.
convert eq_rec_prod (λ I, α) (λ I, plift (I = I)) _ _,
{ simp [u], },
{ ext, } }
end
|
f822f88a54129bfe0d07a2dd010a4dfaa3da0d58 | ea11767c9c6a467c4b7710ec6f371c95cfc023fd | /src/monoidal_categories/enriched/enriched_category_old.lean | b58efaaaab78a51c274766cefbc03b979050c0fe | [] | no_license | RitaAhmadi/lean-monoidal-categories | 68a23f513e902038e44681336b87f659bbc281e0 | 81f43e1e0d623a96695aa8938951d7422d6d7ba6 | refs/heads/master | 1,651,458,686,519 | 1,529,824,613,000 | 1,529,824,613,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,010 | lean | -- -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- -- Released under Apache 2.0 license as described in the file LICENSE.
-- -- Authors: Stephen Morgan, Scott Morrison
-- import ..monoidal_category
-- namespace categories.enriched
-- open categories
-- open categories.monoidal_category
-- structure {u v w} EnrichedCategory { V: Category.{v w} } ( m : MonoidalStructure V ) :=
-- (Obj : Type u)
-- (Hom : Obj → Obj → V.Obj)
-- (compose : Π ( X Y Z : Obj ), V.Hom (m.tensorObjects (Hom X Y) (Hom Y Z)) (Hom X Z))
-- (identity : Π X : Obj, V.Hom m.tensor_unit (Hom X X))
-- (left_identity : ∀ { X Y : Obj },
-- V.compose
-- (m.inverse_left_unitor (Hom X Y))
-- (V.compose
-- (m.tensorMorphisms (identity X) (V.identity (Hom X Y)))
-- (compose _ _ _)
-- ) = V.identity (Hom X Y) )
-- (right_identity : ∀ { X Y : Obj },
-- V.compose
-- (m.inverse_right_unitor (Hom X Y))
-- (V.compose
-- (m.tensorMorphisms (V.identity (Hom X Y)) (identity Y))
-- (compose _ _ _)
-- ) = V.identity (Hom X Y) )
-- (associativity : ∀ { W X Y Z : Obj },
-- V.compose
-- (m.tensorMorphisms (compose _ _ _) (V.identity (Hom Y Z)))
-- (compose _ _ _)
-- = V.compose
-- (m.associator (Hom W X) (Hom X Y) (Hom Y Z))
-- (V.compose
-- (m.tensorMorphisms (V.identity (Hom W X)) (compose _ _ _))
-- (compose _ _ _)) )
-- attribute [simp,ematch] EnrichedCategory.left_identity
-- attribute [simp,ematch] EnrichedCategory.right_identity
-- attribute [ematch] EnrichedCategory.associativity
-- -- instance EnrichedCategory_to_Hom { V : Category } { m : MonoidalStructure V } : has_coe_to_fun (EnrichedCategory m) :=
-- -- { F := λ C, C.Obj → C.Obj → V.Obj,
-- -- coe := EnrichedCategory.Hom }
-- -- definition {u v w} UnderlyingCategory { V: Category.{v w} } { m : MonoidalStructure V } ( C : EnrichedCategory m ) : Category := {
-- -- Obj := C.Obj,
-- -- Hom := λ X Y, V.Hom m.tensor_unit (C.Hom X Y),
-- -- identity := C.identity,
-- -- compose := λ X Y Z f g, begin
-- -- have p := m.tensorMorphisms f g,
-- -- tidy,
-- -- have p' := V.compose p (C.compose X Y Z),
-- -- have p'' := m.inverse_left_unitor m.tensor_unit,
-- -- tidy,
-- -- exact V.compose p'' p'
-- -- end,
-- -- left_identity := begin
-- -- tidy,
-- -- have p := C.left_identity,
-- -- have p' := @p X Y,
-- -- have p'' := congr_arg (λ x, V.compose f x) p',
-- -- dsimp at *,
-- -- admit,
-- -- end,
-- -- right_identity := sorry,
-- -- associativity := begin
-- -- tidy,
-- -- -- PROJECT
-- -- -- These are great examples of things that are trivial in string diagrams, but horrific here.
-- -- admit,
-- -- end,
-- -- }
-- structure Functor { V : Category } { m : MonoidalStructure V } ( C D : EnrichedCategory m ) :=
-- ( onObjects : C.Obj → D.Obj )
-- ( onMorphisms : ∀ { X Y : C.Obj }, V.Hom (C.Hom X Y) (D.Hom (onObjects X) (onObjects Y)) )
-- ( identities : ∀ X : C.Obj, V.compose (C.identity X) onMorphisms = D.identity (onObjects X) )
-- -- TODO fix this
-- -- ( functoriality : ∀ { X Y Z : C.Obj }, V.compose C.compose (@onMorphisms X Z) = V.compose (m.tensorMorphisms (@onMorphisms X Y) (@onMorphisms Y Z)) D.compose )
-- attribute [simp,ematch] Functor.identities
-- -- attribute [simp,ematch] Functor.functoriality
-- -- PROJECT natural transformations don't always exist; you need various limits!
-- end categories.enriched |
d4803bb6866915c064d50ca1c4f71daa81ff0360 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/group/pi.lean | 5d6fef1254a959186fc99266098b5db93748ff73 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,185 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import data.pi
import data.set.function
import tactic.pi_instances
import algebra.group.defs
import algebra.group.hom
/-!
# Pi instances for groups and monoids
This file defines instances for group, monoid, semigroup and related structures on Pi types.
-/
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equipped with instances
variables (x y : Π i, f i) (i : I)
namespace pi
@[to_additive]
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) :=
by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive]
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive]
instance mul_one_class [∀ i, mul_one_class $ f i] : mul_one_class (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive]
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive]
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive]
instance div_inv_monoid [∀ i, div_inv_monoid $ f i] :
div_inv_monoid (Π i : I, f i) :=
{ div_eq_mul_inv := λ x y, funext (λ i, div_eq_mul_inv (x i) (y i)),
.. pi.monoid, .. pi.has_div, .. pi.has_inv }
@[to_additive]
instance group [∀ i, group $ f i] : group (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div, .. };
tactic.pi_instance_derive_field
@[to_additive]
instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div, .. };
tactic.pi_instance_derive_field
@[to_additive add_left_cancel_semigroup]
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] :
left_cancel_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*) }; tactic.pi_instance_derive_field
@[to_additive add_right_cancel_semigroup]
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] :
right_cancel_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*) }; tactic.pi_instance_derive_field
@[to_additive add_left_cancel_monoid]
instance left_cancel_monoid [∀ i, left_cancel_monoid $ f i] :
left_cancel_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*) }; tactic.pi_instance_derive_field
@[to_additive add_right_cancel_monoid]
instance right_cancel_monoid [∀ i, right_cancel_monoid $ f i] :
right_cancel_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*) }; tactic.pi_instance_derive_field
@[to_additive add_cancel_monoid]
instance cancel_monoid [∀ i, cancel_monoid $ f i] :
cancel_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*) }; tactic.pi_instance_derive_field
@[to_additive add_cancel_comm_monoid]
instance cancel_comm_monoid [∀ i, cancel_comm_monoid $ f i] :
cancel_comm_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*) }; tactic.pi_instance_derive_field
instance mul_zero_class [∀ i, mul_zero_class $ f i] :
mul_zero_class (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
instance monoid_with_zero [∀ i, monoid_with_zero $ f i] :
monoid_with_zero (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), .. };
tactic.pi_instance_derive_field
instance comm_monoid_with_zero [∀ i, comm_monoid_with_zero $ f i] :
comm_monoid_with_zero (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), .. };
tactic.pi_instance_derive_field
section instance_lemmas
open function
variables {α β γ : Type*}
@[simp, to_additive] lemma const_one [has_one β] : const α (1 : β) = 1 := rfl
@[simp, to_additive] lemma comp_one [has_one β] {f : β → γ} : f ∘ 1 = const α (f 1) := rfl
@[simp, to_additive] lemma one_comp [has_one γ] {f : α → β} : (1 : β → γ) ∘ f = 1 := rfl
end instance_lemmas
end pi
section monoid_hom
variables (f) [Π i, monoid (f i)]
/-- Evaluation of functions into an indexed collection of monoids at a point is a monoid
homomorphism. -/
@[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point
is an additive monoid homomorphism."]
def monoid_hom.apply (i : I) : (Π i, f i) →* f i :=
{ to_fun := λ g, g i,
map_one' := rfl,
map_mul' := λ x y, rfl, }
@[simp, to_additive]
lemma monoid_hom.apply_apply (i : I) (g : Π i, f i) :
(monoid_hom.apply f i) g = g i := rfl
/-- Coercion of a `monoid_hom` into a function is itself a `monoid_hom`.
See also `monoid_hom.eval`. -/
@[simps, to_additive "Coercion of an `add_monoid_hom` into a function is itself a `add_monoid_hom`.
See also `add_monoid_hom.eval`. "]
def monoid_hom.coe_fn (α β : Type*) [mul_one_class α] [comm_monoid β] : (α →* β) →* (α → β) :=
{ to_fun := λ g, g,
map_one' := rfl,
map_mul' := λ x y, rfl, }
end monoid_hom
section single
variables [decidable_eq I]
open pi
variables (f)
/-- The zero-preserving homomorphism including a single value
into a dependent family of values, as functions supported at a point.
This is the `zero_hom` version of `pi.single`. -/
@[simps] def zero_hom.single [Π i, has_zero $ f i] (i : I) : zero_hom (f i) (Π i, f i) :=
{ to_fun := single i,
map_zero' := single_zero i }
/-- The additive monoid homomorphism including a single additive monoid
into a dependent family of additive monoids, as functions supported at a point.
This is the `add_monoid_hom` version of `pi.single`. -/
@[simps] def add_monoid_hom.single [Π i, add_zero_class $ f i] (i : I) : f i →+ Π i, f i :=
{ to_fun := single i,
map_add' := single_op₂ (λ _, (+)) (λ _, zero_add _) _,
.. (zero_hom.single f i) }
/-- The multiplicative homomorphism including a single `mul_zero_class`
into a dependent family of `mul_zero_class`es, as functions supported at a point.
This is the `mul_hom` version of `pi.single`. -/
@[simps] def mul_hom.single [Π i, mul_zero_class $ f i] (i : I) : mul_hom (f i) (Π i, f i) :=
{ to_fun := single i,
map_mul' := single_op₂ (λ _, (*)) (λ _, zero_mul _) _, }
variables {f}
lemma pi.single_add [Π i, add_zero_class $ f i] (i : I) (x y : f i) :
single i (x + y) = single i x + single i y :=
(add_monoid_hom.single f i).map_add x y
lemma pi.single_neg [Π i, add_group $ f i] (i : I) (x : f i) :
single i (-x) = -single i x :=
(add_monoid_hom.single f i).map_neg x
lemma pi.single_sub [Π i, add_group $ f i] (i : I) (x y : f i) :
single i (x - y) = single i x - single i y :=
(add_monoid_hom.single f i).map_sub x y
lemma pi.single_mul [Π i, mul_zero_class $ f i] (i : I) (x y : f i) :
single i (x * y) = single i x * single i y :=
(mul_hom.single f i).map_mul x y
end single
section piecewise
@[to_additive]
lemma set.piecewise_mul [Π i, has_mul (f i)] (s : set I) [Π i, decidable (i ∈ s)]
(f₁ f₂ g₁ g₂ : Π i, f i) :
s.piecewise (f₁ * f₂) (g₁ * g₂) = s.piecewise f₁ g₁ * s.piecewise f₂ g₂ :=
s.piecewise_op₂ _ _ _ _ (λ _, (*))
@[to_additive]
lemma pi.piecewise_inv [Π i, has_inv (f i)] (s : set I) [Π i, decidable (i ∈ s)]
(f₁ g₁ : Π i, f i) :
s.piecewise (f₁⁻¹) (g₁⁻¹) = (s.piecewise f₁ g₁)⁻¹ :=
s.piecewise_op f₁ g₁ (λ _ x, x⁻¹)
@[to_additive]
lemma pi.piecewise_div [Π i, has_div (f i)] (s : set I) [Π i, decidable (i ∈ s)]
(f₁ f₂ g₁ g₂ : Π i, f i) :
s.piecewise (f₁ / f₂) (g₁ / g₂) = s.piecewise f₁ g₁ / s.piecewise f₂ g₂ :=
s.piecewise_op₂ _ _ _ _ (λ _, (/))
end piecewise
|
f99b22e2853b17730ffe6f9d39d1bde66dff1303 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/data/prod/thms.lean | 088692a809108bd0fa3d123a2881e2f313e724a6 | [
"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 | 4,921 | lean | -- Copyright (c) 2014 Microsoft Corporation. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Leonardo de Moura, Jeremy Avigad
import data.prod.decl logic.inhabited logic.eq logic.decidable
open inhabited decidable eq.ops
namespace prod
variables {A B : Type} {a₁ a₂ : A} {b₁ b₂ : B} {u : A × B}
theorem pair_eq : a₁ = a₂ → b₁ = b₂ → (a₁, b₁) = (a₂, b₂) :=
assume H1 H2, H1 ▸ H2 ▸ rfl
protected theorem equal {p₁ p₂ : prod A B} : pr₁ p₁ = pr₁ p₂ → pr₂ p₁ = pr₂ p₂ → p₁ = p₂ :=
destruct p₁ (take a₁ b₁, destruct p₂ (take a₂ b₂ H₁ H₂, pair_eq H₁ H₂))
protected definition is_inhabited [instance] : inhabited A → inhabited B → inhabited (prod A B) :=
take (H₁ : inhabited A) (H₂ : inhabited B),
inhabited.destruct H₁ (λa, inhabited.destruct H₂ (λb, inhabited.mk (pair a b)))
protected definition has_decidable_eq [instance] : decidable_eq A → decidable_eq B → decidable_eq (A × B) :=
take (H₁ : decidable_eq A) (H₂ : decidable_eq B) (u v : A × B),
have H₃ : u = v ↔ (pr₁ u = pr₁ v) ∧ (pr₂ u = pr₂ v), from
iff.intro
(assume H, H ▸ and.intro rfl rfl)
(assume H, and.elim H (assume H₄ H₅, equal H₄ H₅)),
decidable_iff_equiv _ (iff.symm H₃)
-- ### flip operation
definition flip (a : A × B) : B × A := pair (pr2 a) (pr1 a)
theorem flip_def (a : A × B) : flip a = pair (pr2 a) (pr1 a) := rfl
theorem flip_pair (a : A) (b : B) : flip (pair a b) = pair b a := rfl
theorem flip_pr1 (a : A × B) : pr1 (flip a) = pr2 a := rfl
theorem flip_pr2 (a : A × B) : pr2 (flip a) = pr1 a := rfl
theorem flip_flip (a : A × B) : flip (flip a) = a :=
destruct a (take x y, rfl)
theorem P_flip {P : A → B → Prop} (a : A × B) (H : P (pr1 a) (pr2 a))
: P (pr2 (flip a)) (pr1 (flip a)) :=
(flip_pr1 a)⁻¹ ▸ (flip_pr2 a)⁻¹ ▸ H
theorem flip_inj {a b : A × B} (H : flip a = flip b) : a = b :=
have H2 : flip (flip a) = flip (flip b), from congr_arg flip H,
show a = b, from (flip_flip a) ▸ (flip_flip b) ▸ H2
-- ### coordinatewise unary maps
definition map_pair (f : A → B) (a : A × A) : B × B :=
pair (f (pr1 a)) (f (pr2 a))
theorem map_pair_def (f : A → B) (a : A × A)
: map_pair f a = pair (f (pr1 a)) (f (pr2 a)) :=
rfl
theorem map_pair_pair (f : A → B) (a a' : A)
: map_pair f (pair a a') = pair (f a) (f a') :=
(pr1.mk a a') ▸ (pr2.mk a a') ▸ rfl
theorem map_pair_pr1 (f : A → B) (a : A × A) : pr1 (map_pair f a) = f (pr1 a) :=
!pr1.mk
theorem map_pair_pr2 (f : A → B) (a : A × A) : pr2 (map_pair f a) = f (pr2 a) :=
!pr2.mk
-- ### coordinatewise binary maps
definition map_pair2 {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) : C × C :=
pair (f (pr1 a) (pr1 b)) (f (pr2 a) (pr2 b))
theorem map_pair2_def {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) :
map_pair2 f a b = pair (f (pr1 a) (pr1 b)) (f (pr2 a) (pr2 b)) := rfl
theorem map_pair2_pair {A B C : Type} (f : A → B → C) (a a' : A) (b b' : B) :
map_pair2 f (pair a a') (pair b b') = pair (f a b) (f a' b') :=
calc
map_pair2 f (pair a a') (pair b b')
= pair (f (pr1 (pair a a')) b) (f (pr2 (pair a a')) (pr2 (pair b b')))
: {pr1.mk b b'}
... = pair (f (pr1 (pair a a')) b) (f (pr2 (pair a a')) b') : {pr2.mk b b'}
... = pair (f (pr1 (pair a a')) b) (f a' b') : {pr2.mk a a'}
... = pair (f a b) (f a' b') : {pr1.mk a a'}
theorem map_pair2_pr1 {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) :
pr1 (map_pair2 f a b) = f (pr1 a) (pr1 b) := !pr1.mk
theorem map_pair2_pr2 {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) :
pr2 (map_pair2 f a b) = f (pr2 a) (pr2 b) := !pr2.mk
theorem map_pair2_flip {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) :
flip (map_pair2 f a b) = map_pair2 f (flip a) (flip b) :=
have Hx : pr1 (flip (map_pair2 f a b)) = pr1 (map_pair2 f (flip a) (flip b)), from
calc
pr1 (flip (map_pair2 f a b)) = pr2 (map_pair2 f a b) : flip_pr1 _
... = f (pr2 a) (pr2 b) : map_pair2_pr2 f a b
... = f (pr1 (flip a)) (pr2 b) : {(flip_pr1 a)⁻¹}
... = f (pr1 (flip a)) (pr1 (flip b)) : {(flip_pr1 b)⁻¹}
... = pr1 (map_pair2 f (flip a) (flip b)) : (map_pair2_pr1 f _ _)⁻¹,
have Hy : pr2 (flip (map_pair2 f a b)) = pr2 (map_pair2 f (flip a) (flip b)), from
calc
pr2 (flip (map_pair2 f a b)) = pr1 (map_pair2 f a b) : flip_pr2 _
... = f (pr1 a) (pr1 b) : map_pair2_pr1 f a b
... = f (pr2 (flip a)) (pr1 b) : {flip_pr2 a}
... = f (pr2 (flip a)) (pr2 (flip b)) : {flip_pr2 b}
... = pr2 (map_pair2 f (flip a) (flip b)) : (map_pair2_pr2 f _ _)⁻¹,
pair_eq Hx Hy
end prod
|
27295bf834e9bf150109b02454b08dc78398d502 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/control/lawful_fix.lean | 1996f60b5173ad1b82113e92871219362ba63619 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 7,786 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
-/
import tactic.apply
import control.fix
import order.omega_complete_partial_order
/-!
# Lawful fixed point operators
This module defines the laws required of a `has_fix` instance, using the theory of
omega complete partial orders (ωCPO). Proofs of the lawfulness of all `has_fix` instances in
`control.fix` are provided.
## Main definition
* class `lawful_fix`
-/
universes u v
open_locale classical
variables {α : Type*} {β : α → Type*}
open omega_complete_partial_order
/-- Intuitively, a fixed point operator `fix` is lawful if it satisfies `fix f = f (fix f)` for all
`f`, but this is inconsistent / uninteresting in most cases due to the existence of "exotic"
functions `f`, such as the function that is defined iff its argument is not, familiar from the
halting problem. Instead, this requirement is limited to only functions that are `continuous` in the
sense of `ω`-complete partial orders, which excludes the example because it is not monotone
(making the input argument less defined can make `f` more defined). -/
class lawful_fix (α : Type*) [omega_complete_partial_order α] extends has_fix α :=
(fix_eq : ∀ {f : α →ₘ α}, continuous f → has_fix.fix f = f (has_fix.fix f))
lemma lawful_fix.fix_eq' {α} [omega_complete_partial_order α] [lawful_fix α]
{f : α → α} (hf : continuous' f) :
has_fix.fix f = f (has_fix.fix f) :=
lawful_fix.fix_eq (continuous.to_bundled _ hf)
namespace roption
open roption nat nat.upto
namespace fix
variables (f : (Π a, roption $ β a) →ₘ (Π a, roption $ β a))
lemma approx_mono' {i : ℕ} : fix.approx f i ≤ fix.approx f (succ i) :=
begin
induction i, dsimp [approx], apply @bot_le _ _ (f ⊥),
intro, apply f.monotone, apply i_ih
end
lemma approx_mono ⦃i j : ℕ⦄ (hij : i ≤ j) : approx f i ≤ approx f j :=
begin
induction j, cases hij, refine @le_refl _ _ _,
cases hij, apply @le_refl _ _ _,
apply @le_trans _ _ _ (approx f j_n) _ (j_ih hij_a),
apply approx_mono' f
end
lemma mem_iff (a : α) (b : β a) : b ∈ roption.fix f a ↔ ∃ i, b ∈ approx f i a :=
begin
by_cases h₀ : ∃ (i : ℕ), (approx f i a).dom,
{ simp only [roption.fix_def f h₀],
split; intro hh, exact ⟨_,hh⟩,
have h₁ := nat.find_spec h₀,
rw [dom_iff_mem] at h₁,
cases h₁ with y h₁,
replace h₁ := approx_mono' f _ _ h₁,
suffices : y = b, subst this, exact h₁,
cases hh with i hh,
revert h₁, generalize : (succ (nat.find h₀)) = j, intro,
wlog : i ≤ j := le_total i j using [i j b y,j i y b],
replace hh := approx_mono f case _ _ hh,
apply roption.mem_unique h₁ hh },
{ simp only [fix_def' ⇑f h₀, not_exists, false_iff, not_mem_none],
simp only [dom_iff_mem, not_exists] at h₀,
intro, apply h₀ }
end
lemma approx_le_fix (i : ℕ) : approx f i ≤ roption.fix f :=
assume a b hh,
by { rw [mem_iff f], exact ⟨_,hh⟩ }
lemma exists_fix_le_approx (x : α) : ∃ i, roption.fix f x ≤ approx f i x :=
begin
by_cases hh : ∃ i b, b ∈ approx f i x,
{ rcases hh with ⟨i,b,hb⟩, existsi i,
intros b' h',
have hb' := approx_le_fix f i _ _ hb,
have hh := roption.mem_unique h' hb',
subst hh, exact hb },
{ simp only [not_exists] at hh, existsi 0,
intros b' h',
simp only [mem_iff f] at h',
cases h' with i h',
cases hh _ _ h' }
end
include f
/-- The series of approximations of `fix f` (see `approx`) as a `chain` -/
def approx_chain : chain (Π a, roption $ β a) := ⟨approx f, approx_mono f⟩
lemma le_f_of_mem_approx {x} (hx : x ∈ approx_chain f) : x ≤ f x :=
begin
revert hx, simp [(∈)],
intros i hx, subst x,
apply approx_mono'
end
lemma approx_mem_approx_chain {i} : approx f i ∈ approx_chain f :=
stream.mem_of_nth_eq rfl
end fix
open fix
variables {α}
variables (f : (Π a, roption $ β a) →ₘ (Π a, roption $ β a))
open omega_complete_partial_order
open roption (hiding ωSup) nat
open nat.upto omega_complete_partial_order
lemma fix_eq_ωSup : roption.fix f = ωSup (approx_chain f) :=
begin
apply le_antisymm,
{ intro x, cases exists_fix_le_approx f x with i hx,
transitivity' approx f i.succ x,
{ transitivity', apply hx, apply approx_mono' f },
apply' le_ωSup_of_le i.succ,
dsimp [approx], refl', },
{ apply ωSup_le _ _ _,
simp only [fix.approx_chain, preorder_hom.coe_fun_mk],
intros y x, apply approx_le_fix f },
end
lemma fix_le {X : Π a, roption $ β a} (hX : f X ≤ X) : roption.fix f ≤ X :=
begin
rw fix_eq_ωSup f,
apply ωSup_le _ _ _,
simp only [fix.approx_chain, preorder_hom.coe_fun_mk],
intros i,
induction i, dsimp [fix.approx], apply' bot_le,
transitivity' f X, apply f.monotone i_ih,
apply hX
end
variables {f} (hc : continuous f)
include hc
lemma fix_eq : roption.fix f = f (roption.fix f) :=
begin
rw [fix_eq_ωSup f,hc],
apply le_antisymm,
{ apply ωSup_le_ωSup_of_le _,
intros i, existsi [i], intro x, -- intros x y hx,
apply le_f_of_mem_approx _ ⟨i, rfl⟩, },
{ apply ωSup_le_ωSup_of_le _,
intros i, existsi i.succ, refl', }
end
end roption
namespace roption
/-- `to_unit` as a monotone function -/
@[simps]
def to_unit_mono (f : roption α →ₘ roption α) : (unit → roption α) →ₘ (unit → roption α) :=
{ to_fun := λ x u, f (x u),
monotone' := λ x y (h : x ≤ y) u, f.monotone $ h u }
lemma to_unit_cont (f : roption α →ₘ roption α) (hc : continuous f) : continuous (to_unit_mono f)
| c := begin
ext ⟨⟩ : 1,
dsimp [omega_complete_partial_order.ωSup],
erw [hc, chain.map_comp], refl
end
noncomputable instance : lawful_fix (roption α) :=
⟨λ f hc, show roption.fix (to_unit_mono f) () = _, by rw roption.fix_eq (to_unit_cont f hc); refl⟩
end roption
open sigma
namespace pi
noncomputable instance {β} : lawful_fix (α → roption β) := ⟨λ f, roption.fix_eq⟩
variables {γ : Π a : α, β a → Type*}
section monotone
variables (α β γ)
/-- `sigma.curry` as a monotone function. -/
@[simps]
def monotone_curry [∀ x y, preorder $ γ x y] :
(Π x : Σ a, β a, γ x.1 x.2) →ₘ (Π a (b : β a), γ a b) :=
{ to_fun := curry,
monotone' := λ x y h a b, h ⟨a,b⟩ }
/-- `sigma.uncurry` as a monotone function. -/
@[simps]
def monotone_uncurry [∀ x y, preorder $ γ x y] :
(Π a (b : β a), γ a b) →ₘ (Π x : Σ a, β a, γ x.1 x.2) :=
{ to_fun := uncurry,
monotone' := λ x y h a, h a.1 a.2 }
variables [∀ x y, omega_complete_partial_order $ γ x y]
open omega_complete_partial_order.chain
lemma continuous_curry : continuous $ monotone_curry α β γ :=
λ c, by { ext x y, dsimp [curry,ωSup], rw [map_comp,map_comp], refl }
lemma continuous_uncurry : continuous $ monotone_uncurry α β γ :=
λ c, by { ext x y, dsimp [uncurry,ωSup], rw [map_comp,map_comp], refl }
end monotone
open has_fix
instance [has_fix $ Π x : sigma β, γ x.1 x.2] : has_fix (Π x (y : β x), γ x y) :=
⟨ λ f, curry (fix $ uncurry ∘ f ∘ curry) ⟩
variables [∀ x y, omega_complete_partial_order $ γ x y]
section curry
variables {f : (Π x (y : β x), γ x y) →ₘ (Π x (y : β x), γ x y)}
variables (hc : continuous f)
lemma uncurry_curry_continuous : continuous $ (monotone_uncurry α β γ).comp $ f.comp $ monotone_curry α β γ :=
continuous_comp _ _
(continuous_comp _ _ (continuous_curry _ _ _) hc)
(continuous_uncurry _ _ _)
end curry
instance pi.lawful_fix' [lawful_fix $ Π x : sigma β, γ x.1 x.2] : lawful_fix (Π x y, γ x y) :=
{ fix_eq := λ f hc,
by { dsimp [fix], conv { to_lhs, erw [lawful_fix.fix_eq (uncurry_curry_continuous hc)] }, refl, } }
end pi
|
1ed29d5a40c3dd603f9dc76b48ae615b42b2e2a9 | fe25de614feb5587799621c41487aaee0d083b08 | /stage0/src/Lean/Elab/Deriving/FromToJson.lean | 3a0fd8f9dcdb43f407298c6fc3297fd49d0aee43 | [
"Apache-2.0"
] | permissive | pollend/lean4 | e8469c2f5fb8779b773618c3267883cf21fb9fac | c913886938c4b3b83238a3f99673c6c5a9cec270 | refs/heads/master | 1,687,973,251,481 | 1,628,039,739,000 | 1,628,039,739,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,581 | 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 auxCmd ← `(match $[$discrs],* with $alts:matchAlt*)
let 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 declModsF := Parser.Command.declModifiers false
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 matchCmd ← alts.foldrM (fun xs x => `($xs <|> $x)) (←`(Except.error "no inductive constructor matched"))
let declMods ← if indVal.isRec then `(declModsF| private partial) else `(declModsF| private)
let cmd ← `($declMods:declModifiers def $fromJsonFuncId:ident $header.binders:explicitBinder* (json : Json)
: Except String $(← mkInductiveApp ctx.typeInfos[0] header.argNames) :=
$matchCmd )
return #[cmd] ++ (← 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
|
e64f63c1d1c359201db59a6b07c9ed357ef82107 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/field_theory/separable.lean | 133da3305d72f7b3369f1a2ce5cc452380e78886 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 21,379 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.polynomial.big_operators
import algebra.squarefree
import field_theory.minpoly
import field_theory.splitting_field
import data.polynomial.expand
/-!
# Separable polynomials
We define a polynomial to be separable if it is coprime with its derivative. We prove basic
properties about separable polynomials here.
## Main definitions
* `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative.
* `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a
commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`.
* `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`.
-/
universes u v w
open_locale classical big_operators polynomial
open finset
namespace polynomial
section comm_semiring
variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S]
/-- A polynomial is separable iff it is coprime with its derivative. -/
def separable (f : R[X]) : Prop :=
is_coprime f f.derivative
lemma separable_def (f : R[X]) :
f.separable ↔ is_coprime f f.derivative :=
iff.rfl
lemma separable_def' (f : R[X]) :
f.separable ↔ ∃ a b : R[X], a * f + b * f.derivative = 1 :=
iff.rfl
lemma not_separable_zero [nontrivial R] : ¬ separable (0 : R[X]) :=
begin
rintro ⟨x, y, h⟩,
simpa only [derivative_zero, mul_zero, add_zero, zero_ne_one] using h,
end
lemma separable_one : (1 : R[X]).separable :=
is_coprime_one_left
@[nontriviality] lemma separable_of_subsingleton [subsingleton R] (f : R[X]) :
f.separable := by simp [separable]
lemma separable_X_add_C (a : R) : (X + C a).separable :=
by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero],
exact is_coprime_one_right }
lemma separable_X : (X : R[X]).separable :=
by { rw [separable_def, derivative_X], exact is_coprime_one_right }
lemma separable_C (r : R) : (C r).separable ↔ is_unit r :=
by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C]
lemma separable.of_mul_left {f g : R[X]} (h : (f * g).separable) : f.separable :=
begin
have := h.of_mul_left_left, rw derivative_mul at this,
exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this)
end
lemma separable.of_mul_right {f g : R[X]} (h : (f * g).separable) : g.separable :=
by { rw mul_comm at h, exact h.of_mul_left }
lemma separable.of_dvd {f g : R[X]} (hf : f.separable) (hfg : g ∣ f) : g.separable :=
by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf }
lemma separable_gcd_left {F : Type*} [field F] {f : F[X]}
(hf : f.separable) (g : F[X]) : (euclidean_domain.gcd f g).separable :=
separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g)
lemma separable_gcd_right {F : Type*} [field F] {g : F[X]}
(f : F[X]) (hg : g.separable) : (euclidean_domain.gcd f g).separable :=
separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g)
lemma separable.is_coprime {f g : R[X]} (h : (f * g).separable) : is_coprime f g :=
begin
have := h.of_mul_left_left, rw derivative_mul at this,
exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this)
end
theorem separable.of_pow' {f : R[X]} :
∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0
| 0 := λ h, or.inr $ or.inr rfl
| 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩
| (n+2) := λ h, by { rw [pow_succ, pow_succ] at h,
exact or.inl (is_coprime_self.1 h.is_coprime.of_mul_right_left) }
theorem separable.of_pow {f : R[X]} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0)
(hfs : (f ^ n).separable) : f.separable ∧ n = 1 :=
(hfs.of_pow'.resolve_left hf).resolve_right hn
theorem separable.map {p : R[X]} (h : p.separable) {f : R →+* S} : (p.map f).separable :=
let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f,
by rw [derivative_map, ← polynomial.map_mul, ← polynomial.map_mul, ← polynomial.map_add, H,
polynomial.map_one]⟩
variables (p q : ℕ)
lemma is_unit_of_self_mul_dvd_separable {p q : R[X]}
(hp : p.separable) (hq : q * q ∣ p) : is_unit q :=
begin
obtain ⟨p, rfl⟩ := hq,
apply is_coprime_self.mp,
have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)),
{ simp only [← mul_assoc, mul_add],
convert hp,
rw [derivative_mul, derivative_mul],
ring },
exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this)
end
lemma multiplicity_le_one_of_separable {p q : R[X]} (hq : ¬ is_unit q)
(hsep : separable p) : multiplicity q p ≤ 1 :=
begin
contrapose! hq,
apply is_unit_of_self_mul_dvd_separable hsep,
rw ← sq,
apply multiplicity.pow_dvd_of_le_multiplicity,
simpa only [nat.cast_one, nat.cast_bit0] using part_enat.add_one_le_of_lt hq
end
lemma separable.squarefree {p : R[X]} (hsep : separable p) : squarefree p :=
begin
rw multiplicity.squarefree_iff_multiplicity_le_one p,
intro f,
by_cases hunit : is_unit f,
{ exact or.inr hunit },
exact or.inl (multiplicity_le_one_of_separable hunit hsep)
end
end comm_semiring
section comm_ring
variables {R : Type u} [comm_ring R]
lemma separable_X_sub_C {x : R} : separable (X - C x) :=
by simpa only [sub_eq_add_neg, C_neg] using separable_X_add_C (-x)
lemma separable.mul {f g : R[X]} (hf : f.separable) (hg : g.separable)
(h : is_coprime f g) : (f * g).separable :=
by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left
((h.symm.mul_right hg).mul_add_right_right _) }
lemma separable_prod' {ι : Sort*} {f : ι → R[X]} {s : finset ι} :
(∀x∈s, ∀y∈s, x ≠ y → is_coprime (f x) (f y)) → (∀x∈s, (f x).separable) →
(∏ x in s, f x).separable :=
finset.induction_on s (λ _ _, separable_one) $ λ a s has ih h1 h2, begin
simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has,
exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ λ i his, h1.1.2 i his $
ne.symm $ ne_of_mem_of_not_mem his has)
end
lemma separable_prod {ι : Sort*} [fintype ι] {f : ι → R[X]}
(h1 : pairwise (is_coprime on f)) (h2 : ∀ x, (f x).separable) : (∏ x, f x).separable :=
separable_prod' (λ x hx y hy hxy, h1 x y hxy) (λ x hx, h2 x)
lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ι : Sort*} {f : ι → R} {s : finset ι}
(hfs : (∏ i in s, (X - C (f i))).separable)
{x y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y :=
begin
by_contra hxy,
rw [← insert_erase hx, prod_insert (not_mem_erase _ _),
← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy),
prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← sq] at hfs,
cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C _) two_ne_zero).2
end
lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ι : Sort*} [fintype ι] {f : ι → R}
(hfs : (∏ i, (X - C (f i))).separable) : function.injective f :=
λ x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy
lemma nodup_of_separable_prod [nontrivial R] {s : multiset R}
(hs : separable (multiset.map (λ a, X - C a) s).prod) : s.nodup :=
begin
rw multiset.nodup_iff_ne_cons_cons,
rintros a t rfl,
refine not_is_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _),
simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _)
end
/--If `is_unit n` in a `comm_ring R`, then `X ^ n - u` is separable for any unit `u`. -/
lemma separable_X_pow_sub_C_unit {n : ℕ} (u : Rˣ) (hn : is_unit (n : R)) :
separable (X ^ n - C (u : R)) :=
begin
nontriviality R,
rcases n.eq_zero_or_pos with rfl | hpos,
{ simpa using hn },
apply (separable_def' (X ^ n - C (u : R))).2,
obtain ⟨n', hn'⟩ := hn.exists_left_inv,
refine ⟨-C ↑u⁻¹, C ↑u⁻¹ * C n' * X, _⟩,
rw [derivative_sub, derivative_C, sub_zero, derivative_pow X n, derivative_X, mul_one],
calc - C ↑u⁻¹ * (X ^ n - C ↑u) + C ↑u⁻¹ * C n' * X * (↑n * X ^ (n - 1))
= C (↑u⁻¹ * ↑ u) - C ↑u⁻¹ * X^n + C ↑ u ⁻¹ * C (n' * ↑n) * (X * X ^ (n - 1)) :
by { simp only [C.map_mul, C_eq_nat_cast], ring }
... = 1 : by simp only [units.inv_mul, hn', C.map_one, mul_one, ← pow_succ,
nat.sub_add_cancel (show 1 ≤ n, from hpos), sub_add_cancel]
end
lemma root_multiplicity_le_one_of_separable [nontrivial R] {p : R[X]}
(hsep : separable p) (x : R) : root_multiplicity x p ≤ 1 :=
begin
by_cases hp : p = 0,
{ simp [hp], },
rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← part_enat.coe_le_coe, part_enat.coe_get,
nat.cast_one],
exact multiplicity_le_one_of_separable (not_is_unit_X_sub_C _) hsep
end
end comm_ring
section is_domain
variables {R : Type u} [comm_ring R] [is_domain R]
lemma count_roots_le_one {p : R[X]} (hsep : separable p) (x : R) :
p.roots.count x ≤ 1 :=
begin
rw count_roots p,
exact root_multiplicity_le_one_of_separable hsep x
end
lemma nodup_roots {p : R[X]} (hsep : separable p) : p.roots.nodup :=
multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep)
end is_domain
section field
variables {F : Type u} [field F] {K : Type v} [field K]
theorem separable_iff_derivative_ne_zero {f : F[X]} (hf : irreducible f) :
f.separable ↔ f.derivative ≠ 0 :=
⟨λ h1 h2, hf.not_unit $ is_coprime_zero_right.1 $ h2 ▸ h1,
λ h, euclidean_domain.is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4,
let ⟨u, hu⟩ := (hf.is_unit_or_is_unit hg3).resolve_left hg1 in
have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd },
not_lt_of_le (nat_degree_le_of_dvd this h) $
nat_degree_derivative_lt $ mt derivative_of_nat_degree_zero h⟩
theorem separable_map (f : F →+* K) {p : F[X]} : (p.map f).separable ↔ p.separable :=
by simp_rw [separable_def, derivative_map, is_coprime_map]
lemma separable_prod_X_sub_C_iff' {ι : Sort*} {f : ι → F} {s : finset ι} :
(∏ i in s, (X - C (f i))).separable ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) :=
⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy,
λ H, by { rw ← prod_attach, exact separable_prod' (λ x hx y hy hxy,
@pairwise_coprime_X_sub_C _ _ { x // x ∈ s } (λ x, f x)
(λ x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy)
(λ _ _, separable_X_sub_C) }⟩
lemma separable_prod_X_sub_C_iff {ι : Sort*} [fintype ι] {f : ι → F} :
(∏ i, (X - C (f i))).separable ↔ function.injective f :=
separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff, function.injective]
section char_p
variables (p : ℕ) [HF : char_p F p]
include HF
theorem separable_or {f : F[X]} (hf : irreducible f) : f.separable ∨
¬f.separable ∧ ∃ g : F[X], irreducible g ∧ expand F p g = f :=
if H : f.derivative = 0 then
begin
unfreezingI { rcases p.eq_zero_or_pos with rfl | hp },
{ haveI := char_p.char_p_to_char_zero F,
have := nat_degree_eq_zero_of_derivative_eq_zero H,
have := (nat_degree_pos_iff_degree_pos.mpr $ degree_pos_of_irreducible hf).ne',
contradiction },
haveI := is_local_ring_hom_expand F hp,
exact or.inr
⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H],
contract p f,
of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H hp.ne' at hf),
expand_contract p H hp.ne'⟩
end
else or.inl $ (separable_iff_derivative_ne_zero hf).2 H
theorem exists_separable_of_irreducible {f : F[X]} (hf : irreducible f) (hp : p ≠ 0) :
∃ (n : ℕ) (g : F[X]), g.separable ∧ expand F (p ^ n) g = f :=
begin
replace hp : p.prime := (char_p.char_is_prime_or_zero F p).resolve_right hp,
unfreezingI
{ induction hn : f.nat_degree using nat.strong_induction_on with N ih generalizing f },
rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩,
{ refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] },
{ cases N with N,
{ rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn,
rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1,
have hf0 : f ≠ 0 := hf.ne_zero,
rw [h1, C_0] at hn, exact absurd hn hf0 },
have hg1 : g.nat_degree * p = N.succ,
{ rwa [← nat_degree_expand, hgf] },
have hg2 : g.nat_degree ≠ 0,
{ intro this, rw [this, zero_mul] at hg1, cases hg1 },
have hg3 : g.nat_degree < N.succ,
{ rw [← mul_one g.nat_degree, ← hg1],
exact nat.mul_lt_mul_of_pos_left hp.one_lt hg2.bot_lt },
rcases ih _ hg3 hg rfl with ⟨n, g, hg4, rfl⟩, refine ⟨n+1, g, hg4, _⟩,
rw [← hgf, expand_expand, pow_succ] }
end
theorem is_unit_or_eq_zero_of_separable_expand {f : F[X]} (n : ℕ) (hp : 0 < p)
(hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 :=
begin
rw or_iff_not_imp_right,
rintro hn : n ≠ 0,
have hf2 : (expand F (p ^ n) f).derivative = 0,
{ rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero,
zero_pow hn.bot_lt, zero_mul, mul_zero] },
rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf,
rcases hf with ⟨r, hr, hrf⟩,
rw [eq_comm, expand_eq_C (pow_pos hp _)] at hrf,
rwa [hrf, is_unit_C]
end
theorem unique_separable_of_irreducible {f : F[X]} (hf : irreducible f) (hp : 0 < p)
(n₁ : ℕ) (g₁ : F[X]) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f)
(n₂ : ℕ) (g₂ : F[X]) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) :
n₁ = n₂ ∧ g₁ = g₂ :=
begin
revert g₁ g₂,
wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁],
have hf0 : f ≠ 0 := hf.ne_zero,
unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩,
rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp n₁)] at hgf₂, subst hgf₂,
subst hgf₁,
rcases is_unit_or_eq_zero_of_separable_expand p k hp hg₁ with h | rfl,
{ rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩,
simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 },
{ rw [add_zero, pow_zero, expand_one], split; refl } },
obtain ⟨hn, hg⟩ := this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁,
exact ⟨hn.symm, hg.symm⟩
end
end char_p
/--If `n ≠ 0` in `F`, then ` X ^ n - a` is separable for any `a ≠ 0`. -/
lemma separable_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) :
separable (X ^ n - C a) :=
separable_X_pow_sub_C_unit (units.mk0 a ha) (is_unit.mk0 n hn)
-- this can possibly be strengthened to making `separable_X_pow_sub_C_unit` a
-- bi-implication, but it is nontrivial!
/-- In a field `F`, `X ^ n - 1` is separable iff `↑n ≠ 0`. -/
lemma X_pow_sub_one_separable_iff {n : ℕ} :
(X ^ n - 1 : F[X]).separable ↔ (n : F) ≠ 0 :=
begin
refine ⟨_, λ h, separable_X_pow_sub_C_unit 1 (is_unit.mk0 ↑n h)⟩,
rw [separable_def', derivative_sub, derivative_X_pow, derivative_one, sub_zero],
-- Suppose `(n : F) = 0`, then the derivative is `0`, so `X ^ n - 1` is a unit, contradiction.
rintro (h : is_coprime _ _) hn',
rw [← C_eq_nat_cast, hn', C.map_zero, zero_mul, is_coprime_zero_right] at h,
have := not_is_unit_X_pow_sub_one F n,
contradiction
end
section splits
lemma card_root_set_eq_nat_degree [algebra F K] {p : F[X]} (hsep : p.separable)
(hsplit : splits (algebra_map F K) p) : fintype.card (p.root_set K) = p.nat_degree :=
begin
simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe],
rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots hsplit],
exact nodup_roots hsep.map,
end
variable {i : F →+* K}
lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : F[X]}
(h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h)
(h_roots : ∀ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) :=
begin
have h_ne_zero : h ≠ 0 := by { rintro rfl, exact not_separable_zero h_sep },
apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits,
apply finset.mk.inj,
{ change _ = {i x},
rw finset.eq_singleton_iff_unique_mem,
split,
{ apply finset.mem_mk.mpr,
rw mem_roots (show h.map i ≠ 0, by exact map_ne_zero h_ne_zero),
rw [is_root.def,←eval₂_eq_eval_map,eval₂_hom,h_root],
exact ring_hom.map_zero i },
{ exact h_roots } },
{ exact nodup_roots (separable.map h_sep) },
end
lemma exists_finset_of_splits
(i : F →+* K) {f : F[X]} (sep : separable f) (sp : splits i f) :
∃ (s : finset K), f.map i = C (i f.leading_coeff) * (s.prod (λ a : K, X - C a)) :=
begin
obtain ⟨s, h⟩ := (splits_iff_exists_multiset _).1 sp,
use s.to_finset,
rw [h, finset.prod_eq_multiset_prod, ←multiset.to_finset_eq],
apply nodup_of_separable_prod,
apply separable.of_mul_right,
rw ←h,
exact sep.map,
end
end splits
theorem _root_.irreducible.separable [char_zero F] {f : F[X]}
(hf : irreducible f) : f.separable :=
begin
rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq],
{ rintro ⟨⟩ },
rw [pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff],
refine λ hf1, hf.not_unit _,
rw [hf1, is_unit_C, is_unit_iff_ne_zero],
intro hf2,
rw [hf2, C_0] at hf1,
exact absurd hf1 hf.ne_zero
end
end field
end polynomial
open polynomial
section comm_ring
variables (F K : Type*) [comm_ring F] [ring K] [algebra F K]
-- TODO: refactor to allow transcendental extensions?
-- See: https://en.wikipedia.org/wiki/Separable_extension#Separability_of_transcendental_extensions
-- Note that right now a Galois extension (class `is_galois`) is defined to be an extension which
-- is separable and normal, so if the definition of separable changes here at some point
-- to allow non-algebraic extensions, then the definition of `is_galois` must also be changed.
/-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff
the minimal polynomial of every `x : K` is separable.
We define this for general (commutative) rings and only assume `F` and `K` are fields if this
is needed for a proof.
-/
class is_separable : Prop :=
(is_integral' (x : K) : is_integral F x)
(separable' (x : K) : (minpoly F x).separable)
variables (F) {K}
theorem is_separable.is_integral [is_separable F K] :
∀ x : K, is_integral F x := is_separable.is_integral'
theorem is_separable.separable [is_separable F K] :
∀ x : K, (minpoly F x).separable := is_separable.separable'
variables {F K}
theorem is_separable_iff : is_separable F K ↔ ∀ x : K, is_integral F x ∧ (minpoly F x).separable :=
⟨λ h x, ⟨@@is_separable.is_integral F _ _ _ h x, @@is_separable.separable F _ _ _ h x⟩,
λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩
end comm_ring
instance is_separable_self (F : Type*) [field F] : is_separable F F :=
⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact separable_X_sub_C }⟩
/-- A finite field extension in characteristic 0 is separable. -/
@[priority 100] -- See note [lower instance priority]
instance is_separable.of_finite (F K : Type*) [field F] [field K] [algebra F K]
[finite_dimensional F K] [char_zero F] : is_separable F K :=
have ∀ (x : K), is_integral F x,
from λ x, algebra.is_integral_of_finite _ _ _,
⟨this, λ x, (minpoly.irreducible (this x)).separable⟩
section is_separable_tower
variables (F K E : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E]
[algebra K E] [is_scalar_tower F K E]
lemma is_separable_tower_top_of_is_separable [is_separable F E] : is_separable K E :=
⟨λ x, is_integral_of_is_scalar_tower x (is_separable.is_integral F x),
λ x, (is_separable.separable F x).map.of_dvd (minpoly.dvd_map_of_is_scalar_tower _ _ _)⟩
lemma is_separable_tower_bot_of_is_separable [h : is_separable F E] : is_separable F K :=
is_separable_iff.2 $ λ x, begin
refine (is_separable_iff.1 h (algebra_map K E x)).imp
is_integral_tower_bot_of_is_integral_field (λ hs, _),
obtain ⟨q, hq⟩ := minpoly.dvd F x
(is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero_field
(minpoly.aeval F ((algebra_map K E) x))),
rw hq at hs,
exact hs.of_mul_left
end
variables {E}
lemma is_separable.of_alg_hom (E' : Type*) [field E'] [algebra F E']
(f : E →ₐ[F] E') [is_separable F E'] : is_separable F E :=
begin
letI : algebra E E' := ring_hom.to_algebra f.to_ring_hom,
haveI : is_scalar_tower F E E' := is_scalar_tower.of_algebra_map_eq (λ x, (f.commutes x).symm),
exact is_separable_tower_bot_of_is_separable F E E',
end
end is_separable_tower
section card_alg_hom
variables {R S T : Type*} [comm_ring S]
variables {K L F : Type*} [field K] [field L] [field F]
variables [algebra K S] [algebra K L]
lemma alg_hom.card_of_power_basis (pb : power_basis K S) (h_sep : (minpoly K pb.gen).separable)
(h_splits : (minpoly K pb.gen).splits (algebra_map K L)) :
@fintype.card (S →ₐ[K] L) (power_basis.alg_hom.fintype pb) = pb.dim :=
begin
let s := ((minpoly K pb.gen).map (algebra_map K L)).roots.to_finset,
have H := λ x, multiset.mem_to_finset,
rw [fintype.card_congr pb.lift_equiv', fintype.card_of_subtype s H,
← pb.nat_degree_minpoly, nat_degree_eq_card_roots h_splits, multiset.to_finset_card_of_nodup],
exact nodup_roots ((separable_map (algebra_map K L)).mpr h_sep)
end
end card_alg_hom
|
4c81d1b137736386b8c4dc25280b5fae60c2e1d6 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/meta2.lean | b368882c15d514d9926aeb0772e8d32f0806727e | [
"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 | 218 | lean | import system.io
open io
meta definition foo : nat → nat
| a := nat.cases_on a 1 (λ n, foo n + 2)
#eval (foo 10)
meta definition loop : nat → io unit
| a := do put_str ">> ", print a, put_str "\n", loop (a+1)
|
4d0549e35c94105347fe0e9ce32e2ed87870d278 | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/apply_fun.lean | 59562ed116f0eedb847d8e15fd163a56f9ce3bb6 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 2,759 | lean | /-
Copyright (c) 2019 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Patrick Massot
-/
import tactic.monotonicity
namespace tactic
/-- Apply the function `f` given by `e : pexpr` to the local hypothesis `hyp`, which must either be
of the form `a = b` or `a ≤ b`, replacing the type of `hyp` with `f a = f b` or `f a ≤ f b`. If
`hyp` names an inequality then a new goal `monotone f` is created, unless the name of a proof of
this fact is passed as the optional argument `mono_lem`, or the `mono` tactic can prove it.
-/
meta def apply_fun_to_hyp (e : pexpr) (mono_lem : option pexpr) (hyp : expr) : tactic unit :=
do {
t ← infer_type hyp,
prf ← match t with
| `(%%l = %%r) := do
ltp ← infer_type l,
mv ← mk_mvar,
to_expr ``(congr_arg (%%e : %%ltp → %%mv) %%hyp)
| `(%%l ≤ %%r) := do
Hmono ← match mono_lem with
| some mono_lem :=
tactic.i_to_expr mono_lem
| none := do
n ← get_unused_name `mono,
to_expr ``(monotone %%e) >>= assert n,
do { intro_lst [`x, `y, `h], `[dsimp, mono], skip } <|> swap,
get_local n
end,
to_expr ``(%%Hmono %%hyp)
| _ := fail ("failed to apply " ++ to_string e ++ " at " ++ to_string hyp.local_pp_name)
end,
clear hyp,
hyp ← note hyp.local_pp_name none prf,
-- let's try to force β-reduction at `h`
try $ tactic.dsimp_hyp hyp none [] { eta := false, beta := true }
}
namespace interactive
setup_tactic_parser
/--
Apply a function to some local assumptions which are either equalities
or inequalities. For instance, if the context contains `h : a = b` and
some function `f` then `apply_fun f at h` turns `h` into
`h : f a = f b`. When the assumption is an inequality `h : a ≤ b`, a side
goal `monotone f` is created, unless this condition is provided using
`apply_fun f at h using P` where `P : monotone f`, or the `mono` tactic
can prove it.
Typical usage is:
```lean
open function
example (X Y Z : Type) (f : X → Y) (g : Y → Z) (H : injective $ g ∘ f) :
injective f :=
begin
intros x x' h,
apply_fun g at h,
exact H h
end
```
-/
meta def apply_fun (q : parse texpr) (locs : parse location) (lem : parse (tk "using" *> texpr)?)
: tactic unit :=
match locs with
| (loc.ns l) := l.mmap' $ option.mmap $ λ h, get_local h >>= apply_fun_to_hyp q lem
| wildcard := local_context >>= list.mmap' (apply_fun_to_hyp q lem)
end
add_tactic_doc
{ name := "apply_fun",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_fun],
tags := ["context management"] }
end interactive
end tactic
|
5236ec85ba2acc6aaf397bdcbe1da75aabeaeecb | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch4/ex0204.lean | 5e5c48a29c2579cbd455a5d2947b3d9478146387 | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 153 | lean | universe u
variables (α : Type u) (a b c d : α)
variables (hab : a = b) (hcb : c = b) (hcd : c = d)
example : a = d := (hab.trans hcb.symm).trans hcd
|
810ff3830926eb9b3cbcf34746828a2ed43c0355 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/compiler/partial.lean | 7a9139a8f5610d5450498cc50c627192ae6d72ef | [
"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 | 341 | lean |
set_option pp.explicit true
-- set_option trace.compiler.boxed true
partial def contains : String → Char → Nat → Bool
| s, c, i =>
if s.atEnd i then false
else if s.get i == c then true
else contains s c (s.next i)
def main : IO Unit :=
let s1 := "hello";
IO.println (contains s1 'a' 0) *>
IO.println (contains s1 'o' 0)
|
b7d9a08a4fd076ed2de97c0851039c36465f98cd | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/topology/algebra/ordered.lean | b88f7db7aec4b390dcea4c26fe6249352a4a47dd | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 78,936 | 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, Yury Kudryashov
-/
import tactic.tfae
import order.liminf_limsup
import data.set.intervals
import topology.algebra.group
import topology.constructions
/-! # Theory of topology on ordered spaces
## Main definitions
The order topology on an ordered space is the topology generated by all open intervals (or
equivalently by those of the form `(-∞, a)` and `(b, +∞)`). We define it as `preorder.topology α`.
However, we do *not* register it as an instance (as many existing ordered types already have
topologies, which would be equal but not definitionally equal to `preorder.topology α`). Instead,
we introduce a class `order_topology α`(which is a `Prop`, also known as a mixin) saying that on
the type `α` having already a topological space structure and a preorder structure, the topological
structure is equal to the order topology.
We also introduce another (mixin) class `order_closed_topology α` saying that the set of points
`(x, y)` with `x ≤ y` is closed in the product space. This is automatically satisfied on a linear
order with the order topology.
We prove many basic properties of such topologies.
## Main statements
This file contains the proofs of the following facts. For exact requirements (`order_closed_topology`
vs `order_topology`, `preorder` vs `partial_order` vs `linear_order` etc) see their statements.
### Open / closed sets
* `is_open_lt` : if `f` and `g` are continuous functions, then `{x | f x < g x}` is open;
* `is_open_Iio`, `is_open_Ioi`, `is_open_Ioo` : open intervals are open;
* `is_closed_le` : if `f` and `g` are continuous functions, then `{x | f x ≤ g x}` is closed;
* `is_closed_Iic`, `is_closed_Ici`, `is_closed_Icc` : closed intervals are closed;
* `frontier_le_subset_eq`, `frontier_lt_subset_eq` : frontiers of both `{x | f x ≤ g x}`
and `{x | f x < g x}` are included by `{x | f x = g x}`;
* `exists_Ioc_subset_of_mem_nhds`, `exists_Ico_subset_of_mem_nhds` : if `x < y`, then any
neighborhood of `x` includes an interval `[x, z)` for some `z ∈ (x, y]`, and any neighborhood
of `y` includes an interval `(z, y]` for some `z ∈ [x, y)`.
### Convergence and inequalities
* `le_of_tendsto_of_tendsto` : if `f` converges to `a`, `g` converges to `b`, and eventually
`f x ≤ g x`, then `a ≤ b`
* `le_of_tendsto`, `ge_of_tendsto` : if `f` converges to `a` and eventually `f x ≤ b`
(resp., `b ≤ f x`), then `a ≤ b` (resp., `b ≤ a); we also provide primed versions
that assume the inequalities to hold for all `x`.
### Min, max, `Sup` and `Inf`
* `continuous.min`, `continuous.max`: pointwise `min`/`max` of two continuous functions is continuous.
* `tendsto.min`, `tendsto.max` : if `f` tends to `a` and `g` tends to `b`, then their pointwise
`min`/`max` tend to `min a b` and `max a b`, respectively.
* `tendsto_of_tendsto_of_tendsto_of_le_of_le` : theorem known as squeeze theorem,
sandwich theorem, theorem of Carabinieri, and two policemen (and a drunk) theorem; if `g` and `h`
both converge to `a`, and eventually `g x ≤ f x ≤ h x`, then `f` converges to `a`.
### Connected sets and Intermediate Value Theorem
* `is_connected_I??` : all intervals `I??` are connected,
* `is_connected.intermediate_value`, `intermediate_value_univ` : Intermediate Value Theorem for
connected sets and connected spaces, respectively;
* `intermediate_value_Icc`, `intermediate_value_Icc'`: Intermediate Value Theorem for functions
on closed intervals.
### Miscellaneous facts
* `compact.exists_forall_le`, `compact.exists_forall_ge` : extreme value theorem, a continuous
function on a compact set takes its minimum and maximum values.
* `is_closed.Icc_subset_of_forall_mem_nhds_within` : “Continuous induction” principle;
if `s ∩ [a, b]` is closed, `a ∈ s`, and for each `x ∈ [a, b) ∩ s` some of its right neighborhoods
is included `s`, then `[a, b] ⊆ s`.
* `is_closed.Icc_subset_of_forall_exists_gt`, `is_closed.mem_of_ge_of_forall_exists_gt` : two
other versions of the “continuous induction” principle.
## Implementation
We do _not_ register the order topology as an instance on a preorder (or even on a linear order).
Indeed, on many such spaces, a topology has already been constructed in a different way (think
of the discrete spaces `ℕ` or `ℤ`, or `ℝ` that could inherit a topology as the completion of `ℚ`),
and is in general not defeq to the one generated by the intervals. We make it available as a
definition `preorder.topology α` though, that can be registered as an instance when necessary, or
for specific types.
-/
open classical set filter topological_space
open_locale topological_space classical
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- A topology on a set which is both a topological space and a preorder is _order-closed_ if the
set of points `(x, y)` with `x ≤ y` is closed in the product space. We introduce this as a mixin.
This property is satisfied for the order topology on a linear order, but it can be satisfied more
generally, and suffices to derive many interesting properties relating order and topology. -/
class order_closed_topology (α : Type*) [topological_space α] [preorder α] : Prop :=
(is_closed_le' : is_closed (λp:α×α, p.1 ≤ p.2))
instance : Π [topological_space α], topological_space (order_dual α) := id
section order_closed_topology
section preorder
variables [topological_space α] [preorder α] [t : order_closed_topology α]
include t
lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
is_closed {b | f b ≤ g b} :=
continuous_iff_is_closed.mp (hf.prod_mk hg) _ t.is_closed_le'
lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} :=
is_closed_le continuous_id continuous_const
lemma is_closed_Iic {a : α} : is_closed (Iic a) :=
is_closed_le' a
lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} :=
is_closed_le continuous_const continuous_id
lemma is_closed_Ici {a : α} : is_closed (Ici a) :=
is_closed_ge' a
instance : order_closed_topology (order_dual α) :=
⟨continuous_swap _ (@order_closed_topology.is_closed_le' α _ _ _)⟩
lemma is_closed_Icc {a b : α} : is_closed (Icc a b) :=
is_closed_inter is_closed_Ici is_closed_Iic
lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} (hb : b ≠ ⊥)
(hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : ∀ᶠ x in b, f x ≤ g x) :
a₁ ≤ a₂ :=
have tendsto (λb, (f b, g b)) b (𝓝 (a₁, a₂)),
by rw [nhds_prod_eq]; exact hf.prod_mk hg,
show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2},
from mem_of_closed_of_tendsto hb this t.is_closed_le' h
lemma le_of_tendsto_of_tendsto' {f g : β → α} {b : filter β} {a₁ a₂ : α} (hb : b ≠ ⊥)
(hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : ∀ x, f x ≤ g x) :
a₁ ≤ a₂ :=
le_of_tendsto_of_tendsto hb hf hg (eventually_of_forall _ h)
lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β}
(nt : x ≠ ⊥) (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, f c ≤ b) : a ≤ b :=
le_of_tendsto_of_tendsto nt lim tendsto_const_nhds h
lemma le_of_tendsto' {f : β → α} {a b : α} {x : filter β}
(nt : x ≠ ⊥) (lim : tendsto f x (𝓝 a)) (h : ∀ c, f c ≤ b) : a ≤ b :=
le_of_tendsto nt lim (eventually_of_forall _ h)
lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β}
(nt : x ≠ ⊥) (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, b ≤ f c) : b ≤ a :=
le_of_tendsto_of_tendsto nt tendsto_const_nhds lim h
lemma ge_of_tendsto' {f : β → α} {a b : α} {x : filter β}
(nt : x ≠ ⊥) (lim : tendsto f x (𝓝 a)) (h : ∀ c, b ≤ f c) : b ≤ a :=
ge_of_tendsto nt lim (eventually_of_forall _ h)
@[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
closure {b | f b ≤ g b} = {b | f b ≤ g b} :=
closure_eq_iff_is_closed.mpr $ is_closed_le hf hg
lemma closure_lt_subset_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
closure {b | f b < g b} ⊆ {b | f b ≤ g b} :=
by { rw [←closure_le_eq hf hg], exact closure_mono (λ b, le_of_lt) }
lemma continuous_within_at.closure_le [topological_space β]
{f g : β → α} {s : set β} {x : β} (hx : x ∈ closure s)
(hf : continuous_within_at f s x)
(hg : continuous_within_at g s x)
(h : ∀ y ∈ s, f y ≤ g y) : f x ≤ g x :=
begin
show (f x, g x) ∈ {p : α × α | p.1 ≤ p.2},
suffices : (f x, g x) ∈ closure {p : α × α | p.1 ≤ p.2},
begin
rwa closure_eq_iff_is_closed.2 at this,
exact order_closed_topology.is_closed_le'
end,
exact (continuous_within_at.prod hf hg).mem_closure hx h
end
end preorder
section partial_order
variables [topological_space α] [partial_order α] [t : order_closed_topology α]
include t
private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} :=
by simp [le_antisymm_iff];
exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst)
@[priority 90] -- see Note [lower instance priority]
instance order_closed_topology.to_t2_space : t2_space α :=
{ t2 :=
have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq,
assume a b h,
let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in
⟨u, v, hu, hv, ha, hb,
set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩,
have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩,
this rfl⟩ }
end partial_order
section linear_order
variables [topological_space α] [linear_order α] [order_closed_topology α]
lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
is_open {b | f b < g b} :=
by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf
variables {a b : α}
lemma is_open_Iio : is_open (Iio a) :=
is_open_lt continuous_id continuous_const
lemma is_open_Ioi : is_open (Ioi a) :=
is_open_lt continuous_const continuous_id
lemma is_open_Ioo : is_open (Ioo a b) :=
is_open_inter is_open_Ioi is_open_Iio
@[simp] lemma interior_Ioi : interior (Ioi a) = Ioi a :=
interior_eq_of_open is_open_Ioi
@[simp] lemma interior_Iio : interior (Iio a) = Iio a :=
interior_eq_of_open is_open_Iio
@[simp] lemma interior_Ioo : interior (Ioo a b) = Ioo a b :=
interior_eq_of_open is_open_Ioo
lemma is_preconnected.forall_Icc_subset {s : set α} (hs : is_preconnected s)
{a b : α} (ha : a ∈ s) (hb : b ∈ s) :
Icc a b ⊆ s :=
begin
assume x hx,
obtain ⟨y, hy, hy'⟩ : (s ∩ ((Iic x) ∩ (Ici x))).nonempty,
from is_preconnected_closed_iff.1 hs (Iic x) (Ici x) is_closed_Iic is_closed_Ici
(λ y _, le_total y x) ⟨a, ha, hx.1⟩ ⟨b, hb, hx.2⟩,
exact le_antisymm hy'.1 hy'.2 ▸ hy
end
/-- Intermediate Value Theorem for continuous functions on connected sets. -/
lemma is_preconnected.intermediate_value {γ : Type*} [topological_space γ] {s : set γ}
(hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f : γ → α} (hf : continuous_on f s) :
Icc (f a) (f b) ⊆ f '' s :=
(hs.image f hf).forall_Icc_subset (mem_image_of_mem f ha) (mem_image_of_mem f hb)
/-- Intermediate Value Theorem for continuous functions on connected spaces. -/
lemma intermediate_value_univ {γ : Type*} [topological_space γ] [H : preconnected_space γ]
(a b : γ) {f : γ → α} (hf : continuous f) :
Icc (f a) (f b) ⊆ range f :=
@image_univ _ _ f ▸ H.is_preconnected_univ.intermediate_value trivial trivial hf.continuous_on
end linear_order
section decidable_linear_order
variables [topological_space α] [decidable_linear_order α] [order_closed_topology α] {f g : β → α}
section
variables [topological_space β] (hf : continuous f) (hg : continuous g)
include hf hg
lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} :=
begin
rw [frontier_eq_closure_inter_closure, closure_le_eq hf hg],
rintros b ⟨hb₁, hb₂⟩,
refine le_antisymm hb₁ (closure_lt_subset_le hg hf _),
convert hb₂ using 2, simp only [not_le.symm], refl
end
lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} :=
by rw ← frontier_compl;
convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm]
lemma continuous.max : continuous (λb, max (f b) (g b)) :=
have ∀b∈frontier {b | f b ≤ g b}, g b = f b, from assume b hb, (frontier_le_subset_eq hf hg hb).symm,
continuous_if this hg hf
lemma continuous.min : continuous (λb, min (f b) (g b)) :=
have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb,
continuous_if this hf hg
end
lemma tendsto.max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) :
tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) :=
show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (max a₁ a₂)),
from tendsto.comp
begin
rw [←nhds_prod_eq],
from continuous_iff_continuous_at.mp (continuous_fst.max continuous_snd) _
end
(hf.prod_mk hg)
lemma tendsto.min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) :
tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) :=
show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (min a₁ a₂)),
from tendsto.comp
begin
rw [←nhds_prod_eq],
from continuous_iff_continuous_at.mp (continuous_fst.min continuous_snd) _
end
(hf.prod_mk hg)
end decidable_linear_order
end order_closed_topology
/-- The order topology on an ordered type is the topology generated by open intervals. We register
it on a preorder, but it is mostly interesting in linear orders, where it is also order-closed.
We define it as a mixin. If you want to introduce the order topology on a preorder, use
`preorder.topology`. -/
class order_topology (α : Type*) [t : topological_space α] [preorder α] : Prop :=
(topology_eq_generate_intervals : t = generate_from {s | ∃a, s = Ioi a ∨ s = Iio a})
/-- (Order) topology on a partial order `α` generated by the subbase of open intervals
`(a, ∞) = { x ∣ a < x }, (-∞ , b) = {x ∣ x < b}` for all `a, b` in `α`. We do not register it as an
instance as many ordered sets are already endowed with the same topology, most often in a non-defeq
way though. Register as a local instance when necessary. -/
def preorder.topology (α : Type*) [preorder α] : topological_space α :=
generate_from {s : set α | ∃ (a : α), s = {b : α | a < b} ∨ s = {b : α | b < a}}
section order_topology
instance {α : Type*} [topological_space α] [partial_order α] [order_topology α] :
order_topology (order_dual α) :=
⟨by convert @order_topology.topology_eq_generate_intervals α _ _ _;
conv in (_ ∨ _) { rw or.comm }; refl⟩
section partial_order
variables [topological_space α] [partial_order α] [t : order_topology α]
include t
lemma is_open_iff_generate_intervals {s : set α} :
is_open s ↔ generate_open {s | ∃a, s = Ioi a ∨ s = Iio a} s :=
by rw [t.topology_eq_generate_intervals]; refl
lemma is_open_lt' (a : α) : is_open {b:α | a < b} :=
by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩
lemma is_open_gt' (a : α) : is_open {b:α | b < a} :=
by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩
lemma lt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a < x :=
mem_nhds_sets (is_open_lt' _) h
lemma le_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a ≤ x :=
(𝓝 b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb
lemma gt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x < b :=
mem_nhds_sets (is_open_gt' _) h
lemma ge_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b :=
(𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb
lemma nhds_eq_order (a : α) :
𝓝 a = (⨅b ∈ Iio a, principal (Ioi b)) ⊓ (⨅b ∈ Ioi a, principal (Iio b)) :=
by rw [t.topology_eq_generate_intervals, nhds_generate_from];
from le_antisymm
(le_inf
(le_infi $ assume b, le_infi $ assume hb,
infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩)
(le_infi $ assume b, le_infi $ assume hb,
infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩))
(le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩,
match s, ha, hs with
| _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h
| _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h
end)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_order {f : β → α} {a : α} {x : filter β} :
tendsto f x (𝓝 a) ↔ (∀ a' < a, ∀ᶠ b in x, a' < f b) ∧ (∀ a' > a, ∀ᶠ b in x, f b < a') :=
by simp [nhds_eq_order a, tendsto_inf, tendsto_infi, tendsto_principal]
/-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold
eventually for the filter. -/
lemma tendsto_of_tendsto_of_tendsto_of_le_of_le' {f g h : β → α} {b : filter β} {a : α}
(hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a))
(hgf : ∀ᶠ b in b, g b ≤ f b) (hfh : ∀ᶠ b in b, f b ≤ h b) :
tendsto f b (𝓝 a) :=
tendsto_order.2
⟨assume a' h',
have ∀ᶠ b in b, a' < g b, from (tendsto_order.1 hg).left a' h',
by filter_upwards [this, hgf] assume a, lt_of_lt_of_le,
assume a' h',
have ∀ᶠ b in b, h b < a', from (tendsto_order.1 hh).right a' h',
by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩
/-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold
everywhere. -/
lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α}
(hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : g ≤ f) (hfh : f ≤ h) :
tendsto f b (𝓝 a) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' hg hh
(eventually_of_forall _ hgf) (eventually_of_forall _ hfh)
lemma nhds_order_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) :
𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), principal (Ioo l u)) :=
let ⟨u, hu⟩ := hu, ⟨l, hl⟩ := hl in
calc 𝓝 a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) : nhds_eq_order a
... = (⨅b<a, principal {c | b < c} ⊓ (⨅b>a, principal {c | c < b})) :
binfi_inf hl
... = (⨅l<a, (⨅u>a, principal {c | c < u} ⊓ principal {c | l < c})) :
begin
congr, funext x,
congr, funext hx,
rw [inf_comm],
apply binfi_inf hu
end
... = _ : by simp [inter_comm]; refl
lemma tendsto_order_unbounded {f : β → α} {a : α} {x : filter β}
(hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → ∀ᶠ b in x, l < f b ∧ f b < u) :
tendsto f x (𝓝 a) :=
by rw [nhds_order_unbounded hu hl];
from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl,
tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu)
end partial_order
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem induced_order_topology' {α : Type u} {β : Type v}
[partial_order α] [ta : topological_space β] [partial_order β] [order_topology β]
(f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y)
(H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b)
(H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) :
@order_topology _ (induced f ta) _ :=
begin
letI := induced f ta,
refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩,
rw [nhds_induced, nhds_generate_from, nhds_eq_order (f a)],
apply le_antisymm,
{ refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _),
rcases hs with ⟨ab, b, rfl|rfl⟩,
{ exact mem_comap_sets.2 ⟨{x | f b < x},
mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _,
λ x, hf.1⟩ },
{ exact mem_comap_sets.2 ⟨{x | x < f b},
mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _,
λ x, hf.1⟩ } },
{ rw [← map_le_iff_le_comap],
refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp,
{ rcases H₁ h with ⟨b, ab, xb⟩,
refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)),
exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) },
{ rcases H₂ h with ⟨b, ab, xb⟩,
refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)),
exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } },
end
theorem induced_order_topology {α : Type u} {β : Type v}
[partial_order α] [ta : topological_space β] [partial_order β] [order_topology β]
(f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y)
(H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) :
@order_topology _ (induced f ta) _ :=
induced_order_topology' f @hf
(λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩)
(λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩)
lemma nhds_top_order [topological_space α] [order_top α] [order_topology α] :
𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), principal (Ioi l)) :=
by simp [nhds_eq_order (⊤:α)]
lemma nhds_bot_order [topological_space α] [order_bot α] [order_topology α] :
𝓝 (⊥:α) = (⨅l (h₂ : ⊥ < l), principal (Iio l)) :=
by simp [nhds_eq_order (⊥:α)]
section linear_order
variables [topological_space α] [linear_order α] [order_topology α]
lemma exists_Ioc_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {l : α} (hl : l < a) :
∃ l' ∈ Ico l a, Ioc l' a ⊆ s :=
begin
rw [nhds_eq_order a] at hs,
rcases hs with ⟨t₁, ht₁, t₂, ht₂, hts⟩,
-- First we show that `t₂` includes `(-∞, a]`, so it suffices to show `(l', ∞) ⊆ t₁`
suffices : ∃ l' ∈ Ico l a, Ioi l' ⊆ t₁,
{ have A : principal (Iic a) ≤ ⨅ b ∈ Ioi a, principal (Iio b),
from (le_infi $ λ b, le_infi $ λ hb, principal_mono.2 $ Iic_subset_Iio.2 hb),
have B : t₁ ∩ Iic a ⊆ s,
from subset.trans (inter_subset_inter_right _ (A ht₂)) hts,
from this.imp (λ l', Exists.imp $ λ hl' hl x hx, B ⟨hl hx.1, hx.2⟩) },
clear hts ht₂ t₂,
-- Now we find `l` such that `(l', ∞) ⊆ t₁`
letI := classical.DLO α,
rw [mem_binfi] at ht₁,
{ rcases ht₁ with ⟨b, hb, hb'⟩,
exact ⟨max b l, ⟨le_max_right _ _, max_lt hb hl⟩,
λ x hx, hb' $ Ioi_subset_Ioi (le_max_left _ _) hx⟩ },
{ intros b hb b' hb', simp only [mem_Iio] at hb hb',
use [max b b', max_lt hb hb'],
simp [le_refl] },
exact ⟨l, hl⟩
end
lemma exists_Ico_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {u : α} (hu : a < u) :
∃ u' ∈ Ioc a u, Ico a u' ⊆ s :=
begin
convert @exists_Ioc_subset_of_mem_nhds' (order_dual α) _ _ _ _ _ hs _ hu,
ext, rw [dual_Ico, dual_Ioc]
end
lemma exists_Ioc_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ l, l < a) :
∃ l < a, Ioc l a ⊆ s :=
let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ioc_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.2, hl.snd⟩
lemma exists_Ico_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ u, a < u) :
∃ u (_ : a < u), Ico a u ⊆ s :=
let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ico_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.1, hl.snd⟩
lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) :
s ∈ 𝓝 a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) :=
let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in
have 𝓝 a = (⨅p : {l // l < a} × {u // a < u}, principal (Ioo p.1.val p.2.val)),
by simp [nhds_order_unbounded hu hl, infi_subtype, infi_prod],
iff.intro
(assume hs, by rw [this] at hs; from infi_sets_induct hs
⟨l, u, hl', hu', by simp⟩
begin
intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩,
simp [set.subset_def],
intros s₁ s₂ hs₁ l' hl' u' hu' hs₂,
letI := classical.DLO α,
refine ⟨max l l', _, min u u', _⟩;
simp [*, lt_min_iff, max_lt_iff] {contextual := tt}
end
(assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩))
(assume ⟨l, u, hl, hu, h⟩,
by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂))
lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) :
∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) :=
match dense_or_discrete a₁ a₂ with
| or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂,
assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h,
assume b₁ hb₁ b₂ hb₂,
calc b₁ ≤ a₁ : h₂ _ hb₁
... < a₂ : h
... ≤ b₂ : h₁ _ hb₂⟩
end
@[priority 100] -- see Note [lower instance priority]
instance order_topology.to_order_closed_topology : order_closed_topology α :=
{ is_closed_le' :=
is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂),
have h : a₂ < a₁, from lt_of_not_ge h,
let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in
⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ }
lemma order_topology.t2_space : t2_space α := by apply_instance
@[priority 100] -- see Note [lower instance priority]
instance order_topology.regular_space : regular_space α :=
{ regular := assume s a hs ha,
have hs' : -s ∈ 𝓝 a, from mem_nhds_sets hs ha,
have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ 𝓝 a ⊓ principal t = ⊥,
from by_cases
(assume h : ∃l, l < a,
let ⟨l, hl, h⟩ := exists_Ioc_subset_of_mem_nhds hs' h in
match dense_or_discrete l a with
| or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _,
assume c hcs hca, show c < b,
from lt_of_not_ge $ assume hbc, h ⟨lt_of_lt_of_le hb₁ hbc, le_of_lt hca⟩ hcs,
inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $
assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba,
inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $
assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩
end)
(assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim,
by rw [principal_empty, inf_bot_eq]⟩),
let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in
have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ 𝓝 a ⊓ principal t = ⊥,
from by_cases
(assume h : ∃u, u > a,
let ⟨u, hu, h⟩ := exists_Ico_subset_of_mem_nhds hs' h in
match dense_or_discrete a u with
| or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _,
assume c hcs hca, show c > b,
from lt_of_not_ge $ assume hbc, h ⟨le_of_lt hca, lt_of_le_of_lt hbc hb₂⟩ hcs,
inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $
assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba,
inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $
assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩
end)
(assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim,
by rw [principal_empty, inf_bot_eq]⟩),
let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in
⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o,
assume x hx,
have x ≠ a, from assume eq, ha $ eq ▸ hx,
(ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx),
by rw [←sup_principal, inf_sup_left, ht₁a, ht₂a, bot_sup_eq]⟩,
..order_topology.t2_space }
/-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`,
provided `a` is neither a bottom element nor a top element. -/
lemma mem_nhds_iff_exists_Ioo_subset' {a l' u' : α} {s : set α}
(hl' : l' < a) (hu' : a < u') :
s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s :=
begin
split,
{ assume h,
rcases exists_Ico_subset_of_mem_nhds' h hu' with ⟨u, au, hu⟩,
rcases exists_Ioc_subset_of_mem_nhds' h hl' with ⟨l, la, hl⟩,
refine ⟨l, u, ⟨la.2, au.1⟩, λx hx, _⟩,
cases le_total a x with hax hax,
{ exact hu ⟨hax, hx.2⟩ },
{ exact hl ⟨hx.1, hax⟩ } },
{ rintros ⟨l, u, ha, h⟩,
apply mem_sets_of_superset (mem_nhds_sets is_open_Ioo ha) h }
end
/-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`. -/
lemma mem_nhds_iff_exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {s : set α} :
s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s :=
let ⟨l', hl'⟩ := no_bot a in let ⟨u', hu'⟩ := no_top a in mem_nhds_iff_exists_Ioo_subset' hl' hu'
/-!
### Neighborhoods to the left and to the right
Limits to the left and to the right of real functions are defined in terms of neighborhoods to
the left and to the right, either open or closed, i.e., members of `nhds_within a (Ioi a)` and
`nhds_wihin a (Ici a)` on the right, and similarly on the left. Such neighborhoods can be
characterized as the sets containing suitable intervals to the right or to the left of `a`.
We give now these characterizations. -/
-- NB: If you extend the list, append to the end please to avoid breaking the API
/-- The following statements are equivalent:
0. `s` is a neighborhood of `a` within `(a, +∞)`
1. `s` is a neighborhood of `a` within `(a, b]`
2. `s` is a neighborhood of `a` within `(a, b)`
3. `s` includes `(a, u)` for some `u ∈ (a, b]`
4. `s` includes `(a, u)` for some `u > a` -/
lemma tfae_mem_nhds_within_Ioi {a b : α} (hab : a < b) (s : set α) :
tfae [s ∈ nhds_within a (Ioi a), -- 0 : `s` is a neighborhood of `a` within `(a, +∞)`
s ∈ nhds_within a (Ioc a b), -- 1 : `s` is a neighborhood of `a` within `(a, b]`
s ∈ nhds_within a (Ioo a b), -- 2 : `s` is a neighborhood of `a` within `(a, b)`
∃ u ∈ Ioc a b, Ioo a u ⊆ s, -- 3 : `s` includes `(a, u)` for some `u ∈ (a, b]`
∃ u ∈ Ioi a, Ioo a u ⊆ s] := -- 4 : `s` includes `(a, u)` for some `u > a`
begin
tfae_have : 1 → 2, from λ h, nhds_within_mono _ Ioc_subset_Ioi_self h,
tfae_have : 2 → 3, from λ h, nhds_within_mono _ Ioo_subset_Ioc_self h,
tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩,
tfae_have : 5 → 1,
{ rintros ⟨u, hau, hu⟩,
exact mem_nhds_within.2 ⟨Iio u, is_open_Iio, hau, by rwa [inter_comm, Ioi_inter_Iio]⟩ },
tfae_have : 3 → 4,
{ assume h,
rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩,
rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩,
refine ⟨u, au, λx hx, _⟩,
refine hv ⟨hu ⟨le_of_lt hx.1, hx.2⟩, _⟩,
exact Ioo_subset_Ioo_right au.2 hx },
tfae_finish
end
@[simp] lemma nhds_within_Ioc_eq_nhds_within_Ioi {a b : α} (h : a < b) :
nhds_within a (Ioc a b) = nhds_within a (Ioi a) :=
filter.ext $ λ s, (tfae_mem_nhds_within_Ioi h s).out 1 0
@[simp] lemma nhds_within_Ioo_eq_nhds_within_Ioi {a b : α} (hu : a < b) :
nhds_within a (Ioo a b) = nhds_within a (Ioi a) :=
filter.ext $ λ s, (tfae_mem_nhds_within_Ioi hu s).out 2 0
lemma mem_nhds_within_Ioi_iff_exists_mem_Ioc_Ioo_subset {a u' : α} {s : set α} (hu' : a < u') :
s ∈ nhds_within a (Ioi a) ↔ ∃u ∈ Ioc a u', Ioo a u ⊆ s :=
(tfae_mem_nhds_within_Ioi hu' s).out 0 3
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)`
with `a < u < u'`, provided `a` is not a top element. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset' {a u' : α} {s : set α} (hu' : a < u') :
s ∈ nhds_within a (Ioi a) ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s :=
(tfae_mem_nhds_within_Ioi hu' s).out 0 4
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)`
with `a < u`. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset [no_top_order α] {a : α} {s : set α} :
s ∈ nhds_within a (Ioi a) ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s :=
let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ioi_iff_exists_Ioo_subset' hu'
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u]`
with `a < u`. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioc_subset [no_top_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ nhds_within a (Ioi a) ↔ ∃u ∈ Ioi a, Ioc a u ⊆ s :=
begin
rw mem_nhds_within_Ioi_iff_exists_Ioo_subset,
split,
{ rintros ⟨u, au, as⟩,
rcases dense au with ⟨v, hv⟩,
exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ },
{ rintros ⟨u, au, as⟩,
exact ⟨u, au, subset.trans Ioo_subset_Ioc_self as⟩ }
end
lemma Ioo_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ioo a c ∈ nhds_within b (Ioi b) :=
(mem_nhds_within_Ioi_iff_exists_Ioo_subset' H.2).2 ⟨c, H.2, Ioo_subset_Ioo_left H.1⟩
lemma Ioc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ioc a c ∈ nhds_within b (Ioi b) :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ioc_self
lemma Ico_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ico a c ∈ nhds_within b (Ioi b) :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ico_self
lemma Icc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Icc a c ∈ nhds_within b (Ioi b) :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Icc_self
/-- The following statements are equivalent:
0. `s` is a neighborhood of `b` within `(-∞, b)`
1. `s` is a neighborhood of `b` within `[a, b)`
2. `s` is a neighborhood of `b` within `(a, b)`
3. `s` includes `(l, b)` for some `l ∈ [a, b)`
4. `s` includes `(l, b)` for some `l < b` -/
lemma tfae_mem_nhds_within_Iio {a b : α} (h : a < b) (s : set α) :
tfae [s ∈ nhds_within b (Iio b), -- 0 : `s` is a neighborhood of `b` within `(-∞, b)`
s ∈ nhds_within b (Ico a b), -- 1 : `s` is a neighborhood of `b` within `[a, b)`
s ∈ nhds_within b (Ioo a b), -- 2 : `s` is a neighborhood of `b` within `(a, b)`
∃ l ∈ Ico a b, Ioo l b ⊆ s, -- 3 : `s` includes `(l, b)` for some `l ∈ [a, b)`
∃ l ∈ Iio b, Ioo l b ⊆ s] := -- 4 : `s` includes `(l, b)` for some `l < b`
begin
have := @tfae_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ h s,
-- If we call `convert` here, it generates wrong equations, so we need to simplify first
simp only [exists_prop] at this ⊢,
rw [dual_Ioi, dual_Ioc, dual_Ioo] at this,
convert this; ext l; rw [dual_Ioo]
end
@[simp] lemma nhds_within_Ico_eq_nhds_within_Iio {a b : α} (h : a < b) :
nhds_within b (Ico a b) = nhds_within b (Iio b) :=
filter.ext $ λ s, (tfae_mem_nhds_within_Iio h s).out 1 0
@[simp] lemma nhds_within_Ioo_eq_nhds_within_Iio {a b : α} (h : a < b) :
nhds_within b (Ioo a b) = nhds_within b (Iio b) :=
filter.ext $ λ s, (tfae_mem_nhds_within_Iio h s).out 2 0
lemma mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ nhds_within a (Iio a) ↔ ∃l ∈ Ico l' a, Ioo l a ⊆ s :=
(tfae_mem_nhds_within_Iio hl' s).out 0 3
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)`
with `l < a`, provided `a` is not a bottom element. -/
lemma mem_nhds_within_Iio_iff_exists_Ioo_subset' {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ nhds_within a (Iio a) ↔ ∃l ∈ Iio a, Ioo l a ⊆ s :=
(tfae_mem_nhds_within_Iio hl' s).out 0 4
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)`
with `l < a`. -/
lemma mem_nhds_within_Iio_iff_exists_Ioo_subset [no_bot_order α] {a : α} {s : set α} :
s ∈ nhds_within a (Iio a) ↔ ∃l ∈ Iio a, Ioo l a ⊆ s :=
let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iio_iff_exists_Ioo_subset' hl'
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `[l, a)`
with `l < a`. -/
lemma mem_nhds_within_Iio_iff_exists_Ico_subset [no_bot_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ nhds_within a (Iio a) ↔ ∃l ∈ Iio a, Ico l a ⊆ s :=
begin
convert @mem_nhds_within_Ioi_iff_exists_Ioc_subset (order_dual α) _ _ _ _ _ _ _,
simp only [dual_Ioc], refl
end
lemma Ioo_mem_nhds_within_Iio {a b c : α} (h : b ∈ Ioc a c) :
Ioo a c ∈ nhds_within b (Iio b) :=
(mem_nhds_within_Iio_iff_exists_Ioo_subset' h.1).2 ⟨a, h.1, Ioo_subset_Ioo_right h.2⟩
lemma Ioc_mem_nhds_within_Iio {a b c : α} (h : b ∈ Ioc a c) :
Ioc a c ∈ nhds_within b (Iio b) :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio h) Ioo_subset_Ioc_self
lemma Ico_mem_nhds_within_Iio {a b c : α} (h : b ∈ Ioc a c) :
Ico a c ∈ nhds_within b (Iio b) :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio h) Ioo_subset_Ico_self
lemma Icc_mem_nhds_within_Iio {a b c : α} (h : b ∈ Ioc a c) :
Icc a c ∈ nhds_within b (Iio b) :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio h) Ioo_subset_Icc_self
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)`
with `a < u`, provided `a` is not a top element. -/
lemma mem_nhds_within_Ici_iff_exists_Ico_subset' {a u' : α} {s : set α} (hu' : a < u') :
s ∈ nhds_within a (Ici a) ↔ ∃u, a < u ∧ Ico a u ⊆ s :=
begin
split,
{ assume h,
rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩,
rcases exists_Ico_subset_of_mem_nhds va ⟨u', hu'⟩ with ⟨u, au, hu⟩,
refine ⟨u, au, λx hx, _⟩,
refine hv ⟨_, hx.1⟩,
exact hu hx },
{ rintros ⟨u, au, hu⟩,
rw mem_nhds_within_iff_exists_mem_nhds_inter,
refine ⟨Iio u, mem_nhds_sets is_open_Iio au, _⟩,
rwa [inter_comm, Ici_inter_Iio] }
end
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)`
with `a < u`. -/
lemma mem_nhds_within_Ici_iff_exists_Ico_subset [no_top_order α] {a : α} {s : set α} :
s ∈ nhds_within a (Ici a) ↔ ∃u, a < u ∧ Ico a u ⊆ s :=
let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ici_iff_exists_Ico_subset' hu'
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]`
with `a < u`. -/
lemma mem_nhds_within_Ici_iff_exists_Icc_subset [no_top_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ nhds_within a (Ici a) ↔ ∃u, a < u ∧ Icc a u ⊆ s :=
begin
rw mem_nhds_within_Ici_iff_exists_Ico_subset,
split,
{ rintros ⟨u, au, as⟩,
rcases dense au with ⟨v, hv⟩,
exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ },
{ rintros ⟨u, au, as⟩,
exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ }
end
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]`
with `l < a`, provided `a` is not a bottom element. -/
lemma mem_nhds_within_Iic_iff_exists_Ioc_subset' {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ nhds_within a (Iic a) ↔ ∃l, l < a ∧ Ioc l a ⊆ s :=
begin
split,
{ assume h,
rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩,
rcases exists_Ioc_subset_of_mem_nhds va ⟨l', hl'⟩ with ⟨l, la, hl⟩,
refine ⟨l, la, λx hx, _⟩,
refine hv ⟨_, hx.2⟩,
exact hl hx },
{ rintros ⟨l, la, ha⟩,
rw mem_nhds_within_iff_exists_mem_nhds_inter,
refine ⟨Ioi l, mem_nhds_sets is_open_Ioi la, _⟩,
rwa [Ioi_inter_Iic] }
end
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]`
with `l < a`. -/
lemma mem_nhds_within_Iic_iff_exists_Ioc_subset [no_bot_order α] {a : α} {s : set α} :
s ∈ nhds_within a (Iic a) ↔ ∃l, l < a ∧ Ioc l a ⊆ s :=
let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iic_iff_exists_Ioc_subset' hl'
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]`
with `l < a`. -/
lemma mem_nhds_within_Iic_iff_exists_Icc_subset [no_bot_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ nhds_within a (Iic a) ↔ ∃l, l < a ∧ Icc l a ⊆ s :=
begin
rw mem_nhds_within_Iic_iff_exists_Ioc_subset,
split,
{ rintros ⟨l, la, as⟩,
rcases dense la with ⟨v, hv⟩,
refine ⟨v, hv.2, λx hx, as ⟨lt_of_lt_of_le hv.1 hx.1, hx.2⟩⟩, },
{ rintros ⟨l, la, as⟩,
exact ⟨l, la, subset.trans Ioc_subset_Icc_self as⟩ }
end
end linear_order
lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) :=
(image_eq_preimage_of_inverse neg_neg neg_neg).symm
lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) :=
funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg)
section topological_add_group
variables [topological_space α] [ordered_add_comm_group α] [topological_add_group α]
lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) :=
have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg,
by rw [preimage_neg]; exact
(subset.antisymm (image_closure_subset_closure_image continuous_neg) $
calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) :
by rw [←image_comp, this, image_id]
... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) :
monotone_image $ image_closure_subset_closure_image continuous_neg
... = _ : by rw [←image_comp, this, image_id])
end topological_add_group
section order_topology
variables [topological_space α] [topological_space β]
[linear_order α] [linear_order β] [order_topology α] [order_topology β]
lemma nhds_principal_ne_bot_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) :
𝓝 a ⊓ principal s ≠ ⊥ :=
let ⟨a', ha'⟩ := hs in
forall_sets_nonempty_iff_ne_bot.mp $ assume t ht,
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in
by_cases
(assume h : a = a',
have a ∈ t₁, from mem_of_nhds ht₁,
have a ∈ t₂, from ht₂ $ by rwa [h],
⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩)
(assume : a ≠ a',
have a' < a, from lt_of_le_of_ne (ha.left ‹a' ∈ s›) this.symm,
let ⟨l, hl, hlt₁⟩ := exists_Ioc_subset_of_mem_nhds ht₁ ⟨a', this⟩ in
have ∃a'∈s, l < a',
from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a',
have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩,
have ¬ l < a, from not_lt.2 $ ha.right this,
this ‹l < a›,
let ⟨a', ha', ha'l⟩ := this in
have a' ∈ t₁, from hlt₁ ⟨‹l < a'›, ha.left ha'⟩,
⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩)
lemma nhds_principal_ne_bot_of_is_glb : ∀ {a : α} {s : set α}, is_glb s a → s.nonempty →
𝓝 a ⊓ principal s ≠ ⊥ :=
@nhds_principal_ne_bot_of_is_lub (order_dual α) _ _ _
lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α}
(hsa : a ∈ upper_bounds s) (hsf : s ∈ f) (hfa : f ⊓ 𝓝 a ≠ ⊥) : is_lub s a :=
⟨hsa, assume b hb,
not_lt.1 $ assume hba,
have s ∩ {a | b < a} ∈ f ⊓ 𝓝 a,
from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba),
let ⟨x, ⟨hxs, hxb⟩⟩ := nonempty_of_mem_sets hfa this in
have b < b, from lt_of_lt_of_le hxb $ hb hxs,
lt_irrefl b this⟩
lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α},
a ∈ lower_bounds s → s ∈ f → f ⊓ 𝓝 a ≠ ⊥ → is_glb s a :=
@is_lub_of_mem_nhds (order_dual α) _ _ _
lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s.nonempty)
(hb : tendsto f (𝓝 a ⊓ principal s) (𝓝 b)) : is_lub (f '' s) b :=
have hnbot : (𝓝 a ⊓ principal s) ≠ ⊥, from nhds_principal_ne_bot_of_is_lub ha hs,
have ∀a'∈s, ¬ b < f a',
from assume a' ha' h,
have ∀ᶠ x in 𝓝 b, x < f a', from mem_nhds_sets (is_open_gt' _) h,
let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in
by_cases
(assume h : a = a',
have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩,
have f a < f a', from hs this,
lt_irrefl (f a') $ by rwa [h] at this)
(assume h : a ≠ a',
have a' < a, from lt_of_le_of_ne (ha.left ha') h.symm,
have {x | a' < x} ∈ 𝓝 a, from mem_nhds_sets (is_open_lt' _) this,
have {x | a' < x} ∩ t₁ ∈ 𝓝 a, from inter_mem_sets this ht₁,
have ({x | a' < x} ∩ t₁) ∩ s ∈ 𝓝 a ⊓ principal s,
from inter_mem_inf_sets this (subset.refl s),
let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := nonempty_of_mem_sets hnbot this in
have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩,
have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁,
lt_irrefl _ (lt_of_le_of_lt ha'x hxa')),
and.intro
(assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha')
(assume b' hb', le_of_tendsto hnbot hb $
mem_inf_sets_of_right $ assume x hx, hb' $ mem_image_of_mem _ hx)
lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s.nonempty →
tendsto f (𝓝 a ⊓ principal s) (𝓝 b) → is_glb (f '' s) b :=
@is_lub_of_is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ f s a b
(λ x hx y hy, hf y hy x hx)
lemma is_glb_of_is_lub_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β},
(∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s.nonempty →
tendsto f (𝓝 a ⊓ principal s) (𝓝 b) → is_glb (f '' s) b :=
@is_lub_of_is_lub_of_tendsto α (order_dual β) _ _ _ _ _ _
lemma is_lub_of_is_glb_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β},
(∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s.nonempty →
tendsto f (𝓝 a ⊓ principal s) (𝓝 b) → is_lub (f '' s) b :=
@is_glb_of_is_glb_of_tendsto α (order_dual β) _ _ _ _ _ _
lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : a ∈ closure s :=
by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_lub ha hs
lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s :=
by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_lub ha hs
lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : a ∈ closure s :=
by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_glb ha hs
lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s :=
by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_glb ha hs
/-- A compact set is bounded below -/
lemma bdd_below_of_compact {α : Type u} [topological_space α] [linear_order α]
[order_closed_topology α] [nonempty α] {s : set α} (hs : compact s) : bdd_below s :=
begin
by_contra H,
letI := classical.DLO α,
rcases hs.elim_finite_subcover_image (λ x (_ : x ∈ s), @is_open_Ioi _ _ _ _ x) _
with ⟨t, st, ft, ht⟩,
{ refine H ((bdd_below_finite ft).imp $ λ C hC y hy, _),
rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩,
exact le_trans (hC hx) (le_of_lt xy) },
{ refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H),
exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ }
end
/-- A compact set is bounded above -/
lemma bdd_above_of_compact {α : Type u} [topological_space α] [linear_order α]
[order_topology α] : Π [nonempty α] {s : set α}, compact s → bdd_above s :=
@bdd_below_of_compact (order_dual α) _ _ _
end order_topology
section linear_order
variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α]
/-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`, unless `a` is a top
element. -/
lemma closure_Ioi' {a b : α} (hab : a < b) :
closure (Ioi a) = Ici a :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioi_subset_Ici_self is_closed_Ici },
{ assume x hx,
by_cases h : x = a,
{ rw h, exact mem_closure_of_is_glb is_glb_Ioi ⟨_, hab⟩ },
{ exact subset_closure (lt_of_le_of_ne hx (ne.symm h)) } }
end
/-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`. -/
lemma closure_Ioi (a : α) [no_top_order α] :
closure (Ioi a) = Ici a :=
let ⟨b, hb⟩ := no_top a in closure_Ioi' hb
/-- The closure of the interval `(-∞, a)` is the closed interval `(-∞, a]`, unless `a` is a bottom
element. -/
lemma closure_Iio' {a b : α} (hab : b < a) :
closure (Iio a) = Iic a :=
begin
apply subset.antisymm,
{ exact closure_minimal Iio_subset_Iic_self is_closed_Iic },
{ assume x hx,
by_cases h : x = a,
{ rw h, exact mem_closure_of_is_lub is_lub_Iio ⟨_, hab⟩ },
{ apply subset_closure, by simpa [h] using lt_or_eq_of_le hx } }
end
/-- The closure of the interval `(-∞, a)` is the interval `(-∞, a]`. -/
lemma closure_Iio (a : α) [no_bot_order α] :
closure (Iio a) = Iic a :=
let ⟨b, hb⟩ := no_bot a in closure_Iio' hb
/-- The closure of the open interval `(a, b)` is the closed interval `[a, b]`. -/
lemma closure_Ioo {a b : α} (hab : a < b) :
closure (Ioo a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioo_subset_Icc_self is_closed_Icc },
{ have hab' : (Ioo a b).nonempty, from nonempty_Ioo.2 hab,
assume x hx,
by_cases h : x = a,
{ rw h, exact mem_closure_of_is_glb (is_glb_Ioo hab) hab' },
by_cases h' : x = b,
{ rw h', refine mem_closure_of_is_lub (is_lub_Ioo hab) hab' },
exact subset_closure ⟨lt_of_le_of_ne hx.1 (ne.symm h), by simpa [h'] using lt_or_eq_of_le hx.2⟩ }
end
/-- The closure of the interval `(a, b]` is the closed interval `[a, b]`. -/
lemma closure_Ioc {a b : α} (hab : a < b) :
closure (Ioc a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioc_subset_Icc_self is_closed_Icc },
{ apply subset.trans _ (closure_mono Ioo_subset_Ioc_self),
rw closure_Ioo hab }
end
/-- The closure of the interval `[a, b)` is the closed interval `[a, b]`. -/
lemma closure_Ico {a b : α} (hab : a < b) :
closure (Ico a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ico_subset_Icc_self is_closed_Icc },
{ apply subset.trans _ (closure_mono Ioo_subset_Ico_self),
rw closure_Ioo hab }
end
@[simp] lemma interior_Ici [no_bot_order α] {a : α} : interior (Ici a) = Ioi a :=
by rw [← compl_Iio, interior_compl, closure_Iio, compl_Iic]
@[simp] lemma interior_Iic [no_top_order α] {a : α} : interior (Iic a) = Iio a :=
by rw [← compl_Ioi, interior_compl, closure_Ioi, compl_Ici]
@[simp] lemma interior_Icc [no_bot_order α] [no_top_order α] {a b : α}:
interior (Icc a b) = Ioo a b :=
by rw [← Ici_inter_Iic, interior_inter, interior_Ici, interior_Iic, Ioi_inter_Iio]
@[simp] lemma interior_Ico [no_bot_order α] {a b : α} : interior (Ico a b) = Ioo a b :=
by rw [← Ici_inter_Iio, interior_inter, interior_Ici, interior_Iio, Ioi_inter_Iio]
@[simp] lemma interior_Ioc [no_top_order α] {a b : α} : interior (Ioc a b) = Ioo a b :=
by rw [← Ioi_inter_Iic, interior_inter, interior_Ioi, interior_Iic, Ioi_inter_Iio]
lemma nhds_within_Ioi_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : a ≤ b) :
nhds_within b (Ioi a) ≠ ⊥ :=
mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Ioi' H₁], exact H₂ }
lemma nhds_within_Ioi_ne_bot [no_top_order α] {a b : α} (H : a ≤ b) :
nhds_within b (Ioi a) ≠ ⊥ :=
let ⟨c, hc⟩ := no_top a in nhds_within_Ioi_ne_bot' hc H
lemma nhds_within_Ioi_self_ne_bot' {a b : α} (H : a < b) :
nhds_within a (Ioi a) ≠ ⊥ :=
nhds_within_Ioi_ne_bot' H (le_refl a)
lemma nhds_within_Ioi_self_ne_bot [no_top_order α] (a : α) :
nhds_within a (Ioi a) ≠ ⊥ :=
nhds_within_Ioi_ne_bot (le_refl a)
lemma nhds_within_Iio_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : b ≤ c) :
nhds_within b (Iio c) ≠ ⊥ :=
mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Iio' H₁], exact H₂ }
lemma nhds_within_Iio_ne_bot [no_bot_order α] {a b : α} (H : a ≤ b) :
nhds_within a (Iio b) ≠ ⊥ :=
let ⟨c, hc⟩ := no_bot b in nhds_within_Iio_ne_bot' hc H
lemma nhds_within_Iio_self_ne_bot' {a b : α} (H : a < b) :
nhds_within b (Iio b) ≠ ⊥ :=
nhds_within_Iio_ne_bot' H (le_refl b)
lemma nhds_within_Iio_self_ne_bot [no_bot_order α] (a : α) :
nhds_within a (Iio a) ≠ ⊥ :=
nhds_within_Iio_ne_bot (le_refl a)
end linear_order
section complete_linear_order
variables [complete_linear_order α] [topological_space α] [order_topology α]
[complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ]
lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α]
{s : set α} (hs : s.nonempty) : Sup s ∈ closure s :=
mem_closure_of_is_lub (is_lub_Sup _) hs
lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α]
{s : set α} (hs : s.nonempty) : Inf s ∈ closure s :=
mem_closure_of_is_glb (is_glb_Inf _) hs
lemma Sup_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α]
{s : set α} (hs : s.nonempty) (hc : is_closed s) : Sup s ∈ s :=
mem_of_is_lub_of_is_closed (is_lub_Sup _) hs hc
lemma Inf_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α]
{s : set α} (hs : s.nonempty) (hc : is_closed s) : Inf s ∈ s :=
mem_of_is_glb_of_is_closed (is_glb_Inf _) hs hc
/-- A continuous monotone function sends supremum to supremum for nonempty sets. -/
lemma Sup_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f)
{s : set α} (hs : s.nonempty) : f (Sup s) = Sup (f '' s) :=
--This is a particular case of the more general is_lub_of_is_lub_of_tendsto
(is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Cf xy) (is_lub_Sup _) hs $
tendsto_le_left inf_le_left (Mf.tendsto _)).Sup_eq.symm
/-- A continuous monotone function sending bot to bot sends supremum to supremum. -/
lemma Sup_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f)
(fbot : f ⊥ = ⊥) {s : set α} : f (Sup s) = Sup (f '' s) :=
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, fbot] },
{ exact Sup_of_continuous' Mf Cf h }
end
/-- A continuous monotone function sends indexed supremum to indexed supremum. -/
lemma supr_of_continuous' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α}
(Mf : continuous f) (Cf : monotone f) : f (supr g) = supr (f ∘ g) :=
by rw [supr, Sup_of_continuous' Mf Cf (range_nonempty g), ← range_comp, supr]
/-- A continuous monotone function sends indexed supremum to indexed supremum. -/
lemma supr_of_continuous {ι : Sort*} {f : α → β} {g : ι → α}
(Mf : continuous f) (Cf : monotone f) (fbot : f ⊥ = ⊥) : f (supr g) = supr (f ∘ g) :=
by rw [supr, Sup_of_continuous Mf Cf fbot, ← range_comp, supr]
/-- A continuous monotone function sends infimum to infimum for nonempty sets. -/
lemma Inf_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f)
{s : set α} (hs : s.nonempty) : f (Inf s) = Inf (f '' s) :=
(is_glb_of_is_glb_of_tendsto (λ x hx y hy xy, Cf xy) (is_glb_Inf _) hs $
tendsto_le_left inf_le_left (Mf.tendsto _)).Inf_eq.symm
/-- A continuous monotone function sending top to top sends infimum to infimum. -/
lemma Inf_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f)
(ftop : f ⊤ = ⊤) {s : set α} : f (Inf s) = Inf (f '' s) :=
begin
cases s.eq_empty_or_nonempty with h h,
{ simpa [h] },
{ exact Inf_of_continuous' Mf Cf h }
end
/-- A continuous monotone function sends indexed infimum to indexed infimum. -/
lemma infi_of_continuous' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α}
(Mf : continuous f) (Cf : monotone f) : f (infi g) = infi (f ∘ g) :=
by rw [infi, Inf_of_continuous' Mf Cf (range_nonempty g), ← range_comp, infi]
/-- A continuous monotone function sends indexed infimum to indexed infimum. -/
lemma infi_of_continuous {ι : Sort*} {f : α → β} {g : ι → α}
(Mf : continuous f) (Cf : monotone f) (ftop : f ⊤ = ⊤) : f (infi g) = infi (f ∘ g) :=
by rw [infi, Inf_of_continuous Mf Cf ftop, ← range_comp, infi]
end complete_linear_order
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] [topological_space α] [order_topology α]
[conditionally_complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ]
lemma cSup_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [order_topology α]
{s : set α} (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ closure s :=
mem_closure_of_is_lub (is_lub_cSup hs B) hs
lemma cInf_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [order_topology α]
{s : set α} (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ closure s :=
mem_closure_of_is_glb (is_glb_cInf hs B) hs
lemma cSup_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [order_topology α]
{s : set α} (hs : s.nonempty) (hc : is_closed s) (B : bdd_above s) : Sup s ∈ s :=
mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc
lemma cInf_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [order_topology α]
{s : set α} (hs : s.nonempty) (hc : is_closed s) (B : bdd_below s) : Inf s ∈ s :=
mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc
/-- A continuous monotone function sends supremum to supremum in conditionally complete
lattices, under a boundedness assumption. -/
lemma cSup_of_cSup_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f)
{s : set α} (ne : s.nonempty) (H : bdd_above s) : f (Sup s) = Sup (f '' s) :=
begin
refine ((is_lub_cSup (ne.image f) (Cf.map_bdd_above H)).unique _).symm,
refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Cf xy) (is_lub_cSup ne H) ne _,
exact tendsto_le_left inf_le_left (Mf.tendsto _)
end
/-- A continuous monotone function sends indexed supremum to indexed supremum in conditionally complete
lattices, under a boundedness assumption. -/
lemma csupr_of_csupr_of_monotone_of_continuous {f : α → β} {g : γ → α}
(Mf : continuous f) (Cf : monotone f) (H : bdd_above (range g)) : f (supr g) = supr (f ∘ g) :=
by rw [supr, cSup_of_cSup_of_monotone_of_continuous Mf Cf (range_nonempty _) H, ← range_comp, supr]
/-- A continuous monotone function sends infimum to infimum in conditionally complete
lattices, under a boundedness assumption. -/
lemma cInf_of_cInf_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f)
{s : set α} (ne : s.nonempty) (H : bdd_below s) : f (Inf s) = Inf (f '' s) :=
begin
refine ((is_glb_cInf (ne.image _) (Cf.map_bdd_below H)).unique _).symm,
refine is_glb_of_is_glb_of_tendsto (λx hx y hy xy, Cf xy) (is_glb_cInf ne H) ne _,
exact tendsto_le_left inf_le_left (Mf.tendsto _)
end
/-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete
lattices, under a boundedness assumption. -/
lemma cinfi_of_cinfi_of_monotone_of_continuous {f : α → β} {g : γ → α}
(Mf : continuous f) (Cf : monotone f) (H : bdd_below (range g)) : f (infi g) = infi (f ∘ g) :=
by rw [infi, cInf_of_cInf_of_monotone_of_continuous Mf Cf (range_nonempty _) H, ← range_comp, infi]
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and the set `s ∩ [a, b)` has no maximal point, then `b ∈ s`. -/
lemma is_closed.mem_of_ge_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b))
(ha : a ∈ s) (hab : a ≤ b) (hgt : ∀ x ∈ s ∩ Ico a b, (s ∩ Ioc x b).nonempty) :
b ∈ s :=
begin
let S := s ∩ Icc a b,
replace ha : a ∈ S, from ⟨ha, left_mem_Icc.2 hab⟩,
have Sbd : bdd_above S, from ⟨b, λ z hz, hz.2.2⟩,
let c := Sup (s ∩ Icc a b),
have c_mem : c ∈ S, from cSup_mem_of_is_closed ⟨_, ha⟩ hs Sbd,
have c_le : c ≤ b, from cSup_le ⟨_, ha⟩ (λ x hx, hx.2.2),
cases eq_or_lt_of_le c_le with hc hc, from hc ▸ c_mem.1,
exfalso,
rcases hgt c ⟨c_mem.1, c_mem.2.1, hc⟩ with ⟨x, xs, cx, xb⟩,
exact not_lt_of_le (le_cSup Sbd ⟨xs, le_trans (le_cSup Sbd ha) (le_of_lt cx), xb⟩) cx
end
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and for any `a ≤ x < y ≤ b`, `x ∈ s`, the set `s ∩ (x, y]`
is not empty, then `[a, b] ⊆ s`. -/
lemma is_closed.Icc_subset_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b))
(ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, ∀ y ∈ Ioi x, (s ∩ Ioc x y).nonempty) :
Icc a b ⊆ s :=
begin
assume y hy,
have : is_closed (s ∩ Icc a y),
{ suffices : s ∩ Icc a y = s ∩ Icc a b ∩ Icc a y,
{ rw this, exact is_closed_inter hs is_closed_Icc },
rw [inter_assoc],
congr,
exact (inter_eq_self_of_subset_right $ Icc_subset_Icc_right hy.2).symm },
exact is_closed.mem_of_ge_of_forall_exists_gt this ha hy.1
(λ x hx, hgt x ⟨hx.1, Ico_subset_Ico_right hy.2 hx.2⟩ y hx.2.2)
end
section densely_ordered
variables [densely_ordered α] {a b : α}
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and for any `x ∈ s ∩ [a, b)` the set `s` includes some open
neighborhood of `x` within `(x, +∞)`, then `[a, b] ⊆ s`. -/
lemma is_closed.Icc_subset_of_forall_mem_nhds_within {a b : α} {s : set α}
(hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s)
(hgt : ∀ x ∈ s ∩ Ico a b, s ∈ nhds_within x (Ioi x)) :
Icc a b ⊆ s :=
begin
apply hs.Icc_subset_of_forall_exists_gt ha,
rintros x ⟨hxs, hxab⟩ y hyxb,
have : s ∩ Ioc x y ∈ nhds_within x (Ioi x),
from inter_mem_sets (hgt x ⟨hxs, hxab⟩) (Ioc_mem_nhds_within_Ioi ⟨le_refl _, hyxb⟩),
exact nonempty_of_mem_sets (nhds_within_Ioi_self_ne_bot' hxab.2) this
end
/-- A closed interval is preconnected. -/
lemma is_connected_Icc : is_preconnected (Icc a b) :=
is_preconnected_closed_iff.2
begin
rintros s t hs ht hab ⟨x, hx⟩ ⟨y, hy⟩,
wlog hxy : x ≤ y := le_total x y using [x y s t, y x t s],
have xyab : Icc x y ⊆ Icc a b := Icc_subset_Icc hx.1.1 hy.1.2,
by_contradiction hst,
suffices : Icc x y ⊆ s,
from hst ⟨y, xyab $ right_mem_Icc.2 hxy, this $ right_mem_Icc.2 hxy, hy.2⟩,
apply (is_closed_inter hs is_closed_Icc).Icc_subset_of_forall_mem_nhds_within hx.2,
rintros z ⟨zs, hz⟩,
have zt : z ∈ -t, from λ zt, hst ⟨z, xyab $ Ico_subset_Icc_self hz, zs, zt⟩,
have : -t ∩ Ioc z y ∈ nhds_within z (Ioi z),
{ rw [← nhds_within_Ioc_eq_nhds_within_Ioi hz.2],
exact mem_nhds_within.2 ⟨-t, ht, zt, subset.refl _⟩},
apply mem_sets_of_superset this,
have : Ioc z y ⊆ s ∪ t, from λ w hw, hab (xyab ⟨le_trans hz.1 (le_of_lt hw.1), hw.2⟩),
exact λ w ⟨wt, wzy⟩, (this wzy).elim id (λ h, (wt h).elim)
end
lemma is_preconnected_iff_forall_Icc_subset {s : set α} :
is_preconnected s ↔ ∀ x y ∈ s, x ≤ y → Icc x y ⊆ s :=
⟨λ h x y hx hy hxy, h.forall_Icc_subset hx hy, λ h, is_preconnected_of_forall_pair $ λ x y hx hy,
⟨Icc (min x y) (max x y), h (min x y) (max x y)
((min_choice x y).elim (λ h', by rwa h') (λ h', by rwa h'))
((max_choice x y).elim (λ h', by rwa h') (λ h', by rwa h')) min_le_max,
⟨min_le_left x y, le_max_left x y⟩, ⟨min_le_right x y, le_max_right x y⟩, is_connected_Icc⟩⟩
lemma is_preconnected_Ici : is_preconnected (Ici a) :=
is_preconnected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ici_iff hxy).2 hx
lemma is_preconnected_Iic : is_preconnected (Iic a) :=
is_preconnected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Iic_iff hxy).2 hy
lemma is_preconnected_Iio : is_preconnected (Iio a) :=
is_preconnected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Iio_iff hxy).2 hy
lemma is_preconnected_Ioi : is_preconnected (Ioi a) :=
is_preconnected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ioi_iff hxy).2 hx
lemma is_connected_Ioo : is_preconnected (Ioo a b) :=
is_preconnected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ioo_iff hxy).2 ⟨hx.1, hy.2⟩
lemma is_preconnected_Ioc : is_preconnected (Ioc a b) :=
is_preconnected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ioc_iff hxy).2 ⟨hx.1, hy.2⟩
lemma is_preconnected_Ico : is_preconnected (Ico a b) :=
is_preconnected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ico_iff hxy).2 ⟨hx.1, hy.2⟩
@[priority 100]
instance ordered_connected_space : preconnected_space α :=
⟨is_preconnected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, subset_univ _⟩
/--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≤ t ≤ f b`.-/
lemma intermediate_value_Icc {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) :
Icc (f a) (f b) ⊆ f '' (Icc a b) :=
is_connected_Icc.intermediate_value (left_mem_Icc.2 hab) (right_mem_Icc.2 hab) hf
/--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≥ t ≥ f b`.-/
lemma intermediate_value_Icc' {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) :
Icc (f b) (f a) ⊆ f '' (Icc a b) :=
is_connected_Icc.intermediate_value (right_mem_Icc.2 hab) (left_mem_Icc.2 hab) hf
end densely_ordered
/-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/
lemma compact.exists_forall_le {α : Type u} [topological_space α]
{s : set α} (hs : compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) :
∃x∈s, ∀y∈s, f x ≤ f y :=
begin
have C : compact (f '' s) := hs.image_of_continuous_on hf,
haveI := has_Inf_to_nonempty β,
have B : bdd_below (f '' s) := bdd_below_of_compact C,
have : Inf (f '' s) ∈ f '' s :=
cInf_mem_of_is_closed (ne_s.image _) (closed_of_compact _ C) B,
rcases (mem_image _ _ _).1 this with ⟨x, xs, hx⟩,
exact ⟨x, xs, λ y hy, hx.symm ▸ cInf_le B ⟨_, hy, rfl⟩⟩
end
/-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/
lemma compact.exists_forall_ge {α : Type u} [topological_space α]:
∀ {s : set α}, compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s →
∃x∈s, ∀y∈s, f y ≤ f x :=
@compact.exists_forall_le (order_dual β) _ _ _ _ _
end conditionally_complete_linear_order
section liminf_limsup
section order_closed_topology
variables [semilattice_sup α] [topological_space α] [order_topology α]
lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) :=
match forall_le_or_exists_lt_sup a with
| or.inl h := ⟨a, eventually_of_forall _ h⟩
| or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩
end
lemma is_bounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α}
(h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u :=
is_bounded_of_le h (is_bounded_le_nhds a)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) :=
is_cobounded_of_is_bounded nhds_ne_bot (is_bounded_le_nhds a)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_cobounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α}
(hf : f ≠ ⊥) (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u :=
is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_le_of_tendsto h)
end order_closed_topology
section order_closed_topology
variables [semilattice_inf α] [topological_space α] [order_topology α]
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) :=
match forall_le_or_exists_lt_inf a with
| or.inl h := ⟨a, eventually_of_forall _ h⟩
| or.inr ⟨b, hb⟩ := ⟨b, le_mem_nhds hb⟩
end
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_bounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α}
(h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u :=
is_bounded_of_le h (is_bounded_ge_nhds a)
lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) :=
is_cobounded_of_is_bounded nhds_ne_bot (is_bounded_ge_nhds a)
lemma is_cobounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α}
(hf : f ≠ ⊥) (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u :=
is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_ge_of_tendsto h)
end order_closed_topology
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α]
theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) :
∀ᶠ a in f, a < b :=
let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_cInf_lt h l in
mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → f.Liminf > b →
∀ᶠ a in f, a > b :=
@lt_mem_sets_of_Limsup_lt (order_dual α) _
variables [topological_space α] [order_topology α]
/-- If the liminf and the limsup of a filter coincide, then this filter converges to
their common value, at least if the filter is eventually bounded above and below. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α}
(hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) :
f ≤ 𝓝 a :=
tendsto_order.2 $ and.intro
(assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb)
(assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb)
theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a :=
cInf_intro (is_bounded_le_nhds a)
(assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_nhds α _ a _ h)
(assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from
match dense_or_discrete a b with
| or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩
| or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩
end)
theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a :=
@Limsup_nhds (order_dual α) _ _ _
/-- If a filter is converging, its limsup coincides with its limit. -/
theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} (hf : f ≠ ⊥) (h : f ≤ 𝓝 a) : f.Liminf = a :=
have hb_ge : is_bounded (≥) f, from is_bounded_of_le h (is_bounded_ge_nhds a),
have hb_le : is_bounded (≤) f, from is_bounded_of_le h (is_bounded_le_nhds a),
le_antisymm
(calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hf hb_le hb_ge
... ≤ (𝓝 a).Limsup :
Limsup_le_Limsup_of_le h (is_cobounded_of_is_bounded hf hb_ge) (is_bounded_le_nhds a)
... = a : Limsup_nhds a)
(calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm
... ≤ f.Liminf :
Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) (is_cobounded_of_is_bounded hf hb_le))
/-- If a filter is converging, its liminf coincides with its limit. -/
theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α}, f ≠ ⊥ → f ≤ 𝓝 a → f.Limsup = a :=
@Liminf_eq_of_le_nhds (order_dual α) _ _ _
end conditionally_complete_linear_order
section complete_linear_order
variables [complete_linear_order α] [topological_space α] [order_topology α]
-- In complete_linear_order, the above theorems take a simpler form
/-- If the liminf and the limsup of a function coincide, then the limit of the function
exists and has the same value -/
theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α}
(h : liminf f u = a ∧ limsup f u = a) : tendsto u f (𝓝 a) :=
le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot h.2 h.1
/-- If a function has a limit, then its limsup coincides with its limit-/
theorem limsup_eq_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥)
(h : tendsto u f (𝓝 a)) : limsup f u = a :=
Limsup_eq_of_le_nhds (map_ne_bot hf) h
/-- If a function has a limit, then its liminf coincides with its limit-/
theorem liminf_eq_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥)
(h : tendsto u f (𝓝 a)) : liminf f u = a :=
Liminf_eq_of_le_nhds (map_ne_bot hf) h
end complete_linear_order
end liminf_limsup
end order_topology
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma order_topology_of_nhds_abs
{α : Type*} [decidable_linear_ordered_add_comm_group α] [topological_space α]
(h_nhds : ∀a:α, 𝓝 a = (⨅r>0, principal {b | abs (a - b) < r})) : order_topology α :=
order_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr
begin
simp [infi_and, topological_space.nhds_generate_from,
h_nhds, le_infi_iff, -le_principal_iff, and_comm],
refine ⟨λ s ha b hs, _, λ r hr, _⟩,
{ rcases hs with rfl | rfl,
{ refine infi_le_of_le (a - b)
(infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $
principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _),
have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc,
exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) },
{ refine infi_le_of_le (b - a)
(infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $
principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _),
have : abs (c - a) < b - a, {rw abs_sub; simpa using hc},
have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this,
exact lt_of_add_lt_add_right this } },
{ have h : {b | abs (a - b) < r} = {b | a - r < b} ∩ {b | b < a + r},
from set.ext (assume b,
by simp [abs_lt, sub_lt, lt_sub_iff_add_lt, sub_lt_iff_lt_add']; cc),
rw [h, ← inf_principal],
apply le_inf _ _,
{ exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $
infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) },
{ exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $
infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } }
end
lemma tendsto_at_top_supr_nat [topological_space α] [complete_linear_order α] [order_topology α]
(f : ℕ → α) (hf : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) :=
tendsto_order.2 $ and.intro
(assume a ha, let ⟨n, hn⟩ := lt_supr_iff.1 ha in
mem_at_top_sets.2 ⟨n, assume i hi, lt_of_lt_of_le hn (hf hi)⟩)
(assume a ha, univ_mem_sets' (assume n, lt_of_le_of_lt (le_supr _ n) ha))
lemma tendsto_at_top_infi_nat [topological_space α] [complete_linear_order α] [order_topology α]
(f : ℕ → α) (hf : ∀{n m}, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 (⨅i, f i)) :=
@tendsto_at_top_supr_nat (order_dual α) _ _ _ _ @hf
lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α]
{f : ℕ → α} {a : α} (hf : monotone f) : tendsto f at_top (𝓝 a) → supr f = a :=
tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_supr_nat f hf)
lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α]
{f : ℕ → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 a) → infi f = a :=
tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_infi_nat f hf)
lemma tendsto_abs_at_top_at_top [decidable_linear_ordered_add_comm_group α] : tendsto (abs : α → α) at_top at_top :=
tendsto_at_top_mono _ (λ n, le_abs_self _) tendsto_id
local notation `|` x `|` := abs x
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma decidable_linear_ordered_add_comm_group.tendsto_nhds
[decidable_linear_ordered_add_comm_group α] [topological_space α] [order_topology α] {β : Type*}
(f : β → α) (x : filter β) (a : α) :
filter.tendsto f x (nhds a) ↔ ∀ ε > (0 : α), ∀ᶠ b in x, |f b - a| < ε :=
begin
rw (show _, from @tendsto_order α), -- does not work without `show` for some reason
split,
{ rintros ⟨hyp_lt_a, hyp_gt_a⟩ ε ε_pos,
suffices : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff],
have set1 : {b : β | a - f b < ε} ∈ x,
{ have : {b : β | a - ε < f b} ∈ x, from hyp_lt_a (a - ε) (sub_lt_self a ε_pos),
have : ∀ b, a - f b < ε ↔ a - ε < f b, by { intro _, exact sub_lt },
simpa only [this] },
have set2 : {b : β | f b - a < ε} ∈ x,
{ have : {b : β | a + ε > f b} ∈ x, from hyp_gt_a (a + ε) (lt_add_of_pos_right a ε_pos),
have : ∀ b, f b - a < ε ↔ a + ε > f b, by { intro _, exact sub_lt_iff_lt_add' },
simpa only [this] },
exact (x.inter_sets set2 set1) },
{ assume hyp_ε_pos,
split,
{ assume a' a'_lt_a,
let ε := a - a',
have : {b : β | |f b - a| < ε} ∈ x, from hyp_ε_pos ε (sub_pos.elim_right a'_lt_a),
have : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff] using this,
have : {b : β | a - f b < ε} ∈ x, from x.sets_of_superset this (set.inter_subset_right _ _),
have : ∀ b, a' < f b ↔ a - f b < ε, by {intro b, rw [sub_lt, sub_sub_self] },
simpa only [this] },
{ assume a' a'_gt_a,
let ε := a' - a,
have : {b : β | |f b - a| < ε} ∈ x, from hyp_ε_pos ε (sub_pos.elim_right a'_gt_a),
have : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff] using this,
have : {b : β | f b - a < ε} ∈ x, from x.sets_of_superset this (set.inter_subset_left _ _),
have : ∀ b, f b < a' ↔ f b - a < ε, by { intro b, simp [lt_sub_iff_add_lt] },
simpa only [this] }}
end
|
128d2762dbe4560c306f12046bb2a05299163c2f | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/cone.lean | eed50b78cb6eea5a312e0c106735a985a0633317 | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 2,557 | lean |
import linear_algebra.basic
import data.real.basic
import data.set.basic
import tactic.interactive
import .inner_product_space
noncomputable theory
local attribute [instance] classical.prop_decidable
section basic
variables
{α : Type*}
[has_scalar ℝ α]
{ι : Sort _}
(A : set α) (B : set α) (x : α)
open set
-- Cones
def cone (A : set α) : Prop :=
∀x ∈ A, ∀(c : ℝ), 0 ≤ c → c • x ∈ A
lemma cone_empty :
cone ({} : set α) :=
by finish
lemma cone_univ :
cone (univ : set α) :=
by finish
lemma cone_inter (hA: cone A) (hB: cone B) :
cone (A ∩ B) :=
λ x hx c hc,
mem_inter (hA _ (mem_of_mem_inter_left hx) _ hc)
(hB _ (mem_of_mem_inter_right hx) _ hc)
lemma cone_Inter {s: ι → set α} (h: ∀ i : ι, cone (s i)) :
cone (Inter s) :=
begin
intros x hx c hc,
rw mem_Inter at hx |-,
exact (λ i, h i x (hx i) c hc)
end
lemma cone_union (hA: cone A) (hB: cone B) :
cone (A ∪ B) :=
begin
intros x hx c hc,
apply or.elim (mem_or_mem_of_mem_union hx),
{ intro h,
apply mem_union_left,
apply hA _ h _ hc },
{ intro h,
apply mem_union_right,
apply hB _ h _ hc }
end
lemma cone_Union {s: ι → set α} (h: ∀ i : ι, cone (s i)) :
cone (Union s) :=
begin
intros x hx c hc,
apply exists.elim (mem_Union.1 hx),
intros i hi,
apply mem_Union.2,
use i,
apply h i _ hi _ hc
end
end basic
section vector_space
variables
{α : Type*}
[add_comm_group α] [vector_space ℝ α]
(A : set α) (B : set α) (x : α)
open set
lemma cone_subspace {s : subspace ℝ α} :
cone (s.carrier) :=
λ x hx c hc, s.smul c hx
lemma cone_contains_0 (hA : cone A) :
A ≠ ∅ ↔ (0 : α) ∈ A :=
begin
apply iff.intro,
{ intros h,
apply exists.elim (exists_mem_of_ne_empty h),
intros x hx, rw ←zero_smul ℝ,
apply hA x hx 0 (le_refl 0) },
{ intros h,
exact ne_empty_of_mem h }
end
lemma cone_0 {α : Type*} [add_comm_group α] [semimodule ℝ α] : cone ({0} : set α) :=
begin
intros x hx c hc,
apply mem_singleton_of_eq,
convert smul_zero c,
exact eq_of_mem_singleton hx
end
end vector_space
section dual_cone
def dual_cone {α : Type*} [has_inner ℝ α] (A : set α) : set α :=
{ y | ∀ x ∈ A, 0 ≤ ⟪ x, y ⟫ }
open real_inner_product_space
variables {α : Type*}
[real_inner_product_space α]
(A : set α) (B : set α)
lemma cone_dual_cone : cone (dual_cone A) :=
begin
intros x ha c hc z hz,
rw inner_smul_right,
apply mul_nonneg' hc,
exact ha _ hz
end
end dual_cone |
f21175855ebcafead093d0e4265c2f9c187895d4 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /library/algebra/order_bigops.lean | c9276ce43e52cd9dec6eb9942112c4e888eeeaf5 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 19,027 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
Min and max over finite sets.
To support constructive theories, we start with the class
decidable_linear_ordered_cancel_comm_monoid, because:
(1) We need a decidable linear order to have min and max
(2) We need a default element for min and max over the empty set, and max empty = 0 is the
right choice for nat.
(3) All our number classes are instances.
We can define variants of Min and Max if needed.
-/
import .group_bigops .ordered_ring
variables {A B : Type}
section
variable [decidable_linear_order A]
definition max_comm_semigroup : comm_semigroup A :=
⦃ comm_semigroup,
mul := max,
mul_assoc := max.assoc,
mul_comm := max.comm
⦄
definition min_comm_semigroup : comm_semigroup A :=
⦃ comm_semigroup,
mul := min,
mul_assoc := min.assoc,
mul_comm := min.comm
⦄
end
/- finset versions -/
namespace finset
section deceq_A
variable [decidable_eq A]
section decidable_linear_ordered_cancel_comm_monoid_B
variable [decidable_linear_ordered_cancel_comm_monoid B]
section max_comm_semigroup
local attribute max_comm_semigroup [instance]
open Prod_semigroup
definition Max (s : finset A) (f : A → B) : B := Prod_semigroup 0 s f
notation `Max` binders `∈` s `, ` r:(scoped f, Max s f) := r
proposition Max_empty (f : A → B) : (Max x ∈ ∅, f x) = 0 := !Prod_semigroup_empty
proposition Max_singleton (f : A → B) (a : A) : (Max x ∈ '{a}, f x) = f a :=
!Prod_semigroup_singleton
proposition Max_insert_insert (f : A → B) {a₁ a₂ : A} {s : finset A} :
a₂ ∉ s → a₁ ∉ insert a₂ s →
(Max x ∈ insert a₁ (insert a₂ s), f x) = max (f a₁) (Max x ∈ insert a₂ s, f x) :=
!Prod_semigroup_insert_insert
proposition Max_insert (f : A → B) {a : A} {s : finset A} (anins : a ∉ s) (sne : s ≠ ∅) :
(Max x ∈ insert a s, f x) = max (f a) (Max x ∈ s, f x) :=
!Prod_semigroup_insert anins sne
end max_comm_semigroup
proposition Max_pair (f : A → B) (a₁ a₂ : A) : (Max x ∈ '{a₁, a₂}, f x) = max (f a₁) (f a₂) :=
decidable.by_cases
(suppose a₁ = a₂, by rewrite [this, pair_eq_singleton, max_self] )
(suppose a₁ ≠ a₂,
have a₁ ∉ '{a₂}, by rewrite [mem_singleton_iff]; apply this,
using this, by rewrite [Max_insert f this !singleton_ne_empty])
proposition le_Max (f : A → B) {a : A} {s : finset A} (H : a ∈ s) : f a ≤ Max x ∈ s, f x :=
begin
induction s with a' s' a'nins' ih,
{exact false.elim (not_mem_empty a H)},
cases (decidable.em (s' = ∅)) with s'empty s'nempty,
{rewrite [s'empty at *, Max_singleton, eq_of_mem_singleton H], apply le.refl},
rewrite [Max_insert f a'nins' s'nempty],
cases (eq_or_mem_of_mem_insert H) with aeqa' ains',
{rewrite aeqa', apply le_max_left},
apply le.trans (ih ains') !le_max_right
end
proposition Max_le (f : A → B) {s : finset A} {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → f a ≤ b) :
(Max x ∈ s, f x) ≤ b :=
begin
induction s with a' s' a'nins' ih,
{exact absurd rfl sne},
cases (decidable.em (s' = ∅)) with s'empty s'nempty,
{rewrite [s'empty, Max_singleton], exact H a' !mem_insert},
rewrite [Max_insert f a'nins' s'nempty],
apply max_le (H a' !mem_insert),
apply ih s'nempty,
intro a H',
exact H a (mem_insert_of_mem a' H')
end
proposition Max_add_right (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) :
(Max x ∈ s, f x + b) = (Max x ∈ s, f x) + b :=
begin
induction s with a' s' a'nins' ih,
{exact absurd rfl sne},
cases (decidable.em (s' = ∅)) with s'empty s'ne,
{rewrite [s'empty, Max_singleton]},
rewrite [*Max_insert _ a'nins' s'ne, ih s'ne, max_add_add_right]
end
proposition Max_add_left (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) :
(Max x ∈ s, b + f x) = b + (Max x ∈ s, f x) :=
begin
induction s with a' s' a'nins' ih,
{exact absurd rfl sne},
cases (decidable.em (s' = ∅)) with s'empty s'ne,
{rewrite [s'empty, Max_singleton]},
rewrite [*Max_insert _ a'nins' s'ne, ih s'ne, max_add_add_left]
end
section min_comm_semigroup
local attribute min_comm_semigroup [instance]
open Prod_semigroup
definition Min (s : finset A) (f : A → B) : B := Prod_semigroup 0 s f
notation `Min` binders `∈` s `, ` r:(scoped f, Min s f) := r
proposition Min_empty (f : A → B) : (Min x ∈ ∅, f x) = 0 := !Prod_semigroup_empty
proposition Min_singleton (f : A → B) (a : A) : (Min x ∈ '{a}, f x) = f a :=
!Prod_semigroup_singleton
proposition Min_insert_insert (f : A → B) {a₁ a₂ : A} {s : finset A} :
a₂ ∉ s → a₁ ∉ insert a₂ s →
(Min x ∈ insert a₁ (insert a₂ s), f x) = min (f a₁) (Min x ∈ insert a₂ s, f x) :=
!Prod_semigroup_insert_insert
proposition Min_insert (f : A → B) {a : A} {s : finset A} (anins : a ∉ s) (sne : s ≠ ∅) :
(Min x ∈ insert a s, f x) = min (f a) (Min x ∈ s, f x) :=
!Prod_semigroup_insert anins sne
end min_comm_semigroup
proposition Min_pair (f : A → B) (a₁ a₂ : A) : (Min x ∈ '{a₁, a₂}, f x) = min (f a₁) (f a₂) :=
decidable.by_cases
(suppose a₁ = a₂, by rewrite [this, pair_eq_singleton, min_self] )
(suppose a₁ ≠ a₂,
have a₁ ∉ '{a₂}, by rewrite [mem_singleton_iff]; apply this,
using this, by rewrite [Min_insert f this !singleton_ne_empty])
proposition Min_le (f : A → B) {a : A} {s : finset A} (H : a ∈ s) : (Min x ∈ s, f x) ≤ f a :=
begin
induction s with a' s' a'nins' ih,
{exact false.elim (not_mem_empty a H)},
cases (decidable.em (s' = ∅)) with s'empty s'nempty,
{rewrite [s'empty at *, Min_singleton, eq_of_mem_singleton H], apply le.refl},
rewrite [Min_insert f a'nins' s'nempty],
cases (eq_or_mem_of_mem_insert H) with aeqa' ains',
{rewrite aeqa', apply min_le_left},
apply le.trans !min_le_right (ih ains')
end
proposition le_Min (f : A → B) {s : finset A} {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → b ≤ f a) :
b ≤ Min x ∈ s, f x :=
begin
induction s with a' s' a'nins' ih,
{exact absurd rfl sne},
cases (decidable.em (s' = ∅)) with s'empty s'nempty,
{rewrite [s'empty, Min_singleton], exact H a' !mem_insert},
rewrite [Min_insert f a'nins' s'nempty],
apply le_min (H a' !mem_insert),
apply ih s'nempty,
intro a H',
exact H a (mem_insert_of_mem a' H')
end
proposition Min_add_right (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) :
(Min x ∈ s, f x + b) = (Min x ∈ s, f x) + b :=
begin
induction s with a' s' a'nins' ih,
{exact absurd rfl sne},
cases (decidable.em (s' = ∅)) with s'empty s'ne,
{rewrite [s'empty, Min_singleton]},
rewrite [*Min_insert _ a'nins' s'ne, ih s'ne, min_add_add_right]
end
proposition Min_add_left (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) :
(Min x ∈ s, b + f x) = b + (Min x ∈ s, f x) :=
begin
induction s with a' s' a'nins' ih,
{exact absurd rfl sne},
cases (decidable.em (s' = ∅)) with s'empty s'ne,
{rewrite [s'empty, Min_singleton]},
rewrite [*Min_insert _ a'nins' s'ne, ih s'ne, min_add_add_left]
end
end decidable_linear_ordered_cancel_comm_monoid_B
section decidable_linear_ordered_comm_group_B
variable [decidable_linear_ordered_comm_group B]
proposition Max_neg (f : A → B) (s : finset A) : (Max x ∈ s, - f x) = - Min x ∈ s, f x :=
begin
cases (decidable.em (s = ∅)) with se sne,
{rewrite [se, Max_empty, Min_empty, neg_zero]},
apply eq_of_le_of_ge,
{apply !Max_le sne,
intro a ains,
apply neg_le_neg,
apply !Min_le ains},
apply neg_le_of_neg_le,
apply !le_Min sne,
intro a ains,
apply neg_le_of_neg_le,
apply !le_Max ains
end
proposition Min_neg (f : A → B) (s : finset A) : (Min x ∈ s, - f x) = - Max x ∈ s, f x :=
begin
cases (decidable.em (s = ∅)) with se sne,
{rewrite [se, Max_empty, Min_empty, neg_zero]},
apply eq_of_le_of_ge,
{apply le_neg_of_le_neg,
apply !Max_le sne,
intro a ains,
apply le_neg_of_le_neg,
apply !Min_le ains},
apply !le_Min sne,
intro a ains,
apply neg_le_neg,
apply !le_Max ains
end
proposition Max_eq_neg_Min_neg (f : A → B) (s : finset A) :
(Max x ∈ s, f x) = - Min x ∈ s, - f x :=
by rewrite [Min_neg, neg_neg]
proposition Min_eq_neg_Max_neg (f : A → B) (s : finset A) :
(Min x ∈ s, f x) = - Max x ∈ s, - f x :=
by rewrite [Max_neg, neg_neg]
end decidable_linear_ordered_comm_group_B
end deceq_A
/- Min and Max *of* a finset -/
section decidable_linear_ordered_semiring_A
variable [decidable_linear_ordered_semiring A]
definition Max₀ (s : finset A) : A := Max x ∈ s, x
definition Min₀ (s : finset A) : A := Min x ∈ s, x
proposition Max₀_empty : Max₀ ∅ = (0 : A) := !Max_empty
proposition Max₀_singleton (a : A) : Max₀ '{a} = a := !Max_singleton
proposition Max₀_insert_insert {a₁ a₂ : A} {s : finset A} (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) :
Max₀ (insert a₁ (insert a₂ s)) = max a₁ (Max₀ (insert a₂ s)) :=
!Max_insert_insert H₁ H₂
proposition Max₀_insert {s : finset A} {a : A} (anins : a ∉ s) (sne : s ≠ ∅) :
Max₀ (insert a s) = max a (Max₀ s) := !Max_insert anins sne
proposition Max₀_pair (a₁ a₂ : A) : Max₀ '{a₁, a₂} = max a₁ a₂ := !Max_pair
proposition le_Max₀ {a : A} {s : finset A} (H : a ∈ s) : a ≤ Max₀ s := !le_Max H
proposition Max₀_le {s : finset A} {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → x ≤ a) :
Max₀ s ≤ a := !Max_le sne H
proposition Min₀_empty : Min₀ ∅ = (0 : A) := !Min_empty
proposition Min₀_singleton (a : A) : Min₀ '{a} = a := !Min_singleton
proposition Min₀_insert_insert {a₁ a₂ : A} {s : finset A} (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) :
Min₀ (insert a₁ (insert a₂ s)) = min a₁ (Min₀ (insert a₂ s)) :=
!Min_insert_insert H₁ H₂
proposition Min₀_insert {s : finset A} {a : A} (anins : a ∉ s) (sne : s ≠ ∅) :
Min₀ (insert a s) = min a (Min₀ s) := !Min_insert anins sne
proposition Min₀_pair (a₁ a₂ : A) : Min₀ '{a₁, a₂} = min a₁ a₂ := !Min_pair
proposition Min₀_le {a : A} {s : finset A} (H : a ∈ s) : Min₀ s ≤ a := !Min_le H
proposition le_Min₀ {s : finset A} {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → a ≤ x) :
a ≤ Min₀ s := !le_Min sne H
end decidable_linear_ordered_semiring_A
end finset
/- finite set versions -/
namespace set
open classical
section decidable_linear_ordered_cancel_comm_monoid_B
variable [decidable_linear_ordered_cancel_comm_monoid B]
noncomputable definition Max (s : set A) (f : A → B) : B := finset.Max (to_finset s) f
notation `Max` binders `∈` s `, ` r:(scoped f, Max s f) := r
noncomputable definition Min (s : set A) (f : A → B) : B := finset.Min (to_finset s) f
notation `Min` binders `∈` s `, ` r:(scoped f, Min s f) := r
proposition Max_empty (f : A → B) : (Max x ∈ ∅, f x) = 0 :=
by rewrite [↑set.Max, to_finset_empty, finset.Max_empty]
proposition Max_singleton (f : A → B) (a : A) : (Max x ∈ '{a}, f x) = f a :=
by rewrite [↑set.Max, to_finset_insert, to_finset_empty, finset.Max_singleton]
proposition Max_insert_insert (f : A → B) {a₁ a₂ : A} {s : set A} [h : finite s] :
a₂ ∉ s → a₁ ∉ insert a₂ s →
(Max x ∈ insert a₁ (insert a₂ s), f x) = max (f a₁) (Max x ∈ insert a₂ s, f x) :=
begin
rewrite [↑set.Max, -+mem_to_finset_eq, +to_finset_insert],
apply finset.Max_insert_insert
end
proposition Max_insert (f : A → B) {a : A} {s : set A} [h : finite s] (anins : a ∉ s)
(sne : s ≠ ∅) :
(Max x ∈ insert a s, f x) = max (f a) (Max x ∈ s, f x) :=
begin
revert anins sne,
rewrite [↑set.Max, -+mem_to_finset_eq, +to_finset_insert],
intro h1 h2,
apply finset.Max_insert f h1 (λ h', h2 (eq_empty_of_to_finset_eq_empty h')),
end
proposition Max_pair (f : A → B) (a₁ a₂ : A) : (Max x ∈ '{a₁, a₂}, f x) = max (f a₁) (f a₂) :=
by rewrite [↑set.Max, +to_finset_insert, +to_finset_empty, finset.Max_pair]
proposition le_Max (f : A → B) {a : A} {s : set A} [fins : finite s] (H : a ∈ s) :
f a ≤ Max x ∈ s, f x :=
by rewrite [-+mem_to_finset_eq at H, ↑set.Max]; exact finset.le_Max f H
proposition Max_le (f : A → B) {s : set A} [fins : finite s] {b : B} (sne : s ≠ ∅)
(H : ∀ a, a ∈ s → f a ≤ b) :
(Max x ∈ s, f x) ≤ b :=
begin
rewrite [↑set.Max],
apply finset.Max_le f (λ H', sne (eq_empty_of_to_finset_eq_empty H')),
intro a H', apply H a, rewrite mem_to_finset_eq at H', exact H'
end
proposition Max_add_right (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) :
(Max x ∈ s, f x + b) = (Max x ∈ s, f x) + b :=
begin
rewrite [↑set.Max],
apply finset.Max_add_right f b (λ h, sne (eq_empty_of_to_finset_eq_empty h))
end
proposition Max_add_left (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) :
(Max x ∈ s, b + f x) = b + (Max x ∈ s, f x) :=
begin
rewrite [↑set.Max],
apply finset.Max_add_left f b (λ h, sne (eq_empty_of_to_finset_eq_empty h))
end
proposition Min_empty (f : A → B) : (Min x ∈ ∅, f x) = 0 :=
by rewrite [↑set.Min, to_finset_empty, finset.Min_empty]
proposition Min_singleton (f : A → B) (a : A) : (Min x ∈ '{a}, f x) = f a :=
by rewrite [↑set.Min, to_finset_insert, to_finset_empty, finset.Min_singleton]
proposition Min_insert_insert (f : A → B) {a₁ a₂ : A} {s : set A} [h : finite s] :
a₂ ∉ s → a₁ ∉ insert a₂ s →
(Min x ∈ insert a₁ (insert a₂ s), f x) = min (f a₁) (Min x ∈ insert a₂ s, f x) :=
begin
rewrite [↑set.Min, -+mem_to_finset_eq, +to_finset_insert],
apply finset.Min_insert_insert
end
proposition Min_insert (f : A → B) {a : A} {s : set A} [h : finite s] (anins : a ∉ s)
(sne : s ≠ ∅) :
(Min x ∈ insert a s, f x) = min (f a) (Min x ∈ s, f x) :=
begin
revert anins sne,
rewrite [↑set.Min, -+mem_to_finset_eq, +to_finset_insert],
intro h1 h2,
apply finset.Min_insert f h1 (λ h', h2 (eq_empty_of_to_finset_eq_empty h')),
end
proposition Min_pair (f : A → B) (a₁ a₂ : A) : (Min x ∈ '{a₁, a₂}, f x) = min (f a₁) (f a₂) :=
by rewrite [↑set.Min, +to_finset_insert, +to_finset_empty, finset.Min_pair]
proposition Min_le (f : A → B) {a : A} {s : set A} [fins : finite s] (H : a ∈ s) :
(Min x ∈ s, f x) ≤ f a :=
by rewrite [-+mem_to_finset_eq at H, ↑set.Min]; exact finset.Min_le f H
proposition le_Min (f : A → B) {s : set A} [fins : finite s] {b : B} (sne : s ≠ ∅)
(H : ∀ a, a ∈ s → b ≤ f a) :
b ≤ Min x ∈ s, f x :=
begin
rewrite [↑set.Min],
apply finset.le_Min f (λ H', sne (eq_empty_of_to_finset_eq_empty H')),
intro a H', apply H a, rewrite mem_to_finset_eq at H', exact H'
end
proposition Min_add_right (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) :
(Min x ∈ s, f x + b) = (Min x ∈ s, f x) + b :=
begin
rewrite [↑set.Min],
apply finset.Min_add_right f b (λ h, sne (eq_empty_of_to_finset_eq_empty h))
end
proposition Min_add_left (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) :
(Min x ∈ s, b + f x) = b + (Min x ∈ s, f x) :=
begin
rewrite [↑set.Min],
apply finset.Min_add_left f b (λ h, sne (eq_empty_of_to_finset_eq_empty h))
end
end decidable_linear_ordered_cancel_comm_monoid_B
section decidable_linear_ordered_comm_group_B
variable [decidable_linear_ordered_comm_group B]
proposition Max_neg (f : A → B) (s : set A) : (Max x ∈ s, - f x) = - Min x ∈ s, f x :=
by rewrite [↑set.Max, finset.Max_neg]
proposition Min_neg (f : A → B) (s : set A) : (Min x ∈ s, - f x) = - Max x ∈ s, f x :=
by rewrite [↑set.Min, finset.Min_neg]
proposition Max_eq_neg_Min_neg (f : A → B) (s : set A) : (Max x ∈ s, f x) = - Min x ∈ s, - f x :=
by rewrite [↑set.Max, ↑set.Min, finset.Max_eq_neg_Min_neg]
proposition Min_eq_neg_Max_neg (f : A → B) (s : set A) : (Min x ∈ s, f x) = - Max x ∈ s, - f x :=
by rewrite [↑set.Max, ↑set.Min, finset.Min_eq_neg_Max_neg]
end decidable_linear_ordered_comm_group_B
section decidable_linear_ordered_semiring_A
variable [decidable_linear_ordered_semiring A]
noncomputable definition Max₀ (s : set A) : A := Max x ∈ s, x
noncomputable definition Min₀ (s : set A) : A := Min x ∈ s, x
proposition Max₀_empty : Max₀ ∅ = (0 : A) := !Max_empty
proposition Max₀_singleton (a : A) : Max₀ '{a} = a := !Max_singleton
proposition Max₀_insert_insert {a₁ a₂ : A} {s : set A} [fins : finite s] (H₁ : a₂ ∉ s)
(H₂ : a₁ ∉ insert a₂ s) :
Max₀ (insert a₁ (insert a₂ s)) = max a₁ (Max₀ (insert a₂ s)) :=
!Max_insert_insert H₁ H₂
proposition Max₀_insert {s : set A} [fins : finite s] {a : A} (anins : a ∉ s) (sne : s ≠ ∅) :
Max₀ (insert a s) = max a (Max₀ s) := !Max_insert anins sne
proposition Max₀_pair (a₁ a₂ : A) : Max₀ '{a₁, a₂} = max a₁ a₂ := !Max_pair
proposition le_Max₀ {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : a ≤ Max₀ s := !le_Max H
proposition Max₀_le {s : set A} [fins : finite s] {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → x ≤ a) :
Max₀ s ≤ a := !Max_le sne H
proposition Min₀_empty : Min₀ ∅ = (0 : A) := !Min_empty
proposition Min₀_singleton (a : A) : Min₀ '{a} = a := !Min_singleton
proposition Min₀_insert_insert {a₁ a₂ : A} {s : set A} [fins : finite s] (H₁ : a₂ ∉ s)
(H₂ : a₁ ∉ insert a₂ s) :
Min₀ (insert a₁ (insert a₂ s)) = min a₁ (Min₀ (insert a₂ s)) :=
!Min_insert_insert H₁ H₂
proposition Min₀_insert {s : set A} [fins : finite s] {a : A} (anins : a ∉ s) (sne : s ≠ ∅) :
Min₀ (insert a s) = min a (Min₀ s) := !Min_insert anins sne
proposition Min₀_pair (a₁ a₂ : A) : Min₀ '{a₁, a₂} = min a₁ a₂ := !Min_pair
proposition Min₀_le {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : Min₀ s ≤ a := !Min_le H
proposition le_Min₀ {s : set A} [fins : finite s] {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → a ≤ x) :
a ≤ Min₀ s := !le_Min sne H
end decidable_linear_ordered_semiring_A
end set
|
8652d80005d399a4987332b49644bd7153a7908a | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/category_theory/closed/cartesian.lean | eb5572f5e921d1fdeb3439ac7fa62add83c634fc | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 16,495 | lean | /-
Copyright (c) 2020 Bhavik Mehta, Edward Ayers, Thomas Read. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Edward Ayers, Thomas Read
-/
import category_theory.limits.shapes.finite_products
import category_theory.limits.shapes.constructions.preserve_binary_products
import category_theory.closed.monoidal
import category_theory.monoidal.of_has_finite_products
import category_theory.adjunction
import category_theory.epi_mono
/-!
# Cartesian closed categories
Given a category with finite products, the cartesian monoidal structure is provided by the local
instance `monoidal_of_has_finite_products`.
We define exponentiable objects to be closed objects with respect to this monoidal structure,
i.e. `(X × -)` is a left adjoint.
We say a category is cartesian closed if every object is exponentiable
(equivalently, that the category equipped with the cartesian monoidal structure is closed monoidal).
Show that exponential forms a difunctor and define the exponential comparison morphisms.
## TODO
Some of the results here are true more generally for closed objects and
for closed monoidal categories, and these could be generalised.
-/
universes v u u₂
noncomputable theory
namespace category_theory
open category_theory category_theory.category category_theory.limits
local attribute [instance] monoidal_of_has_finite_products
/--
An object `X` is *exponentiable* if `(X × -)` is a left adjoint.
We define this as being `closed` in the cartesian monoidal structure.
-/
abbreviation exponentiable {C : Type u} [category.{v} C] [has_finite_products C] (X : C) :=
closed X
/--
If `X` and `Y` are exponentiable then `X ⨯ Y` is.
This isn't an instance because it's not usually how we want to construct exponentials, we'll usually
prove all objects are exponential uniformly.
-/
def binary_product_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] {X Y : C}
(hX : exponentiable X) (hY : exponentiable Y) : exponentiable (X ⨯ Y) :=
{ is_adj :=
begin
haveI := hX.is_adj,
haveI := hY.is_adj,
exact adjunction.left_adjoint_of_nat_iso (monoidal_category.tensor_left_tensor _ _).symm
end }
/--
The terminal object is always exponentiable.
This isn't an instance because most of the time we'll prove cartesian closed for all objects
at once, rather than just for this one.
-/
def terminal_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] :
exponentiable ⊤_C :=
unit_closed
/--
A category `C` is cartesian closed if it has finite products and every object is exponentiable.
We define this as `monoidal_closed` with respect to the cartesian monoidal structure.
-/
abbreviation cartesian_closed (C : Type u) [category.{v} C] [has_finite_products C] :=
monoidal_closed C
variables {C : Type u} [category.{v} C] (A B : C) {X X' Y Y' Z : C}
section exp
variables [has_finite_products C] [exponentiable A]
/-- This is (-)^A. -/
def exp : C ⥤ C :=
(@closed.is_adj _ _ _ A _).right
/-- The adjunction between A ⨯ - and (-)^A. -/
def exp.adjunction : prod_functor.obj A ⊣ exp A :=
closed.is_adj.adj
/-- The evaluation natural transformation. -/
def ev : exp A ⋙ prod_functor.obj A ⟶ 𝟭 C :=
closed.is_adj.adj.counit
/-- The coevaluation natural transformation. -/
def coev : 𝟭 C ⟶ prod_functor.obj A ⋙ exp A :=
closed.is_adj.adj.unit
notation A ` ⟹ `:20 B:20 := (exp A).obj B
notation B ` ^^ `:30 A:30 := (exp A).obj B
@[simp, reassoc] lemma ev_coev :
limits.prod.map (𝟙 A) ((coev A).app B) ≫ (ev A).app (A ⨯ B) = 𝟙 (A ⨯ B) :=
adjunction.left_triangle_components (exp.adjunction A)
@[simp, reassoc] lemma coev_ev : (coev A).app (A⟹B) ≫ (exp A).map ((ev A).app B) = 𝟙 (A⟹B) :=
adjunction.right_triangle_components (exp.adjunction A)
end exp
variables {A}
-- Wrap these in a namespace so we don't clash with the core versions.
namespace cartesian_closed
variables [has_finite_products C] [exponentiable A]
/-- Currying in a cartesian closed category. -/
def curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X) :=
(closed.is_adj.adj.hom_equiv _ _).to_fun
/-- Uncurrying in a cartesian closed category. -/
def uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X) :=
(closed.is_adj.adj.hom_equiv _ _).inv_fun
end cartesian_closed
open cartesian_closed
variables [has_finite_products C] [exponentiable A]
@[reassoc]
lemma curry_natural_left (f : X ⟶ X') (g : A ⨯ X' ⟶ Y) :
curry (limits.prod.map (𝟙 _) f ≫ g) = f ≫ curry g :=
adjunction.hom_equiv_naturality_left _ _ _
@[reassoc]
lemma curry_natural_right (f : A ⨯ X ⟶ Y) (g : Y ⟶ Y') :
curry (f ≫ g) = curry f ≫ (exp _).map g :=
adjunction.hom_equiv_naturality_right _ _ _
@[reassoc]
lemma uncurry_natural_right (f : X ⟶ A⟹Y) (g : Y ⟶ Y') :
uncurry (f ≫ (exp _).map g) = uncurry f ≫ g :=
adjunction.hom_equiv_naturality_right_symm _ _ _
@[reassoc]
lemma uncurry_natural_left (f : X ⟶ X') (g : X' ⟶ A⟹Y) :
uncurry (f ≫ g) = limits.prod.map (𝟙 _) f ≫ uncurry g :=
adjunction.hom_equiv_naturality_left_symm _ _ _
@[simp]
lemma uncurry_curry (f : A ⨯ X ⟶ Y) : uncurry (curry f) = f :=
(closed.is_adj.adj.hom_equiv _ _).left_inv f
@[simp]
lemma curry_uncurry (f : X ⟶ A⟹Y) : curry (uncurry f) = f :=
(closed.is_adj.adj.hom_equiv _ _).right_inv f
lemma curry_eq_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) :
curry f = g ↔ f = uncurry g :=
adjunction.hom_equiv_apply_eq _ f g
lemma eq_curry_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) :
g = curry f ↔ uncurry g = f :=
adjunction.eq_hom_equiv_apply _ f g
-- I don't think these two should be simp.
lemma uncurry_eq (g : Y ⟶ A ⟹ X) : uncurry g = limits.prod.map (𝟙 A) g ≫ (ev A).app X :=
adjunction.hom_equiv_counit _
lemma curry_eq (g : A ⨯ Y ⟶ X) : curry g = (coev A).app Y ≫ (exp A).map g :=
adjunction.hom_equiv_unit _
lemma uncurry_id_eq_ev (A X : C) [exponentiable A] : uncurry (𝟙 (A ⟹ X)) = (ev A).app X :=
by rw [uncurry_eq, prod_map_id_id, id_comp]
lemma curry_id_eq_coev (A X : C) [exponentiable A] : curry (𝟙 _) = (coev A).app X :=
by { rw [curry_eq, (exp A).map_id (A ⨯ _)], apply comp_id }
lemma curry_injective : function.injective (curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X)) :=
(closed.is_adj.adj.hom_equiv _ _).injective
lemma uncurry_injective : function.injective (uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X)) :=
(closed.is_adj.adj.hom_equiv _ _).symm.injective
/--
Show that the exponential of the terminal object is isomorphic to itself, i.e. `X^1 ≅ X`.
The typeclass argument is explicit: any instance can be used.
-/
def exp_terminal_iso_self [exponentiable ⊤_C] : (⊤_C ⟹ X) ≅ X :=
yoneda.ext (⊤_ C ⟹ X) X
(λ Y f, (prod.left_unitor Y).inv ≫ uncurry f)
(λ Y f, curry ((prod.left_unitor Y).hom ≫ f))
(λ Z g, by rw [curry_eq_iff, iso.hom_inv_id_assoc] )
(λ Z g, by simp)
(λ Z W f g, by rw [uncurry_natural_left, prod_left_unitor_inv_naturality_assoc f] )
/-- The internal element which points at the given morphism. -/
def internalize_hom (f : A ⟶ Y) : ⊤_C ⟶ (A ⟹ Y) :=
curry (limits.prod.fst ≫ f)
section pre
variables {B}
/-- Pre-compose an internal hom with an external hom. -/
def pre (X : C) (f : B ⟶ A) [exponentiable B] : (A⟹X) ⟶ B⟹X :=
curry (limits.prod.map f (𝟙 _) ≫ (ev A).app X)
lemma pre_id (A X : C) [exponentiable A] : pre X (𝟙 A) = 𝟙 (A⟹X) :=
by { rw [pre, prod_map_id_id, id_comp, ← uncurry_id_eq_ev], simp }
-- There's probably a better proof of this somehow
/-- Precomposition is contrafunctorial. -/
lemma pre_map [exponentiable B] {D : C} [exponentiable D] (f : A ⟶ B) (g : B ⟶ D) :
pre X (f ≫ g) = pre X g ≫ pre X f :=
begin
rw [pre, curry_eq_iff, pre, pre, uncurry_natural_left, uncurry_curry, prod_map_map_assoc,
prod_map_comp_id, assoc, ← uncurry_id_eq_ev, ← uncurry_id_eq_ev, ← uncurry_natural_left,
curry_natural_right, comp_id, uncurry_natural_right, uncurry_curry],
end
end pre
lemma pre_post_comm [cartesian_closed C] {A B : C} {X Y : Cᵒᵖ} (f : A ⟶ B) (g : X ⟶ Y) :
pre A g.unop ≫ (exp Y.unop).map f = (exp X.unop).map f ≫ pre B g.unop :=
begin
erw [← curry_natural_left, eq_curry_iff, uncurry_natural_right, uncurry_curry, prod_map_map_assoc,
(ev _).naturality, assoc], refl
end
/-- The internal hom functor given by the cartesian closed structure. -/
def internal_hom [cartesian_closed C] : C ⥤ Cᵒᵖ ⥤ C :=
{ obj := λ X,
{ obj := λ Y, Y.unop ⟹ X,
map := λ Y Y' f, pre _ f.unop,
map_id' := λ Y, pre_id _ _,
map_comp' := λ Y Y' Y'' f g, pre_map _ _ },
map := λ A B f, { app := λ X, (exp X.unop).map f, naturality' := λ X Y g, pre_post_comm _ _ },
map_id' := λ X, by { ext, apply functor.map_id },
map_comp' := λ X Y Z f g, by { ext, apply functor.map_comp } }
/-- If an initial object `I` exists in a CCC, then `A ⨯ I ≅ I`. -/
@[simps]
def zero_mul {I : C} (t : is_initial I) : A ⨯ I ≅ I :=
{ hom := limits.prod.snd,
inv := t.to _,
hom_inv_id' :=
begin
have: (limits.prod.snd : A ⨯ I ⟶ I) = uncurry (t.to _),
rw ← curry_eq_iff,
apply t.hom_ext,
rw [this, ← uncurry_natural_right, ← eq_curry_iff],
apply t.hom_ext,
end,
inv_hom_id' := t.hom_ext _ _ }
/-- If an initial object `0` exists in a CCC, then `0 ⨯ A ≅ 0`. -/
def mul_zero {I : C} (t : is_initial I) : I ⨯ A ≅ I :=
limits.prod.braiding _ _ ≪≫ zero_mul t
/-- If an initial object `0` exists in a CCC then `0^B ≅ 1` for any `B`. -/
def pow_zero {I : C} (t : is_initial I) [cartesian_closed C] : I ⟹ B ≅ ⊤_ C :=
{ hom := default _,
inv := curry ((mul_zero t).hom ≫ t.to _),
hom_inv_id' :=
begin
rw [← curry_natural_left, curry_eq_iff, ← cancel_epi (mul_zero t).inv],
{ apply t.hom_ext },
{ apply_instance },
{ apply_instance }
end }
-- TODO: Generalise the below to its commutated variants.
-- TODO: Define a distributive category, so that zero_mul and friends can be derived from this.
/-- In a CCC with binary coproducts, the distribution morphism is an isomorphism. -/
def prod_coprod_distrib [has_binary_coproducts C] [cartesian_closed C] (X Y Z : C) :
(Z ⨯ X) ⨿ (Z ⨯ Y) ≅ Z ⨯ (X ⨿ Y) :=
{ hom := coprod.desc (limits.prod.map (𝟙 _) coprod.inl) (limits.prod.map (𝟙 _) coprod.inr),
inv := uncurry (coprod.desc (curry coprod.inl) (curry coprod.inr)),
hom_inv_id' :=
begin
apply coprod.hom_ext,
rw [coprod.inl_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inl_desc, uncurry_curry],
rw [coprod.inr_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inr_desc, uncurry_curry],
end,
inv_hom_id' :=
begin
rw [← uncurry_natural_right, ←eq_curry_iff],
apply coprod.hom_ext,
rw [coprod.inl_desc_assoc, ←curry_natural_right, coprod.inl_desc, ←curry_natural_left, comp_id],
rw [coprod.inr_desc_assoc, ←curry_natural_right, coprod.inr_desc, ←curry_natural_left, comp_id],
end }
/--
If an initial object `I` exists in a CCC then it is a strict initial object,
i.e. any morphism to `I` is an iso.
This actually shows a slightly stronger version: any morphism to an initial object from an
exponentiable object is an isomorphism.
-/
def strict_initial {I : C} (t : is_initial I) (f : A ⟶ I) : is_iso f :=
begin
haveI : mono (limits.prod.lift (𝟙 A) f ≫ (zero_mul t).hom) := mono_comp _ _,
rw [zero_mul_hom, prod.lift_snd] at _inst,
haveI: split_epi f := ⟨t.to _, t.hom_ext _ _⟩,
apply is_iso_of_mono_of_split_epi
end
instance to_initial_is_iso [has_initial C] (f : A ⟶ ⊥_ C) : is_iso f :=
strict_initial initial_is_initial _
/-- If an initial object `0` exists in a CCC then every morphism from it is monic. -/
lemma initial_mono {I : C} (B : C) (t : is_initial I) [cartesian_closed C] : mono (t.to B) :=
⟨λ B g h _, by { haveI := strict_initial t g, haveI := strict_initial t h, exact eq_of_inv_eq_inv (t.hom_ext _ _) }⟩
instance initial.mono_to [has_initial C] (B : C) [cartesian_closed C] : mono (initial.to B) :=
initial_mono B initial_is_initial
variables {D : Type u₂} [category.{v} D]
section functor
variables [has_finite_products D]
/--
Transport the property of being cartesian closed across an equivalence of categories.
Note we didn't require any coherence between the choice of finite products here, since we transport
along the `prod_comparison` isomorphism.
-/
def cartesian_closed_of_equiv (e : C ≌ D) [h : cartesian_closed C] : cartesian_closed D :=
{ closed := λ X,
{ is_adj :=
begin
haveI q : exponentiable (e.inverse.obj X) := infer_instance,
have : is_left_adjoint (prod_functor.obj (e.inverse.obj X)) := q.is_adj,
have : e.functor ⋙ prod_functor.obj X ⋙ e.inverse ≅ prod_functor.obj (e.inverse.obj X),
apply nat_iso.of_components _ _,
intro Y,
{ apply as_iso (prod_comparison e.inverse X (e.functor.obj Y)) ≪≫ _,
exact ⟨limits.prod.map (𝟙 _) (e.unit_inv.app _),
limits.prod.map (𝟙 _) (e.unit.app _),
by simpa [←prod_map_id_comp, prod_map_id_id],
by simpa [←prod_map_id_comp, prod_map_id_id]⟩, },
{ intros Y Z g,
simp only [prod_comparison, inv_prod_comparison_map_fst, inv_prod_comparison_map_snd,
prod.lift_map, functor.comp_map, prod_functor_obj_map, assoc, comp_id,
iso.trans_hom, as_iso_hom],
apply prod.hom_ext,
{ rw [assoc, prod.lift_fst, prod.lift_fst, ←functor.map_comp,
limits.prod.map_fst, comp_id], },
{ rw [assoc, prod.lift_snd, prod.lift_snd, ←functor.map_comp_assoc, limits.prod.map_snd],
simp only [iso.hom_inv_id_app, assoc, equivalence.inv_fun_map,
functor.map_comp, comp_id],
erw comp_id, }, },
{ have : is_left_adjoint (e.functor ⋙ prod_functor.obj X ⋙ e.inverse) :=
by exactI adjunction.left_adjoint_of_nat_iso this.symm,
have : is_left_adjoint (e.inverse ⋙ e.functor ⋙ prod_functor.obj X ⋙ e.inverse) :=
by exactI adjunction.left_adjoint_of_comp e.inverse _,
have : (e.inverse ⋙ e.functor ⋙ prod_functor.obj X ⋙ e.inverse) ⋙ e.functor ≅
prod_functor.obj X,
{ apply iso_whisker_right e.counit_iso (prod_functor.obj X ⋙ e.inverse ⋙ e.functor) ≪≫ _,
change prod_functor.obj X ⋙ e.inverse ⋙ e.functor ≅ prod_functor.obj X,
apply iso_whisker_left (prod_functor.obj X) e.counit_iso, },
resetI,
apply adjunction.left_adjoint_of_nat_iso this },
end } }
variables [cartesian_closed C] [cartesian_closed D]
variables (F : C ⥤ D) [preserves_limits_of_shape (discrete walking_pair) F]
/--
The exponential comparison map.
`F` is a cartesian closed functor if this is an iso for all `A,B`.
-/
def exp_comparison (A B : C) :
F.obj (A ⟹ B) ⟶ F.obj A ⟹ F.obj B :=
curry (inv (prod_comparison F A _) ≫ F.map ((ev _).app _))
/-- The exponential comparison map is natural in its left argument. -/
lemma exp_comparison_natural_left (A A' B : C) (f : A' ⟶ A) :
exp_comparison F A B ≫ pre (F.obj B) (F.map f) = F.map (pre B f) ≫ exp_comparison F A' B :=
begin
rw [exp_comparison, exp_comparison, ← curry_natural_left, eq_curry_iff, uncurry_natural_left,
pre, uncurry_curry, prod_map_map_assoc, curry_eq, prod_map_id_comp, assoc],
erw [(ev _).naturality, ev_coev_assoc, ← F.map_id, ← prod_comparison_inv_natural_assoc,
← F.map_id, ← prod_comparison_inv_natural_assoc, ← F.map_comp, ← F.map_comp, pre, curry_eq,
prod_map_id_comp, assoc, (ev _).naturality, ev_coev_assoc], refl,
end
/-- The exponential comparison map is natural in its right argument. -/
lemma exp_comparison_natural_right (A B B' : C) (f : B ⟶ B') :
exp_comparison F A B ≫ (exp (F.obj A)).map (F.map f) =
F.map ((exp A).map f) ≫ exp_comparison F A B' :=
by
erw [exp_comparison, ← curry_natural_right, curry_eq_iff, exp_comparison, uncurry_natural_left,
uncurry_curry, assoc, ← F.map_comp, ← (ev _).naturality, F.map_comp,
prod_comparison_inv_natural_assoc, F.map_id]
-- TODO: If F has a left adjoint L, then F is cartesian closed if and only if
-- L (B ⨯ F A) ⟶ L B ⨯ L F A ⟶ L B ⨯ A
-- is an iso for all A ∈ D, B ∈ C.
-- Corollary: If F has a left adjoint L which preserves finite products, F is cartesian closed iff
-- F is full and faithful.
end functor
end category_theory
|
2ba1e7a8ff9fa28922327dffc0bf5cc89f277815 | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/universal/opposites.lean | 35ba76aa93ef8c8eb2d6b00293f1bfbf653059e1 | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 1,151 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison, Daniel Barter
import category_theory.opposites
import category_theory.equivalence
import category_theory.universal.cones
import category_theory.limits
open category_theory
namespace category_theory.limits
universes u v
section
variable {C : Type u}
variable [𝒞 : category.{u v} C]
include 𝒞
def opposite_fan_of_cofan {β : Type v} (f : β → C) (t : cofan f) : @fan (Cᵒᵖ) _ _ f :=
{ X := t.X,
π := λ b, t.ι b }
def fan_of_opposite_cofan {β : Type v} (f : β → C) (t : @cofan (Cᵒᵖ) _ _ f) : fan f :=
{ X := t.X,
π := λ b, t.ι b }
instance [has_coproducts.{u v} C] : has_products.{u v} (Cᵒᵖ) :=
{ prod := λ {β : Type v} (f : β → C), fan_of_opposite_cofan f sorry,
is_product := sorry }
instance [has_coequalizers.{u v} C] : has_equalizers.{u v} (Cᵒᵖ) := sorry
-- making this an instance would cause loops:
def has_colimits_of_opposite_has_limits [has_limits.{u v} (Cᵒᵖ)] : has_colimits.{u v} C := sorry
end
end category_theory.limits
|
9525ea6ca7938ffc3ffeb881a332d0c66a30025c | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/sheaves/stalks.lean | 61956d8613af183f27810a8c3c7cc1e6e50f1b77 | [
"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 | 20,621 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Justus Springer
-/
import topology.category.Top.open_nhds
import topology.sheaves.presheaf
import topology.sheaves.sheaf_condition.unique_gluing
import category_theory.limits.types
import category_theory.limits.preserves.filtered
import tactic.elementwise
/-!
# Stalks
For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F`
at the point `x : X` is defined as the colimit of the following functor
(nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ ⥤ C
where the functor on the left is the inclusion of categories and the functor on the right is `F`.
For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the
canonical morphism into this colimit.
Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`,
sending presheaves on `X` to objects of `C`. Furthermore, for a map `f : X ⟶ Y` between
topological spaces, we define `stalk_pushforward` as the induced map on the stalks
`(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`.
Some lemmas about stalks and germs only hold for certain classes of concrete categories. A basic
property of forgetful functors of categories of algebraic structures (like `Mon`, `CommRing`,...)
is that they preserve filtered colimits. Since stalks are filtered colimits, this ensures that
the stalks of presheaves valued in these categories behave exactly as for `Type`-valued presheaves.
For example, in `germ_exist` we prove that in such a category, every element of the stalk is the
germ of a section.
Furthermore, if we require the forgetful functor to reflect isomorphisms and preserve limits (as
is the case for most algebraic structures), we have access to the unique gluing API and can prove
further properties. Most notably, in `is_iso_iff_stalk_functor_map_iso`, we prove that in such
a category, a morphism of sheaves is an isomorphism if and only if all of its stalk maps are
isomorphisms.
See also the definition of "algebraic structures" in the stacks project:
https://stacks.math.columbia.edu/tag/007L
-/
noncomputable theory
universes v u v' u'
open category_theory
open Top
open category_theory.limits
open topological_space
open opposite
variables {C : Type u} [category.{v} C]
variables [has_colimits.{v} C]
variables {X Y Z : Top.{v}}
namespace Top.presheaf
variables (C)
/-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/
def stalk_functor (x : X) : X.presheaf C ⥤ C :=
((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim
variables {C}
/--
The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor
nbhds x ⥤ opens F.X ⥤ C
-/
def stalk (ℱ : X.presheaf C) (x : X) : C :=
(stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ)
@[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) :
(stalk_functor C x).obj ℱ = ℱ.stalk x := rfl
/--
The germ of a section of a presheaf over an open at a point of that open.
-/
def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x :=
colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩)
@[simp, elementwise]
lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) :
F.map i.op ≫ germ F x = germ F (i x : V) :=
let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in
colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op
/--
A morphism from the stalk of `F` at `x` to some object `Y` is completely determined by its
composition with the `germ` morphisms.
-/
lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y}
(ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ :=
colimit.hom_ext $ λ U, by { induction U using opposite.rec, cases U with U hxU, exact ih U hxU }
@[simp, reassoc, elementwise]
lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U)
(f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x :=
colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩)
variables (C)
/--
For a presheaf `F` on a space `X`, a continuous map `f : X ⟶ Y` induces a morphisms between the
stalk of `f _ * F` at `f x` and the stalk of `F` at `x`.
-/
def stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) (x : X) : (f _* F).stalk (f x) ⟶ F.stalk x :=
begin
-- This is a hack; Lean doesn't like to elaborate the term written directly.
transitivity,
swap,
exact colimit.pre _ (open_nhds.map f x).op,
exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) F),
end
@[simp, elementwise, reassoc]
lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y)
(x : (opens.map f).obj U) :
(f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x :=
begin
rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app],
erw [category_theory.functor.map_id, category.id_comp],
refl,
end
-- Here are two other potential solutions, suggested by @fpvandoorn at
-- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240>
-- However, I can't get the subsequent two proofs to work with either one.
-- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) :
-- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x :=
-- colim.map ((functor.associator _ _ _).inv ≫
-- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫
-- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op
-- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) :
-- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x :=
-- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) :
-- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫
-- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op
namespace stalk_pushforward
local attribute [tidy] tactic.op_induction'
@[simp] lemma id (ℱ : X.presheaf C) (x : X) :
ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) :=
begin
dsimp [stalk_pushforward, stalk_functor],
ext1,
tactic.op_induction',
cases j, cases j_val,
rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app,
pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl],
dsimp,
-- FIXME A simp lemma which unfortunately doesn't fire:
erw [category_theory.functor.map_id],
end
-- This proof is sadly not at all robust:
-- having to use `erw` at all is a bad sign.
@[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) :
ℱ.stalk_pushforward C (f ≫ g) x =
((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) :=
begin
dsimp [stalk_pushforward, stalk_functor],
ext U,
induction U using opposite.rec,
cases U,
cases U_val,
simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc,
whisker_right_app, category.assoc],
dsimp,
-- FIXME: Some of these are simp lemmas, but don't fire successfully:
erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp,
colimit.ι_pre, colimit.ι_pre],
refl,
end
end stalk_pushforward
section stalk_pullback
/-- The morphism `ℱ_{f x} ⟶ (f⁻¹ℱ)ₓ` that factors through `(f_*f⁻¹ℱ)_{f x}`. -/
def stalk_pullback_hom (f : X ⟶ Y) (F : Y.presheaf C) (x : X) :
F.stalk (f x) ⟶ (pullback_obj f F).stalk x :=
(stalk_functor _ (f x)).map ((pushforward_pullback_adjunction C f).unit.app F) ≫
stalk_pushforward _ _ _ x
/-- The morphism `(f⁻¹ℱ)(U) ⟶ ℱ_{f(x)}` for some `U ∋ x`. -/
def germ_to_pullback_stalk (f : X ⟶ Y) (F : Y.presheaf C) (U : opens X) (x : U) :
(pullback_obj f F).obj (op U) ⟶ F.stalk (f x) :=
colimit.desc (Lan.diagram (opens.map f).op F (op U))
{ X := F.stalk (f x),
ι := { app := λ V, F.germ ⟨f x, V.hom.unop.le x.2⟩,
naturality' := λ _ _ i, by { erw category.comp_id, exact F.germ_res i.left.unop _ } } }
/-- The morphism `(f⁻¹ℱ)ₓ ⟶ ℱ_{f(x)}`. -/
def stalk_pullback_inv (f : X ⟶ Y) (F : Y.presheaf C) (x : X) :
(pullback_obj f F).stalk x ⟶ F.stalk (f x) :=
colimit.desc ((open_nhds.inclusion x).op ⋙ presheaf.pullback_obj f F)
{ X := F.stalk (f x),
ι := { app := λ U, F.germ_to_pullback_stalk _ f (unop U).1 ⟨x, (unop U).2⟩,
naturality' := λ _ _ _, by { erw [colimit.pre_desc, category.comp_id], congr } } }
/-- The isomorphism `ℱ_{f(x)} ≅ (f⁻¹ℱ)ₓ`. -/
def stalk_pullback_iso (f : X ⟶ Y) (F : Y.presheaf C) (x : X) :
F.stalk (f x) ≅ (pullback_obj f F).stalk x :=
{ hom := stalk_pullback_hom _ _ _ _,
inv := stalk_pullback_inv _ _ _ _,
hom_inv_id' :=
begin
delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward
germ_to_pullback_stalk germ,
ext j,
induction j using opposite.rec,
cases j,
simp only [topological_space.open_nhds.inclusion_map_iso_inv, whisker_right_app,
whisker_left_app, whiskering_left_obj_map, functor.comp_map, colimit.ι_map_assoc,
nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app, category.assoc,
colimit.ι_pre_assoc],
erw [colimit.ι_desc, colimit.pre_desc, colimit.ι_desc, category.comp_id],
simpa
end,
inv_hom_id' :=
begin
delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward,
ext U j,
induction U using opposite.rec,
cases U, cases j, cases j_right,
erw [colimit.map_desc, colimit.map_desc, colimit.ι_desc_assoc,
colimit.ι_desc_assoc, colimit.ι_desc, category.comp_id],
simp only [cocone.whisker_ι, colimit.cocone_ι, open_nhds.inclusion_map_iso_inv,
cocones.precompose_obj_ι, whisker_right_app, whisker_left_app, nat_trans.comp_app,
whiskering_left_obj_map, nat_trans.op_id, Lan_obj_map,
pushforward_pullback_adjunction_unit_app_app],
erw ←colimit.w _
(@hom_of_le (open_nhds x) _
⟨_, U_property⟩ ⟨(opens.map f).obj (unop j_left), j_hom.unop.le U_property⟩
j_hom.unop.le).op,
erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _),
erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _),
congr,
simp only [category.assoc, costructured_arrow.map_mk],
delta costructured_arrow.mk,
congr
end }
end stalk_pullback
section concrete
variables {C}
variables [concrete_category.{v} C]
local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun
@[ext]
lemma germ_ext (F : X.presheaf C) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V}
(W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)}
(ih : F.map iWU.op sU = F.map iWV.op sV) :
F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV :=
by erw [← F.germ_res iWU ⟨x, hxW⟩,
← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih]
variables [preserves_filtered_colimits (forget C)]
/--
For presheaves valued in a concrete category whose forgetful functor preserves filtered colimits,
every element of the stalk is the germ of a section.
-/
lemma germ_exist (F : X.presheaf C) (x : X) (t : stalk F x) :
∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t :=
begin
obtain ⟨U, s, e⟩ := types.jointly_surjective _
(is_colimit_of_preserves (forget C) (colimit.is_colimit _)) t,
revert s e,
rw [(show U = op (unop U), from rfl)],
generalize : unop U = V, clear U,
cases V with V m,
intros s e,
exact ⟨V, m, s, e⟩,
end
lemma germ_eq (F : X.presheaf C) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V)
(s : F.obj (op U)) (t : F.obj (op V))
(h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) :
∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t :=
begin
obtain ⟨W, iU, iV, e⟩ := (types.filtered_colimit.is_colimit_eq_iff _
(is_colimit_of_preserves _ (colimit.is_colimit ((open_nhds.inclusion x).op ⋙ F)))).mp h,
exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩,
end
lemma stalk_functor_map_injective_of_app_injective {F G : presheaf C X} (f : F ⟶ G)
(h : ∀ U : opens X, function.injective (f.app (op U))) (x : X) :
function.injective ((stalk_functor C x).map f) := λ s t hst,
begin
rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩,
rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩,
simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst,
obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst,
rw [← comp_apply, ← comp_apply, ← f.naturality, ← f.naturality, comp_apply, comp_apply] at heq,
replace heq := h W heq,
convert congr_arg (F.germ ⟨x,hxW⟩) heq,
exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm,
(F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm],
end
variables [has_limits C] [preserves_limits (forget C)] [reflects_isomorphisms (forget C)]
/--
Let `F` be a sheaf valued in a concrete category, whose forgetful functor reflects isomorphisms,
preserves limits and filtered colimits. Then two sections who agree on every stalk must be equal.
-/
lemma section_ext (F : sheaf C X) (U : opens X) (s t : F.1.obj (op U))
(h : ∀ x : U, F.1.germ x s = F.1.germ x t) :
s = t :=
begin
-- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood
-- `V x`, such that the restrictions of `s` and `t` to `V x` coincide.
choose V m i₁ i₂ heq using λ x : U, F.1.germ_eq x.1 x.2 x.2 s t (h x),
-- Since `F` is a sheaf, we can prove the equality locally, if we can show that these
-- neighborhoods form a cover of `U`.
apply F.eq_of_locally_eq' V U i₁,
{ intros x hxU,
rw [opens.mem_coe, opens.mem_supr],
exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ },
{ intro x,
rw [heq, subsingleton.elim (i₁ x) (i₂ x)] }
end
/-
Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not
imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism
is an epi, but this fact is not yet formalized.
-/
lemma app_injective_of_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X}
(f : F.1 ⟶ G) (h : ∀ x : X, function.injective ((stalk_functor C x).map f))
(U : opens X) :
function.injective (f.app (op U)) :=
λ s t hst, section_ext F _ _ _ $ λ x, h x.1 $ by
rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst]
lemma app_injective_iff_stalk_functor_map_injective {F : sheaf C X}
{G : presheaf C X} (f : F.1 ⟶ G) :
(∀ x : X, function.injective ((stalk_functor C x).map f)) ↔
(∀ U : opens X, function.injective (f.app (op U))) :=
⟨app_injective_of_stalk_functor_map_injective f, stalk_functor_map_injective_of_app_injective f⟩
/-- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it.
We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct
a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t`
agree on `V`. -/
lemma app_surjective_of_injective_of_locally_surjective {F G : sheaf C X} (f : F ⟶ G)
(hinj : ∀ x : X, function.injective ((stalk_functor C x).map f)) (U : opens X)
(hsurj : ∀ (t) (x : U), ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.1.obj (op V)),
f.app (op V) s = G.1.map iVU.op t) :
function.surjective (f.app (op U)) :=
begin
intro t,
-- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a
-- preimage under `f` on `V`.
choose V mV iVU sf heq using hsurj t,
-- These neighborhoods clearly cover all of `U`.
have V_cover : U ≤ supr V,
{ intros x hxU,
rw [opens.mem_coe, opens.mem_supr],
exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ },
-- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage.
obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _,
{ use s,
apply G.eq_of_locally_eq' V U iVU V_cover,
intro x,
rw [← comp_apply, ← f.naturality, comp_apply, s_spec, heq] },
{ intros x y,
-- What's left to show here is that the secions `sf` are compatible, i.e. they agree on
-- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal.
apply section_ext,
intro z,
-- Here, we need to use injectivity of the stalk maps.
apply (hinj z),
erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply],
simp_rw [← comp_apply, f.naturality, comp_apply, heq, ← comp_apply, ← G.1.map_comp],
refl }
end
lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G)
(h : ∀ x : X, function.bijective ((stalk_functor C x).map f)) (U : opens X) :
function.surjective (f.app (op U)) :=
begin
refine app_surjective_of_injective_of_locally_surjective f (λ x, (h x).1) U (λ t x, _),
-- Now we need to prove our initial claim: That we can find preimages of `t` locally.
-- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x`
obtain ⟨s₀,hs₀⟩ := (h x).2 (G.1.germ x t),
-- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁`
obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.1.germ_exist x.1 s₀,
subst hs₁, rename hs₀ hs₁,
erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f s₁ at hs₁,
-- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on
-- some open neighborhood `V₂`.
obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.1.germ_eq x.1 hxV₁ x.2 _ _ hs₁,
-- The restriction of `s₁` to that neighborhood is our desired local preimage.
use [V₂, hxV₂, iV₂U, F.1.map iV₂V₁.op s₁],
rw [← comp_apply, f.naturality, comp_apply, heq],
end
lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G)
(h : ∀ x : X, function.bijective ((stalk_functor C x).map f)) (U : opens X) :
function.bijective (f.app (op U)) :=
⟨app_injective_of_stalk_functor_map_injective f (λ x, (h x).1) U,
app_surjective_of_stalk_functor_map_bijective f h U⟩
/--
Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects
isomorphisms, preserves limits and filtered colimits. Then if the stalk maps of a morphism
`f : F ⟶ G` are all isomorphisms, `f` must be an isomorphism.
-/
-- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso`
lemma is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G)
[∀ x : X, is_iso ((stalk_functor C x).map f)] : is_iso f :=
begin
-- Since the inclusion functor from sheaves to presheaves is fully faithful, it suffices to
-- show that `f`, as a morphism between _presheaves_, is an isomorphism.
suffices : is_iso ((sheaf.forget C X).map f),
{ exactI is_iso_of_fully_faithful (sheaf.forget C X) f },
-- We show that all components of `f` are isomorphisms.
suffices : ∀ U : (opens X)ᵒᵖ, is_iso (f.app U),
{ exact @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.1 G.1 f this, },
intro U, induction U using opposite.rec,
-- Since the forgetful functor of `C` reflects isomorphisms, it suffices to see that the
-- underlying map between types is an isomorphism, i.e. bijective.
suffices : is_iso ((forget C).map (f.app (op U))),
{ exactI is_iso_of_reflects_iso (f.app (op U)) (forget C) },
rw is_iso_iff_bijective,
apply app_bijective_of_stalk_functor_map_bijective,
intro x,
apply (is_iso_iff_bijective _).mp,
exact functor.map_is_iso (forget C) ((stalk_functor C x).map f),
end
/--
Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects
isomorphisms, preserves limits and filtered colimits. Then a morphism `f : F ⟶ G` is an
isomorphism if and only if all of its stalk maps are isomorphisms.
-/
lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) :
is_iso f ↔ ∀ x : X, is_iso ((stalk_functor C x).map f) :=
begin
split,
{ intros h x, resetI,
exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor C x) f
((sheaf.forget C X).map_is_iso f) },
{ intro h,
exactI is_iso_of_stalk_functor_map_iso f }
end
end concrete
end Top.presheaf
|
74dde7e145fbfdd4aefdb3a0e0e309adc1654206 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/real/cardinality.lean | d301d012069d2ef4b04ac82a4c1d25be80dfaa56 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 9,588 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import analysis.specific_limits.basic
import data.rat.denumerable
import data.set.intervals.image_preimage
import set_theory.cardinal.continuum
/-!
# The cardinality of the reals
This file shows that the real numbers have cardinality continuum, i.e. `#ℝ = 𝔠`.
We show that `#ℝ ≤ 𝔠` by noting that every real number is determined by a Cauchy-sequence of the
form `ℕ → ℚ`, which has cardinality `𝔠`. To show that `#ℝ ≥ 𝔠` we define an injection from
`{0, 1} ^ ℕ` to `ℝ` with `f ↦ Σ n, f n * (1 / 3) ^ n`.
We conclude that all intervals with distinct endpoints have cardinality continuum.
## Main definitions
* `cardinal.cantor_function` is the function that sends `f` in `{0, 1} ^ ℕ` to `ℝ` by
`f ↦ Σ' n, f n * (1 / 3) ^ n`
## Main statements
* `cardinal.mk_real : #ℝ = 𝔠`: the reals have cardinality continuum.
* `cardinal.not_countable_real`: the universal set of real numbers is not countable.
We can use this same proof to show that all the other sets in this file are not countable.
* 8 lemmas of the form `mk_Ixy_real` for `x,y ∈ {i,o,c}` state that intervals on the reals
have cardinality continuum.
## Notation
* `𝔠` : notation for `cardinal.continuum` in locale `cardinal`, defined in `set_theory.continuum`.
## Tags
continuum, cardinality, reals, cardinality of the reals
-/
open nat set
open_locale cardinal
noncomputable theory
namespace cardinal
variables {c : ℝ} {f g : ℕ → bool} {n : ℕ}
/-- The body of the sum in `cantor_function`.
`cantor_function_aux c f n = c ^ n` if `f n = tt`;
`cantor_function_aux c f n = 0` if `f n = ff`. -/
def cantor_function_aux (c : ℝ) (f : ℕ → bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0
@[simp] lemma cantor_function_aux_tt (h : f n = tt) : cantor_function_aux c f n = c ^ n :=
by simp [cantor_function_aux, h]
@[simp] lemma cantor_function_aux_ff (h : f n = ff) : cantor_function_aux c f n = 0 :=
by simp [cantor_function_aux, h]
lemma cantor_function_aux_nonneg (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n :=
by { cases h' : f n; simp [h'], apply pow_nonneg h }
lemma cantor_function_aux_eq (h : f n = g n) :
cantor_function_aux c f n = cantor_function_aux c g n :=
by simp [cantor_function_aux, h]
lemma cantor_function_aux_succ (f : ℕ → bool) :
(λ n, cantor_function_aux c f (n + 1)) = λ n, c * cantor_function_aux c (λ n, f (n + 1)) n :=
by { ext n, cases h : f (n + 1); simp [h, pow_succ] }
lemma summable_cantor_function (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) :
summable (cantor_function_aux c f) :=
begin
apply (summable_geometric_of_lt_1 h1 h2).summable_of_eq_zero_or_self,
intro n, cases h : f n; simp [h]
end
/-- `cantor_function c (f : ℕ → bool)` is `Σ n, f n * c ^ n`, where `tt` is interpreted as `1` and
`ff` is interpreted as `0`. It is implemented using `cantor_function_aux`. -/
def cantor_function (c : ℝ) (f : ℕ → bool) : ℝ := ∑' n, cantor_function_aux c f n
lemma cantor_function_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) :
cantor_function c f ≤ cantor_function c g :=
begin
apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2),
intro n, cases h : f n, simp [h, cantor_function_aux_nonneg h1],
replace h3 : g n = tt := h3 n h, simp [h, h3]
end
lemma cantor_function_succ (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) :
cantor_function c f = cond (f 0) 1 0 + c * cantor_function c (λ n, f (n+1)) :=
begin
rw [cantor_function, tsum_eq_zero_add (summable_cantor_function f h1 h2)],
rw [cantor_function_aux_succ, tsum_mul_left, cantor_function_aux, pow_zero],
refl
end
/-- `cantor_function c` is strictly increasing with if `0 < c < 1/2`, if we endow `ℕ → bool` with a
lexicographic order. The lexicographic order doesn't exist for these infinitary products, so we
explicitly write out what it means. -/
lemma increasing_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → bool}
(hn : ∀(k < n), f k = g k) (fn : f n = ff) (gn : g n = tt) :
cantor_function c f < cantor_function c g :=
begin
have h3 : c < 1, { apply h2.trans, norm_num },
induction n with n ih generalizing f g,
{ let f_max : ℕ → bool := λ n, nat.rec ff (λ _ _, tt) n,
have hf_max : ∀n, f n → f_max n,
{ intros n hn, cases n, rw [fn] at hn, contradiction, apply rfl },
let g_min : ℕ → bool := λ n, nat.rec tt (λ _ _, ff) n,
have hg_min : ∀n, g_min n → g n,
{ intros n hn, cases n, rw [gn], apply rfl, contradiction },
apply (cantor_function_le (le_of_lt h1) h3 hf_max).trans_lt,
refine lt_of_lt_of_le _ (cantor_function_le (le_of_lt h1) h3 hg_min),
have : c / (1 - c) < 1,
{ rw [div_lt_one, lt_sub_iff_add_lt],
{ convert add_lt_add h2 h2, norm_num },
rwa sub_pos },
convert this,
{ rw [cantor_function_succ _ (le_of_lt h1) h3, div_eq_mul_inv,
←tsum_geometric_of_lt_1 (le_of_lt h1) h3],
apply zero_add },
{ convert tsum_eq_single 0 _,
{ apply_instance },
{ intros n hn, cases n, contradiction, refl } } },
rw [cantor_function_succ f (le_of_lt h1) h3, cantor_function_succ g (le_of_lt h1) h3],
rw [hn 0 $ zero_lt_succ n],
apply add_lt_add_left, rw mul_lt_mul_left h1, exact ih (λ k hk, hn _ $ nat.succ_lt_succ hk) fn gn
end
/-- `cantor_function c` is injective if `0 < c < 1/2`. -/
lemma cantor_function_injective (h1 : 0 < c) (h2 : c < 1 / 2) :
function.injective (cantor_function c) :=
begin
intros f g hfg, classical, by_contra h, revert hfg,
have : ∃n, f n ≠ g n,
{ rw [←not_forall], intro h', apply h, ext, apply h' },
let n := nat.find this,
have hn : ∀ (k : ℕ), k < n → f k = g k,
{ intros k hk, apply of_not_not, exact nat.find_min this hk },
cases fn : f n,
{ apply ne_of_lt, refine increasing_cantor_function h1 h2 hn fn _,
apply eq_tt_of_not_eq_ff, rw [←fn], apply ne.symm, exact nat.find_spec this },
{ apply ne_of_gt, refine increasing_cantor_function h1 h2 (λ k hk, (hn k hk).symm) _ fn,
apply eq_ff_of_not_eq_tt, rw [←fn], apply ne.symm, exact nat.find_spec this }
end
/-- The cardinality of the reals, as a type. -/
lemma mk_real : #ℝ = 𝔠 :=
begin
apply le_antisymm,
{ rw real.equiv_Cauchy.cardinal_eq,
apply mk_quotient_le.trans, apply (mk_subtype_le _).trans_eq,
rw [← power_def, mk_nat, mk_rat, omega_power_omega] },
{ convert mk_le_of_injective (cantor_function_injective _ _),
rw [←power_def, mk_bool, mk_nat, two_power_omega], exact 1 / 3, norm_num, norm_num }
end
/-- The cardinality of the reals, as a set. -/
lemma mk_univ_real : #(set.univ : set ℝ) = 𝔠 :=
by rw [mk_univ, mk_real]
/-- **Non-Denumerability of the Continuum**: The reals are not countable. -/
lemma not_countable_real : ¬ countable (set.univ : set ℝ) :=
by { rw [← mk_set_le_omega, not_le, mk_univ_real], apply cantor }
/-- The cardinality of the interval (a, ∞). -/
lemma mk_Ioi_real (a : ℝ) : #(Ioi a) = 𝔠 :=
begin
refine le_antisymm (mk_real ▸ mk_set_le _) _,
rw [← not_lt], intro h,
refine ne_of_lt _ mk_univ_real,
have hu : Iio a ∪ {a} ∪ Ioi a = set.univ,
{ convert Iic_union_Ioi, exact Iio_union_right },
rw ← hu,
refine lt_of_le_of_lt (mk_union_le _ _) _,
refine lt_of_le_of_lt (add_le_add_right (mk_union_le _ _) _) _,
have h2 : (λ x, a + a - x) '' Ioi a = Iio a,
{ convert image_const_sub_Ioi _ _, simp },
rw ← h2,
refine add_lt_of_lt (cantor _).le _ h,
refine add_lt_of_lt (cantor _).le (mk_image_le.trans_lt h) _,
rw mk_singleton,
exact one_lt_omega.trans (cantor _)
end
/-- The cardinality of the interval [a, ∞). -/
lemma mk_Ici_real (a : ℝ) : #(Ici a) = 𝔠 :=
le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioi_real a ▸ mk_le_mk_of_subset Ioi_subset_Ici_self)
/-- The cardinality of the interval (-∞, a). -/
lemma mk_Iio_real (a : ℝ) : #(Iio a) = 𝔠 :=
begin
refine le_antisymm (mk_real ▸ mk_set_le _) _,
have h2 : (λ x, a + a - x) '' Iio a = Ioi a,
{ convert image_const_sub_Iio _ _, simp },
exact mk_Ioi_real a ▸ h2 ▸ mk_image_le
end
/-- The cardinality of the interval (-∞, a]. -/
lemma mk_Iic_real (a : ℝ) : #(Iic a) = 𝔠 :=
le_antisymm (mk_real ▸ mk_set_le _) (mk_Iio_real a ▸ mk_le_mk_of_subset Iio_subset_Iic_self)
/-- The cardinality of the interval (a, b). -/
lemma mk_Ioo_real {a b : ℝ} (h : a < b) : #(Ioo a b) = 𝔠 :=
begin
refine le_antisymm (mk_real ▸ mk_set_le _) _,
have h1 : #((λ x, x - a) '' Ioo a b) ≤ #(Ioo a b) := mk_image_le,
refine le_trans _ h1,
rw [image_sub_const_Ioo, sub_self],
replace h := sub_pos_of_lt h,
have h2 : #(has_inv.inv '' Ioo 0 (b - a)) ≤ #(Ioo 0 (b - a)) := mk_image_le,
refine le_trans _ h2,
rw [image_inv, inv_Ioo_0_left h, mk_Ioi_real]
end
/-- The cardinality of the interval [a, b). -/
lemma mk_Ico_real {a b : ℝ} (h : a < b) : #(Ico a b) = 𝔠 :=
le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Ico_self)
/-- The cardinality of the interval [a, b]. -/
lemma mk_Icc_real {a b : ℝ} (h : a < b) : #(Icc a b) = 𝔠 :=
le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Icc_self)
/-- The cardinality of the interval (a, b]. -/
lemma mk_Ioc_real {a b : ℝ} (h : a < b) : #(Ioc a b) = 𝔠 :=
le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Ioc_self)
end cardinal
|
338cb513baead01c6b2cd6b942936fc4132a99f9 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Parser/Extension.lean | 35e724664f775979bd789c1c7e51ec44cf9af288 | [
"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 | 31,695 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.ResolveName
import Lean.ScopedEnvExtension
import Lean.Parser.Basic
import Lean.Parser.StrInterpolation
import Lean.KeyedDeclsAttribute
import Lean.DocString
import Lean.DeclarationRange
/-! Extensible parsing via attributes -/
namespace Lean
namespace Parser
builtin_initialize builtinTokenTable : IO.Ref TokenTable ← IO.mkRef {}
/- Global table with all SyntaxNodeKind's -/
builtin_initialize builtinSyntaxNodeKindSetRef : IO.Ref SyntaxNodeKindSet ← IO.mkRef {}
def registerBuiltinNodeKind (k : SyntaxNodeKind) : IO Unit :=
builtinSyntaxNodeKindSetRef.modify fun s => s.insert k
builtin_initialize
registerBuiltinNodeKind choiceKind
registerBuiltinNodeKind identKind
registerBuiltinNodeKind strLitKind
registerBuiltinNodeKind numLitKind
registerBuiltinNodeKind scientificLitKind
registerBuiltinNodeKind charLitKind
registerBuiltinNodeKind nameLitKind
builtin_initialize builtinParserCategoriesRef : IO.Ref ParserCategories ← IO.mkRef {}
private def throwParserCategoryAlreadyDefined {α} (catName : Name) : ExceptT String Id α :=
throw s!"parser category '{catName}' has already been defined"
private def addParserCategoryCore (categories : ParserCategories) (catName : Name) (initial : ParserCategory) : Except String ParserCategories :=
if categories.contains catName then
throwParserCategoryAlreadyDefined catName
else
pure $ categories.insert catName initial
/-- All builtin parser categories are Pratt's parsers -/
private def addBuiltinParserCategory (catName declName : Name) (behavior : LeadingIdentBehavior) : IO Unit := do
let categories ← builtinParserCategoriesRef.get
let categories ← IO.ofExcept $ addParserCategoryCore categories catName { declName, behavior }
builtinParserCategoriesRef.set categories
namespace ParserExtension
inductive OLeanEntry where
| token (val : Token) : OLeanEntry
| kind (val : SyntaxNodeKind) : OLeanEntry
| category (catName : Name) (declName : Name) (behavior : LeadingIdentBehavior)
| parser (catName : Name) (declName : Name) (prio : Nat) : OLeanEntry
deriving Inhabited
inductive Entry where
| token (val : Token) : Entry
| kind (val : SyntaxNodeKind) : Entry
| category (catName : Name) (declName : Name) (behavior : LeadingIdentBehavior)
| parser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Entry
deriving Inhabited
def Entry.toOLeanEntry : Entry → OLeanEntry
| token v => OLeanEntry.token v
| kind v => OLeanEntry.kind v
| category c d b => OLeanEntry.category c d b
| parser c d _ _ prio => OLeanEntry.parser c d prio
structure State where
tokens : TokenTable := {}
kinds : SyntaxNodeKindSet := {}
categories : ParserCategories := {}
deriving Inhabited
end ParserExtension
open ParserExtension in
abbrev ParserExtension := ScopedEnvExtension OLeanEntry Entry State
private def ParserExtension.mkInitial : IO ParserExtension.State := do
let tokens ← builtinTokenTable.get
let kinds ← builtinSyntaxNodeKindSetRef.get
let categories ← builtinParserCategoriesRef.get
pure { tokens := tokens, kinds := kinds, categories := categories }
private def addTokenConfig (tokens : TokenTable) (tk : Token) : Except String TokenTable := do
if tk == "" then throw "invalid empty symbol"
else match tokens.find? tk with
| none => pure $ tokens.insert tk tk
| some _ => pure tokens
def throwUnknownParserCategory {α} (catName : Name) : ExceptT String Id α :=
throw s!"unknown parser category '{catName}'"
abbrev getCategory (categories : ParserCategories) (catName : Name) : Option ParserCategory :=
categories.find? catName
def addLeadingParser (categories : ParserCategories) (catName declName : Name) (p : Parser) (prio : Nat) : Except String ParserCategories :=
match getCategory categories catName with
| none =>
throwUnknownParserCategory catName
| some cat =>
let kinds := cat.kinds.insert declName
let addTokens (tks : List Token) : Except String ParserCategories :=
let tks := tks.map Name.mkSimple
let tables := tks.eraseDups.foldl (init := cat.tables) fun tables tk =>
{ tables with leadingTable := tables.leadingTable.insert tk (p, prio) }
pure $ categories.insert catName { cat with kinds, tables }
match p.info.firstTokens with
| FirstTokens.tokens tks => addTokens tks
| FirstTokens.optTokens tks => addTokens tks
| _ =>
let tables := { cat.tables with leadingParsers := (p, prio) :: cat.tables.leadingParsers }
pure $ categories.insert catName { cat with kinds, tables }
private def addTrailingParserAux (tables : PrattParsingTables) (p : TrailingParser) (prio : Nat) : PrattParsingTables :=
let addTokens (tks : List Token) : PrattParsingTables :=
let tks := tks.map fun tk => Name.mkSimple tk
tks.eraseDups.foldl (init := tables) fun tables tk =>
{ tables with trailingTable := tables.trailingTable.insert tk (p, prio) }
match p.info.firstTokens with
| FirstTokens.tokens tks => addTokens tks
| FirstTokens.optTokens tks => addTokens tks
| _ => { tables with trailingParsers := (p, prio) :: tables.trailingParsers }
def addTrailingParser (categories : ParserCategories) (catName declName : Name) (p : TrailingParser) (prio : Nat) : Except String ParserCategories :=
match getCategory categories catName with
| none => throwUnknownParserCategory catName
| some cat =>
let kinds := cat.kinds.insert declName
let tables := addTrailingParserAux cat.tables p prio
pure $ categories.insert catName { cat with kinds, tables }
def addParser (categories : ParserCategories) (catName declName : Name)
(leading : Bool) (p : Parser) (prio : Nat) : Except String ParserCategories := do
match leading, p with
| true, p => addLeadingParser categories catName declName p prio
| false, p => addTrailingParser categories catName declName p prio
def addParserTokens (tokenTable : TokenTable) (info : ParserInfo) : Except String TokenTable :=
let newTokens := info.collectTokens []
newTokens.foldlM addTokenConfig tokenTable
private def updateBuiltinTokens (info : ParserInfo) (declName : Name) : IO Unit := do
let tokenTable ← builtinTokenTable.swap {}
match addParserTokens tokenTable info with
| Except.ok tokenTable => builtinTokenTable.set tokenTable
| Except.error msg => throw (IO.userError s!"invalid builtin parser '{declName}', {msg}")
def ParserExtension.addEntryImpl (s : State) (e : Entry) : State :=
match e with
| Entry.token tk =>
match addTokenConfig s.tokens tk with
| Except.ok tokens => { s with tokens }
| _ => unreachable!
| Entry.kind k =>
{ s with kinds := s.kinds.insert k }
| Entry.category catName declName behavior =>
if s.categories.contains catName then s
else { s with
categories := s.categories.insert catName { declName, behavior } }
| Entry.parser catName declName leading parser prio =>
match addParser s.categories catName declName leading parser prio with
| Except.ok categories => { s with categories }
| _ => unreachable!
/-- Parser aliases for making `ParserDescr` extensible -/
inductive AliasValue (α : Type) where
| const (p : α)
| unary (p : α → α)
| binary (p : α → α → α)
abbrev AliasTable (α) := NameMap (AliasValue α)
def registerAliasCore {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) (value : AliasValue α) : IO Unit := do
unless (← IO.initializing) do throw ↑"aliases can only be registered during initialization"
if (← mapRef.get).contains aliasName then
throw ↑s!"alias '{aliasName}' has already been declared"
mapRef.modify (·.insert aliasName value)
def getAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (Option (AliasValue α)) := do
return (← mapRef.get).find? aliasName
def getConstAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO α := do
match (← getAlias mapRef aliasName) with
| some (AliasValue.const v) => pure v
| some (AliasValue.unary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes one argument"
| some (AliasValue.binary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes two arguments"
| none => throw ↑s!"parser '{aliasName}' was not found"
def getUnaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α) := do
match (← getAlias mapRef aliasName) with
| some (AliasValue.unary v) => pure v
| some _ => throw ↑s!"parser '{aliasName}' does not take one argument"
| none => throw ↑s!"parser '{aliasName}' was not found"
def getBinaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α → α) := do
match (← getAlias mapRef aliasName) with
| some (AliasValue.binary v) => pure v
| some _ => throw ↑s!"parser '{aliasName}' does not take two arguments"
| none => throw ↑s!"parser '{aliasName}' was not found"
abbrev ParserAliasValue := AliasValue Parser
structure ParserAliasInfo where
declName : Name := .anonymous
/-- Number of syntax nodes produced by this parser. `none` means "sum of input sizes". -/
stackSz? : Option Nat := some 1
/-- Whether arguments should be wrapped in `group(·)` if they do not produce exactly one syntax node. -/
autoGroupArgs : Bool := stackSz?.isSome
builtin_initialize parserAliasesRef : IO.Ref (NameMap ParserAliasValue) ← IO.mkRef {}
builtin_initialize parserAlias2kindRef : IO.Ref (NameMap SyntaxNodeKind) ← IO.mkRef {}
builtin_initialize parserAliases2infoRef : IO.Ref (NameMap ParserAliasInfo) ← IO.mkRef {}
def getParserAliasInfo (aliasName : Name) : IO ParserAliasInfo := do
return (← parserAliases2infoRef.get).findD aliasName {}
-- Later, we define macro `register_parser_alias` which registers a parser, formatter and parenthesizer
def registerAlias (aliasName declName : Name) (p : ParserAliasValue) (kind? : Option SyntaxNodeKind := none) (info : ParserAliasInfo := {}) : IO Unit := do
registerAliasCore parserAliasesRef aliasName p
if let some kind := kind? then
parserAlias2kindRef.modify (·.insert aliasName kind)
parserAliases2infoRef.modify (·.insert aliasName { info with declName })
instance : Coe Parser ParserAliasValue := { coe := AliasValue.const }
instance : Coe (Parser → Parser) ParserAliasValue := { coe := AliasValue.unary }
instance : Coe (Parser → Parser → Parser) ParserAliasValue := { coe := AliasValue.binary }
def isParserAlias (aliasName : Name) : IO Bool := do
match (← getAlias parserAliasesRef aliasName) with
| some _ => pure true
| _ => pure false
def getSyntaxKindOfParserAlias? (aliasName : Name) : IO (Option SyntaxNodeKind) :=
return (← parserAlias2kindRef.get).find? aliasName
def ensureUnaryParserAlias (aliasName : Name) : IO Unit :=
discard $ getUnaryAlias parserAliasesRef aliasName
def ensureBinaryParserAlias (aliasName : Name) : IO Unit :=
discard $ getBinaryAlias parserAliasesRef aliasName
def ensureConstantParserAlias (aliasName : Name) : IO Unit :=
discard $ getConstAlias parserAliasesRef aliasName
unsafe def mkParserOfConstantUnsafe (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser) := do
let env := (← read).env
let opts := (← read).opts
match env.find? constName with
| none => throw ↑s!"unknown constant '{constName}'"
| some info =>
match info.type with
| Expr.const `Lean.Parser.TrailingParser _ =>
let p ← IO.ofExcept $ env.evalConst Parser opts constName
pure ⟨false, p⟩
| Expr.const `Lean.Parser.Parser _ =>
let p ← IO.ofExcept $ env.evalConst Parser opts constName
pure ⟨true, p⟩
| Expr.const `Lean.ParserDescr _ =>
let d ← IO.ofExcept $ env.evalConst ParserDescr opts constName
let p ← compileParserDescr d
pure ⟨true, p⟩
| Expr.const `Lean.TrailingParserDescr _ =>
let d ← IO.ofExcept $ env.evalConst TrailingParserDescr opts constName
let p ← compileParserDescr d
pure ⟨false, p⟩
| _ => throw ↑s!"unexpected parser type at '{constName}' (`ParserDescr`, `TrailingParserDescr`, `Parser` or `TrailingParser` expected)"
@[implementedBy mkParserOfConstantUnsafe]
opaque mkParserOfConstantAux (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser)
partial def compileParserDescr (categories : ParserCategories) (d : ParserDescr) : ImportM Parser :=
let rec visit : ParserDescr → ImportM Parser
| ParserDescr.const n => getConstAlias parserAliasesRef n
| ParserDescr.unary n d => return (← getUnaryAlias parserAliasesRef n) (← visit d)
| ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias parserAliasesRef n) (← visit d₁) (← visit d₂)
| ParserDescr.node k prec d => return leadingNode k prec (← visit d)
| ParserDescr.nodeWithAntiquot n k d => return nodeWithAntiquot n k (← visit d) (anonymous := true)
| ParserDescr.sepBy p sep psep trail => return sepBy (← visit p) sep (← visit psep) trail
| ParserDescr.sepBy1 p sep psep trail => return sepBy1 (← visit p) sep (← visit psep) trail
| ParserDescr.trailingNode k prec lhsPrec d => return trailingNode k prec lhsPrec (← visit d)
| ParserDescr.symbol tk => return symbol tk
| ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol tk includeIdent
| ParserDescr.parser constName => do
let (_, p) ← mkParserOfConstantAux constName visit;
pure p
| ParserDescr.cat catName prec =>
match getCategory categories catName with
| some _ => pure $ categoryParser catName prec
| none => IO.ofExcept $ throwUnknownParserCategory catName
visit d
def mkParserOfConstant (categories : ParserCategories) (constName : Name) : ImportM (Bool × Parser) :=
mkParserOfConstantAux constName (compileParserDescr categories)
structure ParserAttributeHook where
/-- Called after a parser attribute is applied to a declaration. -/
postAdd (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit
builtin_initialize parserAttributeHooks : IO.Ref (List ParserAttributeHook) ← IO.mkRef {}
def registerParserAttributeHook (hook : ParserAttributeHook) : IO Unit := do
parserAttributeHooks.modify fun hooks => hook::hooks
def runParserAttributeHooks (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit := do
let hooks ← parserAttributeHooks.get
hooks.forM fun hook => hook.postAdd catName declName builtin
builtin_initialize
registerBuiltinAttribute {
name := `runBuiltinParserAttributeHooks
descr := "explicitly run hooks normally activated by builtin parser attributes"
add := fun decl stx _ => do
Attribute.Builtin.ensureNoArgs stx
runParserAttributeHooks Name.anonymous decl (builtin := true)
}
builtin_initialize
registerBuiltinAttribute {
name := `runParserAttributeHooks
descr := "explicitly run hooks normally activated by parser attributes"
add := fun decl stx _ => do
Attribute.Builtin.ensureNoArgs stx
runParserAttributeHooks Name.anonymous decl (builtin := false)
}
private def ParserExtension.OLeanEntry.toEntry (s : State) : OLeanEntry → ImportM Entry
| token tk => return Entry.token tk
| kind k => return Entry.kind k
| category c d l => return Entry.category c d l
| parser catName declName prio => do
let (leading, p) ← mkParserOfConstant s.categories declName
return Entry.parser catName declName leading p prio
builtin_initialize parserExtension : ParserExtension ←
registerScopedEnvExtension {
name := `parserExt
mkInitial := ParserExtension.mkInitial
addEntry := ParserExtension.addEntryImpl
toOLeanEntry := ParserExtension.Entry.toOLeanEntry
ofOLeanEntry := ParserExtension.OLeanEntry.toEntry
}
def isParserCategory (env : Environment) (catName : Name) : Bool :=
(parserExtension.getState env).categories.contains catName
def addParserCategory (env : Environment) (catName declName : Name) (behavior : LeadingIdentBehavior) : Except String Environment := do
if isParserCategory env catName then
throwParserCategoryAlreadyDefined catName
else
return parserExtension.addEntry env <| ParserExtension.Entry.category catName declName behavior
def leadingIdentBehavior (env : Environment) (catName : Name) : LeadingIdentBehavior :=
match getCategory (parserExtension.getState env).categories catName with
| none => LeadingIdentBehavior.default
| some cat => cat.behavior
unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => unsafeBaseIO do
let categories := (parserExtension.getState ctx.env).categories
match (← (mkParserOfConstant categories declName { env := ctx.env, opts := ctx.options }).toBaseIO) with
| .ok (_, p) =>
-- We should manually register `p`'s tokens before invoking it as it might not be part of any syntax category (yet)
let ctx := { ctx with tokens := p.info.collectTokens [] |>.foldl (fun tks tk => tks.insert tk tk) ctx.tokens }
return p.fn ctx s
| .error e => return s.mkUnexpectedError e.toString
@[implementedBy evalParserConstUnsafe]
opaque evalParserConst (declName : Name) : ParserFn
register_builtin_option internal.parseQuotWithCurrentStage : Bool := {
defValue := false
group := "internal"
descr := "(Lean bootstrapping) use parsers from the current stage inside quotations"
}
/-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/
def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with
fn := fun c s =>
if c.quotDepth > 0 && !c.suppressInsideQuot && internal.parseQuotWithCurrentStage.get c.options && c.env.contains declName then
evalParserConst declName c s
else
p.fn c s }
def addBuiltinParser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : IO Unit := do
let p := evalInsideQuot declName p
let categories ← builtinParserCategoriesRef.get
let categories ← IO.ofExcept $ addParser categories catName declName leading p prio
builtinParserCategoriesRef.set categories
builtinSyntaxNodeKindSetRef.modify p.info.collectKinds
updateBuiltinTokens p.info declName
def addBuiltinLeadingParser (catName : Name) (declName : Name) (p : Parser) (prio : Nat) : IO Unit :=
addBuiltinParser catName declName true p prio
def addBuiltinTrailingParser (catName : Name) (declName : Name) (p : TrailingParser) (prio : Nat) : IO Unit :=
addBuiltinParser catName declName false p prio
def mkCategoryAntiquotParser (kind : Name) : Parser :=
mkAntiquot kind.toString kind (isPseudoKind := true)
-- helper decl to work around inlining issue https://github.com/leanprover/lean4/commit/3f6de2af06dd9a25f62294129f64bc05a29ea912#r41340377
@[inline] private def mkCategoryAntiquotParserFn (kind : Name) : ParserFn :=
(mkCategoryAntiquotParser kind).fn
def categoryParserFnImpl (catName : Name) : ParserFn := fun ctx s =>
let catName := if catName == `syntax then `stx else catName -- temporary Hack
let categories := (parserExtension.getState ctx.env).categories
match getCategory categories catName with
| some cat =>
prattParser catName cat.tables cat.behavior (mkCategoryAntiquotParserFn catName) ctx s
| none => s.mkUnexpectedError ("unknown parser category '" ++ toString catName ++ "'")
builtin_initialize
categoryParserFnRef.set categoryParserFnImpl
def addToken (tk : Token) (kind : AttributeKind) : AttrM Unit := do
-- Recall that `ParserExtension.addEntry` is pure, and assumes `addTokenConfig` does not fail.
-- So, we must run it here to handle exception.
discard <| ofExcept <| addTokenConfig (parserExtension.getState (← getEnv)).tokens tk
parserExtension.add (ParserExtension.Entry.token tk) kind
def addSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Environment :=
parserExtension.addEntry env <| ParserExtension.Entry.kind k
def isValidSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Bool :=
let kinds := (parserExtension.getState env).kinds
-- accept any constant in stage 1 (i.e. when compiled by stage 0) so that
-- we can add a built-in parser and its elaborator in the same stage
kinds.contains k || (Internal.isStage0 () && env.contains k)
def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind :=
let kinds := (parserExtension.getState env).kinds
kinds.foldl (fun ks k _ => k::ks) []
def getTokenTable (env : Environment) : TokenTable :=
(parserExtension.getState env).tokens
def mkInputContext (input : String) (fileName : String) : InputContext := {
input := input,
fileName := fileName,
fileMap := input.toFileMap
}
def mkParserContext (ictx : InputContext) (pmctx : ParserModuleContext) : ParserContext := {
prec := 0,
toInputContext := ictx,
toParserModuleContext := pmctx,
tokens := getTokenTable pmctx.env
}
def mkParserState (input : String) : ParserState :=
{ cache := initCacheForInput input }
/-- convenience function for testing -/
def runParserCategory (env : Environment) (catName : Name) (input : String) (fileName := "<input>") : Except String Syntax :=
let c := mkParserContext (mkInputContext input fileName) { env := env, options := {} }
let s := mkParserState input
let s := whitespace c s
let s := categoryParserFnImpl catName c s
if s.hasError then
Except.error (s.toErrorMsg c)
else if input.atEnd s.pos then
Except.ok s.stxStack.back
else
Except.error ((s.mkError "end of input").toErrorMsg c)
def declareBuiltinParser (addFnName : Name) (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit :=
let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName, mkRawNatLit prio]
declareBuiltin declName val
def declareLeadingBuiltinParser (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit :=
declareBuiltinParser `Lean.Parser.addBuiltinLeadingParser catName declName prio
def declareTrailingBuiltinParser (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit :=
declareBuiltinParser `Lean.Parser.addBuiltinTrailingParser catName declName prio
def getParserPriority (args : Syntax) : Except String Nat :=
match args.getNumArgs with
| 0 => pure 0
| 1 => match (args.getArg 0).isNatLit? with
| some prio => pure prio
| none => throw "invalid parser attribute, numeral expected"
| _ => throw "invalid parser attribute, no argument or numeral expected"
private def BuiltinParserAttribute.add (attrName : Name) (catName : Name)
(declName : Name) (stx : Syntax) (kind : AttributeKind) : AttrM Unit := do
let prio ← Attribute.Builtin.getPrio stx
unless kind == AttributeKind.global do throwError "invalid attribute '{attrName}', must be global"
let decl ← getConstInfo declName
match decl.type with
| Expr.const `Lean.Parser.TrailingParser _ =>
declareTrailingBuiltinParser catName declName prio
| Expr.const `Lean.Parser.Parser _ =>
declareLeadingBuiltinParser catName declName prio
| _ => throwError "unexpected parser type at '{declName}' (`Parser` or `TrailingParser` expected)"
if let some doc ← findDocString? (← getEnv) declName then
declareBuiltin (declName ++ `docString) (mkAppN (mkConst ``addBuiltinDocString) #[toExpr declName, toExpr doc])
if let some declRanges ← findDeclarationRanges? declName then
declareBuiltin (declName ++ `declRange) (mkAppN (mkConst ``addBuiltinDeclarationRanges) #[toExpr declName, toExpr declRanges])
runParserAttributeHooks catName declName (builtin := true)
/--
The parsing tables for builtin parsers are "stored" in the extracted source code.
-/
def registerBuiltinParserAttribute (attrName declName : Name)
(behavior := LeadingIdentBehavior.default) : IO Unit := do
let .str ``Lean.Parser.Category s := declName
| throw (IO.userError "`declName` should be in Lean.Parser.Category")
let catName := Name.mkSimple s
addBuiltinParserCategory catName declName behavior
registerBuiltinAttribute {
ref := declName
name := attrName
descr := "Builtin parser"
add := fun declName stx kind => liftM $ BuiltinParserAttribute.add attrName catName declName stx kind
applicationTime := AttributeApplicationTime.afterCompilation
}
private def ParserAttribute.add (_attrName : Name) (catName : Name) (declName : Name) (stx : Syntax) (attrKind : AttributeKind) : AttrM Unit := do
let prio ← Attribute.Builtin.getPrio stx
let env ← getEnv
let categories := (parserExtension.getState env).categories
let p ← mkParserOfConstant categories declName
let leading := p.1
let parser := p.2
let tokens := parser.info.collectTokens []
tokens.forM fun token => do
try
addToken token attrKind
catch
| Exception.error _ msg => throwError "invalid parser '{declName}', {msg}"
| ex => throw ex
let kinds := parser.info.collectKinds {}
kinds.forM fun kind _ => modifyEnv fun env => addSyntaxNodeKind env kind
let entry := ParserExtension.Entry.parser catName declName leading parser prio
match addParser categories catName declName leading parser prio with
| Except.error ex => throwError ex
| Except.ok _ => parserExtension.add entry attrKind
runParserAttributeHooks catName declName (builtin := false)
def mkParserAttributeImpl (attrName catName : Name) (ref : Name := by exact decl_name%) : AttributeImpl where
ref := ref
name := attrName
descr := "parser"
add declName stx attrKind := ParserAttribute.add attrName catName declName stx attrKind
applicationTime := AttributeApplicationTime.afterCompilation
/-- A builtin parser attribute that can be extended by users. -/
def registerBuiltinDynamicParserAttribute (attrName catName : Name) (ref : Name := by exact decl_name%) : IO Unit := do
registerBuiltinAttribute (mkParserAttributeImpl attrName catName ref)
builtin_initialize
registerAttributeImplBuilder `parserAttr fun ref args =>
match args with
| [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName ref
| _ => throw "invalid parser attribute implementation builder arguments"
def registerParserCategory (env : Environment) (attrName catName : Name)
(behavior := LeadingIdentBehavior.default) (ref : Name := by exact decl_name%) : IO Environment := do
let env ← IO.ofExcept $ addParserCategory env catName ref behavior
registerAttributeOfBuilder env `parserAttr ref [DataValue.ofName attrName, DataValue.ofName catName]
-- declare `termParser` here since it is used everywhere via antiquotations
builtin_initialize registerBuiltinParserAttribute `builtinTermParser ``Category.term
builtin_initialize registerBuiltinDynamicParserAttribute `termParser `term
-- declare `commandParser` to break cyclic dependency
builtin_initialize registerBuiltinParserAttribute `builtinCommandParser ``Category.command
builtin_initialize registerBuiltinDynamicParserAttribute `commandParser `command
@[inline] def commandParser (rbp : Nat := 0) : Parser :=
categoryParser `command rbp
private def withNamespaces (ids : Array Name) (p : ParserFn) (addOpenSimple : Bool) : ParserFn := fun c s =>
let c := ids.foldl (init := c) fun c id =>
let nss := ResolveName.resolveNamespace c.env c.currNamespace c.openDecls id
let (env, openDecls) := nss.foldl (init := (c.env, c.openDecls)) fun (env, openDecls) ns =>
let openDecls := if addOpenSimple then OpenDecl.simple ns [] :: openDecls else openDecls
let env := parserExtension.activateScoped env ns
(env, openDecls)
{ c with env, openDecls }
let tokens := parserExtension.getState c.env |>.tokens
p { c with tokens } s
def withOpenDeclFnCore (openDeclStx : Syntax) (p : ParserFn) : ParserFn := fun c s =>
if openDeclStx.getKind == `Lean.Parser.Command.openSimple then
withNamespaces (openDeclStx[0].getArgs.map fun stx => stx.getId) (addOpenSimple := true) p c s
else if openDeclStx.getKind == `Lean.Parser.Command.openScoped then
withNamespaces (openDeclStx[1].getArgs.map fun stx => stx.getId) (addOpenSimple := false) p c s
else if openDeclStx.getKind == `Lean.Parser.Command.openOnly then
-- It does not activate scoped attributes, nor affects namespace resolution
p c s
else if openDeclStx.getKind == `Lean.Parser.Command.openHiding then
-- TODO: it does not activate scoped attributes, but it affects namespaces resolution of open decls parsed by `p`.
p c s
else
p c s
/-- If the parsing stack is of the form `#[.., openCommand]`, we process the open command, and execute `p` -/
def withOpenFn (p : ParserFn) : ParserFn := fun c s =>
if s.stxStack.size > 0 then
let stx := s.stxStack.back
if stx.getKind == `Lean.Parser.Command.open then
withOpenDeclFnCore stx[1] p c s
else
p c s
else
p c s
@[inline] def withOpen (p : Parser) : Parser := {
info := p.info
fn := withOpenFn p.fn
}
/-- If the parsing stack is of the form `#[.., openDecl]`, we process the open declaration, and execute `p` -/
def withOpenDeclFn (p : ParserFn) : ParserFn := fun c s =>
if s.stxStack.size > 0 then
let stx := s.stxStack.back
withOpenDeclFnCore stx p c s
else
p c s
@[inline] def withOpenDecl (p : Parser) : Parser := {
info := p.info
fn := withOpenDeclFn p.fn
}
def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) :=
ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id
def parserOfStackFn (offset : Nat) : ParserFn := fun ctx s => Id.run do
let stack := s.stxStack
if stack.size < offset + 1 then
return s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small")
let Syntax.ident (val := parserName) .. := stack.get! (stack.size - offset - 1)
| s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier")
match ctx.resolveName parserName with
| [(parserName, [])] =>
let iniSz := s.stackSize
let mut ctx' := ctx
if !internal.parseQuotWithCurrentStage.get ctx'.options then
-- static quotations such as `(e) do not use the interpreter unless the above option is set,
-- so for consistency neither should dynamic quotations using this function
ctx' := { ctx' with options := ctx'.options.setBool `interpreter.prefer_native true }
let s := evalParserConst parserName ctx' s
if !s.hasError && s.stackSize != iniSz + 1 then
s.mkUnexpectedError "expected parser to return exactly one syntax object"
else
s
| _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}"
| _ => s.mkUnexpectedError s!"unknown parser {parserName}"
def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser :=
{ fn := fun c s => parserOfStackFn offset { c with prec := prec } s }
end Parser
end Lean
|
2f413a500e91f572de45447ac8f3adc07fbc6d83 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/elab3.lean | 88608ec2b52c40439650f70e703aed8e0b1c85cb | [
"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 | 89 | lean | set_option pp.binder_types true
axiom Sorry {A : Sort*} : A
check (Sorry : ∀ a, a > 0)
|
4feec8487b4a0d9fafcf7ad2f7ff811973d0b6ff | 75c54c8946bb4203e0aaf196f918424a17b0de99 | /old/reflect_test.lean | d0e25a7d4b00f48146d2ca47165f86d2f4047bef | [
"Apache-2.0"
] | permissive | urkud/flypitch | 261e2a45f1038130178575406df8aea78255ba77 | 2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c | refs/heads/master | 1,653,266,469,246 | 1,577,819,679,000 | 1,577,819,679,000 | 259,862,235 | 1 | 0 | Apache-2.0 | 1,588,147,244,000 | 1,588,147,244,000 | null | UTF-8 | Lean | false | false | 7,059 | lean | import .fol .abel
universe u
section weekdays
@[derive has_reflect]
inductive weekday : Type
| monday : weekday
| another_day : weekday → weekday
open weekday
meta def dump_weekday (f : weekday) : tactic unit :=
tactic.trace $ to_string (expr.to_raw_fmt (reflect f).to_expr)
-- run_cmd dump_weekday (another_day (another_day monday))
--(app (const weekday.another_day []) (app (const weekday.another_day []) (const weekday.monday [])))
inductive weekday' : Type
| monday : weekday'
| another_day : weekday' → weekday'
open weekday'
meta instance has_reflect_weekday' : has_reflect weekday'
| weekday'.monday := `(monday)
| (weekday'.another_day x) := `(λ l, weekday'.another_day l).subst $
by haveI := has_reflect_weekday'; exact (reflect x)
meta def dump_weekday' (f : weekday') : tactic unit :=
tactic.trace $ to_string (expr.to_raw_fmt (reflect f).to_expr)
-- run_cmd dump_weekday' (another_day (another_day monday))
-- (app (const weekday'.another_day []) (app (const weekday'.another_day []) (const weekday'.monday [])))
end weekdays
-- meta instance has_reflect_preterm {L : Language.{u}} : Π{n : ℕ}, has_reflect (preterm L n)
-- | 0 (var k) := `(@preterm.var L).subst (reflect k)
-- @[derive has_reflect]
open fol abel
section preterm_aux
inductive preterm_aux (L : Language.{u}) : Type u
| var : ℕ → preterm_aux
| func : ∀ k : ℕ, L.functions k → preterm_aux
| app : preterm_aux → preterm_aux → preterm_aux
def to_aux {L : Language.{u}} : ∀ {l : ℕ}, preterm L l → preterm_aux L
| 0 (var n) := preterm_aux.var _ n
| k (func f) := preterm_aux.func _ f
| k (app t₁ t₂) := preterm_aux.app (to_aux t₁) (to_aux t₂)
def L_abel_plus' (t₁ t₂ : preterm L_abel 0) : preterm L_abel 0 :=
@term_of_function L_abel 2 (abel_functions.plus : L_abel.functions 2) t₁ t₂
end preterm_aux
local infix ` +' `:100 := L_abel_plus'
local notation ` zero ` := (func abel_functions.zero : preterm L_abel 0)
section L_abel_term_biopsy
def sample1 : preterm L_abel 0 := (zero +' zero)
def sample2 : preterm L_abel 0 := zero
-- #reduce sample2
open expr
meta def sample2_expr : expr :=
mk_app (const `preterm.func list.nil) ([(const `L_abel list.nil), `(0), const `abel_functions.zero list.nil] : list expr)
end L_abel_term_biopsy
section simpler_biopsy
inductive my_inductive : Type
| a : my_inductive
| b : my_inductive
| f : my_inductive → my_inductive
open my_inductive
def sample3 : my_inductive := f a
open expr
meta def sample3_expr : expr :=
app (const `my_inductive.f list.nil) (const `my_inductive.a list.nil)
def sample3_again : my_inductive := by tactic.exact (sample3_expr)
example : sample3 = sample3_again := rfl
end simpler_biopsy
namespace tactic
namespace interactive
open interactive interactive.types expr
def my_test_term : preterm L_abel 0 := (zero +' zero)
end interactive
end tactic
section test
-- def my_term : preterm L_abel 0 := sorry
-- #check tactic.interactive.rcases
end test
section sample4
/-- Note: this is the same as `dfin` -/
inductive my_indexed_family : ℕ → Type u
| z {} : my_indexed_family 0
| s : ∀ {k}, my_indexed_family k → my_indexed_family (k+1)
-- meta example : ∀ {n}, has_reflect (my_indexed_family n)
-- | 0 z := `(z)
open my_indexed_family
def sample4 : my_indexed_family 1 := s z
-- #check tactic.eval_expr
end sample4
section sample4
inductive dfin'' : ℕ → Type
| fz {n} : dfin'' (n+1)
| fs {n} : dfin'' n → dfin'' (n+1)
inductive dfin' : ℕ → Type u
| gz {n} : dfin' (n+1)
| gs {n} : dfin' n → dfin' (n+1)
open dfin dfin'
meta instance dfin.reflect : ∀ {n}, has_reflect (dfin'' n)
| _ dfin''.fz := `(dfin''.fz)
| _ (dfin''.fs n) := `(dfin''.fs).subst (dfin.reflect n)
-- /- errors all over---why doesn't reflect like universe parameters? -/
-- meta instance dfin'.reflect : ∀ {n}, has_reflect (dfin' n)
-- | _ fz := `(fz)
-- | _ (fs n) := `(fs).subst (dfin'.reflect n)
end sample4
section reflect_preterm
/- Language with a single constant symbol -/
inductive L_pt_functions : ℕ → Type
| pt : L_pt_functions 0
def L_pt : Language.{0} := ⟨L_pt_functions, λ _, empty⟩
def pt_preterm : preterm L_pt 0 := preterm.func L_pt_functions.pt
meta def pt_preterm_reflected : expr :=
expr.mk_app (expr.const `preterm.func [level.zero]) [ (expr.const `L_pt list.nil), `(0), (expr.const `L_pt_functions.pt list.nil)]
set_option trace.app_builder true
-- meta def pt_preterm_reflected' : expr := by tactic.mk_app "preterm.func" [(expr.const `L_pt []), `(0), (expr.const `L_pt_functions.pt [])]
#check tactic.mk_app
meta def pt_preterm_reflected'' : tactic expr :=
tactic.to_expr ```(preterm.func L_pt_functions.pt : preterm L_pt 0)
def pt_preterm' : preterm L_pt 0 := by pt_preterm_reflected'' >>= tactic.exact
-- def pt_preterm' : preterm L_pt 0 := by tactic.exact pt_preterm_reflected
example : pt_preterm = pt_preterm' := rfl
-- infer type failed, incorrect number of universe levels
-- want: example : pt_preterm = pt_preterm' := rfl
end reflect_preterm
namespace hewwo
section reflect_preterm2
def L_pt.pt' : L_pt.functions 0 := L_pt_functions.pt
#reduce (by apply_instance : reflected L_pt.pt')
-- `(L_pt.pt')
meta def pt_preterm_reflected : tactic expr :=
tactic.mk_app ``preterm.func [`(L_pt.pt')]
def pt_preterm' : preterm L_pt 0 := by pt_preterm_reflected >>= tactic.exact
#eval tactic.trace (@expr.to_raw_fmt tt `(L_pt.pt'))
#check reflect
end reflect_preterm2
end hewwo
section reflect_preterm3
inductive L_pt_func_functions : ℕ → Type
| pt : L_pt_func_functions 0
| foo : L_pt_func_functions 1
open L_pt_func_functions
def L_pt_func : Language.{0} :=
⟨L_pt_func_functions, λ _, ulift empty⟩
-- def foo_pt_term : preterm L_pt_func 0 :=
-- preterm.app (preterm.func L_pt_func_functions.foo) (preterm.func L_pt_func_functions.pt)
-- def foo_pt_term_reflected : expr :=
-- begin
-- tactic.mk_app ``preterm.func [(by tactic.mk_app `preterm.func [`(L_pt_func_functions.foo)]), (by tactic.mk_app `preterm.func [`(L_pt_func_functions.pt)])]
-- end
-- def foo' : preterm L_pt_func 1 := preterm.func L_pt_func_functions.foo
-- #reduce (by apply_instance : reflected L_pt_func_functions.foo)
set_option trace.app_builder true
def my_foo : L_pt_func.functions 1 := L_pt_func_functions.foo
def my_pt : L_pt_func.functions 0 := L_pt_func_functions.pt
-- meta def foo_pt_term_reflected : tactic expr := tactic.mk_app ``preterm.func [`()]
meta def foo_pt_term_reflected' : tactic expr :=
do e₁ <- tactic.mk_app ``preterm.func [`(my_foo)],
e₂ <- tactic.mk_app ``preterm.func [`(my_pt)],
tactic.mk_app ``preterm.app [e₁, e₂]
-- #print foo_pt_term_reflected'
-- meta def bar : tactic expr :=
-- tactic.mk_app ``preterm.func [`(foo_mask)]
set_option trace.app_builder true
def foo_pt_term_reflected : preterm L_pt_func 0 := by (foo_pt_term_reflected' >>= tactic.exact)
-- #reduce foo_pt_term_reflected
end reflect_preterm3
|
13eb368db661771ec112edcb7effb4738a5eb4d4 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /hott/types/arrow_2.hlean | 148a431fd8c135a1c4e900a376d4521cd18868fc | [
"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 | 4,091 | hlean | /-
Copyright (c) 2015 Ulrik Buchholtz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ulrik Buchholtz
-/
import ..function
open eq is_equiv function
namespace arrow
structure arrow :=
(dom : Type)
(cod : Type)
(arrow : dom → cod)
abbreviation dom [unfold 2] := @arrow.dom
abbreviation cod [unfold 2] := @arrow.cod
definition arrow_of_fn {A B : Type} (f : A → B) : arrow :=
arrow.mk A B f
structure morphism (A B : Type) :=
(mor : A → B)
definition morphism_of_arrow [coercion] (f : arrow) : morphism (dom f) (cod f) :=
morphism.mk (arrow.arrow f)
attribute morphism.mor [coercion]
structure arrow_hom (f g : arrow) :=
(on_dom : dom f → dom g)
(on_cod : cod f → cod g)
(commute : Π(x : dom f), g (on_dom x) = on_cod (f x))
abbreviation on_dom [unfold 2] := @arrow_hom.on_dom
abbreviation on_cod [unfold 2] := @arrow_hom.on_cod
abbreviation commute [unfold 2] := @arrow_hom.commute
variables {f g : arrow}
definition on_fiber [reducible] (r : arrow_hom f g) (y : cod f)
: fiber f y → fiber g (on_cod r y) :=
fiber.rec (λx p, fiber.mk (on_dom r x) (commute r x ⬝ ap (on_cod r) p))
structure is_retraction [class] (r : arrow_hom f g) : Type :=
(sect : arrow_hom g f)
(right_inverse_dom : Π(a : dom g), on_dom r (on_dom sect a) = a)
(right_inverse_cod : Π(b : cod g), on_cod r (on_cod sect b) = b)
(cohere : Π(a : dom g), commute r (on_dom sect a) ⬝ ap (on_cod r) (commute sect a)
= ap g (right_inverse_dom a) ⬝ (right_inverse_cod (g a))⁻¹)
definition retraction_on_fiber [reducible] (r : arrow_hom f g) [H : is_retraction r]
(b : cod g) : fiber f (on_cod (is_retraction.sect r) b) → fiber g b :=
fiber.rec (λx q, fiber.mk (on_dom r x) (commute r x ⬝ ap (on_cod r) q ⬝ is_retraction.right_inverse_cod r b))
definition retraction_on_fiber_right_inverse' (r : arrow_hom f g) [H : is_retraction r]
(a : dom g) (b : cod g) (p : g a = b)
: retraction_on_fiber r b (on_fiber (is_retraction.sect r) b (fiber.mk a p)) = fiber.mk a p :=
begin
induction p, unfold on_fiber, unfold retraction_on_fiber,
apply @fiber.fiber_eq _ _ g (g a)
(fiber.mk
(on_dom r (on_dom (is_retraction.sect r) a))
(commute r (on_dom (is_retraction.sect r) a)
⬝ ap (on_cod r) (commute (is_retraction.sect r) a)
⬝ is_retraction.right_inverse_cod r (g a)))
(fiber.mk a (refl (g a)))
(is_retraction.right_inverse_dom r a), -- everything but this field should be inferred
unfold fiber.point_eq,
rewrite [is_retraction.cohere r a],
apply inv_con_cancel_right
end
definition retraction_on_fiber_right_inverse (r : arrow_hom f g) [H : is_retraction r]
: Π(b : cod g), Π(z : fiber g b), retraction_on_fiber r b (on_fiber (is_retraction.sect r) b z) = z :=
λb, fiber.rec (λa p, retraction_on_fiber_right_inverse' r a b p)
-- Lemma 4.7.3
definition retraction_on_fiber_is_retraction [instance] (r : arrow_hom f g) [H : is_retraction r]
(b : cod g) : _root_.is_retraction (retraction_on_fiber r b) :=
_root_.is_retraction.mk (on_fiber (is_retraction.sect r) b) (retraction_on_fiber_right_inverse r b)
-- Theorem 4.7.4
definition retract_of_equivalence_is_equivalence (r : arrow_hom f g) [H : is_retraction r]
[K : is_equiv f] : is_equiv g :=
begin
apply @is_equiv_of_is_contr_fun _ _ g,
intro b,
apply is_contr_retract (retraction_on_fiber r b),
exact is_contr_fun_of_is_equiv f (on_cod (is_retraction.sect r) b)
end
end arrow
namespace arrow
variables {A B : Type} {f g : A → B} (p : f ~ g)
definition arrow_hom_of_homotopy : arrow_hom (arrow_of_fn f) (arrow_of_fn g) :=
arrow_hom.mk id id (λx, (p x)⁻¹)
definition is_retraction_arrow_hom_of_homotopy [instance]
: is_retraction (arrow_hom_of_homotopy p) :=
is_retraction.mk
(arrow_hom_of_homotopy (λx, (p x)⁻¹))
(λa, idp)
(λb, idp)
(λa, con_eq_of_eq_inv_con (ap_id _))
end arrow
|
e8c77a81de09061d1e54751c8c79c646645a3614 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/control/applicative.lean | 7afdd96e3367fb831b95b604c43a5e5517862a4c | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,973 | lean | /-
Copyright (c) 2017 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import algebra.group.defs
import control.functor
/-!
# `applicative` instances
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides `applicative` instances for concrete functors:
* `id`
* `functor.comp`
* `functor.const`
* `functor.add_const`
-/
universes u v w
section lemmas
open function
variables {F : Type u → Type v}
variables [applicative F] [is_lawful_applicative F]
variables {α β γ σ : Type u}
lemma applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) :
(f <$> x) <*> (g <$> y) = (flip (∘) g ∘ f) <$> x <*> y :=
by simp [flip] with functor_norm
lemma applicative.pure_seq_eq_map' (f : α → β) : (<*>) (pure f : F (α → β)) = (<$>) f :=
by ext; simp with functor_norm
theorem applicative.ext {F} : ∀ {A1 : applicative F} {A2 : applicative F}
[@is_lawful_applicative F A1] [@is_lawful_applicative F A2]
(H1 : ∀ {α : Type u} (x : α),
@has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x)
(H2 : ∀ {α β : Type u} (f : F (α → β)) (x : F α),
@has_seq.seq _ A1.to_has_seq _ _ f x = @has_seq.seq _ A2.to_has_seq _ _ f x),
A1 = A2
| {to_functor := F1, seq := s1, pure := p1, seq_left := sl1, seq_right := sr1}
{to_functor := F2, seq := s2, pure := p2, seq_left := sl2, seq_right := sr2} L1 L2 H1 H2 :=
begin
obtain rfl : @p1 = @p2, {funext α x, apply H1},
obtain rfl : @s1 = @s2, {funext α β f x, apply H2},
cases L1, cases L2,
obtain rfl : F1 = F2,
{ resetI, apply functor.ext, intros,
exact (L1_pure_seq_eq_map _ _).symm.trans (L2_pure_seq_eq_map _ _) },
congr; funext α β x y,
{ exact (L1_seq_left_eq _ _).trans (L2_seq_left_eq _ _).symm },
{ exact (L1_seq_right_eq _ _).trans (L2_seq_right_eq _ _).symm }
end
end lemmas
instance : is_comm_applicative id :=
by refine { .. }; intros; refl
namespace functor
namespace comp
open function (hiding comp)
open functor
variables {F : Type u → Type w} {G : Type v → Type u}
variables [applicative F] [applicative G]
variables [is_lawful_applicative F] [is_lawful_applicative G]
variables {α β γ : Type v}
lemma map_pure (f : α → β) (x : α) : (f <$> pure x : comp F G β) = pure (f x) :=
comp.ext $ by simp
lemma seq_pure (f : comp F G (α → β)) (x : α) :
f <*> pure x = (λ g : α → β, g x) <$> f :=
comp.ext $ by simp [(∘)] with functor_norm
lemma seq_assoc (x : comp F G α) (f : comp F G (α → β)) (g : comp F G (β → γ)) :
g <*> (f <*> x) = (@function.comp α β γ <$> g) <*> f <*> x :=
comp.ext $ by simp [(∘)] with functor_norm
lemma pure_seq_eq_map (f : α → β) (x : comp F G α) :
pure f <*> x = f <$> x :=
comp.ext $ by simp [applicative.pure_seq_eq_map'] with functor_norm
instance : is_lawful_applicative (comp F G) :=
{ pure_seq_eq_map := @comp.pure_seq_eq_map F G _ _ _ _,
map_pure := @comp.map_pure F G _ _ _ _,
seq_pure := @comp.seq_pure F G _ _ _ _,
seq_assoc := @comp.seq_assoc F G _ _ _ _ }
theorem applicative_id_comp {F} [AF : applicative F] [LF : is_lawful_applicative F] :
@comp.applicative id F _ _ = AF :=
@applicative.ext F _ _ (@comp.is_lawful_applicative id F _ _ _ _) _
(λ α x, rfl) (λ α β f x, rfl)
theorem applicative_comp_id {F} [AF : applicative F] [LF : is_lawful_applicative F] :
@comp.applicative F id _ _ = AF :=
@applicative.ext F _ _ (@comp.is_lawful_applicative F id _ _ _ _) _
(λ α x, rfl) (λ α β f x, show id <$> f <*> x = f <*> x, by rw id_map)
open is_comm_applicative
instance {f : Type u → Type w} {g : Type v → Type u}
[applicative f] [applicative g]
[is_comm_applicative f] [is_comm_applicative g] :
is_comm_applicative (comp f g) :=
by { refine { .. @comp.is_lawful_applicative f g _ _ _ _, .. },
intros, casesm* comp _ _ _, simp! [map,has_seq.seq] with functor_norm,
rw [commutative_map],
simp [comp.mk,flip,(∘)] with functor_norm,
congr, funext, rw [commutative_map], congr }
end comp
end functor
open functor
@[functor_norm]
lemma comp.seq_mk {α β : Type w}
{f : Type u → Type v} {g : Type w → Type u}
[applicative f] [applicative g]
(h : f (g (α → β))) (x : f (g α)) :
comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl
instance {α} [has_one α] [has_mul α] : applicative (const α) :=
{ pure := λ β x, (1 : α),
seq := λ β γ f x, (f * x : α) }
instance {α} [monoid α] : is_lawful_applicative (const α) :=
by refine { .. }; intros; simp [mul_assoc, (<$>), (<*>), pure]
instance {α} [has_zero α] [has_add α] : applicative (add_const α) :=
{ pure := λ β x, (0 : α),
seq := λ β γ f x, (f + x : α) }
instance {α} [add_monoid α] : is_lawful_applicative (add_const α) :=
by refine { .. }; intros; simp [add_assoc, (<$>), (<*>), pure]
|
9e4cc073fe5eb5cbffdbbeb279716d2e53cf2172 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/field_theory/polynomial_galois_group.lean | f837e799837ad44a624fe6162c610b1b4011ba32 | [
"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 | 21,477 | lean | /-
Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Patrick Lutz
-/
import analysis.complex.polynomial
import field_theory.galois
import group_theory.perm.cycle_type
import ring_theory.eisenstein_criterion
/-!
# Galois Groups of Polynomials
In this file, we introduce the Galois group of a polynomial `p` over a field `F`,
defined as the automorphism group of its splitting field. We also provide
some results about some extension `E` above `p.splitting_field`, and some specific
results about the Galois groups of ℚ-polynomials with specific numbers of non-real roots.
## Main definitions
- `polynomial.gal p`: the Galois group of a polynomial p.
- `polynomial.gal.restrict p E`: the restriction homomorphism `(E ≃ₐ[F] E) → gal p`.
- `polynomial.gal.gal_action p E`: the action of `gal p` on the roots of `p` in `E`.
## Main results
- `polynomial.gal.restrict_smul`: `restrict p E` is compatible with `gal_action p E`.
- `polynomial.gal.gal_action_hom_injective`: `gal p` acting on the roots of `p` in `E` is faithful.
- `polynomial.gal.restrict_prod_injective`: `gal (p * q)` embeds as a subgroup of `gal p × gal q`.
- `polynomial.gal.card_of_separable`: For a separable polynomial, its Galois group has cardinality
equal to the dimension of its splitting field over `F`.
- `polynomial.gal.gal_action_hom_bijective_of_prime_degree`:
An irreducible polynomial of prime degree with two non-real roots has full Galois group.
## Other results
- `polynomial.gal.card_complex_roots_eq_card_real_add_card_not_gal_inv`: The number of complex roots
equals the number of real roots plus the number of roots not fixed by complex conjugation
(i.e. with some imaginary component).
-/
noncomputable theory
open_locale classical
open finite_dimensional
namespace polynomial
variables {F : Type*} [field F] (p q : polynomial F) (E : Type*) [field E] [algebra F E]
/-- The Galois group of a polynomial. -/
@[derive [has_coe_to_fun, group, fintype]]
def gal := p.splitting_field ≃ₐ[F] p.splitting_field
namespace gal
@[ext] lemma ext {σ τ : p.gal} (h : ∀ x ∈ p.root_set p.splitting_field, σ x = τ x) : σ = τ :=
begin
refine alg_equiv.ext (λ x, (alg_hom.mem_equalizer σ.to_alg_hom τ.to_alg_hom x).mp
((set_like.ext_iff.mp _ x).mpr algebra.mem_top)),
rwa [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff],
end
/-- If `p` splits in `F` then the `p.gal` is trivial. -/
def unique_gal_of_splits (h : p.splits (ring_hom.id F)) : unique p.gal :=
{ default := 1,
uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp
((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h) x).mp algebra.mem_top),
rw [alg_equiv.commutes, alg_equiv.commutes] }) }
instance [h : fact (p.splits (ring_hom.id F))] : unique p.gal :=
unique_gal_of_splits _ (h.1)
instance unique_gal_zero : unique (0 : polynomial F).gal :=
unique_gal_of_splits _ (splits_zero _)
instance unique_gal_one : unique (1 : polynomial F).gal :=
unique_gal_of_splits _ (splits_one _)
instance unique_gal_C (x : F) : unique (C x).gal :=
unique_gal_of_splits _ (splits_C _ _)
instance unique_gal_X : unique (X : polynomial F).gal :=
unique_gal_of_splits _ (splits_X _)
instance unique_gal_X_sub_C (x : F) : unique (X - C x).gal :=
unique_gal_of_splits _ (splits_X_sub_C _)
instance unique_gal_X_pow (n : ℕ) : unique (X ^ n : polynomial F).gal :=
unique_gal_of_splits _ (splits_X_pow _ _)
instance [h : fact (p.splits (algebra_map F E))] : algebra p.splitting_field E :=
(is_splitting_field.lift p.splitting_field p h.1).to_ring_hom.to_algebra
instance [h : fact (p.splits (algebra_map F E))] : is_scalar_tower F p.splitting_field E :=
is_scalar_tower.of_algebra_map_eq
(λ x, ((is_splitting_field.lift p.splitting_field p h.1).commutes x).symm)
/-- Restrict from a superfield automorphism into a member of `gal p`. -/
def restrict [fact (p.splits (algebra_map F E))] : (E ≃ₐ[F] E) →* p.gal :=
alg_equiv.restrict_normal_hom p.splitting_field
lemma restrict_surjective [fact (p.splits (algebra_map F E))] [normal F E] :
function.surjective (restrict p E) :=
alg_equiv.restrict_normal_hom_surjective E
section roots_action
/-- The function taking `roots p p.splitting_field` to `roots p E`. This is actually a bijection,
see `polynomial.gal.map_roots_bijective`. -/
def map_roots [fact (p.splits (algebra_map F E))] :
root_set p p.splitting_field → root_set p E :=
λ x, ⟨is_scalar_tower.to_alg_hom F p.splitting_field E x, begin
have key := subtype.mem x,
by_cases p = 0,
{ simp only [h, root_set_zero] at key,
exact false.rec _ key },
{ rw [mem_root_set h, aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩
lemma map_roots_bijective [h : fact (p.splits (algebra_map F E))] :
function.bijective (map_roots p E) :=
begin
split,
{ exact λ _ _ h, subtype.ext (ring_hom.injective _ (subtype.ext_iff.mp h)) },
{ intro y,
-- this is just an equality of two different ways to write the roots of `p` as an `E`-polynomial
have key := roots_map
(is_scalar_tower.to_alg_hom F p.splitting_field E : p.splitting_field →+* E)
((splits_id_iff_splits _).mpr (is_splitting_field.splits p.splitting_field p)),
rw [map_map, alg_hom.comp_algebra_map] at key,
have hy := subtype.mem y,
simp only [root_set, finset.mem_coe, multiset.mem_to_finset, key, multiset.mem_map] at hy,
rcases hy with ⟨x, hx1, hx2⟩,
exact ⟨⟨x, multiset.mem_to_finset.mpr hx1⟩, subtype.ext hx2⟩ }
end
/-- The bijection between `root_set p p.splitting_field` and `root_set p E`. -/
def roots_equiv_roots [fact (p.splits (algebra_map F E))] :
(root_set p p.splitting_field) ≃ (root_set p E) :=
equiv.of_bijective (map_roots p E) (map_roots_bijective p E)
instance gal_action_aux : mul_action p.gal (root_set p p.splitting_field) :=
{ smul := λ ϕ x, ⟨ϕ x, begin
have key := subtype.mem x,
--simp only [root_set, finset.mem_coe, multiset.mem_to_finset] at *,
by_cases p = 0,
{ simp only [h, root_set_zero] at key,
exact false.rec _ key },
{ rw mem_root_set h,
change aeval (ϕ.to_alg_hom x) p = 0,
rw [aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩,
one_smul := λ _, by { ext, refl },
mul_smul := λ _ _ _, by { ext, refl } }
/-- The action of `gal p` on the roots of `p` in `E`. -/
instance gal_action [fact (p.splits (algebra_map F E))] : mul_action p.gal (root_set p E) :=
{ smul := λ ϕ x, roots_equiv_roots p E (ϕ • ((roots_equiv_roots p E).symm x)),
one_smul := λ _, by simp only [equiv.apply_symm_apply, one_smul],
mul_smul := λ _ _ _, by simp only [equiv.apply_symm_apply, equiv.symm_apply_apply, mul_smul] }
variables {p E}
/-- `polynomial.gal.restrict p E` is compatible with `polynomial.gal.gal_action p E`. -/
@[simp] lemma restrict_smul [fact (p.splits (algebra_map F E))]
(ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑((restrict p E ϕ) • x) = ϕ x :=
begin
let ψ := alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F p.splitting_field E),
change ↑(ψ (ψ.symm _)) = ϕ x,
rw alg_equiv.apply_symm_apply ψ,
change ϕ (roots_equiv_roots p E ((roots_equiv_roots p E).symm x)) = ϕ x,
rw equiv.apply_symm_apply (roots_equiv_roots p E),
end
variables (p E)
/-- `polynomial.gal.gal_action` as a permutation representation -/
def gal_action_hom [fact (p.splits (algebra_map F E))] : p.gal →* equiv.perm (root_set p E) :=
{ to_fun := λ ϕ, equiv.mk (λ x, ϕ • x) (λ x, ϕ⁻¹ • x)
(λ x, inv_smul_smul ϕ x) (λ x, smul_inv_smul ϕ x),
map_one' := by { ext1 x, exact mul_action.one_smul x },
map_mul' := λ x y, by { ext1 z, exact mul_action.mul_smul x y z } }
lemma gal_action_hom_restrict [fact (p.splits (algebra_map F E))]
(ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑(gal_action_hom p E (restrict p E ϕ) x) = ϕ x :=
restrict_smul ϕ x
/-- `gal p` embeds as a subgroup of permutations of the roots of `p` in `E`. -/
lemma gal_action_hom_injective [fact (p.splits (algebra_map F E))] :
function.injective (gal_action_hom p E) :=
begin
rw monoid_hom.injective_iff,
intros ϕ hϕ,
ext x hx,
have key := equiv.perm.ext_iff.mp hϕ (roots_equiv_roots p E ⟨x, hx⟩),
change roots_equiv_roots p E (ϕ • (roots_equiv_roots p E).symm
(roots_equiv_roots p E ⟨x, hx⟩)) = roots_equiv_roots p E ⟨x, hx⟩ at key,
rw equiv.symm_apply_apply at key,
exact subtype.ext_iff.mp (equiv.injective (roots_equiv_roots p E) key),
end
end roots_action
variables {p q}
/-- `polynomial.gal.restrict`, when both fields are splitting fields of polynomials. -/
def restrict_dvd (hpq : p ∣ q) : q.gal →* p.gal :=
if hq : q = 0 then 1 else @restrict F _ p _ _ _
⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩
lemma restrict_dvd_surjective (hpq : p ∣ q) (hq : q ≠ 0) :
function.surjective (restrict_dvd hpq) :=
by simp only [restrict_dvd, dif_neg hq, restrict_surjective]
variables (p q)
/-- The Galois group of a product maps into the product of the Galois groups. -/
def restrict_prod : (p * q).gal →* p.gal × q.gal :=
monoid_hom.prod (restrict_dvd (dvd_mul_right p q)) (restrict_dvd (dvd_mul_left q p))
/-- `polynomial.gal.restrict_prod` is actually a subgroup embedding. -/
lemma restrict_prod_injective : function.injective (restrict_prod p q) :=
begin
by_cases hpq : (p * q) = 0,
{ haveI : unique (p * q).gal := by { rw hpq, apply_instance },
exact λ f g h, eq.trans (unique.eq_default f) (unique.eq_default g).symm },
intros f g hfg,
dsimp only [restrict_prod, restrict_dvd] at hfg,
simp only [dif_neg hpq, monoid_hom.prod_apply, prod.mk.inj_iff] at hfg,
ext x hx,
rw [root_set, map_mul, polynomial.roots_mul] at hx,
cases multiset.mem_add.mp (multiset.mem_to_finset.mp hx) with h h,
{ haveI : fact (p.splits (algebra_map F (p * q).splitting_field)) :=
⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_right p q)⟩,
have key : x = algebra_map (p.splitting_field) (p * q).splitting_field
((roots_equiv_roots p _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) :=
subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots p _) ⟨x, _⟩).symm,
rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes],
exact congr_arg _ (alg_equiv.ext_iff.mp hfg.1 _) },
{ haveI : fact (q.splits (algebra_map F (p * q).splitting_field)) :=
⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_left q p)⟩,
have key : x = algebra_map (q.splitting_field) (p * q).splitting_field
((roots_equiv_roots q _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) :=
subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots q _) ⟨x, _⟩).symm,
rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes],
exact congr_arg _ (alg_equiv.ext_iff.mp hfg.2 _) },
{ rwa [ne.def, mul_eq_zero, map_eq_zero, map_eq_zero, ←mul_eq_zero] }
end
lemma mul_splits_in_splitting_field_of_mul {p₁ q₁ p₂ q₂ : polynomial F}
(hq₁ : q₁ ≠ 0) (hq₂ : q₂ ≠ 0) (h₁ : p₁.splits (algebra_map F q₁.splitting_field))
(h₂ : p₂.splits (algebra_map F q₂.splitting_field)) :
(p₁ * p₂).splits (algebra_map F (q₁ * q₂).splitting_field) :=
begin
apply splits_mul,
{ rw ← (splitting_field.lift q₁ (splits_of_splits_of_dvd _
(mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_right q₁ q₂))).comp_algebra_map,
exact splits_comp_of_splits _ _ h₁, },
{ rw ← (splitting_field.lift q₂ (splits_of_splits_of_dvd _
(mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_left q₂ q₁))).comp_algebra_map,
exact splits_comp_of_splits _ _ h₂, },
end
/-- `p` splits in the splitting field of `p ∘ q`, for `q` non-constant. -/
lemma splits_in_splitting_field_of_comp (hq : q.nat_degree ≠ 0) :
p.splits (algebra_map F (p.comp q).splitting_field) :=
begin
let P : polynomial F → Prop := λ r, r.splits (algebra_map F (r.comp q).splitting_field),
have key1 : ∀ {r : polynomial F}, irreducible r → P r,
{ intros r hr,
by_cases hr' : nat_degree r = 0,
{ exact splits_of_nat_degree_le_one _ (le_trans (le_of_eq hr') zero_le_one) },
obtain ⟨x, hx⟩ := exists_root_of_splits _ (splitting_field.splits (r.comp q))
(λ h, hr' ((mul_eq_zero.mp (nat_degree_comp.symm.trans
(nat_degree_eq_of_degree_eq_some h))).resolve_right hq)),
rw [←aeval_def, aeval_comp] at hx,
have h_normal : normal F (r.comp q).splitting_field := splitting_field.normal (r.comp q),
have qx_int := normal.is_integral h_normal (aeval x q),
exact splits_of_splits_of_dvd _
(minpoly.ne_zero qx_int)
(normal.splits h_normal _)
(dvd_symm_of_irreducible (minpoly.irreducible qx_int) hr (minpoly.dvd F _ hx)) },
have key2 : ∀ {p₁ p₂ : polynomial F}, P p₁ → P p₂ → P (p₁ * p₂),
{ intros p₁ p₂ hp₁ hp₂,
by_cases h₁ : p₁.comp q = 0,
{ cases comp_eq_zero_iff.mp h₁ with h h,
{ rw [h, zero_mul],
exact splits_zero _ },
{ exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } },
by_cases h₂ : p₂.comp q = 0,
{ cases comp_eq_zero_iff.mp h₂ with h h,
{ rw [h, mul_zero],
exact splits_zero _ },
{ exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } },
have key := mul_splits_in_splitting_field_of_mul h₁ h₂ hp₁ hp₂,
rwa ← mul_comp at key },
exact wf_dvd_monoid.induction_on_irreducible p (splits_zero _)
(λ _, splits_of_is_unit _) (λ _ _ _ h, key2 (key1 h)),
end
/-- `polynomial.gal.restrict` for the composition of polynomials. -/
def restrict_comp (hq : q.nat_degree ≠ 0) : (p.comp q).gal →* p.gal :=
@restrict F _ p _ _ _ ⟨splits_in_splitting_field_of_comp p q hq⟩
lemma restrict_comp_surjective (hq : q.nat_degree ≠ 0) :
function.surjective (restrict_comp p q hq) :=
by simp only [restrict_comp, restrict_surjective]
variables {p q}
/-- For a separable polynomial, its Galois group has cardinality
equal to the dimension of its splitting field over `F`. -/
lemma card_of_separable (hp : p.separable) :
fintype.card p.gal = finrank F p.splitting_field :=
begin
haveI : is_galois F p.splitting_field := is_galois.of_separable_splitting_field hp,
exact is_galois.card_aut_eq_finrank F p.splitting_field,
end
lemma prime_degree_dvd_card [char_zero F] (p_irr : irreducible p) (p_deg : p.nat_degree.prime) :
p.nat_degree ∣ fintype.card p.gal :=
begin
rw gal.card_of_separable p_irr.separable,
have hp : p.degree ≠ 0 :=
λ h, nat.prime.ne_zero p_deg (nat_degree_eq_zero_iff_degree_le_zero.mpr (le_of_eq h)),
let α : p.splitting_field := root_of_splits (algebra_map F p.splitting_field)
(splitting_field.splits p) hp,
have hα : is_integral F α :=
(is_algebraic_iff_is_integral F).mp (algebra.is_algebraic_of_finite α),
use finite_dimensional.finrank F⟮α⟯ p.splitting_field,
suffices : (minpoly F α).nat_degree = p.nat_degree,
{ rw [←finite_dimensional.finrank_mul_finrank F F⟮α⟯ p.splitting_field,
intermediate_field.adjoin.finrank hα, this] },
suffices : minpoly F α ∣ p,
{ have key := dvd_symm_of_irreducible (minpoly.irreducible hα) p_irr this,
apply le_antisymm,
{ exact nat_degree_le_of_dvd this p_irr.ne_zero },
{ exact nat_degree_le_of_dvd key (minpoly.ne_zero hα) } },
apply minpoly.dvd F α,
rw [aeval_def, map_root_of_splits _ (splitting_field.splits p) hp],
end
section rationals
lemma splits_ℚ_ℂ {p : polynomial ℚ} : fact (p.splits (algebra_map ℚ ℂ)) :=
⟨is_alg_closed.splits_codomain p⟩
local attribute [instance] splits_ℚ_ℂ
/-- The number of complex roots equals the number of real roots plus
the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/
lemma card_complex_roots_eq_card_real_add_card_not_gal_inv (p : polynomial ℚ) :
(p.root_set ℂ).to_finset.card = (p.root_set ℝ).to_finset.card +
(gal_action_hom p ℂ (restrict p ℂ (complex.conj_alg_equiv.restrict_scalars ℚ))).support.card :=
begin
by_cases hp : p = 0,
{ simp_rw [hp, root_set_zero, set.to_finset_eq_empty_iff.mpr rfl, finset.card_empty, zero_add],
refine eq.symm (nat.le_zero_iff.mp ((finset.card_le_univ _).trans (le_of_eq _))),
simp_rw [hp, root_set_zero, fintype.card_eq_zero_iff],
apply_instance },
have inj : function.injective (is_scalar_tower.to_alg_hom ℚ ℝ ℂ) := (algebra_map ℝ ℂ).injective,
rw [←finset.card_image_of_injective _ subtype.coe_injective,
←finset.card_image_of_injective _ inj],
let a : finset ℂ := _,
let b : finset ℂ := _,
let c : finset ℂ := _,
change a.card = b.card + c.card,
have ha : ∀ z : ℂ, z ∈ a ↔ aeval z p = 0 :=
λ z, by rw [set.mem_to_finset, mem_root_set hp],
have hb : ∀ z : ℂ, z ∈ b ↔ aeval z p = 0 ∧ z.im = 0,
{ intro z,
simp_rw [finset.mem_image, exists_prop, set.mem_to_finset, mem_root_set hp],
split,
{ rintros ⟨w, hw, rfl⟩,
exact ⟨by rw [aeval_alg_hom_apply, hw, alg_hom.map_zero], rfl⟩ },
{ rintros ⟨hz1, hz2⟩,
have key : is_scalar_tower.to_alg_hom ℚ ℝ ℂ z.re = z := by { ext, refl, rw hz2, refl },
exact ⟨z.re, inj (by rwa [←aeval_alg_hom_apply, key, alg_hom.map_zero]), key⟩ } },
have hc0 : ∀ w : p.root_set ℂ, gal_action_hom p ℂ
(restrict p ℂ (complex.conj_alg_equiv.restrict_scalars ℚ)) w = w ↔ w.val.im = 0,
{ intro w,
rw [subtype.ext_iff, gal_action_hom_restrict],
exact complex.eq_conj_iff_im },
have hc : ∀ z : ℂ, z ∈ c ↔ aeval z p = 0 ∧ z.im ≠ 0,
{ intro z,
simp_rw [finset.mem_image, exists_prop],
split,
{ rintros ⟨w, hw, rfl⟩,
exact ⟨(mem_root_set hp).mp w.2, mt (hc0 w).mpr (equiv.perm.mem_support.mp hw)⟩ },
{ rintros ⟨hz1, hz2⟩,
exact ⟨⟨z, (mem_root_set hp).mpr hz1⟩,
equiv.perm.mem_support.mpr (mt (hc0 _).mp hz2), rfl⟩ } },
rw ← finset.card_disjoint_union,
{ apply congr_arg finset.card,
simp_rw [finset.ext_iff, finset.mem_union, ha, hb, hc],
tauto },
{ intro z,
rw [finset.inf_eq_inter, finset.mem_inter, hb, hc],
tauto },
{ apply_instance },
end
/-- An irreducible polynomial of prime degree with two non-real roots has full Galois group. -/
lemma gal_action_hom_bijective_of_prime_degree
{p : polynomial ℚ} (p_irr : irreducible p) (p_deg : p.nat_degree.prime)
(p_roots : fintype.card (p.root_set ℂ) = fintype.card (p.root_set ℝ) + 2) :
function.bijective (gal_action_hom p ℂ) :=
begin
have h1 : fintype.card (p.root_set ℂ) = p.nat_degree,
{ simp_rw [root_set_def, fintype.card_coe],
rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots],
{ exact is_alg_closed.splits_codomain p },
{ exact nodup_roots ((separable_map (algebra_map ℚ ℂ)).mpr p_irr.separable) } },
have h2 : fintype.card p.gal = fintype.card (gal_action_hom p ℂ).range :=
fintype.card_congr (monoid_hom.of_injective (gal_action_hom_injective p ℂ)).to_equiv,
let conj := restrict p ℂ (complex.conj_alg_equiv.restrict_scalars ℚ),
refine ⟨gal_action_hom_injective p ℂ, λ x, (congr_arg (has_mem.mem x)
(show (gal_action_hom p ℂ).range = ⊤, from _)).mpr (subgroup.mem_top x)⟩,
apply equiv.perm.subgroup_eq_top_of_swap_mem,
{ rwa h1 },
{ rw [h1, ←h2],
exact prime_degree_dvd_card p_irr p_deg },
{ exact ⟨conj, rfl⟩ },
{ rw ← equiv.perm.card_support_eq_two,
apply nat.add_left_cancel,
rw [←p_roots, ←set.to_finset_card (root_set p ℝ), ←set.to_finset_card (root_set p ℂ)],
exact (card_complex_roots_eq_card_real_add_card_not_gal_inv p).symm },
end
/-- An irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group. -/
lemma gal_action_hom_bijective_of_prime_degree'
{p : polynomial ℚ} (p_irr : irreducible p) (p_deg : p.nat_degree.prime)
(p_roots1 : fintype.card (p.root_set ℝ) + 1 ≤ fintype.card (p.root_set ℂ))
(p_roots2 : fintype.card (p.root_set ℂ) ≤ fintype.card (p.root_set ℝ) + 3) :
function.bijective (gal_action_hom p ℂ) :=
begin
apply gal_action_hom_bijective_of_prime_degree p_irr p_deg,
let n := (gal_action_hom p ℂ (restrict p ℂ
(complex.conj_alg_equiv.restrict_scalars ℚ))).support.card,
have hn : 2 ∣ n :=
equiv.perm.two_dvd_card_support (by rw [←monoid_hom.map_pow, ←monoid_hom.map_pow,
show alg_equiv.restrict_scalars ℚ complex.conj_alg_equiv ^ 2 = 1,
from alg_equiv.ext complex.conj_conj, monoid_hom.map_one, monoid_hom.map_one]),
have key := card_complex_roots_eq_card_real_add_card_not_gal_inv p,
simp_rw [set.to_finset_card] at key,
rw [key, add_le_add_iff_left] at p_roots1 p_roots2,
rw [key, add_right_inj],
suffices : ∀ m : ℕ, 2 ∣ m → 1 ≤ m → m ≤ 3 → m = 2,
{ exact this n hn p_roots1 p_roots2 },
rintros m ⟨k, rfl⟩ h2 h3,
exact le_antisymm (nat.lt_succ_iff.mp (lt_of_le_of_ne h3 (show 2 * k ≠ 2 * 1 + 1,
from nat.two_mul_ne_two_mul_add_one))) (nat.succ_le_iff.mpr (lt_of_le_of_ne h2
(show 2 * 0 + 1 ≠ 2 * k, from nat.two_mul_ne_two_mul_add_one.symm))),
end
end rationals
end gal
end polynomial
|
86a62c5e6d56f36f7c441a9c83b512fb511ecc7b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/list/nodup.lean | 3b323391f18c2c5de74507c25924acf6d481c198 | [
"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 | 14,530 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau
-/
import data.list.lattice
import data.list.pairwise
import data.list.forall2
import data.set.pairwise.basic
/-!
# Lists with no duplicates
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
`list.nodup` is defined in `data/list/defs`. In this file we prove various properties of this
predicate.
-/
universes u v
open nat function
variables {α : Type u} {β : Type v} {l l₁ l₂ : list α} {r : α → α → Prop} {a b : α}
namespace list
@[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_nil : @nodup α [] := pairwise.nil
@[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l :=
by simp only [nodup, pairwise_cons, forall_mem_ne]
protected lemma pairwise.nodup {l : list α} {r : α → α → Prop} [is_irrefl α r] (h : pairwise r l) :
nodup l :=
h.imp $ λ a b, ne_of_irrefl
lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup
| _ _ forall₂.nil := by simp only [nodup_nil]
| _ _ (forall₂.cons hab h) :=
by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h))
(rel_nodup h)
protected lemma nodup.cons (ha : a ∉ l) (hl : nodup l) : nodup (a :: l) := nodup_cons.2 ⟨ha, hl⟩
lemma nodup_singleton (a : α) : nodup [a] := pairwise_singleton _ _
lemma nodup.of_cons (h : nodup (a :: l)) : nodup l := (nodup_cons.1 h).2
lemma nodup.not_mem (h : (a :: l).nodup) : a ∉ l := (nodup_cons.1 h).1
lemma not_nodup_cons_of_mem : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 nodup.not_mem
protected lemma nodup.sublist : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise.sublist
theorem not_nodup_pair (a : α) : ¬ nodup [a, a] :=
not_nodup_cons_of_mem $ mem_singleton_self _
theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l :=
⟨λ d a h, not_nodup_pair a (d.sublist h), begin
induction l with a l IH; intro h, {exact nodup_nil},
exact (IH $ λ a s, h a $ sublist_cons_of_sublist _ s).cons
(λ al, h a $ (singleton_sublist.2 al).cons_cons _)
end⟩
theorem nodup_iff_nth_le_inj {l : list α} :
nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j :=
pairwise_iff_nth_le.trans
⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _)
.resolve_left (λ h', H _ _ h₂ h' h))
.resolve_right (λ h', H _ _ h₁ h' h.symm),
λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩
theorem nodup.nth_le_inj_iff {l : list α} (h : nodup l)
{i j : ℕ} (hi : i < l.length) (hj : j < l.length) :
l.nth_le i hi = l.nth_le j hj ↔ i = j :=
⟨nodup_iff_nth_le_inj.mp h _ _ _ _, by simp {contextual := tt}⟩
lemma nodup_iff_nth_ne_nth {l : list α} :
l.nodup ↔ ∀ (i j : ℕ), i < j → j < l.length → l.nth i ≠ l.nth j :=
begin
rw nodup_iff_nth_le_inj,
simp only [nth_le_eq_iff, some_nth_le_eq],
split; rintro h i j h₁ h₂,
{ exact mt (h i j (h₁.trans h₂) h₂) (ne_of_lt h₁) },
{ intro h₃,
by_contra h₄,
cases lt_or_gt_of_ne h₄ with h₅ h₅,
{ exact h i j h₅ h₂ h₃ },
{ exact h j i h₅ h₁ h₃.symm }},
end
lemma nodup.ne_singleton_iff {l : list α} (h : nodup l) (x : α) :
l ≠ [x] ↔ l = [] ∨ ∃ y ∈ l, y ≠ x :=
begin
induction l with hd tl hl,
{ simp },
{ specialize hl h.of_cons,
by_cases hx : tl = [x],
{ simpa [hx, and.comm, and_or_distrib_left] using h },
{ rw [←ne.def, hl] at hx,
rcases hx with rfl | ⟨y, hy, hx⟩,
{ simp },
{ have : tl ≠ [] := ne_nil_of_mem hy,
suffices : ∃ (y : α) (H : y ∈ hd :: tl), y ≠ x,
{ simpa [ne_nil_of_mem hy] },
exact ⟨y, mem_cons_of_mem _ hy, hx⟩ } } }
end
lemma nth_le_eq_of_ne_imp_not_nodup (xs : list α) (n m : ℕ) (hn : n < xs.length)
(hm : m < xs.length) (h : xs.nth_le n hn = xs.nth_le m hm) (hne : n ≠ m) :
¬ nodup xs :=
begin
rw nodup_iff_nth_le_inj,
simp only [exists_prop, exists_and_distrib_right, not_forall],
exact ⟨n, m, ⟨hn, hm, h⟩, hne⟩
end
@[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) :
index_of (nth_le l n h) l = n :=
nodup_iff_nth_le_inj.1 H _ _ _ h $
index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _
theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans $ forall_congr $ λ a,
have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_replicate_sublist _ _ a l 2).symm,
(not_congr this).trans not_lt
theorem nodup_replicate (a : α) : ∀ {n : ℕ}, nodup (replicate n a) ↔ n ≤ 1
| 0 := by simp [nat.zero_le]
| 1 := by simp
| (n+2) := iff_of_false
(λ H, nodup_iff_sublist.1 H a ((replicate_sublist_replicate _).2 (nat.le_add_left 2 n)))
(not_le_of_lt $ nat.le_add_left 2 n)
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α}
(d : nodup l) (h : a ∈ l) : count a l = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
lemma count_eq_of_nodup [decidable_eq α] {a : α} {l : list α}
(d : nodup l) : count a l = if a ∈ l then 1 else 0 :=
begin
split_ifs with h,
{ exact count_eq_one_of_mem d h },
{ exact count_eq_zero_of_not_mem h },
end
lemma nodup.of_append_left : nodup (l₁ ++ l₂) → nodup l₁ :=
nodup.sublist (sublist_append_left l₁ l₂)
lemma nodup.of_append_right : nodup (l₁ ++ l₂) → nodup l₂ :=
nodup.sublist (sublist_append_right l₁ l₂)
theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ :=
by simp only [nodup, pairwise_append, disjoint_iff_ne]
theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
lemma nodup.append (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁ ++ l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
theorem nodup_append_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) :=
by simp only [nodup_append, and.left_comm, disjoint_comm]
theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) :=
by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append,
disjoint_cons_right]
lemma nodup.of_map (f : α → β) {l : list α} : nodup (map f l) → nodup l :=
pairwise.of_map f $ λ a b, mt $ congr_arg f
lemma nodup.map_on {f : α → β} (H : ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y) (d : nodup l) :
(map f l).nodup :=
pairwise.map _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d)
theorem inj_on_of_nodup_map {f : α → β} {l : list α} (d : nodup (map f l)) :
∀ ⦃x⦄, x ∈ l → ∀ ⦃y⦄, y ∈ l → f x = f y → x = y :=
begin
induction l with hd tl ih,
{ simp },
{ simp only [map, nodup_cons, mem_map, not_exists, not_and, ←ne.def] at d,
rintro _ (rfl | h₁) _ (rfl | h₂) h₃,
{ refl },
{ apply (d.1 _ h₂ h₃.symm).elim },
{ apply (d.1 _ h₁ h₃).elim },
{ apply ih d.2 h₁ h₂ h₃ } }
end
theorem nodup_map_iff_inj_on {f : α → β} {l : list α} (d : nodup l) :
nodup (map f l) ↔ (∀ (x ∈ l) (y ∈ l), f x = f y → x = y) :=
⟨inj_on_of_nodup_map, λ h, d.map_on h⟩
protected lemma nodup.map {f : α → β} (hf : injective f) : nodup l → nodup (map f l) :=
nodup.map_on (assume x _ y _ h, hf h)
theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l :=
⟨nodup.of_map _, nodup.map hf⟩
@[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l :=
⟨λ h, attach_map_val l ▸ h.map (λ a b, subtype.eq),
λ h, nodup.of_map subtype.val ((attach_map_val l).symm ▸ h)⟩
alias nodup_attach ↔ nodup.of_attach nodup.attach
attribute [protected] nodup.attach
lemma nodup.pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) :=
by rw [pmap_eq_map_attach]; exact h.attach.map
(λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h)
lemma nodup.filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) :=
pairwise.filter p
@[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l :=
pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm]
lemma nodup.erase_eq_filter [decidable_eq α] {l} (d : nodup l) (a : α) :
l.erase a = filter (≠ a) l :=
begin
induction d with b l m d IH, {refl},
by_cases b = a,
{ subst h, rw [erase_cons_head, filter_cons_of_neg],
symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl },
{ rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h }
end
lemma nodup.erase [decidable_eq α] (a : α) : nodup l → nodup (l.erase a) :=
nodup.sublist $ erase_sublist _ _
lemma nodup.diff [decidable_eq α] : l₁.nodup → (l₁.diff l₂).nodup :=
nodup.sublist $ diff_sublist _ _
lemma nodup.mem_erase_iff [decidable_eq α] (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw [d.erase_eq_filter, mem_filter, and_comm]
lemma nodup.not_mem_erase [decidable_eq α] (h : nodup l) : a ∉ l.erase a :=
λ H, (h.mem_erase_iff.1 H).1 rfl
theorem nodup_join {L : list (list α)} :
nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L :=
by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne]
theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔
(∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ :=
by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map,
exists_imp_distrib, and_imp];
rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔
(∀ (x : α), x ∈ l₁ → nodup (f x)),
from forall_swap.trans $ forall_congr $ λ_, forall_eq']
protected lemma nodup.product {l₂ : list β} (d₁ : l₁.nodup) (d₂ : l₂.nodup) :
(l₁.product l₂).nodup :=
nodup_bind.2
⟨λ a ma, d₂.map $ left_inverse.injective $ λ b, (rfl : (a,b).2 = b),
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
lemma nodup.sigma {σ : α → Type*} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) :
(l₁.sigma l₂).nodup :=
nodup_bind.2
⟨λ a ma, (d₂ a).map (λ b b' h, by injection h with _ h; exact eq_of_heq h),
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
protected lemma nodup.filter_map {f : α → option β} (h : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') :
nodup l → nodup (filter_map f l) :=
pairwise.filter_map f $ λ a a' n b bm b' bm' e, n $ h a a' b' (e ▸ bm) bm'
protected lemma nodup.concat (h : a ∉ l) (h' : l.nodup) : (l.concat a).nodup :=
by rw concat_eq_append; exact h'.append (nodup_singleton _) (disjoint_singleton.2 h)
lemma nodup.insert [decidable_eq α] (h : l.nodup) : (insert a l).nodup :=
if h' : a ∈ l then by rw [insert_of_mem h']; exact h
else by rw [insert_of_not_mem h', nodup_cons]; split; assumption
lemma nodup.union [decidable_eq α] (l₁ : list α) (h : nodup l₂) : (l₁ ∪ l₂).nodup :=
begin
induction l₁ with a l₁ ih generalizing l₂,
{ exact h },
{ exact (ih h).insert }
end
lemma nodup.inter [decidable_eq α] (l₂ : list α) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup.filter _
lemma nodup.diff_eq_filter [decidable_eq α] :
∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂)
| l₁ [] hl₁ := by simp
| l₁ (a::l₂) hl₁ :=
begin
rw [diff_cons, (hl₁.erase _).diff_eq_filter, hl₁.erase_eq_filter, filter_filter],
simp only [mem_cons_iff, not_or_distrib, and.comm]
end
lemma nodup.mem_diff_iff [decidable_eq α] (hl₁ : l₁.nodup) : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ :=
by rw [hl₁.diff_eq_filter, mem_filter]
protected lemma nodup.update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l),
(l.update_nth n a).nodup
| [] n a hl ha := nodup_nil
| (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩
| (b::l) (n+1) a hl ha := nodup_cons.2
⟨λ h, (mem_or_eq_of_mem_update_nth h).elim
(nodup_cons.1 hl).1
(λ hba, ha (hba ▸ mem_cons_self _ _)), hl.of_cons.update_nth (mt (mem_cons_of_mem _) ha)⟩
lemma nodup.map_update [decidable_eq α] {l : list α} (hl : l.nodup) (f : α → β) (x : α) (y : β) :
l.map (function.update f x y) =
if x ∈ l then (l.map f).update_nth (l.index_of x) y else l.map f :=
begin
induction l with hd tl ihl, { simp },
rw [nodup_cons] at hl,
simp only [mem_cons_iff, map, ihl hl.2],
by_cases H : hd = x,
{ subst hd,
simp [update_nth, hl.1] },
{ simp [ne.symm H, H, update_nth, ← apply_ite (cons (f hd))] }
end
lemma nodup.pairwise_of_forall_ne {l : list α} {r : α → α → Prop}
(hl : l.nodup) (h : ∀ (a ∈ l) (b ∈ l), a ≠ b → r a b) : l.pairwise r :=
begin
classical,
refine pairwise_of_reflexive_on_dupl_of_forall_ne _ h,
intros x hx,
rw nodup_iff_count_le_one at hl,
exact absurd (hl x) hx.not_le
end
lemma nodup.pairwise_of_set_pairwise {l : list α} {r : α → α → Prop}
(hl : l.nodup) (h : {x | x ∈ l}.pairwise r) : l.pairwise r :=
hl.pairwise_of_forall_ne h
@[simp] lemma nodup.pairwise_coe [is_symm α r] (hl : l.nodup) :
{a | a ∈ l}.pairwise r ↔ l.pairwise r :=
begin
induction l with a l ih,
{ simp },
rw list.nodup_cons at hl,
have : ∀ b ∈ l, ¬a = b → r a b ↔ r a b :=
λ b hb, imp_iff_right (ne_of_mem_of_not_mem hb hl.1).symm,
simp [set.set_of_or, set.pairwise_insert_of_symmetric (@symm_of _ r _), ih hl.2, and_comm,
forall₂_congr this],
end
end list
theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup
| none := list.nodup_nil
| (some x) := list.nodup_singleton x
|
ad2978b2859540b877224eb9efba453050877953 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/set/equitable.lean | 4d3d766714651482872558ba6f4062ae80b8bf0e | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,185 | lean | /-
Copyright (c) 2021 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 algebra.big_operators.order
import data.nat.basic
/-!
# Equitable functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines equitable functions.
A function `f` is equitable on a set `s` if `f a₁ ≤ f a₂ + 1` for all `a₁, a₂ ∈ s`. This is mostly
useful when the codomain of `f` is `ℕ` or `ℤ` (or more generally a successor order).
## TODO
`ℕ` can be replaced by any `succ_order` + `conditionally_complete_monoid`, but we don't have the
latter yet.
-/
open_locale big_operators
variables {α β : Type*}
namespace set
/-- A set is equitable if no element value is more than one bigger than another. -/
def equitable_on [has_le β] [has_add β] [has_one β] (s : set α) (f : α → β) : Prop :=
∀ ⦃a₁ a₂⦄, a₁ ∈ s → a₂ ∈ s → f a₁ ≤ f a₂ + 1
@[simp]
lemma equitable_on_empty [has_le β] [has_add β] [has_one β] (f : α → β) : equitable_on ∅ f :=
λ a _ ha, (set.not_mem_empty _ ha).elim
lemma equitable_on_iff_exists_le_le_add_one {s : set α} {f : α → ℕ} :
s.equitable_on f ↔ ∃ b, ∀ a ∈ s, b ≤ f a ∧ f a ≤ b + 1 :=
begin
refine ⟨_, λ ⟨b, hb⟩ x y hx hy, (hb x hx).2.trans (add_le_add_right (hb y hy).1 _)⟩,
obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty,
{ simp },
intros hs,
by_cases h : ∀ y ∈ s, f x ≤ f y,
{ exact ⟨f x, λ y hy, ⟨h _ hy, hs hy hx⟩⟩ },
push_neg at h,
obtain ⟨w, hw, hwx⟩ := h,
refine ⟨f w, λ y hy, ⟨nat.le_of_succ_le_succ _, hs hy hw⟩⟩,
rw (nat.succ_le_of_lt hwx).antisymm (hs hx hw),
exact hs hx hy,
end
lemma equitable_on_iff_exists_image_subset_Icc {s : set α} {f : α → ℕ} :
s.equitable_on f ↔ ∃ b, f '' s ⊆ Icc b (b + 1) :=
by simpa only [image_subset_iff] using equitable_on_iff_exists_le_le_add_one
lemma equitable_on_iff_exists_eq_eq_add_one {s : set α} {f : α → ℕ} :
s.equitable_on f ↔ ∃ b, ∀ a ∈ s, f a = b ∨ f a = b + 1 :=
by simp_rw [equitable_on_iff_exists_le_le_add_one, nat.le_and_le_add_one_iff]
section ordered_semiring
variables [ordered_semiring β]
lemma subsingleton.equitable_on {s : set α} (hs : s.subsingleton) (f : α → β) : s.equitable_on f :=
λ i j hi hj, by { rw hs hi hj, exact le_add_of_nonneg_right zero_le_one }
lemma equitable_on_singleton (a : α) (f : α → β) : set.equitable_on {a} f :=
set.subsingleton_singleton.equitable_on f
end ordered_semiring
end set
open set
namespace finset
variables {s : finset α} {f : α → ℕ} {a : α}
lemma equitable_on_iff_le_le_add_one :
equitable_on (s : set α) f ↔
∀ a ∈ s, (∑ i in s, f i) / s.card ≤ f a ∧ f a ≤ (∑ i in s, f i) / s.card + 1 :=
begin
rw set.equitable_on_iff_exists_le_le_add_one,
refine ⟨_, λ h, ⟨_, h⟩ ⟩,
rintro ⟨b, hb⟩,
by_cases h : ∀ a ∈ s, f a = b + 1,
{ intros a ha,
rw [h _ ha, sum_const_nat h, nat.mul_div_cancel_left _ (card_pos.2 ⟨a, ha⟩)],
exact ⟨le_rfl, nat.le_succ _⟩ },
push_neg at h,
obtain ⟨x, hx₁, hx₂⟩ := h,
suffices h : b = (∑ i in s, f i) / s.card,
{ simp_rw ←h,
apply hb },
symmetry,
refine nat.div_eq_of_lt_le (le_trans (by simp [mul_comm]) (sum_le_sum (λ a ha, (hb a ha).1)))
((sum_lt_sum (λ a ha, (hb a ha).2) ⟨_, hx₁, (hb _ hx₁).2.lt_of_ne hx₂⟩).trans_le _),
rw [mul_comm, sum_const_nat],
exact λ _ _, rfl,
end
lemma equitable_on.le (h : equitable_on (s : set α) f) (ha : a ∈ s) :
(∑ i in s, f i) / s.card ≤ f a :=
(equitable_on_iff_le_le_add_one.1 h a ha).1
lemma equitable_on.le_add_one (h : equitable_on (s : set α) f) (ha : a ∈ s) :
f a ≤ (∑ i in s, f i) / s.card + 1 :=
(equitable_on_iff_le_le_add_one.1 h a ha).2
lemma equitable_on_iff :
equitable_on (s : set α) f ↔
∀ a ∈ s, f a = (∑ i in s, f i) / s.card ∨ f a = (∑ i in s, f i) / s.card + 1 :=
by simp_rw [equitable_on_iff_le_le_add_one, nat.le_and_le_add_one_iff]
end finset
|
808e147cee739521a020809d0adb6b067aa65862 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Default.lean | 40d6ec9df0a20b9a33c43329dff5d20b4794e0a9 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 361 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Core
import Init.Control
import Init.Data.Basic
import Init.WF
import Init.Data
import Init.System
import Init.Util
import Init.Fix
import Init.LeanInit
import Init.ShareCommon
|
ba8c58c2f67874f55d00e6101eb5877ed8238d1d | d436468d80b739ba7e06843c4d0d2070e43448e5 | /src/data/zmod/basic.lean | e0eda6c5637d577e0a795a87075bf8fb8c3eb44f | [
"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 | 21,017 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Chris Hughes
# zmod and zmodp
Definition of the integers mod n, and the field structure on the integers mod p.
There are two types defined, `zmod n`, which is for integers modulo a positive nat `n : ℕ+`.
`zmodp` is the type of integers modulo a prime number, for which a field structure is defined.
## Definitions
`val` is inherited from `fin` and returns the least natural number in the equivalence class
`val_min_abs` returns the integer closest to zero in the equivalence class.
A coercion `cast` is defined from `zmod n` into any semiring. This is a semiring hom if the ring has
characteristic dividing `n`
## Implentation notes
`zmod` and `zmodp` are implemented as different types so that the field instance for `zmodp` can be
synthesized. This leads to a lot of code duplication and most of the functions and theorems for
`zmod` are restated for `zmodp`
-/
import data.int.modeq data.int.gcd data.fintype data.pnat.basic tactic.ring
open nat nat.modeq int
def zmod (n : ℕ+) := fin n
namespace zmod
instance (n : ℕ+) : has_neg (zmod n) :=
⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n,
have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 n.pos,
have h₁ : ((n : ℕ) : ℤ) = abs n := (abs_of_nonneg (int.coe_nat_nonneg n)).symm,
by rw [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h), h₁];
exact int.mod_lt _ h⟩⟩
instance (n : ℕ+) : add_comm_semigroup (zmod n) :=
{ add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(show ((a + b) % n + c) ≡ (a + (b + c) % n) [MOD n],
from calc ((a + b) % n + c) ≡ a + b + c [MOD n] : modeq_add (nat.mod_mod _ _) rfl
... ≡ a + (b + c) [MOD n] : by rw add_assoc
... ≡ (a + (b + c) % n) [MOD n] : modeq_add rfl (nat.mod_mod _ _).symm),
add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % n = (b + a) % n, by rw add_comm),
..fin.has_add }
instance (n : ℕ+) : comm_semigroup (zmod n) :=
{ mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc ((a * b) % n * c) ≡ a * b * c [MOD n] : modeq_mul (nat.mod_mod _ _) rfl
... ≡ a * (b * c) [MOD n] : by rw mul_assoc
... ≡ a * (b * c % n) [MOD n] : modeq_mul rfl (nat.mod_mod _ _).symm),
mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % n = (b * a) % n, by rw mul_comm),
..fin.has_mul }
instance (n : ℕ+) : has_one (zmod n) := ⟨⟨(1 % n), nat.mod_lt _ n.pos⟩⟩
instance (n : ℕ+) : has_zero (zmod n) := ⟨⟨0, n.pos⟩⟩
instance zmod_one.subsingleton : subsingleton (zmod 1) :=
⟨λ a b, fin.eq_of_veq (by rw [eq_zero_of_le_zero (le_of_lt_succ a.2),
eq_zero_of_le_zero (le_of_lt_succ b.2)])⟩
lemma add_val {n : ℕ+} : ∀ a b : zmod n, (a + b).val = (a.val + b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma mul_val {n : ℕ+} : ∀ a b : zmod n, (a * b).val = (a.val * b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma one_val {n : ℕ+} : (1 : zmod n).val = 1 % n := rfl
@[simp] lemma zero_val (n : ℕ+) : (0 : zmod n).val = 0 := rfl
private lemma one_mul_aux (n : ℕ+) (a : zmod n) : (1 : zmod n) * a = a :=
begin
cases n with n hn,
cases n with n,
{ exact (lt_irrefl _ hn).elim },
{ cases n with n,
{ exact @subsingleton.elim (zmod 1) _ _ _ },
{ have h₁ : a.1 % n.succ.succ = a.1 := nat.mod_eq_of_lt a.2,
have h₂ : 1 % n.succ.succ = 1 := nat.mod_eq_of_lt dec_trivial,
refine fin.eq_of_veq _,
simp [mul_val, one_val, h₁, h₂] } }
end
private lemma left_distrib_aux (n : ℕ+) : ∀ a b c : zmod n, a * (b + c) = a * b + a * c :=
λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc a * ((b + c) % n) ≡ a * (b + c) [MOD n] : modeq_mul rfl (nat.mod_mod _ _)
... ≡ a * b + a * c [MOD n] : by rw mul_add
... ≡ (a * b) % n + (a * c) % n [MOD n] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm)
instance (n : ℕ+) : comm_ring (zmod n) :=
{ zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % n = a, by rw zero_add; exact nat.mod_eq_of_lt ha),
add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha),
add_left_neg :=
λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % n).to_nat + a) % n = 0,
from int.coe_nat_inj
begin
have hn : (n : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 n.pos)).symm,
rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm],
simp,
end),
one_mul := one_mul_aux n,
mul_one := λ a, by rw mul_comm; exact one_mul_aux n a,
left_distrib := left_distrib_aux n,
right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl,
..zmod.has_zero n,
..zmod.has_one n,
..zmod.has_neg n,
..zmod.add_comm_semigroup n,
..zmod.comm_semigroup n }
lemma val_cast_nat {n : ℕ+} (a : ℕ) : (a : zmod n).val = a % n :=
begin
induction a with a ih,
{ rw [nat.zero_mod]; refl },
{ rw [succ_eq_add_one, nat.cast_add, add_val, ih],
show (a % n + ((0 + (1 % n)) % n)) % n = (a + 1) % n,
rw [zero_add, nat.mod_mod],
exact nat.modeq.modeq_add (nat.mod_mod a n) (nat.mod_mod 1 n) }
end
lemma neg_val' {m : pnat} (n : zmod m) : (-n).val = (m - n.val) % m :=
have ((-n).val + n.val) % m = (m - n.val + n.val) % m,
by { rw [←add_val, add_left_neg, nat.sub_add_cancel (le_of_lt n.is_lt), nat.mod_self], refl },
(nat.mod_eq_of_lt (fin.is_lt _)).symm.trans (nat.modeq.modeq_add_cancel_right rfl this)
lemma neg_val {m : pnat} (n : zmod m) : (-n).val = if n = 0 then 0 else m - n.val :=
begin
rw neg_val',
by_cases h : n = 0; simp [h],
cases n with n nlt; cases n; dsimp, { contradiction },
rw nat.mod_eq_of_lt,
apply nat.sub_lt m.2 (nat.succ_pos _),
end
lemma mk_eq_cast {n : ℕ+} {a : ℕ} (h : a < n) : (⟨a, h⟩ : zmod n) = (a : zmod n) :=
fin.eq_of_veq (by rw [val_cast_nat, nat.mod_eq_of_lt h])
@[simp] lemma cast_self_eq_zero {n : ℕ+} : ((n : ℕ) : zmod n) = 0 :=
fin.eq_of_veq (show (n : zmod n).val = 0, by simp [val_cast_nat])
lemma val_cast_of_lt {n : ℕ+} {a : ℕ} (h : a < n) : (a : zmod n).val = a :=
by rw [val_cast_nat, nat.mod_eq_of_lt h]
@[simp] lemma cast_mod_nat (n : ℕ+) (a : ℕ) : ((a % n : ℕ) : zmod n) = a :=
by conv {to_rhs, rw ← nat.mod_add_div a n}; simp
@[simp] lemma cast_mod_nat' {n : ℕ} (hn : 0 < n) (a : ℕ) : ((a % n : ℕ) : zmod ⟨n, hn⟩) = a :=
cast_mod_nat _ _
@[simp] lemma cast_val {n : ℕ+} (a : zmod n) : (a.val : zmod n) = a :=
by cases a; simp [mk_eq_cast]
@[simp] lemma cast_mod_int (n : ℕ+) (a : ℤ) : ((a % (n : ℕ) : ℤ) : zmod n) = a :=
by conv {to_rhs, rw ← int.mod_add_div a n}; simp
@[simp] lemma cast_mod_int' {n : ℕ} (hn : 0 < n) (a : ℤ) :
((a % (n : ℕ) : ℤ) : zmod ⟨n, hn⟩) = a := cast_mod_int _ _
lemma val_cast_int {n : ℕ+} (a : ℤ) : (a : zmod n).val = (a % (n : ℕ)).nat_abs :=
have h : nat_abs (a % (n : ℕ)) < n := int.coe_nat_lt.1 begin
rw [nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))],
conv {to_rhs, rw ← abs_of_nonneg (int.coe_nat_nonneg n)},
exact int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)
end,
int.coe_nat_inj $
by conv {to_lhs, rw [← cast_mod_int n a,
← nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)),
int.cast_coe_nat, val_cast_of_lt h] }
lemma coe_val_cast_int {n : ℕ+} (a : ℤ) : ((a : zmod n).val : ℤ) = a % (n : ℕ) :=
by rw [val_cast_int, int.nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))]
lemma eq_iff_modeq_nat {n : ℕ+} {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] :=
⟨λ h, by have := fin.veq_of_eq h;
rwa [val_cast_nat, val_cast_nat] at this,
λ h, fin.eq_of_veq $ by rwa [val_cast_nat, val_cast_nat]⟩
lemma eq_iff_modeq_nat' {n : ℕ} (hn : 0 < n) {a b : ℕ} : (a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [MOD n] :=
eq_iff_modeq_nat
lemma eq_iff_modeq_int {n : ℕ+} {a b : ℤ} : (a : zmod n) = b ↔ a ≡ b [ZMOD (n : ℕ)] :=
⟨λ h, by have := fin.veq_of_eq h;
rwa [val_cast_int, val_cast_int, ← int.coe_nat_eq_coe_nat_iff,
nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)),
nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))] at this,
λ h : a % (n : ℕ) = b % (n : ℕ),
by rw [← cast_mod_int n a, ← cast_mod_int n b, h]⟩
lemma eq_iff_modeq_int' {n : ℕ} (hn : 0 < n) {a b : ℤ} :
(a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [ZMOD (n : ℕ)] := eq_iff_modeq_int
lemma eq_zero_iff_dvd_nat {n : ℕ+} {a : ℕ} : (a : zmod n) = 0 ↔ (n : ℕ) ∣ a :=
by rw [← @nat.cast_zero (zmod n), eq_iff_modeq_nat, nat.modeq.modeq_zero_iff]
lemma eq_zero_iff_dvd_int {n : ℕ+} {a : ℤ} : (a : zmod n) = 0 ↔ ((n : ℕ) : ℤ) ∣ a :=
by rw [← @int.cast_zero (zmod n), eq_iff_modeq_int, int.modeq.modeq_zero_iff]
instance (n : ℕ+) : fintype (zmod n) := fin.fintype _
instance decidable_eq (n : ℕ+) : decidable_eq (zmod n) := fin.decidable_eq _
instance (n : ℕ+) : has_repr (zmod n) := fin.has_repr _
lemma card_zmod (n : ℕ+) : fintype.card (zmod n) = n := fintype.card_fin n
lemma le_div_two_iff_lt_neg {n : ℕ+} (hn : (n : ℕ) % 2 = 1)
{x : zmod n} (hx0 : x ≠ 0) : x.1 ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).1 :=
have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left n.pos).2 dec_trivial),
have hn2' : (n : ℕ) - n / 2 = n / 2 + 1,
by conv {to_lhs, congr, rw [← succ_sub_one n, succ_sub n.pos]};
rw [← two_mul_odd_div_two hn, two_mul, ← succ_add, nat.add_sub_cancel],
have hxn : (n : ℕ) - x.val < n,
begin
rw [nat.sub_lt_iff (le_of_lt x.2) (le_refl _), nat.sub_self],
rw ← zmod.cast_val x at hx0,
exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0)
end,
by conv {to_rhs, rw [← nat.succ_le_iff, succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self_eq_zero,
← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.2),
zmod.val_cast_nat, mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.2)] }
lemma ne_neg_self {n : ℕ+} (hn1 : (n : ℕ) % 2 = 1) {a : zmod n} (ha : a ≠ 0) : a ≠ -a :=
λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg hn1 ha,
by rwa [← h, ← not_lt, not_iff_self] at this
@[simp] lemma cast_mul_right_val_cast {n m : ℕ+} (a : ℕ) :
((a : zmod (m * n)).val : zmod m) = (a : zmod m) :=
zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat;
exact nat.modeq.modeq_of_modeq_mul_right _ (nat.mod_mod _ _))
@[simp] lemma cast_mul_left_val_cast {n m : ℕ+} (a : ℕ) :
((a : zmod (n * m)).val : zmod m) = (a : zmod m) :=
zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat;
exact nat.modeq.modeq_of_modeq_mul_left _ (nat.mod_mod _ _))
lemma cast_val_cast_of_dvd {n m : ℕ+} (h : (m : ℕ) ∣ n) (a : ℕ) :
((a : zmod n).val : zmod m) = (a : zmod m) :=
let ⟨k , hk⟩ := h in
zmod.eq_iff_modeq_nat.2 (nat.modeq.modeq_of_modeq_mul_right k
(by rw [← hk, zmod.val_cast_nat]; exact nat.mod_mod _ _))
def units_equiv_coprime {n : ℕ+} : units (zmod n) ≃ {x : zmod n // nat.coprime x.1 n} :=
{ to_fun := λ x, ⟨x, nat.modeq.coprime_of_mul_modeq_one (x⁻¹).1.1 begin
have := units.ext_iff.1 (mul_right_inv x),
rwa [← zmod.cast_val ((1 : units (zmod n)) : zmod n), units.coe_one, zmod.one_val,
← zmod.cast_val ((x * x⁻¹ : units (zmod n)) : zmod n),
units.coe_mul, zmod.mul_val, zmod.cast_mod_nat, zmod.cast_mod_nat,
zmod.eq_iff_modeq_nat] at this
end⟩,
inv_fun := λ x,
have x.val * ↑(gcd_a ((x.val).val) ↑n) = 1,
by rw [← zmod.cast_val x.1, ← int.cast_coe_nat, ← int.cast_one, ← int.cast_mul,
zmod.eq_iff_modeq_int, ← int.coe_nat_one, ← (show nat.gcd _ _ = _, from x.2)];
simpa using int.modeq.gcd_a_modeq x.1.1 n,
⟨x.1, gcd_a x.1.1 n, this, by simpa [mul_comm] using this⟩,
left_inv := λ ⟨_, _, _, _⟩, units.ext rfl,
right_inv := λ ⟨_, _⟩, rfl }
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]` -/
def val_min_abs {n : ℕ+} (x : zmod n) : ℤ :=
if x.val ≤ n / 2 then x.val else x.val - n
@[simp] lemma coe_val_min_abs {n : ℕ+} (x : zmod n) :
(x.val_min_abs : zmod n) = x :=
by simp [zmod.val_min_abs]; split_ifs; simp
lemma nat_abs_val_min_abs_le {n : ℕ+} (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 :=
have (x.val - n : ℤ) ≤ 0, from sub_nonpos.2 $ int.coe_nat_le.2 $ le_of_lt x.2,
begin
rw zmod.val_min_abs,
split_ifs with h,
{ exact h },
{ rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub],
conv_lhs { congr, rw [coe_coe, ← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul,
int.coe_nat_bit0, int.coe_nat_one] },
rw ← sub_nonneg,
suffices : (0 : ℤ) ≤ x.val - ((n % 2 : ℕ) + (n / 2 : ℕ)),
{ exact le_trans this (le_of_eq $ by ring) },
exact sub_nonneg.2 (by rw [← int.coe_nat_add, int.coe_nat_le];
exact calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 :
add_le_add (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) (le_refl _)
... ≤ x.val : by rw add_comm; exact nat.succ_le_of_lt (lt_of_not_ge h)) }
end
@[simp] lemma val_min_abs_zero {n : ℕ+} : (0 : zmod n).val_min_abs = 0 :=
by simp [zmod.val_min_abs]
@[simp] lemma val_min_abs_eq_zero {n : ℕ+} (x : zmod n) :
x.val_min_abs = 0 ↔ x = 0 :=
⟨λ h, begin
dsimp [zmod.val_min_abs] at h,
split_ifs at h,
{ exact fin.eq_of_veq (by simp * at *) },
{ exact absurd h (mt sub_eq_zero.1 (ne_of_lt $ int.coe_nat_lt.2 x.2)) }
end, λ hx0, hx0.symm ▸ zmod.val_min_abs_zero⟩
lemma cast_nat_abs_val_min_abs {n : ℕ+} (a : zmod n) :
(a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a :=
have (a.val : ℤ) + -n ≤ 0, by erw [sub_nonpos, int.coe_nat_le]; exact le_of_lt a.2,
begin
dsimp [zmod.val_min_abs],
split_ifs,
{ simp },
{ erw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this],
simp }
end
@[simp] lemma nat_abs_val_min_abs_neg {n : ℕ+} (a : zmod n) :
(-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs :=
if haa : -a = a then by rw [haa]
else
have hpa : (n : ℕ) - a.val ≤ n / 2 ↔ (n : ℕ) / 2 < a.val,
from suffices (((n : ℕ) % 2) + 2 * (n / 2)) - a.val ≤ (n : ℕ) / 2 ↔ (n : ℕ) / 2 < a.val,
by rwa [nat.mod_add_div] at this,
begin
rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel],
cases (n : ℕ).mod_two_eq_zero_or_one with hn0 hn1,
{ split,
{ exact λ h, lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h)
begin
assume hna,
rw [← zmod.cast_val a, ← hna, neg_eq_iff_add_eq_zero, ← nat.cast_add,
zmod.eq_zero_iff_dvd_nat, ← two_mul, ← zero_add (2 * _), ← hn0,
nat.mod_add_div] at haa,
exact haa (dvd_refl _)
end },
{ rw [hn0, zero_add], exact le_of_lt } },
{ rw [hn1, add_comm, nat.succ_le_iff] }
end,
have ha0 : ¬ a = 0, from λ ha0, by simp * at *,
begin
dsimp [zmod.val_min_abs],
rw [← not_le] at hpa,
simp only [if_neg ha0, zmod.neg_val, hpa, int.coe_nat_sub (le_of_lt a.2)],
split_ifs,
{ simp },
{ rw [← int.nat_abs_neg], simp }
end
lemma val_eq_ite_val_min_abs {n : ℕ+} (a : zmod n) :
(a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n :=
by simp [zmod.val_min_abs]; split_ifs; simp
lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial
@[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a :=
by cases a; simp [zmod.neg_eq_self_mod_two]
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α] {n : ℕ+}
def cast : zmod n → α := nat.cast ∘ fin.val
end
end zmod
def zmodp (p : ℕ) (hp : prime p) : Type := zmod ⟨p, hp.pos⟩
namespace zmodp
variables {p : ℕ} (hp : prime p)
instance : comm_ring (zmodp p hp) := zmod.comm_ring ⟨p, hp.pos⟩
instance {p : ℕ} (hp : prime p) : has_inv (zmodp p hp) :=
⟨λ a, gcd_a a.1 p⟩
lemma add_val : ∀ a b : zmodp p hp, (a + b).val = (a.val + b.val) % p
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma mul_val : ∀ a b : zmodp p hp, (a * b).val = (a.val * b.val) % p
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp] lemma one_val : (1 : zmodp p hp).val = 1 :=
nat.mod_eq_of_lt hp.one_lt
@[simp] lemma zero_val : (0 : zmodp p hp).val = 0 := rfl
lemma val_cast_nat (a : ℕ) : (a : zmodp p hp).val = a % p :=
@zmod.val_cast_nat ⟨p, hp.pos⟩ _
lemma mk_eq_cast {a : ℕ} (h : a < p) : (⟨a, h⟩ : zmodp p hp) = (a : zmodp p hp) :=
@zmod.mk_eq_cast ⟨p, hp.pos⟩ _ _
@[simp] lemma cast_self_eq_zero: (p : zmodp p hp) = 0 :=
fin.eq_of_veq $ by simp [val_cast_nat]
lemma val_cast_of_lt {a : ℕ} (h : a < p) : (a : zmodp p hp).val = a :=
@zmod.val_cast_of_lt ⟨p, hp.pos⟩ _ h
@[simp] lemma cast_mod_nat (a : ℕ) : ((a % p : ℕ) : zmodp p hp) = a :=
@zmod.cast_mod_nat ⟨p, hp.pos⟩ _
@[simp] lemma cast_val (a : zmodp p hp) : (a.val : zmodp p hp) = a :=
@zmod.cast_val ⟨p, hp.pos⟩ _
@[simp] lemma cast_mod_int (a : ℤ) : ((a % p : ℤ) : zmodp p hp) = a :=
@zmod.cast_mod_int ⟨p, hp.pos⟩ _
lemma val_cast_int (a : ℤ) : (a : zmodp p hp).val = (a % p).nat_abs :=
@zmod.val_cast_int ⟨p, hp.pos⟩ _
lemma coe_val_cast_int (a : ℤ) : ((a : zmodp p hp).val : ℤ) = a % (p : ℕ) :=
@zmod.coe_val_cast_int ⟨p, hp.pos⟩ _
lemma eq_iff_modeq_nat {a b : ℕ} : (a : zmodp p hp) = b ↔ a ≡ b [MOD p] :=
@zmod.eq_iff_modeq_nat ⟨p, hp.pos⟩ _ _
lemma eq_iff_modeq_int {a b : ℤ} : (a : zmodp p hp) = b ↔ a ≡ b [ZMOD p] :=
@zmod.eq_iff_modeq_int ⟨p, hp.pos⟩ _ _
lemma eq_zero_iff_dvd_nat (a : ℕ) : (a : zmodp p hp) = 0 ↔ p ∣ a :=
@zmod.eq_zero_iff_dvd_nat ⟨p, hp.pos⟩ _
lemma eq_zero_iff_dvd_int (a : ℤ) : (a : zmodp p hp) = 0 ↔ (p : ℤ) ∣ a :=
@zmod.eq_zero_iff_dvd_int ⟨p, hp.pos⟩ _
instance : fintype (zmodp p hp) := @zmod.fintype ⟨p, hp.pos⟩
instance decidable_eq : decidable_eq (zmodp p hp) := fin.decidable_eq _
instance : has_repr (zmodp p hp) := fin.has_repr _
@[simp] lemma card_zmodp : fintype.card (zmodp p hp) = p :=
@zmod.card_zmod ⟨p, hp.pos⟩
lemma le_div_two_iff_lt_neg {p : ℕ} (hp : prime p) (hp1 : p % 2 = 1)
{x : zmodp p hp} (hx0 : x ≠ 0) : x.1 ≤ (p / 2 : ℕ) ↔ (p / 2 : ℕ) < (-x).1 :=
@zmod.le_div_two_iff_lt_neg ⟨p, hp.pos⟩ hp1 _ hx0
lemma ne_neg_self (hp1 : p % 2 = 1) {a : zmodp p hp} (ha : a ≠ 0) : a ≠ -a :=
@zmod.ne_neg_self ⟨p, hp.pos⟩ hp1 _ ha
variable {hp}
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]` -/
def val_min_abs (x : zmodp p hp) : ℤ := zmod.val_min_abs x
@[simp] lemma coe_val_min_abs (x : zmodp p hp) :
(x.val_min_abs : zmodp p hp) = x :=
zmod.coe_val_min_abs x
lemma nat_abs_val_min_abs_le (x : zmodp p hp) : x.val_min_abs.nat_abs ≤ p / 2 :=
zmod.nat_abs_val_min_abs_le x
@[simp] lemma val_min_abs_zero : (0 : zmodp p hp).val_min_abs = 0 :=
zmod.val_min_abs_zero
@[simp] lemma val_min_abs_eq_zero (x : zmodp p hp) : x.val_min_abs = 0 ↔ x = 0 :=
zmod.val_min_abs_eq_zero x
lemma cast_nat_abs_val_min_abs (a : zmodp p hp) :
(a.val_min_abs.nat_abs : zmodp p hp) = if a.val ≤ p / 2 then a else -a :=
zmod.cast_nat_abs_val_min_abs a
@[simp] lemma nat_abs_val_min_abs_neg (a : zmodp p hp) :
(-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs :=
zmod.nat_abs_val_min_abs_neg _
lemma val_eq_ite_val_min_abs (a : zmodp p hp) :
(a.val : ℤ) = a.val_min_abs + if a.val ≤ p / 2 then 0 else p :=
zmod.val_eq_ite_val_min_abs _
variable (hp)
lemma prime_ne_zero {q : ℕ} (hq : prime q) (hpq : p ≠ q) : (q : zmodp p hp) ≠ 0 :=
by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff,
← hp.coprime_iff_not_dvd, coprime_primes hp hq]
lemma mul_inv_eq_gcd (a : ℕ) : (a : zmodp p hp) * a⁻¹ = nat.gcd a p :=
by rw [← int.cast_coe_nat (nat.gcd _ _), nat.gcd_comm, nat.gcd_rec, ← (eq_iff_modeq_int _).2 (int.modeq.gcd_a_modeq _ _)];
simp [has_inv.inv, val_cast_nat]
private lemma mul_inv_cancel_aux : ∀ a : zmodp p hp, a ≠ 0 → a * a⁻¹ = 1 :=
λ ⟨a, hap⟩ ha0, begin
rw [mk_eq_cast, ne.def, ← @nat.cast_zero (zmodp p hp), eq_iff_modeq_nat, modeq_zero_iff] at ha0,
have : nat.gcd p a = 1 := (prime.coprime_iff_not_dvd hp).2 ha0,
rw [mk_eq_cast _ hap, mul_inv_eq_gcd, nat.gcd_comm],
simpa [nat.gcd_comm, this]
end
instance : discrete_field (zmodp p hp) :=
{ zero_ne_one := fin.ne_of_vne $ show 0 ≠ 1 % p,
by rw nat.mod_eq_of_lt hp.one_lt;
exact zero_ne_one,
mul_inv_cancel := mul_inv_cancel_aux hp,
inv_mul_cancel := λ a, by rw mul_comm; exact mul_inv_cancel_aux hp _,
has_decidable_eq := by apply_instance,
inv_zero := show (gcd_a 0 p : zmodp p hp) = 0,
by unfold gcd_a xgcd xgcd_aux; refl,
..zmodp.comm_ring hp,
..zmodp.has_inv hp }
end zmodp
|
d6f3db61903caa104fd59f6a201597f9fc5b9d62 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1812.lean | a95ec42979bd0bec5e895508e405b7f278613458 | [
"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 | 92 | lean | set_option trace.Compiler.result true
def notList : List Prop → List Prop := List.map Not
|
5939e8ae85621445b91346610d2465c153f92ad8 | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean/deps/galois_stdlib/src/galois/data/bitvec/basic.lean | 42fb3a16368b3645081831ece4733fe073f936a9 | [
"Apache-2.0"
] | permissive | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 13,601 | lean | /-
Copyright (c) 2015 Joe Hendrix. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joe Hendrix, Sebastian Ullrich, Jason Dagit
Basic operations on bitvectors.
This is a work-in-progress, and contains additions to other theories.
-/
import galois.data.nat.basic
import data.vector
-- A `bitvec n` is a subtype of natural numbers such that the value of
-- the bitvec is strictly less than 2^n.
structure bitvec (sz:ℕ) :=
(to_nat : ℕ)
(property : to_nat < (2 ^ sz))
namespace bitvec
open galois
instance (w:ℕ) : decidable_eq (bitvec w) := by tactic.mk_dec_eq_instance
-- By default just show a bitvector as a nat.
instance (w:ℕ) : has_repr (bitvec w) := ⟨λv, repr (v.to_nat)⟩
section to_hex
protected def to_hex_with_leading_zeros : list char → ℕ → ℕ → string
| prev 0 _ := prev.as_string
| prev (nat.succ w) x :=
let c := (nat.land x 0xf).digit_char in
to_hex_with_leading_zeros (c::prev) w (nat.shiftr x 4)
protected def to_hex' : list char → ℕ → ℕ → string
| prev 0 _ := prev.as_string
| prev w 0 := prev.as_string
| prev (nat.succ w) x :=
let c := (nat.land x 0xf).digit_char in
to_hex' (c::prev) w (nat.shiftr x 4)
--- Print word as hex
def pp_hex {n : ℕ} (v : bitvec n) : string := "0x" ++ bitvec.to_hex' [] (n / 4) v.to_nat
end to_hex
section zero
-- Create a zero bitvector
protected
def zero (n : ℕ) : bitvec n :=
⟨0, nat.pos_pow_of_pos n dec_trivial⟩
-- bitvectors have a zero, at every length
instance {n:ℕ} : has_zero (bitvec n) := ⟨bitvec.zero n⟩
@[simp]
lemma bitvec_zero_zero (x : bitvec 0) : x.to_nat = 0 :=
begin
cases x with x_val x_prop,
{ simp [nat.pow_zero, nat.lt_one_is_zero] at x_prop,
simp, assumption
}
end
end zero
section one
lemma one_le_pow_2 {n: ℕ} (h : n > 0) : 1 < 2^n :=
calc 1 < 2^1 : by exact (of_as_true trivial)
... ≤ 2^n : nat.pow_le_pow_of_le_right (of_as_true trivial) h
-- In pratice, it's more useful to allow 0 length bitvectors to have 1
-- as well. This leads to a special case where the 0-length bitvector
-- 1 is really just 0. This turns out to simplify things.
protected
def one : Π(n:ℕ), bitvec n
| 0 := 0
| (nat.succ _) := ⟨1, one_le_pow_2 (nat.zero_lt_succ _)⟩
instance {n:ℕ} : has_one (bitvec n) := ⟨bitvec.one n⟩
end one
protected def cong {a b : ℕ} (h : a = b) : bitvec a → bitvec b
| ⟨x, p⟩ := ⟨x, h ▸ p⟩
lemma cong_val {n m : ℕ} {H : n = m} (x : bitvec n)
: (bitvec.cong H x).to_nat = x.to_nat :=
begin
cases x, simp [bitvec.cong]
end
protected
lemma intro {n:ℕ} : Π(x y : bitvec n), x.to_nat = y.to_nat → x = y
| ⟨x, h1⟩ ⟨.(_), h2⟩ rfl := rfl
-- FIXME: more efficient implementation of of_nat
-- protected def of_nat (n : ℕ) (x:ℕ) : bitvec n := ⟨ x % ((nat.shiftl 1 n)), sorry⟩
protected def of_nat (n : ℕ) (x:ℕ) : bitvec n :=
⟨ x % 2^n, nat.mod_lt _ (nat.pos_pow_of_pos n (of_as_true trivial))⟩
instance nat_to_bitvec_coe {w : ℕ} : has_coe ℕ (bitvec w) := ⟨bitvec.of_nat w⟩
theorem of_nat_to_nat {n : ℕ} (x : bitvec n)
: bitvec.of_nat n (bitvec.to_nat x) = x :=
begin
cases x,
simp [bitvec.to_nat, bitvec.of_nat],
apply nat.mod_eq_of_lt x_property,
end
theorem to_nat_of_nat (k n : ℕ)
: bitvec.to_nat (bitvec.of_nat k n) = n % 2^k :=
begin
simp [bitvec.of_nat, bitvec.to_nat]
end
--- Most significant bit
def msb {n:ℕ} (x: bitvec n) : bool := (nat.shiftr x.to_nat (n-1)) = 1
--- Least significant bit.
def lsb {n:ℕ} (x: bitvec n) : bool := nat.bodd x.to_nat
section conversion
-- Operations for converting to/from bitvectors
protected def to_int {n:ℕ} (x: bitvec n) : int :=
match msb x with
| ff := int.of_nat x.to_nat
| tt := int.neg_of_nat (2^n - x.to_nat)
end
--- Convert an int to two's complement bitvector.
protected def of_int : Π(n : ℕ), ℤ → bitvec n
| n (int.of_nat x) := bitvec.of_nat n x
| n -[1+ x] := bitvec.of_nat n (nat.ldiff (2^n-1) x)
end conversion
section bitwise
-- bitwise negation
def not {w:ℕ} (x: bitvec w) : bitvec w := ⟨2^w - x.to_nat - 1,
begin
have xval_pos : 0 < x.to_nat + 1,
{ apply (nat.succ_pos x.to_nat) },
apply (nat.sub_lt _ xval_pos),
apply nat.pos_pow_of_pos,
apply (nat.succ_pos 1)
end⟩
-- logical bitwise and
def and {w:ℕ} (x y : bitvec w) : bitvec w := bitvec.of_nat w (nat.land x.to_nat y.to_nat)
-- diff x y = x & not y
def diff {w:ℕ} (x y : bitvec w) : bitvec w := bitvec.of_nat w (nat.ldiff x.to_nat y.to_nat)
-- logical bitwise or
def or {w:ℕ} (x y : bitvec w) : bitvec w := bitvec.of_nat w (nat.lor x.to_nat y.to_nat)
-- logical bitwise xor
def xor {w:ℕ} (x y : bitvec w) : bitvec w := bitvec.of_nat w (nat.lxor x.to_nat y.to_nat)
infix `.&&.`:70 := and
infix `.||.`:65 := or
end bitwise
section arith
-- Arithmetic operations on bitvectors
variable {n : ℕ}
protected def add (x y : bitvec n) : bitvec n := bitvec.of_nat n (x.to_nat + y.to_nat)
def adc (x y : bitvec n) : bitvec n × bool := ⟨ bitvec.add x y , x.to_nat + y.to_nat ≥ 2^n ⟩
-- Usual arithmetic subtraction
protected def sub (x y : bitvec n) : bitvec n := bitvec.of_int n (x.to_int - y.to_int)
-- 2s complement negation
protected def neg {n:ℕ} (x : bitvec n) : bitvec n :=
⟨if x.to_nat = 0 then 0 else 2^n - x.to_nat,
begin
by_cases (x.to_nat = 0),
{ simp [h], exact nat.pos_pow_of_pos _ (of_as_true trivial), },
{ simp [h],
--x.to_nat (2^n) x_to_nat_pos,
have pos : 0 < 2^n - x.to_nat, { apply nat.sub_pos_of_lt x.property },
have x_to_nat_pos: 0 < x.to_nat, { apply nat.pos_of_ne_zero h },
apply nat.sub_lt_of_pos_le x.to_nat (2^n) x_to_nat_pos,
apply le_of_lt x.property,
}
end⟩
instance : has_add (bitvec n) := ⟨bitvec.add⟩
instance : has_sub (bitvec n) := ⟨bitvec.sub⟩
instance : has_neg (bitvec n) := ⟨bitvec.neg⟩
protected def mul (x y : bitvec n) : bitvec n := bitvec.of_nat n (x.to_nat * y.to_nat)
instance : has_mul (bitvec n) := ⟨bitvec.mul⟩
def bitvec_pow (x: bitvec n) (k:ℕ) : bitvec n := bitvec.of_nat n (x.to_nat^k)
instance bitvec_has_pow : has_pow (bitvec n) ℕ := ⟨bitvec_pow⟩
end arith
section shift
-- Shift related operations, including signed and unsigned shift.
variable {n : ℕ}
-- shift left
def shl (x : bitvec n) (i : ℕ) : bitvec n := bitvec.of_nat n (nat.shiftl x.to_nat i)
-- unsigned shift right
def ushr (x : bitvec n) (i : ℕ) : bitvec n := bitvec.of_nat n (nat.shiftr x.to_nat i)
-- signed shift right
def sshr (x: bitvec n) (i:ℕ) : bitvec n := bitvec.of_int n (int.shiftr (bitvec.to_int x) i)
end shift
section listlike
-- Operations that treat bitvectors as a list of bits.
--- Test if a specific bit with given index is set.
def nth {w:ℕ} (x : bitvec w) (idx : ℕ) : bool := nat.test_bit x.to_nat idx
-- Change number of bits result while preserving unsigned value modulo output width.
def uresize {m:ℕ} (x: bitvec m) (n:ℕ) : bitvec n := bitvec.of_nat _ x.to_nat
-- Change number of bits result while preserving signed value modulo output width.
def sresize {m:ℕ} (x: bitvec m) (n:ℕ) : bitvec n := bitvec.of_int _ x.to_int
open nat
-- bitvec specific version of vector.append
def append {m n} (x: bitvec m) (y: bitvec n) : bitvec (m + n)
:= ⟨ x.to_nat * 2^n + y.to_nat, nat.mul_pow_add_lt_pow x.property y.property ⟩
protected
def bsf' : Π(n:ℕ), ℕ → ℕ → option ℕ
| 0 idx _ := none
| (succ m) idx x :=
if nat.test_bit x idx then
some idx
else
bsf' m (idx+1) x
--- index of least-significant bit that is 1.
def bsf : Π{n:ℕ}, bitvec n → option ℕ
| n x := bitvec.bsf' n 0 x.to_nat
protected
def bsr' : ℕ → ℕ → option ℕ
| x zero := none
| x (succ idx) :=
if nat.test_bit x idx then
some idx
else
bsr' x idx
--- index of the most-significant bit that is 1.
def bsr : Π{n:ℕ}, bitvec n → option ℕ
| n x := bitvec.bsr' x.to_nat n
example : bsf (bitvec.of_nat 3 0) = none := of_as_true trivial
example : bsr (bitvec.of_nat 3 0) = none := of_as_true trivial
example : bsf (bitvec.of_nat 3 5) = some 0 := of_as_true trivial
example : bsr (bitvec.of_nat 3 5) = some 2 := of_as_true trivial
def slice {w: ℕ} (u l k:ℕ) (H: w = k + (u + 1 - l)) (x: bitvec w) : bitvec (u + 1 - l) :=
bitvec.of_nat _ (nat.shiftr x.to_nat l)
protected
def {u} foldl' {α : Sort u} (f : α -> bool → α) (x : ℕ) (init : α) : ℕ → α
| zero := init
| (succ idx) := f (foldl' idx) (x.test_bit idx)
-- foldl follows nth's behaviour, so
-- foldl f i b = f (f (f i b!0) b!1) b!2 etc.
def {u} foldl {α : Sort u} {n : ℕ} (f : α → bool → α) (init : α) (b : bitvec n) : α :=
bitvec.foldl' f b.to_nat init n
protected
def {u} foldr' {α : Sort u} (f : bool → α → α) (x : ℕ) (init : α) (n : ℕ) : ℕ → α
| zero := init
| (succ idx) := f (x.test_bit (n - succ idx)) (foldr' idx)
-- foldr follows nth's behaviour, so
-- foldr f i b = f b!0 (f b!1 ... (f b!(n-1) i))
def {u} foldr {α : Sort u} {n : ℕ} (f : bool → α → α) (init : α) (b : bitvec n) : α :=
bitvec.foldr' f b.to_nat init n n
end listlike
section comparison
-- Comparison operations, including signed and unsigned versions
variable {n : ℕ}
def ult (x y : bitvec n) : Prop := x.to_nat < y.to_nat
def ugt (x y : bitvec n) : Prop := ult y x
def ule (x y : bitvec n) : Prop := ¬ (ult y x)
def uge (x y : bitvec n) : Prop := ule y x
def slt (x y : bitvec n) : Prop := x.to_int < y.to_int
def sgt (x y : bitvec n) : Prop := slt y x
def sle (x y : bitvec n) : Prop := ¬ (slt y x)
def sge (x y : bitvec n) : Prop := sle y x
local attribute [reducible] ult
local attribute [reducible] ugt
local attribute [reducible] ule
local attribute [reducible] uge
instance decidable_ult {n} {x y : bitvec n} : decidable (bitvec.ult x y) := by apply_instance
instance decidable_ugt {n} {x y : bitvec n} : decidable (bitvec.ugt x y) := by apply_instance
instance decidable_ule {n} {x y : bitvec n} : decidable (bitvec.ule x y) := by apply_instance
instance decidable_uge {n} {x y : bitvec n} : decidable (bitvec.uge x y) := by apply_instance
local attribute [reducible] slt
local attribute [reducible] sgt
local attribute [reducible] sle
local attribute [reducible] sge
instance decidable_slt {n} {x y : bitvec n} : decidable (bitvec.slt x y) := by apply_instance
instance decidable_sgt {n} {x y : bitvec n} : decidable (bitvec.sgt x y) := by apply_instance
instance decidable_sle {n} {x y : bitvec n} : decidable (bitvec.sle x y) := by apply_instance
instance decidable_sge {n} {x y : bitvec n} : decidable (bitvec.sge x y) := by apply_instance
end comparison
def concat' {n:ℕ} (input: list (bitvec n)): ℕ :=
list.foldl (λv (a:bitvec n), nat.shiftl v n + a.to_nat) 0 input
--- Concatenation all bitvectors in the list together and return a new bitvector.
--
-- The most significant bits of are returned first.
def concat_list {m:ℕ}(input: list (bitvec m)) (n:ℕ) : bitvec n :=
bitvec.of_nat _ (concat' input)
--- Concatenation all bitvectors in the vector together and return a new bitvector.
--
-- The most significant bits of are returned first.
--
-- To minimize the need for proofs, we intentionally do not force that the output
-- has a specific length.
def concat_vec {w m : ℕ}(input: vector (bitvec w) m) (n:ℕ) : bitvec n :=
bitvec.of_nat _ (concat' input.to_list)
example : concat_list [(1 : bitvec 4), 0] 8 = (16 : bitvec 8) := by exact (of_as_true trivial)
--- Forms a list of bitvectors by taking a specific number of bits from parts of the
-- first argument.
--
-- The head of the list has the most-significant bits.
def split_to_list (x:ℕ) (w:ℕ) : ℕ → list (bitvec w)
| nat.zero := []
| (nat.succ n) := bitvec.of_nat w (nat.shiftr x (n*w)) :: split_to_list n
theorem length_split_to_list (x:ℕ) (w : ℕ) (m:ℕ) : list.length (split_to_list x w m) = m :=
begin
induction m,
case nat.zero { simp [split_to_list], },
case nat.succ : m ind { simp [split_to_list, ind, nat.succ_add], },
end
/- Split a single bitvector into a list of bitvectors with most-significant bits first. -/
def split_list {n:ℕ} (x:bitvec n) (w:ℕ) : list (bitvec w) := split_to_list x.to_nat w (nat.div n w)
/- Split a single bitvector into a vector of bitvectors with most-significant bits first. -/
def split_vec {n:ℕ} (x:bitvec n) (w m:ℕ) : vector (bitvec w) m :=
⟨split_to_list x.to_nat w m, length_split_to_list _ _ _⟩
example : split_list (16 : bitvec 8) 4 = [(1 : bitvec 4), 0] := by exact (of_as_true trivial)
--- Git bits [i..i+m] out of n.
def get_bits {n} (x:bitvec n) (i m : ℕ) (p:i+m ≤ n) : bitvec m :=
bitvec.of_nat m (nat.shiftr x.to_nat i)
--#eval ((get_bits (0x01234567 : bitvec 32) 8 16 (of_as_true trivial) = 0x2345) : bool)
--- Set bits at given index.
def set_bits {n} (x:bitvec n) (i:ℕ) {m} (y:bitvec m) (p:i+m ≤ n) : bitvec n :=
let mask := bitvec.of_nat n (nat.shiftl ((2^m)-1) i) in
or (diff x mask) (bitvec.of_nat n (nat.shiftl y.to_nat i))
--#eval ((set_bits (0x01234567 : bitvec 32) 8 (0x5432 : bitvec 16) (of_as_true trivial) = 0x01543267) : bool)
end bitvec
|
251d7b66facabe2640eb216de18c56ec70e14289 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/t9.lean | dbd15cd4e967f46c684e9e2e9c0e86462cba9173 | [
"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 | 396 | lean | prelude precedence `+` : 65
precedence `*` : 75
precedence `=` : 50
precedence `≃` : 50
constant N : Type.{1}
constant a : N
constant b : N
constant add : N → N → N
constant mul : N → N → N
namespace foo
infixl + := add
infixl * := mul
check a+b*a
end foo
-- Notation is not avaiable outside the namespace
check a+b*a
namespace foo
-- Notation is restored
check a+b*a
end foo
|
cbc05645a80ff32ddc5a1ac3cc6f12df95042d8a | 5b0c53e5aaa0e60538d10f6b619a464aaf463815 | /ch2.hlean | 6c88c2db2c82da47e0598317eff0b6fe8ef9ab0a | [
"Apache-2.0"
] | permissive | bbentzen/hott-book-in-lean | f845a19ef09d48d2fb813624b4650d5832a47e10 | 9e262e633e653280b9cde5d287631fcec8501f64 | refs/heads/master | 1,586,430,679,994 | 1,519,975,089,000 | 1,519,975,089,000 | 50,330,220 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 39,449 | hlean | /-
Copyright (c) 2016 Bruno Bentzen. All rights reserved.
Released under the Apache License 2.0 (see "License");
Theorems and exercises of the HoTT book (Chapter 2)
-/
import .ch1 types.bool
open eq prod sum sigma bool lift
/- ************************************** -/
/- Ch.2 Homotopy Type Theory -/
/- ************************************** -/
/- §2.1 Types are Higher Groupoids -/
variables {A B C D Z: Type}
-- Lemma 2.1.1 "Paths can be reversed" :
definition path_inv {x y : A} (p : x = y) :
y = x :=
eq.rec_on p (refl x)
-- Lemma 2.1.2 "Paths can be composed" :
definition path_conc {x y z: A} (p : x = y) (q : y = z) :
x = z :=
eq.rec_on q p
-- Notation for conc and inv:
notation q `⬝` p := path_conc q p
notation p `⁻¹` := path_inv p
notation [parsing-only] p `⁻¹'` := path_inv p
-- Lemma 2.1.4 (i) "The constant path is a unit for composition" :
definition ru {x y : A} (p : x = y) :
p = p ⬝ refl y :=
refl p
definition lu {x y : A} (p : x = y) :
p = refl x ⬝ p :=
eq.rec_on p (refl (refl x))
-- Lemma 2.1.4 (ii) "Inverses are well-behaved" :
definition left_inv {x y : A} (p : x = y) :
p⁻¹ ⬝ p = refl y :=
eq.rec_on p (refl (refl x) )
definition right_inv {x y : A} (p : x = y) :
p ⬝ p⁻¹ = refl x :=
eq.rec_on p (refl (refl x) )
-- Lemma 2.1.4 (iii) "Double application of inverses cancel out" :
definition inv_canc {x y : A} (p : x = y) :
( p⁻¹ )⁻¹ = p :=
eq.rec_on p (refl (refl x))
-- Lemma 2.1.4 (iii) "composition is associative" :
definition conc_assoc {x y z w: A} (p : x = y) (q : y = z) (r : z = w) :
p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r :=
eq.rec_on r (eq.rec_on q (refl ( p ⬝ refl y ⬝ refl y )) )
-- Theorem 2.1.6 Eckmann-Hilton
-- Whiskering
definition r_whisker {x y z : A} {p q : x = y} (r : y = z) (α : p = q) :
p ⬝ r = q ⬝ r :=
by induction r; apply ((ru p)⁻¹ ⬝ α ⬝ ru q)
definition l_whisker {x y z : A} (q : x = y) {r s : y = z} (β : r = s) :
q ⬝ r = q ⬝ s :=
by induction q; apply ((lu r)⁻¹ ⬝ β ⬝ lu s)
notation α `⬝ᵣ` r := r_whisker r α
notation q `⬝ₗ` β := l_whisker q β
definition unwhisker_right {x y z : A} {p q : x = y} (r : y = z) (h : p ⬝ r = q ⬝ r) :
p = q :=
(eq.rec_on r (refl p ))⁻¹ ⬝ (h ⬝ᵣ r⁻¹) ⬝ (eq.rec_on r (refl q))
definition unwhisker_left {x y z : A} {r s : y = z} (q : x = y) (h : q ⬝ r = q ⬝ s) :
r = s :=
(conc_assoc q⁻¹ q r ⬝ (left_inv q ⬝ᵣ r) ⬝ (lu r)⁻¹)⁻¹ ⬝
(q⁻¹ ⬝ₗ h) ⬝ (conc_assoc q⁻¹ q s ⬝ (left_inv q ⬝ᵣ s) ⬝ (lu s)⁻¹)
definition whisker_comm (a b c: A) (p q : a = b) (r s : b = c) (α : p = q) (β : r = s):
(α ⬝ᵣ r) ⬝ (q ⬝ₗ β) = (p ⬝ₗ β) ⬝ (α ⬝ᵣ s) :=
by induction α; induction β; induction p; induction r; apply idp
-- Eckmann-Hilton
definition eckmann_hilton (a : A) (α β : refl a = refl a) :
α ⬝ β = β ⬝ α :=
calc
α ⬝ β = (α ⬝ᵣ refl a) ⬝ (refl a ⬝ₗ β) : begin rewrite (α ⬝ₗ (lu β)), exact (lu _ ⬝ conc_assoc _ _ _) end
... = (refl a ⬝ₗ β) ⬝ (α ⬝ᵣ refl a) : whisker_comm
... = β ⬝ α : begin rewrite (β ⬝ₗ (lu α)), exact (lu _ ⬝ conc_assoc _ _ _)⁻¹ end
-- Definition 2.1.7 Pointed types
definition pointed : Type := Σ (A : Type), A
--
/- §2.2 (Functions are functors) -/
-- Lemma 2.2.1 "Functions are continuous"
definition ap {x y : A} (f : A → B) (p : x = y) :
f x = f y :=
eq.rec_on p (refl (f x))
-- Lemma 2.2.2 (i)-(iv)
-- (i) ap behaves functorially:
definition ap_func_i {x y z : A} (f : A → B) (p : x = y) (q : y = z) :
ap f ( p ⬝ q ) = (ap f p) ⬝ (ap f q) :=
eq.rec_on q (eq.rec_on p (refl ((ap f (refl x)) ⬝ (ap f (refl x))) ) )
definition ap_func_ii {x y : A} (f : A → B) (p : x = y) :
ap f ( p⁻¹ ) = (ap f p)⁻¹ :=
eq.rec (refl (ap f (refl x))) p
definition ap_func_iii {x y : A} (f : A → B) (g : B → A) (p : x = y) :
ap g ( ap f p ) = (ap (g ∘ f) p) :=
eq.rec (refl (ap (g ∘ f) (refl x))) p
definition ap_func_iv {x y : A} (p : x = y) :
ap (id A) ( p ) = p :=
eq.rec (refl (refl x)) p
--
/- §2.3 (Type families are fibrations) -/
-- Lemma 2.3.1 "Transport"
definition transport {x y : A} (P : A → Type) (p : x = y) :
P x → P y :=
assume u : P x , eq.rec_on p u
-- Lemma 2.3.2 "Path Lifting property" :
definition path_lifting {x y : A} (P : A → Type) (p : x = y) (u : P x) :
(x , u) = (y , (transport _ p u)) :=
eq.rec_on p (refl (x , u))
-- Lemma 2.3.4 "Dependent maps" :
definition apd {x y : A} {P : A → Type} (f : Π (x : A), P(x)) (p : x = y) :
transport P p (f x) = f y :=
eq.rec_on p (refl (f x))
-- Lemma 2.3.5 "Transport over constant families"
definition trans_const {x y : A} (p : x = y) (b : B) :
transport _ p b = b :=
eq.rec_on p (refl b)
-- Lemma 2.3.8 :
definition apd_eq_trans_const_ap {x y : A} (P : A → Type) (f :A → B) (p : x = y) :
apd f p = trans_const p (f x) ⬝ ap f p :=
eq.rec_on p (refl (refl (f x)) )
-- Lemma 2.3.9 "Composition of transport equals composition of their underlying paths" :
definition comp_trans_comp_path {x y z : A} (P : A → Type) (p : x = y) (q : y = z) (u : P x) :
transport P q (transport P p u) = transport P (p ⬝ q) u :=
eq.rec_on q (eq.rec_on p refl u)
-- Lemma 2.3.10 :
definition trans_ap_fun {x y : A} (f : A → B) (P : B → Type) (p : x = y) (u : P (f x)) :
transport (P ∘ f) p u = transport P (ap f p) u :=
eq.rec_on p (refl u)
-- Lemma 2.3.11 :
definition lemma_2_3_11 {x y : A} {P Q : A → Type} (f : Π (x : A), P(x) → Q(x)) (p : x = y) (u : P x) :
transport Q p (f x u) = f y (transport P p u) :=
eq.rec_on p (refl (f x u))
--
/- §2.4 (Homotopies and equivalences) -/
infix `~` := homotopy
-- id is a unit for function composition
definition id_ru (f : A → B) :
f ∘ id A ~ f :=
assume (x : A), refl (f x)
definition id_lu (f : A → B) :
id B ∘ f ~ f :=
assume (x : A), refl (f x)
-- Lemma 2.4.2 "Homotopy is an equivalence relation" :
definition hom_refl (f : A → B) :
f ~ f :=
λ x, (refl (f x))
definition hom_sym {f g : A → B} (H : f ~ g) :
g ~ f :=
λ x, (H x)⁻¹
definition hom_trans {f g h : A → B} (H₁: f ~ g) (H₂: g ~ h) :
f ~ h :=
λ x, (H₁ x) ⬝ (H₂ x)
notation H `⁻¹` := hom_sym H
notation H₁ `~~` H₂ := hom_trans H₁ H₂
-- Lemma 2.4.3 "Homotopies are natural transformations" :
definition hom_ap {x y : A} (f g : A → B) (H : f ~ g) (p : x = y) :
ap f p ⬝ H y = H x ⬝ ap g p :=
eq.rec_on p (lu (H x ⬝ ap g (refl x)))⁻¹
-- Corollary 2.4.4 :
definition lem_hom_ap_id {x : A} (f : A → A) (H : f ~ id A) :
H (f x) ⬝ ap (λ(x : A), x) (H x) = H (f x) ⬝ H x :=
l_whisker (H (f x)) (eq.rec_on (H x) (refl (refl (f x))))
definition hom_ap_id' {x : A} (f : A → A) (H : f ~ id A ) :
H (f x) = ap f (H x) :=
(unwhisker_right (H x) ((hom_ap f (λx : A, x) H (H x)) ⬝ (lem_hom_ap_id f H) ))⁻¹
-- Equivalences
definition qinv {A B : Type} (f : A → B) : Type :=
Σ (g : B → A), (f ∘ g ~ id B) × (g ∘ f ~ id A)
definition id_qinv :
qinv (id A) :=
sigma.mk (id A) (prod.mk (λ x : A, refl x) (λ x : A, refl x))
definition ex_2_4_8 {x y z : A} (p: x = y) :
qinv (λ q : y = z, p ⬝ q) :=
sigma.mk (λ q : x = z, p⁻¹ ⬝ q)
(prod.mk
(λ q : x = z, (conc_assoc p p⁻¹ q) ⬝ (r_whisker q ( right_inv p)) ⬝ (lu q)⁻¹)
(λ q : y = z,(conc_assoc p⁻¹ p q) ⬝ (r_whisker q ( left_inv p)) ⬝ (lu q)⁻¹) )
definition trans_id_right {x y : A}(P : A → Type) (p: x = y) (u : P y) :
transport P (p⁻¹ ⬝ p) u = u :=
eq.rec_on p refl (transport P (refl y) u)
definition trans_id_left {x y : A}(P : A → Type) (p: x = y) (u : P x) :
transport P (p ⬝ p⁻¹) u = u :=
eq.rec_on p refl (transport P (refl x) u)
definition ex_2_4_9 {x y : A} (p: x = y) (P : A → Type) :
qinv (λ u : P x, transport P p u) :=
⟨(λ u : P y, transport P p⁻¹ u), ((λ u : P y, comp_trans_comp_path P p⁻¹ p u ⬝ trans_id_right _ p u),
(λ u : P x, comp_trans_comp_path P p p⁻¹ u ⬝ trans_id_left _ p u) )⟩
-- definition of isequiv
definition isequiv {A B : Type} (f : A → B) : Type :=
( Σ (g : B → A), f ∘ g ~ id B ) × ( Σ (h : B → A), h ∘ f ~ id A )
-- (i) Quasi-inverse → Equivalence
definition qinv_to_isequiv (f : A → B) :
qinv f → isequiv f :=
assume e : qinv f, prod.mk
( sigma.rec_on e (λ(g : B → A) (α : (f ∘ g ~ id B) × (g ∘ f ~ id A) ), ⟨g, pr1 α⟩ ) )
( sigma.rec_on e (λ(h : B → A) (β : (f ∘ h ~ id B) × (h ∘ f ~ id A) ), ⟨h, pr2 β⟩ ) )
-- (ii) Equivalence → Quasi-Inverse
definition hom_r_whisker {f g : B → C} (α : f ~ g) (h : A → B) :
f ∘ h ~ g ∘ h :=
assume (x : A), α (h x)
definition hom_l_whisker (h : B → C) {f g : A → B} (β : f ~ g) :
h ∘ f ~ h ∘ g :=
assume (x : A),
calc
h (f x) = h (f x) : rfl
... = h (g x) : β x
notation α `~ᵣ` h := hom_r_whisker α h
notation h `~ₗ` β := hom_l_whisker h β
definition hom_comp_assoc (f : A → B) (g : B → C) (h : C → D) : h ∘ (g ∘ f) ~ (h ∘ g) ∘ f := -- Superfluous, given univalence
λ (x : A), refl (h (g (f x)))
definition isequiv_to_qinv (f : A → B) :
isequiv f → qinv f :=
assume e : isequiv f, sigma.rec_on (pr1 e) (λ (g : B → A) (α : (f ∘ g ~ id B)),
sigma.rec_on (pr2 e) (λ (h : B → A) (β : (h ∘ f ~ id A)),
have γ : g ~ h, from (β ~ᵣ g ~~ id_lu g)⁻¹ ~~ (h ~ₗ α ~~ id_ru h),
have β' : g ∘ f ~ id A, from assume (x : A), (γ (f x)) ⬝ (β x),
sigma.mk g (α, β') ) )
-- Type Equivalences
definition typeq (A : Type) (B : Type) : Type :=
Σ (f : A → B), isequiv f
notation A `≃` B := typeq A B
-- Lemma 2.4.12 "Type equivalence is an equivalence relation on Type Universes"
definition typeq_refl (A : Type) :
A ≃ A :=
⟨ id A , (prod.mk (sigma.mk (id A) (λ x : A, refl x)) (sigma.mk (id A) (λ x : A, refl x))) ⟩
definition typeq_sym (H : A ≃ B):
B ≃ A :=
sigma.rec_on H (λ (f : A → B) (e : isequiv f),
have e' : qinv f, from (isequiv_to_qinv f) e,
sigma.rec_on e' (λ (g : B → A) (p : (f ∘ g ~ id B) × (g ∘ f ~ id A)),
sigma.mk g (prod.mk (sigma.mk f (pr2 p)) (sigma.mk f (pr1 p))) ) )
notation H `⁻¹` := typeq_sym H
definition typeq_trans (H₁ : A ≃ B) (H₂ : B ≃ C) :
A ≃ C :=
sigma.rec_on H₁ (λ (f : A → B) (e₁ : isequiv f),
sigma.rec_on H₂ (λ (g : B → C) (e₂ : isequiv g),
have e₁' : qinv f, from (isequiv_to_qinv f) e₁,
have e₂' : qinv g, from (isequiv_to_qinv g) e₂,
sigma.rec_on e₁' (λ (f' : B → A) (p₁ : (f ∘ f' ~ id B) × (f' ∘ f ~ id A)),
sigma.rec_on e₂' (λ (g' : C → B) (p₂ : (g ∘ g' ~ id C) × (g' ∘ g ~ id B)),
have q₁ : (g ∘ f) ∘ (f' ∘ g') ~ id C, from
((hom_comp_assoc f' f g) ~ᵣ g')⁻¹ ~~ (((g ~ₗ (pr1 p₁)) ~~ id_ru g) ~ᵣ g') ~~ (pr1 p₂),
have q₂ : (f' ∘ g') ∘ (g ∘ f) ~ id A, from
(f' ~ₗ (hom_comp_assoc f g g')) ~~ (f' ~ₗ (((pr2 p₂) ~ᵣ f) ~~ id_lu f)) ~~ (pr2 p₁),
sigma.mk (g ∘ f) (prod.mk (sigma.mk (f' ∘ g') q₁) (sigma.mk (f' ∘ g') q₂)) ) ) ) )
notation H₁ `∘` H₂ := typeq_trans H₁ H₂
--
/- §2.6 (Cartesian Product Types) -/
definition pair_eq {x y : A × B} :
(pr1 x = pr1 y) × (pr2 x = pr2 y) → x = y :=
by intro s; cases s with p q; cases x with a b; cases y with a' b'; esimp at *; induction p; induction q; apply idp
-- Propositional Computation and Uniqueness rules
definition prod_beta {x y : A × B} (s : (pr1 x = pr1 y) × (pr2 x = pr2 y)) :
(ap pr1 (pair_eq s), ap pr2 (pair_eq s)) = s :=
by cases s with p q; cases x with a b; cases y with a' b'; esimp at *; induction p; induction q; esimp at *
definition prod_uniq {x y : A × B} (r : x = y) :
pair_eq (ap pr1 r, ap pr2 r) = r :=
by induction r; cases x; apply idp
-- Alternative versions for prod_beta
definition prod_beta1 {x y : A × B} (s : (pr1 x = pr1 y) × (pr2 x = pr2 y)) :
ap pr1 (pair_eq s) = pr1 s :=
by cases s with p q; cases x with a b; cases y with a' b';
esimp at *; induction p; induction q; reflexivity
definition prod_beta2 {x y : A × B} (s : (pr1 x = pr1 y) × (pr2 x = pr2 y)) :
ap pr2 (pair_eq s) = pr2 s :=
by cases s with p q; cases x with a b; cases y with a' b';
esimp at *; induction p; induction q; reflexivity
-- Theorem 2.6.2
definition pair_equiv {x y : A × B} :
x = y ≃ (pr1 x = pr1 y) × (pr2 x = pr2 y) :=
⟨ (λ x, (ap pr1 x, ap pr2 x)), ( ⟨pair_eq, λ s, prod_beta s⟩, ⟨pair_eq, λ r, prod_uniq r⟩ ) ⟩
-- Higher Groupoid Structure
definition prod_refl {z : A × B} :
refl z = pair_eq ( ap pr1 (refl z), ap pr2 (refl z)) :=
by cases z; apply idp
definition prod_inv {x y : A × B} (p : x = y) :
p⁻¹ = pair_eq ( ap pr1 (p⁻¹), ap pr2 (p⁻¹)) :=
by induction p; cases x; apply idp
definition prod_comp {x y z: A × B} (p : x = y) (q : y = z):
p ⬝ q = pair_eq ( ap pr1 p, ap pr2 p) ⬝ pair_eq ( ap pr1 q, ap pr2 q) :=
by induction p; induction q; cases x with a b; apply idp
-- Theorem 2.6.4
definition trans_prod {z w : Z} (A B: Z → Type) (p : z = w) (x : A z × B z) :
transport (λ z, A z × B z) p x = (transport A p (pr1 x), transport B p (pr2 x)) :=
eq.rec_on p (uppt x)
-- Theorem 2.6.5
definition func_prod {A' B' : Type} (g : A → A') (h : B → B') : -- g and h induces a func_prod
A × B → A' × B' :=
λ (x : A × B), (g(pr1 x), h(pr2 x))
definition prod_ap_func {x y : A × B} {A' B' : Type} (g : A → A') (h : B → B') (p : pr1 x = pr1 y) (q : pr2 x = pr2 y):
ap (func_prod g h) (pair_eq (p,q)) = pair_eq (ap g(p), ap h(q)) :=
prod.rec_on x (λ a b , prod.rec_on y (λ a' b' p, eq.rec_on p (λ q, eq.rec_on q idp ))) p q
--
/- §2.7 (Sigma Types) -/
definition ap_sigma {P : A → Type} {w w' : Σ (x:A), P x} :
w = w' → ⟨Σ (p : pr1 w = pr1 w'), transport P p (pr2 w) = pr2 w'⟩ :=
by intro r; induction r; cases w with w1 w2; esimp at *; fapply sigma.mk; exact refl w1; apply idp
definition sigma_eq {P : A → Type} {w w' : Σ (x:A), P x} :
⟨Σ (p : pr1 w = pr1 w'), transport P p (pr2 w) = pr2 w'⟩ → w = w' :=
by intro s; cases w; cases w'; cases s with p q; esimp at *; induction p; induction q; apply idp
-- Propositional Computation and Uniqueness rules
definition sigma_comp {P : A → Type} {w w' : Σ (x:A), P x} (r : Σ (p : pr1 w = pr1 w'), transport P p (pr2 w) = pr2 w'):
ap_sigma (sigma_eq r) = r :=
by cases w with w1 w2; cases w' with w1' w2'; cases r with p q; esimp at *; induction p; induction q; apply idp
definition sigma_uniq {P : A → Type} {w w' : Σ (x:A), P x} (p : w = w'):
sigma_eq (ap_sigma p) = p :=
by induction p; cases w; apply idp
-- Theorem 2.7.2
definition sigma_equiv {P : A → Type} {w w' : Σ (x:A), P x} :
w = w' ≃ Σ (p : pr1 w = pr1 w'), transport P p (pr2 w) = pr2 w' :=
⟨ ap_sigma, ( ⟨sigma_eq, λ s, sigma_comp s⟩, ⟨sigma_eq, λ r, sigma_uniq r⟩ ) ⟩
-- Corollary 2.7.3
definition eta_sigma {P : A → Type} (z : Σ (x : A), P x) :
z = ⟨pr1 z, pr2 z⟩ :=
by cases z; esimp at *
-- Theorem 2.7.4
definition sigma_trans {P : A → Type} {Q : (Σ (x : A), P x) → Type} {x y : A} (p : x = y) (u : P x) (z : Q ⟨x, u⟩) :
transport (λ x, (Σ (u : P x), Q ⟨x, u⟩)) p ⟨u,z⟩ = ⟨transport P p u, transport Q (sigma_eq ⟨p, refl (transport P p u)⟩) z⟩ :=
by induction p; apply refl ⟨u,z⟩
-- Higher Groupoid Structure
definition sigma_refl {P : A → Type} {z : Σ (x : A), P x} :
refl z = sigma_eq ⟨ ap pr1 (refl z), refl (transport P (ap pr1 (refl z)) (pr2 z)) ⟩ :=
by cases z; apply idp
definition sigma_inv {P : A → Type} {x y : Σ (x : A), P x} (p : x = y) :
p⁻¹ = (sigma_eq (ap_sigma p⁻¹)) :=
by induction p; cases x; apply idp
definition sigma_com {P : A → Type} {x y z: Σ (x : A), P x} (p : x = y) (q : y = z):
p ⬝ q = sigma_eq (ap_sigma (p ⬝ q)) :=
by induction p; induction q; cases x; apply idp
--
/- §2.8 (Unit Types) -/
open unit
notation `⋆` := star
definition eq_star {x y : unit} :
(x = y) → unit :=
λ (p : x = y), ⋆
definition unit_eq {x y : unit} :
unit → (x = y) :=
λ u: unit, unit.rec_on x ( unit.rec_on y (refl ⋆))
-- Theorem 2.8.1.
definition unit_equiv {x y : unit} :
x = y ≃ unit :=
have comp_rule : eq_star ∘ unit_eq ~ id unit, from λ u : unit, unit.rec_on u (refl ⋆),
have uniq_rule : unit_eq ∘ eq_star ~ id (x = y), from λ (p : x = y), unit.rec_on x (unit.rec_on y (λ p, eq.rec_on p (refl (refl ⋆)) ) ) p,
⟨ eq_star, ( ⟨unit_eq, comp_rule⟩, ⟨unit_eq, uniq_rule⟩ ) ⟩
-- Higher Groupoid Structure
definition unit_refl {u : unit} :
refl u = unit_eq (eq_star (refl u)) :=
by cases u; apply refl (refl ⋆)
definition unit_inv {x y : unit} (p : x = y) :
p⁻¹ = unit_eq (eq_star (p⁻¹)) :=
by induction p; cases x; apply refl (refl ⋆)
definition unit_comp {x y z: unit} (p : x = y) (q : y = z) :
p ⬝ q = @unit_eq x y (eq_star (p)) ⬝ unit_eq (eq_star (q)) :=
by induction p; induction q; cases x; apply refl (refl ⋆)
--
/- §2.9 (Π-types and the function extensionality axiom) -/
namespace funext
definition happly {A : Type} {B : A → Type} {f g: Π (x : A), B x} :
f = g → Π x : A, f x = g x :=
λ p x, eq.rec_on p (refl (f x))
axiom fun_extensionality {A : Type} {B : A → Type} {f g: Π (x : A), B x} :
isequiv (@happly A B f g)
definition funext [reducible] {A : Type} {B : A → Type} {f g: Π (x : A), B x} :
(Π x : A, f x = g x) → f = g :=
by cases fun_extensionality with p q; cases p with funext comp; exact funext
-- Propositional Computational and Uniqueness rules
definition funext_comp {A : Type} {B : A → Type} {f g: Π (x : A), B x} (h : Π x : A, f x = g x) :
happly (funext h) = h :=
by unfold [happly,funext]; cases @fun_extensionality A B f g with p q; cases p with funxet' comprule; exact (comprule h)
definition funext_uniq {A : Type} {B : A → Type} {f g: Π (x : A), B x} (p : f = g) :
funext (happly p) = p :=
begin
cases @fun_extensionality A B f g with α β, cases β with funext' uniqrule,
apply ((show funext (happly p) = funext' (happly p), from calc
funext (happly p) = funext' (happly (funext (happly p))) : uniqrule (funext (happly p))
... = funext' (happly p) : funext_comp)
⬝ uniqrule p)
end
-- Higher Groupoid Structure
definition pi_refl {A : Type} {B : A → Type} {f : Π (x : A), B x} :
refl f = funext (λ x, (refl (f x))) :=
(funext_uniq (refl f))⁻¹
definition pi_inv {A : Type} {B : A → Type} {f g : Π (x : A), B x} (p : f = g) :
p⁻¹ = (funext (λ x, (happly p x)⁻¹)) :=
by induction p; apply (funext_uniq (refl f))⁻¹
definition pi_comp {A : Type} {B : A → Type} {f g h: Π (x : A), B x} (p : f = g) (q : g = h) :
p ⬝ q = (funext (λ x, (happly p x) ⬝ (happly q x))) :=
by induction p; induction q; apply (funext_uniq idp)⁻¹
-- Transporting non-dependent and dependent functions
definition nondep_trans_pi {X : Type} {A B : X → Type} {x₁ x₂ : X} (p : x₁ = x₂) (f : A x₁ → B x₁) :
transport (λ (x₁ : X), (A x₁) → (B x₁)) p f = (λ x, transport B p (f (transport A p⁻¹ x))) :=
eq.rec (refl f) p
definition trans_pi {X : Type} {A : X → Type} {B : Π (x : X), (A x → Type)} {x₁ x₂ : X} (p : x₁ = x₂) (f : Π (a : A x₁), B x₁ a) (a : A x₂) :
(transport (λ (x₁ : X), (Π (a : A x₁), (B x₁ a))) p f) a =
transport (λ (w : Σ (x : X), A x), B (pr1 w) (pr2 w)) (sigma_eq ⟨p⁻¹, refl (transport A p⁻¹ a)⟩)⁻¹ (f (transport A p⁻¹ a)) :=
by induction p; apply idp
-- Lemma 2.9.6
definition nondep_eq {X : Type} {A B : X → Type} {x y : X} (p : x = y) (f : A x → B x) (g : A y → B y):
(transport (λ x, A x → B x) p f = g) ≃ (Π (a : A x), (transport B p (f a)) = g (transport A p a)) :=
by induction p; fapply sigma.mk; exact happly; apply fun_extensionality
-- Lemma 2.9.7
definition dep_eq {X : Type} {A : X → Type} {B : Π (x : X), (A x → Type)} {x y : X} (p : x = y) (f : Π (a : A x), B x a)
(g : Π (a : A y), B y a) (a : A y) :
(transport (λ (x₁ : X), (Π (a : A x₁), (B x₁ a))) p f = g) ≃
(Π (a : A x), transport (λ (w : Σ (x : X), A x), B (pr1 w) (pr2 w)) (sigma_eq ⟨p, refl (transport A p a)⟩) (f a) = g (transport A p a)) :=
by induction p; fapply sigma.mk; exact happly; apply fun_extensionality
end funext
--
/- §2.10 (Universes and the Univalence axiom) -/
namespace ua
universe variables i j
definition idtoeqv {A B : Type.{i}} :
(A = B) → (A ≃ B) :=
λ (p : A = B), eq.rec_on p ⟨id A, (qinv_to_isequiv (id A) (id_qinv))⟩
axiom univalence {A B : Type.{i}}:
isequiv (@idtoeqv A B)
definition ua [reducible] {A B: Type.{i}} :
(A ≃ B) → (A = B) :=
by cases univalence with p q; cases p with ua comp_rule; exact ua
-- Propositional and Computational rules
definition ua_comp {A B: Type.{i}} (e : A ≃ B):
idtoeqv (ua e) = e :=
by unfold [idtoeqv,ua]; cases @univalence A B with p q; cases p with ua' comprule; exact (comprule e)
definition ua_uniq {A B: Type.{i}} (p : A = B):
ua (idtoeqv p) = p :=
begin
cases @univalence A B with α β, cases β with ua' uniqrule,
apply ((show ua (idtoeqv p) = ua' (idtoeqv p), from calc
ua (idtoeqv p) = ua' (idtoeqv (ua (idtoeqv p))) : uniqrule (ua (idtoeqv p))
... = ua' (idtoeqv p) : ua_comp)
⬝ uniqrule p)
end
-- Higher Groupoid Structure
definition ua_refl :
refl A = ua (typeq_refl A) :=
(ua_uniq _)⁻¹ ⬝ ((ua_uniq _)⁻¹ ⬝ (ap ua ((ua_comp (typeq_refl A)) ⬝ idp)))⁻¹
definition ua_inv {A B: Type.{i}} (f : A ≃ B) :
(ua f)⁻¹ = ua (f⁻¹) :=
calc
(ua f)⁻¹ = ua (idtoeqv (ua f)⁻¹) : ua_uniq
... = ua (idtoeqv (ua f))⁻¹ : eq.rec_on (ua f) idp
... = ua (f⁻¹) : ua_comp f
definition ua_com {A B C: Type.{i}} (f : A ≃ B) (g : B ≃ C) :
ua f ⬝ ua g = ua (f ∘ g) :=
calc
ua f ⬝ ua g = ua (idtoeqv ((ua f) ⬝ (ua g))) : ua_uniq
... = ua ((idtoeqv (ua f)) ∘ (idtoeqv (ua g))) : begin induction (ua f), induction (ua g), esimp end
... = ua ((idtoeqv (ua f)) ∘ g ) : ua_comp
... = ua (f ∘ g) : ua_comp
-- Lemma 2.10.5
definition trans_univ {A : Type} {B : A → Type} {x y : A} (p : x = y) (u : B x) :
transport B p u = transport (λ (X : Type), X) (ap B p) u :=
by induction p; apply idp
definition trans_idtoequiv {A : Type} {B : A → Type} {x y : A} (p : x = y) (u : B x) :
transport (λ (X : Type), X) (ap B p) u = pr1 (idtoeqv (ap B p)) u :=
by induction p; apply idp
end ua
--
/- §2.11 (Identity type) -/
-- Theorem 2.11.1
open funext
definition id_eq {a a' : A} (f : A → B) (h : isequiv f) :
isequiv (@ap A B a a' f ) :=
have h' : qinv f, from (isequiv_to_qinv f) h,
sigma.rec_on h'
(λ finv p, prod.rec_on p (λ α β,
have α' : (Π (q : f a = f a'), ap f((β a)⁻¹ ⬝ ap finv q ⬝ β a') = q), from λ (q : f a = f a'), -- book suggs. lemmas 2.2.2 and 2.4.3
calc
ap f((β a)⁻¹ ⬝ ap finv q ⬝ β a') = ap f((β a)⁻¹ ⬝ ap finv q ⬝ β a') : idp
--... = ((α (f a))⁻¹ ⬝ (α (f a))) ⬝ ap f (β a)⁻¹ ⬝ ap f (ap finv q ⬝ β a') :
--... = ((α (f a))⁻¹ ⬝ (α (f a))) ⬝ ap f (β a)⁻¹ ⬝ ap f (ap finv q ⬝ β a') ⬝ ((α (f a'))⁻¹ ⬝ (α (f a'))) : (refl (refl _))
--... = ap f ((β a)⁻¹ ⬝ (ap finv q ⬝ β a')) : (path_inv (conc_assoc (path_inv (β a)) (ap finv q) (β a')))
... = ap f ((β a)⁻¹ ⬝ ap finv q) ⬝ ap f (β a') : ap_func_i f _ _
... = ap f (β a)⁻¹ ⬝ ap f (ap finv q) ⬝ ap f (β a') : (ap_func_i f _ _) ⬝ᵣ ap f (β a')
--... = ap f (β a)⁻¹ ⬝ ap (f ∘ finv) q ⬝ ap f (β a') : ap_func_iii finv f q
--... = ap f (β a)⁻¹ ⬝ ap (id B) q ⬝ ap f (β a') : α
... = q : sorry , -- don't erase this comma!
have β' : (Π (p : a = a'), (β a)⁻¹ ⬝ ap finv (ap f p) ⬝ β a' = p), from -- right inverse
λ (p : a = a'), eq.rec_on p (eq.rec_on (β a) (refl (refl (finv (f a)))) ),
qinv_to_isequiv (ap f) ⟨λ q, (β a)⁻¹ ⬝ ap finv q ⬝ β a', (α',β')⟩))
definition path_pair {w w' : A × B} (p q : w = w') :
p = q ≃ (ap pr1 p = ap pr1 q) × (ap pr2 p = ap pr2 q) :=
typeq_trans ⟨ap (λ x, (ap pr1 x, ap pr2 x)) , id_eq _ ( ⟨pair_eq, λ s, prod_beta s⟩, ⟨pair_eq, λ r, prod_uniq r⟩ ) ⟩ pair_equiv
definition path_sigma {B : A → Type} {w w' : Σ (x : A), B x} (p q : w = w') :
(p = q) ≃ (Σ (r : pr1 (ap_sigma p) = pr1 (ap_sigma q)), transport (λ (s : pr1 w = pr1 w'), transport B s (pr2 w) = pr2 w')
r (pr2 (ap_sigma p)) = pr2 (ap_sigma q)) :=
typeq_trans ⟨ap ap_sigma , id_eq ap_sigma ( ⟨sigma_eq, λ s, sigma_comp s⟩, ⟨sigma_eq, λ r, sigma_uniq r⟩ )⟩ sigma_equiv
definition path_funext {B : A → Type} {f g: Π (x : A), B x} {p q : f = g} :
p = q ≃ Π (x : A), (happly p x = happly q x) :=
typeq_trans ⟨ap happly, id_eq happly fun_extensionality ⟩ ⟨happly, fun_extensionality⟩
-- Lemma 2.11.2
definition id_trans_i {x₁ x₂ : A} (a : A) (p : x₁ = x₂) (q : a = x₁):
transport (λ x, a = x) p q = q ⬝ p :=
by induction p; induction q; apply refl (refl a)
definition id_trans_ii {x₁ x₂ : A} (a : A) (p : x₁ = x₂) (q : x₁ = a):
transport (λ x, x = a) p q = p⁻¹ ⬝ q :=
by induction p; induction q; apply refl (refl x₁)
definition id_trans_iii {x₁ x₂ : A} (p : x₁ = x₂) (q : x₁ = x₁):
transport (λ x, x = x) p q = p⁻¹ ⬝ q ⬝ p :=
eq.rec_on p (calc
transport (λ x, x = x) (refl x₁) q = q : idp
... = (refl x₁)⁻¹ ⬝ q : lu
... = ((refl x₁)⁻¹ ⬝ q) ⬝ (refl x₁) : ru )
-- Theorem 2.11.3 (More general form of the previous lemma iii)
definition id_trans_fun {a a' : A} (f g : A → B) (p : a = a') (q : f (a) = g (a)):
transport (λ x, f x = g x) p q = (ap f p)⁻¹ ⬝ q ⬝ (ap g p) :=
eq.rec_on p (calc
transport (λ x, f x = g x) (refl a) q = q : idp
... = (refl (f a))⁻¹ ⬝ q : lu
... = ((refl (f a))⁻¹ ⬝ q) ⬝ (refl (g a)) : ru )
-- Theorem 2.11.4 (Dependent version of the previous theorem)
definition id_trans_dfun {a a' : A} {B : A → Type} (f g : Π (x : A), B x) (p : a = a') (q : f (a) = g (a)) :
transport (λ x, f x = g x) p q = (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) :=
eq.rec_on p (calc
transport (λ x, f x = g x) (refl a) q = q : idp
... = ap (transport B (refl a)) q : (λ x y (q : x = y), eq.rec_on q (refl (refl x))) (f a) (g a) q
... = (refl (f a))⁻¹ ⬝ ap (transport B (refl a)) q : lu
... = ((refl (f a))⁻¹ ⬝ ap (transport B (refl a)) q) ⬝ (refl (g a)) : ru )
-- Theorem 2.11.5
definition id_trans_equiv {a a' : A} (p : a = a') (q : a = a) (r : a' = a'):
(transport (λ x, x = x) p q = r) ≃ (q ⬝ p = p ⬝ r) :=
by induction p; apply ua.idtoeqv; exact (calc
(transport (λ x, x = x) (refl a) q = r) = (q ⬝ refl a = r) : idp
... = (q ⬝ refl a = refl a ⬝ r) : lu )
--
/- §2.12 (Coproducts) -/
section coproduct
universe variables i j parameters {A' : Type.{i}} {B' : Type.{j}} {a₀ : A'}
definition code : --{A : Type.{i}} {B : Type.{j}} {a₀ : A} :
A' + B' → Type
| code (inl a) := (a₀ = a)
| code (inr b) := lift empty
definition encode : Π (x : A' + B') (p : inl (a₀) = x), code x
| encode x p := transport code p (refl a₀)
definition decode (x : A' + B') (c : code x) : inl (a₀) = x :=
by cases x with l r; exact ap inl (c); exact (empty.rec_on _ (down c))
-- Propositional Computation and Uniqueness rules
definition sum_uniq (x : A' + B') (p : inl (a₀) = x) :
decode x (encode x p) = p :=
by induction p; apply idp
definition sum_beta (x : A' + B') (c : code x) :
encode x (decode x c) = c :=
by cases x; exact (calc
encode (inl a) (decode (inl a) c) = transport code (ap inl (c)) (refl a₀) : idp
... = transport (code ∘ inl) (c) (refl a₀) : (trans_ap_fun inl code (c) (refl a₀))⁻¹
... = transport (λ a : A', (a₀ = a)) (c) (refl a₀) : idp
... = (refl a₀) ⬝ (c) : id_trans_i -- check lean's library
... = c : lu );
exact (empty.rec_on _ (down c))
-- Theorem 2.12.5
definition sum_equiv (x : A' + B') :
(inl a₀ = x) ≃ code x :=
⟨ encode x, ( ⟨decode x, sum_beta x⟩, ⟨decode x, sum_uniq x⟩ ) ⟩
definition inl_eq (a₁ : A') :
(inl a₀ = inl a₁ ) ≃ (a₀ = a₁) :=
code_equiv (inl a₁)
definition inl_inr_neq (a₁ : B') :
(inl a₀ = inr a₁ ) ≃ lift empty :=
code_equiv (inr a₁)
-- Remark 2.12.6
definition bool_eq_unit_unit :
𝟮 ≃ 𝟭 + 𝟭 :=
⟨λ (b : 𝟮), bool.rec_on b (inl ⋆) (inr ⋆),
(⟨(λ (w : 𝟭 + 𝟭), sum.rec_on w (λ u, ff) (λ u, tt)), begin intro u, cases u, cases a, reflexivity, cases a, reflexivity end⟩,
⟨(λ (w : 𝟭 + 𝟭), sum.rec_on w (λ u, ff) (λ u, tt)), begin intro b, cases b, reflexivity, reflexivity end⟩) ⟩
-- Transport of coproducts
definition trans_inl {X : Type} {A B : X → Type} {x₁ x₂ : X} (p : x₁ = x₂) (a : A x₁) :
transport (λ x, A x + B x) p (inl a) = inl (transport A p a) :=
by induction p; apply (refl (inl a))
definition trans_inr {X : Type} {A B : X → Type} {x₁ x₂ : X} (p : x₁ = x₂) (b : B x₁) :
transport (λ x, A x + B x) p (inr b) = inr (transport B p b) :=
by induction p; apply (refl (inr b))
end coproduct
--
/- §2.13 (Natural numbers) -/
open nat
definition natcode [reducible] :
ℕ → ℕ → Type₀
| natcode 0 0 := unit
| natcode (succ m) 0 := empty
| natcode 0 (succ n) := empty
| natcode (succ m) (succ n) := natcode m n
definition r : Π (n : ℕ), natcode n n
| r 0 := ⋆
| r (succ n) := r n
definition natencode (m n : ℕ) :
(m = n) → natcode m n :=
λ p, transport (natcode m) p (r m)
definition natdecode : Π (m n : ℕ), natcode m n → (m = n)
| natdecode 0 0 c := refl 0
| natdecode (succ i) 0 c := empty.rec_on _ c
| natdecode 0 (succ j) c := empty.rec_on _ c
| natdecode (succ i) (succ j) c := ap succ (natdecode i j c)
-- Propositional Computation and Uniqueness rules
definition nat_comp : Π (m n : ℕ) (c : natcode m n),
natencode (natdecode m n c) = c
| nat_comp 0 0 c := @unit_eq (r 0) c c
| nat_comp (succ i) 0 c := empty.rec_on _ c
| nat_comp 0 (succ j) c := empty.rec_on _ c
| nat_comp (succ i) (succ j) c := calc
natencode (natdecode (succ i) (succ j) c) = transport (natcode (succ i)) (ap succ (natdecode i j c)) (r (succ i)) : idp
... = transport (λ x, natcode (succ i) (succ x)) (natdecode i j c) (r (succ i)) : trans_ap_fun
... = natencode (natdecode i j c) : idp
... = c : nat_comp i j
definition nat_uniq {m n : ℕ} (p : m = n) :
natdecode m n (natencode p) = p :=
by induction p; unfold natencode; induction m with m IH; reflexivity; rewrite [↑natdecode,↑r,IH]
-- Theorem 2.13.1 (Nat is equivalent to its encoding)
definition nat_eq (m n : ℕ) :
(m = n) ≃ natcode m n :=
⟨natencode, ( ⟨natdecode m n, nat_comp m n⟩, ⟨natdecode m n, nat_uniq⟩ ) ⟩
--
/- §2.14 (Example: equality of structures) -/
open ua
definition semigroupStr (A : Type) : Type :=
Σ (m : A → A → A), Π (x y z : A), m x (m y z) = m (m x y) z
definition semigroup : Type :=
Σ (A : Type), semigroupStr A
-- §2.14.1 Lifting Equivalences
universe variables i j
example {A B : Type.{i}} (e : A ≃ B) (g : semigroupStr A) : semigroupStr B :=
transport semigroupStr (ua e) g
/- §2.15 (Universal Properties) -/
-- Product type satisfies the expected universal property
definition upprod {X : Type} :
(X → A × B) → ((X → A) × (X → B)) :=
λ u, (λ x, pr1 (u x) , λ x, pr2 (u x) )
-- Theorem 2.15.2
definition upprod_eq {X : Type} :
(X → A × B) ≃ (X → A) × (X → B) :=
let prodinv := λ fg, λ x, ((pr1 fg) x, (pr2 fg) x) in
have comp_rule : upprod ∘ prodinv ~ id _, from begin intro x, cases x with f g, reflexivity end,
have uniq_rule : Π h, prodinv (upprod h) = h, from begin intro h, unfold upprod,
apply funext, intro x, cases (h x) with a b, esimp end,
⟨upprod, (⟨prodinv, comp_rule⟩, ⟨prodinv, uniq_rule⟩)⟩
-- Theorem 2.15.5 (Dependent version of the UP)
definition dupprod {X : Type} {A B : X → Type} :
(Π (x : X), A x × B x) → ((Π (x : X), A x) × (Π (x : X), B x)) :=
λ u, (λ x, pr1 (u x) , λ x, pr2 (u x) )
definition dupprod_eq {X : Type} {A B : X → Type} :
(Π (x : X), A x × B x) ≃ ((Π (x : X), A x) × (Π (x : X), B x)) :=
let dprodinv := λ fg, λ x, ((pr1 fg) x, (pr2 fg) x) in
have comp_rule : dupprod ∘ dprodinv ~ id _, from begin intro x, cases x with f g, reflexivity end,
have uniq_rule : Π h, dprodinv (dupprod h) = h, from begin intro h, unfold dupprod,
apply funext, intro x, cases (h x) with a b, esimp end,
⟨dupprod, (⟨dprodinv, comp_rule⟩, ⟨dprodinv, uniq_rule⟩)⟩
-- Theorem 2.15.7 (Sigma type satisfies the expected universal property )
-- Non-dependent case
definition upsig {X : Type} {P : A → Type} :
(X → (Σ (a : A), P a)) → (Σ (g : X → A), (Π (x : X), P (g x))) :=
λ f, ⟨ λ x, pr1 (f x), λ x, sigma.rec_on (f x) (λ w1 w2, w2) ⟩
definition upsig_eq {X : Type} {P : A → Type} :
(X → (Σ (a : A), P a)) ≃ (Σ (g : X → A), (Π (x : X), P (g x))) :=
let invupsig := λ w x, sigma.rec_on w (λ w1 w2, ⟨ w1 x, w2 x⟩) in
have comp_rule : Π w, upsig (invupsig w) = w, from begin intro w, cases w with w1 w2, apply idp end,
have uniq_rule : Π f, invupsig (upsig f) = f, from begin intro f, apply funext, intro x,
unfold upsig, cases (f x) with w1 w2, esimp end,
⟨upsig, (⟨invupsig, comp_rule⟩, ⟨invupsig, uniq_rule⟩)⟩
-- Dependent case (with basically the same proof)
definition dupsig {X : Type} {A : X → Type} {P : Π (x : X), A x → Type} :
(Π (x : X), (Σ (a : A x), P x a)) → (Σ (g : Π (x : X), A x), (Π (x : X), P x (g x))) :=
λ f, ⟨ λ x, pr1 (f x), λ x, sigma.rec_on (f x) (λ w1 w2, w2) ⟩
definition dupsig_eq {X : Type} {A : X → Type} {P : Π (x : X), A x → Type} :
(Π (x : X), (Σ (a : A x), P x a)) ≃ (Σ (g : Π (x : X), A x), (Π (x : X), P x (g x))) :=
let qinv := λ w x, sigma.rec_on w (λ w1 w2, ⟨ w1 x, w2 x⟩) in
have α : Π w, dupsig (qinv w) = w, from begin intro w, cases w with w1 w2, apply idp end,
have β : Π f, qinv (dupsig f) = f, from begin intro f, apply funext, intro x,
unfold dupsig, cases (f x) with w1 w2, esimp end,
⟨dupsig, (⟨qinv, α⟩, ⟨qinv, β⟩)⟩
-- Product type and the "mapping out" universal property
definition ccadj :
(A × B → C) → (A → (B → C)) :=
λ f a b, f (a,b)
definition ccadj_eq :
(A × B → C) ≃ (A → (B → C)) :=
let qinv := λ g p, (g (pr1 p)) (pr2 p) in
have α : ccadj ∘ qinv ~ id (A → (B → C)), from λ g, idp,
have β : Π (f : A × B → C), qinv (ccadj f)= f, from begin intro f, apply funext, intro x, apply (ap f (uppt x)⁻¹) end,
⟨ccadj, (⟨qinv, α⟩, ⟨qinv, β⟩)⟩
-- Dependent version
definition dccadj {C : A × B → Type} :
(Π (w : A × B), C w) → (Π (a : A) (b : B), C (a,b)) :=
λ f a b, f (a,b)
definition dccadj_eq {C : A × B → Type} :
(Π (w : A × B), C w) ≃ (Π (a : A) (b : B), C (a,b)) :=
let qinv := λ g w, prod.rec_on w (λ a b, g a b ) in
have α : dccadj ∘ qinv ~ id _, from λ g, idp,
have β : Π f, qinv (dccadj f)= f, from begin intro f, apply funext, intro x,
cases x with a b, reflexivity end, ⟨dccadj, (⟨qinv, α⟩, ⟨qinv, β⟩)⟩
-- Sigma types "mapping out" dependent UP
definition sigccadj {B : A → Type} {C : (Σ (x : A), B x) → Type}:
(Π (w : Σ (x : A), B x), C w) → (Π (x : A) (y : B x), C ⟨x,y⟩) :=
λ f x y, f ⟨x,y⟩
definition sigccadj_eq {B : A → Type} {C : (Σ (x : A), B x) → Type}:
(Π (w : Σ (x : A), B x), C w) ≃ (Π (x : A) (y : B x), C ⟨x,y⟩) :=
let qinv := λ g w, sigma.rec_on w (λ x y, g x y ) in
have α : sigccadj ∘ qinv ~ id _, from λ g, idp,
have β : Π f, qinv (sigccadj f)= f, from begin intro f, apply funext, intro x,
cases x with a b, reflexivity end, ⟨sigccadj, (⟨qinv, α⟩, ⟨qinv, β⟩)⟩
-- Path induction is part of "mapping out" UP of identity types
definition pathind_inv {a : A} {B : Π (x : A), a = x → Type} :
(Π (x : A) (p : a = x), B x p) → B a (refl a) :=
λ f, f a (refl a)
definition pathind_eq {a : A} {B : Π (x : A), a = x → Type} :
(Π (x : A) (p : a = x), B x p) ≃ B a (refl a) :=
let pathind := λ g x p, eq.rec_on p g in
have α : pathind_inv ∘ pathind ~ id _, from λ g, idp,
have β : Π f, pathind (pathind_inv f)= f, from begin intro f, apply funext,
intro x, apply funext, intro x_1, induction x_1, reflexivity end,
⟨pathind_inv, (⟨pathind, α⟩, ⟨pathind, β⟩)⟩
--
/- Selected Exercises -/
-- Exercise 2.10 (required later in 4.1.1)
definition sigma_assoc (B : A → Type) (C : (Σ (x : A), B x) → Type) :
(Σ (x : A) (y : B x), C ⟨x,y⟩) ≃ (Σ (p : Σ (x : A), B x), C p) :=
let sigma_f := λ w, ⟨⟨pr1 w, pr1 (pr2 w)⟩, pr2 (pr2 w)⟩ in
let sigma_g := λ h, sigma.rec_on h (λ h1 h2, sigma.rec_on h1 (λ w1 w2 h2 , ⟨w1,⟨w2,h2⟩⟩ ) h2) in
have η : Π (h : Σ (p : Σ (x : A), B x), C p), sigma_f (sigma_g h) = h, from
begin intro h, cases h with h1 h2, cases h1 with w1 w2, reflexivity end,
have ε : Π (w : Σ (x : A) (y : B x), C ⟨x,y⟩), sigma_g (sigma_f w) = w, from
begin intro h, cases h with h1 h2, cases h2 with w1 w2, reflexivity end,
⟨sigma_f, (⟨sigma_g,η⟩,⟨sigma_g,ε⟩)⟩
-- Exercise 2.14
-- Let p : x = y, then x ≡ y and p = refl x is a well-formed type.
-- But by induction, it suffices to assume that p is refl x.
-- Then refl(refl x) is a proof of p = refl x.
--
|
3ecefc9c79432777c4b5755f68236a29723bb8ad | 46125763b4dbf50619e8846a1371029346f4c3db | /src/data/real/basic.lean | d2f8f3bf29da9283cc7e101d23cb735f44a23bc8 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 25,898 | 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
The (classical) real numbers ℝ. This is a direct construction
from Cauchy sequences.
-/
import order.conditionally_complete_lattice data.real.cau_seq_completion
algebra.archimedean order.bounds
def real := @cau_seq.completion.Cauchy ℚ _ _ _ abs _
notation `ℝ` := real
namespace real
open cau_seq cau_seq.completion
variables {x y : ℝ}
def of_rat (x : ℚ) : ℝ := of_rat x
def mk (x : cau_seq ℚ abs) : ℝ := cau_seq.completion.mk x
def comm_ring_aux : comm_ring ℝ := cau_seq.completion.comm_ring
instance : comm_ring ℝ := { ..comm_ring_aux }
/- Extra instances to short-circuit type class resolution -/
instance : ring ℝ := by apply_instance
instance : comm_semiring ℝ := by apply_instance
instance : semiring ℝ := 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⟩
theorem of_rat_sub (x y : ℚ) : of_rat (x - y) = of_rat x - of_rat y :=
congr_arg mk (const_sub _ _)
instance : has_lt ℝ :=
⟨λ 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))⟩⟩
@[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := iff.rfl
theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := mk_eq
theorem quotient_mk_eq_mk (f : cau_seq ℚ abs) : ⟦f⟧ = mk f := rfl
theorem mk_eq_mk {f : cau_seq ℚ abs} : cau_seq.completion.mk f = mk f := rfl
@[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f :=
iff_of_eq (congr_arg pos (sub_zero f))
protected def le (x y : ℝ) : Prop := x < y ∨ x = y
instance : has_le ℝ := ⟨real.le⟩
@[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g :=
or_congr iff.rfl quotient.eq
theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b :=
quotient.induction_on₃ a b c (λ f g h,
iff_of_eq (congr_arg pos $ by rw add_sub_add_left_eq_sub))
instance : linear_order ℝ :=
{ le := (≤), lt := (<),
le_refl := λ a, or.inr rfl,
le_trans := λ a b c, quotient.induction_on₃ a b c $
λ f g h, by simpa [quotient_mk_eq_mk] using le_trans,
lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [quotient_mk_eq_mk] using lt_iff_le_not_le,
le_antisymm := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [mk_eq, quotient_mk_eq_mk] using @cau_seq.le_antisymm _ _ f g,
le_total := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [quotient_mk_eq_mk] using le_total f g }
instance : partial_order ℝ := by apply_instance
instance : preorder ℝ := by apply_instance
theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := const_lt
protected theorem zero_lt_one : (0 : ℝ) < 1 := of_rat_lt.2 zero_lt_one
protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b :=
quotient.induction_on₂ a b $ λ f g,
show pos (f - 0) → pos (g - 0) → pos (f * g - 0),
by simpa using cau_seq.mul_pos
instance : linear_ordered_comm_ring ℝ :=
{ add_le_add_left := λ a b h c,
(le_iff_le_iff_lt_iff_lt.2 $ real.add_lt_add_iff_left c).2 h,
zero_ne_one := ne_of_lt real.zero_lt_one,
mul_nonneg := λ a b a0 b0,
match a0, b0 with
| or.inl a0, or.inl b0 := le_of_lt (real.mul_pos a0 b0)
| or.inr a0, _ := by simp [a0.symm]
| _, or.inr b0 := by simp [b0.symm]
end,
mul_pos := @real.mul_pos,
zero_lt_one := real.zero_lt_one,
add_lt_add_left := λ a b h c, (real.add_lt_add_iff_left c).2 h,
..real.comm_ring, ..real.linear_order }
/- Extra instances to short-circuit type class resolution -/
instance : linear_ordered_ring ℝ := by apply_instance
instance : ordered_ring ℝ := by apply_instance
instance : linear_ordered_semiring ℝ := by apply_instance
instance : ordered_semiring ℝ := by apply_instance
instance : ordered_comm_group ℝ := by apply_instance
instance : ordered_cancel_comm_monoid ℝ := by apply_instance
instance : ordered_comm_monoid ℝ := by apply_instance
instance : domain ℝ := by apply_instance
open_locale classical
noncomputable instance : discrete_linear_ordered_field ℝ :=
{ decidable_le := by apply_instance,
..real.linear_ordered_comm_ring,
..real.domain,
..cau_seq.completion.field }
/- Extra instances to short-circuit type class resolution -/
noncomputable instance : linear_ordered_field ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_comm_ring ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_semiring ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_comm_group ℝ := by apply_instance
noncomputable instance field : field ℝ := by apply_instance
noncomputable instance : division_ring ℝ := by apply_instance
noncomputable instance : integral_domain ℝ := by apply_instance
noncomputable instance : nonzero_comm_ring ℝ := by apply_instance
noncomputable instance : decidable_linear_order ℝ := by apply_instance
noncomputable instance : lattice.distrib_lattice ℝ := by apply_instance
noncomputable instance : lattice.lattice ℝ := by apply_instance
noncomputable instance : lattice.semilattice_inf ℝ := by apply_instance
noncomputable instance : lattice.semilattice_sup ℝ := by apply_instance
noncomputable instance : lattice.has_inf ℝ := by apply_instance
noncomputable instance : lattice.has_sup ℝ := by apply_instance
lemma le_of_forall_epsilon_le {a b : real} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense $ assume x hxb,
calc a ≤ b + (x - b) : h (x-b) $ sub_pos.2 hxb
... = x : by rw [add_comm]; simp
open rat
@[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x :=
eq_cast of_rat rfl of_rat_add of_rat_mul
theorem le_mk_of_forall_le {f : cau_seq ℚ abs} :
(∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f :=
quotient.induction_on x $ λ g h, le_of_not_lt $
λ ⟨K, K0, hK⟩,
let ⟨i, H⟩ := exists_forall_ge_and h $
exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0) in
begin
apply not_lt_of_le (H _ (le_refl _)).1,
rw ← of_rat_eq_cast,
refine ⟨_, half_pos K0, i, λ j ij, _⟩,
have := add_le_add (H _ ij).2.1
(le_of_lt (abs_lt.1 $ (H _ (le_refl _)).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 : ℝ} :
(∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) → mk f ≤ x
| ⟨i, H⟩ := by rw [← neg_le_neg_iff, ← mk_eq_mk, mk_neg]; exact
le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩
theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ}
(H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (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.1 $ le_mk_of_forall_le $
H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩
instance : archimedean ℝ :=
archimedean_iff_rat_le.2 $ λ x, quotient.induction_on 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⟩⟩
/- mark `real` irreducible in order to prevent `auto_cases` unfolding reals,
since users rarely want to consider real numbers as Cauchy sequences.
Marking `comm_ring_aux` `irreducible` is done to ensure that there are no problems
with non definitionally equal instances, caused by making `real` irreducible-/
attribute [irreducible] real comm_ring_aux
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, abs ((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_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) →
∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y
| ⟨L, hL⟩ ⟨U, hU⟩ := begin
choose f hf using begin
refine λ d : ℕ, @int.exists_greatest_of_bdd
(λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _ _,
{ cases exists_int_gt U with k hk,
refine ⟨k * d, λ z h, _⟩,
rcases h with ⟨y, yS, hy⟩,
refine int.cast_le.1 (le_trans hy _),
simp,
exact mul_le_mul_of_nonneg_right
(le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) },
{ exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ }
end,
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 := lt_of_lt_of_le (sub_one_lt_floor _)
(int.cast_le.2 $ (hf n).2 _ ⟨y, yS, 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) },
suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩,
refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ 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 := le_trans (le_of_lt hK) (nat.cast_le.2 nK),
have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos xz) hK),
refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS),
rwa [le_sub, 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)⟩ },
intros ε ε0,
suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε,
{ refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩,
rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij },
intros j k ij ik,
replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij),
replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik),
have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ij),
have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) 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)
end
noncomputable def Sup (S : set ℝ) : ℝ :=
if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x)
then classical.some (exists_sup S h.1 h.2) else 0
theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y :=
by simp [Sup, h₁, h₂]; exact
classical.some_spec (exists_sup S h₁ h₂) y
section
-- this proof times out without this
local attribute [instance, priority 1000] classical.prop_decidable
theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : y < Sup S ↔ ∃ z ∈ S, y < z :=
by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y)
end
theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S :=
(Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub :=
(Sup_le S h₁ ⟨_, h₂⟩).2 h₂
protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) :
is_lub s (Sup s) :=
⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs,
λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩
noncomputable def Inf (S : set ℝ) : ℝ := -Sup {x | -x ∈ S}
theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z :=
begin
refine le_neg.trans ((Sup_le _ _ _).trans _),
{ cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ },
{ cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ },
split; intros H z hz,
{ exact neg_le_neg_iff.1 (H _ $ by simp [hz]) },
{ exact le_neg.2 (H _ hz) }
end
section
-- this proof times out without this
local attribute [instance, priority 1000] classical.prop_decidable
theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : Inf S < y ↔ ∃ z ∈ S, z < y :=
by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y)
end
theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x :=
(le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S :=
(le_Inf S h₁ ⟨_, h₂⟩).2 h₂
open lattice
noncomputable instance lattice : lattice ℝ := by apply_instance
noncomputable instance : conditionally_complete_linear_order ℝ :=
{ Sup := real.Sup,
Inf := real.Inf,
le_cSup :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s),
show a ≤ Sup s,
from le_Sup s ‹bdd_above s› ‹a ∈ s›,
cSup_le :=
assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a),
show Sup s ≤ a,
from Sup_le_ub s ‹s.nonempty› H,
cInf_le :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s),
show Inf s ≤ a,
from Inf_le s ‹bdd_below s› ‹a ∈ s›,
le_cInf :=
assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b),
show a ≤ Inf s,
from lb_le_Inf s ‹s.nonempty› H,
decidable_le := classical.dec_rel _,
..real.linear_order, ..real.lattice}
theorem Sup_empty : lattice.Sup (∅ : set ℝ) = 0 := dif_neg $ by simp
theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : lattice.Sup s = 0 :=
dif_neg $ assume h, hs h.2
theorem Sup_univ : real.Sup set.univ = 0 :=
real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _)
theorem Inf_empty : lattice.Inf (∅ : set ℝ) = 0 :=
show Inf ∅ = 0, by simp [Inf]; exact Sup_empty
theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : lattice.Inf s = 0 :=
have bdd_above {x | -x ∈ s} → bdd_below s, from
assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩,
have ¬ bdd_above {x | -x ∈ s}, from mt this hs,
neg_eq_zero.2 $ Sup_of_not_bdd_above $ this
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 not_lt_of_le (Sup_le_ub S lb (ub' _ _))
((sub_lt_self_iff _).2 (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 not_lt_of_le (le_Sup S ub _)
((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
noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩
theorem sqrt_exists : ∀ {x : ℝ}, 0 ≤ x → ∃ y, 0 ≤ y ∧ y * y = x :=
suffices H : ∀ {x : ℝ}, 0 < x → x ≤ 1 → ∃ y, 0 < y ∧ y * y = x, begin
intros x x0, cases x0,
cases le_total x 1 with x1 x1,
{ rcases H x0 x1 with ⟨y, y0, hy⟩,
exact ⟨y, le_of_lt y0, hy⟩ },
{ have := (inv_le_inv x0 zero_lt_one).2 x1,
rw inv_one at this,
rcases H (inv_pos x0) this with ⟨y, y0, hy⟩,
refine ⟨y⁻¹, le_of_lt (inv_pos y0), _⟩, rw [← mul_inv', hy, inv_inv'] },
{ exact ⟨0, by simp [x0.symm]⟩ }
end,
λ x x0 x1, begin
let S := {y | 0 < y ∧ y * y ≤ x},
have lb : x ∈ S := ⟨x0, by simpa using (mul_le_mul_right x0).2 x1⟩,
have ub : ∀ y ∈ S, (y:ℝ) ≤ 1,
{ intros y yS, cases yS with y0 yx,
refine (mul_self_le_mul_self_iff (le_of_lt y0) zero_le_one).2 _,
simpa using le_trans yx x1 },
have S0 : 0 < Sup S := lt_of_lt_of_le x0 (le_Sup _ ⟨_, ub⟩ lb),
refine ⟨Sup S, S0, le_antisymm (not_lt.1 $ λ h, _) (not_lt.1 $ λ h, _)⟩,
{ rw [← div_lt_iff S0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at h,
rcases h with ⟨y, ⟨y0, yx⟩, hy⟩,
rw [div_lt_iff S0, ← div_lt_iff' y0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at hy,
rcases hy with ⟨z, ⟨z0, zx⟩, hz⟩,
rw [div_lt_iff y0] at hz,
exact not_lt_of_lt
((mul_lt_mul_right y0).1 (lt_of_le_of_lt yx hz))
((mul_lt_mul_left z0).1 (lt_of_le_of_lt zx hz)) },
{ let s := Sup S, let y := s + (x - s * s) / 3,
replace h : 0 < x - s * s := sub_pos.2 h,
have _30 := bit1_pos zero_le_one,
have : s < y := (lt_add_iff_pos_right _).2 (div_pos h _30),
refine not_le_of_lt this (le_Sup S ⟨_, ub⟩ ⟨lt_trans S0 this, _⟩),
rw [add_mul_self_eq, add_assoc, ← le_sub_iff_add_le', ← add_mul,
← le_div_iff (div_pos h _30), field.div_div_cancel (ne_of_gt h)],
apply add_le_add,
{ simpa using (mul_le_mul_left (@two_pos ℝ _)).2 (Sup_le_ub _ ⟨_, lb⟩ ub) },
{ rw [div_le_one_iff_le _30],
refine le_trans (sub_le_self _ (mul_self_nonneg _)) (le_trans x1 _),
exact (le_add_iff_nonneg_left _).2 (le_of_lt two_pos) } }
end
def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ
| 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt
| (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2
theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i
| 0 := by rw [sqrt_aux, mk_nat_eq, mk_eq_div];
apply div_nonneg'; exact int.cast_nonneg.2 (int.of_nat_nonneg _)
| (n + 1) := le_max_left _ _
/- TODO(Mario): finish the proof
theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧
mk ⟨sqrt_aux f, h⟩ = x :=
begin
rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩,
suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x,
{ exact this.imp (λ h e, ⟨x, x0, hx, e⟩) },
apply of_near,
suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i,
{ rcases this with ⟨δ, δ0, hδ⟩,
intros,
}
end -/
noncomputable def sqrt (x : ℝ) : ℝ :=
classical.some (sqrt_exists (le_max_left 0 x))
/-quotient.lift_on x
(λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩)
(λ f g e, begin
rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩,
rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩,
refine xs.trans (eq.trans _ ys.symm),
rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg],
congr' 1, exact quotient.sound e
end)-/
theorem sqrt_prop (x : ℝ) : 0 ≤ sqrt x ∧ sqrt x * sqrt x = max 0 x :=
classical.some_spec (sqrt_exists (le_max_left 0 x))
/-quotient.induction_on x $ λ f,
by rcases sqrt_aux_converges f with ⟨hf, _, x0, xf, rfl⟩; exact ⟨x0, xf⟩-/
theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 :=
eq_zero_of_mul_self_eq_zero $ (sqrt_prop x).2.trans $ max_eq_left h
theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := (sqrt_prop x).1
@[simp] theorem mul_self_sqrt (h : 0 ≤ x) : sqrt x * sqrt x = x :=
(sqrt_prop x).2.trans (max_eq_right h)
@[simp] theorem sqrt_mul_self (h : 0 ≤ x) : sqrt (x * x) = x :=
(mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _))
theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y * y = x :=
⟨λ h, by rw [← h, mul_self_sqrt hx],
λ h, by rw [← h, sqrt_mul_self hy]⟩
@[simp] theorem sqr_sqrt (h : 0 ≤ x) : sqrt x ^ 2 = x :=
by rw [pow_two, mul_self_sqrt h]
@[simp] theorem sqrt_sqr (h : 0 ≤ x) : sqrt (x ^ 2) = x :=
by rw [pow_two, sqrt_mul_self h]
theorem sqrt_eq_iff_sqr_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y ^ 2 = x :=
by rw [pow_two, sqrt_eq_iff_mul_self_eq hx hy]
theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = abs x :=
(le_total 0 x).elim
(λ h, (sqrt_mul_self h).trans (abs_of_nonneg h).symm)
(λ h, by rw [← neg_mul_neg,
sqrt_mul_self (neg_nonneg.2 h), abs_of_nonpos h])
theorem sqrt_sqr_eq_abs (x : ℝ) : sqrt (x ^ 2) = abs x :=
by rw [pow_two, sqrt_mul_self_eq_abs]
@[simp] theorem sqrt_zero : sqrt 0 = 0 :=
by simpa using sqrt_mul_self (le_refl _)
@[simp] theorem sqrt_one : sqrt 1 = 1 :=
by simpa using sqrt_mul_self zero_le_one
@[simp] theorem sqrt_le (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y :=
by rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _),
mul_self_sqrt hx, mul_self_sqrt hy]
@[simp] theorem sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < sqrt y ↔ x < y :=
lt_iff_lt_of_le_iff_le (sqrt_le hy hx)
lemma sqrt_le_sqrt (h : x ≤ y) : sqrt x ≤ sqrt y :=
begin
rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _), (sqrt_prop _).2, (sqrt_prop _).2],
exact max_le_max (le_refl _) h
end
lemma sqrt_le_left (hy : 0 ≤ y) : sqrt x ≤ y ↔ x ≤ y ^ 2 :=
begin
rw [mul_self_le_mul_self_iff (sqrt_nonneg _) hy, pow_two],
cases le_total 0 x with hx hx,
{ rw [mul_self_sqrt hx] },
{ have h1 : 0 ≤ y * y := mul_nonneg hy hy,
have h2 : x ≤ y * y := le_trans hx h1,
simp [sqrt_eq_zero_of_nonpos, hx, h1, h2] }
end
/- note: if you want to conclude `x ≤ sqrt y`, then use `le_sqrt_of_sqr_le`.
if you have `x > 0`, consider using `le_sqrt'` -/
lemma le_sqrt (hx : 0 ≤ x) (hy : 0 ≤ y) : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
by rw [mul_self_le_mul_self_iff hx (sqrt_nonneg _), pow_two, mul_self_sqrt hy]
lemma le_sqrt' (hx : 0 < x) : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
begin
rw [mul_self_le_mul_self_iff (le_of_lt hx) (sqrt_nonneg _), pow_two],
cases le_total 0 y with hy hy,
{ rw [mul_self_sqrt hy] },
{ have h1 : 0 < x * x := mul_pos hx hx,
have h2 : ¬x * x ≤ y := not_le_of_lt (lt_of_le_of_lt hy h1),
simp [sqrt_eq_zero_of_nonpos, hy, h1, h2] }
end
lemma le_sqrt_of_sqr_le (h : x ^ 2 ≤ y) : x ≤ sqrt y :=
begin
cases lt_or_ge 0 x with hx hx,
{ rwa [le_sqrt' hx] },
{ exact le_trans hx (sqrt_nonneg y) }
end
@[simp] theorem sqrt_inj (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y :=
by simp [le_antisymm_iff, hx, hy]
@[simp] theorem sqrt_eq_zero (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 :=
by simpa using sqrt_inj h (le_refl _)
theorem sqrt_eq_zero' : sqrt x = 0 ↔ x ≤ 0 :=
(le_total x 0).elim
(λ h, by simp [h, sqrt_eq_zero_of_nonpos])
(λ h, by simp [h]; simp [le_antisymm_iff, h])
@[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x :=
lt_iff_lt_of_le_iff_le (iff.trans
(by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero')
@[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y :=
begin
cases le_total 0 x with hx hx,
{ refine (mul_self_inj_of_nonneg _ (mul_nonneg _ _)).1 _; try {apply sqrt_nonneg},
rw [mul_self_sqrt (mul_nonneg hx hy), mul_assoc,
mul_left_comm (sqrt y), mul_self_sqrt hy, ← mul_assoc, mul_self_sqrt hx] },
{ rw [sqrt_eq_zero'.2 (mul_nonpos_of_nonpos_of_nonneg hx hy),
sqrt_eq_zero'.2 hx, zero_mul] }
end
@[simp] theorem sqrt_mul (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y :=
by rw [mul_comm, sqrt_mul' _ hx, mul_comm]
@[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ :=
(le_or_lt x 0).elim
(λ h, by simp [sqrt_eq_zero'.2, inv_nonpos, h])
(λ h, by rw [
← mul_self_inj_of_nonneg (sqrt_nonneg _) (le_of_lt $ inv_pos $ sqrt_pos.2 h),
mul_self_sqrt (le_of_lt $ inv_pos h), ← mul_inv', mul_self_sqrt (le_of_lt h)])
@[simp] theorem sqrt_div (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y :=
by rw [division_def, sqrt_mul hx, sqrt_inv]; refl
attribute [irreducible] real.le
end real
|
d39a883814a0c3210ff5f875bbbb3537f2cc51b1 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/rewrite_search/rewrite_search.lean | 4c3c4ccf547d252854da476f6ae4782df1c80403 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 3,406 | lean | /-
Copyright (c) 2020 Kevin Lacker, Keeley Hoek, Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Lacker, Keeley Hoek, Scott Morrison
-/
import tactic.rewrite_search
import data.rat.basic
import data.real.basic
/-
These tests ensure that `rewrite_search` works on some relatively simple examples.
They do not monitor for performance regression, so be aware of that if you make changes.
-/
namespace tactic.rewrite_search.testing
private axiom foo' : [6] = [7]
private axiom bar' : [[5], [5]] = [[6], [6]]
example : [[7], [6]] = [[5], [5]] :=
begin
success_if_fail { rewrite_search },
rewrite_search [foo', bar']
end
@[rewrite] private axiom foo : [0] = [1]
@[rewrite] private axiom bar1 : [1] = [2]
@[rewrite] private axiom bar2 : [3] = [2]
@[rewrite] private axiom bar3 : [3] = [4]
private example : [[0], [0]] = [[4], [4]] := by rewrite_search
private example (x : unit) : [[0], [0]] = [[4], [4]] := by rewrite_search
@[rewrite] private axiom qux' : [[1], [2]] = [[6], [7]]
@[rewrite] private axiom qux'' : [6] = [7]
private example : [[1], [1]] = [[7], [7]] := by rewrite_search
constants f g : ℕ → ℕ → ℕ → ℕ
@[rewrite] axiom f_0_0 : ∀ a b c : ℕ, f a b c = f 0 b c
@[rewrite] axiom f_0_1 : ∀ a b c : ℕ, f a b c = f 1 b c
@[rewrite] axiom f_0_2 : ∀ a b c : ℕ, f a b c = f 2 b c
@[rewrite] axiom f_1_0 : ∀ a b c : ℕ, f a b c = f a 0 c
@[rewrite] axiom f_1_1 : ∀ a b c : ℕ, f a b c = f a 1 c
@[rewrite] axiom f_1_2 : ∀ a b c : ℕ, f a b c = f a 2 c
@[rewrite] axiom f_2_0 : ∀ a b c : ℕ, f a b c = f a b 0
@[rewrite] axiom f_2_1 : ∀ a b c : ℕ, f a b c = f a b 1
@[rewrite] axiom f_2_2 : ∀ a b c : ℕ, f a b c = f a b 2
@[rewrite] axiom g_0_0 : ∀ a b c : ℕ, g a b c = g 0 b c
@[rewrite] axiom g_0_1 : ∀ a b c : ℕ, g a b c = g 1 b c
@[rewrite] axiom g_0_2 : ∀ a b c : ℕ, g a b c = g 2 b c
@[rewrite] axiom g_1_0 : ∀ a b c : ℕ, g a b c = g a 0 c
@[rewrite] axiom g_1_1 : ∀ a b c : ℕ, g a b c = g a 1 c
@[rewrite] axiom g_1_2 : ∀ a b c : ℕ, g a b c = g a 2 c
@[rewrite] axiom g_2_0 : ∀ a b c : ℕ, g a b c = g a b 0
@[rewrite] axiom g_2_1 : ∀ a b c : ℕ, g a b c = g a b 1
@[rewrite] axiom g_2_2 : ∀ a b c : ℕ, g a b c = g a b 2
@[rewrite] axiom f_g : f 0 1 2 = g 2 0 1
lemma test_pathfinding : f 0 0 0 = g 0 0 0 := by rewrite_search
constant h : ℕ → ℕ
@[rewrite,simp] axiom a1 : h 0 = h 1
@[rewrite,simp] axiom a2 : h 1 = h 2
@[rewrite,simp] axiom a3 : h 2 = h 3
@[rewrite,simp] axiom a4 : h 3 = h 4
lemma test_linear_path : h 0 = h 4 := by rewrite_search
constants a b c d e : ℚ
lemma test_algebra : (a * (b + c)) * d = a * (b * d) + a * (c * d) :=
by rewrite_search [add_comm, add_assoc, mul_assoc, mul_comm, left_distrib, right_distrib]
lemma test_simpler_algebra : a + (b + c) = (a + b) + c :=
by rewrite_search [add_assoc]
def idf : ℝ → ℝ := id
/-
These problems test `rewrite_search`'s ability to carry on in the presence of multiple
expressions that `pp` to the same thing but are not actually equal.
-/
lemma test_pp_1 : idf (0 : ℕ) = idf (0 : ℚ) :=
by rewrite_search [rat.cast_zero, nat.cast_zero, add_comm]
lemma test_pp_2 : idf (0 : ℕ) + 1 = 1 + idf (0 : ℚ) :=
by rewrite_search [rat.cast_zero, nat.cast_zero, add_comm]
example (x : ℕ) : x = x := by rewrite_search
end tactic.rewrite_search.testing
|
ab11d542da6e4102beae2cc173b641783724bbf3 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/303.lean | d02e7f51d17f685d7d251f1d7f7c2642db277b9a | [
"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 | 30 | lean | #eval (2147483648 / 0) + (-0)
|
14c6fd0cae44761096592b56a4215a17c67738c8 | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/algebra/default.lean | 7e83c3c3cd17cd123550018c2abdfc5cdf2dd7a9 | [
"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 | 202 | 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.algebra.functions
|
be0af9ce7f601e3fb123c8544f70c09b22c957b7 | 0d2e44896897eda703992595d71a0b19ed30b8a1 | /uexp/src/uexp/rules/conjunctive.lean | 93bbd1b4d1561a10063990bf986ca99b154f61fd | [
"BSD-2-Clause"
] | permissive | wwombat/Cosette | a87312aabefdb53ea8b67c37731bd58c7485afb6 | 4c5dc6172e24d3546c9818ac1fad06f72fe1c991 | refs/heads/master | 1,619,479,568,051 | 1,520,292,502,000 | 1,520,292,502,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 899 | lean | import ..u_semiring
import ..sql
import ..tactics
open SQL
open Pred
open Expr
open Proj
lemma CQExample0:
forall Γ s1 s2 (a: SQL Γ s1) (b: SQL Γ s2)
ty0 ty1 (x: Column ty0 s1)
(ya: Column ty1 s1) (yb: Column ty1 s2),
denoteSQL ((DISTINCT (SELECT1 (right⋅left⋅x) (FROM1 (product a b)
WHERE (equal (uvariable (right⋅left⋅ya)) (uvariable (right⋅right⋅yb)))))) : SQL Γ _) =
denoteSQL ((DISTINCT (SELECT1 (right⋅left⋅left⋅x)
(FROM1 (product (product a a) b)
WHERE (and (equal (uvariable (right⋅left⋅left⋅x)) (uvariable (right⋅left⋅right⋅x)))
(equal (uvariable (right⋅left⋅left⋅ya)) (uvariable (right⋅right⋅yb))))))) : SQL Γ _ ) :=
begin
intros,
unfold_all_denotations,
funext,
sorry -- TODO: SDP should be used here
end
|
00168c48863dd89d583a3727628bdf4fca5afe0c | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/limits/opposites.lean | 88f821f6e171d61574f6ed0a046dbb2c372617e7 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 5,367 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Floris van Doorn
-/
import category_theory.limits.shapes.finite_products
import category_theory.limits.shapes.kernels
import category_theory.discrete_category
universes v u
noncomputable theory
open category_theory
open category_theory.functor
open opposite
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
variables {J : Type v} [small_category J]
variable (F : J ⥤ Cᵒᵖ)
/--
If `F.left_op : Jᵒᵖ ⥤ C` has a colimit, we can construct a limit for `F : J ⥤ Cᵒᵖ`.
-/
lemma has_limit_of_has_colimit_left_op [has_colimit F.left_op] : has_limit F :=
has_limit.mk
{ cone := cone_of_cocone_left_op (colimit.cocone F.left_op),
is_limit :=
{ lift := λ s, (colimit.desc F.left_op (cocone_left_op_of_cone s)).op,
fac' := λ s j,
begin
rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, ←op_comp,
colimit.ι_desc, cocone_left_op_of_cone_ι_app, quiver.hom.op_unop],
refl, end,
uniq' := λ s m w,
begin
-- It's a pity we can't do this automatically.
-- Usually something like this would work by limit.hom_ext,
-- but the opposites get in the way of this firing.
have u := (colimit.is_colimit F.left_op).uniq (cocone_left_op_of_cone s) (m.unop),
convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u,
intro j,
rw [cocone_left_op_of_cone_ι_app, colimit.cocone_ι],
convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w,
rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, quiver.hom.unop_op],
refl,
end } }
/--
If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
lemma has_limits_of_shape_op_of_has_colimits_of_shape [has_colimits_of_shape Jᵒᵖ C] :
has_limits_of_shape J Cᵒᵖ :=
{ has_limit := λ F, has_limit_of_has_colimit_left_op F }
local attribute [instance] has_limits_of_shape_op_of_has_colimits_of_shape
/--
If `C` has colimits, we can construct limits for `Cᵒᵖ`.
-/
lemma has_limits_op_of_has_colimits [has_colimits C] : has_limits Cᵒᵖ := {}
/--
If `F.left_op : Jᵒᵖ ⥤ C` has a limit, we can construct a colimit for `F : J ⥤ Cᵒᵖ`.
-/
lemma has_colimit_of_has_limit_left_op [has_limit F.left_op] : has_colimit F :=
has_colimit.mk
{ cocone := cocone_of_cone_left_op (limit.cone F.left_op),
is_colimit :=
{ desc := λ s, (limit.lift F.left_op (cone_left_op_of_cocone s)).op,
fac' := λ s j,
begin
rw [cocone_of_cone_left_op_ι_app, limit.cone_π, ←op_comp,
limit.lift_π, cone_left_op_of_cocone_π_app, quiver.hom.op_unop],
refl, end,
uniq' := λ s m w,
begin
have u := (limit.is_limit F.left_op).uniq (cone_left_op_of_cocone s) (m.unop),
convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u,
intro j,
rw [cone_left_op_of_cocone_π_app, limit.cone_π],
convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w,
rw [cocone_of_cone_left_op_ι_app, limit.cone_π, quiver.hom.unop_op],
refl,
end } }
/--
If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
lemma has_colimits_of_shape_op_of_has_limits_of_shape [has_limits_of_shape Jᵒᵖ C] :
has_colimits_of_shape J Cᵒᵖ :=
{ has_colimit := λ F, has_colimit_of_has_limit_left_op F }
local attribute [instance] has_colimits_of_shape_op_of_has_limits_of_shape
/--
If `C` has limits, we can construct colimits for `Cᵒᵖ`.
-/
lemma has_colimits_op_of_has_limits [has_limits C] : has_colimits Cᵒᵖ := {}
variables (X : Type v)
/--
If `C` has products indexed by `X`, then `Cᵒᵖ` has coproducts indexed by `X`.
-/
lemma has_coproducts_opposite [has_products_of_shape X C] :
has_coproducts_of_shape X Cᵒᵖ :=
begin
haveI : has_limits_of_shape (discrete X)ᵒᵖ C :=
has_limits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
/--
If `C` has coproducts indexed by `X`, then `Cᵒᵖ` has products indexed by `X`.
-/
lemma has_products_opposite [has_coproducts_of_shape X C] :
has_products_of_shape X Cᵒᵖ :=
begin
haveI : has_colimits_of_shape (discrete X)ᵒᵖ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
lemma has_finite_coproducts_opposite [has_finite_products C] :
has_finite_coproducts Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, begin
resetI,
haveI : has_limits_of_shape (discrete J)ᵒᵖ C :=
has_limits_of_shape_of_equivalence (discrete.opposite J).symm,
apply_instance,
end }
lemma has_finite_products_opposite [has_finite_coproducts C] :
has_finite_products Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, begin
resetI,
haveI : has_colimits_of_shape (discrete J)ᵒᵖ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite J).symm,
apply_instance,
end }
local attribute [instance] fin_category_opposite
lemma has_finite_colimits_opposite [has_finite_limits C] :
has_finite_colimits Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, by { resetI, apply_instance, }, }
lemma has_finite_limits_opposite [has_finite_colimits C] :
has_finite_limits Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, by { resetI, apply_instance, }, }
end category_theory.limits
|
52b30b53c28eb4b860d2cb90b16d6cc88384e7fc | 969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb | /src/algebra/group/basic.lean | 1e94732442949fd2d3b08c536e80b0158e4e08fb | [
"Apache-2.0"
] | permissive | SAAluthwela/mathlib | 62044349d72dd63983a8500214736aa7779634d3 | 83a4b8b990907291421de54a78988c024dc8a552 | refs/heads/master | 1,679,433,873,417 | 1,615,998,031,000 | 1,615,998,031,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,157 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Simon Hudon, Mario Carneiro
-/
import algebra.group.defs
import logic.function.basic
/-!
# Basic lemmas about semigroups, monoids, and groups
This file lists various basic lemmas about semigroups, monoids, and groups. Most proofs are
one-liners from the corresponding axioms. For the definitions of semigroups, monoids and groups, see
`algebra/group/defs.lean`.
-/
universe u
section associative
variables {α : Type u} (f : α → α → α) [is_associative α f] (x y : α)
/--
Composing two associative operations of `f : α → α → α` on the left
is equal to an associative operation on the left.
-/
lemma comp_assoc_left : (f x) ∘ (f y) = (f (f x y)) :=
by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] }
/--
Composing two associative operations of `f : α → α → α` on the right
is equal to an associative operation on the right.
-/
lemma comp_assoc_right : (λ z, f z x) ∘ (λ z, f z y) = (λ z, f z (f y x)) :=
by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] }
end associative
section semigroup
variables {α : Type*}
/--
Composing two multiplications on the left by `y` then `x`
is equal to a multiplication on the left by `x * y`.
-/
@[simp, to_additive
"Composing two additions on the left by `y` then `x`
is equal to a addition on the left by `x + y`."]
lemma comp_mul_left [semigroup α] (x y : α) :
((*) x) ∘ ((*) y) = ((*) (x * y)) :=
comp_assoc_left _ _ _
/--
Composing two multiplications on the right by `y` and `x`
is equal to a multiplication on the right by `y * x`.
-/
@[simp, to_additive
"Composing two additions on the right by `y` and `x`
is equal to a addition on the right by `y + x`."]
lemma comp_mul_right [semigroup α] (x y : α) :
(* x) ∘ (* y) = (* (y * x)) :=
comp_assoc_right _ _ _
end semigroup
section monoid
variables {M : Type u} [monoid M]
@[to_additive]
lemma ite_mul_one {P : Prop} [decidable P] {a b : M} :
ite P (a * b) 1 = ite P a 1 * ite P b 1 :=
by { by_cases h : P; simp [h], }
@[to_additive]
lemma eq_one_iff_eq_one_of_mul_eq_one {a b : M} (h : a * b = 1) : a = 1 ↔ b = 1 :=
by split; { rintro rfl, simpa using h }
end monoid
section comm_semigroup
variables {G : Type u} [comm_semigroup G]
@[no_rsimp, to_additive]
lemma mul_left_comm : ∀ a b c : G, a * (b * c) = b * (a * c) :=
left_comm has_mul.mul mul_comm mul_assoc
attribute [no_rsimp] add_left_comm
@[to_additive]
lemma mul_right_comm : ∀ a b c : G, a * b * c = a * c * b :=
right_comm has_mul.mul mul_comm mul_assoc
@[to_additive]
theorem mul_mul_mul_comm (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) :=
by simp only [mul_left_comm, mul_assoc]
end comm_semigroup
local attribute [simp] mul_assoc sub_eq_add_neg
section add_monoid
variables {M : Type u} [add_monoid M] {a b c : M}
@[simp] lemma bit0_zero : bit0 (0 : M) = 0 := add_zero _
@[simp] lemma bit1_zero [has_one M] : bit1 (0 : M) = 1 :=
by rw [bit1, bit0_zero, zero_add]
end add_monoid
section comm_monoid
variables {M : Type u} [comm_monoid M] {x y z : M}
@[to_additive] lemma inv_unique (hy : x * y = 1) (hz : x * z = 1) : y = z :=
left_inv_eq_right_inv (trans (mul_comm _ _) hy) hz
end comm_monoid
section left_cancel_monoid
variables {M : Type u} [left_cancel_monoid M] {a b : M}
@[simp, to_additive] lemma mul_right_eq_self : a * b = a ↔ b = 1 :=
calc a * b = a ↔ a * b = a * 1 : by rw mul_one
... ↔ b = 1 : mul_left_cancel_iff
@[simp, to_additive] lemma self_eq_mul_right : a = a * b ↔ b = 1 :=
eq_comm.trans mul_right_eq_self
end left_cancel_monoid
section right_cancel_monoid
variables {M : Type u} [right_cancel_monoid M] {a b : M}
@[simp, to_additive] lemma mul_left_eq_self : a * b = b ↔ a = 1 :=
calc a * b = b ↔ a * b = 1 * b : by rw one_mul
... ↔ a = 1 : mul_right_cancel_iff
@[simp, to_additive] lemma self_eq_mul_left : b = a * b ↔ a = 1 :=
eq_comm.trans mul_left_eq_self
end right_cancel_monoid
section div_inv_monoid
variables {G : Type u} [div_inv_monoid G]
@[to_additive]
lemma inv_eq_one_div (x : G) :
x⁻¹ = 1 / x :=
by rw [div_eq_mul_inv, one_mul]
@[to_additive]
lemma mul_one_div (x y : G) :
x * (1 / y) = x / y :=
by rw [div_eq_mul_inv, one_mul, div_eq_mul_inv]
lemma mul_div_assoc {a b c : G} : a * b / c = a * (b / c) :=
by rw [div_eq_mul_inv, div_eq_mul_inv, mul_assoc _ _ _]
lemma mul_div_assoc' (a b c : G) : a * (b / c) = (a * b) / c :=
mul_div_assoc.symm
@[simp, to_additive] lemma one_div (a : G) : 1 / a = a⁻¹ :=
(inv_eq_one_div a).symm
end div_inv_monoid
section group
variables {G : Type u} [group G] {a b c : G}
@[simp, to_additive]
lemma inv_mul_cancel_right (a b : G) : a * b⁻¹ * b = a :=
by simp [mul_assoc]
@[simp, to_additive neg_zero]
lemma one_inv : 1⁻¹ = (1 : G) :=
inv_eq_of_mul_eq_one (one_mul 1)
@[to_additive]
theorem left_inverse_inv (G) [group G] :
function.left_inverse (λ a : G, a⁻¹) (λ a, a⁻¹) :=
inv_inv
@[simp, to_additive]
lemma inv_involutive : function.involutive (has_inv.inv : G → G) := inv_inv
@[to_additive]
lemma inv_injective : function.injective (has_inv.inv : G → G) :=
inv_involutive.injective
@[simp, to_additive] theorem inv_inj : a⁻¹ = b⁻¹ ↔ a = b := inv_injective.eq_iff
@[simp, to_additive]
lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b :=
by rw [← mul_assoc, mul_right_inv, one_mul]
@[to_additive]
theorem mul_left_surjective (a : G) : function.surjective ((*) a) :=
λ x, ⟨a⁻¹ * x, mul_inv_cancel_left a x⟩
@[to_additive]
theorem mul_right_surjective (a : G) : function.surjective (λ x, x * a) :=
λ x, ⟨x * a⁻¹, inv_mul_cancel_right x a⟩
@[simp, to_additive neg_add_rev]
lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
inv_eq_of_mul_eq_one $ by simp
@[to_additive]
lemma eq_inv_of_eq_inv (h : a = b⁻¹) : b = a⁻¹ :=
by simp [h]
@[to_additive]
lemma eq_inv_of_mul_eq_one (h : a * b = 1) : a = b⁻¹ :=
have a⁻¹ = b, from inv_eq_of_mul_eq_one h,
by simp [this.symm]
@[to_additive]
lemma eq_mul_inv_of_mul_eq (h : a * c = b) : a = b * c⁻¹ :=
by simp [h.symm]
@[to_additive]
lemma eq_inv_mul_of_mul_eq (h : b * a = c) : a = b⁻¹ * c :=
by simp [h.symm]
@[to_additive]
lemma inv_mul_eq_of_eq_mul (h : b = a * c) : a⁻¹ * b = c :=
by simp [h]
@[to_additive]
lemma mul_inv_eq_of_eq_mul (h : a = c * b) : a * b⁻¹ = c :=
by simp [h]
@[to_additive]
lemma eq_mul_of_mul_inv_eq (h : a * c⁻¹ = b) : a = b * c :=
by simp [h.symm]
@[to_additive]
lemma eq_mul_of_inv_mul_eq (h : b⁻¹ * a = c) : a = b * c :=
by simp [h.symm, mul_inv_cancel_left]
@[to_additive]
lemma mul_eq_of_eq_inv_mul (h : b = a⁻¹ * c) : a * b = c :=
by rw [h, mul_inv_cancel_left]
@[to_additive]
lemma mul_eq_of_eq_mul_inv (h : a = c * b⁻¹) : a * b = c :=
by simp [h]
@[simp, to_additive]
theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 :=
by rw [← @inv_inj _ _ a 1, one_inv]
@[simp, to_additive]
theorem one_eq_inv : 1 = a⁻¹ ↔ a = 1 :=
by rw [eq_comm, inv_eq_one]
@[to_additive]
theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 :=
not_congr inv_eq_one
@[to_additive]
theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ :=
⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩
@[to_additive]
theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a :=
eq_comm.trans $ eq_inv_iff_eq_inv.trans eq_comm
@[to_additive]
theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ :=
⟨eq_inv_of_mul_eq_one, λ h, by rw [h, mul_left_inv]⟩
@[to_additive]
theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b :=
by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm]
@[to_additive]
theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 :=
mul_eq_one_iff_eq_inv.symm
@[to_additive]
theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 :=
mul_eq_one_iff_inv_eq.symm
@[to_additive]
theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b :=
⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩
@[to_additive]
theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c :=
⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩
@[to_additive]
theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c :=
⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩
@[to_additive]
theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b :=
⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩
@[to_additive]
theorem mul_inv_eq_one : a * b⁻¹ = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inv]
@[to_additive]
theorem inv_mul_eq_one : a⁻¹ * b = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inj]
@[to_additive]
lemma div_left_injective : function.injective (λ a, a / b) :=
by simpa only [div_eq_mul_inv] using λ a a' h, mul_left_injective (b⁻¹) h
@[to_additive]
lemma div_right_injective : function.injective (λ a, b / a) :=
by simpa only [div_eq_mul_inv] using λ a a' h, inv_injective (mul_right_injective b h)
end group
section add_group
variables {G : Type u} [add_group G] {a b c d : G}
@[simp] lemma sub_self (a : G) : a - a = 0 :=
by rw [sub_eq_add_neg, add_right_neg a]
@[simp] lemma sub_add_cancel (a b : G) : a - b + b = a :=
by rw [sub_eq_add_neg, neg_add_cancel_right a b]
@[simp] lemma add_sub_cancel (a b : G) : a + b - b = a :=
by rw [sub_eq_add_neg, add_neg_cancel_right a b]
lemma add_sub_assoc (a b c : G) : a + b - c = a + (b - c) :=
by rw [sub_eq_add_neg, add_assoc, ←sub_eq_add_neg]
lemma eq_of_sub_eq_zero (h : a - b = 0) : a = b :=
have 0 + b = b, by rw zero_add,
have (a - b) + b = b, by rwa h,
by rwa [sub_eq_add_neg, neg_add_cancel_right] at this
lemma sub_eq_zero_of_eq (h : a = b) : a - b = 0 :=
by rw [h, sub_self]
lemma sub_eq_zero_iff_eq : a - b = 0 ↔ a = b :=
⟨eq_of_sub_eq_zero, sub_eq_zero_of_eq⟩
@[simp] lemma sub_zero (a : G) : a - 0 = a :=
by rw [sub_eq_add_neg, neg_zero, add_zero]
lemma sub_ne_zero_of_ne (h : a ≠ b) : a - b ≠ 0 :=
begin
intro hab,
apply h,
apply eq_of_sub_eq_zero hab
end
@[simp] lemma sub_neg_eq_add (a b : G) : a - (-b) = a + b :=
by rw [sub_eq_add_neg, neg_neg]
@[simp] lemma neg_sub (a b : G) : -(a - b) = b - a :=
neg_eq_of_add_eq_zero (by rw [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left,
add_right_neg])
local attribute [simp] add_assoc
lemma add_sub (a b c : G) : a + (b - c) = a + b - c :=
by simp
lemma sub_add_eq_sub_sub_swap (a b c : G) : a - (b + c) = a - c - b :=
by simp
@[simp] lemma add_sub_add_right_eq_sub (a b c : G) : (a + c) - (b + c) = a - b :=
by rw [sub_add_eq_sub_sub_swap]; simp
lemma eq_sub_of_add_eq (h : a + c = b) : a = b - c :=
by simp [h.symm]
lemma sub_eq_of_eq_add (h : a = c + b) : a - b = c :=
by simp [h]
lemma eq_add_of_sub_eq (h : a - c = b) : a = b + c :=
by simp [h.symm]
lemma add_eq_of_eq_sub (h : a = c - b) : a + b = c :=
by simp [h]
@[simp] lemma sub_right_inj : a - b = a - c ↔ b = c :=
sub_right_injective.eq_iff
@[simp] lemma sub_left_inj : b - a = c - a ↔ b = c :=
by { rw [sub_eq_add_neg, sub_eq_add_neg], exact add_left_inj _ }
lemma sub_add_sub_cancel (a b c : G) : (a - b) + (b - c) = a - c :=
by rw [← add_sub_assoc, sub_add_cancel]
lemma sub_sub_sub_cancel_right (a b c : G) : (a - c) - (b - c) = a - b :=
by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel]
theorem sub_sub_assoc_swap : a - (b - c) = a + c - b :=
by simp
theorem sub_eq_zero : a - b = 0 ↔ a = b :=
⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩
theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b :=
not_congr sub_eq_zero
theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b :=
by rw [sub_eq_add_neg, eq_add_neg_iff_add_eq]
theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b :=
by rw [sub_eq_add_neg, add_neg_eq_iff_eq_add]
theorem eq_iff_eq_of_sub_eq_sub (H : a - b = c - d) : a = b ↔ c = d :=
by rw [← sub_eq_zero, H, sub_eq_zero]
theorem left_inverse_sub_add_left (c : G) : function.left_inverse (λ x, x - c) (λ x, x + c) :=
assume x, add_sub_cancel x c
theorem left_inverse_add_left_sub (c : G) : function.left_inverse (λ x, x + c) (λ x, x - c) :=
assume x, sub_add_cancel x c
theorem left_inverse_add_right_neg_add (c : G) :
function.left_inverse (λ x, c + x) (λ x, - c + x) :=
assume x, add_neg_cancel_left c x
theorem left_inverse_neg_add_add_right (c : G) :
function.left_inverse (λ x, - c + x) (λ x, c + x) :=
assume x, neg_add_cancel_left c x
end add_group
section comm_group
variables {G : Type u} [comm_group G]
@[to_additive neg_add]
lemma mul_inv (a b : G) : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev, mul_comm]
end comm_group
section add_comm_group
variables {G : Type u} [add_comm_group G] {a b c d : G}
local attribute [simp] add_assoc add_comm add_left_comm sub_eq_add_neg
lemma sub_add_eq_sub_sub (a b c : G) : a - (b + c) = a - b - c :=
by simp
lemma neg_add_eq_sub (a b : G) : -a + b = b - a :=
by simp
lemma sub_add_eq_add_sub (a b c : G) : a - b + c = a + c - b :=
by simp
lemma sub_sub (a b c : G) : a - b - c = a - (b + c) :=
by simp
lemma sub_add (a b c : G) : a - b + c = a - (b - c) :=
by simp
@[simp] lemma add_sub_add_left_eq_sub (a b c : G) : (c + a) - (c + b) = a - b :=
by simp
lemma eq_sub_of_add_eq' (h : c + a = b) : a = b - c :=
by simp [h.symm]
lemma sub_eq_of_eq_add' (h : a = b + c) : a - b = c :=
begin simp [h], rw [add_left_comm], simp end
lemma eq_add_of_sub_eq' (h : a - b = c) : a = b + c :=
by simp [h.symm]
lemma add_eq_of_eq_sub' (h : b = c - a) : a + b = c :=
begin simp [h], rw [add_comm c, add_neg_cancel_left] end
lemma sub_sub_self (a b : G) : a - (a - b) = b :=
begin simp, rw [add_comm b, add_neg_cancel_left] end
lemma add_sub_comm (a b c d : G) : a + b - (c + d) = (a - c) + (b - d) :=
by simp
lemma sub_eq_sub_add_sub (a b c : G) : a - b = c - b + (a - c) :=
begin simp, rw [add_left_comm c], simp end
lemma neg_neg_sub_neg (a b : G) : - (-a - -b) = a - b :=
by simp
@[simp] lemma sub_sub_cancel (a b : G) : a - (a - b) = b := sub_sub_self a b
lemma sub_eq_neg_add (a b : G) : a - b = -b + a :=
by rw [sub_eq_add_neg, add_comm _ _]
theorem neg_add' (a b : G) : -(a + b) = -a - b :=
by rw [sub_eq_add_neg, neg_add a b]
@[simp]
lemma neg_sub_neg (a b : G) : -a - -b = b - a :=
by simp [sub_eq_neg_add, add_comm]
lemma eq_sub_iff_add_eq' : a = b - c ↔ c + a = b :=
by rw [eq_sub_iff_add_eq, add_comm]
lemma sub_eq_iff_eq_add' : a - b = c ↔ a = b + c :=
by rw [sub_eq_iff_eq_add, add_comm]
@[simp]
lemma add_sub_cancel' (a b : G) : a + b - a = b :=
by rw [sub_eq_neg_add, neg_add_cancel_left]
@[simp]
lemma add_sub_cancel'_right (a b : G) : a + (b - a) = b :=
by rw [← add_sub_assoc, add_sub_cancel']
-- This lemma is in the `simp` set under the name `add_neg_cancel_comm_assoc`,
-- defined in `algebra/group/commute`
lemma add_add_neg_cancel'_right (a b : G) : a + (b + -a) = b :=
by rw [← sub_eq_add_neg, add_sub_cancel'_right a b]
lemma sub_right_comm (a b c : G) : a - b - c = a - c - b :=
by { repeat { rw sub_eq_add_neg }, exact add_right_comm _ _ _ }
@[simp] lemma add_add_sub_cancel (a b c : G) : (a + c) + (b - c) = a + b :=
by rw [add_assoc, add_sub_cancel'_right]
@[simp] lemma sub_add_add_cancel (a b c : G) : (a - c) + (b + c) = a + b :=
by rw [add_left_comm, sub_add_cancel, add_comm]
@[simp] lemma sub_add_sub_cancel' (a b c : G) : (a - b) + (c - a) = c - b :=
by rw add_comm; apply sub_add_sub_cancel
@[simp] lemma add_sub_sub_cancel (a b c : G) : (a + b) - (a - c) = b + c :=
by rw [← sub_add, add_sub_cancel']
@[simp] lemma sub_sub_sub_cancel_left (a b c : G) : (c - a) - (c - b) = b - a :=
by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel]
lemma sub_eq_sub_iff_add_eq_add : a - b = c - d ↔ a + d = c + b :=
begin
rw [sub_eq_iff_eq_add, sub_add_eq_add_sub, eq_comm, sub_eq_iff_eq_add'],
simp only [add_comm, eq_comm]
end
lemma sub_eq_sub_iff_sub_eq_sub : a - b = c - d ↔ a - c = b - d :=
by rw [sub_eq_iff_eq_add, sub_add_eq_add_sub, sub_eq_iff_eq_add', add_sub_assoc]
end add_comm_group
|
fdc94ab3b408c54fdb883569818163ab75d2840c | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/inner_product_space/adjoint.lean | e03af80401fc1249b3b1007586e412efbcea6975 | [
"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 | 18,841 | lean | /-
Copyright (c) 2021 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis, Heather Macbeth
-/
import analysis.inner_product_space.dual
import analysis.inner_product_space.pi_L2
/-!
# Adjoint of operators on Hilbert spaces
Given an operator `A : E →L[𝕜] F`, where `E` and `F` are Hilbert spaces, its adjoint
`adjoint A : F →L[𝕜] E` is the unique operator such that `⟪x, A y⟫ = ⟪adjoint A x, y⟫` for all
`x` and `y`.
We then use this to put a C⋆-algebra structure on `E →L[𝕜] E` with the adjoint as the star
operation.
This construction is used to define an adjoint for linear maps (i.e. not continuous) between
finite dimensional spaces.
## Main definitions
* `continuous_linear_map.adjoint : (E →L[𝕜] F) ≃ₗᵢ⋆[𝕜] (F →L[𝕜] E)`: the adjoint of a continuous
linear map, bundled as a conjugate-linear isometric equivalence.
* `linear_map.adjoint : (E →ₗ[𝕜] F) ≃ₗ⋆[𝕜] (F →ₗ[𝕜] E)`: the adjoint of a linear map between
finite-dimensional spaces, this time only as a conjugate-linear equivalence, since there is no
norm defined on these maps.
## Implementation notes
* The continuous conjugate-linear version `adjoint_aux` is only an intermediate
definition and is not meant to be used outside this file.
## Tags
adjoint
-/
noncomputable theory
open is_R_or_C
open_locale complex_conjugate
variables {𝕜 E F G : Type*} [is_R_or_C 𝕜]
variables [inner_product_space 𝕜 E] [inner_product_space 𝕜 F] [inner_product_space 𝕜 G]
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
/-! ### Adjoint operator -/
open inner_product_space
namespace continuous_linear_map
variables [complete_space E] [complete_space G]
/-- The adjoint, as a continuous conjugate-linear map. This is only meant as an auxiliary
definition for the main definition `adjoint`, where this is bundled as a conjugate-linear isometric
equivalence. -/
def adjoint_aux : (E →L[𝕜] F) →L⋆[𝕜] (F →L[𝕜] E) :=
(continuous_linear_map.compSL _ _ _ _ _ ((to_dual 𝕜 E).symm : normed_space.dual 𝕜 E →L⋆[𝕜] E)).comp
(to_sesq_form : (E →L[𝕜] F) →L[𝕜] F →L⋆[𝕜] normed_space.dual 𝕜 E)
@[simp] lemma adjoint_aux_apply (A : E →L[𝕜] F) (x : F) :
adjoint_aux A x = ((to_dual 𝕜 E).symm : (normed_space.dual 𝕜 E) → E) ((to_sesq_form A) x) := rfl
lemma adjoint_aux_inner_left (A : E →L[𝕜] F) (x : E) (y : F) : ⟪adjoint_aux A y, x⟫ = ⟪y, A x⟫ :=
by { simp only [adjoint_aux_apply, to_dual_symm_apply, to_sesq_form_apply_coe, coe_comp',
innerSL_apply_coe]}
lemma adjoint_aux_inner_right (A : E →L[𝕜] F) (x : E) (y : F) : ⟪x, adjoint_aux A y⟫ = ⟪A x, y⟫ :=
by rw [←inner_conj_sym, adjoint_aux_inner_left, inner_conj_sym]
variables [complete_space F]
lemma adjoint_aux_adjoint_aux (A : E →L[𝕜] F) : adjoint_aux (adjoint_aux A) = A :=
begin
ext v,
refine ext_inner_left 𝕜 (λ w, _),
rw [adjoint_aux_inner_right, adjoint_aux_inner_left],
end
@[simp] lemma adjoint_aux_norm (A : E →L[𝕜] F) : ∥adjoint_aux A∥ = ∥A∥ :=
begin
refine le_antisymm _ _,
{ refine continuous_linear_map.op_norm_le_bound _ (norm_nonneg _) (λ x, _),
rw [adjoint_aux_apply, linear_isometry_equiv.norm_map],
exact to_sesq_form_apply_norm_le },
{ nth_rewrite_lhs 0 [←adjoint_aux_adjoint_aux A],
refine continuous_linear_map.op_norm_le_bound _ (norm_nonneg _) (λ x, _),
rw [adjoint_aux_apply, linear_isometry_equiv.norm_map],
exact to_sesq_form_apply_norm_le }
end
/-- The adjoint of a bounded operator from Hilbert space E to Hilbert space F. -/
def adjoint : (E →L[𝕜] F) ≃ₗᵢ⋆[𝕜] (F →L[𝕜] E) :=
linear_isometry_equiv.of_surjective
{ norm_map' := adjoint_aux_norm,
..adjoint_aux }
(λ A, ⟨adjoint_aux A, adjoint_aux_adjoint_aux A⟩)
localized "postfix (name := adjoint) `†`:1000 := continuous_linear_map.adjoint" in inner_product
/-- The fundamental property of the adjoint. -/
lemma adjoint_inner_left (A : E →L[𝕜] F) (x : E) (y : F) : ⟪A† y, x⟫ = ⟪y, A x⟫ :=
adjoint_aux_inner_left A x y
/-- The fundamental property of the adjoint. -/
lemma adjoint_inner_right (A : E →L[𝕜] F) (x : E) (y : F) : ⟪x, A† y⟫ = ⟪A x, y⟫ :=
adjoint_aux_inner_right A x y
/-- The adjoint is involutive -/
@[simp] lemma adjoint_adjoint (A : E →L[𝕜] F) : A†† = A :=
adjoint_aux_adjoint_aux A
/-- The adjoint of the composition of two operators is the composition of the two adjoints
in reverse order. -/
@[simp] lemma adjoint_comp (A : F →L[𝕜] G) (B : E →L[𝕜] F) : (A ∘L B)† = B† ∘L A† :=
begin
ext v,
refine ext_inner_left 𝕜 (λ w, _),
simp only [adjoint_inner_right, continuous_linear_map.coe_comp', function.comp_app],
end
lemma apply_norm_sq_eq_inner_adjoint_left (A : E →L[𝕜] E) (x : E) : ∥A x∥^2 = re ⟪(A† * A) x, x⟫ :=
have h : ⟪(A† * A) x, x⟫ = ⟪A x, A x⟫ := by { rw [←adjoint_inner_left], refl },
by rw [h, ←inner_self_eq_norm_sq _]
lemma apply_norm_eq_sqrt_inner_adjoint_left (A : E →L[𝕜] E) (x : E) :
∥A x∥ = real.sqrt (re ⟪(A† * A) x, x⟫) :=
by rw [←apply_norm_sq_eq_inner_adjoint_left, real.sqrt_sq (norm_nonneg _)]
lemma apply_norm_sq_eq_inner_adjoint_right (A : E →L[𝕜] E) (x : E) : ∥A x∥^2 = re ⟪x, (A† * A) x⟫ :=
have h : ⟪x, (A† * A) x⟫ = ⟪A x, A x⟫ := by { rw [←adjoint_inner_right], refl },
by rw [h, ←inner_self_eq_norm_sq _]
lemma apply_norm_eq_sqrt_inner_adjoint_right (A : E →L[𝕜] E) (x : E) :
∥A x∥ = real.sqrt (re ⟪x, (A† * A) x⟫) :=
by rw [←apply_norm_sq_eq_inner_adjoint_right, real.sqrt_sq (norm_nonneg _)]
/-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫`
for all `x` and `y`. -/
lemma eq_adjoint_iff (A : E →L[𝕜] F) (B : F →L[𝕜] E) :
A = B† ↔ (∀ x y, ⟪A x, y⟫ = ⟪x, B y⟫) :=
begin
refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩,
ext x,
exact ext_inner_right 𝕜 (λ y, by simp only [adjoint_inner_left, h x y])
end
@[simp] lemma adjoint_id : (continuous_linear_map.id 𝕜 E).adjoint = continuous_linear_map.id 𝕜 E :=
begin
refine eq.symm _,
rw eq_adjoint_iff,
simp,
end
lemma _root_.submodule.adjoint_subtypeL (U : submodule 𝕜 E)
[complete_space U] :
(U.subtypeL)† = orthogonal_projection U :=
begin
symmetry,
rw eq_adjoint_iff,
intros x u,
rw [U.coe_inner, inner_orthogonal_projection_left_eq_right,
orthogonal_projection_mem_subspace_eq_self],
refl
end
lemma _root_.submodule.adjoint_orthogonal_projection (U : submodule 𝕜 E)
[complete_space U] :
(orthogonal_projection U : E →L[𝕜] U)† = U.subtypeL :=
by rw [← U.adjoint_subtypeL, adjoint_adjoint]
/-- `E →L[𝕜] E` is a star algebra with the adjoint as the star operation. -/
instance : has_star (E →L[𝕜] E) := ⟨adjoint⟩
instance : has_involutive_star (E →L[𝕜] E) := ⟨adjoint_adjoint⟩
instance : star_semigroup (E →L[𝕜] E) := ⟨adjoint_comp⟩
instance : star_ring (E →L[𝕜] E) := ⟨linear_isometry_equiv.map_add adjoint⟩
instance : star_module 𝕜 (E →L[𝕜] E) := ⟨linear_isometry_equiv.map_smulₛₗ adjoint⟩
lemma star_eq_adjoint (A : E →L[𝕜] E) : star A = A† := rfl
/-- A continuous linear operator is self-adjoint iff it is equal to its adjoint. -/
lemma is_self_adjoint_iff' {A : E →L[𝕜] E} : is_self_adjoint A ↔ A.adjoint = A := iff.rfl
instance : cstar_ring (E →L[𝕜] E) :=
⟨begin
intros A,
rw [star_eq_adjoint],
refine le_antisymm _ _,
{ calc ∥A† * A∥ ≤ ∥A†∥ * ∥A∥ : op_norm_comp_le _ _
... = ∥A∥ * ∥A∥ : by rw [linear_isometry_equiv.norm_map] },
{ rw [←sq, ←real.sqrt_le_sqrt_iff (norm_nonneg _), real.sqrt_sq (norm_nonneg _)],
refine op_norm_le_bound _ (real.sqrt_nonneg _) (λ x, _),
have := calc
re ⟪(A† * A) x, x⟫ ≤ ∥(A† * A) x∥ * ∥x∥ : re_inner_le_norm _ _
... ≤ ∥A† * A∥ * ∥x∥ * ∥x∥ : mul_le_mul_of_nonneg_right
(le_op_norm _ _) (norm_nonneg _),
calc ∥A x∥ = real.sqrt (re ⟪(A† * A) x, x⟫) : by rw [apply_norm_eq_sqrt_inner_adjoint_left]
... ≤ real.sqrt (∥A† * A∥ * ∥x∥ * ∥x∥) : real.sqrt_le_sqrt this
... = real.sqrt (∥A† * A∥) * ∥x∥
: by rw [mul_assoc, real.sqrt_mul (norm_nonneg _), real.sqrt_mul_self (norm_nonneg _)] }
end⟩
section real
variables {E' : Type*} {F' : Type*} [inner_product_space ℝ E'] [inner_product_space ℝ F']
variables [complete_space E'] [complete_space F']
-- Todo: Generalize this to `is_R_or_C`.
lemma is_adjoint_pair_inner (A : E' →L[ℝ] F') :
linear_map.is_adjoint_pair (sesq_form_of_inner : E' →ₗ[ℝ] E' →ₗ[ℝ] ℝ)
(sesq_form_of_inner : F' →ₗ[ℝ] F' →ₗ[ℝ] ℝ) A (A†) :=
λ x y, by simp only [sesq_form_of_inner_apply_apply, adjoint_inner_left, to_linear_map_eq_coe,
coe_coe]
end real
end continuous_linear_map
/-! ### Self-adjoint operators -/
namespace is_self_adjoint
open continuous_linear_map
variables [complete_space E] [complete_space F]
lemma adjoint_eq {A : E →L[𝕜] E} (hA : is_self_adjoint A) : A.adjoint = A := hA
/-- Every self-adjoint operator on an inner product space is symmetric. -/
lemma is_symmetric {A : E →L[𝕜] E} (hA : is_self_adjoint A) :
(A : E →ₗ[𝕜] E).is_symmetric :=
λ x y, by rw_mod_cast [←A.adjoint_inner_right, hA.adjoint_eq]
/-- Conjugating preserves self-adjointness -/
lemma conj_adjoint {T : E →L[𝕜] E} (hT : is_self_adjoint T) (S : E →L[𝕜] F) :
is_self_adjoint (S ∘L T ∘L S.adjoint) :=
begin
rw is_self_adjoint_iff' at ⊢ hT,
simp only [hT, adjoint_comp, adjoint_adjoint],
exact continuous_linear_map.comp_assoc _ _ _,
end
/-- Conjugating preserves self-adjointness -/
lemma adjoint_conj {T : E →L[𝕜] E} (hT : is_self_adjoint T) (S : F →L[𝕜] E) :
is_self_adjoint (S.adjoint ∘L T ∘L S) :=
begin
rw is_self_adjoint_iff' at ⊢ hT,
simp only [hT, adjoint_comp, adjoint_adjoint],
exact continuous_linear_map.comp_assoc _ _ _,
end
lemma _root_.continuous_linear_map.is_self_adjoint_iff_is_symmetric {A : E →L[𝕜] E} :
is_self_adjoint A ↔ (A : E →ₗ[𝕜] E).is_symmetric :=
⟨λ hA, hA.is_symmetric, λ hA, ext $ λ x, ext_inner_right 𝕜 $
λ y, (A.adjoint_inner_left y x).symm ▸ (hA x y).symm⟩
lemma _root_.linear_map.is_symmetric.is_self_adjoint {A : E →L[𝕜] E}
(hA : (A : E →ₗ[𝕜] E).is_symmetric) : is_self_adjoint A :=
by rwa ←continuous_linear_map.is_self_adjoint_iff_is_symmetric at hA
/-- The orthogonal projection is self-adjoint. -/
lemma _root_.orthogonal_projection_is_self_adjoint (U : submodule 𝕜 E)
[complete_space U] :
is_self_adjoint (U.subtypeL ∘L orthogonal_projection U) :=
(orthogonal_projection_is_symmetric U).is_self_adjoint
lemma conj_orthogonal_projection {T : E →L[𝕜] E}
(hT : is_self_adjoint T) (U : submodule 𝕜 E) [complete_space U] :
is_self_adjoint (U.subtypeL ∘L orthogonal_projection U ∘L T ∘L U.subtypeL ∘L
orthogonal_projection U) :=
begin
rw ←continuous_linear_map.comp_assoc,
nth_rewrite 0 ←(orthogonal_projection_is_self_adjoint U).adjoint_eq,
refine hT.adjoint_conj _,
end
end is_self_adjoint
namespace linear_map
variables [complete_space E]
variables {T : E →ₗ[𝕜] E}
/-- The **Hellinger--Toeplitz theorem**: Construct a self-adjoint operator from an everywhere
defined symmetric operator.-/
def is_symmetric.to_self_adjoint (hT : is_symmetric T) : self_adjoint (E →L[𝕜] E) :=
⟨⟨T, hT.continuous⟩, continuous_linear_map.is_self_adjoint_iff_is_symmetric.mpr hT⟩
lemma is_symmetric.coe_to_self_adjoint (hT : is_symmetric T) :
(hT.to_self_adjoint : E →ₗ[𝕜] E) = T := rfl
lemma is_symmetric.to_self_adjoint_apply (hT : is_symmetric T) {x : E} :
hT.to_self_adjoint x = T x := rfl
end linear_map
namespace linear_map
variables [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] [finite_dimensional 𝕜 G]
local attribute [instance, priority 20] finite_dimensional.complete
/-- The adjoint of an operator from the finite-dimensional inner product space E to the finite-
dimensional inner product space F. -/
def adjoint : (E →ₗ[𝕜] F) ≃ₗ⋆[𝕜] (F →ₗ[𝕜] E) :=
((linear_map.to_continuous_linear_map : (E →ₗ[𝕜] F) ≃ₗ[𝕜] (E →L[𝕜] F)).trans
continuous_linear_map.adjoint.to_linear_equiv).trans
linear_map.to_continuous_linear_map.symm
lemma adjoint_to_continuous_linear_map (A : E →ₗ[𝕜] F) :
A.adjoint.to_continuous_linear_map = A.to_continuous_linear_map.adjoint := rfl
lemma adjoint_eq_to_clm_adjoint (A : E →ₗ[𝕜] F) :
A.adjoint = A.to_continuous_linear_map.adjoint := rfl
/-- The fundamental property of the adjoint. -/
lemma adjoint_inner_left (A : E →ₗ[𝕜] F) (x : E) (y : F) : ⟪adjoint A y, x⟫ = ⟪y, A x⟫ :=
begin
rw [←coe_to_continuous_linear_map A, adjoint_eq_to_clm_adjoint],
exact continuous_linear_map.adjoint_inner_left _ x y,
end
/-- The fundamental property of the adjoint. -/
lemma adjoint_inner_right (A : E →ₗ[𝕜] F) (x : E) (y : F) : ⟪x, adjoint A y⟫ = ⟪A x, y⟫ :=
begin
rw [←coe_to_continuous_linear_map A, adjoint_eq_to_clm_adjoint],
exact continuous_linear_map.adjoint_inner_right _ x y,
end
/-- The adjoint is involutive -/
@[simp] lemma adjoint_adjoint (A : E →ₗ[𝕜] F) : A.adjoint.adjoint = A :=
begin
ext v,
refine ext_inner_left 𝕜 (λ w, _),
rw [adjoint_inner_right, adjoint_inner_left],
end
/-- The adjoint of the composition of two operators is the composition of the two adjoints
in reverse order. -/
@[simp] lemma adjoint_comp (A : F →ₗ[𝕜] G) (B : E →ₗ[𝕜] F) :
(A ∘ₗ B).adjoint = B.adjoint ∘ₗ A.adjoint :=
begin
ext v,
refine ext_inner_left 𝕜 (λ w, _),
simp only [adjoint_inner_right, linear_map.coe_comp, function.comp_app],
end
/-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫`
for all `x` and `y`. -/
lemma eq_adjoint_iff (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) :
A = B.adjoint ↔ (∀ x y, ⟪A x, y⟫ = ⟪x, B y⟫) :=
begin
refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩,
ext x,
exact ext_inner_right 𝕜 (λ y, by simp only [adjoint_inner_left, h x y])
end
/-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫`
for all basis vectors `x` and `y`. -/
lemma eq_adjoint_iff_basis {ι₁ : Type*} {ι₂ : Type*} (b₁ : basis ι₁ 𝕜 E) (b₂ : basis ι₂ 𝕜 F)
(A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) :
A = B.adjoint ↔ (∀ (i₁ : ι₁) (i₂ : ι₂), ⟪A (b₁ i₁), b₂ i₂⟫ = ⟪b₁ i₁, B (b₂ i₂)⟫) :=
begin
refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩,
refine basis.ext b₁ (λ i₁, _),
exact ext_inner_right_basis b₂ (λ i₂, by simp only [adjoint_inner_left, h i₁ i₂]),
end
lemma eq_adjoint_iff_basis_left {ι : Type*} (b : basis ι 𝕜 E) (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) :
A = B.adjoint ↔ (∀ i y, ⟪A (b i), y⟫ = ⟪b i, B y⟫) :=
begin
refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, basis.ext b (λ i, _)⟩,
exact ext_inner_right 𝕜 (λ y, by simp only [h i, adjoint_inner_left]),
end
lemma eq_adjoint_iff_basis_right {ι : Type*} (b : basis ι 𝕜 F) (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) :
A = B.adjoint ↔ (∀ i x, ⟪A x, b i⟫ = ⟪x, B (b i)⟫) :=
begin
refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩,
ext x,
refine ext_inner_right_basis b (λ i, by simp only [h i, adjoint_inner_left]),
end
/-- `E →ₗ[𝕜] E` is a star algebra with the adjoint as the star operation. -/
instance : has_star (E →ₗ[𝕜] E) := ⟨adjoint⟩
instance : has_involutive_star (E →ₗ[𝕜] E) := ⟨adjoint_adjoint⟩
instance : star_semigroup (E →ₗ[𝕜] E) := ⟨adjoint_comp⟩
instance : star_ring (E →ₗ[𝕜] E) := ⟨linear_equiv.map_add adjoint⟩
instance : star_module 𝕜 (E →ₗ[𝕜] E) := ⟨linear_equiv.map_smulₛₗ adjoint⟩
lemma star_eq_adjoint (A : E →ₗ[𝕜] E) : star A = A.adjoint := rfl
/-- A continuous linear operator is self-adjoint iff it is equal to its adjoint. -/
lemma is_self_adjoint_iff' {A : E →ₗ[𝕜] E} : is_self_adjoint A ↔ A.adjoint = A := iff.rfl
lemma is_symmetric_iff_is_self_adjoint (A : E →ₗ[𝕜] E) :
is_symmetric A ↔ is_self_adjoint A :=
by { rw [is_self_adjoint_iff', is_symmetric, ← linear_map.eq_adjoint_iff], exact eq_comm }
section real
variables {E' : Type*} {F' : Type*} [inner_product_space ℝ E'] [inner_product_space ℝ F']
variables [finite_dimensional ℝ E'] [finite_dimensional ℝ F']
-- Todo: Generalize this to `is_R_or_C`.
lemma is_adjoint_pair_inner (A : E' →ₗ[ℝ] F') :
is_adjoint_pair (sesq_form_of_inner : E' →ₗ[ℝ] E' →ₗ[ℝ] ℝ)
(sesq_form_of_inner : F' →ₗ[ℝ] F' →ₗ[ℝ] ℝ) A A.adjoint :=
λ x y, by simp only [sesq_form_of_inner_apply_apply, adjoint_inner_left]
end real
/-- The Gram operator T†T is symmetric. -/
lemma is_symmetric_adjoint_mul_self (T : E →ₗ[𝕜] E) : is_symmetric (T.adjoint * T) :=
λ x y, by simp only [mul_apply, adjoint_inner_left, adjoint_inner_right]
/-- The Gram operator T†T is a positive operator. -/
lemma re_inner_adjoint_mul_self_nonneg (T : E →ₗ[𝕜] E) (x : E) :
0 ≤ re ⟪ x, (T.adjoint * T) x ⟫ := by {simp only [mul_apply, adjoint_inner_right,
inner_self_eq_norm_sq_to_K], norm_cast, exact sq_nonneg _}
@[simp] lemma im_inner_adjoint_mul_self_eq_zero (T : E →ₗ[𝕜] E) (x : E) :
im ⟪ x, linear_map.adjoint T (T x) ⟫ = 0 := by {simp only [mul_apply,
adjoint_inner_right, inner_self_eq_norm_sq_to_K], norm_cast}
end linear_map
namespace matrix
variables {m n : Type*} [fintype m] [decidable_eq m] [fintype n] [decidable_eq n]
open_locale complex_conjugate
/-- The adjoint of the linear map associated to a matrix is the linear map associated to the
conjugate transpose of that matrix. -/
lemma conj_transpose_eq_adjoint (A : matrix m n 𝕜) :
to_lin' A.conj_transpose =
@linear_map.adjoint _ (euclidean_space 𝕜 n) (euclidean_space 𝕜 m) _ _ _ _ _ (to_lin' A) :=
begin
rw @linear_map.eq_adjoint_iff _ (euclidean_space 𝕜 m) (euclidean_space 𝕜 n),
intros x y,
convert dot_product_assoc (conj ∘ (id x : m → 𝕜)) y A using 1,
simp [dot_product, mul_vec, ring_hom.map_sum, ← star_ring_end_apply, mul_comm],
end
end matrix
|
4ab5bb579e7439c3b99dd76919789f0ed19c48c1 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/order/symm_diff.lean | 8ff6d2324906e5fb03a698e8b4fb0637bfedb7dd | [
"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 | 10,599 | lean | /-
Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz, Bryan Gin-ge Chen
-/
import order.boolean_algebra
/-!
# Symmetric difference
The symmetric difference or disjunctive union of sets `A` and `B` is the set of elements that are
in either `A` or `B` but not both. Translated into propositions, the symmetric difference is `xor`.
The symmetric difference operator (`symm_diff`) is defined in this file for any type with `⊔` and
`\` via the formula `(A \ B) ⊔ (B \ A)`, however the theorems proved about it only hold for
`generalized_boolean_algebra`s and `boolean_algebra`s.
The symmetric difference is the addition operator in the Boolean ring structure on Boolean algebras.
## Main declarations
* `symm_diff`: the symmetric difference operator, defined as `(A \ B) ⊔ (B \ A)`
In generalized Boolean algebras, the symmetric difference operator is:
* `symm_diff_comm`: commutative, and
* `symm_diff_assoc`: associative.
## Notations
* `a ∆ b`: `symm_diff a b`
## References
The proof of associativity follows the note "Associativity of the Symmetric Difference of Sets: A
Proof from the Book" by John McCuan:
* <https://people.math.gatech.edu/~mccuan/courses/4317/symmetricdifference.pdf>
## Tags
boolean ring, generalized boolean algebra, boolean algebra, symmetric differences
-/
/-- The symmetric difference operator on a type with `⊔` and `\` is `(A \ B) ⊔ (B \ A)`. -/
def symm_diff {α : Type*} [has_sup α] [has_sdiff α] (A B : α) : α := (A \ B) ⊔ (B \ A)
/- This notation might conflict with the Laplacian once we have it. Feel free to put it in locale
`order` or `symm_diff` if that happens. -/
infix ` ∆ `:100 := symm_diff
lemma symm_diff_def {α : Type*} [has_sup α] [has_sdiff α] (A B : α) :
A ∆ B = (A \ B) ⊔ (B \ A) :=
rfl
lemma symm_diff_eq_xor (p q : Prop) : p ∆ q = xor p q := rfl
section generalized_boolean_algebra
variables {α : Type*} [generalized_boolean_algebra α] (a b c d : α)
lemma symm_diff_comm : a ∆ b = b ∆ a := by simp only [(∆), sup_comm]
instance symm_diff_is_comm : is_commutative α (∆) := ⟨symm_diff_comm⟩
@[simp] lemma symm_diff_self : a ∆ a = ⊥ := by rw [(∆), sup_idem, sdiff_self]
@[simp] lemma symm_diff_bot : a ∆ ⊥ = a := by rw [(∆), sdiff_bot, bot_sdiff, sup_bot_eq]
@[simp] lemma bot_symm_diff : ⊥ ∆ a = a := by rw [symm_diff_comm, symm_diff_bot]
lemma symm_diff_eq_sup_sdiff_inf : a ∆ b = (a ⊔ b) \ (a ⊓ b) :=
by simp [sup_sdiff, sdiff_inf, sup_comm, (∆)]
@[simp] lemma sup_sdiff_symm_diff : (a ⊔ b) \ (a ∆ b) = a ⊓ b :=
sdiff_eq_symm inf_le_sup (by rw symm_diff_eq_sup_sdiff_inf)
lemma disjoint_symm_diff_inf : disjoint (a ∆ b) (a ⊓ b) :=
begin
rw [symm_diff_eq_sup_sdiff_inf],
exact disjoint_sdiff_self_left,
end
lemma symm_diff_le_sup : a ∆ b ≤ a ⊔ b := by { rw symm_diff_eq_sup_sdiff_inf, exact sdiff_le }
lemma inf_symm_diff_distrib_left : a ⊓ (b ∆ c) = (a ⊓ b) ∆ (a ⊓ c) :=
by rw [symm_diff_eq_sup_sdiff_inf, inf_sdiff_distrib_left, inf_sup_left, inf_inf_distrib_left,
symm_diff_eq_sup_sdiff_inf]
lemma inf_symm_diff_distrib_right : (a ∆ b) ⊓ c = (a ⊓ c) ∆ (b ⊓ c) :=
by simp_rw [@inf_comm _ _ _ c, inf_symm_diff_distrib_left]
lemma sdiff_symm_diff : c \ (a ∆ b) = (c ⊓ a ⊓ b) ⊔ ((c \ a) ⊓ (c \ b)) :=
by simp only [(∆), sdiff_sdiff_sup_sdiff']
lemma sdiff_symm_diff' : c \ (a ∆ b) = (c ⊓ a ⊓ b) ⊔ (c \ (a ⊔ b)) :=
by rw [sdiff_symm_diff, sdiff_sup, sup_comm]
lemma symm_diff_sdiff : (a ∆ b) \ c = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) :=
by rw [symm_diff_def, sup_sdiff, sdiff_sdiff_left, sdiff_sdiff_left]
@[simp] lemma symm_diff_sdiff_left : (a ∆ b) \ a = b \ a :=
by rw [symm_diff_def, sup_sdiff, sdiff_idem, sdiff_sdiff_self, bot_sup_eq]
@[simp] lemma symm_diff_sdiff_right : (a ∆ b) \ b = a \ b :=
by rw [symm_diff_comm, symm_diff_sdiff_left]
@[simp] lemma sdiff_symm_diff_self : a \ (a ∆ b) = a ⊓ b := by simp [sdiff_symm_diff]
lemma symm_diff_eq_iff_sdiff_eq {a b c : α} (ha : a ≤ c) :
a ∆ b = c ↔ c \ a = b :=
begin
split; intro h,
{ have hba : disjoint (a ⊓ b) c := begin
rw [←h, disjoint.comm],
exact disjoint_symm_diff_inf _ _,
end,
have hca : _ := congr_arg (\ a) h,
rw [symm_diff_sdiff_left] at hca,
rw [←hca, sdiff_eq_self_iff_disjoint],
exact hba.of_disjoint_inf_of_le ha },
{ have hd : disjoint a b := by { rw ←h, exact disjoint_sdiff_self_right },
rw [symm_diff_def, hd.sdiff_eq_left, hd.sdiff_eq_right, ←h, sup_sdiff_cancel_right ha] }
end
lemma disjoint.symm_diff_eq_sup {a b : α} (h : disjoint a b) : a ∆ b = a ⊔ b :=
by rw [(∆), h.sdiff_eq_left, h.sdiff_eq_right]
lemma symm_diff_eq_sup : a ∆ b = a ⊔ b ↔ disjoint a b :=
begin
split; intro h,
{ rw [symm_diff_eq_sup_sdiff_inf, sdiff_eq_self_iff_disjoint] at h,
exact h.of_disjoint_inf_of_le le_sup_left, },
{ exact h.symm_diff_eq_sup, },
end
lemma symm_diff_symm_diff_left :
a ∆ b ∆ c = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) :=
calc a ∆ b ∆ c = ((a ∆ b) \ c) ⊔ (c \ (a ∆ b)) : symm_diff_def _ _
... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔
((c \ (a ⊔ b)) ⊔ (c ⊓ a ⊓ b)) :
by rw [sdiff_symm_diff', @sup_comm _ _ (c ⊓ a ⊓ b), symm_diff_sdiff]
... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔
(c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) : by ac_refl
lemma symm_diff_symm_diff_right :
a ∆ (b ∆ c) = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) :=
calc a ∆ (b ∆ c) = (a \ (b ∆ c)) ⊔ ((b ∆ c) \ a) : symm_diff_def _ _
... = (a \ (b ⊔ c)) ⊔ (a ⊓ b ⊓ c) ⊔
(b \ (c ⊔ a) ⊔ c \ (b ⊔ a)) :
by rw [sdiff_symm_diff', @sup_comm _ _ (a ⊓ b ⊓ c), symm_diff_sdiff]
... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔
(c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) : by ac_refl
lemma symm_diff_assoc : a ∆ b ∆ c = a ∆ (b ∆ c) :=
by rw [symm_diff_symm_diff_left, symm_diff_symm_diff_right]
instance symm_diff_is_assoc : is_associative α (∆) := ⟨symm_diff_assoc⟩
lemma symm_diff_left_comm : a ∆ (b ∆ c) = b ∆ (a ∆ c) :=
by simp_rw [←symm_diff_assoc, symm_diff_comm]
lemma symm_diff_right_comm : a ∆ b ∆ c = a ∆ c ∆ b := by simp_rw [symm_diff_assoc, symm_diff_comm]
lemma symm_diff_symm_diff_symm_diff_comm : (a ∆ b) ∆ (c ∆ d) = (a ∆ c) ∆ (b ∆ d) :=
by simp_rw [symm_diff_assoc, symm_diff_left_comm]
@[simp] lemma symm_diff_symm_diff_self : a ∆ (a ∆ b) = b := by simp [←symm_diff_assoc]
@[simp] lemma symm_diff_symm_diff_self' : a ∆ b ∆ a = b :=
by rw [symm_diff_comm, ←symm_diff_assoc, symm_diff_self, bot_symm_diff]
@[simp] lemma symm_diff_right_inj : a ∆ b = a ∆ c ↔ b = c :=
begin
split; intro h,
{ have H1 := congr_arg ((∆) a) h,
rwa [symm_diff_symm_diff_self, symm_diff_symm_diff_self] at H1, },
{ rw h, },
end
@[simp] lemma symm_diff_left_inj : a ∆ b = c ∆ b ↔ a = c :=
by rw [symm_diff_comm a b, symm_diff_comm c b, symm_diff_right_inj]
@[simp] lemma symm_diff_eq_left : a ∆ b = a ↔ b = ⊥ :=
calc a ∆ b = a ↔ a ∆ b = a ∆ ⊥ : by rw symm_diff_bot
... ↔ b = ⊥ : by rw symm_diff_right_inj
@[simp] lemma symm_diff_eq_right : a ∆ b = b ↔ a = ⊥ := by rw [symm_diff_comm, symm_diff_eq_left]
@[simp] lemma symm_diff_eq_bot : a ∆ b = ⊥ ↔ a = b :=
calc a ∆ b = ⊥ ↔ a ∆ b = a ∆ a : by rw symm_diff_self
... ↔ a = b : by rw [symm_diff_right_inj, eq_comm]
@[simp] lemma symm_diff_symm_diff_inf : a ∆ b ∆ (a ⊓ b) = a ⊔ b :=
by rw [symm_diff_eq_iff_sdiff_eq (symm_diff_le_sup _ _), sup_sdiff_symm_diff]
@[simp] lemma inf_symm_diff_symm_diff : (a ⊓ b) ∆ (a ∆ b) = a ⊔ b :=
by rw [symm_diff_comm, symm_diff_symm_diff_inf]
variables {a b c}
protected lemma disjoint.symm_diff_left (ha : disjoint a c) (hb : disjoint b c) :
disjoint (a ∆ b) c :=
by { rw symm_diff_eq_sup_sdiff_inf, exact (ha.sup_left hb).disjoint_sdiff_left }
protected lemma disjoint.symm_diff_right (ha : disjoint a b) (hb : disjoint a c) :
disjoint a (b ∆ c) :=
(ha.symm.symm_diff_left hb.symm).symm
end generalized_boolean_algebra
section boolean_algebra
variables {α : Type*} [boolean_algebra α] (a b c : α)
lemma symm_diff_eq : a ∆ b = (a ⊓ bᶜ) ⊔ (b ⊓ aᶜ) := by simp only [(∆), sdiff_eq]
@[simp] lemma symm_diff_top : a ∆ ⊤ = aᶜ := by simp [symm_diff_eq]
@[simp] lemma top_symm_diff : ⊤ ∆ a = aᶜ := by rw [symm_diff_comm, symm_diff_top]
lemma compl_symm_diff : (a ∆ b)ᶜ = (a ⊓ b) ⊔ (aᶜ ⊓ bᶜ) :=
by simp only [←top_sdiff, sdiff_symm_diff, top_inf_eq]
lemma symm_diff_eq_top_iff : a ∆ b = ⊤ ↔ is_compl a b :=
by rw [symm_diff_eq_iff_sdiff_eq le_top, top_sdiff, compl_eq_iff_is_compl]
lemma is_compl.symm_diff_eq_top (h : is_compl a b) : a ∆ b = ⊤ := (symm_diff_eq_top_iff a b).2 h
@[simp] lemma compl_symm_diff_self : aᶜ ∆ a = ⊤ :=
by simp only [symm_diff_eq, compl_compl, inf_idem, compl_sup_eq_top]
@[simp] lemma symm_diff_compl_self : a ∆ aᶜ = ⊤ := by rw [symm_diff_comm, compl_symm_diff_self]
lemma symm_diff_symm_diff_right' :
a ∆ (b ∆ c) = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔ (aᶜ ⊓ b ⊓ cᶜ) ⊔ (aᶜ ⊓ bᶜ ⊓ c) :=
calc a ∆ (b ∆ c) = (a ⊓ ((b ⊓ c) ⊔ (bᶜ ⊓ cᶜ))) ⊔
(((b ⊓ cᶜ) ⊔ (c ⊓ bᶜ)) ⊓ aᶜ) : by rw [symm_diff_eq, compl_symm_diff,
symm_diff_eq]
... = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔
(b ⊓ cᶜ ⊓ aᶜ) ⊔ (c ⊓ bᶜ ⊓ aᶜ) : by rw [inf_sup_left, inf_sup_right,
←sup_assoc, ←inf_assoc, ←inf_assoc]
... = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔
(aᶜ ⊓ b ⊓ cᶜ) ⊔ (aᶜ ⊓ bᶜ ⊓ c) : begin
congr' 1,
{ congr' 1,
rw [inf_comm, inf_assoc], },
{ apply inf_left_right_swap }
end
end boolean_algebra
|
f211c7421b35ca22974c8bfa8d0a368ffd09bcb7 | 5e60919d574b821fabd9387be5589c0c4d3f3fe2 | /test/example.lean | 32c8b86f7d7faf95969b20cada117ab0e2d2606f | [] | no_license | unitb/unitb-pointers | 3fc72b873377a12e3f677ccd30143fc001a56c63 | c057420c1e72bba00181bc6db30cf369ef2bfd23 | refs/heads/master | 1,629,969,967,065 | 1,511,386,892,000 | 1,511,386,892,000 | 110,323,164 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 741 | lean |
import language.unitb.parser
open list -- unitb.parser
machine foo
variables x, y
invariants
bar: x ∪ y ⊆ x
initialization
x := ∅, y := ∅
events
move
when grd1 : ∅ ∈ x
then end
add_x begin x := y end
swap begin x,y := y,x end
proofs
bar :=
begin
simp [x_1,y_1], admit,
end,
end
#print foo.correctness
-- #print prefix foo.event.swap
-- #print prefix foo.event.move
#print foo.event.swap.step'
#print foo.event.add_x.step'
#print foo.event.move.step'
#print foo.event.spec
#print foo.init'
#print foo.spec
example (s : foo.state) (J : foo.inv s) : true :=
begin
induction s,
dunfold foo.inv at J,
induction J,
admit
end
example (k : foo.state) : true :=
begin
induction k,
admit
end
|
3d5cde0947524c41ba02133e14cbf9af1030dc7d | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/category_theory/limits/opposites.lean | 1a2f74f1909f08f0583e3e943e4954bf2a2e4cdd | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,375 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Floris van Doorn
-/
import category_theory.limits.shapes.products
import category_theory.discrete_category
universes v u
noncomputable theory
open category_theory
open category_theory.functor
open opposite
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
variables {J : Type v} [small_category J]
variable (F : J ⥤ Cᵒᵖ)
/--
If `F.left_op : Jᵒᵖ ⥤ C` has a colimit, we can construct a limit for `F : J ⥤ Cᵒᵖ`.
-/
lemma has_limit_of_has_colimit_left_op [has_colimit F.left_op] : has_limit F :=
has_limit.mk
{ cone := cone_of_cocone_left_op (colimit.cocone F.left_op),
is_limit :=
{ lift := λ s, (colimit.desc F.left_op (cocone_left_op_of_cone s)).op,
fac' := λ s j,
begin
rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, ←op_comp,
colimit.ι_desc, cocone_left_op_of_cone_ι_app, has_hom.hom.op_unop],
refl, end,
uniq' := λ s m w,
begin
-- It's a pity we can't do this automatically.
-- Usually something like this would work by limit.hom_ext,
-- but the opposites get in the way of this firing.
have u := (colimit.is_colimit F.left_op).uniq (cocone_left_op_of_cone s) (m.unop),
convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u,
intro j,
rw [cocone_left_op_of_cone_ι_app, colimit.cocone_ι],
convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w,
rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, has_hom.hom.unop_op],
refl,
end } }
/--
If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
lemma has_limits_of_shape_op_of_has_colimits_of_shape [has_colimits_of_shape Jᵒᵖ C] :
has_limits_of_shape J Cᵒᵖ :=
{ has_limit := λ F, has_limit_of_has_colimit_left_op F }
local attribute [instance] has_limits_of_shape_op_of_has_colimits_of_shape
/--
If `C` has colimits, we can construct limits for `Cᵒᵖ`.
-/
lemma has_limits_op_of_has_colimits [has_colimits C] : has_limits Cᵒᵖ := {}
/--
If `F.left_op : Jᵒᵖ ⥤ C` has a limit, we can construct a colimit for `F : J ⥤ Cᵒᵖ`.
-/
lemma has_colimit_of_has_limit_left_op [has_limit F.left_op] : has_colimit F :=
has_colimit.mk
{ cocone := cocone_of_cone_left_op (limit.cone F.left_op),
is_colimit :=
{ desc := λ s, (limit.lift F.left_op (cone_left_op_of_cocone s)).op,
fac' := λ s j,
begin
rw [cocone_of_cone_left_op_ι_app, limit.cone_π, ←op_comp,
limit.lift_π, cone_left_op_of_cocone_π_app, has_hom.hom.op_unop],
refl, end,
uniq' := λ s m w,
begin
have u := (limit.is_limit F.left_op).uniq (cone_left_op_of_cocone s) (m.unop),
convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u,
intro j,
rw [cone_left_op_of_cocone_π_app, limit.cone_π],
convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w,
rw [cocone_of_cone_left_op_ι_app, limit.cone_π, has_hom.hom.unop_op],
refl,
end } }
/--
If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
lemma has_colimits_of_shape_op_of_has_limits_of_shape [has_limits_of_shape Jᵒᵖ C] :
has_colimits_of_shape J Cᵒᵖ :=
{ has_colimit := λ F, has_colimit_of_has_limit_left_op F }
local attribute [instance] has_colimits_of_shape_op_of_has_limits_of_shape
/--
If `C` has limits, we can construct colimits for `Cᵒᵖ`.
-/
lemma has_colimits_op_of_has_limits [has_limits C] : has_colimits Cᵒᵖ := {}
variables (X : Type v)
/--
If `C` has products indexed by `X`, then `Cᵒᵖ` has coproducts indexed by `X`.
-/
lemma has_coproducts_opposite [has_products_of_shape X C] :
has_coproducts_of_shape X Cᵒᵖ :=
begin
haveI : has_limits_of_shape (discrete X)ᵒᵖ C :=
has_limits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
/--
If `C` has coproducts indexed by `X`, then `Cᵒᵖ` has products indexed by `X`.
-/
lemma has_products_opposite [has_coproducts_of_shape X C] :
has_products_of_shape X Cᵒᵖ :=
begin
haveI : has_colimits_of_shape (discrete X)ᵒᵖ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
end category_theory.limits
|
08f396439c2a890246128b3e95afc545e04ce356 | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/LP.lean | 7a1aeba69f091863a73be3f032ec96226e91515c | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 4,100 | lean | import .NN .misc system.io
variables {α : Type} [has_mul α] [add_comm_monoid α] [has_le α]
variables {k m n : nat}
structure LP (α : Type) (m n : nat) :=
(obf : N α)
(lhs : NN α)
(rhs : N α)
def LP.feasible : LP α m n → N α → Prop
| ⟨c, A, b⟩ x := N.le m (mul_vec n A x) b ∧ (N.le n (N.zero α) x)
def LP.is_feasible (P : LP α m n) : Prop :=
∃ x : N α, P.feasible x
instance LP.feasible.decidable [decidable_rel ((≤) : α → α → Prop)]
(P : LP α m n) (x : N α) : decidable (P.feasible x) :=
by {cases P, unfold LP.feasible, apply_instance }
open tactic
meta def Nx.repr (vx : expr) : nat → tactic string
| 0 := return ""
| (k + 1) :=
do vs ← Nx.repr k,
a ← to_expr ``(%%vx %%`(k)) >>= eval_expr rat,
return $ string.join [vs, " ", a.repr]
meta def NNx.repr_aux (Ax : expr) : nat → nat → tactic string
| 0 n := return ""
| (m + 1) n :=
do vs ← NNx.repr_aux m n,
a ← to_expr ``(%%Ax %%`(m) %%`(n)) >>= eval_expr rat,
return $ string.join [vs, " ", a.repr]
meta def NNx.repr (Ax : expr) (m : nat) : nat → tactic string
| 0 := return ""
| 1 := NNx.repr_aux Ax m 0
| (n + 1) :=
do As ← NNx.repr n,
vs ← NNx.repr_aux Ax m n,
return $ string.join [As, "\n", vs]
meta def put_LP : tactic (string × string × string) :=
do `(LP.is_feasible %%lp) ← target,
`(⟨%%cx, %%Ax, %%bx⟩ : LP _ _ _) ← pure lp,
`(LP _ %%mx %%nx) ← infer_type lp,
m ← eval_expr nat mx,
n ← eval_expr nat nx,
cs ← Nx.repr cx n,
As ← NNx.repr Ax m n,
bs ← Nx.repr bx m,
return ⟨cs, As, bs⟩
open tactic
-- meta instance int.has_reflect : has_reflect ℤ := by tactic.mk_has_reflect_instance
meta def rat.has_reflect' : Π x : ℚ, Σ y : ℚ, Σ' h : x = y, reflected y
| ⟨x,y,h,h'⟩ := ⟨rat.mk_nat x y, by { rw [rat.num_denom',rat.mk_nat_eq] } , `(_)⟩
-- meta instance : has_reflect ℚ
-- | x :=
-- match rat.has_reflect' x with
-- | ⟨ ._, rfl, h ⟩ := h
-- end
meta def cvxopt_lp (cs As bs : string) : tactic string :=
unsafe_run_io $ do
cwd ← io.env.get_cwd,
io.cmd {
cmd := "python3",
args := ["src/lp.py", cs, As, bs],
cwd := cwd
}
open parser
def digits : list char :=
[ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]
def parser_digits : parser string := many_char (one_of digits)
def parser_sign : parser bool :=
(ch '+' >> return tt) <|> (ch '-' >> return ff) <|> (return tt)
def parser_dnat : parser string :=
do d ← one_of digits,
ch '.',
ds ← parser_digits,
return ⟨d::ds.data⟩
def drop_zeroes : string → string := string.drop_chars '0'
def drop_trailing_nl (s : string) : string :=
(s.reverse.drop_chars '\n').reverse
def parser_mantissa : parser rat :=
do b ← parser_sign,
ds ← parser_dnat,
let i := int.of_nat (drop_zeroes ds).to_nat,
let numer : int := if b then i else -i,
let denom : ℕ := 10 ^ ds.length.pred,
return (rat.mk_nat numer denom)
def parser_magnitude : parser rat :=
do b ← parser_sign,
ds ← parser_digits,
let m : ℕ := 10 ^ (drop_zeroes ds).to_nat,
return (if b then (rat.mk_nat m 1) else (rat.mk_nat 1 m))
def parser_scinot : parser rat :=
do r ← parser_mantissa,
ch 'e',
s ← parser_magnitude,
return (r * s)
def ws : parser unit := many' (ch ' ')
def parser_entry : parser rat :=
ch '[' *> ws *> parser_scinot <* ws <* ch ']'
def parser_vector : parser (list rat) :=
sep_by (ch '\n') parser_entry
meta def LP.show_is_feasible : tactic unit :=
do ⟨cs, As, bs⟩ ← put_LP,
vs ← cvxopt_lp cs As bs,
match run_string parser_vector (drop_trailing_nl vs) with
| (sum.inl _) := fail "Cannot parse vector"
| (sum.inr rs) :=
do vx ← to_expr ``(@N.of_list rat _ %%`(rs)),
existsi vx,
exact_dec_trivial
end
def ex_c : N rat := N.of_list [2, 1]
def ex_A : NN rat := NN.of_lists rat [[-1, 1], [-1, -1], [0, -1], [1, -2]]
def ex_b : N rat := N.of_list [1, -2, 0, 4]
example : LP.is_feasible (⟨ex_c, ex_A, ex_b⟩ : LP _ 4 2) :=
by LP.show_is_feasible |
bcfc0afd9283f3682c6dcb6fe2760db482b7ae01 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/G_delta.lean | 71ae4d3de353eb1e96627d2f4d19b65c57a69770 | [
"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,845 | 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, Yury Kudryashov
-/
import topology.uniform_space.basic
import topology.separation
/-!
# `Gδ` sets
In this file we define `Gδ` sets and prove their basic properties.
## Main definitions
* `is_Gδ`: a set `s` is a `Gδ` set if it can be represented as an intersection
of countably many open sets;
* `residual`: the filter of residual sets. A set `s` is called *residual* if it includes a dense
`Gδ` set. In a Baire space (e.g., in a complete (e)metric space), residual sets form a filter.
For technical reasons, we define `residual` in any topological space but the definition agrees
with the description above only in Baire spaces.
## Main results
We prove that finite or countable intersections of Gδ sets is a Gδ set. We also prove that the
continuity set of a function from a topological space to an (e)metric space is a Gδ set.
## Tags
Gδ set, residual set
-/
noncomputable theory
open_locale classical topological_space filter uniformity
open filter encodable set
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
section is_Gδ
variable [topological_space α]
/-- A Gδ set is a countable intersection of open sets. -/
def is_Gδ (s : set α) : Prop :=
∃T : set (set α), (∀t ∈ T, is_open t) ∧ T.countable ∧ s = (⋂₀ T)
/-- An open set is a Gδ set. -/
lemma is_open.is_Gδ {s : set α} (h : is_open s) : is_Gδ s :=
⟨{s}, by simp [h], countable_singleton _, (set.sInter_singleton _).symm⟩
@[simp] lemma is_Gδ_empty : is_Gδ (∅ : set α) := is_open_empty.is_Gδ
@[simp] lemma is_Gδ_univ : is_Gδ (univ : set α) := is_open_univ.is_Gδ
lemma is_Gδ_bInter_of_open {I : set ι} (hI : I.countable) {f : ι → set α}
(hf : ∀i ∈ I, is_open (f i)) : is_Gδ (⋂i∈I, f i) :=
⟨f '' I, by rwa ball_image_iff, hI.image _, by rw sInter_image⟩
lemma is_Gδ_Inter_of_open [encodable ι] {f : ι → set α}
(hf : ∀i, is_open (f i)) : is_Gδ (⋂i, f i) :=
⟨range f, by rwa forall_range_iff, countable_range _, by rw sInter_range⟩
/-- The intersection of an encodable family of Gδ sets is a Gδ set. -/
lemma is_Gδ_Inter [encodable ι] {s : ι → set α} (hs : ∀ i, is_Gδ (s i)) : is_Gδ (⋂ i, s i) :=
begin
choose T hTo hTc hTs using hs,
obtain rfl : s = λ i, ⋂₀ T i := funext hTs,
refine ⟨⋃ i, T i, _, countable_Union hTc, (sInter_Union _).symm⟩,
simpa [@forall_swap ι] using hTo
end
lemma is_Gδ_bInter {s : set ι} (hs : s.countable) {t : Π i ∈ s, set α}
(ht : ∀ i ∈ s, is_Gδ (t i ‹_›)) : is_Gδ (⋂ i ∈ s, t i ‹_›) :=
begin
rw [bInter_eq_Inter],
haveI := hs.to_encodable,
exact is_Gδ_Inter (λ x, ht x x.2)
end
/-- A countable intersection of Gδ sets is a Gδ set. -/
lemma is_Gδ_sInter {S : set (set α)} (h : ∀s∈S, is_Gδ s) (hS : S.countable) : is_Gδ (⋂₀ S) :=
by simpa only [sInter_eq_bInter] using is_Gδ_bInter hS h
lemma is_Gδ.inter {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∩ t) :=
by { rw inter_eq_Inter, exact is_Gδ_Inter (bool.forall_bool.2 ⟨ht, hs⟩) }
/-- The union of two Gδ sets is a Gδ set. -/
lemma is_Gδ.union {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∪ t) :=
begin
rcases hs with ⟨S, Sopen, Scount, rfl⟩,
rcases ht with ⟨T, Topen, Tcount, rfl⟩,
rw [sInter_union_sInter],
apply is_Gδ_bInter_of_open (Scount.prod Tcount),
rintros ⟨a, b⟩ ⟨ha, hb⟩,
exact (Sopen a ha).union (Topen b hb)
end
/-- The union of finitely many Gδ sets is a Gδ set. -/
lemma is_Gδ_bUnion {s : set ι} (hs : s.finite) {f : ι → set α} (h : ∀ i ∈ s, is_Gδ (f i)) :
is_Gδ (⋃ i ∈ s, f i) :=
begin
refine finite.induction_on hs (by simp) _ h,
simp only [ball_insert_iff, bUnion_insert],
exact λ a s _ _ ihs H, H.1.union (ihs H.2)
end
lemma is_closed.is_Gδ {α} [uniform_space α] [is_countably_generated (𝓤 α)]
{s : set α} (hs : is_closed s) : is_Gδ s :=
begin
rcases (@uniformity_has_basis_open α _).exists_antitone_subbasis with ⟨U, hUo, hU, -⟩,
rw [← hs.closure_eq, ← hU.bInter_bUnion_ball],
refine is_Gδ_bInter (to_countable _) (λ n hn, is_open.is_Gδ _),
exact is_open_bUnion (λ x hx, uniform_space.is_open_ball _ (hUo _).2)
end
section t1_space
variable [t1_space α]
lemma is_Gδ_compl_singleton (a : α) : is_Gδ ({a}ᶜ : set α) :=
is_open_compl_singleton.is_Gδ
lemma set.countable.is_Gδ_compl {s : set α} (hs : s.countable) : is_Gδ sᶜ :=
begin
rw [← bUnion_of_singleton s, compl_Union₂],
exact is_Gδ_bInter hs (λ x _, is_Gδ_compl_singleton x)
end
lemma set.finite.is_Gδ_compl {s : set α} (hs : s.finite) : is_Gδ sᶜ :=
hs.countable.is_Gδ_compl
lemma set.subsingleton.is_Gδ_compl {s : set α} (hs : s.subsingleton) : is_Gδ sᶜ :=
hs.finite.is_Gδ_compl
lemma finset.is_Gδ_compl (s : finset α) : is_Gδ (sᶜ : set α) :=
s.finite_to_set.is_Gδ_compl
open topological_space
variables [first_countable_topology α]
lemma is_Gδ_singleton (a : α) : is_Gδ ({a} : set α) :=
begin
rcases (nhds_basis_opens a).exists_antitone_subbasis with ⟨U, hU, h_basis⟩,
rw [← bInter_basis_nhds h_basis.to_has_basis],
exact is_Gδ_bInter (to_countable _) (λ n hn, (hU n).2.is_Gδ),
end
lemma set.finite.is_Gδ {s : set α} (hs : s.finite) : is_Gδ s :=
finite.induction_on hs is_Gδ_empty $ λ a s _ _ hs, (is_Gδ_singleton a).union hs
end t1_space
end is_Gδ
section continuous_at
open topological_space
open_locale uniformity
variables [topological_space α]
/-- The set of points where a function is continuous is a Gδ set. -/
lemma is_Gδ_set_of_continuous_at [uniform_space β] [is_countably_generated (𝓤 β)] (f : α → β) :
is_Gδ {x | continuous_at f x} :=
begin
obtain ⟨U, hUo, hU⟩ := (@uniformity_has_basis_open_symmetric β _).exists_antitone_subbasis,
simp only [uniform.continuous_at_iff_prod, nhds_prod_eq],
simp only [(nhds_basis_opens _).prod_self.tendsto_iff hU.to_has_basis, forall_prop_of_true,
set_of_forall, id],
refine is_Gδ_Inter (λ k, is_open.is_Gδ $ is_open_iff_mem_nhds.2 $ λ x, _),
rintros ⟨s, ⟨hsx, hso⟩, hsU⟩,
filter_upwards [is_open.mem_nhds hso hsx] with _ hy using ⟨s, ⟨hy, hso⟩, hsU⟩,
end
end continuous_at
/-- A set `s` is called *residual* if it includes a dense `Gδ` set. If `α` is a Baire space
(e.g., a complete metric space), then residual sets form a filter, see `mem_residual`.
For technical reasons we define the filter `residual` in any topological space but in a non-Baire
space it is not useful because it may contain some non-residual sets. -/
def residual (α : Type*) [topological_space α] : filter α :=
⨅ t (ht : is_Gδ t) (ht' : dense t), 𝓟 t
|
ca737ec81faef5780395c44f6a1f9b06a88e0362 | 54deab7025df5d2df4573383df7e1e5497b7a2c2 | /data/bool.lean | 8581d671abd1c90dd7b8c9fa3d1a8cb1e5c5c16f | [
"Apache-2.0"
] | permissive | HGldJ1966/mathlib | f8daac93a5b4ae805cfb0ecebac21a9ce9469009 | c5c5b504b918a6c5e91e372ee29ed754b0513e85 | refs/heads/master | 1,611,340,395,683 | 1,503,040,489,000 | 1,503,040,489,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,605 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad
-/
namespace bool
-- TODO(Jeremy): is this right?
@[simp] theorem coe_tt : (↑tt : Prop) := dec_trivial
theorem band_tt (a : bool) : a && tt = a := by cases a; refl
theorem tt_band (a : bool) : tt && a = a := by cases a; refl
theorem band_ff (a : bool) : a && ff = ff := by cases a; refl
theorem ff_band (a : bool) : ff && a = ff := by cases a; refl
theorem bor_tt (a : bool) : a || tt = tt := by cases a; refl
theorem tt_bor (a : bool) : tt || a = tt := by cases a; refl
theorem bor_ff (a : bool) : a || ff = a := by cases a; refl
theorem ff_bor (a : bool) : ff || a = a := by cases a; refl
attribute [simp] band_tt tt_band band_ff ff_band bor_tt tt_bor bor_ff ff_bor
theorem band_eq_tt (a b : bool) : (a && b = tt) = (a = tt ∧ b = tt) :=
by cases a; cases b; simp
theorem band_eq_ff (a b : bool) : (a && b = ff) = (a = ff ∨ b = ff) :=
by cases a; cases b; simp
theorem bor_eq_tt (a b : bool) : (a || b = tt) = (a = tt ∨ b = tt) :=
by cases a; cases b; simp
theorem bor_eq_ff (a b : bool) : (a || b = ff) = (a = ff ∧ b = ff) :=
by cases a; cases b; simp
theorem dichotomy (b : bool) : b = ff ∨ b = tt :=
by cases b; simp
@[simp] theorem cond_ff {A : Type} (t e : A) : cond ff t e = e := rfl
@[simp] theorem cond_tt {A : Type} (t e : A) : cond tt t e = t := rfl
theorem eq_tt_of_ne_ff {a : bool} : a ≠ ff → a = tt :=
by cases a; simp
theorem eq_ff_of_ne_tt {a : bool} : a ≠ tt → a = ff :=
by cases a; simp
theorem absurd_of_eq_ff_of_eq_tt {B : Prop} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B :=
by cases a; contradiction
@[simp] theorem bor_comm (a b : bool) : a || b = b || a :=
by cases a; cases b; simp
@[simp] theorem bor_assoc (a b c : bool) : (a || b) || c = a || (b || c) :=
by cases a; cases b; simp
@[simp] theorem bor_left_comm (a b c : bool) : a || (b || c) = b || (a || c) :=
by cases a; cases b; simp
theorem or_of_bor_eq {a b : bool} : a || b = tt → a = tt ∨ b = tt :=
begin cases a, simp, intro h, simp [h], simp end
theorem bor_inl {a b : bool} (H : a = tt) : a || b = tt :=
by simp [H]
theorem bor_inr {a b : bool} (H : b = tt) : a || b = tt :=
by simp [H]
@[simp] theorem band_self (a : bool) : a && a = a :=
by cases a; simp
@[simp] theorem band_comm (a b : bool) : a && b = b && a :=
by cases a; simp
@[simp] theorem band_assoc (a b c : bool) : (a && b) && c = a && (b && c) :=
by cases a; simp
@[simp] theorem band_left_comm (a b c : bool) : a && (b && c) = b && (a && c) :=
by cases a; simp
theorem band_elim_left {a b : bool} (H : a && b = tt) : a = tt :=
begin cases a, simp at H, simp [H] end
theorem band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt :=
begin cases a, simp [H₁, H₂], simp [H₂] end
theorem band_elim_right {a b : bool} (H : a && b = tt) : b = tt :=
begin cases a, contradiction, simp at H, exact H end
@[simp] theorem bnot_false : bnot ff = tt := rfl
@[simp] theorem bnot_true : bnot tt = ff := rfl
@[simp] theorem bnot_bnot (a : bool) : bnot (bnot a) = a :=
by cases a; simp
theorem eq_tt_of_bnot_eq_ff {a : bool} : bnot a = ff → a = tt :=
by cases a; simp
theorem eq_ff_of_bnot_eq_tt {a : bool} : bnot a = tt → a = ff :=
by cases a; simp
def bxor : bool → bool → bool
| ff ff := ff
| ff tt := tt
| tt ff := tt
| tt tt := ff
@[simp] theorem ff_bxor_ff : bxor ff ff = ff := rfl
@[simp] theorem ff_bxor_tt : bxor ff tt = tt := rfl
@[simp] theorem tt_bxor_ff : bxor tt ff = tt := rfl
@[simp] theorem tt_bxor_tt : bxor tt tt = ff := rfl
@[simp] theorem bxor_self (a : bool) : bxor a a = ff :=
by cases a; simp
@[simp] theorem bxor_ff (a : bool) : bxor a ff = a :=
by cases a; simp
@[simp] theorem bxor_tt (a : bool) : bxor a tt = bnot a :=
by cases a; simp
@[simp] theorem ff_bxor (a : bool) : bxor ff a = a :=
by cases a; simp
@[simp] theorem tt_bxor (a : bool) : bxor tt a = bnot a :=
by cases a; simp
@[simp] theorem bxor_comm (a b : bool) : bxor a b = bxor b a :=
by cases a; simp
@[simp] theorem bxor_assoc (a b c : bool) : bxor (bxor a b) c = bxor a (bxor b c) :=
by cases a; cases b; simp
@[simp] theorem bxor_left_comm (a b c : bool) : bxor a (bxor b c) = bxor b (bxor a c) :=
by cases a; cases b; simp
instance forall_decidable {P : bool → Prop} [decidable_pred P] : decidable (∀b, P b) :=
suffices P ff ∧ P tt ↔ _, from decidable_of_decidable_of_iff (by apply_instance) this,
⟨λ⟨pf, pt⟩ b, bool.rec_on b pf pt, λal, ⟨al _, al _⟩⟩
end bool
|
de72b907f00462bf48c5c92b9d1b9f53ca0630db | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /kb_solns/sets_level09.lean | c7e90bc4da6d71224e40bfc6e796e141d5242d2f | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 776 | lean | import data.real.basic
/-
# Chapter 1 : Sets
## Level 9
-/
/-
This is a little more complicated example asking you to work with intervals of reals.
The result will be of help in the sup-inf world.
-/
notation `[` a `,` b `]` := set.Icc a b
def mem_prod_sets (A : set ℝ) (B : set ℝ) := { x : ℝ | ∃ y ∈ A, ∃ z ∈ B, x = y * z}
/- Lemma
Prove that if $x = 0$, then `x ∈ mem_prod_sets [(-2:ℝ),-1] [(0:ℝ), 3]`
-/
lemma zero_in_prod : (0:ℝ) ∈ mem_prod_sets [(-2:ℝ), -1] [(0:ℝ), 3] :=
begin
set a0 := (0:ℝ) with ha,
have h1 : a0 ∈ (set.Icc (0:ℝ) 3), simp, linarith,
set b := (-2:ℝ) with hb,
have h2 : b ∈ set.Icc (-2:ℝ) (-1:ℝ), simp, linarith,
use b, split, exact h2,
use a0, split, exact h1, rw ha, norm_num, done
end
|
43a4b653e8903f7e32bc9277844bcd56020c57ee | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/ideal/associated_prime.lean | 5306118f8f003218f846d5a7f01835655dcf48b0 | [
"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,401 | 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 linear_algebra.span
import ring_theory.ideal.operations
import ring_theory.ideal.quotient_operations
import ring_theory.noetherian
/-!
# Associated primes of a module
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We provide the definition and related lemmas about associated primes of modules.
## Main definition
- `is_associated_prime`: `is_associated_prime I M` if the prime ideal `I` is the
annihilator of some `x : M`.
- `associated_primes`: The set of associated primes of a module.
## Main results
- `exists_le_is_associated_prime_of_is_noetherian_ring`: In a noetherian ring, any `ann(x)` is
contained in an associated prime for `x ≠ 0`.
- `associated_primes.eq_singleton_of_is_primary`: In a noetherian ring, `I.radical` is the only
associated prime of `R ⧸ I` when `I` is primary.
## Todo
Generalize this to a non-commutative setting once there are annihilator for non-commutative rings.
-/
variables {R : Type*} [comm_ring R] (I J : ideal R) (M : Type*) [add_comm_group M] [module R M]
/-- `is_associated_prime I M` if the prime ideal `I` is the annihilator of some `x : M`. -/
def is_associated_prime : Prop :=
I.is_prime ∧ ∃ x : M, I = (R ∙ x).annihilator
variables (R)
/-- The set of associated primes of a module. -/
def associated_primes : set (ideal R) := { I | is_associated_prime I M }
variables {I J M R} (h : is_associated_prime I M)
variables {M' : Type*} [add_comm_group M'] [module R M'] (f : M →ₗ[R] M')
lemma associate_primes.mem_iff : I ∈ associated_primes R M ↔ is_associated_prime I M := iff.rfl
lemma is_associated_prime.is_prime : I.is_prime := h.1
lemma is_associated_prime.map_of_injective
(h : is_associated_prime I M) (hf : function.injective f) :
is_associated_prime I M' :=
begin
obtain ⟨x, rfl⟩ := h.2,
refine ⟨h.1, ⟨f x, _⟩⟩,
ext r,
rw [submodule.mem_annihilator_span_singleton, submodule.mem_annihilator_span_singleton,
← map_smul, ← f.map_zero, hf.eq_iff],
end
lemma linear_equiv.is_associated_prime_iff (l : M ≃ₗ[R] M') :
is_associated_prime I M ↔ is_associated_prime I M' :=
⟨λ h, h.map_of_injective l l.injective, λ h, h.map_of_injective l.symm l.symm.injective⟩
lemma not_is_associated_prime_of_subsingleton [subsingleton M] : ¬ is_associated_prime I M :=
begin
rintro ⟨hI, x, hx⟩,
apply hI.ne_top,
rwa [subsingleton.elim x 0, submodule.span_singleton_eq_bot.mpr rfl,
submodule.annihilator_bot] at hx
end
variable (R)
lemma exists_le_is_associated_prime_of_is_noetherian_ring [H : is_noetherian_ring R]
(x : M) (hx : x ≠ 0) :
∃ P : ideal R, is_associated_prime P M ∧ (R ∙ x).annihilator ≤ P :=
begin
have : (R ∙ x).annihilator ≠ ⊤,
{ rwa [ne.def, ideal.eq_top_iff_one, submodule.mem_annihilator_span_singleton, one_smul] },
obtain ⟨P, ⟨l, h₁, y, rfl⟩, h₃⟩ := set_has_maximal_iff_noetherian.mpr H
({ P | (R ∙ x).annihilator ≤ P ∧ P ≠ ⊤ ∧ ∃ y : M, P = (R ∙ y).annihilator })
⟨(R ∙ x).annihilator, rfl.le, this, x, rfl⟩,
refine ⟨_, ⟨⟨h₁, _⟩, y, rfl⟩, l⟩,
intros a b hab,
rw or_iff_not_imp_left,
intro ha,
rw submodule.mem_annihilator_span_singleton at ha hab,
have H₁ : (R ∙ y).annihilator ≤ (R ∙ a • y).annihilator,
{ intros c hc,
rw submodule.mem_annihilator_span_singleton at hc ⊢,
rw [smul_comm, hc, smul_zero] },
have H₂ : (submodule.span R {a • y}).annihilator ≠ ⊤,
{ rwa [ne.def, submodule.annihilator_eq_top_iff, submodule.span_singleton_eq_bot] },
rwa [H₁.eq_of_not_lt (h₃ (R ∙ a • y).annihilator ⟨l.trans H₁, H₂, _, rfl⟩),
submodule.mem_annihilator_span_singleton, smul_comm, smul_smul]
end
variable {R}
lemma associated_primes.subset_of_injective (hf : function.injective f) :
associated_primes R M ⊆ associated_primes R M' :=
λ I h, h.map_of_injective f hf
lemma linear_equiv.associated_primes.eq (l : M ≃ₗ[R] M') :
associated_primes R M = associated_primes R M' :=
le_antisymm (associated_primes.subset_of_injective l l.injective)
(associated_primes.subset_of_injective l.symm l.symm.injective)
lemma associated_primes.eq_empty_of_subsingleton [subsingleton M] : associated_primes R M = ∅ :=
begin
ext, simp only [set.mem_empty_iff_false, iff_false], apply not_is_associated_prime_of_subsingleton
end
variables (R M)
lemma associated_primes.nonempty [is_noetherian_ring R] [nontrivial M] :
(associated_primes R M).nonempty :=
begin
obtain ⟨x, hx⟩ := exists_ne (0 : M),
obtain ⟨P, hP, _⟩ := exists_le_is_associated_prime_of_is_noetherian_ring R x hx,
exact ⟨P, hP⟩,
end
variables {R M}
lemma is_associated_prime.annihilator_le (h : is_associated_prime I M) :
(⊤ : submodule R M).annihilator ≤ I :=
begin
obtain ⟨hI, x, rfl⟩ := h,
exact submodule.annihilator_mono le_top,
end
lemma is_associated_prime.eq_radical (hI : I.is_primary) (h : is_associated_prime J (R ⧸ I)) :
J = I.radical :=
begin
obtain ⟨hJ, x, e⟩ := h,
have : x ≠ 0,
{ rintro rfl, apply hJ.1,
rwa [submodule.span_singleton_eq_bot.mpr rfl, submodule.annihilator_bot] at e },
obtain ⟨x, rfl⟩ := ideal.quotient.mkₐ_surjective R _ x,
replace e : ∀ {y}, y ∈ J ↔ x * y ∈ I,
{ intro y, rw [e, submodule.mem_annihilator_span_singleton, ← map_smul, smul_eq_mul, mul_comm,
ideal.quotient.mkₐ_eq_mk, ← ideal.quotient.mk_eq_mk, submodule.quotient.mk_eq_zero] },
apply le_antisymm,
{ intros y hy,
exact (hI.2 $ e.mp hy).resolve_left ((submodule.quotient.mk_eq_zero I).not.mp this) },
{ rw hJ.radical_le_iff, intros y hy, exact e.mpr (I.mul_mem_left x hy) }
end
lemma associated_primes.eq_singleton_of_is_primary [is_noetherian_ring R] (hI : I.is_primary) :
associated_primes R (R ⧸ I) = {I.radical} :=
begin
ext J,
rw [set.mem_singleton_iff],
refine ⟨is_associated_prime.eq_radical hI, _⟩,
rintro rfl,
haveI : nontrivial (R ⧸ I) := ⟨⟨(I^.quotient.mk : _) 1, (I^.quotient.mk : _) 0, _⟩⟩,
obtain ⟨a, ha⟩ := associated_primes.nonempty R (R ⧸ I),
exact ha.eq_radical hI ▸ ha,
rw [ne.def, ideal.quotient.eq, sub_zero, ← ideal.eq_top_iff_one],
exact hI.1
end
|
dcf54c31ff53ec38d4a25d1b91942b5b77a36e85 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/field_theory/adjoin.lean | caaa9d554f777a828ef7852de7ae252c2621407d | [
"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 | 45,292 | lean | /-
Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Patrick Lutz
-/
import field_theory.intermediate_field
import field_theory.separable
import ring_theory.tensor_product
/-!
# Adjoining Elements to Fields
In this file we introduce the notion of adjoining elements to fields.
This isn't quite the same as adjoining elements to rings.
For example, `algebra.adjoin K {x}` might not include `x⁻¹`.
## Main results
- `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`.
- `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x`
in `E` then `F = E`
## Notation
- `F⟮α⟯`: adjoin a single element `α` to `F`.
-/
open finite_dimensional polynomial
open_locale classical polynomial
namespace intermediate_field
section adjoin_def
variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E)
/-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/
def adjoin : intermediate_field F E :=
{ algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)),
..subfield.closure (set.range (algebra_map F E) ∪ S) }
end adjoin_def
section lattice
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
@[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T :=
⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H,
λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr
(set.union_subset (intermediate_field.set_range_subset T) H)⟩
lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff
/-- Galois insertion between `adjoin` and `coe`. -/
def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe :=
{ choice := λ s hs, (adjoin F s).copy s $ le_antisymm (gc.le_u_l s) hs,
gc := intermediate_field.gc,
le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_rfl,
choice_eq := λ _ _, copy_eq _ _ _ }
instance : complete_lattice (intermediate_field F E) :=
galois_insertion.lift_complete_lattice intermediate_field.gi
instance : inhabited (intermediate_field F E) := ⟨⊤⟩
lemma coe_bot : ↑(⊥ : intermediate_field F E) = set.range (algebra_map F E) :=
begin
change ↑(subfield.closure (set.range (algebra_map F E) ∪ ∅)) = set.range (algebra_map F E),
simp [←set.image_univ, ←ring_hom.map_field_closure]
end
lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) :=
set.ext_iff.mp coe_bot x
@[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ :=
by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] }
@[simp] lemma coe_top : ↑(⊤ : intermediate_field F E) = (set.univ : set E) := rfl
@[simp] lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) :=
trivial
@[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ :=
rfl
@[simp] lemma top_to_subfield : (⊤ : intermediate_field F E).to_subfield = ⊤ :=
rfl
@[simp, norm_cast]
lemma coe_inf (S T : intermediate_field F E) : (↑(S ⊓ T) : set E) = S ∩ T := rfl
@[simp]
lemma mem_inf {S T : intermediate_field F E} {x : E} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl
@[simp] lemma inf_to_subalgebra (S T : intermediate_field F E) :
(S ⊓ T).to_subalgebra = S.to_subalgebra ⊓ T.to_subalgebra :=
rfl
@[simp] lemma inf_to_subfield (S T : intermediate_field F E) :
(S ⊓ T).to_subfield = S.to_subfield ⊓ T.to_subfield :=
rfl
@[simp, norm_cast]
lemma coe_Inf (S : set (intermediate_field F E)) : (↑(Inf S) : set E) = Inf (coe '' S) := rfl
@[simp] lemma Inf_to_subalgebra (S : set (intermediate_field F E)) :
(Inf S).to_subalgebra = Inf (to_subalgebra '' S) :=
set_like.coe_injective $ by simp [set.sUnion_image]
@[simp] lemma Inf_to_subfield (S : set (intermediate_field F E)) :
(Inf S).to_subfield = Inf (to_subfield '' S) :=
set_like.coe_injective $ by simp [set.sUnion_image]
@[simp, norm_cast]
lemma coe_infi {ι : Sort*} (S : ι → intermediate_field F E) : (↑(infi S) : set E) = ⋂ i, (S i) :=
by simp [infi]
@[simp] lemma infi_to_subalgebra {ι : Sort*} (S : ι → intermediate_field F E) :
(infi S).to_subalgebra = ⨅ i, (S i).to_subalgebra :=
set_like.coe_injective $ by simp [infi]
@[simp] lemma infi_to_subfield {ι : Sort*} (S : ι → intermediate_field F E) :
(infi S).to_subfield = ⨅ i, (S i).to_subfield :=
set_like.coe_injective $ by simp [infi]
/-- Construct an algebra isomorphism from an equality of intermediate fields -/
@[simps apply]
def equiv_of_eq {S T : intermediate_field F E} (h : S = T) : S ≃ₐ[F] T :=
by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy
@[simp] lemma equiv_of_eq_symm {S T : intermediate_field F E} (h : S = T) :
(equiv_of_eq h).symm = equiv_of_eq h.symm :=
rfl
@[simp] lemma equiv_of_eq_rfl (S : intermediate_field F E) :
equiv_of_eq (rfl : S = S) = alg_equiv.refl :=
by { ext, refl }
@[simp] lemma equiv_of_eq_trans {S T U : intermediate_field F E} (hST : S = T) (hTU : T = U) :
(equiv_of_eq hST).trans (equiv_of_eq hTU) = equiv_of_eq (trans hST hTU) :=
rfl
variables (F E)
/-- The bottom intermediate_field is isomorphic to the field. -/
noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F :=
(subalgebra.equiv_of_eq _ _ bot_to_subalgebra).trans (algebra.bot_equiv F E)
variables {F E}
@[simp] lemma bot_equiv_def (x : F) :
bot_equiv F E (algebra_map F (⊥ : intermediate_field F E) x) = x :=
alg_equiv.commutes (bot_equiv F E) x
@[simp] lemma bot_equiv_symm (x : F) :
(bot_equiv F E).symm x = algebra_map F _ x :=
rfl
noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F :=
(intermediate_field.bot_equiv F E).to_alg_hom.to_ring_hom.to_algebra
lemma coe_algebra_map_over_bot :
(algebra_map (⊥ : intermediate_field F E) F : (⊥ : intermediate_field F E) → F) =
(intermediate_field.bot_equiv F E) :=
rfl
instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E :=
is_scalar_tower.of_algebra_map_eq
begin
intro x,
obtain ⟨y, rfl⟩ := (bot_equiv F E).symm.surjective x,
rw [coe_algebra_map_over_bot, (bot_equiv F E).apply_symm_apply, bot_equiv_symm,
is_scalar_tower.algebra_map_apply F (⊥ : intermediate_field F E) E]
end
/-- The top intermediate_field is isomorphic to the field.
This is the intermediate field version of `subalgebra.top_equiv`. -/
@[simps apply] def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E :=
(subalgebra.equiv_of_eq _ _ top_to_subalgebra).trans subalgebra.top_equiv
@[simp] lemma top_equiv_symm_apply_coe (a : E) :
↑((top_equiv.symm) a : (⊤ : intermediate_field F E)) = a := rfl
@[simp] lemma restrict_scalars_bot_eq_self (K : intermediate_field F E) :
(⊥ : intermediate_field K E).restrict_scalars _ = K :=
by { ext, rw [mem_restrict_scalars, mem_bot], exact set.ext_iff.mp subtype.range_coe x }
@[simp] lemma restrict_scalars_top {K : Type*} [field K] [algebra K E] [algebra K F]
[is_scalar_tower K F E] :
(⊤ : intermediate_field F E).restrict_scalars K = ⊤ :=
rfl
lemma _root_.alg_hom.field_range_eq_map {K : Type*} [field K] [algebra F K] (f : E →ₐ[F] K) :
f.field_range = intermediate_field.map f ⊤ :=
set_like.ext' set.image_univ.symm
lemma _root_.alg_hom.map_field_range {K L : Type*} [field K] [field L] [algebra F K] [algebra F L]
(f : E →ₐ[F] K) (g : K →ₐ[F] L) : f.field_range.map g = (g.comp f).field_range :=
set_like.ext' (set.range_comp g f).symm
end lattice
section adjoin_def
variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E)
lemma adjoin_eq_range_algebra_map_adjoin :
(adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm
lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S :=
intermediate_field.algebra_map_mem (adjoin F S) x
lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S :=
begin
intros x hx,
cases hx with f hf,
rw ← hf,
exact adjoin.algebra_map_mem F S f,
end
instance adjoin.field_coe : has_coe_t F (adjoin F S) :=
{coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩}
lemma subset_adjoin : S ⊆ adjoin F S :=
λ x hx, subfield.subset_closure (or.inr hx)
instance adjoin.set_coe : has_coe_t S (adjoin F S) :=
{coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩}
@[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T :=
galois_connection.monotone_l gc h
lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S :=
λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩
lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S :=
λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩
lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S :=
λ x hx, subset_adjoin F S (H hx)
@[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] :
adjoin F (∅ : set E) = ⊥ :=
eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _))
@[simp] lemma adjoin_univ (F E : Type*) [field F] [field E] [algebra F E] :
adjoin F (set.univ : set E) = ⊤ :=
eq_top_iff.mpr $ subset_adjoin _ _
/-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/
lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K)
(HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K :=
begin
apply subfield.closure_le.mpr,
rw set.union_subset_iff,
exact ⟨HF, HS⟩,
end
lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E]
{S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔
set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' :=
⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩,
λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩
/-- `F[S][T] = F[S ∪ T]` -/
lemma adjoin_adjoin_left (T : set E) :
(adjoin (adjoin F S) T).restrict_scalars _ = adjoin F (S ∪ T) :=
begin
rw set_like.ext'_iff,
change ↑(adjoin (adjoin F S) T) = _,
apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split,
{ rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx },
{ exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) },
{ exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) },
{ exact set.union_subset
(subset_adjoin_of_subset_left _ (subset_adjoin _ _))
(subset_adjoin _ _) },
end
@[simp] lemma adjoin_insert_adjoin (x : E) :
adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) :=
le_antisymm
(adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _),
adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩))
(adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _)))
/-- `F[S][T] = F[T][S]` -/
lemma adjoin_adjoin_comm (T : set E) :
(adjoin (adjoin F S) T).restrict_scalars F = (adjoin (adjoin F T) S).restrict_scalars F :=
by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm]
lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') :
(adjoin F S).map f = adjoin F (f '' S) :=
begin
ext x,
show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔
x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S),
rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp,
f.comp_algebra_map],
refl,
end
lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra :=
algebra.adjoin_le (subset_adjoin _ _)
lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) :
(adjoin F S).to_subalgebra = algebra.adjoin F S :=
le_antisymm
(show adjoin F S ≤
{ neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S},
from adjoin_le_iff.mpr (algebra.subset_adjoin))
(algebra_adjoin_le_adjoin _ _)
lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E)
(h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S :=
begin
apply to_subalgebra_injective,
rw h,
refine (adjoin_eq_algebra_adjoin _ _ _).symm,
intros x,
convert K.inv_mem,
rw ← h,
refl
end
@[elab_as_eliminator]
lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s)
(Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x))
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hneg : ∀ x, p x → p (-x))
(Hinv : ∀ x, p x → p x⁻¹)
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x))
((algebra_map F E).map_one ▸ Hmap 1)
Hadd Hneg Hinv Hmul
/--
Variation on `set.insert` to enable good notation for adjoining elements to fields.
Used to preferentially use `singleton` rather than `insert` when adjoining one element.
-/
--this definition of notation is courtesy of Kyle Miller on zulip
class insert {α : Type*} (s : set α) :=
(insert : α → set α)
@[priority 1000]
instance insert_empty {α : Type*} : insert (∅ : set α) :=
{ insert := λ x, @singleton _ _ set.has_singleton x }
@[priority 900]
instance insert_nonempty {α : Type*} (s : set α) : insert s :=
{ insert := λ x, has_insert.insert x s }
notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l
section adjoin_simple
variables (α : E)
lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ :=
subset_adjoin F {α} (set.mem_singleton α)
/-- generator of `F⟮α⟯` -/
def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩
@[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl
@[simp] lemma adjoin_simple.is_integral_gen :
is_integral F (adjoin_simple.gen F α) ↔ is_integral F α :=
by { conv_rhs { rw ← adjoin_simple.algebra_map_gen F α },
rw is_integral_algebra_map_iff (algebra_map F⟮α⟯ E).injective,
apply_instance }
lemma adjoin_simple_adjoin_simple (β : E) : F⟮α⟯⟮β⟯.restrict_scalars F = F⟮α, β⟯ :=
adjoin_adjoin_left _ _ _
lemma adjoin_simple_comm (β : E) : F⟮α⟯⟮β⟯.restrict_scalars F = F⟮β⟯⟮α⟯.restrict_scalars F :=
adjoin_adjoin_comm _ _ _
variables {F} {α}
lemma adjoin_algebraic_to_subalgebra
{S : set E} (hS : ∀ x ∈ S, is_algebraic F x) :
(intermediate_field.adjoin F S).to_subalgebra = algebra.adjoin F S :=
begin
simp only [is_algebraic_iff_is_integral] at hS,
have : algebra.is_integral F (algebra.adjoin F S) :=
by rwa [←le_integral_closure_iff_is_integral, algebra.adjoin_le_iff],
have := is_field_of_is_integral_of_is_field' this (field.to_is_field F),
rw ← ((algebra.adjoin F S).to_intermediate_field' this).eq_adjoin_of_eq_algebra_adjoin F S; refl,
end
lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) :
(F⟮α⟯).to_subalgebra = algebra.adjoin F {α} :=
begin
apply adjoin_algebraic_to_subalgebra,
rintro x (rfl : x = α),
rwa is_algebraic_iff_is_integral,
end
lemma is_splitting_field_iff {p : F[X]} {K : intermediate_field F E} :
p.is_splitting_field F K ↔ p.splits (algebra_map F K) ∧ K = adjoin F (p.root_set E) :=
begin
suffices : _ → ((algebra.adjoin F (p.root_set K) = ⊤ ↔ K = adjoin F (p.root_set E))),
{ exact ⟨λ h, ⟨h.1, (this h.1).mp h.2⟩, λ h, ⟨h.1, (this h.1).mpr h.2⟩⟩ },
simp_rw [set_like.ext_iff, ←mem_to_subalgebra, ←set_like.ext_iff],
rw [←K.range_val, adjoin_algebraic_to_subalgebra (λ x, is_algebraic_of_mem_root_set)],
exact λ hp, (adjoin_root_set_eq_range hp K.val).symm.trans eq_comm,
end
lemma adjoin_root_set_is_splitting_field {p : F[X]} (hp : p.splits (algebra_map F E)) :
p.is_splitting_field F (adjoin F (p.root_set E)) :=
is_splitting_field_iff.mpr ⟨splits_of_splits hp (λ x hx, subset_adjoin F (p.root_set E) hx), rfl⟩
open_locale big_operators
/-- A compositum of splitting fields is a splitting field -/
lemma is_splitting_field_supr {ι : Type*} {t : ι → intermediate_field F E} {p : ι → F[X]}
{s : finset ι} (h0 : ∏ i in s, p i ≠ 0) (h : ∀ i ∈ s, (p i).is_splitting_field F (t i)) :
(∏ i in s, p i).is_splitting_field F (⨆ i ∈ s, t i : intermediate_field F E) :=
begin
let K : intermediate_field F E := ⨆ i ∈ s, t i,
have hK : ∀ i ∈ s, t i ≤ K := λ i hi, le_supr_of_le i (le_supr (λ _, t i) hi),
simp only [is_splitting_field_iff] at h ⊢,
refine ⟨splits_prod (algebra_map F K) (λ i hi, polynomial.splits_comp_of_splits
(algebra_map F (t i)) (inclusion (hK i hi)).to_ring_hom (h i hi).1), _⟩,
simp only [root_set_prod p s h0, ←set.supr_eq_Union, (@gc F _ E _ _).l_supr₂],
exact supr_congr (λ i, supr_congr (λ hi, (h i hi).2)),
end
open set complete_lattice
@[simp] lemma adjoin_simple_le_iff {K : intermediate_field F E} : F⟮α⟯ ≤ K ↔ α ∈ K :=
adjoin_le_iff.trans singleton_subset_iff
/-- Adjoining a single element is compact in the lattice of intermediate fields. -/
lemma adjoin_simple_is_compact_element (x : E) : is_compact_element F⟮x⟯ :=
begin
rw is_compact_element_iff_le_of_directed_Sup_le,
rintros s ⟨F₀, hF₀⟩ hs hx,
simp only [adjoin_simple_le_iff] at hx ⊢,
let F : intermediate_field F E :=
{ carrier := ⋃ E ∈ s, ↑E,
add_mem' := by
{ rintros x₁ x₂ ⟨-, ⟨F₁, rfl⟩, ⟨-, ⟨hF₁, rfl⟩, hx₁⟩⟩ ⟨-, ⟨F₂, rfl⟩, ⟨-, ⟨hF₂, rfl⟩, hx₂⟩⟩,
obtain ⟨F₃, hF₃, h₁₃, h₂₃⟩ := hs F₁ hF₁ F₂ hF₂,
exact mem_Union_of_mem F₃ (mem_Union_of_mem hF₃ (F₃.add_mem (h₁₃ hx₁) (h₂₃ hx₂))) },
neg_mem' := by
{ rintros x ⟨-, ⟨E, rfl⟩, ⟨-, ⟨hE, rfl⟩, hx⟩⟩,
exact mem_Union_of_mem E (mem_Union_of_mem hE (E.neg_mem hx)) },
mul_mem' := by
{ rintros x₁ x₂ ⟨-, ⟨F₁, rfl⟩, ⟨-, ⟨hF₁, rfl⟩, hx₁⟩⟩ ⟨-, ⟨F₂, rfl⟩, ⟨-, ⟨hF₂, rfl⟩, hx₂⟩⟩,
obtain ⟨F₃, hF₃, h₁₃, h₂₃⟩ := hs F₁ hF₁ F₂ hF₂,
exact mem_Union_of_mem F₃ (mem_Union_of_mem hF₃ (F₃.mul_mem (h₁₃ hx₁) (h₂₃ hx₂))) },
inv_mem' := by
{ rintros x ⟨-, ⟨E, rfl⟩, ⟨-, ⟨hE, rfl⟩, hx⟩⟩,
exact mem_Union_of_mem E (mem_Union_of_mem hE (E.inv_mem hx)) },
algebra_map_mem' := λ x, mem_Union_of_mem F₀ (mem_Union_of_mem hF₀ (F₀.algebra_map_mem x)) },
have key : Sup s ≤ F := Sup_le (λ E hE, subset_Union_of_subset E (subset_Union _ hE)),
obtain ⟨-, ⟨E, rfl⟩, -, ⟨hE, rfl⟩, hx⟩ := key hx,
exact ⟨E, hE, hx⟩,
end
/-- Adjoining a finite subset is compact in the lattice of intermediate fields. -/
lemma adjoin_finset_is_compact_element (S : finset E) :
is_compact_element (adjoin F S : intermediate_field F E) :=
begin
have key : adjoin F ↑S = ⨆ x ∈ S, F⟮x⟯ :=
le_antisymm (adjoin_le_iff.mpr (λ x hx, set_like.mem_coe.mpr (adjoin_simple_le_iff.mp
(le_supr_of_le x (le_supr_of_le hx le_rfl)))))
(supr_le (λ x, supr_le (λ hx, adjoin_simple_le_iff.mpr (subset_adjoin F S hx)))),
rw [key, ←finset.sup_eq_supr],
exact finset_sup_compact_of_compact S (λ x hx, adjoin_simple_is_compact_element x),
end
/-- Adjoining a finite subset is compact in the lattice of intermediate fields. -/
lemma adjoin_finite_is_compact_element {S : set E} (h : S.finite) :
is_compact_element (adjoin F S) :=
finite.coe_to_finset h ▸ (adjoin_finset_is_compact_element h.to_finset)
/-- The lattice of intermediate fields is compactly generated. -/
instance : is_compactly_generated (intermediate_field F E) :=
⟨λ s, ⟨(λ x, F⟮x⟯) '' s, ⟨by rintros t ⟨x, hx, rfl⟩; exact adjoin_simple_is_compact_element x,
Sup_image.trans (le_antisymm (supr_le (λ i, supr_le (λ hi, adjoin_simple_le_iff.mpr hi)))
(λ x hx, adjoin_simple_le_iff.mp (le_supr_of_le x (le_supr_of_le hx le_rfl))))⟩⟩⟩
lemma exists_finset_of_mem_supr {ι : Type*} {f : ι → intermediate_field F E}
{x : E} (hx : x ∈ ⨆ i, f i) : ∃ s : finset ι, x ∈ ⨆ i ∈ s, f i :=
begin
have := (adjoin_simple_is_compact_element x).exists_finset_of_le_supr (intermediate_field F E) f,
simp only [adjoin_simple_le_iff] at this,
exact this hx,
end
lemma exists_finset_of_mem_supr' {ι : Type*} {f : ι → intermediate_field F E}
{x : E} (hx : x ∈ ⨆ i, f i) : ∃ s : finset (Σ i, f i), x ∈ ⨆ i ∈ s, F⟮(i.2 : E)⟯ :=
exists_finset_of_mem_supr (set_like.le_def.mp (supr_le
(λ i x h, set_like.le_def.mp (le_supr_of_le ⟨i, x, h⟩ le_rfl) (mem_adjoin_simple_self F x))) hx)
lemma exists_finset_of_mem_supr'' {ι : Type*} {f : ι → intermediate_field F E}
(h : ∀ i, algebra.is_algebraic F (f i)) {x : E} (hx : x ∈ ⨆ i, f i) :
∃ s : finset (Σ i, f i), x ∈ ⨆ i ∈ s, adjoin F ((minpoly F (i.2 : _)).root_set E) :=
begin
refine exists_finset_of_mem_supr (set_like.le_def.mp (supr_le (λ i x hx, set_like.le_def.mp
(le_supr_of_le ⟨i, x, hx⟩ le_rfl) (subset_adjoin F _ _))) hx),
rw [intermediate_field.minpoly_eq, subtype.coe_mk, polynomial.mem_root_set, minpoly.aeval],
exact minpoly.ne_zero (is_integral_iff.mp (is_algebraic_iff_is_integral.mp (h i ⟨x, hx⟩)))
end
end adjoin_simple
end adjoin_def
section adjoin_intermediate_field_lattice
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E}
@[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) :=
by { rw [eq_bot_iff, adjoin_le_iff], refl, }
@[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff }
@[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥)
@[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (one_mem ⊥)
@[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n)
@[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (coe_nat_mem ⊥ n)
section adjoin_dim
open finite_dimensional module
variables {K L : intermediate_field F E}
@[simp] lemma dim_eq_one_iff : module.rank F K = 1 ↔ K = ⊥ :=
by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra,
subalgebra.dim_eq_one_iff, bot_to_subalgebra]
@[simp] lemma finrank_eq_one_iff : finrank F K = 1 ↔ K = ⊥ :=
by rw [← to_subalgebra_eq_iff, ← finrank_eq_finrank_subalgebra,
subalgebra.finrank_eq_one_iff, bot_to_subalgebra]
@[simp] lemma dim_bot : module.rank F (⊥ : intermediate_field F E) = 1 :=
by rw dim_eq_one_iff
@[simp] lemma finrank_bot : finrank F (⊥ : intermediate_field F E) = 1 :=
by rw finrank_eq_one_iff
lemma dim_adjoin_eq_one_iff : module.rank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) :=
iff.trans dim_eq_one_iff adjoin_eq_bot_iff
lemma dim_adjoin_simple_eq_one_iff : module.rank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff }
lemma finrank_adjoin_eq_one_iff : finrank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) :=
iff.trans finrank_eq_one_iff adjoin_eq_bot_iff
lemma finrank_adjoin_simple_eq_one_iff : finrank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw [finrank_adjoin_eq_one_iff], exact set.singleton_subset_iff }
/-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/
lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) :
(⊥ : intermediate_field F E) = ⊤ :=
begin
ext,
rw iff_true_right intermediate_field.mem_top,
exact dim_adjoin_simple_eq_one_iff.mp (h x),
end
lemma bot_eq_top_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) :
(⊥ : intermediate_field F E) = ⊤ :=
begin
ext,
rw iff_true_right intermediate_field.mem_top,
exact finrank_adjoin_simple_eq_one_iff.mp (h x),
end
lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) :
subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h)
lemma subsingleton_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) :
subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_eq_one h)
/-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/
lemma bot_eq_top_of_finrank_adjoin_le_one [finite_dimensional F E]
(h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ :=
begin
apply bot_eq_top_of_finrank_adjoin_eq_one,
exact λ x, by linarith [h x, show 0 < finrank F F⟮x⟯, from finrank_pos],
end
lemma subsingleton_of_finrank_adjoin_le_one [finite_dimensional F E]
(h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_le_one h)
end adjoin_dim
end adjoin_intermediate_field_lattice
section adjoin_integral_element
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E}
variables {K : Type*} [field K] [algebra F K]
lemma minpoly_gen {α : E} (h : is_integral F α) :
minpoly F (adjoin_simple.gen F α) = minpoly F α :=
begin
rw ← adjoin_simple.algebra_map_gen F α at h,
have inj := (algebra_map F⟮α⟯ E).injective,
exact minpoly.eq_of_algebra_map_eq inj ((is_integral_algebra_map_iff inj).mp h)
(adjoin_simple.algebra_map_gen _ _).symm
end
variables (F)
lemma aeval_gen_minpoly (α : E) :
aeval (adjoin_simple.gen F α) (minpoly F α) = 0 :=
begin
ext,
convert minpoly.aeval F α,
conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] },
exact is_scalar_tower.algebra_map_aeval F F⟮α⟯ E _ _
end
/-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/
noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) :
adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ :=
alg_equiv.of_bijective
(adjoin_root.lift_hom (minpoly F α) (adjoin_simple.gen F α) (aeval_gen_minpoly F α))
(begin
set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α : _),
haveI := fact.mk (minpoly.irreducible h),
split,
{ exact ring_hom.injective f },
{ suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f),
{ exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy⟩) },
exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy,
⟨y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩))
(set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α),
by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩)) } end)
lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) :
adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) =
adjoin_simple.gen F α :=
adjoin_root.lift_root (aeval_gen_minpoly F α)
section power_basis
variables {L : Type*} [field L] [algebra K L]
/-- The elements `1, x, ..., x ^ (d - 1)` form a basis for `K⟮x⟯`,
where `d` is the degree of the minimal polynomial of `x`. -/
noncomputable def power_basis_aux {x : L} (hx : is_integral K x) :
basis (fin (minpoly K x).nat_degree) K K⟮x⟯ :=
(adjoin_root.power_basis (minpoly.ne_zero hx)).basis.map
(adjoin_root_equiv_adjoin K hx).to_linear_equiv
/-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`,
where `d` is the degree of the minimal polynomial of `x`. -/
@[simps]
noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) :
power_basis K K⟮x⟯ :=
{ gen := adjoin_simple.gen K x,
dim := (minpoly K x).nat_degree,
basis := power_basis_aux hx,
basis_eq_pow := λ i,
by rw [power_basis_aux, basis.map_apply, power_basis.basis_eq_pow,
alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow, adjoin_root.power_basis_gen,
adjoin_root_equiv_adjoin_apply_root] }
lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ :=
power_basis.finite_dimensional (adjoin.power_basis hx)
lemma adjoin.finrank {x : L} (hx : is_integral K x) :
finite_dimensional.finrank K K⟮x⟯ = (minpoly K x).nat_degree :=
begin
rw power_basis.finrank (adjoin.power_basis hx : _),
refl
end
end power_basis
/-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots
of `minpoly α` in `K`. -/
noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) :
(F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} :=
(adjoin.power_basis h).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x,
by rw [adjoin.power_basis_gen, minpoly_gen h, equiv.refl_apply]))
/-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/
noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) :
fintype (F⟮α⟯ →ₐ[F] K) :=
power_basis.alg_hom.fintype (adjoin.power_basis h)
lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable)
(h_splits : (minpoly F α).splits (algebra_map F K)) :
@fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) =
(minpoly F α).nat_degree :=
begin
rw alg_hom.card_of_power_basis;
simp only [adjoin.power_basis_dim, adjoin.power_basis_gen, minpoly_gen h, h_sep, h_splits],
end
end adjoin_integral_element
section induction
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
/-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that
`intermediate_field.adjoin F t = S`. -/
def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S
lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg :=
⟨t, rfl⟩
theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S :=
iff.symm set.exists_finite_iff_finset
theorem fg_bot : (⊥ : intermediate_field F E).fg :=
⟨∅, adjoin_empty F E⟩
lemma fg_of_fg_to_subalgebra (S : intermediate_field F E)
(h : S.to_subalgebra.fg) : S.fg :=
begin
cases h with t ht,
exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩
end
lemma fg_of_noetherian (S : intermediate_field F E)
[is_noetherian F E] : S.fg :=
S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian
lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥)
(ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P (K⟮x⟯.restrict_scalars F)) :
P (adjoin F ↑S) :=
begin
apply finset.induction_on' S,
{ exact base },
{ intros a s h1 _ _ h4,
rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left],
exact ih (adjoin F s) a h1 h4 }
end
lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop)
(base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P (K⟮x⟯.restrict_scalars F))
(K : intermediate_field F E) (hK : K.fg) : P K :=
begin
obtain ⟨S, rfl⟩ := hK,
exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK),
end
lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop)
(base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P (K⟮x⟯.restrict_scalars F))
(K : intermediate_field F E) : P K :=
begin
letI : is_noetherian F E := is_noetherian.iff_fg.2 infer_instance,
exact induction_on_adjoin_fg P base ih K K.fg_of_noetherian
end
end induction
section alg_hom_mk_adjoin_splits
variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E}
/-- Lifts `L → K` of `F → K` -/
def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K)
variables {F E K}
instance : partial_order (lifts F E K) :=
{ le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t),
le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩,
le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans
(hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩,
le_antisymm :=
begin
rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩,
obtain rfl : x1 = y1 := le_antisymm hxy1 hyx1,
congr,
exact alg_hom.ext (λ s, hxy2 s s rfl),
end }
noncomputable instance : order_bot (lifts F E K) :=
{ bot := ⟨⊥, (algebra.of_id F K).comp (bot_equiv F E).to_alg_hom⟩,
bot_le := λ x, ⟨bot_le, λ s t hst,
begin
cases intermediate_field.mem_bot.mp s.mem with u hu,
rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes],
rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes],
end⟩ }
noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩
lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) :
x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl
lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : is_chain (≤) c)
(hx : x ∈ has_insert.insert ⊥ c) (hy : y ∈ has_insert.insert ⊥ c) :
∃ z : lifts F E K, z ∈ has_insert.insert ⊥ c ∧ x ≤ z ∧ y ≤ z :=
begin
cases (hc.insert $ λ _ _ _, or.inl bot_le).total hx hy with hxy hyx,
{ exact ⟨y, hy, hxy, le_refl y⟩ },
{ exact ⟨x, hx, le_refl x, hyx⟩ },
end
lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : is_chain (≤) c)
(hx : x ∈ has_insert.insert ⊥ c) (hy : y ∈ has_insert.insert ⊥ c)
(hz : z ∈ has_insert.insert ⊥ c) :
∃ w : lifts F E K, w ∈ has_insert.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w :=
begin
obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy,
obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv,
exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩,
end
/-- An upper bound on a chain of lifts -/
def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : is_chain (≤) c) :
intermediate_field F E :=
{ carrier := λ s, ∃ x : (lifts F E K), x ∈ has_insert.insert ⊥ c ∧ (s ∈ x.1 : Prop),
zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩,
one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩,
neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ },
inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ },
add_mem' := by
{ rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy,
exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ },
mul_mem' := by
{ rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy,
exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ },
algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ }
/-- The lift on the upper bound on a chain of lifts -/
noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : is_chain (≤) c) :
lifts.upper_bound_intermediate_field hc →ₐ[F] K :=
{ to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩,
map_zero' := alg_hom.map_zero _,
map_one' := alg_hom.map_one _,
map_add' := λ s t, begin
obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc
(classical.some_spec s.mem).1 (classical.some_spec t.mem).1
(classical.some_spec (s + t).mem).1,
rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add],
refl,
end,
map_mul' := λ s t, begin
obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc
(classical.some_spec s.mem).1 (classical.some_spec t.mem).1
(classical.some_spec (s * t).mem).1,
rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul],
refl,
end,
commutes' := λ _, alg_hom.commutes _ _ }
/-- An upper bound on a chain of lifts -/
noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : is_chain (≤) c) :
lifts F E K :=
⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩
lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : is_chain (≤) c) :
∃ ub, ∀ a ∈ c, a ≤ ub :=
⟨lifts.upper_bound hc,
begin
intros x hx,
split,
{ exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ },
{ intros s t hst,
change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx)
(classical.some_spec t.mem).1,
rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz],
exact congr_arg z.2 (subtype.ext hst) },
end⟩
/-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/
noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K :=
let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower s h1 in
let key : (minpoly x.1 s).splits x.2.to_ring_hom :=
splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1))
((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)}))
(minpoly.dvd_map_of_is_scalar_tower _ _ _) in
⟨x.1⟮s⟯.restrict_scalars F, (@alg_hom_equiv_sigma F x.1 (x.1⟮s⟯.restrict_scalars F) K _ _ _ _ _ _ _
(intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun
⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra
h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by
{ simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map],
exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩
lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 :=
⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin
rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)],
letI : algebra x.1 K := x.2.to_ring_hom.to_algebra,
exact (alg_hom.commutes _ t),
end⟩
lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 :=
mem_adjoin_simple_self x.1 s
lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 :=
⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩
lemma alg_hom_mk_adjoin_splits
(hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) :
nonempty (adjoin F S →ₐ[F] K) :=
begin
obtain ⟨x : lifts F E K, hx⟩ := zorn_partial_order lifts.exists_upper_bound,
refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t,
x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩,
rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩,
rwa hx y h1 at h2
end
lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤)
(hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) :
nonempty (E →ₐ[F] K) :=
begin
cases alg_hom_mk_adjoin_splits hK with ϕ,
rw hS at ϕ,
exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩,
end
end alg_hom_mk_adjoin_splits
section supremum
variables {K L : Type*} [field K] [field L] [algebra K L] (E1 E2 : intermediate_field K L)
lemma le_sup_to_subalgebra :
E1.to_subalgebra ⊔ E2.to_subalgebra ≤ (E1 ⊔ E2).to_subalgebra :=
sup_le (show E1 ≤ E1 ⊔ E2, from le_sup_left) (show E2 ≤ E1 ⊔ E2, from le_sup_right)
lemma sup_to_subalgebra [h1 : finite_dimensional K E1] [h2 : finite_dimensional K E2] :
(E1 ⊔ E2).to_subalgebra = E1.to_subalgebra ⊔ E2.to_subalgebra :=
begin
let S1 := E1.to_subalgebra,
let S2 := E2.to_subalgebra,
refine le_antisymm (show _ ≤ (S1 ⊔ S2).to_intermediate_field _, from (sup_le (show S1 ≤ _,
from le_sup_left) (show S2 ≤ _, from le_sup_right))) (le_sup_to_subalgebra E1 E2),
suffices : is_field ↥(S1 ⊔ S2),
{ intros x hx,
by_cases hx' : (⟨x, hx⟩ : S1 ⊔ S2) = 0,
{ rw [←subtype.coe_mk x hx, hx', subalgebra.coe_zero, inv_zero],
exact (S1 ⊔ S2).zero_mem },
{ obtain ⟨y, h⟩ := this.mul_inv_cancel hx',
exact (congr_arg (∈ S1 ⊔ S2) $ eq_inv_of_mul_eq_one_right $ subtype.ext_iff.mp h).mp y.2 } },
exact is_field_of_is_integral_of_is_field'
(is_integral_sup.mpr ⟨algebra.is_integral_of_finite K E1, algebra.is_integral_of_finite K E2⟩)
(field.to_is_field K),
end
instance finite_dimensional_sup [h1 : finite_dimensional K E1] [h2 : finite_dimensional K E2] :
finite_dimensional K ↥(E1 ⊔ E2) :=
begin
let g := algebra.tensor_product.product_map E1.val E2.val,
suffices : g.range = (E1 ⊔ E2).to_subalgebra,
{ have h : finite_dimensional K g.range.to_submodule := g.to_linear_map.finite_dimensional_range,
rwa this at h },
rw [algebra.tensor_product.product_map_range, E1.range_val, E2.range_val, sup_to_subalgebra],
end
instance finite_dimensional_supr_of_finite
{ι : Type*} {t : ι → intermediate_field K L} [h : finite ι] [Π i, finite_dimensional K (t i)] :
finite_dimensional K (⨆ i, t i : intermediate_field K L) :=
begin
rw ← supr_univ,
let P : set ι → Prop := λ s, finite_dimensional K (⨆ i ∈ s, t i : intermediate_field K L),
change P set.univ,
apply set.finite.induction_on,
{ exact set.finite_univ },
all_goals { dsimp only [P] },
{ rw supr_emptyset,
exact (bot_equiv K L).symm.to_linear_equiv.finite_dimensional },
{ intros _ s _ _ hs,
rw supr_insert,
exactI intermediate_field.finite_dimensional_sup _ _ },
end
instance finite_dimensional_supr_of_finset {ι : Type*}
{f : ι → intermediate_field K L} {s : finset ι} [h : Π i ∈ s, finite_dimensional K (f i)] :
finite_dimensional K (⨆ i ∈ s, f i : intermediate_field K L) :=
begin
haveI : Π i : {i // i ∈ s}, finite_dimensional K (f i) := λ i, h i i.2,
have : (⨆ i ∈ s, f i) = ⨆ i : {i // i ∈ s}, f i :=
le_antisymm (supr_le (λ i, supr_le (λ h, le_supr (λ i : {i // i ∈ s}, f i) ⟨i, h⟩)))
(supr_le (λ i, le_supr_of_le i (le_supr_of_le i.2 le_rfl))),
exact this.symm ▸ intermediate_field.finite_dimensional_supr_of_finite,
end
/-- A compositum of algebraic extensions is algebraic -/
lemma is_algebraic_supr {ι : Type*} {f : ι → intermediate_field K L}
(h : ∀ i, algebra.is_algebraic K (f i)) :
algebra.is_algebraic K (⨆ i, f i : intermediate_field K L) :=
begin
rintros ⟨x, hx⟩,
obtain ⟨s, hx⟩ := exists_finset_of_mem_supr' hx,
rw [is_algebraic_iff, subtype.coe_mk, ←subtype.coe_mk x hx, ←is_algebraic_iff],
haveI : ∀ i : (Σ i, f i), finite_dimensional K K⟮(i.2 : L)⟯ :=
λ ⟨i, x⟩, adjoin.finite_dimensional (is_integral_iff.1 (is_algebraic_iff_is_integral.1 (h i x))),
apply algebra.is_algebraic_of_finite,
end
end supremum
end intermediate_field
section power_basis
variables {K L : Type*} [field K] [field L] [algebra K L]
namespace power_basis
open intermediate_field
/-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/
noncomputable def equiv_adjoin_simple (pb : power_basis K L) :
K⟮pb.gen⟯ ≃ₐ[K] L :=
(adjoin.power_basis pb.is_integral_gen).equiv_of_minpoly pb
(minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective
(adjoin.power_basis pb.is_integral_gen).is_integral_gen
(by rw [adjoin.power_basis_gen, adjoin_simple.algebra_map_gen]))
@[simp]
lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : K[X]) :
pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f :=
equiv_of_minpoly_aeval _ pb _ f
@[simp]
lemma equiv_adjoin_simple_gen (pb : power_basis K L) :
pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen :=
equiv_of_minpoly_gen _ pb _
@[simp]
lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : K[X]) :
pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f :=
by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_aeval, adjoin.power_basis_gen]
@[simp]
lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) :
pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) :=
by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_gen, adjoin.power_basis_gen]
end power_basis
end power_basis
|
d86c20fc4e1b457a56a8b6af04f0c5622af17ab5 | dc253be9829b840f15d96d986e0c13520b085033 | /pointed_binary.hlean | d3c8a602111754afa26d84e199cb15ad7b0da430 | [
"Apache-2.0"
] | permissive | cmu-phil/Spectral | 4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea | 3b078f5f1de251637decf04bd3fc8aa01930a6b3 | refs/heads/master | 1,685,119,195,535 | 1,684,169,772,000 | 1,684,169,772,000 | 46,450,197 | 42 | 13 | null | 1,505,516,767,000 | 1,447,883,921,000 | Lean | UTF-8 | Lean | false | false | 10,541 | hlean | /-
Copyright (c) 2018 Ulrik Buchholtz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import .pointed_pi
open eq pointed equiv sigma is_equiv trunc option pi function fiber sigma.ops
namespace pointed
section bpmap
/- binary pointed maps -/
structure bpmap (A B C : Type*) : Type :=
(f : A → B →* C)
(q : Πb, f pt b = pt)
(r : q pt = respect_pt (f pt))
attribute [coercion] bpmap.f
variables {A B C D A' B' C' : Type*} {f f' : bpmap A B C}
definition respect_pt1 [unfold 4] (f : bpmap A B C) (b : B) : f pt b = pt :=
bpmap.q f b
definition respect_pt2 [unfold 4] (f : bpmap A B C) (a : A) : f a pt = pt :=
respect_pt (f a)
definition respect_ptpt [unfold 4] (f : bpmap A B C) : respect_pt1 f pt = respect_pt2 f pt :=
bpmap.r f
definition bpconst [constructor] (A B C : Type*) : bpmap A B C :=
bpmap.mk (λa, pconst B C) (λb, idp) idp
definition bppmap [constructor] (A B C : Type*) : Type* :=
pointed.MK (bpmap A B C) (bpconst A B C)
definition pmap_of_bpmap [constructor] (f : bppmap A B C) : ppmap A (ppmap B C) :=
begin
fapply pmap.mk,
{ intro a, exact pmap.mk (f a) (respect_pt2 f a) },
{ exact eq_of_phomotopy (phomotopy.mk (respect_pt1 f) (respect_ptpt f)) }
end
definition bpmap_of_pmap [constructor] (f : ppmap A (ppmap B C)) : bppmap A B C :=
begin
apply bpmap.mk (λa, f a) (ap010 pmap.to_fun (respect_pt f)),
exact respect_pt (phomotopy_of_eq (respect_pt f))
end
protected definition bpmap.sigma_char [constructor] (A B C : Type*) :
bpmap A B C ≃ Σ(f : A → B →* C) (q : Πb, f pt b = pt), q pt = respect_pt (f pt) :=
begin
fapply equiv.MK,
{ intro f, exact ⟨f, respect_pt1 f, respect_ptpt f⟩ },
{ intro fqr, exact bpmap.mk fqr.1 fqr.2.1 fqr.2.2 },
{ intro fqr, induction fqr with f qr, induction qr with q r, reflexivity },
{ intro f, induction f, reflexivity }
end
definition to_homotopy_pt_square {f g : A →* B} (h : f ~* g) :
square (respect_pt f) (respect_pt g) (h pt) idp :=
square_of_eq (to_homotopy_pt h)⁻¹
definition bpmap_eq_equiv [constructor] (f f' : bpmap A B C):
f = f' ≃ Σ(h : Πa, f a ~* f' a) (q : Πb, square (respect_pt1 f b) (respect_pt1 f' b) (h pt b) idp), cube (vdeg_square (respect_ptpt f)) (vdeg_square (respect_ptpt f'))
vrfl ids
(q pt) (to_homotopy_pt_square (h pt)) :=
begin
refine eq_equiv_fn_eq (bpmap.sigma_char A B C) f f' ⬝e _,
refine !sigma_eq_equiv ⬝e _, esimp,
refine sigma_equiv_sigma (!eq_equiv_homotopy ⬝e pi_equiv_pi_right (λa, !pmap_eq_equiv)) _,
intro h, exact sorry
end
definition bpmap_eq [constructor] (h : Πa, f a ~* f' a)
(q : Πb, square (respect_pt1 f b) (respect_pt1 f' b) (h pt b) idp)
(r : cube (vdeg_square (respect_ptpt f)) (vdeg_square (respect_ptpt f'))
vrfl ids
(q pt) (to_homotopy_pt_square (h pt))) : f = f' :=
(bpmap_eq_equiv f f')⁻¹ᵉ ⟨h, q, r⟩
definition pmap_equiv_bpmap [constructor] (A B C : Type*) : pmap A (ppmap B C) ≃ bpmap A B C :=
begin
refine !pmap.sigma_char ⬝e _ ⬝e !bpmap.sigma_char⁻¹ᵉ,
refine sigma_equiv_sigma_right (λf, pmap_eq_equiv (f pt) !pconst) ⬝e _,
refine sigma_equiv_sigma_right (λf, !phomotopy.sigma_char)
end
definition pmap_equiv_bpmap' [constructor] (A B C : Type*) : pmap A (ppmap B C) ≃ bpmap A B C :=
begin
refine equiv_change_fun (pmap_equiv_bpmap A B C) _,
exact bpmap_of_pmap, intro f, reflexivity
end
definition ppmap_pequiv_bppmap [constructor] (A B C : Type*) :
ppmap A (ppmap B C) ≃* bppmap A B C :=
pequiv_of_equiv (pmap_equiv_bpmap' A B C) idp
definition bpmap_functor [constructor] (f : A' →* A) (g : B' →* B) (h : C →* C')
(k : bpmap A B C) : bpmap A' B' C' :=
begin
fapply bpmap.mk (λa', h ∘* k (f a') ∘* g),
{ intro b', refine ap h _ ⬝ respect_pt h,
exact ap010 (λa b, k a b) (respect_pt f) (g b') ⬝ respect_pt1 k (g b') },
{ apply whisker_right, apply ap02 h, esimp,
induction A with A a₀, induction B with B b₀, induction f with f f₀, induction g with g g₀,
esimp at *, induction f₀, induction g₀, esimp, apply whisker_left, exact respect_ptpt k },
end
definition bppmap_functor [constructor] (f : A' →* A) (g : B' →* B) (h : C →* C') :
bppmap A B C →* bppmap A' B' C' :=
begin
apply pmap.mk (bpmap_functor f g h),
induction A with A a₀, induction B with B b₀, induction C' with C' c₀',
induction f with f f₀, induction g with g g₀, induction h with h h₀, esimp at *,
induction f₀, induction g₀, induction h₀,
reflexivity
end
definition ppcompose_left' [constructor] (g : B →* C) : ppmap A B →* ppmap A C :=
pmap.mk (pcompose g)
begin induction C with C c₀, induction g with g g₀, esimp at *, induction g₀, reflexivity end
definition ppcompose_right' [constructor] (f : A →* B) : ppmap B C →* ppmap A C :=
pmap.mk (λg, g ∘* f)
begin induction B with B b₀, induction f with f f₀, esimp at *, induction f₀, reflexivity end
definition ppmap_pequiv_bppmap_natural (f : A' →* A) (g : B' →* B) (h : C →* C') :
psquare (ppmap_pequiv_bppmap A B C) (ppmap_pequiv_bppmap A' B' C')
(ppcompose_right' f ∘* ppcompose_left' (ppcompose_right' g ∘* ppcompose_left' h))
(bppmap_functor f g h) :=
begin
induction A with A a₀, induction B with B b₀, induction C' with C' c₀',
induction f with f f₀, induction g with g g₀, induction h with h h₀, esimp at *,
induction f₀, induction g₀, induction h₀,
fapply phomotopy.mk,
{ intro k, fapply bpmap_eq,
{ intro a, exact !passoc⁻¹* },
{ intro b, apply vdeg_square, esimp,
refine ap02 _ !idp_con ⬝ _ ⬝ (ap (λx, ap010 pmap.to_fun x b) !idp_con)⁻¹ᵖ,
refine ap02 _ !ap_eq_ap010⁻¹ ⬝ !ap_compose' ⬝ !ap_compose ⬝ !ap_eq_ap010 },
{ exact sorry }},
{ exact sorry }
end
/- maybe this is useful for pointed naturality in C? -/
definition ppmap_pequiv_bppmap_natural_right (h : C →* C') :
psquare (ppmap_pequiv_bppmap A B C) (ppmap_pequiv_bppmap A B C')
(ppcompose_left' (ppcompose_left' h))
(bppmap_functor !pid !pid h) :=
begin
induction A with A a₀, induction B with B b₀, induction C' with C' c₀',
induction h with h h₀, esimp at *, induction h₀,
fapply phomotopy.mk,
{ intro k, fapply bpmap_eq,
{ intro a, exact pwhisker_left _ !pcompose_pid },
{ intro b, apply vdeg_square, esimp,
refine ap02 _ !idp_con ⬝ _,
refine ap02 _ !ap_eq_ap010⁻¹ ⬝ !ap_compose' ⬝ !ap_compose ⬝ !ap_eq_ap010 },
{ exact sorry }},
{ exact sorry }
end
end bpmap
/- fiberwise pointed maps -/
structure dbpmap {A : Type*} (B C : A → Type*) : Type :=
(f : Πa, B a →* C a)
(q : Πb, f pt b = pt)
(r : q pt = respect_pt (f pt))
attribute [coercion] dbpmap.f
variables {A A' : Type*} {B C : A → Type*} {B' C' : A' → Type*} {f f' : dbpmap B C}
definition respect_ptd1 [unfold 4] (f : dbpmap B C) (b : B pt) : f pt b = pt :=
dbpmap.q f b
definition respect_ptd2 [unfold 4] (f : dbpmap B C) (a : A) : f a pt = pt :=
respect_pt (f a)
definition respect_dptpt [unfold 4] (f : dbpmap B C) : respect_ptd1 f pt = respect_ptd2 f pt :=
dbpmap.r f
definition dbpconst [constructor] (B C : A → Type*) : dbpmap B C :=
dbpmap.mk (λa, pconst (B a) (C a)) (λb, idp) idp
definition dbppmap [constructor] (B C : A → Type*) : Type* :=
pointed.MK (dbpmap B C) (dbpconst B C)
definition ppi_of_dbpmap [constructor] (f : dbppmap B C) : Π*a, B a →** C a :=
begin
fapply ppi.mk,
{ intro a, exact pmap.mk (f a) (respect_ptd2 f a) },
{ exact eq_of_phomotopy (phomotopy.mk (respect_ptd1 f) (respect_dptpt f)) }
end
definition dbpmap_of_ppi [constructor] (f : Π*a, B a →** C a) : dbppmap B C :=
begin
apply dbpmap.mk (λa, f a) (ap010 pmap.to_fun (respect_pt f)),
exact respect_pt (phomotopy_of_eq (respect_pt f))
end
protected definition dbpmap.sigma_char [constructor] (B C : A → Type*) :
dbpmap B C ≃ Σ(f : Πa, B a →* C a) (q : Πb, f pt b = pt), q pt = respect_pt (f pt) :=
begin
fapply equiv.MK,
{ intro f, exact ⟨f, respect_ptd1 f, respect_dptpt f⟩ },
{ intro fqr, exact dbpmap.mk fqr.1 fqr.2.1 fqr.2.2 },
{ intro fqr, induction fqr with f qr, induction qr with q r, reflexivity },
{ intro f, induction f, reflexivity }
end
definition dbpmap_eq_equiv [constructor] (f f' : dbpmap B C):
f = f' ≃ Σ(h : Πa, f a ~* f' a) (q : Πb, square (respect_ptd1 f b) (respect_ptd1 f' b) (h pt b) idp), cube (vdeg_square (respect_dptpt f)) (vdeg_square (respect_dptpt f'))
vrfl ids
(q pt) (to_homotopy_pt_square (h pt)) :=
begin
refine eq_equiv_fn_eq (dbpmap.sigma_char B C) f f' ⬝e _,
refine !sigma_eq_equiv ⬝e _, esimp,
refine sigma_equiv_sigma (!eq_equiv_homotopy ⬝e pi_equiv_pi_right (λa, !pmap_eq_equiv)) _,
intro h, exact sorry
end
definition dbpmap_eq [constructor] (h : Πa, f a ~* f' a)
(q : Πb, square (respect_ptd1 f b) (respect_ptd1 f' b) (h pt b) idp)
(r : cube (vdeg_square (respect_dptpt f)) (vdeg_square (respect_dptpt f'))
vrfl ids
(q pt) (to_homotopy_pt_square (h pt))) : f = f' :=
(dbpmap_eq_equiv f f')⁻¹ᵉ ⟨h, q, r⟩
definition ppi_equiv_dbpmap [constructor] (B C : A → Type*) : (Π*a, B a →** C a) ≃ dbpmap B C :=
begin
refine !ppi.sigma_char ⬝e _ ⬝e !dbpmap.sigma_char⁻¹ᵉ,
refine sigma_equiv_sigma_right (λf, pmap_eq_equiv (f pt) !pconst) ⬝e _,
refine sigma_equiv_sigma_right (λf, !phomotopy.sigma_char)
end
definition ppi_equiv_dbpmap' [constructor] (B C : A → Type*) : (Π*a, B a →** C a) ≃ dbpmap B C :=
begin
refine equiv_change_fun (ppi_equiv_dbpmap B C) _,
exact dbpmap_of_ppi, intro f, reflexivity
end
definition pppi_pequiv_dbppmap [constructor] (B C : A → Type*) :
(Π*a, B a →** C a) ≃* dbppmap B C :=
pequiv_of_equiv (ppi_equiv_dbpmap' B C) idp
definition dbpmap_functor [constructor] (f : A' →* A) (g : Πa, B' a →* B (f a)) (h : Πa, C (f a) →* C' a)
(k : dbpmap B C) : dbpmap B' C' :=
begin
fapply dbpmap.mk (λa', h a' ∘* k (f a') ∘* g a'),
{ intro b', refine ap (h pt) _ ⬝ respect_pt (h pt),
exact sorry }, --ap010 (λa b, k a b) (respect_pt f) (g pt b') ⬝ respect_ptd1 k (g pt b') },
{ exact sorry },
-- apply whisker_right, apply ap02 h, esimp,
-- induction A with A a₀, induction B with B b₀, induction f with f f₀, induction g with g g₀,
-- esimp at *, induction f₀, induction g₀, esimp, apply whisker_left, exact respect_dptpt k },
end
end pointed
|
8247878e2f0f2902767167b76675478eb14021e5 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/number_theory/fermat4.lean | e802a60fc2046d838bc91a867837e7316928ec33 | [
"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,883 | lean | /-
Copyright (c) 2020 Paul van Wamelen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Paul van Wamelen
-/
import number_theory.pythagorean_triples
import ring_theory.coprime.lemmas
import tactic.linear_combination
/-!
# Fermat's Last Theorem for the case n = 4
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
There are no non-zero integers `a`, `b` and `c` such that `a ^ 4 + b ^ 4 = c ^ 4`.
-/
noncomputable theory
open_locale classical
/-- Shorthand for three non-zero integers `a`, `b`, and `c` satisfying `a ^ 4 + b ^ 4 = c ^ 2`.
We will show that no integers satisfy this equation. Clearly Fermat's Last theorem for n = 4
follows. -/
def fermat_42 (a b c : ℤ) : Prop := a ≠ 0 ∧ b ≠ 0 ∧ a ^ 4 + b ^ 4 = c ^ 2
namespace fermat_42
lemma comm {a b c : ℤ} :
(fermat_42 a b c) ↔ (fermat_42 b a c) :=
by { delta fermat_42, rw add_comm, tauto }
lemma mul {a b c k : ℤ} (hk0 : k ≠ 0) :
fermat_42 a b c ↔ fermat_42 (k * a) (k * b) (k ^ 2 * c) :=
begin
delta fermat_42,
split,
{ intro f42,
split, { exact mul_ne_zero hk0 f42.1 },
split, { exact mul_ne_zero hk0 f42.2.1 },
{ have H : a ^ 4 + b ^ 4 = c ^ 2 := f42.2.2,
linear_combination k ^ 4 * H } },
{ intro f42,
split, { exact right_ne_zero_of_mul f42.1 },
split, { exact right_ne_zero_of_mul f42.2.1 },
apply (mul_right_inj' (pow_ne_zero 4 hk0)).mp,
linear_combination f42.2.2 }
end
lemma ne_zero {a b c : ℤ} (h : fermat_42 a b c) : c ≠ 0 :=
begin
apply ne_zero_pow two_ne_zero _, apply ne_of_gt,
rw [← h.2.2, (by ring : a ^ 4 + b ^ 4 = (a ^ 2) ^ 2 + (b ^ 2) ^ 2)],
exact add_pos (sq_pos_of_ne_zero _ (pow_ne_zero 2 h.1))
(sq_pos_of_ne_zero _ (pow_ne_zero 2 h.2.1))
end
/-- We say a solution to `a ^ 4 + b ^ 4 = c ^ 2` is minimal if there is no other solution with
a smaller `c` (in absolute value). -/
def minimal (a b c : ℤ) : Prop :=
(fermat_42 a b c) ∧ ∀ (a1 b1 c1 : ℤ), (fermat_42 a1 b1 c1) → int.nat_abs c ≤ int.nat_abs c1
/-- if we have a solution to `a ^ 4 + b ^ 4 = c ^ 2` then there must be a minimal one. -/
lemma exists_minimal {a b c : ℤ} (h : fermat_42 a b c) :
∃ (a0 b0 c0), (minimal a0 b0 c0) :=
begin
let S : set ℕ := { n | ∃ (s : ℤ × ℤ × ℤ), fermat_42 s.1 s.2.1 s.2.2 ∧ n = int.nat_abs s.2.2},
have S_nonempty : S.nonempty,
{ use int.nat_abs c,
rw set.mem_set_of_eq,
use ⟨a, ⟨b, c⟩⟩, tauto },
let m : ℕ := nat.find S_nonempty,
have m_mem : m ∈ S := nat.find_spec S_nonempty,
rcases m_mem with ⟨s0, hs0, hs1⟩,
use [s0.1, s0.2.1, s0.2.2, hs0],
intros a1 b1 c1 h1,
rw ← hs1,
apply nat.find_min',
use ⟨a1, ⟨b1, c1⟩⟩, tauto
end
/-- a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` must have `a` and `b` coprime. -/
lemma coprime_of_minimal {a b c : ℤ} (h : minimal a b c) : is_coprime a b :=
begin
apply int.gcd_eq_one_iff_coprime.mp,
by_contradiction hab,
obtain ⟨p, hp, hpa, hpb⟩ := nat.prime.not_coprime_iff_dvd.mp hab,
obtain ⟨a1, rfl⟩ := (int.coe_nat_dvd_left.mpr hpa),
obtain ⟨b1, rfl⟩ := (int.coe_nat_dvd_left.mpr hpb),
have hpc : (p : ℤ) ^ 2 ∣ c,
{ rw [←int.pow_dvd_pow_iff zero_lt_two, ←h.1.2.2],
apply dvd.intro (a1 ^ 4 + b1 ^ 4), ring },
obtain ⟨c1, rfl⟩ := hpc,
have hf : fermat_42 a1 b1 c1,
exact (fermat_42.mul (int.coe_nat_ne_zero.mpr (nat.prime.ne_zero hp))).mpr h.1,
apply nat.le_lt_antisymm (h.2 _ _ _ hf),
rw [int.nat_abs_mul, lt_mul_iff_one_lt_left, int.nat_abs_pow, int.nat_abs_of_nat],
{ exact nat.one_lt_pow _ _ zero_lt_two (nat.prime.one_lt hp) },
{ exact (nat.pos_of_ne_zero (int.nat_abs_ne_zero_of_ne_zero (ne_zero hf))) },
end
/-- We can swap `a` and `b` in a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2`. -/
lemma minimal_comm {a b c : ℤ} : (minimal a b c) → (minimal b a c) :=
λ ⟨h1, h2⟩, ⟨fermat_42.comm.mp h1, h2⟩
/-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has positive `c`. -/
lemma neg_of_minimal {a b c : ℤ} :
(minimal a b c) → (minimal a b (-c)) :=
begin
rintros ⟨⟨ha, hb, heq⟩, h2⟩,
split,
{ apply and.intro ha (and.intro hb _),
rw heq, exact (neg_sq c).symm },
rwa (int.nat_abs_neg c),
end
/-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has `a` odd. -/
lemma exists_odd_minimal {a b c : ℤ} (h : fermat_42 a b c) :
∃ (a0 b0 c0), (minimal a0 b0 c0) ∧ a0 % 2 = 1 :=
begin
obtain ⟨a0, b0, c0, hf⟩ := exists_minimal h,
cases int.mod_two_eq_zero_or_one a0 with hap hap,
{ cases int.mod_two_eq_zero_or_one b0 with hbp hbp,
{ exfalso,
have h1 : 2 ∣ (int.gcd a0 b0 : ℤ),
{ exact int.dvd_gcd (int.dvd_of_mod_eq_zero hap) (int.dvd_of_mod_eq_zero hbp) },
rw int.gcd_eq_one_iff_coprime.mpr (coprime_of_minimal hf) at h1, revert h1, norm_num },
{ exact ⟨b0, ⟨a0, ⟨c0, minimal_comm hf, hbp⟩⟩⟩ } },
exact ⟨a0, ⟨b0, ⟨c0 , hf, hap⟩⟩⟩,
end
/-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has
`a` odd and `c` positive. -/
lemma exists_pos_odd_minimal {a b c : ℤ} (h : fermat_42 a b c) :
∃ (a0 b0 c0), (minimal a0 b0 c0) ∧ a0 % 2 = 1 ∧ 0 < c0 :=
begin
obtain ⟨a0, b0, c0, hf, hc⟩ := exists_odd_minimal h,
rcases lt_trichotomy 0 c0 with (h1 | rfl | h1),
{ use [a0, b0, c0], tauto },
{ exfalso, exact ne_zero hf.1 rfl},
{ use [a0, b0, -c0, neg_of_minimal hf, hc],
exact neg_pos.mpr h1 },
end
end fermat_42
lemma int.coprime_of_sq_sum {r s : ℤ} (h2 : is_coprime s r) :
is_coprime (r ^ 2 + s ^ 2) r :=
begin
rw [sq, sq],
exact (is_coprime.mul_left h2 h2).mul_add_left_left r
end
lemma int.coprime_of_sq_sum' {r s : ℤ} (h : is_coprime r s) :
is_coprime (r ^ 2 + s ^ 2) (r * s) :=
begin
apply is_coprime.mul_right (int.coprime_of_sq_sum (is_coprime_comm.mp h)),
rw add_comm, apply int.coprime_of_sq_sum h
end
namespace fermat_42
-- If we have a solution to a ^ 4 + b ^ 4 = c ^ 2, we can construct a smaller one. This
-- implies there can't be a smallest solution.
lemma not_minimal {a b c : ℤ}
(h : minimal a b c) (ha2 : a % 2 = 1) (hc : 0 < c) : false :=
begin
-- Use the fact that a ^ 2, b ^ 2, c form a pythagorean triple to obtain m and n such that
-- a ^ 2 = m ^ 2 - n ^ 2, b ^ 2 = 2 * m * n and c = m ^ 2 + n ^ 2
-- first the formula:
have ht : pythagorean_triple (a ^ 2) (b ^ 2) c,
{ delta pythagorean_triple,
linear_combination h.1.2.2 },
-- coprime requirement:
have h2 : int.gcd (a ^ 2) (b ^ 2) = 1 :=
int.gcd_eq_one_iff_coprime.mpr (coprime_of_minimal h).pow,
-- in order to reduce the possibilities we get from the classification of pythagorean triples
-- it helps if we know the parity of a ^ 2 (and the sign of c):
have ha22 : a ^ 2 % 2 = 1, { rw [sq, int.mul_mod, ha2], norm_num },
obtain ⟨m, n, ht1, ht2, ht3, ht4, ht5, ht6⟩ := ht.coprime_classification' h2 ha22 hc,
-- Now a, n, m form a pythagorean triple and so we can obtain r and s such that
-- a = r ^ 2 - s ^ 2, n = 2 * r * s and m = r ^ 2 + s ^ 2
-- formula:
have htt : pythagorean_triple a n m,
{ delta pythagorean_triple,
linear_combination (ht1) },
-- a and n are coprime, because a ^ 2 = m ^ 2 - n ^ 2 and m and n are coprime.
have h3 : int.gcd a n = 1,
{ apply int.gcd_eq_one_iff_coprime.mpr,
apply @is_coprime.of_mul_left_left _ _ _ a,
rw [← sq, ht1, (by ring : m ^ 2 - n ^ 2 = m ^ 2 + (-n) * n)],
exact (int.gcd_eq_one_iff_coprime.mp ht4).pow_left.add_mul_right_left (-n) },
-- m is positive because b is non-zero and b ^ 2 = 2 * m * n and we already have 0 ≤ m.
have hb20 : b ^ 2 ≠ 0 := mt pow_eq_zero h.1.2.1,
have h4 : 0 < m,
{ apply lt_of_le_of_ne ht6,
rintro rfl,
revert hb20,
rw ht2, simp },
obtain ⟨r, s, htt1, htt2, htt3, htt4, htt5, htt6⟩ := htt.coprime_classification' h3 ha2 h4,
-- Now use the fact that (b / 2) ^ 2 = m * r * s, and m, r and s are pairwise coprime to obtain
-- i, j and k such that m = i ^ 2, r = j ^ 2 and s = k ^ 2.
-- m and r * s are coprime because m = r ^ 2 + s ^ 2 and r and s are coprime.
have hcp : int.gcd m (r * s) = 1,
{ rw htt3,
exact int.gcd_eq_one_iff_coprime.mpr (int.coprime_of_sq_sum'
(int.gcd_eq_one_iff_coprime.mp htt4)) },
-- b is even because b ^ 2 = 2 * m * n.
have hb2 : 2 ∣ b,
{ apply @int.prime.dvd_pow' _ 2 _ nat.prime_two,
rw [ht2, mul_assoc], exact dvd_mul_right 2 (m * n) },
cases hb2 with b' hb2',
have hs : b' ^ 2 = m * (r * s),
{ apply (mul_right_inj' (by norm_num : (4 : ℤ) ≠ 0)).mp,
linear_combination (- b - 2 * b') * hb2' + ht2 + 2 * m * htt2 },
have hrsz : r * s ≠ 0, -- because b ^ 2 is not zero and (b / 2) ^ 2 = m * (r * s)
{ by_contradiction hrsz,
revert hb20, rw [ht2, htt2, mul_assoc, @mul_assoc _ _ _ r s, hrsz],
simp },
have h2b0 : b' ≠ 0,
{ apply ne_zero_pow two_ne_zero,
rw hs, apply mul_ne_zero, { exact ne_of_gt h4}, { exact hrsz } },
obtain ⟨i, hi⟩ := int.sq_of_gcd_eq_one hcp hs.symm,
-- use m is positive to exclude m = - i ^ 2
have hi' : ¬ m = - i ^ 2,
{ by_contradiction h1,
have hit : - i ^ 2 ≤ 0, apply neg_nonpos.mpr (sq_nonneg i),
rw ← h1 at hit,
apply absurd h4 (not_lt.mpr hit) },
replace hi : m = i ^ 2, { apply or.resolve_right hi hi' },
rw mul_comm at hs,
rw [int.gcd_comm] at hcp,
-- obtain d such that r * s = d ^ 2
obtain ⟨d, hd⟩ := int.sq_of_gcd_eq_one hcp hs.symm,
-- (b / 2) ^ 2 and m are positive so r * s is positive
have hd' : ¬ r * s = - d ^ 2,
{ by_contradiction h1,
rw h1 at hs,
have h2 : b' ^ 2 ≤ 0,
{ rw [hs, (by ring : - d ^ 2 * m = - (d ^ 2 * m))],
exact neg_nonpos.mpr ((zero_le_mul_right h4).mpr (sq_nonneg d)) },
have h2' : 0 ≤ b' ^ 2, { apply sq_nonneg b' },
exact absurd (lt_of_le_of_ne h2' (ne.symm (pow_ne_zero _ h2b0))) (not_lt.mpr h2) },
replace hd : r * s = d ^ 2, { apply or.resolve_right hd hd' },
-- r = +/- j ^ 2
obtain ⟨j, hj⟩ := int.sq_of_gcd_eq_one htt4 hd,
have hj0 : j ≠ 0,
{ intro h0, rw [h0, zero_pow zero_lt_two, neg_zero, or_self] at hj,
apply left_ne_zero_of_mul hrsz hj },
rw mul_comm at hd,
rw [int.gcd_comm] at htt4,
-- s = +/- k ^ 2
obtain ⟨k, hk⟩ := int.sq_of_gcd_eq_one htt4 hd,
have hk0 : k ≠ 0,
{ intro h0, rw [h0, zero_pow zero_lt_two, neg_zero, or_self] at hk,
apply right_ne_zero_of_mul hrsz hk },
have hj2 : r ^ 2 = j ^ 4, { cases hj with hjp hjp; { rw hjp, ring } },
have hk2 : s ^ 2 = k ^ 4, { cases hk with hkp hkp; { rw hkp, ring } },
-- from m = r ^ 2 + s ^ 2 we now get a new solution to a ^ 4 + b ^ 4 = c ^ 2:
have hh : i ^ 2 = j ^ 4 + k ^ 4, { rw [← hi, htt3, hj2, hk2] },
have hn : n ≠ 0, { rw ht2 at hb20, apply right_ne_zero_of_mul hb20 },
-- and it has a smaller c: from c = m ^ 2 + n ^ 2 we see that m is smaller than c, and i ^ 2 = m.
have hic : int.nat_abs i < int.nat_abs c,
{ apply int.coe_nat_lt.mp, rw ← (int.eq_nat_abs_of_zero_le (le_of_lt hc)),
apply gt_of_gt_of_ge _ (int.abs_le_self_sq i),
rw [← hi, ht3],
apply gt_of_gt_of_ge _ (int.le_self_sq m),
exact lt_add_of_pos_right (m ^ 2) (sq_pos_of_ne_zero n hn) },
have hic' : int.nat_abs c ≤ int.nat_abs i,
{ apply (h.2 j k i),
exact ⟨hj0, hk0, hh.symm⟩ },
apply absurd (not_le_of_lt hic) (not_not.mpr hic')
end
end fermat_42
lemma not_fermat_42 {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) :
a ^ 4 + b ^ 4 ≠ c ^ 2 :=
begin
intro h,
obtain ⟨a0, b0, c0, ⟨hf, h2, hp⟩⟩ :=
fermat_42.exists_pos_odd_minimal (and.intro ha (and.intro hb h)),
apply fermat_42.not_minimal hf h2 hp
end
theorem not_fermat_4 {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) :
a ^ 4 + b ^ 4 ≠ c ^ 4 :=
begin
intro heq,
apply @not_fermat_42 _ _ (c ^ 2) ha hb,
rw heq, ring
end
|
5e8f5c29a16e8eb1b6e892d9a99a3766b2a01509 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/set/enumerate.lean | 16a2dd83830f6e3c9396c18f346d8257943643ca | [
"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 | 2,383 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Enumerate elements of a set with a select function.
-/
import data.set.lattice tactic.wlog
noncomputable theory
open function set
namespace set
section enumerate
parameters {α : Type*} (sel : set α → option α)
def enumerate : set α → ℕ → option α
| s 0 := sel s
| s (n + 1) := do a ← sel s, enumerate (s - {a}) n
lemma enumerate_eq_none_of_sel {s : set α} (h : sel s = none) : ∀{n}, enumerate s n = none
| 0 := by simp [h, enumerate]; refl
| (n + 1) := by simp [h, enumerate]; refl
lemma enumerate_eq_none : ∀{s n₁ n₂}, enumerate s n₁ = none → n₁ ≤ n₂ → enumerate s n₂ = none
| s 0 m := assume : sel s = none, by simp [enumerate_eq_none_of_sel, this]
| s (n + 1) m := assume h hm,
begin
cases hs : sel s,
{ by simp [enumerate_eq_none_of_sel, hs] },
{ cases m,
case nat.zero {
have : n + 1 = 0, from nat.eq_zero_of_le_zero hm,
contradiction },
case nat.succ : m' {
simp [hs, enumerate] at h ⊢,
have hm : n ≤ m', from nat.le_of_succ_le_succ hm,
exact enumerate_eq_none h hm } }
end
lemma enumerate_mem (h_sel : ∀s a, sel s = some a → a ∈ s) :
∀{s n a}, enumerate s n = some a → a ∈ s
| s 0 a := h_sel s a
| s (n+1) a :=
begin
cases h : sel s,
case none { simp [enumerate_eq_none_of_sel, h] },
case some : a' {
simp [enumerate, h],
exact assume h' : enumerate _ (s - {a'}) n = some a,
have a ∈ s - {a'}, from enumerate_mem h',
this.left }
end
lemma enumerate_inj {n₁ n₂ : ℕ} {a : α} {s : set α} (h_sel : ∀s a, sel s = some a → a ∈ s)
(h₁ : enumerate s n₁ = some a) (h₂ : enumerate s n₂ = some a) : n₁ = n₂ :=
begin
wlog hn : n₁ ≤ n₂,
{ rcases nat.le.dest hn with ⟨m, rfl⟩, clear hn,
induction n₁ generalizing s,
case nat.zero {
cases m,
case nat.zero { refl },
case nat.succ : m {
have : enumerate sel (s - {a}) m = some a, { simp [enumerate, *] at * },
have : a ∈ s \ {a}, from enumerate_mem _ h_sel this,
by simpa } },
case nat.succ { cases h : sel s; simp [enumerate, nat.add_succ, *] at *; tauto } }
end
end enumerate
end set
|
6a3147427a64f3f88bd65e132971ca3be064d935 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/data/rat/basic.lean | 6e01c9c3d9ee7b6edd0885351dad46981a9ad09f | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,788 | 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, Mario Carneiro
-/
import data.equiv.encodable.basic
import algebra.euclidean_domain
import data.nat.gcd
import data.int.cast
/-!
# Basics for the Rational Numbers
## Summary
We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where
- `num` is the numerator of `q`,
- `denom` is the denominator of `q`,
- `pos` is a proof that `denom > 0`, and
- `cop` is a proof `num` and `denom` are coprime.
We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it.
Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`.
## Main Definitions
- `rat` is the structure encoding `ℚ`.
- `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`.
## Notations
- `/.` is infix notation for `rat.mk`.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom
-/
/-- `rat`, or `ℚ`, is the type of rational numbers. It is defined
as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and
`d` are coprime. This representation is preferred to the quotient
because without periodic reduction, the numerator and denominator can grow
exponentially (for example, adding 1/2 to itself repeatedly). -/
structure rat := mk' ::
(num : ℤ)
(denom : ℕ)
(pos : 0 < denom)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
/-- String representation of a rational numbers, used in `has_repr`, `has_to_string`, and
`has_to_format` instances. -/
protected def repr : ℚ → string
| ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else
_root_.repr n ++ "/" ++ _root_.repr d
instance : has_repr ℚ := ⟨rat.repr⟩
instance : has_to_string ℚ := ⟨rat.repr⟩
meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩
instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // 0 < d ∧ n.nat_abs.coprime d})
⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩,
λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩
/-- Embed an integer as a rational number -/
def of_int (n : ℤ) : ℚ :=
⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩
instance : has_zero ℚ := ⟨of_int 0⟩
instance : has_one ℚ := ⟨of_int 1⟩
instance : inhabited ℚ := ⟨0⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/
def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ :=
let n' := n.nat_abs, g := n'.gcd d in
⟨n / g, d / g, begin
apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2,
simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _)
end, begin
have : int.nat_abs (n / ↑g) = n' / g,
{ cases int.nat_abs_eq n with e e; rw e, { refl },
rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl },
exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) },
rw this,
exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos)
end⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we
define `n / 0 = 0` by convention. -/
def mk_nat (n : ℤ) (d : ℕ) : ℚ :=
if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩
/-- Form the quotient `n / d` where `n d : ℤ`. -/
def mk : ℤ → ℤ → ℚ
| n (d : ℕ) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
localized "infix ` /. `:70 := rat.mk" in rat
theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d :=
by change n /. d with dite _ _ _; simp [ne_of_gt h]
theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl
@[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl
@[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 :=
by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl
@[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 :=
by by_cases n = 0; simp [*, mk_nat]
@[simp] theorem zero_mk (n) : 0 /. n = 0 :=
by cases n; simp [mk]
private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a :=
int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b
@[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 :=
begin
constructor; intro h; [skip, {subst a, simp}],
have : ∀ {a b}, mk_pnat a b = 0 → a = 0,
{ intros a b e, cases b with b h,
injection e with e,
apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e },
cases b with b; simp [mk, mk_nat] at h,
{ simp [mt (congr_arg int.of_nat) b0] at h,
exact this h },
{ apply neg_injective, simp [this h] }
end
theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0),
a /. b = c /. d ↔ a * d = c * b :=
suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b,
begin
intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hb],
all_goals {
cases d with d d; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hd],
all_goals { rw this, try {refl} } },
{ change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b,
constructor; intro h; apply neg_injective; simpa [left_distrib, neg_add_eq_iff_eq_add,
eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h },
{ change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ,
constructor; intro h; apply neg_injective; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib, sub_eq_add_neg], cc }
end,
begin
intros, simp [mk_pnat], constructor; intro h,
{ cases h with ha hb,
have ha, {
have dv := @gcd_abs_dvd_left,
have := int.eq_mul_of_div_eq_right dv ha,
rw ← int.mul_div_assoc _ dv at this,
exact int.eq_mul_of_div_eq_left (dv.mul_left _) this.symm },
have hb, {
have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b,
have := nat.eq_mul_of_div_eq_right dv hb,
rw ← nat.mul_div_assoc _ dv at this,
exact nat.eq_mul_of_div_eq_left (dv.mul_left _) this.symm },
have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, {
refine int.coe_nat_ne_zero.2 (ne_of_gt _),
apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption },
apply mul_right_cancel' m0,
simpa [mul_comm, mul_left_comm] using
congr (congr_arg (*) ha.symm) (congr_arg coe hb) },
{ suffices : ∀ a c, a * d = c * b →
a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d,
{ cases this a.nat_abs c.nat_abs
(by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂,
have hs := congr_arg int.sign h,
simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb),
int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs,
conv in a { rw ← int.sign_mul_nat_abs a },
conv in c { rw ← int.sign_mul_nat_abs c },
rw [int.mul_div_assoc, int.mul_div_assoc],
exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩,
all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } },
intros a c h,
suffices bd : b / a.gcd b = d / c.gcd d,
{ refine ⟨_, bd⟩,
apply nat.eq_of_mul_eq_mul_left hb,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd,
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] },
suffices : ∀ {a c : ℕ} (b>0) (d>0),
a * d = c * b → b / a.gcd b ≤ d / c.gcd d,
{ exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) },
intros a c b hb d hd h,
have gb0 := nat.gcd_pos_of_pos_right a hb,
have gd0 := nat.gcd_pos_of_pos_right c hd,
apply nat.le_of_dvd,
apply (nat.le_div_iff_mul_le _ _ gd0).2,
simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _),
apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left,
refine ⟨c / c.gcd d, _⟩,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)],
apply congr_arg (/ c.gcd d),
rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }
end
@[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) :
(a * c) /. (b * c) = a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp },
apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc]
end
@[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a
| ⟨n, d, h, (c:_=1)⟩ := show mk_nat n d = _,
by simp [mk_nat, ne_of_gt h, mk_pnat, c]
theorem num_denom' {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom.symm
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom'
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational
numbers of the form `n /. d` with `0 < d` and coprime `n`, `d`. -/
@[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, 0 < d → (int.nat_abs n).coprime d → C (n /. d)), C a
| ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational
numbers of the form `n /. d` with `d ≠ 0`. -/
@[elab_as_eliminator] def {u} num_denom_cases_on' {C : ℚ → Sort u}
(a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a :=
num_denom_cases_on a $ λ n d h c, H n d h.ne'
theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a :=
begin
cases e : a /. b with n d h c,
rw [rat.num_denom', rat.mk_eq b0
(ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $
c.dvd_of_dvd_mul_right _),
have := congr_arg int.nat_abs e,
simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this]
end
theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b :=
begin
by_cases b0 : b = 0, {simp [b0]},
cases e : a /. b with n d h c,
rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _),
rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp
end
/-- Addition of rational numbers. Use `(+)` instead. -/
protected def add : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_add ℚ := ⟨rat.add⟩
theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ)
(fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂},
f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂)
(f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0)
(a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0)
(H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d),
f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) :
f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc,
rw fv,
have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁),
have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂),
exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc))
end
@[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b + c /. d = (a * d + c * b) /. (b * d) :=
begin
apply lift_binop_eq rat.add; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
calc (n₁ * d₂ + n₂ * d₁) * (b * d) =
(n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm]
... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂]
... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm]
end
/-- Negation of rational numbers. Use `-r` instead. -/
protected def neg (r : ℚ) : ℚ :=
⟨-r.num, r.denom, r.pos, by simp [r.cop]⟩
instance : has_neg ℚ := ⟨rat.neg⟩
@[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
show rat.mk' _ _ _ _ = _, rw num_denom',
have d0 := ne_of_gt (int.coe_nat_lt.2 h₁),
apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha,
simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁]
end
/-- Multiplication of rational numbers. Use `(*)` instead. -/
protected def mul : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_mul ℚ := ⟨rat.mul⟩
@[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
(a /. b) * (c /. d) = (a * c) /. (b * d) :=
begin
apply lift_binop_eq rat.mul; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
cc
end
/-- Inverse rational number. Use `r⁻¹` instead. -/
protected def inv : ℚ → ℚ
| ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩
| ⟨0, d, h, c⟩ := 0
| ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩
instance : has_inv ℚ := ⟨rat.inv⟩
@[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a :=
begin
by_cases a0 : a = 0, { subst a0, simp, refl },
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha,
refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _,
{ cases n with n; [cases n with n, skip],
{ refl },
{ change int.of_nat n.succ with (n+1:ℕ),
unfold rat.inv, rw num_denom' },
{ unfold rat.inv, rw num_denom', refl } },
have n0 : n ≠ 0,
{ refine mt (λ (n0 : n = 0), _) a0,
subst n0, simp at ha,
exact (mk_eq_zero b0).1 ha },
have d0 := ne_of_gt (int.coe_nat_lt.2 h),
have ha := (mk_eq b0 d0).1 ha,
apply (mk_eq n0 a0).2,
cc
end
variables (a b c : ℚ)
protected theorem add_zero : a + 0 = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem zero_add : 0 + a = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem add_comm : a + b = b + a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂]; cc
protected theorem add_assoc : a + b + c = a + (b + c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm, add_assoc]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
@[simp] lemma mk_zero_one : 0 /. 1 = 0 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
@[simp] lemma mk_one_one : 1 /. 1 = 1 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
@[simp] lemma mk_neg_one_one : (-1) /. 1 = -1 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by { rw ← mk_one_one, simp [h, -mk_one_one] }
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by { rw ← mk_one_one, simp [h, -mk_one_one] }
protected theorem mul_comm : a * b = b * a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem mul_assoc : a * b * c = a * (b * c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm]
protected theorem add_mul : (a + b) * c = a * c + b * c :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero];
refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _;
simp [mul_add, mul_comm, mul_assoc, mul_left_comm]
protected theorem mul_add : a * (b + c) = a * b + a * c :=
by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a]
protected theorem zero_ne_one : 0 ≠ (1:ℚ) :=
suffices (1:ℚ) = 0 → false, by cc,
by { rw [← mk_one_one, mk_eq_zero one_ne_zero], exact one_ne_zero }
protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 :=
num_denom_cases_on' a $ λ n d h a0,
have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0,
by simpa [h, n0, mul_comm] using @div_mk_div_cancel_left 1 1 _ n0
protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h)
instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance
instance : field ℚ :=
{ zero := 0,
add := rat.add,
neg := rat.neg,
one := 1,
mul := rat.mul,
inv := rat.inv,
zero_add := rat.zero_add,
add_zero := rat.add_zero,
add_comm := rat.add_comm,
add_assoc := rat.add_assoc,
add_left_neg := rat.add_left_neg,
mul_one := rat.mul_one,
one_mul := rat.one_mul,
mul_comm := rat.mul_comm,
mul_assoc := rat.mul_assoc,
left_distrib := rat.mul_add,
right_distrib := rat.add_mul,
exists_pair_ne := ⟨0, 1, rat.zero_ne_one⟩,
mul_inv_cancel := rat.mul_inv_cancel,
inv_zero := rfl }
/- Extra instances to short-circuit type class resolution -/
instance : division_ring ℚ := by apply_instance
instance : integral_domain ℚ := by apply_instance
-- TODO(Mario): this instance slows down data.real.basic
--instance : domain ℚ := by apply_instance
instance : nontrivial ℚ := by apply_instance
instance : comm_ring ℚ := by apply_instance
--instance : ring ℚ := by apply_instance
instance : comm_semiring ℚ := by apply_instance
instance : semiring ℚ := 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
theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b - c /. d = (a * d - c * b) /. (b * d) :=
by simp [b0, d0, sub_eq_add_neg]
@[simp] lemma denom_neg_eq_denom (q : ℚ) : (-q).denom = q.denom := rfl
@[simp] lemma num_neg_eq_neg_num (q : ℚ) : (-q).num = -(q.num) := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
@[simp] lemma denom_zero : rat.denom 0 = 1 := rfl
lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom.symm,
by simpa [hq]
lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 :=
⟨λ _, by simp *, zero_of_num_zero⟩
lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 :=
assume : q.num = 0,
h $ zero_of_num_zero this
@[simp] lemma num_one : (1 : ℚ).num = 1 := rfl
@[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl
lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 :=
ne_of_gt q.pos
lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom :=
begin
conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] },
apply rat.mk_eq,
{ exact_mod_cast p.denom_ne_zero },
{ exact_mod_cast q.denom_ne_zero }
end
lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 :=
assume : n = 0,
hq $ by simpa [this] using hqnd
lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 :=
assume : d = 0,
hq $ by simpa [this] using hqnd
lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 :=
assume : n /. d = 0,
h $ (mk_eq_zero hd).1 this
lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) :=
have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa,
have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa,
suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom),
by simpa using this,
by simp [mul_def hq' hr', -num_denom]
lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) :=
if hr : r.num = 0 then
have hr' : r = 0, from zero_of_num_zero hr,
by simp *
else
calc q / r = q * r⁻¹ : div_eq_mul_inv q r
... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp
... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def
... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr
lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) :
∃ c : ℤ, n = c * q.num ∧ d = c * q.denom :=
have hq : q ≠ 0, from
assume : q = 0,
hn $ (rat.mk_eq_zero hd).1 (by cc),
have q.num /. q.denom = n /. d, by rwa [num_denom],
have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this,
begin
existsi n / q.num,
have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end,
split,
{ rw int.div_mul_cancel hqdn },
{ apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left,
{ apply rat.num_ne_zero_of_ne_zero hq },
repeat { assumption } }
end
theorem mk_pnat_num (n : ℤ) (d : ℕ+) :
(mk_pnat n d).num = n / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mk_pnat_denom (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom = d / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mk_pnat_denom_dvd (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom ∣ d.1 :=
begin
rw mk_pnat_denom,
apply nat.div_dvd_of_dvd,
apply nat.gcd_dvd_right
end
theorem add_denom_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).denom ∣ q₁.denom * q₂.denom :=
by { cases q₁, cases q₂, apply mk_pnat_denom_dvd }
theorem mul_denom_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).denom ∣ q₁.denom * q₂.denom :=
by { cases q₁, cases q₂, apply mk_pnat_denom_dvd }
theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num =
(q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom =
(q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num :=
by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom :=
by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
lemma add_num_denom (q r : ℚ) : q + r =
((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) :=
have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3,
have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3,
by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] };
simp [mul_comm]
section casts
protected lemma add_mk (a b c : ℤ) : (a + b) /. c = a /. c + b /. c :=
if h : c = 0 then by simp [h] else
by { rw [add_def h h, mk_eq h (mul_ne_zero h h)], simp [add_mul, mul_assoc] }
theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1
| (n : ℕ) := show (n:ℚ) = n /. 1,
by induction n with n IH n; simp [*, rat.add_mk]
| -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin
induction n with n IH, { rw ← of_int_eq_mk, simp, refl },
show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1,
rw [neg_add, IH, ← mk_neg_one_one],
simp [-mk_neg_one_one]
end
theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0]
end
@[simp]
theorem num_div_denom (r : ℚ) : (r.num / r.denom : ℚ) = r :=
by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom]
lemma exists_eq_mul_div_num_and_eq_mul_div_denom {n d : ℤ} (n_ne_zero : n ≠ 0)
(d_ne_zero : d ≠ 0) :
∃ (c : ℤ), n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).denom :=
begin
have : ((n : ℚ) / d) = rat.mk n d, by rw [←rat.mk_eq_div],
exact rat.num_denom_mk n_ne_zero d_ne_zero this
end
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
@[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q :=
by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl }
lemma denom_eq_one_iff (r : ℚ) : r.denom = 1 ↔ ↑r.num = r :=
⟨rat.coe_int_num_of_denom_eq_one, λ h, h ▸ rat.coe_int_denom r.num⟩
instance : can_lift ℚ ℤ :=
⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩
theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 :=
by rw [← int.cast_coe_nat, coe_int_eq_mk]
@[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
-- Will be subsumed by `int.coe_inj` after we have defined
-- `linear_ordered_field ℚ` (which implies characteristic zero).
lemma coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n :=
⟨λ h, by simpa using congr_arg num h, congr_arg _⟩
end casts
lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num :=
by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] }
@[simp] lemma mul_denom_eq_num {q : ℚ} : q * q.denom = q.num :=
begin
suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by
{ conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] },
have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos),
rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)]
end
lemma denom_div_cast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) :
((m : ℚ) / n).denom = 1 ↔ n ∣ m :=
begin
replace hn : (n:ℚ) ≠ 0, by rwa [ne.def, ← int.cast_zero, coe_int_inj],
split,
{ intro h,
lift ((m : ℚ) / n) to ℤ using h with k hk,
use k,
rwa [eq_div_iff_mul_eq hn, ← int.cast_mul, mul_comm, eq_comm, coe_int_inj] at hk },
{ rintros ⟨d, rfl⟩,
rw [int.cast_mul, mul_comm, mul_div_cancel _ hn, rat.coe_int_denom] }
end
lemma num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
(a / b : ℚ).num = a :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_num, pnat.mk_coe, h.gcd_eq_one,
int.coe_nat_one, int.div_one]
end
lemma denom_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
((a / b : ℚ).denom : ℤ) = b :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_denom, pnat.mk_coe, h.gcd_eq_one,
nat.div_one]
end
lemma div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d)
(h1 : nat.coprime a.nat_abs b.nat_abs) (h2 : nat.coprime c.nat_abs d.nat_abs)
(h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d :=
begin
apply and.intro,
{ rw [← (num_div_eq_of_coprime hb0 h1), h, num_div_eq_of_coprime hd0 h2] },
{ rw [← (denom_div_eq_of_coprime hb0 h1), h, denom_div_eq_of_coprime hd0 h2] }
end
@[norm_cast] lemma coe_int_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n :=
begin
by_cases hn : n = 0,
{ subst hn, simp only [int.cast_zero, euclidean_domain.zero_div] },
{ have : (n : ℚ) ≠ 0, { rwa ← coe_int_inj at hn },
simp only [int.div_self hn, int.cast_one, ne.def, not_false_iff, div_self this] }
end
@[norm_cast] lemma coe_nat_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n :=
coe_int_div_self n
lemma coe_int_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b :=
begin
rcases h with ⟨c, rfl⟩,
simp only [mul_comm b, int.mul_div_assoc c (dvd_refl b), int.cast_mul, mul_div_assoc,
coe_int_div_self]
end
lemma coe_nat_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b :=
begin
rcases h with ⟨c, rfl⟩,
simp only [mul_comm b, nat.mul_div_assoc c (dvd_refl b), nat.cast_mul, mul_div_assoc,
coe_nat_div_self]
end
lemma inv_coe_int_num {a : ℤ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 :=
begin
rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one],
apply num_div_eq_of_coprime ha0,
rw int.nat_abs_one,
exact nat.coprime_one_left _,
end
lemma inv_coe_nat_num {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 :=
inv_coe_int_num (by exact_mod_cast ha0 : 0 < (a : ℤ))
lemma inv_coe_int_denom {a : ℤ} (ha0 : 0 < a) : ((a : ℚ)⁻¹.denom : ℤ) = a :=
begin
rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one],
apply denom_div_eq_of_coprime ha0,
rw int.nat_abs_one,
exact nat.coprime_one_left _,
end
lemma inv_coe_nat_denom {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.denom = a :=
by exact_mod_cast inv_coe_int_denom (by exact_mod_cast ha0 : 0 < (a : ℤ))
protected lemma «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) :=
⟨λ h _ _, h _,
λ h q, (show q = q.num / q.denom, from by simp [rat.div_num_denom]).symm ▸ (h q.1 q.2)⟩
protected lemma «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) :=
⟨λ ⟨r, hr⟩, ⟨r.num, r.denom, by rwa [← mk_eq_div, num_denom]⟩, λ ⟨a, b, h⟩, ⟨_, h⟩⟩
end rat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.