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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cca2c6661fb5eef7e9604d1c61c84d997c302fb9 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/logic/embedding/basic.lean | 8334cd6e317a420995aabb9d56fc4a57529d2cfc | [
"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 | 15,100 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.fun_like.embedding
import data.prod.pprod
import data.sigma.basic
import data.option.basic
import data.subtype
import logic.equiv.basic
/-!
# Injective functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/700
> Any changes to this file require a corresponding PR to mathlib4.
-/
universes u v w x
namespace function
/-- `α ↪ β` is a bundled injective function. -/
@[nolint has_nonempty_instance] -- depending on cardinalities, an injective function may not exist
structure embedding (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inj' : injective to_fun)
infixr ` ↪ `:25 := embedding
instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) (λ _, α → β) := ⟨embedding.to_fun⟩
initialize_simps_projections embedding (to_fun → apply)
instance {α : Sort u} {β : Sort v} : embedding_like (α ↪ β) α β :=
{ coe := embedding.to_fun,
injective' := embedding.inj',
coe_injective' := λ f g h, by { cases f, cases g, congr' } }
instance {α β : Sort*} : can_lift (α → β) (α ↪ β) coe_fn injective :=
{ prf := λ f hf, ⟨⟨f, hf⟩, rfl⟩ }
end function
section equiv
variables {α : Sort u} {β : Sort v} (f : α ≃ β)
/-- Convert an `α ≃ β` to `α ↪ β`.
This is also available as a coercion `equiv.coe_embedding`.
The explicit `equiv.to_embedding` version is preferred though, since the coercion can have issues
inferring the type of the resulting embedding. For example:
```lean
-- Works:
example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f.to_embedding = s.map f := by simp
-- Error, `f` has type `fin 3 ≃ fin 3` but is expected to have type `fin 3 ↪ ?m_1 : Type ?`
example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f = s.map f.to_embedding := by simp
```
-/
protected def equiv.to_embedding : α ↪ β := ⟨f, f.injective⟩
@[simp] lemma equiv.coe_to_embedding : ⇑f.to_embedding = f := rfl
lemma equiv.to_embedding_apply (a : α) : f.to_embedding a = f a := rfl
instance equiv.coe_embedding : has_coe (α ≃ β) (α ↪ β) := ⟨equiv.to_embedding⟩
@[reducible]
instance equiv.perm.coe_embedding : has_coe (equiv.perm α) (α ↪ α) := equiv.coe_embedding
@[simp] lemma equiv.coe_eq_to_embedding : ↑f = f.to_embedding := rfl
/-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding
set. -/
@[simps]
def equiv.as_embedding {p : β → Prop} (e : α ≃ subtype p) : α ↪ β :=
⟨coe ∘ e, subtype.coe_injective.comp e.injective⟩
end equiv
namespace function
namespace embedding
lemma coe_injective {α β} : @function.injective (α ↪ β) (α → β) coe_fn := fun_like.coe_injective
@[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h
lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := fun_like.ext_iff.symm
@[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl
@[simp] theorem coe_fn_mk {α β} (f : α → β) (i) :
(@mk _ _ f i : α → β) = f := rfl
@[simp] lemma mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f :=
by { ext, simp }
protected theorem injective {α β} (f : α ↪ β) : injective f := embedding_like.injective f
lemma apply_eq_iff_eq {α β} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y :=
embedding_like.apply_eq_iff_eq f
/-- The identity map as a `function.embedding`. -/
@[refl, simps {simp_rhs := tt}]
protected def refl (α : Sort*) : α ↪ α :=
⟨id, injective_id⟩
/-- Composition of `f : α ↪ β` and `g : β ↪ γ`. -/
@[trans, simps {simp_rhs := tt}]
protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ :=
⟨g ∘ f, g.injective.comp f.injective⟩
@[simp]
lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) :
e.to_embedding.trans e.symm.to_embedding = embedding.refl _ :=
by { ext, simp, }
@[simp]
lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) :
e.symm.to_embedding.trans e.to_embedding = embedding.refl _ :=
by { ext, simp, }
/-- Transfer an embedding along a pair of equivalences. -/
@[simps { fully_applied := ff }]
protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x}
(e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) :=
(equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding)
/-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/
protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) :
α ↪ β :=
⟨surj_inv hf, injective_surj_inv _⟩
/-- Convert a surjective `embedding` to an `equiv` -/
protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) :
α ≃ β :=
equiv.of_bijective f ⟨f.injective, hf⟩
/-- There is always an embedding from an empty type. -/
protected def of_is_empty {α β} [is_empty α] : α ↪ β :=
⟨is_empty_elim, is_empty_elim⟩
/-- Change the value of an embedding `f` at one point. If the prescribed image
is already occupied by some `f a'`, then swap the values at these two points. -/
def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)]
[∀ a', decidable (f a' = b)] : α ↪ β :=
⟨λ a', if a' = a then b else if f a' = b then f a else f a',
begin
intros x y h,
dsimp at h,
split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc
end⟩
theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)]
[∀ a', decidable (f a' = b)] : set_value f a b a = b :=
by simp [set_value]
/-- Embedding into `option α` using `some`. -/
@[simps { fully_applied := ff }] protected def some {α} : α ↪ option α :=
⟨some, option.some_injective α⟩
/-- Embedding into `option α` using `coe`. Usually the correct synctatical form for `simp`. -/
@[simps { fully_applied := ff }]
def coe_option {α} : α ↪ option α := ⟨coe, option.some_injective α⟩
/-- A version of `option.map` for `function.embedding`s. -/
@[simps { fully_applied := ff }]
def option_map {α β} (f : α ↪ β) : option α ↪ option β :=
⟨option.map f, option.map_injective f.injective⟩
/-- Embedding of a `subtype`. -/
def subtype {α} (p : α → Prop) : subtype p ↪ α :=
⟨coe, λ _ _, subtype.ext_val⟩
@[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl
/-- `quotient.out` as an embedding. -/
noncomputable def quotient_out (α) [s : setoid α] : quotient s ↪ α :=
⟨_, quotient.out_injective⟩
@[simp] theorem coe_quotient_out (α) [s : setoid α] : ⇑(quotient_out α) = quotient.out := rfl
/-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/
def punit {β : Sort*} (b : β) : punit ↪ β :=
⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩
/-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/
@[simps] def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β :=
⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩
/-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/
@[simps] def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β :=
⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩
/-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/
def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ :=
⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩
@[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :
⇑(e₁.prod_map e₂) = prod.map e₁ e₂ :=
rfl
/-- If `e₁` and `e₂` are embeddings, then so is `λ ⟨a, b⟩, ⟨e₁ a, e₂ b⟩ : pprod α γ → pprod β δ`. -/
def pprod_map {α β γ δ : Sort*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : pprod α γ ↪ pprod β δ :=
⟨λ x, ⟨e₁ x.1, e₂ x.2⟩, e₁.injective.pprod_map e₂.injective⟩
section sum
open sum
/-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/
def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ :=
⟨sum.map e₁ e₂,
assume s₁ s₂ h, match s₁, s₂, h with
| inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h
| inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h
end⟩
@[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :
⇑(sum_map e₁ e₂) = sum.map e₁ e₂ :=
rfl
/-- The embedding of `α` into the sum `α ⊕ β`. -/
@[simps] def inl {α β : Type*} : α ↪ α ⊕ β :=
⟨sum.inl, λ a b, sum.inl.inj⟩
/-- The embedding of `β` into the sum `α ⊕ β`. -/
@[simps] def inr {α β : Type*} : β ↪ α ⊕ β :=
⟨sum.inr, λ a b, sum.inr.inj⟩
end sum
section sigma
variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*}
/-- `sigma.mk` as an `function.embedding`. -/
@[simps apply] def sigma_mk (a : α) : β a ↪ Σ x, β x :=
⟨sigma.mk a, sigma_mk_injective⟩
/-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family
of embeddings, then `sigma.map f g` is an embedding. -/
@[simps apply] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) :
(Σ a, β a) ↪ Σ a', β' a' :=
⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩
end sigma
/-- Define an embedding `(Π a : α, β a) ↪ (Π a : α, γ a)` from a family of embeddings
`e : Π a, (β a ↪ γ a)`. This embedding sends `f` to `λ a, e a (f a)`. -/
@[simps] def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) :
(Π a, β a) ↪ (Π a, γ a) :=
⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩
/-- An embedding `e : α ↪ β` defines an embedding `(γ → α) ↪ (γ → β)` that sends each `f`
to `e ∘ f`. -/
def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) : (γ → α) ↪ (γ → β) :=
Pi_congr_right (λ _, e)
@[simp] lemma arrow_congr_right_apply {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) (f : γ ↪ α) : arrow_congr_right e f = e ∘ f := rfl
/-- An embedding `e : α ↪ β` defines an embedding `(α → γ) ↪ (β → γ)` for any inhabited type `γ`.
This embedding sends each `f : α → γ` to a function `g : β → γ` such that `g ∘ e = f` and
`g y = default` whenever `y ∉ range e`. -/
noncomputable def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ]
(e : α ↪ β) : (α → γ) ↪ (β → γ) :=
⟨λ f, extend e f default, λ f₁ f₂ h, funext $ λ x,
by simpa only [e.injective.extend_apply] using congr_fun h (e x)⟩
/-- Restrict both domain and codomain of an embedding. -/
protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β)
(h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} :=
⟨subtype.map f h, subtype.map_injective h f.2⟩
open set
lemma swap_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y z : α) :
equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) :=
f.injective.swap_apply x y z
lemma swap_comp {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y : α) :
equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y :=
f.injective.swap_comp x y
end embedding
end function
namespace equiv
open function.embedding
/-- The type of embeddings `α ↪ β` is equivalent to
the subtype of all injective functions `α → β`. -/
def subtype_injective_equiv_embedding (α β : Sort*) :
{f : α → β // function.injective f} ≃ (α ↪ β) :=
{ to_fun := λ f, ⟨f.val, f.property⟩,
inv_fun := λ f, ⟨f, f.injective⟩,
left_inv := λ f, by simp,
right_inv := λ f, by {ext, refl} }
/-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁`
is equivalent to the type of embeddings `α₂ ↪ β₂`. -/
@[congr, simps apply] def embedding_congr {α β γ δ : Sort*}
(h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) :=
{ to_fun := λ f, f.congr h h',
inv_fun := λ f, f.congr h.symm h'.symm,
left_inv := λ x, by {ext, simp},
right_inv := λ x, by {ext, simp} }
@[simp] lemma embedding_congr_refl {α β : Sort*} :
embedding_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ↪ β) :=
by {ext, refl}
@[simp] lemma embedding_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
embedding_congr (e₁.trans e₂) (e₁'.trans e₂') =
(embedding_congr e₁ e₁').trans (embedding_congr e₂ e₂') :=
rfl
@[simp] lemma embedding_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(embedding_congr e₁ e₂).symm = embedding_congr e₁.symm e₂.symm :=
rfl
lemma embedding_congr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*}
(ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) :
equiv.embedding_congr ea ec (f.trans g) =
(equiv.embedding_congr ea eb f).trans (equiv.embedding_congr eb ec g) :=
by {ext, simp}
@[simp]
lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl
@[simp]
lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) :
(e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl
end equiv
section subtype
variable {α : Type*}
/-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split
into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/
def subtype_or_left_embedding (p q : α → Prop) [decidable_pred p] :
{x // p x ∨ q x} ↪ {x // p x} ⊕ {x // q x} :=
⟨λ x, if h : p x then sum.inl ⟨x, h⟩ else sum.inr ⟨x, x.prop.resolve_left h⟩,
begin
intros x y,
dsimp only,
split_ifs;
simp [subtype.ext_iff]
end⟩
lemma subtype_or_left_embedding_apply_left {p q : α → Prop} [decidable_pred p]
(x : {x // p x ∨ q x}) (hx : p x) : subtype_or_left_embedding p q x = sum.inl ⟨x, hx⟩ :=
dif_pos hx
lemma subtype_or_left_embedding_apply_right {p q : α → Prop} [decidable_pred p]
(x : {x // p x ∨ q x}) (hx : ¬ p x) :
subtype_or_left_embedding p q x = sum.inr ⟨x, x.prop.resolve_left hx⟩ :=
dif_neg hx
/-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`,
if `p x → q x` for all `x : α`. -/
@[simps] def subtype.imp_embedding (p q : α → Prop) (h : ∀ x, p x → q x) :
{x // p x} ↪ {x // q x} :=
⟨λ x, ⟨x, h x x.prop⟩, λ x y, by simp [subtype.ext_iff]⟩
end subtype
|
a5033a67afc85d271dbf36b322c9a18b7f88ce87 | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /src/Lean/Meta/Basic.lean | fea3d4c8696695e84517454b7563859d0e32b23b | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47,073 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.LOption
import Lean.Environment
import Lean.Class
import Lean.ReducibilityAttrs
import Lean.Util.Trace
import Lean.Util.RecDepth
import Lean.Util.PPExt
import Lean.Util.OccursCheck
import Lean.Util.MonadBacktrack
import Lean.Compiler.InlineAttrs
import Lean.Meta.TransparencyMode
import Lean.Meta.DiscrTreeTypes
import Lean.Eval
import Lean.CoreM
/-
This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.
1- Weak head normal form computation with support for metavariables and transparency modes.
2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).
3- Type inference.
4- Type class resolution.
They are packed into the MetaM monad.
-/
namespace Lean.Meta
builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck
structure Config where
foApprox : Bool := false
ctxApprox : Bool := false
quasiPatternApprox : Bool := false
/- When `constApprox` is set to true,
we solve `?m t =?= c` using
`?m := fun _ => c`
when `?m t` is not a higher-order pattern and `c` is not an application as -/
constApprox : Bool := false
/-
When the following flag is set,
`isDefEq` throws the exeption `Exeption.isDefEqStuck`
whenever it encounters a constraint `?m ... =?= t` where
`?m` is read only.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`. -/
isDefEqStuckEx : Bool := false
transparency : TransparencyMode := TransparencyMode.default
/- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/
zetaNonDep : Bool := true
/- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/
trackZeta : Bool := false
unificationHints : Bool := true
/- Enables proof irrelevance at `isDefEq` -/
proofIrrelevance : Bool := true
structure ParamInfo where
implicit : Bool := false
instImplicit : Bool := false
hasFwdDeps : Bool := false
backDeps : Array Nat := #[]
deriving Inhabited
def ParamInfo.isExplicit (p : ParamInfo) : Bool :=
!p.implicit && !p.instImplicit
structure FunInfo where
paramInfo : Array ParamInfo := #[]
resultDeps : Array Nat := #[]
structure InfoCacheKey where
transparency : TransparencyMode
expr : Expr
nargs? : Option Nat
deriving Inhabited, BEq
namespace InfoCacheKey
instance : Hashable InfoCacheKey :=
⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩
end InfoCacheKey
open Std (PersistentArray PersistentHashMap)
abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr)
abbrev InferTypeCache := PersistentExprStructMap Expr
abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo
abbrev WhnfCache := PersistentExprStructMap Expr
structure Cache where
inferType : InferTypeCache := {}
funInfo : FunInfoCache := {}
synthInstance : SynthInstanceCache := {}
whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default`
whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all`
deriving Inhabited
/--
"Context" for a postponed universe constraint.
`lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created.
-/
structure DefEqContext where
lhs : Expr
rhs : Expr
lctx : LocalContext
localInstances : LocalInstances
/--
Auxiliary structure for representing postponed universe constraints.
Remark: the fields `ref` and `rootDefEq?` are used for error message generation only.
Remark: we may consider improving the error message generation in the future.
-/
structure PostponedEntry where
ref : Syntax -- We save the `ref` at entry creation time
lhs : Level
rhs : Level
ctx? : Option DefEqContext -- Context for the surrounding `isDefEq` call when entry was created
deriving Inhabited
structure State where
mctx : MetavarContext := {}
cache : Cache := {}
/- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/
zetaFVarIds : NameSet := {}
postponed : PersistentArray PostponedEntry := {}
deriving Inhabited
structure SavedState where
core : Core.State
meta : State
deriving Inhabited
structure Context where
config : Config := {}
lctx : LocalContext := {}
localInstances : LocalInstances := #[]
/-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/
defEqCtx? : Option DefEqContext := none
abbrev MetaM := ReaderT Context $ StateRefT State CoreM
instance : Inhabited (MetaM α) where
default := fun _ _ => arbitrary
instance : MonadLCtx MetaM where
getLCtx := return (← read).lctx
instance : MonadMCtx MetaM where
getMCtx := return (← get).mctx
modifyMCtx f := modify fun s => { s with mctx := f s.mctx }
instance : AddMessageContext MetaM where
addMessageContext := addMessageContextFull
protected def saveState : MetaM SavedState :=
return { core := (← getThe Core.State), meta := (← get) }
/-- Restore backtrackable parts of the state. -/
def SavedState.restore (b : SavedState) : MetaM Unit := do
Core.restore b.core
modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed }
instance : MonadBacktrack SavedState MetaM where
saveState := Meta.saveState
restoreState s := s.restore
@[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) :=
x ctx |>.run s
@[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α :=
Prod.fst <$> x.run ctx s
@[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do
let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore
pure (a, sCore, s)
instance [MetaEval α] : MetaEval (MetaM α) :=
⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩
protected def throwIsDefEqStuck : MetaM α :=
throw <| Exception.internal isDefEqStuckExceptionId
builtin_initialize
registerTraceClass `Meta
registerTraceClass `Meta.debug
@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α :=
liftM x
@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α :=
controlAt MetaM fun runInBase => f <| runInBase x
@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α :=
controlAt MetaM fun runInBase => f fun b => runInBase <| k b
@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α :=
controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c
section Methods
variable [MonadControlT MetaM n] [Monad n]
@[inline] def modifyCache (f : Cache → Cache) : MetaM Unit :=
modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩
@[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit :=
modifyCache fun ⟨ic, c1, c2, c3, c4⟩ => ⟨f ic, c1, c2, c3, c4⟩
def getLocalInstances : MetaM LocalInstances :=
return (← read).localInstances
def getConfig : MetaM Config :=
return (← read).config
def setMCtx (mctx : MetavarContext) : MetaM Unit :=
modify fun s => { s with mctx := mctx }
def resetZetaFVarIds : MetaM Unit :=
modify fun s => { s with zetaFVarIds := {} }
def getZetaFVarIds : MetaM NameSet :=
return (← get).zetaFVarIds
def getPostponed : MetaM (PersistentArray PostponedEntry) :=
return (← get).postponed
def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := postponed }
@[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := f s.postponed }
builtin_initialize whnfRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "whnf implementation was not set"
builtin_initialize inferTypeRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "inferType implementation was not set"
builtin_initialize isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) ← IO.mkRef fun _ _ => throwError "isDefEq implementation was not set"
builtin_initialize synthPendingRef : IO.Ref (MVarId → MetaM Bool) ← IO.mkRef fun _ => pure false
def whnf (e : Expr) : MetaM Expr :=
withIncRecDepth do (← whnfRef.get) e
def whnfForall (e : Expr) : MetaM Expr := do
let e' ← whnf e
if e'.isForall then pure e' else pure e
def inferType (e : Expr) : MetaM Expr :=
withIncRecDepth do (← inferTypeRef.get) e
protected def isExprDefEqAux (t s : Expr) : MetaM Bool :=
withIncRecDepth do (← isExprDefEqAuxRef.get) t s
protected def synthPending (mvarId : MVarId) : MetaM Bool :=
withIncRecDepth do (← synthPendingRef.get) mvarId
-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`
protected def withIncRecDepth (x : n α) : n α :=
mapMetaM (withIncRecDepth (m := MetaM)) x
private def mkFreshExprMVarAtCore
(mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do
modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;
return mkMVar mvarId
def mkFreshExprMVarAt
(lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
let mvarId ← mkFreshId
mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs
def mkFreshLevelMVar : MetaM Level := do
let mvarId ← mkFreshId
modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;
return mkLevelMVar mvarId
private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do
let lctx ← getLCtx
let localInsts ← getLocalInstances
mkFreshExprMVarAt lctx localInsts type kind userName
private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarCore type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous
mkFreshExprMVarCore type kind userName
def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
mkFreshExprMVarImpl type? kind userName
def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do
let u ← mkFreshLevelMVar
mkFreshExprMVar (mkSort u) kind userName
/- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create
the metavar using this method. -/
private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
let lctx ← getLCtx
let localInsts ← getLocalInstances
mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs
def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarWithIdCore mvarId type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVar (mkSort u)
mkFreshExprMVarWithIdCore mvarId type kind userName
def mkFreshLevelMVars (num : Nat) : MetaM (List Level) :=
num.foldM (init := []) fun _ us =>
return (← mkFreshLevelMVar)::us
def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) :=
mkFreshLevelMVars info.numLevelParams
def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do
let info ← getConstInfo declName
return mkConst declName (← mkFreshLevelMVarsFor info)
def getTransparency : MetaM TransparencyMode :=
return (← getConfig).transparency
def shouldReduceAll : MetaM Bool :=
return (← getTransparency) == TransparencyMode.all
def shouldReduceReducibleOnly : MetaM Bool :=
return (← getTransparency) == TransparencyMode.reducible
def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do
let mctx ← getMCtx
match mctx.findDecl? mvarId with
| some d => pure d
| none => throwError "unknown metavariable '?{mvarId}'"
def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=
modifyMCtx fun mctx => mctx.setMVarKind mvarId kind
/- Update the type of the given metavariable. This function assumes the new type is
definitionally equal to the current one -/
def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do
modifyMCtx fun mctx => mctx.setMVarType mvarId type
def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvarId
let mctx ← getMCtx
return mvarDecl.depth != mctx.depth
def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvarId
match mvarDecl.kind with
| MetavarKind.syntheticOpaque => pure true
| _ =>
let mctx ← getMCtx
return mvarDecl.depth != mctx.depth
def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do
let mctx ← getMCtx
match mctx.findLevelDepth? mvarId with
| some depth => return depth != mctx.depth
| _ => throwError "unknown universe metavariable '?{mvarId}'"
def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=
modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName
def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isExprAssigned mvarId
def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) :=
return (← getMCtx).getExprAssignment? mvarId
/-- Return true if `e` contains `mvarId` directly or indirectly -/
def occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool :=
return (← getMCtx).occursCheck mvarId e
def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit :=
modifyMCtx fun mctx => mctx.assignExpr mvarId val
def isDelayedAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isDelayedAssigned mvarId
def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) :=
return (← getMCtx).getDelayedAssignment? mvarId
def hasAssignableMVar (e : Expr) : MetaM Bool :=
return (← getMCtx).hasAssignableMVar e
def throwUnknownFVar (fvarId : FVarId) : MetaM α :=
throwError "unknown free variable '{mkFVar fvarId}'"
def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=
return (← getLCtx).find? fvarId
def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do
match (← getLCtx).find? fvarId with
| some d => pure d
| none => throwUnknownFVar fvarId
def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=
getLocalDecl fvar.fvarId!
def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do
match (← getLCtx).findFromUserName? userName with
| some d => pure d
| none => throwError "unknown local declaration '{userName}'"
def instantiateLevelMVars (u : Level) : MetaM Level :=
MetavarContext.instantiateLevelMVars u
def instantiateMVars (e : Expr) : MetaM Expr :=
(MetavarContext.instantiateExprMVars e).run
def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl := do
match localDecl with
| LocalDecl.cdecl idx id n type bi =>
let type ← instantiateMVars type
return LocalDecl.cdecl idx id n type bi
| LocalDecl.ldecl idx id n type val nonDep =>
let type ← instantiateMVars type
let val ← instantiateMVars val
return LocalDecl.ldecl idx id n type val nonDep
@[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do
match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with
| EStateM.Result.ok e newS => do
setNGen newS.ngen;
setMCtx newS.mctx;
pure e
| EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do
setMCtx newS.mctx;
setNGen newS.ngen;
throwError "failed to create binder due to failure when reverting variable dependencies"
def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly
def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly
def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) : MetaM Expr :=
mkLambdaFVars xs e (usedLetOnly := usedLetOnly)
def mkArrow (d b : Expr) : MetaM Expr := do
let n ← mkFreshUserName `x
return Lean.mkForall n BinderInfo.default d b
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder
@[inline] def withConfig (f : Config → Config) : n α → n α :=
mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })
@[inline] def withTrackingZeta (x : n α) : n α :=
withConfig (fun cfg => { cfg with trackZeta := true }) x
@[inline] def withoutProofIrrelevance (x : n α) : n α :=
withConfig (fun cfg => { cfg with proofIrrelevance := false }) x
@[inline] def withTransparency (mode : TransparencyMode) : n α → n α :=
mapMetaM <| withConfig (fun config => { config with transparency := mode })
@[inline] def withDefault (x : n α) : n α :=
withTransparency TransparencyMode.default x
@[inline] def withReducible (x : n α) : n α :=
withTransparency TransparencyMode.reducible x
@[inline] def withReducibleAndInstances (x : n α) : n α :=
withTransparency TransparencyMode.instances x
@[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α :=
withConfig
(fun config =>
let oldMode := config.transparency
let mode := if oldMode.lt mode then mode else oldMode
{ config with transparency := mode })
x
/-- Save cache, execute `x`, restore cache -/
@[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do
let s ← get
let savedCache := s.cache
try x finally modify fun s => { s with cache := savedCache }
@[inline] def savingCache : n α → n α :=
mapMetaM savingCacheImpl
def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
if (← shouldReduceAll) then
return some info
else
return none
private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
match (← getTransparency) with
| TransparencyMode.all => return some info
| TransparencyMode.default => return some info
| _ =>
if (← isReducible info.name) then
return some info
else
return none
/- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.
This method is only used to implement `isClassQuickConst?`.
It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and
`constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/
private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do
let env ← getEnv
match env.find? constName with
| some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info
| some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info
| some info => pure (some info)
| none => throwUnknownConstant constName
private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do
let env ← getEnv
if isClass env constName then
pure (LOption.some constName)
else
match (← getConstTemp? constName) with
| some _ => pure LOption.undef
| none => pure LOption.none
private partial def isClassQuick? : Expr → MetaM (LOption Name)
| Expr.bvar .. => pure LOption.none
| Expr.lit .. => pure LOption.none
| Expr.fvar .. => pure LOption.none
| Expr.sort .. => pure LOption.none
| Expr.lam .. => pure LOption.none
| Expr.letE .. => pure LOption.undef
| Expr.proj .. => pure LOption.undef
| Expr.forallE _ _ b _ => isClassQuick? b
| Expr.mdata _ e _ => isClassQuick? e
| Expr.const n _ _ => isClassQuickConst? n
| Expr.mvar mvarId _ => do
match (← getExprMVarAssignment? mvarId) with
| some val => isClassQuick? val
| none => pure LOption.none
| Expr.app f _ _ =>
match f.getAppFn with
| Expr.const n .. => isClassQuickConst? n
| Expr.lam .. => pure LOption.undef
| _ => pure LOption.none
def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do
let s ← get
let savedSythInstance := s.cache.synthInstance
modifyCache fun c => { c with synthInstance := {} }
pure savedSythInstance
def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit :=
modifyCache fun c => { c with synthInstance := cache }
@[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do
let savedSythInstance ← saveAndResetSynthInstanceCache
try x finally restoreSynthInstanceCache savedSythInstance
/-- Reset `synthInstance` cache, execute `x`, and restore cache -/
@[inline] def resettingSynthInstanceCache : n α → n α :=
mapMetaM resettingSynthInstanceCacheImpl
@[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α :=
if b then resettingSynthInstanceCache x else x
private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do
let localDecl ← getFVarLocalDecl fvar
/- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/
match localDecl.binderInfo with
| BinderInfo.auxDecl => k
| _ =>
resettingSynthInstanceCache <|
withReader
(fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } })
k
/-- Add entry `{ className := className, fvar := fvar }` to localInstances,
and then execute continuation `k`.
It resets the type class cache using `resettingSynthInstanceCache`. -/
def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α :=
mapMetaM <| withNewLocalInstanceImp className fvar
private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=
match maxFVars? with
| some maxFVars => fvars.size < maxFVars
| none => true
mutual
/--
`withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances
using free variables `fvars[j] ... fvars.back`, and execute `k`.
- `isClassExpensive` is defined later.
- The type class chache is reset whenever a new local instance is found.
- `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.
Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/
private partial def withNewLocalInstancesImp
(fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do
if h : i < fvars.size then
let fvar := fvars.get ⟨i, h⟩
let decl ← getFVarLocalDecl fvar
match (← isClassQuick? decl.type) with
| LOption.none => withNewLocalInstancesImp fvars (i+1) k
| LOption.undef =>
match (← isClassExpensive? decl.type) with
| none => withNewLocalInstancesImp fvars (i+1) k
| some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k
| LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k
else
k
/--
`forallTelescopeAuxAux lctx fvars j type`
Remarks:
- `lctx` is the `MetaM` local context extended with declarations for `fvars`.
- `type` is the type we are computing the telescope for. It contains only
dangling bound variables in the range `[j, fvars.size)`
- if `reducing? == true` and `type` is not `forallE`, we use `whnf`.
- when `type` is not a `forallE` nor it can't be reduced to one, we
excute the continuation `k`.
Here is an example that demonstrates the `reducing?`.
Suppose we have
```
abbrev StateM s a := s -> Prod a s
```
Now, assume we are trying to build the telescope for
```
forall (x : Nat), StateM Int Bool
```
if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.
if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`
if `maxFVars?` is `some max`, then we interrupt the telescope construction
when `fvars.size == max`
-/
private partial def forallTelescopeReducingAuxAux
(reducing : Bool) (maxFVars? : Option Nat)
(type : Expr)
(k : Array Expr → Expr → MetaM α) : MetaM α := do
let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do
match type with
| Expr.forallE n d b c =>
if fvarsSizeLtMaxFVars fvars maxFVars? then
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
let fvars := fvars.push fvar
process lctx fvars j b
else
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars type
| _ =>
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then
let newType ← whnf type
if newType.isForall then
process lctx fvars fvars.size newType
else
k fvars type
else
k fvars type
process (← getLCtx) #[] 0 type
private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do
match maxFVars? with
| some 0 => k #[] type
| _ => do
let newType ← whnf type
if newType.isForall then
forallTelescopeReducingAuxAux true maxFVars? newType k
else
k #[] type
private partial def isClassExpensive? : Expr → MetaM (Option Name)
| type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants.
forallTelescopeReducingAux type none fun xs type => do
let env ← getEnv
match type.getAppFn with
| Expr.const c _ _ => do
if isClass env c then
return some c
else
-- make sure abbreviations are unfolded
match (← whnf type).getAppFn with
| Expr.const c _ _ => return if isClass env c then some c else none
| _ => return none
| _ => return none
private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do
match (← isClassQuick? type) with
| LOption.none => pure none
| LOption.some c => pure (some c)
| LOption.undef => isClassExpensive? type
end
def isClass? (type : Expr) : MetaM (Option Name) :=
try isClassImp? type catch _ => pure none
private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM <| withNewLocalInstancesImp fvars j
partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM <| withNewLocalInstancesImpAux fvars j
@[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k
/--
Given `type` of the form `forall xs, A`, execute `k xs A`.
This combinator will declare local declarations, create free variables for them,
execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/
def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeImp type k) k
private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type (maxFVars? := none) k
/--
Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,
it reduces `A` and continues bulding the telescope if it is a `forall`. -/
def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeReducingImp type k) k
private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type maxFVars? k
/--
Similar to `forallTelescopeReducing`, stops constructing the telescope when
it reaches size `maxFVars`. -/
def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k
/-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/
private partial def lambdaTelescopeAux
(k : Array Expr → Expr → MetaM α)
: Bool → LocalContext → Array Expr → Nat → Expr → MetaM α
| consumeLet, lctx, fvars, j, Expr.lam n d b c => do
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
lambdaTelescopeAux k consumeLet lctx (fvars.push fvar) j b
| true, lctx, fvars, j, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars
let v := v.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLetDecl fvarId n t v
let fvar := mkFVar fvarId
lambdaTelescopeAux k true lctx (fvars.push fvar) j b
| _, lctx, fvars, j, e =>
let e := e.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars e
private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do
let rec process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do
match consumeLet, e with
| _, Expr.lam n d b c =>
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
process consumeLet lctx (fvars.push fvar) j b
| true, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars
let v := v.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLetDecl fvarId n t v
let fvar := mkFVar fvarId
process true lctx (fvars.push fvar) j b
| _, e =>
let e := e.instantiateRevRange j fvars.size fvars
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars e
process consumeLet (← getLCtx) #[] 0 e
/-- Similar to `forallTelescope` but for lambda and let expressions. -/
def lambdaLetTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type true k) k
/-- Similar to `forallTelescope` but for lambda expressions. -/
def lambdaTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type false k) k
/-- Return the parameter names for the givel global declaration. -/
def getParamNames (declName : Name) : MetaM (Array Name) := do
let cinfo ← getConstInfo declName
forallTelescopeReducing cinfo.type fun xs _ => do
xs.mapM fun x => do
let localDecl ← getLocalDecl x.fvarId!
pure localDecl.userName
-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.
private partial def forallMetaTelescopeReducingAux
(e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) :=
let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
match type with
| Expr.forallE n d b c =>
let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
let d := d.instantiateRevRange j mvars.size mvars
let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind
let mvar ← mkFreshExprMVar d k n
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
match maxMVars? with
| none => cont ()
| some maxMVars =>
if mvars.size < maxMVars then
cont ()
else
let type := type.instantiateRevRange j mvars.size mvars;
pure (mvars, bis, type)
| _ =>
let type := type.instantiateRevRange j mvars.size mvars;
if reducing then do
let newType ← whnf type;
if newType.isForall then
process mvars bis mvars.size newType
else
pure (mvars, bis, type)
else
pure (mvars, bis, type)
process #[] #[] 0 e
/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/
def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind
/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/
def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind
/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/
partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) :=
let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
let type := type.instantiateRevRange j mvars.size mvars
pure (mvars, bis, type)
let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
match type with
| Expr.lam n d b c =>
let d := d.instantiateRevRange j mvars.size mvars
let mvar ← mkFreshExprMVar d
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
| _ => finalize ()
match maxMVars? with
| none => cont ()
| some maxMVars =>
if mvars.size < maxMVars then
cont ()
else
finalize ()
process #[] #[] 0 e
private def withNewFVar (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do
match (← isClass? fvarType) with
| none => k fvar
| some c => withNewLocalInstance c fvar <| k fvar
private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshId
let ctx ← read
let lctx := ctx.lctx.mkLocalDecl fvarId n type bi
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLocalDeclImp name bi type k) k
def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α :=
withLocalDecl name BinderInfo.default type k
partial def withLocalDecls
[Inhabited α]
(declInfos : Array (Name × BinderInfo × (Array Expr → n Expr)))
(k : (xs : Array Expr) → n α)
: n α :=
let rec loop
[Inhabited α]
(acc : Array Expr) : n α := do
if acc.size < declInfos.size then
let (name, bi, typeCtor) := declInfos[acc.size]
withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x)
else k acc
loop #[]
def withLocalDeclsD
[Inhabited α]
(declInfos : Array (Name × (Array Expr → n Expr)))
(k : (xs : Array Expr) → n α)
: n α :=
withLocalDecls
(declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k
private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do
let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) =>
lctx.setBinderInfo fvarId bi
withReader (fun ctx => { ctx with lctx := lctx }) k
def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α :=
mapMetaM (fun k => withNewBinderInfosImp bs k) k
private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshId
let ctx ← read
let lctx := ctx.lctx.mkLetDecl fvarId n type val
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLetDeclImp name type val k) k
private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do
let ctx ← read
let numLocalInstances := ctx.localInstances.size
let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx
withReader (fun ctx => { ctx with lctx := lctx }) do
let newLocalInsts ← decls.foldlM
(fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do {
match (← isClass? decl.type) with
| none => pure newlocalInsts
| some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _))
ctx.localInstances;
if newLocalInsts.size == numLocalInstances then
k
else
resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k
def withExistingLocalDecls (decls : List LocalDecl) : n α → n α :=
mapMetaM <| withExistingLocalDeclsImp decls
private def withNewMCtxDepthImp (x : MetaM α) : MetaM α := do
let saved ← get
modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} }
try
x
finally
modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed }
/--
Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,
and restore saved data. -/
def withNewMCtxDepth : n α → n α :=
mapMetaM withNewMCtxDepthImp
private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do
let localInstsCurr ← getLocalInstances
withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do
if localInsts == localInstsCurr then
x
else
resettingSynthInstanceCache x
def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α :=
mapMetaM <| withLocalContextImp lctx localInsts
private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do
let mvarDecl ← getMVarDecl mvarId
withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x
/--
Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.
The type class resolution cache is flushed when executing `x` if its `LocalInstances` are
different from the current ones. -/
def withMVarContext (mvarId : MVarId) : n α → n α :=
mapMetaM <| withMVarContextImp mvarId
private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do
let mctx' ← getMCtx
setMCtx mctx
try x finally setMCtx mctx'
def withMCtx (mctx : MetavarContext) : n α → n α :=
mapMetaM <| withMCtxImp mctx
@[inline] private def approxDefEqImp (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x
/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/
@[inline] def approxDefEq : n α → n α :=
mapMetaM approxDefEqImp
@[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x
/--
Similar to `approxDefEq`, but uses all available approximations.
We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.
For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.
Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved
as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to
solve `[Pure (fun _ => IO Bool)]` -/
@[inline] def fullApproxDefEq : n α → n α :=
mapMetaM fullApproxDefEqImp
def normalizeLevel (u : Level) : MetaM Level := do
let u ← instantiateLevelMVars u
pure u.normalize
def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do
modifyMCtx fun mctx => mctx.assignLevel mvarId u
def whnfR (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.reducible <| whnf e
def whnfD (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.default <| whnf e
def whnfI (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.instances <| whnf e
def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do
let env ← getEnv
match Compiler.setInlineAttribute env declName kind with
| Except.ok env => setEnv env
| Except.error msg => throwError msg
private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
let e ← whnf e
match e with
| Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateForall, too many parameters"
else
pure e
/- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/
def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateForallAux ps 0 e
private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
let e ← whnf e
match e with
| Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateLambda, too many parameters"
else
pure e
/- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.
It uses `whnf` to reduce `e` if it is not a lambda -/
def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateLambdaAux ps 0 e
/-- Return true iff `e` depends on the free variable `fvarId` -/
def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool :=
return (← getMCtx).exprDependsOn e fvarId
def ppExpr (e : Expr) : MetaM Format := do
let env ← getEnv
let mctx ← getMCtx
let lctx ← getLCtx
let opts ← getOptions
let ctxCore ← readThe Core.Context
Lean.ppExpr { env := env, mctx := mctx, lctx := lctx, opts := opts, currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e
@[inline] protected def orelse (x y : MetaM α) : MetaM α := do
let env ← getEnv
let mctx ← getMCtx
try x catch _ => setEnv env; setMCtx mctx; y
instance : OrElse (MetaM α) := ⟨Meta.orelse⟩
@[inline] private def orelseMergeErrorsImp (x y : MetaM α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do
let env ← getEnv
let mctx ← getMCtx
try
x
catch ex =>
setEnv env
setMCtx mctx
match ex with
| Exception.error ref₁ m₁ =>
try
y
catch
| Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂)
| ex => throw ex
| ex => throw ex
/--
Similar to `orelse`, but merge errors. Note that internal errors are not caught.
The default `mergeRef` uses the `ref` (position information) for the first message.
The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/
@[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do
controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg
/-- Execute `x`, and apply `f` to the produced error message -/
def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do
try
x
catch
| Exception.error ref msg => throw <| Exception.error ref <| f msg
| ex => throw ex
@[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α :=
controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f
end Methods
end Meta
export Meta (MetaM)
end Lean
|
a85b012d650f63c711d9b3e99942e88583eeb80e | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/auto_cases.lean | 22504b8c5147849508bd567994d6280311c1459e | [] | 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 | 421 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.hint
import Mathlib.PostPort
namespace Mathlib
namespace tactic
namespace auto_cases
/-- Structure representing a tactic which can be used by `tactic.auto_cases`. -/
|
80b24d1eb4d0f63fd24bda134ebb8284c8b7682e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/simpExtraArgsBug.lean | 36297c40c38fd534a81c77184bbbe106184dcd34 | [
"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 | 918 | lean | variable {X : Type u} {Y : Type v} {Z : Type w}
def comp (f : Y→Z) (g : X→Y) (x : X) := f (g x)
def swap (f : X→Y→Z) (y : Y) (x : X) := f x y
def diag (f : X→X→Y) (x : X) := (f x x)
@[simp] def comp_reduce (f : Y→Z) (g : X→Y) (x : X) : (comp f g x) = f (g x) := by simp[comp]; done
def swap_reduce (f : X→Y→Z) (y : Y) (x : X) : (swap f y x) = f x y := by simp[swap]; done
@[simp] def diag_reduce (f : X→X→Y) (x : X) : (diag f x) = f x x := by simp[diag]; done
def subs : (X→Y→Z) → (X→Y) → (X→Z) := (swap (comp (comp diag) (comp comp (swap comp))))
def foo {W} := ((comp comp (swap comp)) : (X→Y) → _ → W → X → Z)
def subs_reduce' (f : X→Y→Z) (g : X→Y) (x : X) : comp (comp diag) foo g f x = (f x) (g x) :=
by
simp
simp [foo, swap, comp]
def subs_reduce'' (f : X→Y→Z) (g : X→Y) (x : X) : comp (comp diag) foo g f x = (f x) (g x) :=
by
simp
admit
|
f488f36609b867e9784d567b02eb484544d429c0 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/System/IOError.lean | 9696c4e412d304b9d0dff440dca4807b1082263d | [
"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 | 8,463 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
prelude
import Init.Core
import Init.Data.UInt
import Init.Data.ToString
import Init.Data.String.Basic
/-
Imitate the structure of IOErrorType in Haskell:
https://hackage.haskell.org/package/base-4.12.0.0/docs/System-IO-Error.html#t:IOErrorType
-/
inductive IO.Error
| alreadyExists (osCode : UInt32) (details : String) -- EEXIST, EINPROGRESS, EISCONN
| otherError (osCode : UInt32) (details : String) -- EFAULT, default
| resourceBusy (osCode : UInt32) (details : String)
-- EADDRINUSE, EBUSY, EDEADLK, ETXTBSY
| resourceVanished (osCode : UInt32) (details : String)
-- ECONNRESET, EIDRM, ENETDOWN, ENETRESET,
-- ENOLINK, EPIPE
| unsupportedOperation (osCode : UInt32) (details : String)
-- EADDRNOTAVAIL, EAFNOSUPPORT, ENODEV, ENOPROTOOPT
-- ENOSYS, EOPNOTSUPP, ERANGE, ESPIPE, EXDEV
| hardwareFault (osCode : UInt32) (details : String) -- EIO
| unsatisfiedConstraints (osCode : UInt32) (details : String) -- ENOTEMPTY
| illegalOperation (osCode : UInt32) (details : String) -- ENOTTY
| protocolError (osCode : UInt32) (details : String)
-- EPROTO, EPROTONOSUPPORT, EPROTOTYPE
| timeExpired (osCode : UInt32) (details : String)
-- ETIME, ETIMEDOUT
| interrupted (filename : String) (osCode : UInt32) (details : String) -- EINTR
| noFileOrDirectory (filename : String) (osCode : UInt32) (details : String) -- ENOENT
| invalidArgument (filename : Option String) (osCode : UInt32) (details : String)
-- ELOOP, ENAMETOOLONG, EDESTADDRREQ, EILSEQ, EINVAL, EDOM, EBADF
-- ENOEXEC, ENOSTR, ENOTCONN, ENOTSOCK
| permissionDenied (filename : Option String) (osCode : UInt32) (details : String)
-- EACCES, EROFS, ECONNABORTED, EFBIG, EPERM
| resourceExhausted (filename : Option String) (osCode : UInt32) (details : String)
-- EMFILE, ENFILE, ENOSPC, E2BIG, EAGAIN, EMLINK:
-- EMSGSIZE, ENOBUFS, ENOLCK, ENOMEM, ENOSR:
| inappropriateType (filename : Option String) (osCode : UInt32) (details : String)
-- EISDIR, EBADMSG, ENOTDIR:
| noSuchThing (filename : Option String) (osCode : UInt32) (details : String)
-- ENXIO, EHOSTUNREACH, ENETUNREACH, ECHILD, ECONNREFUSED,
-- ENODATA, ENOMSG, ESRCH
| unexpectedEof
| userError (msg : String)
@[export mk_io_user_error]
def IO.userError (s : String) : IO.Error :=
IO.Error.userError s
namespace IO.Error
@[export lean_mk_io_error_eof]
def mkEofError : Unit → IO.Error := fun _ => unexpectedEof
@[export lean_mk_io_error_inappropriate_type_file]
def mkInappropriateTypeFile : String → UInt32 → String → IO.Error :=
inappropriateType ∘ some
@[export lean_mk_io_error_interrupted]
def mkInterrupted : String → UInt32 → String → IO.Error :=
interrupted
@[export lean_mk_io_error_invalid_argument_file]
def mkInvalidArgumentFile : String → UInt32 → String → IO.Error :=
invalidArgument ∘ some
@[export lean_mk_io_error_no_file_or_directory]
def mkNoFileOrDirectory : String → UInt32 → String → IO.Error :=
noFileOrDirectory
@[export lean_mk_io_error_no_such_thing_file]
def mkNoSuchThingFile : String → UInt32 → String → IO.Error :=
noSuchThing ∘ some
@[export lean_mk_io_error_permission_denied_file]
def mkPermissionDeniedFile : String → UInt32 → String → IO.Error :=
permissionDenied ∘ some
@[export lean_mk_io_error_resource_exhausted_file]
def mkResourceExhaustedFile : String → UInt32 → String → IO.Error :=
resourceExhausted ∘ some
@[export lean_mk_io_error_unsupported_operation]
def mkUnsupportedOperation : UInt32 → String → IO.Error :=
unsupportedOperation
@[export lean_mk_io_error_resource_exhausted]
def mkResourceExhausted : UInt32 → String → IO.Error :=
resourceExhausted none
@[export lean_mk_io_error_already_exists]
def mkAlreadyExists : UInt32 → String → IO.Error :=
alreadyExists
@[export lean_mk_io_error_inappropriate_type]
def mkInappropriateType : UInt32 → String → IO.Error :=
inappropriateType none
@[export lean_mk_io_error_no_such_thing]
def mkNoSuchThing : UInt32 → String → IO.Error :=
noSuchThing none
@[export lean_mk_io_error_resource_vanished]
def mkResourceVanished : UInt32 → String → IO.Error :=
resourceVanished
@[export lean_mk_io_error_resource_busy]
def mkResourceBusy : UInt32 → String → IO.Error :=
resourceBusy
@[export lean_mk_io_error_invalid_argument]
def mkInvalidArgument : UInt32 → String → IO.Error :=
invalidArgument none
@[export lean_mk_io_error_other_error]
def mkOtherError : UInt32 → String → IO.Error :=
otherError
@[export lean_mk_io_error_permission_denied]
def mkPermissionDenied : UInt32 → String → IO.Error :=
permissionDenied none
@[export lean_mk_io_error_hardware_fault]
def mkHardwareFault : UInt32 → String → IO.Error :=
hardwareFault
@[export lean_mk_io_error_unsatisfied_constraints]
def mkUnsatisfiedConstraints : UInt32 → String → IO.Error :=
unsatisfiedConstraints
@[export lean_mk_io_error_illegal_operation]
def mkIllegalOperation : UInt32 → String → IO.Error :=
illegalOperation
@[export lean_mk_io_error_protocol_error]
def mkProtocolError : UInt32 → String → IO.Error :=
protocolError
@[export lean_mk_io_error_time_expired]
def mkTimeExpired : UInt32 → String → IO.Error :=
timeExpired
private def downCaseFirst (s : String) : String := s.modify 0 Char.toLower
def fopenErrorToString (gist fn : String) (code : UInt32) : Option String → String
| some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")\n file: " ++ fn
| none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")\n file: " ++ fn
def otherErrorToString (gist : String) (code : UInt32) : Option String → String
| some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")"
| none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")"
@[export lean_io_error_to_string]
def toString : IO.Error → String
| unexpectedEof => "end of file"
| inappropriateType (some fn) code details => fopenErrorToString "inappropriate type" fn code details
| inappropriateType none code details => otherErrorToString "inappropriate type" code details
| interrupted fn code details => fopenErrorToString "interrupted system call" fn code details
| invalidArgument (some fn) code details => fopenErrorToString "invalid argument" fn code details
| invalidArgument none code details => otherErrorToString "invalid argument" code details
| noFileOrDirectory fn code _ => fopenErrorToString "no such file or directory" fn code none
| noSuchThing (some fn) code details => fopenErrorToString "no such thing" fn code details
| noSuchThing none code details => otherErrorToString "no such thing" code details
| permissionDenied (some fn) code details => fopenErrorToString details fn code none
| permissionDenied none code details => otherErrorToString details code none
| resourceExhausted (some fn) code details => fopenErrorToString "resource exhausted" fn code details
| resourceExhausted none code details => otherErrorToString "resource exhausted" code details
| alreadyExists code details => otherErrorToString "already exists" code details
| otherError code details => otherErrorToString details code none
| resourceBusy code details => otherErrorToString "resource busy" code details
| resourceVanished code details => otherErrorToString "resource vanished" code details
| hardwareFault code _ => otherErrorToString "hardware fault" code none
| illegalOperation code details => otherErrorToString "illegal operation" code details
| protocolError code details => otherErrorToString "protocol error" code details
| timeExpired code details => otherErrorToString "time expired" code details
| unsatisfiedConstraints code _ => otherErrorToString "directory not empty" code none
| unsupportedOperation code details => otherErrorToString "unsupported operation" code details
| userError msg => msg
instance : HasToString IO.Error := ⟨ IO.Error.toString ⟩
instance : Inhabited IO.Error := ⟨ userError "" ⟩
end IO.Error
|
03ebf88b9721cd49fee8695a7c808f98ca1980cf | 52b9f0379b3b0200088f3b2ec594d4dd3d3e6128 | /datatypes.lean | 900baa08389ebf452308724e3882635834a780f5 | [] | no_license | minchaowu/mathematica_examples | f83fdf092a136f157dde8119b8a75c2cd4d91aae | fcc65b0b9fcb854f8671c0ebbca77bb3c1a9ecc1 | refs/heads/master | 1,610,729,580,720 | 1,498,331,049,000 | 1,498,331,049,000 | 99,731,631 | 0 | 0 | null | 1,502,222,706,000 | 1,502,222,706,000 | null | UTF-8 | Lean | false | false | 1,399 | lean | /-
Copyright (c) 2017 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
-/
import init.meta.mathematica
constant real : Type
notation `ℝ` := real
constant rof : linear_ordered_field ℝ
attribute [instance] rof
constants (sin cos tan : ℝ → ℝ) (pi : ℝ)
def {u} npow {α : Type u} [has_mul α] [has_one α] : α → ℕ → α
| r 0 := 1
| r (n+1) := r*npow r n
infix `^` := npow
@[simp] lemma rpow_zero (r : ℝ) : r^0 = 1 := rfl
@[simp] lemma rpow_succ (r : ℝ) (n : ℕ) : r^(n+1) = r*r^n := rfl
lemma sq_nonneg {α : Type} [linear_ordered_ring α] (a : α) : a^2 ≥ 0 :=
begin
unfold npow, rw mul_one, apply mul_self_nonneg
end
section
open mathematica
@[sym_to_pexpr]
meta def pow_to_pexpr : sym_trans_pexpr_rule :=
⟨"Power", ```(npow)⟩
end
@[instance] def {u} inhabited_of_has_zero {α : Type u} [has_zero α] : inhabited α := ⟨0⟩ -- works
open tactic
meta def mk_inhabitant_using (A : expr) (t : tactic unit) : tactic expr :=
do m ← mk_meta_var A,
gs ← get_goals,
set_goals [m],
t,
n ← num_goals,
if n > 0 then fail "mk_inhabitant_using failed" else do
r ← instantiate_mvars m,
set_goals gs,
return r
meta definition eq_by_simp (e1 e2 : expr) : tactic expr :=
do gl ← mk_app `eq [e1, e2],
mk_inhabitant_using gl simp <|> fail "unable to simplify"
|
cc24da5ad1357d60cd4589bce7aa29b4afefc16d | 137c667471a40116a7afd7261f030b30180468c2 | /src/data/finset/basic.lean | 655052e0368780e9f560363630d58f5fa2546188 | [
"Apache-2.0"
] | permissive | bragadeesh153/mathlib | 46bf814cfb1eecb34b5d1549b9117dc60f657792 | b577bb2cd1f96eb47031878256856020b76f73cd | refs/heads/master | 1,687,435,188,334 | 1,626,384,207,000 | 1,626,384,207,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 124,421 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
-/
import data.multiset.finset_ops
import tactic.monotonicity
import tactic.apply
import tactic.nth_rewrite
/-!
# Finite sets
Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib.
Below, `finset α` is defined as a structure with 2 fields:
1. `val` is a `multiset α` of elements;
2. `nodup` is a proof that `val` has no duplicates.
Finsets in Lean are constructive in that they have an underlying `list` that enumerates their
elements. In particular, any function that uses the data of the underlying list cannot depend on its
ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't
worry about it explicitly.
Finsets give a basic foundation for defining finite sums and products over types:
1. `∑ i in (s : finset α), f i`;
2. `∏ i in (s : finset α), f i`.
Lean refers to these operations as `big_operator`s.
More information can be found in `algebra.big_operators.basic`.
Finsets are directly used to define fintypes in Lean.
A `fintype α` instance for a type `α` consists of
a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`.
There is also `univ'`, the noncomputable partner to `univ`,
which is defined to be `α` as a finset if `α` is finite,
and the empty finset otherwise. See `data.fintype.basic`.
## Main declarations
### Main definitions
* `finset`: Defines a type for the finite subsets of `α`.
Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements,
and `nodup`, a proof that `val` has no duplicates.
* `finset.has_mem`: Defines membership `a ∈ (s : finset α)`.
* `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`.
* `finset.has_coe_to_sort`: Coerce `s : finset α` to the type of all `x ∈ s`.
* `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`,
then it holds for the finset obtained by inserting a new element.
* `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element
satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate.
* `finset.card`: `card s : ℕ` returns the cardinalilty of `s : finset α`.
The API for `card`'s interaction with operations on finsets is extensive.
TODO: The noncomputable sister `fincard` is about to be added into mathlib.
### Finset constructions
* `singleton`: Denoted by `{a}`; the finset consisting of one element.
* `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements.
* `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`.
This convention is consistent with other languages and normalizes `card (range n) = n`.
Beware, `n` is not in `range n`.
* `finset.diag`: Given `s`, `diag s` is the set of pairs `(a, a)` with `a ∈ s`. See also
`finset.off_diag`: Given a finite set `s`, the off-diagonal,
`s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`.
* `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype
`{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set.
### Finsets from functions
* `finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`.
* `finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`.
* `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is
the finset consisting of those elements in `s` satisfying the predicate `p`.
### The lattice structure on subsets of finsets
There is a natural lattice structure on the subsets of a set.
In Lean, we use lattice notation to talk about things involving unions and intersections. See
`order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is
called `top` with `⊤ = univ`.
* `finset.subset`: Lots of API about lattices, otherwise behaves exactly as one would expect.
* `finset.union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`.
See `finset.bUnion` for finite unions.
* `finset.inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`.
TODO: `finset.bInter` for finite intersections.
* `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint,
`s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does
not require decidable equality on the type `α`.
### Operations on two or more finsets
* `finset.insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h`
returns the same except that it requires a hypothesis stating that `a` is not already in `s`.
This does not require decidable equality on the type `α`.
* `finset.union`: see "The lattice structure on subsets of finsets"
* `finset.inter`: see "The lattice structure on subsets of finsets"
* `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed.
* `finset.sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`.
* `finset.prod`: Given finsets of `α` and `β`, defines finsets of `α × β`.
For arbitrary dependent products, see `data.finset.pi`.
* `finset.sigma`: Given finsets of `α` and `β`, defines finsets of the dependent sum type `Σ α, β`
* `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a
`s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`.
* `finset.bInter`: TODO: Implemement finite intersections.
### Maps constructed using finsets
* `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal
to `f` on `s` and `g` on the complement.
### Predicates on finsets
* `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their
intersection is empty.
* `finset.nonempty`: A finset is nonempty if it has elements.
This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form.
### Equivalences between finsets
* The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas.
There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`.
TODO: examples
## Tags
finite sets, finset
-/
open multiset subtype nat function
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type*) :=
(val : multiset α)
(nodup : nodup val)
namespace finset
theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ rfl := rfl
@[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t :=
⟨eq_of_veq, congr_arg _⟩
@[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 :=
erase_dup_eq_self.2 s.2
instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α)
| s₁ s₂ := decidable_of_iff _ val_inj
/-! ### membership -/
instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩
theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl
@[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl
instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) :=
multiset.decidable_mem _ _
/-! ### set coercion -/
/-- Convert a finset to a set in the natural way. -/
instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩
@[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl
@[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl
@[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2
@[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} :
(⟨x, h⟩ : (s : set α)) = x :=
subtype.coe_eta _ _
instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) :
decidable (a ∈ (s : set α)) := s.decidable_mem _
/-! ### extensionality -/
theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ nodup_ext s₁.2 s₂.2
@[ext]
theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
ext_iff.2
@[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ :=
set.ext_iff.trans ext_iff.symm
lemma coe_injective {α} : injective (coe : finset α → set α) :=
λ s t, coe_inj.1
/-! ### type coercion -/
/-- Coercion from a finset to the corresponding subtype. -/
instance {α : Type*} : has_coe_to_sort (finset α) := ⟨_, λ s, {x // x ∈ s}⟩
instance pi_finset_coe.can_lift (ι : Type*) (α : Π i : ι, Type*) [ne : Π i, nonempty (α i)]
(s : finset ι) :
can_lift (Π i : s, α i) (Π i, α i) :=
{ coe := λ f i, f i,
.. pi_subtype.can_lift ι α (∈ s) }
instance pi_finset_coe.can_lift' (ι α : Type*) [ne : nonempty α] (s : finset ι) :
can_lift (s → α) (ι → α) :=
pi_finset_coe.can_lift ι (λ _, α) s
instance finset_coe.can_lift (s : finset α) : can_lift α s :=
{ coe := coe,
cond := λ a, a ∈ s,
prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ }
@[simp, norm_cast] lemma coe_sort_coe (s : finset α) :
((s : set α) : Sort*) = s := rfl
/-! ### subset -/
instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩
theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl
@[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _
theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _
theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans
theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ :=
λ h' h, subset.trans h h'
-- TODO: these should be global attributes, but this will require fixing other files
local attribute [trans] subset.trans superset.trans
theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset
theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext $ λ a, ⟨@H₁ a, @H₂ a⟩
theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl
@[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} :
(s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2
instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩
instance : partial_order (finset α) :=
{ le := (⊆),
lt := (⊂),
le_refl := subset.refl,
le_trans := @subset.trans _,
le_antisymm := @subset.antisymm _ }
theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
@[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl
@[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl
theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl
@[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ :=
show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁,
by simp only [set.ssubset_def, finset.coe_subset]
@[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff $ not_congr val_le_iff
lemma ssubset_iff_subset_ne {s t : finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t :=
@lt_iff_le_and_ne _ _ s t
theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ :=
set.ssubset_iff_of_subset h
lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) :
s₁ ⊂ s₃ :=
set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃
lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) :
s₁ ⊂ s₃ :=
set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃
lemma exists_of_ssubset {s₁ s₂ : finset α} (h : s₁ ⊂ s₂) :
∃ x ∈ s₂, x ∉ s₁ :=
set.exists_of_ssubset h
/-! ### Nonempty -/
/-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s
@[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s:set α).nonempty ↔ s.nonempty := iff.rfl
lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h
lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty :=
set.nonempty.mono hst hs
lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p :=
let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩
/-! ### empty -/
/-- The empty finset -/
protected def empty : finset α := ⟨0, nodup_zero⟩
instance : has_emptyc (finset α) := ⟨finset.empty⟩
instance inhabited_finset : inhabited (finset α) := ⟨∅⟩
@[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl
@[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id
@[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty :=
λ ⟨x, hx⟩, not_mem_empty x hx
@[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl
theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ :=
λ e, not_mem_empty a $ e ▸ h
theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ :=
exists.elim h $ λ a, ne_empty_of_mem
@[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _
theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_not_mem H)
lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s :=
⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩
@[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅
theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ :=
⟨nonempty.ne_empty, nonempty_of_ne_empty⟩
@[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ :=
by { rw nonempty_iff_ne_empty, exact not_not, }
theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty :=
classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h))
@[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl
@[simp, norm_cast] lemma coe_eq_empty {s : finset α} :
(s : set α) = ∅ ↔ s = ∅ :=
by rw [← coe_empty, coe_inj]
/-- A `finset` for an empty type is empty. -/
lemma eq_empty_of_is_empty [is_empty α] (s : finset α) : s = ∅ :=
finset.eq_empty_of_forall_not_mem is_empty_elim
/-- A `finset` for an empty type is empty. -/
lemma eq_empty_of_not_nonempty (h : ¬ nonempty α) (s : finset α) : s = ∅ :=
finset.eq_empty_of_forall_not_mem $ λ x, false.elim $ not_nonempty_iff_imp_false.1 h x
/-! ### singleton -/
/--
`{a} : finset a` is the set `{a}` containing `a` and nothing else.
This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`.
-/
instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩
@[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = a ::ₘ 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton
theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton
theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl
theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b :=
⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩
@[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩
@[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty
@[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} :=
by { ext, simp }
lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} :
s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
begin
split; intro t,
rw t,
refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩,
ext, rw finset.mem_singleton,
refine ⟨t.right _, λ r, r.symm ▸ t.left⟩
end
lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} :
s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a :=
begin
split,
{ intros h, subst h, simp, },
{ rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩,
rw ← h_uniq hne.some hne.some_spec, apply hne.some_spec, },
end
lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s :=
by simp only [eq_singleton_iff_unique_mem, exists_unique]
lemma singleton_subset_set_iff {s : set α} {a : α} :
↑({a} : finset α) ⊆ s ↔ a ∈ s :=
by rw [coe_singleton, set.singleton_subset_iff]
@[simp] lemma singleton_subset_iff {s : finset α} {a : α} :
{a} ⊆ s ↔ a ∈ s :=
singleton_subset_set_iff
@[simp] lemma subset_singleton_iff {s : finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} :=
begin
split,
{ intro hs,
apply or.imp_right _ s.eq_empty_or_nonempty,
rintro ⟨t, ht⟩,
apply subset.antisymm hs,
rwa [singleton_subset_iff, ←mem_singleton.1 (hs ht)] },
rintro (rfl | rfl),
{ exact empty_subset _ },
exact subset.refl _,
end
@[simp] lemma ssubset_singleton_iff {s : finset α} {a : α} :
s ⊂ {a} ↔ s = ∅ :=
by rw [←coe_ssubset, coe_singleton, set.ssubset_singleton_iff, coe_eq_empty]
lemma eq_empty_of_ssubset_singleton {s : finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ :=
ssubset_singleton_iff.1 hs
/-! ### cons -/
/-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as
`insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`,
and the union is guaranteed to be disjoint. -/
def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α :=
⟨a ::ₘ s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩
@[simp] theorem mem_cons {α a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s :=
by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff
@[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl
@[simp] theorem mk_cons {a : α} {s : multiset α} (h : (a ::ₘ s).nodup) :
(⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (multiset.nodup_cons.1 h).2⟩ (multiset.nodup_cons.1 h).1 :=
rfl
@[simp] theorem nonempty_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).nonempty :=
⟨a, mem_cons.2 (or.inl rfl)⟩
@[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ []
| [] hl := by simp
| (a::l) hl := by simp [← multiset.cons_coe]
/-! ### disjoint union -/
/-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`.
It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis
ensures that the sets are disjoint. -/
def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α :=
⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩
@[simp] theorem mem_disj_union {α s t h a} :
a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t :=
by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append
/-! ### insert -/
section decidable_eq
variables [decidable_eq α]
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩
theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl
@[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl
theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a ::ₘ s.1) :=
by rw [erase_dup_cons, erase_dup_eq_self]; refl
theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 :=
by rw [insert_val, ndinsert_of_not_mem h]
@[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert
theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1
theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s :=
mem_ndinsert_of_mem h
theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
(mem_insert.1 h).resolve_left
@[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s :=
ext $ λ a, by simp
@[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) :
↑(insert a s) = (insert a s : set α) :=
set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff]
lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) :=
by simp
instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩
@[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s :=
eq_of_veq $ ndinsert_of_mem h
@[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} :=
insert_eq_of_mem $ mem_singleton_self _
theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) :=
ext $ λ x, by simp only [mem_insert, or.left_comm]
theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} :=
begin
ext,
simp [or.comm]
end
@[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s :=
ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self]
@[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty :=
⟨a, mem_insert_self a s⟩
@[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ :=
(insert_nonempty a s).ne_empty
section
universe u
/-!
The universe annotation is required for the following instance, possibly this is a bug in Lean. See
leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F)
-/
instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) :
nonempty.{u + 1} ((insert i s : finset α) : set α) :=
(finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype
end
lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) :
s ≠ insert a t :=
by { contrapose! h, simp [h] }
theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib]
theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s :=
λ b, mem_insert_of_mem
theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩
lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) :=
by exact_mod_cast @set.ssubset_iff_insert α s t
lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff.mpr ⟨a, h, subset.refl _⟩
@[elab_as_eliminator]
lemma cons_induction {α : Type*} {p : finset α → Prop}
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : ∀ s, p s
| ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin
cases nodup_cons.1 nd with m nd',
rw [← (eq_of_veq _ : cons a (finset.mk s _) m = ⟨a ::ₘ s, nd⟩)],
{ exact h₂ (by exact m) (IH nd') },
{ rw [cons_val] }
end) nd
@[elab_as_eliminator]
lemma cons_induction_on {α : Type*} {p : finset α → Prop} (s : finset α)
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : p s :=
cons_induction h₁ h₂ s
@[elab_as_eliminator]
protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α]
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s :=
cons_induction h₁ $ λ a s ha, (s.cons_eq_insert a ha).symm ▸ h₂ ha
/--
To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α`,
then it holds for the `finset` obtained by inserting a new element.
-/
@[elab_as_eliminator]
protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α]
(s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
/--
To prove a proposition about `S : finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α ⊆ S`,
then it holds for the `finset` obtained by inserting a new element of `S`.
-/
@[elab_as_eliminator]
theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α]
(S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S :=
@finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs,
let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S)
/-- Inserting an element to a finite set is equivalent to the option type. -/
def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) :
{i // i ∈ insert x t} ≃ option {i // i ∈ t} :=
begin
refine
{ to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩,
inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩,
.. },
{ intro y, by_cases h : ↑y = x,
simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk],
simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] },
{ rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk],
have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 },
simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta,
subtype.coe_mk] },
end
/-! ### union -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩
theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl
@[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 :=
ndunion_eq_union s₁.2
@[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion
@[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t :=
ext $ λ a, by simp
theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ :=
mem_union.2 $ or.inl h
theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ :=
mem_union.2 $ or.inr h
theorem forall_mem_union {s₁ s₂ : finset α} {p : α → Prop} :
(∀ ab ∈ (s₁ ∪ s₂), p ab) ↔ (∀ a ∈ s₁, p a) ∧ (∀ b ∈ s₂, p b) :=
⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩,
λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩
theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ :=
by rw [mem_union, not_or_distrib]
@[simp, norm_cast]
lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union
theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ :=
val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩)
theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _
theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _
lemma union_subset_union {s₁ t₁ s₂ t₂ : finset α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) :
s₁ ∪ s₂ ⊆ t₁ ∪ t₂ :=
by { intros x hx, rw finset.mem_union at hx ⊢, tauto }
theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ :=
ext $ λ x, by simp only [mem_union, or_comm]
instance : is_commutative (finset α) (∪) := ⟨union_comm⟩
@[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
ext $ λ x, by simp only [mem_union, or_assoc]
instance : is_associative (finset α) (∪) := ⟨union_assoc⟩
@[simp] theorem union_idempotent (s : finset α) : s ∪ s = s :=
ext $ λ _, mem_union.trans $ or_self _
instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩
theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext $ λ _, by simp only [mem_union, or.left_comm]
theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)]
theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s
@[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s :=
ext $ λ x, mem_union.trans $ or_false _
@[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s :=
ext $ λ x, mem_union.trans $ false_or _
theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl
@[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) :=
by simp only [insert_eq, union_assoc]
@[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) :=
by simp only [insert_eq, union_left_comm]
theorem insert_union_distrib (a : α) (s t : finset α) :
insert a (s ∪ t) = insert a s ∪ insert a t :=
by simp only [insert_union, union_insert, insert_idem]
@[simp] lemma union_eq_left_iff_subset {s t : finset α} :
s ∪ t = s ↔ t ⊆ s :=
begin
split,
{ assume h,
have : t ⊆ s ∪ t := subset_union_right _ _,
rwa h at this },
{ assume h,
exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) }
end
@[simp] lemma left_eq_union_iff_subset {s t : finset α} :
s = s ∪ t ↔ t ⊆ s :=
by rw [← union_eq_left_iff_subset, eq_comm]
@[simp] lemma union_eq_right_iff_subset {s t : finset α} :
t ∪ s = s ↔ t ⊆ s :=
by rw [union_comm, union_eq_left_iff_subset]
@[simp] lemma right_eq_union_iff_subset {s t : finset α} :
s = t ∪ s ↔ t ⊆ s :=
by rw [← union_eq_right_iff_subset, eq_comm]
/--
To prove a relation on pairs of `finset X`, it suffices to show that it is
* symmetric,
* it holds when one of the `finset`s is empty,
* it holds for pairs of singletons,
* if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`.
-/
lemma induction_on_union (P : finset α → finset α → Prop)
(symm : ∀ {a b}, P a b → P b a)
(empty_right : ∀ {a}, P a ∅)
(singletons : ∀ {a b}, P {a} {b})
(union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) :
∀ a b, P a b :=
begin
intros a b,
refine finset.induction_on b empty_right (λ x s xs hi, symm _),
rw finset.insert_eq,
apply union_of _ (symm hi),
refine finset.induction_on a empty_right (λ a t ta hi, symm _),
rw finset.insert_eq,
exact union_of singletons (symm hi),
end
lemma exists_mem_subset_of_subset_bUnion_of_directed_on {α ι : Type*}
{f : ι → set α} {c : set ι} {a : ι} (hac : a ∈ c) (hc : directed_on (λ i j, f i ⊆ f j) c)
{s : finset α} (hs : (s : set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : set α) ⊆ f i :=
begin
classical,
revert hs,
apply s.induction_on,
{ intros,
use [a, hac],
simp },
{ intros b t hbt htc hbtc,
obtain ⟨i : ι , hic : i ∈ c, hti : (t : set α) ⊆ f i⟩ :=
htc (set.subset.trans (t.subset_insert b) hbtc),
obtain ⟨j, hjc, hbj⟩ : ∃ j ∈ c, b ∈ f j,
by simpa [set.mem_bUnion_iff] using hbtc (t.mem_insert_self b),
rcases hc j hjc i hic with ⟨k, hkc, hk, hk'⟩,
use [k, hkc],
rw [coe_insert, set.insert_subset],
exact ⟨hk hbj, trans hti hk'⟩ }
end
/-! ### inter -/
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩
-- TODO: some of these results may have simpler proofs, once there are enough results
-- to obtain the `lattice` instance.
theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl
@[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 :=
ndinter_eq_inter s₁.2
@[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) :
a ∈ s₁ := (mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) :
a ∈ s₂ := (mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left
theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right
theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ :=
by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial
@[simp, norm_cast]
lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter
@[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left]
@[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right]
theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ :=
ext $ λ _, by simp only [mem_inter, and_comm]
@[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) :=
ext $ λ _, by simp only [mem_inter, and_assoc]
theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext $ λ _, by simp only [mem_inter, and.left_comm]
theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext $ λ _, by simp only [mem_inter, and.right_comm]
@[simp] theorem inter_self (s : finset α) : s ∩ s = s :=
ext $ λ _, mem_inter.trans $ and_self _
@[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ :=
ext $ λ _, mem_inter.trans $ and_false _
@[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ :=
ext $ λ _, mem_inter.trans $ false_and _
@[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s :=
by rw [inter_comm, union_inter_cancel_right]
@[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h,
by simp only [mem_inter, mem_insert, or_and_distrib_left, this]
@[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) :=
by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H,
by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or]
@[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
by rw [inter_comm, insert_inter_of_not_mem h, inter_comm]
@[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} :=
show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter]
@[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ :=
eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h
@[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} :=
by rw [inter_comm, singleton_inter_of_mem h]
@[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ :=
by rw [inter_comm, singleton_inter_of_not_mem h]
@[mono]
lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t :=
begin
intros a a_in,
rw finset.mem_inter at a_in ⊢,
exact ⟨h a_in.1, h' a_in.2⟩
end
lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s :=
finset.inter_subset_inter h (finset.subset.refl _)
lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y :=
finset.inter_subset_inter (finset.subset.refl _) h
/-! ### lattice laws -/
instance : lattice (finset α) :=
{ sup := (∪),
sup_le := assume a b c, union_subset,
le_sup_left := subset_union_left,
le_sup_right := subset_union_right,
inf := (∩),
le_inf := assume a b c, subset_inter,
inf_le_left := inter_subset_left,
inf_le_right := inter_subset_right,
..finset.partial_order }
@[simp] theorem sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl
@[simp] theorem inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl
instance : semilattice_inf_bot (finset α) :=
{ bot := ∅, bot_le := empty_subset, ..finset.lattice }
@[simp] lemma bot_eq_empty : (⊥ : finset α) = ∅ := rfl
instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) :=
{ ..finset.semilattice_inf_bot, ..finset.lattice }
instance : distrib_lattice (finset α) :=
{ le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c,
by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt};
simp only [true_or, imp_true_iff, true_and, or_true],
..finset.lattice }
theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left
theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right
theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left
theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right
lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff
lemma union_subset_iff {s₁ s₂ s₃ : finset α} :
s₁ ∪ s₂ ⊆ s₃ ↔ s₁ ⊆ s₃ ∧ s₂ ⊆ s₃ :=
(sup_le_iff : s₁ ⊔ s₂ ≤ s₃ ↔ s₁ ≤ s₃ ∧ s₂ ≤ s₃)
lemma subset_inter_iff {s₁ s₂ s₃ : finset α} :
s₁ ⊆ s₂ ∩ s₃ ↔ s₁ ⊆ s₂ ∧ s₁ ⊆ s₃ :=
(le_inf_iff : s₁ ≤ s₂ ⊓ s₃ ↔ s₁ ≤ s₂ ∧ s₁ ≤ s₃)
theorem inter_eq_left_iff_subset (s t : finset α) :
s ∩ t = s ↔ s ⊆ t :=
(inf_eq_left : s ⊓ t = s ↔ s ≤ t)
theorem inter_eq_right_iff_subset (s t : finset α) :
t ∩ s = s ↔ s ⊆ t :=
(inf_eq_right : t ⊓ s = s ↔ s ≤ t)
/-! ### erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩
@[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl
@[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
mem_erase_iff_of_nodup s.2
theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2
@[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl
theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a :=
by simp only [mem_erase]; exact and.left
theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase
theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b :=
by simp only [mem_erase]; exact and.intro
/-- An element of `s` that is not an element of `erase s a` must be
`a`. -/
lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s)
(hsa : b ∉ s.erase a) : b = a :=
begin
rw [mem_erase, not_and] at hsa,
exact not_imp_not.mp hsa hs
end
theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s :=
ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or];
apply and_iff_right_of_imp; rintro H rfl; exact h H
theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s :=
ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and];
apply or_iff_right_of_imp; rintro rfl; exact h
theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h
theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _
@[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) :=
set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl
lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s :=
calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _
... = _ : insert_erase h
theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq $ erase_of_not_mem h
theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t :=
by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp];
exact forall_congr (λ x, forall_swap)
theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 $ subset.refl _
theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 $ subset.refl _
lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) :
s.erase x = s.erase y ↔ x = y :=
begin
refine ⟨λ h, _, congr_arg _⟩,
rw eq_of_mem_of_not_mem_erase hx,
rw ←h,
simp,
end
lemma erase_inj_on (s : finset α) : set.inj_on s.erase s :=
λ _ _ _ _, (erase_inj s ‹_›).mp
/-! ### sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩
@[simp] lemma sdiff_val (s₁ s₂ : finset α) : (s₁ \ s₂).val = s₁.val - s₂.val := rfl
@[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} :
a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2
@[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ :=
eq_empty_of_forall_not_mem $
by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h
instance : generalized_boolean_algebra (finset α) :=
{ sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union,
mem_inter], tauto },
inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc,
false_iff, inf_eq_inter, not_mem_empty], tauto },
..finset.has_sdiff,
..finset.distrib_lattice,
..finset.semilattice_inf_bot }
lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t :=
by simp only [mem_sdiff, h, not_true, not_false_iff, and_false]
theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ :=
sup_sdiff_of_le h
theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ :=
(union_comm _ _).trans (union_sdiff_of_subset h)
theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u :=
by { ext x, simp [and_assoc] }
@[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ :=
inf_sdiff_self_left
@[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ :=
sdiff_self
theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) :=
sdiff_inf
@[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ :=
sdiff_inf_self_left
@[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ :=
sdiff_inf_self_right
@[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ :=
sdiff_bot
@[mono]
theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) :
t₁ \ s₁ ⊆ t₂ \ s₂ :=
sdiff_le_sdiff ‹t₁ ≤ t₂› ‹s₂ ≤ s₁›
@[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) :=
set.ext $ λ _, mem_sdiff
@[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t :=
sup_sdiff_self_right
@[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t :=
sup_sdiff_self_left
lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) :=
sup_sdiff_symm
lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s :=
by { rw union_comm, exact sup_inf_sdiff _ _ }
@[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t :=
sdiff_idem
lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t :=
sdiff_eq_bot_iff
@[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ :=
bot_sdiff
lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) :
(insert x s) \ t = insert x (s \ t) :=
begin
rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_not_mem s h
end
lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) :
(insert x s) \ t = s \ t :=
begin
rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_mem s h
end
@[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) :
(insert x s) \ (insert x t) = s \ insert x t :=
insert_sdiff_of_mem _ (mem_insert_self _ _)
lemma sdiff_insert_of_not_mem {s : finset α} {x : α} (h : x ∉ s) (t : finset α) :
s \ (insert x t) = s \ t :=
begin
refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _),
simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢,
exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩
end
@[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s :=
show s \ t ≤ s, from sdiff_le
lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t :=
sup_sdiff
lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) :=
sdiff_sup
lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t :=
sup_sdiff_right_self
lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a :=
by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto }
lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t :=
sdiff_sdiff_right_self
lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ :=
sdiff_eq_sdiff_iff_inf_eq_inf
lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) :
s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) :=
sup_eq_sdiff_sup_sdiff_sup_inf
end decidable_eq
/-! ### attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype
`{x // x ∈ s}`. -/
def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) :
sizeof x < sizeof s := by
{ cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof],
apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx }
@[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl
@[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _
@[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl
@[simp] lemma attach_nonempty_iff (s : finset α) : s.attach.nonempty ↔ s.nonempty :=
by simp [finset.nonempty]
@[simp] lemma attach_eq_empty_iff (s : finset α) : s.attach = ∅ ↔ s = ∅ :=
by simpa [eq_empty_iff_forall_not_mem]
/-! ### piecewise -/
section piecewise
/-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its
complement. -/
def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] :
Πi, δ i :=
λi, if i ∈ s then f i else g i
variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i)
@[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
@[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
variable [∀j, decidable (j ∈ s)]
@[norm_cast] lemma piecewise_coe [∀j, decidable (j ∈ (s : set α))] :
(s : set α).piecewise f g = s.piecewise f g :=
by { ext, congr }
@[simp, priority 980]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i :=
by simp [piecewise, hi]
@[simp, priority 980]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i :=
by simp [piecewise, hi]
lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) :
s.piecewise f g = s.piecewise f' g' :=
funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i)
@[simp, priority 990]
lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)]
(h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i :=
by simp [piecewise, h]
lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = update (s.piecewise f g) j (f j) :=
begin
classical,
rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s],
congr
end
lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) :=
by by_cases hi : i ∈ s; simpa [hi]
lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)}
{f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' :=
by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg }
lemma piecewise_singleton [decidable_eq α] (i : α) :
piecewise {i} f g = update g i (f i) :=
by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty]
lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)]
[Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) :
s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g :=
s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl)
@[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) :
s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g :=
piecewise_piecewise_of_subset_left (subset.refl _) _ _ _
lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)]
[Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) :
s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ :=
s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi))
@[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) :
s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ :=
piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂
lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) :
update f i v = piecewise (singleton i) (λj, v) f :=
(piecewise_singleton _ _ _).symm
lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) :=
begin
ext j,
rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp *
end
lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise (update f i v) g :=
begin
rw update_piecewise,
refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _),
exact λ h, hj (h.symm ▸ hi)
end
lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise f (update g i v) :=
begin
rw update_piecewise,
refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl),
exact λ h, hi (h ▸ hj)
end
lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i}
(Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h :=
λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x)
lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i}
(Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g :=
λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x)
lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i}
(Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' :=
λ x, by { by_cases hx : x ∈ s; simp [hx, *] }
lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i}
(Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' :=
s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x)
lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i}
(hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) :
s.piecewise f g ∈ set.Icc f₁ g₁ :=
⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩
lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) :
s.piecewise f g ∈ set.Icc f g :=
piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h)
lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) :
s.piecewise f g ∈ set.Icc g f :=
piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h)
end piecewise
section decidable_pi_exists
variables {s : finset α}
instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∀a (h : a ∈ s), p a h) :=
multiset.decidable_dforall_multiset
/-- decidable equality for functions whose domain is bounded by finsets -/
instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈s, β a) :=
multiset.decidable_eq_pi_multiset
instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∃a (h : a ∈ s), p a h) :=
multiset.decidable_dexists_multiset
end decidable_pi_exists
/-! ### filter -/
section filter
variables (p q : α → Prop) [decidable_pred p] [decidable_pred q]
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter (s : finset α) : finset α :=
⟨_, nodup_filter p s.2⟩
@[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl
@[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _
variable {p}
@[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter
theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x :=
⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩,
λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩
variable (p)
theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) :=
ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm]
lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] :
@finset.filter α (λ _, true) h s = s :=
by ext; simp
@[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ :=
ext $ assume a, by simp only [mem_filter, and_false]; refl
variables {p q}
/-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/
@[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s :=
ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩
/-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/
lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ :=
eq_empty_of_forall_not_mem (by simpa)
lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s :=
eq_of_veq $ filter_congr H
variables (p q)
lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _
lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p :=
assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩
@[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
set.ext $ λ _, mem_filter
theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ :=
by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
variable [decidable_eq α]
theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p :=
ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right]
theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) :=
ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm]
lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] :
s.filter (λ i, i ∈ t) = s ∩ t :=
ext $ λ i, by rw [mem_filter, mem_inter]
theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) :=
by { ext, simp only [mem_inter, mem_filter, and.right_comm] }
theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) :=
by rw [inter_comm, filter_inter, inter_comm]
theorem filter_insert (a : α) (s : finset α) :
filter p (insert a s) = if p a then insert a (filter p s) else filter p s :=
by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) :
s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q :=
ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left]
theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) :
s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q :=
ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self]
theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) :
s.filter (λ a, ¬ p a) = s \ s.filter p :=
ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $
λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm
theorem sdiff_eq_filter (s₁ s₂ : finset α) :
s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter]
theorem sdiff_eq_self (s₁ s₂ : finset α) :
s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ :=
by { simp [subset.antisymm_iff],
split; intro h,
{ transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp },
{ calc s₁ \ s₂
⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)]
... ⊇ s₁ \ ∅ : by mono using [(⊇)]
... ⊇ s₁ : by simp [(⊇)] } }
theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)]
(s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s :=
by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)]
theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ :=
by simp only [filter_not, inter_sdiff_self]
lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) :
∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ :=
begin
classical,
refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩,
{ simp [filter_union_right, em] },
{ intro x, simp },
{ intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ }
end
/- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/
@[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p)
[decidable_pred p] : @filter α p h s = s.filter p :=
by congr
section classical
open_locale classical
/-- The following instance allows us to write `{x ∈ s | p x}` for `finset.filter p s`.
Since the former notation requires us to define this for all propositions `p`, and `finset.filter`
only works for decidable propositions, the notation `{x ∈ s | p x}` is only compatible with
classical logic because it uses `classical.prop_decidable`.
We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp`
unfolds the notation `{x ∈ s | p x}` to `finset.filter p s`. If `p` happens to be decidable, the
simp-lemma `finset.filter_congr_decidable` will make sure that `finset.filter` uses the right
instance for decidability.
-/
noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩
@[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl
end classical
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq'` with the equality the other way.
-/
-- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing
-- on, e.g. `x ∈ s.filter(eq b)`.
lemma filter_eq [decidable_eq β] (s : finset β) (b : β) :
s.filter (eq b) = ite (b ∈ s) {b} ∅ :=
begin
split_ifs,
{ ext,
simp only [mem_filter, mem_singleton],
exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ },
{ ext,
simp only [mem_filter, not_and, iff_false, not_mem_empty],
rintros m ⟨e⟩, exact h m, }
end
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq` with the equality the other way.
-/
lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ :=
trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b)
lemma filter_ne [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, b ≠ a) = s.erase b :=
by { ext, simp only [mem_filter, mem_erase, ne.def], tauto, }
lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, a ≠ b) = s.erase b :=
trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b)
end filter
/-! ### range -/
section range
variables {n m l : ℕ}
/-- `range n` is the set of natural numbers less than `n`. -/
def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩
@[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl
@[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range
@[simp] theorem range_zero : range 0 = ∅ := rfl
@[simp] theorem range_one : range 1 = {0} := rfl
theorem range_succ : range (succ n) = insert n (range n) :=
eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm
theorem range_add_one : range (n + 1) = insert n (range n) :=
range_succ
@[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self
@[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n
@[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset
theorem range_mono : monotone range := λ _ _, range_subset.2
lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b :=
finset.mem_range.trans nat.lt_succ_iff
lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n :=
(mem_range.1 hx).le
lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 :=
ne_of_gt $ nat.sub_pos_of_lt $ mem_range.1 hx
end range
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false :=
by simp only [not_mem_empty, false_and, exists_false]
theorem exists_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) :=
by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true :=
iff_true_intro $ λ _, false.elim
theorem forall_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) :=
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
end finset
/-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/
def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ :=
{ to_fun := λ i, i.1 - k,
inv_fun := λ j, ⟨j + k, by simp⟩,
left_inv :=
begin
assume j,
rw subtype.ext_iff_val,
apply nat.sub_add_cancel,
simpa using j.2
end,
right_inv := λ j, nat.add_sub_cancel _ _ }
@[simp] lemma coe_not_mem_range_equiv (k : ℕ) :
(not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl
@[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) :
((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl
namespace option
/-- Construct an empty or singleton finset from an `option` -/
def to_finset (o : option α) : finset α :=
match o with
| none := ∅
| some a := {a}
end
@[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl
@[simp] theorem to_finset_some {a : α} : (some a).to_finset = {a} := rfl
@[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o :=
by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl
end option
/-! ### erase_dup on list and multiset -/
namespace multiset
variable [decidable_eq α]
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩
@[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl
theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset :=
finset.val_inj.1 (erase_dup_eq_self.2 n).symm
lemma nodup.to_finset_inj {l l' : multiset α} (hl : nodup l) (hl' : nodup l')
(h : l.to_finset = l'.to_finset) : l = l' :=
by simpa [←to_finset_eq hl, ←to_finset_eq hl'] using h
@[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s :=
mem_erase_dup
@[simp] lemma to_finset_zero :
to_finset (0 : multiset α) = ∅ :=
rfl
@[simp] lemma to_finset_cons (a : α) (s : multiset α) :
to_finset (a ::ₘ s) = insert a (to_finset s) :=
finset.eq_of_veq erase_dup_cons
@[simp] lemma to_finset_add (s t : multiset α) :
to_finset (s + t) = to_finset s ∪ to_finset t :=
finset.ext $ by simp
@[simp] lemma to_finset_nsmul (s : multiset α) :
∀(n : ℕ) (hn : n ≠ 0), (n • s).to_finset = s.to_finset
| 0 h := by contradiction
| (n+1) h :=
begin
by_cases n = 0,
{ rw [h, zero_add, one_nsmul] },
{ rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] }
end
@[simp] lemma to_finset_inter (s t : multiset α) :
to_finset (s ∩ t) = to_finset s ∩ to_finset t :=
finset.ext $ by simp
@[simp] lemma to_finset_union (s t : multiset α) :
(s ∪ t).to_finset = s.to_finset ∪ t.to_finset :=
by ext; simp
theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 :=
finset.val_inj.symm.trans multiset.erase_dup_eq_zero
@[simp] lemma to_finset_subset (m1 m2 : multiset α) :
m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 :=
by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset]
end multiset
namespace finset
@[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s :=
by { ext, rw [multiset.mem_to_finset, ←mem_def] }
end finset
namespace list
variable [decidable_eq α]
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset (l : list α) : finset α := multiset.to_finset l
@[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl
theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset :=
multiset.to_finset_eq n
@[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l :=
mem_erase_dup
@[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ :=
rfl
@[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) :=
finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h]
lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ :=
begin
rintro s -,
cases s with t hl, induction t using quot.ind with l,
refine ⟨l, hl, (to_finset_eq hl).symm⟩
end
theorem to_finset_surjective : surjective (to_finset : list α → finset α) :=
by { intro s, rcases to_finset_surj_on (set.mem_univ s) with ⟨l, -, hls⟩, exact ⟨l, hls⟩ }
lemma to_finset_eq_iff_perm_erase_dup {l l' : list α} :
l.to_finset = l'.to_finset ↔ l.erase_dup ~ l'.erase_dup :=
by simp [finset.ext_iff, perm_ext (nodup_erase_dup _) (nodup_erase_dup _)]
lemma to_finset_eq_of_perm (l l' : list α) (h : l ~ l') :
l.to_finset = l'.to_finset :=
to_finset_eq_iff_perm_erase_dup.mpr h.erase_dup
lemma perm_of_nodup_nodup_to_finset_eq {l l' : list α} (hl : nodup l) (hl' : nodup l')
(h : l.to_finset = l'.to_finset) : l ~ l' :=
begin
rw ←multiset.coe_eq_coe,
exact multiset.nodup.to_finset_inj hl hl' h
end
@[simp] lemma to_finset_append {l l' : list α} :
to_finset (l ++ l') = l.to_finset ∪ l'.to_finset :=
begin
induction l with hd tl hl,
{ simp },
{ simp [hl] }
end
@[simp] lemma to_finset_reverse {l : list α} :
to_finset l.reverse = l.to_finset :=
to_finset_eq_of_perm _ _ (reverse_perm l)
end list
namespace finset
lemma exists_list_nodup_eq [decidable_eq α] (s : finset α) :
∃ (l : list α), l.nodup ∧ l.to_finset = s :=
begin
obtain ⟨⟨l⟩, hs⟩ := s,
exact ⟨l, hs, (list.to_finset_eq _).symm⟩,
end
/-! ### map -/
section map
open function
/-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image
finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/
def map (f : α ↪ β) (s : finset α) : finset β :=
⟨s.1.map f, nodup_map f.2 s.2⟩
@[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl
@[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl
variables {f : α ↪ β} {s : finset α}
@[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b :=
mem_map.trans $ by simp only [exists_prop]; refl
@[simp] theorem mem_map_equiv {f : α ≃ β} {b : β} :
b ∈ s.map f.to_embedding ↔ f.symm b ∈ s :=
by { rw mem_map, exact ⟨by { rintro ⟨a, H, rfl⟩, simpa }, λ h, ⟨_, h, by simp⟩⟩ }
theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s :=
mem_map_of_injective f.2
theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f :=
(mem_map' _).2
lemma apply_coe_mem_map (f : α ↪ β) (s : finset α) (x : s) : f x ∈ s.map f :=
mem_map_of_mem f x.prop
@[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (s.map f : set β) = f '' s :=
set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm
theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (s.map f : set β) ⊆ set.range f :=
calc ↑(s.map f) = f '' s : coe_map f s
... ⊆ set.range f : set.image_subset_range f ↑s
theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} :
s.to_finset.map f = (s.map f).to_finset :=
ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset]
@[simp] theorem map_refl : s.map (embedding.refl _) = s :=
ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right
@[simp] theorem map_cast_heq {α β} (h : α = β) (s : finset α) :
s.map (equiv.cast h).to_embedding == s :=
by { subst h, simp }
theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq $ by simp only [map_val, multiset.map_map]; refl
theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ :=
⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs,
λ h, by simp [subset_def, map_subset_map h]⟩
theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ :=
by simp only [subset.antisymm_iff, map_subset_map]
/-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image
under `f`. -/
def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩
@[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl
theorem map_filter {p : β → Prop} [decidable_pred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
eq_of_veq (map_filter _ _ _)
theorem map_union [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
ext $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem map_inter [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
ext $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact
⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩,
by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩
@[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} :=
ext $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm
@[simp] theorem map_insert [decidable_eq α] [decidable_eq β]
(f : α ↪ β) (a : α) (s : finset α) :
(insert a s).map f = insert (f a) (s.map f) :=
by simp only [insert_eq, map_union, map_singleton]
@[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s :=
eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _
lemma nonempty.map (h : s.nonempty) (f : α ↪ β) : (s.map f).nonempty :=
let ⟨a, ha⟩ := h in ⟨f a, (mem_map' f).mpr ha⟩
end map
lemma range_add_one' (n : ℕ) :
range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) :=
by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n]
/-! ### image -/
section image
variables [decidable_eq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset
@[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl
@[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl
variables {f : α → β} {s : finset α}
@[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b :=
by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop]
theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f :=
mem_image.2 ⟨_, h, rfl⟩
lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) :
t.filter (λ y, y ∈ s.image f) = s.image f :=
by { ext, rw [mem_filter, mem_image],
simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib],
rintros x xel rfl, exact h _ xel }
lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) :
(s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f :=
by simp [finset.nonempty]
@[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s :=
set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm
lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty :=
let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩
@[simp]
lemma nonempty.image_iff (f : α → β) : (s.image f).nonempty ↔ s.nonempty :=
⟨λ ⟨y, hy⟩, let ⟨x, hx, _⟩ := mem_image.mp hy in ⟨x, hx⟩, λ h, h.image f⟩
theorem image_to_finset [decidable_eq α] {s : multiset α} :
s.to_finset.image f = (s.map f).to_finset :=
ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map]
theorem image_val_of_inj_on (H : set.inj_on f s) : (image f s).1 = s.1.map f :=
multiset.erase_dup_eq_self.2 (nodup_map_on H s.2)
@[simp]
theorem image_id [decidable_eq α] : s.image id = s :=
ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right]
theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map]
theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f :=
by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset',
multiset.map_subset_map h]
theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} :
s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t :=
calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast
... ↔ _ : set.image_subset_iff
theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image
theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f :=
calc ↑(s.image f) = f '' ↑s : coe_image
... ⊆ set.range f : set.image_subset_range f ↑s
theorem image_filter {p : β → Prop} [decidable_pred p] :
(s.image f).filter p = (s.filter (p ∘ f)).image f :=
ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩,
by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) :
(s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right,
exists_or_distrib]
theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) :
(s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b,
⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩,
λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩.
@[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} :=
ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm
@[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) :
(insert a s).image f = insert (f a) (s.image f) :=
by simp only [insert_eq, image_singleton, image_union]
@[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma mem_range_iff_mem_finset_range_of_mod_eq' [decidable_eq α] {f : ℕ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀i, f (i % n) = f i) :
a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) :=
begin
split,
{ rintros ⟨i, hi⟩,
simp only [mem_image, exists_prop, mem_range],
exact ⟨i % n, nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ },
{ rintro h,
simp only [mem_image, exists_prop, set.mem_range, mem_range] at *,
rcases h with ⟨i, hi, ha⟩,
use ⟨i, ha⟩ },
end
lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀i, f (i % n) = f i) :
a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) :=
suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h],
have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn,
iff.intro
(assume ⟨i, hi⟩,
have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'),
⟨int.to_nat (i % n),
by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩)
(assume ⟨i, hi, ha⟩,
⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩)
lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s :=
eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self]
@[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} :
attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s})
((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) :=
ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx)
(λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h)
(λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩),
λ _, finset.mem_attach _ _⟩
theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f :=
eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm
lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b :=
ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right,
h.bex, true_and, mem_singleton, eq_comm]
/--
Because `finset.image` requires a `decidable_eq` instances for the target type,
we can only construct a `functor finset` when working classically.
-/
instance [Π P, decidable P] : functor finset :=
{ map := λ α β f s, s.image f, }
instance [Π P, decidable P] : is_lawful_functor finset :=
{ id_map := λ α x, image_id,
comp_map := λ α β γ f g s, image_image.symm, }
/-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose
elements belong to `s`. -/
protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) :=
(s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩,
λ x y H, subtype.eq $ subtype.mk.inj H⟩
@[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} :
∀{a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s
| ⟨a, ha⟩ := by simp [finset.subtype, ha]
lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} :
s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s :=
by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl
/-- `s.subtype p` converts back to `s.filter p` with
`embedding.subtype`. -/
@[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] :
(s.subtype p).map (embedding.subtype _) = s.filter p :=
begin
ext x,
rw mem_map,
change (∃ a : {x // p x}, ∃ H, (a : α) = x) ↔ _,
split,
{ rintros ⟨y, hy, hyval⟩,
rw [mem_subtype, hyval] at hy,
rw mem_filter,
use hy,
rw ← hyval,
use y.property },
{ intro hx,
rw mem_filter at hx,
use ⟨⟨x, hx.2⟩, mem_subtype.2 hx.1, rfl⟩ }
end
/-- If all elements of a `finset` satisfy the predicate `p`,
`s.subtype p` converts back to `s` with `embedding.subtype`. -/
lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) :
(s.subtype p).map (embedding.subtype _) = s :=
by rw [subtype_map, filter_true_of_mem h]
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, all elements of the result have the property of
the subtype. -/
lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α}
(h : a ∈ s.map (embedding.subtype _)) : p a :=
begin
rcases mem_map.1 h with ⟨x, hx, rfl⟩,
exact x.2
end
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result does not contain any value that does
not satisfy the property of the subtype. -/
lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x})
{a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) :=
mt s.property_of_mem_map_subtype h
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result is a subset of the set giving the
subtype. -/
lemma map_subtype_subset {t : set α} (s : finset t) :
↑(s.map (embedding.subtype _)) ⊆ t :=
begin
intros a ha,
rw mem_coe at ha,
convert property_of_mem_map_subtype s ha
end
lemma subset_image_iff {f : α → β}
{s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s :=
begin
classical,
split, swap,
{ rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs },
intro h, induction s using finset.induction with a s has ih h,
{ refine ⟨∅, set.empty_subset _, _⟩,
convert finset.image_empty _ },
rw [finset.coe_insert, set.insert_subset] at h,
rcases ih h.2 with ⟨s', hst, hsi⟩,
rcases h.1 with ⟨x, hxt, rfl⟩,
refine ⟨insert x s', _, _⟩,
{ rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ },
rw [finset.image_insert, hsi],
congr
end
end image
end finset
theorem multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) :
(m.map f).to_finset = m.to_finset.image f :=
finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm
namespace finset
/-! ### card -/
section card
/-- `card s` is the cardinality (number of elements) of `s`. -/
def card (s : finset α) : nat := s.1.card
theorem card_def (s : finset α) : s.card = s.1.card := rfl
@[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl
@[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl
theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t :=
multiset.card_le_of_le ∘ val_le_iff.mpr
@[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ :=
card_eq_zero.trans val_eq_zero
theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty :=
pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm
theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 :=
(not_congr card_eq_zero).2 (ne_empty_of_mem h)
theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = {a} :=
by cases s; simp only [multiset.card_eq_one, finset.card, ← val_inj, singleton_val]
theorem card_le_one {s : finset α} : s.card ≤ 1 ↔ ∀ (a ∈ s) (b ∈ s), a = b :=
begin
rcases s.eq_empty_or_nonempty with rfl|⟨x, hx⟩, { simp },
refine (nat.succ_le_of_lt (card_pos.2 ⟨x, hx⟩)).le_iff_eq.trans (card_eq_one.trans ⟨_, _⟩),
{ rintro ⟨y, rfl⟩, simp },
{ exact λ h, ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, λ y hy, h _ hy _ hx⟩⟩ }
end
theorem card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {a b}, a ∈ s → b ∈ s → a = b :=
by { rw card_le_one, tauto }
lemma card_le_one_iff_subset_singleton [nonempty α] {s : finset α} :
s.card ≤ 1 ↔ ∃ (x : α), s ⊆ {x} :=
begin
split,
{ assume H,
by_cases h : ∃ x, x ∈ s,
{ rcases h with ⟨x, hx⟩,
refine ⟨x, λ y hy, _⟩,
rw [card_le_one.1 H y hy x hx, mem_singleton] },
{ push_neg at h,
inhabit α,
exact ⟨default α, λ y hy, (h y hy).elim⟩ } },
{ rintros ⟨x, hx⟩,
rw ← card_singleton x,
exact card_le_of_subset hx }
end
/-- A `finset` of a subsingleton type has cardinality at most one. -/
lemma card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 :=
finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _
theorem one_lt_card {s : finset α} : 1 < s.card ↔ ∃ (a ∈ s) (b ∈ s), a ≠ b :=
by { rw ← not_iff_not, push_neg, exact card_le_one }
lemma one_lt_card_iff {s : finset α} :
1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y :=
by { rw one_lt_card, simp only [exists_prop, exists_and_distrib_left] }
@[simp] theorem card_insert_of_not_mem [decidable_eq α]
{a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 :=
by simpa only [card_cons, card, insert_val] using
congr_arg multiset.card (ndinsert_of_not_mem h)
theorem card_insert_of_mem [decidable_eq α] {a : α} {s : finset α}
(h : a ∈ s) : card (insert a s) = card s := by rw insert_eq_of_mem h
theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 :=
by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right},
rw [card_insert_of_not_mem h]]
@[simp] theorem card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _
lemma card_singleton_inter [decidable_eq α] {x : α} {s : finset α} : ({x} ∩ s).card ≤ 1 :=
begin
cases (finset.decidable_mem x s),
{ simp [finset.singleton_inter_of_not_mem h] },
{ simp [finset.singleton_inter_of_mem h] },
end
theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} :
a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem
theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} :
a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem
theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} :
card (erase s a) ≤ card s := card_erase_le
theorem pred_card_le_card_erase [decidable_eq α] {a : α} {s : finset α} :
card s - 1 ≤ card (erase s a) :=
begin
by_cases h : a ∈ s,
{ rw [card_erase_of_mem h], refl },
{ rw [erase_eq_of_not_mem h], apply nat.sub_le }
end
@[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n
@[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach
end card
end finset
theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card :=
card_le_of_le (erase_dup_le _)
lemma list.card_to_finset [decidable_eq α] (l : list α) :
finset.card l.to_finset = l.erase_dup.length := rfl
theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length :=
multiset.to_finset_card_le ⟦l⟧
namespace finset
section card
theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s :=
by simpa only [card_map] using (s.1.map f).to_finset_card_le
theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α}
(H : set.inj_on f s) : card (image f s) = card s :=
by simp only [card, image_val_of_inj_on H, card_map]
theorem inj_on_of_card_image_eq [decidable_eq β] {f : α → β} {s : finset α}
(H : card (image f s) = card s) :
set.inj_on f s :=
begin
change (s.1.map f).erase_dup.card = s.1.card at H,
have : (s.1.map f).erase_dup = s.1.map f,
{ apply multiset.eq_of_le_of_card_le,
{ apply multiset.erase_dup_le },
rw H,
simp only [multiset.card_map] },
rw multiset.erase_dup_eq_self at this,
apply inj_on_of_nodup_map this,
end
theorem card_image_eq_iff_inj_on [decidable_eq β] {f : α → β} {s : finset α} :
(s.image f).card = s.card ↔ set.inj_on f s :=
⟨inj_on_of_card_image_eq, card_image_of_inj_on⟩
theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α)
(H : injective f) : card (image f s) = card s :=
card_image_of_inj_on $ λ x _ y _ h, H h
lemma fiber_card_ne_zero_iff_mem_image (s : finset α) (f : α → β) [decidable_eq β] (y : β) :
(s.filter (λ x, f x = y)).card ≠ 0 ↔ y ∈ s.image f :=
by { rw [←pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] }
@[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card :=
multiset.card_map _ _
@[simp] lemma card_subtype (p : α → Prop) [decidable_pred p] (s : finset α) :
(s.subtype p).card = (s.filter p).card :=
by simp [finset.subtype]
lemma card_eq_of_bijective {s : finset α} {n : ℕ}
(f : ∀i, i < n → α)
(hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s)
(f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) :
card s = n :=
begin
classical,
have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a,
from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩,
assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩,
have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)),
by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and],
calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) :
by rw [this]
... = card ((range n).attach) :
card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq,
subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq
... = card (range n) : card_attach
... = n : card_range n
end
lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} :
s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) :=
iff.intro
(assume eq,
have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _,
let ⟨a, has⟩ := card_pos.mp this in
⟨a, s.erase a, s.not_mem_erase a, insert_erase has,
by simp only [eq, card_erase_of_mem has, pred_succ]⟩)
(assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat)
theorem card_filter_le (s : finset α) (p : α → Prop) [decidable_pred p] :
card (s.filter p) ≤ card s :=
card_le_of_subset $ filter_subset _ _
theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t :=
eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂
lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card :=
card_lt_of_lt (val_lt_iff.2 h)
lemma card_le_card_of_inj_on {s : finset α} {t : finset β}
(f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) :
card s ≤ card t :=
begin
classical,
calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj]
... ≤ card t : card_le_of_subset $ image_subset_iff.2 hf
end
/--
If there are more pigeons than pigeonholes, then there are two pigeons
in the same pigeonhole.
-/
lemma exists_ne_map_eq_of_card_lt_of_maps_to {s : finset α} {t : finset β} (hc : t.card < s.card)
{f : α → β} (hf : ∀ a ∈ s, f a ∈ t) :
∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y :=
begin
classical, by_contra hz, push_neg at hz,
refine hc.not_le (card_le_card_of_inj_on f hf _),
intros x hx y hy, contrapose, exact hz x hx y hy,
end
lemma le_card_of_inj_on_range {n} {s : finset α}
(f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀ (i<n) (j<n), f i = f j → i = j) : n ≤ card s :=
calc n = card (range n) : (card_range n).symm
... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simpa only [mem_range])
/-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to
define an object on `s`. Then one can inductively define an object on all finsets, starting from
the empty set and iterating. This can be used either to define data, or to prove properties. -/
def strong_induction {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) :
∀ (s : finset α), p s
| s := H s (λ t h, have card t < card s, from card_lt_card h, strong_induction t)
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
lemma strong_induction_eq {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) (s : finset α) :
strong_induction H s = H s (λ t h, strong_induction H t) :=
by rw strong_induction
/-- Analogue of `strong_induction` with order of arguments swapped. -/
@[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} :
∀ (s : finset α), (∀s, (∀ t ⊂ s, p t) → p s) → p s :=
λ s H, strong_induction H s
lemma strong_induction_on_eq {p : finset α → Sort*} (s : finset α) (H : ∀ s, (∀ t ⊂ s, p t) → p s) :
s.strong_induction_on H = H s (λ t h, t.strong_induction_on H) :=
by { dunfold strong_induction_on, rw strong_induction }
@[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop}
(s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀ t ⊆ s, p t) → p (insert a s)) : p s :=
finset.strong_induction_on s $ λ s,
finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $
λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _)
/-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than
`n`, one knows how to define `p s`. Then one can inductively define `p s` for all finsets `s` of
cardinality less than `n`, starting from finsets of card `n` and iterating. This
can be used either to define data, or to prove properties. -/
def strong_downward_induction {p : finset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α},
t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) :
∀ (s : finset α), s.card ≤ n → p s
| s := H s (λ t ht h, have n - card t < n - card s,
from (nat.sub_lt_sub_left_iff ht).2 (finset.card_lt_card h),
strong_downward_induction t ht)
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ (t : finset α), n - t.card)⟩]}
lemma strong_downward_induction_eq {p : finset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α},
t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : finset α) :
strong_downward_induction H s = H s (λ t ht hst, strong_downward_induction H t ht) :=
by rw strong_downward_induction
/-- Analogue of `strong_downward_induction` with order of arguments swapped. -/
@[elab_as_eliminator] def strong_downward_induction_on {p : finset α → Sort*} {n : ℕ} :
∀ (s : finset α), (∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁)
→ s.card ≤ n → p s :=
λ s H, strong_downward_induction H s
lemma strong_downward_induction_on_eq {p : finset α → Sort*} (s : finset α) {n : ℕ} (H : ∀ t₁,
(∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) :
s.strong_downward_induction_on H = H s (λ t ht h, t.strong_downward_induction_on H ht) :=
by { dunfold strong_downward_induction_on, rw strong_downward_induction }
lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β)
(h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b)
(h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card :=
by haveI := classical.prop_decidable; exact
calc s.card = s.attach.card : card_attach.symm
... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card :
eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h)))
... = t.card : congr_arg card (finset.ext $ λ b,
⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _,
λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩)
lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) :
(s ∪ t).card + (s ∩ t).card = s.card + t.card :=
finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc
lemma card_union_le [decidable_eq α] (s t : finset α) :
(s ∪ t).card ≤ s.card + t.card :=
card_union_add_card_inter s t ▸ le_add_right _ _
lemma card_union_eq [decidable_eq α] {s t : finset α} (h : disjoint s t) :
(s ∪ t).card = s.card + t.card :=
begin
rw [← card_union_add_card_inter],
convert (add_zero _).symm, rw [card_eq_zero], rwa [disjoint_iff] at h
end
lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂)
(hst : card t ≤ card s) :
(∀ b ∈ t, ∃ a ha, b = f a ha) :=
by haveI := classical.dec_eq β; exact
λ b hb,
have h : card (image (λ (a : {a // a ∈ s}), f a a.prop) (attach s)) = card s,
from @card_attach _ s ▸ card_image_of_injective _
(λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h),
have h₁ : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t :=
eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in
ha₂ ▸ hf _ _) (by simp [hst, h]),
begin
rw ← h₁ at hb,
rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩,
exact ⟨a, a.2, ha₂.symm⟩,
end
open function
lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha)
(hst : card s ≤ card t)
⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s)
(ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ :=
by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact
let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in
let g : {x // x ∈ t} → {x // x ∈ s} :=
@surj_inv _ _ f'
(λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in
have hg : injective g, from injective_surj_inv _,
have hsg : surjective g, from λ x,
let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x)
(λ x _, show (g x) ∈ s.attach, from mem_attach _ _)
(λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in
⟨y, hy.snd.symm⟩,
have hif : injective f',
from (left_inverse_of_surjective_of_right_inverse hsg
(right_inverse_surj_inv _)).injective,
subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂))
end card
section bUnion
/-!
### bUnion
This section is about the bounded union of an indexed family `t : α → finset β` of finite sets
over a finite set `s : finset α`.
-/
variables [decidable_eq β] {s : finset α} {t : α → finset β}
/-- `bUnion s t` is the union of `t x` over `x ∈ s`.
(This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/
protected def bUnion (s : finset α) (t : α → finset β) : finset β :=
(s.1.bind (λ a, (t a).1)).to_finset
@[simp] theorem bUnion_val (s : finset α) (t : α → finset β) :
(s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl
@[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl
@[simp] theorem mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃a∈s, b ∈ t a :=
by simp only [mem_def, bUnion_val, mem_erase_dup, mem_bind, exists_prop]
@[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t :=
ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert,
or_and_distrib_right, exists_or_distrib, exists_eq_left]
-- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib]
@[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a :=
begin
classical,
rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty]
end
theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) :
s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) :=
begin
ext x,
simp only [mem_bUnion, mem_inter],
tauto
end
theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) :
t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) :=
by rw [inter_comm, bUnion_inter]; simp [inter_comm]
theorem image_bUnion [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} :
(s.image f).bUnion t = s.bUnion (λa, t (f a)) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [image_insert, bUnion_insert, ih])
theorem bUnion_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} :
(s.bUnion t).image f = s.bUnion (λa, (t a).image f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [bUnion_insert, image_union, ih])
theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) :
(s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) :=
ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop]
lemma bUnion_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion t₂ :=
have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a),
from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩,
by simpa only [subset_iff, mem_bUnion, exists_imp_distrib, and_imp, exists_prop]
lemma bUnion_subset_bUnion_of_subset_left {α : Type*} {s₁ s₂ : finset α}
(t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bUnion t ⊆ s₂.bUnion t :=
begin
intro x,
simp only [and_imp, mem_bUnion, exists_prop],
exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩)
end
lemma subset_bUnion_of_mem {s : finset α}
(u : α → finset β) {x : α} (xs : x ∈ s) :
u x ⊆ s.bUnion u :=
begin
apply subset.trans _ (bUnion_subset_bUnion_of_subset_left u (singleton_subset_iff.2 xs)),
exact subset_of_eq singleton_bUnion.symm,
end
lemma bUnion_singleton {f : α → β} : s.bUnion (λa, {f a}) = s.image f :=
ext $ λ x, by simp only [mem_bUnion, mem_image, mem_singleton, eq_comm]
@[simp] lemma bUnion_singleton_eq_self [decidable_eq α] :
s.bUnion (singleton : α → finset α) = s :=
by { rw bUnion_singleton, exact image_id }
lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β}
(h : ∀ x ∈ s, f x ∈ t) :
t.bUnion (λa, s.filter $ (λc, f c = a)) = s :=
ext $ λ b, by simpa using h b
lemma image_bUnion_filter_eq [decidable_eq α] (s : finset β) (g : β → α) :
(s.image g).bUnion (λa, s.filter $ (λc, g c = a)) = s :=
bUnion_filter_eq_of_maps_to (λ x, mem_image_of_mem g)
lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) :
(s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) :=
by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] }
end bUnion
/-! ### prod -/
section prod
variables {s : finset α} {t : finset β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩
@[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
theorem subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} :
s ⊆ (s.image prod.fst).product (s.image prod.snd) :=
λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩
theorem product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = s.bUnion (λa, t.image $ λb, (a, b)) :=
ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
@[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t :=
multiset.card_product _ _
theorem filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] :
(s.product t).filter (λ (x : α × β), p x.1 ∧ q x.2) = (s.filter p).product (t.filter q) :=
by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], finish, }
lemma filter_product_card (s : finset α) (t : finset β)
(p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] :
((s.product t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card =
(s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card :=
begin
classical,
rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq],
{ apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product],
split; intros; finish, },
{ rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter, finish, },
end
lemma empty_product (t : finset β) :
(∅ : finset α).product t = ∅ :=
rfl
lemma product_empty (s : finset α) :
s.product (∅ : finset β) = ∅ :=
eq_empty_of_forall_not_mem (λ x h, (finset.mem_product.1 h).2)
end prod
/-! ### sigma -/
section sigma
variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)}
/-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/
protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) :=
⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩
@[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma
theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)}
(H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ :=
λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩
theorem sigma_eq_bUnion [decidable_eq (Σ a, σ a)] (s : finset α)
(t : Πa, finset (σ a)) :
s.sigma t = s.bUnion (λa, (t a).map $ embedding.sigma_mk a) :=
by { ext ⟨x, y⟩, simp [and.left_comm] }
end sigma
/-! ### disjoint -/
section disjoint
variable [decidable_eq α]
theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and,
and_imp]; refl
theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 :=
disjoint_left
theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) :=
decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff
theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁))
theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁))
@[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left
@[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right
@[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s :=
by simp only [disjoint_left, mem_singleton, forall_eq]
@[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s :=
disjoint.comm.trans singleton_disjoint
@[simp] theorem disjoint_insert_left {a : α} {s t : finset α} :
disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t :=
by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] theorem disjoint_insert_right {a : α} {s t : finset α} :
disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm]
@[simp] theorem disjoint_union_left {s t u : finset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right {s t u : finset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib]
lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s :=
disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2
lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) :=
sdiff_disjoint.symm
lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) :=
disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint
lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t :=
by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty]
lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s :=
sdiff_eq_self_iff_disjoint.2 h
lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ :=
disjoint_self
lemma disjoint_bUnion_left {ι : Type*}
(s : finset ι) (f : ι → finset α) (t : finset α) :
disjoint (s.bUnion f) t ↔ (∀i∈s, disjoint (f i) t) :=
begin
classical,
refine s.induction _ _,
{ simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] },
{ assume i s his ih,
simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] }
end
lemma disjoint_bUnion_right {ι : Type*}
(s : finset α) (t : finset ι) (f : ι → finset α) :
disjoint s (t.bUnion f) ↔ (∀i∈t, disjoint s (f i)) :=
by simpa only [disjoint.comm] using disjoint_bUnion_left t f s
@[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) :
card (s ∪ t) = card s + card t :=
by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero]
theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s :=
suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this,
by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel]
lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] :
disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) :=
by split; simp [disjoint_left] {contextual := tt}
lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p]
[decidable_pred q] :
(disjoint s t) → disjoint (s.filter p) (t.filter q) :=
disjoint.mono (filter_subset _ _) (filter_subset _ _)
lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] :
disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) :=
by { rw [finset.disjoint_left, set.disjoint_left], refl }
lemma filter_card_add_filter_neg_card_eq_card {α : Type*} {s : finset α} (p : α → Prop)
[decidable_pred p] :
(s.filter p).card + (s.filter (not ∘ p)).card = s.card :=
by { classical, simp [← card_union_eq, filter_union_filter_neg_eq, disjoint_filter], }
end disjoint
section self_prod
variables (s : finset α) [decidable_eq α]
/-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for
`a ∈ s`. -/
def diag := (s.product s).filter (λ (a : α × α), a.fst = a.snd)
/-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b`
for `a, b ∈ s`. -/
def off_diag := (s.product s).filter (λ (a : α × α), a.fst ≠ a.snd)
@[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 :=
by { simp only [diag, mem_filter, mem_product], split; intros; finish, }
@[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 :=
by { simp only [off_diag, mem_filter, mem_product], split; intros; finish, }
@[simp] lemma diag_card : (diag s).card = s.card :=
begin
suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, finish, },
ext ⟨a₁, a₂⟩, rw mem_diag, split; intros; finish,
end
@[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card :=
begin
suffices : (diag s).card + (off_diag s).card = s.card * s.card,
{ nth_rewrite 2 ← s.diag_card, finish, },
rw ← card_product,
apply filter_card_add_filter_neg_card_eq_card,
end
end self_prod
/--
Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B
inside it.
-/
lemma exists_intermediate_set {A B : finset α} (i : ℕ)
(h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) :
∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B :=
begin
classical,
rcases nat.le.dest h₁ with ⟨k, _⟩,
clear h₁,
induction k with k ih generalizing A,
{ exact ⟨A, h₂, subset.refl _, h.symm⟩ },
{ have : (A \ B).nonempty,
{ rw [← card_pos, card_sdiff h₂, ← h, nat.add_right_comm,
nat.add_sub_cancel, nat.add_succ],
apply nat.succ_pos },
rcases this with ⟨a, ha⟩,
have z : i + card B + k = card (erase A a),
{ rw [card_erase_of_mem, ← h, nat.add_succ, nat.pred_succ],
rw mem_sdiff at ha,
exact ha.1 },
rcases ih _ z with ⟨B', hB', B'subA', cards⟩,
{ exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ },
{ rintros t th,
apply mem_erase_of_ne_of_mem _ (h₂ th),
rintro rfl,
exact not_mem_sdiff_of_mem_right th ha } }
end
/-- We can shrink A to any smaller size. -/
lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) :
∃ (B : finset α), B ⊆ A ∧ card B = i :=
let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩
/-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/
def fin_range (k : ℕ) : finset (fin k) :=
⟨list.fin_range k, list.nodup_fin_range k⟩
@[simp]
lemma fin_range_card {k : ℕ} : (fin_range k).card = k :=
by simp [fin_range]
@[simp]
lemma mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k :=
list.mem_fin_range m
@[simp] lemma coe_fin_range (k : ℕ) : (fin_range k : set (fin k)) = set.univ :=
set.eq_univ_of_forall mem_fin_range
/-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n`
is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/
def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) :=
⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.veq_of_eq) s.2⟩
@[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} :
a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s :=
⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁,
λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩
@[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) :
(s.attach_fin h).card = s.card := multiset.card_pmap _ _ _
/-! ### choose -/
section choose
variables (p : α → Prop) [decidable_pred p] (l : finset α)
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } :=
multiset.choose_x p l.val hp
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the ambient type. -/
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) :=
have H : subrelation (@has_lt.lt (finset α) _)
(inv_image (<) card),
from λ x y hxy, card_lt_card hxy,
subrelation.wf H $ inv_image.wf _ $ nat.lt_wf
end finset
namespace equiv
/-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/
protected def finset_congr (e : α ≃ β) : finset α ≃ finset β :=
{ to_fun := λ s, s.map e.to_embedding,
inv_fun := λ s, s.map e.symm.to_embedding,
left_inv := λ s, by simp [finset.map_map],
right_inv := λ s, by simp [finset.map_map] }
@[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) :
e.finset_congr s = s.map e.to_embedding :=
rfl
@[simp] lemma finset_congr_refl :
(equiv.refl α).finset_congr = equiv.refl _ :=
by { ext, simp }
@[simp] lemma finset_congr_symm (e : α ≃ β) :
e.finset_congr.symm = e.symm.finset_congr :=
rfl
@[simp] lemma finset_congr_trans (e : α ≃ β) (e' : β ≃ γ) :
e.finset_congr.trans (e'.finset_congr) = (e.trans e').finset_congr :=
by { ext, simp [-finset.mem_map, -equiv.trans_to_embedding] }
end equiv
namespace multiset
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : multiset α} (h : l.nodup) : l.to_finset.card = l.card :=
congr_arg card $ multiset.erase_dup_eq_self.mpr h
lemma disjoint_to_finset {m1 m2 : multiset α} :
_root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 :=
begin
rw finset.disjoint_iff_ne,
split,
{ intro h,
intros a ha1 ha2,
rw ← multiset.mem_to_finset at ha1 ha2,
exact h _ ha1 _ ha2 rfl },
{ rintros h a ha b hb rfl,
rw multiset.mem_to_finset at ha hb,
exact h ha hb }
end
end multiset
namespace list
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length :=
multiset.to_finset_card_of_nodup h
lemma disjoint_to_finset_iff_disjoint {l l' : list α} :
_root_.disjoint l.to_finset l'.to_finset ↔ l.disjoint l' :=
multiset.disjoint_to_finset
end list
|
4d33461baf221116dbe798cb7a5afc94afef196d | 1fbca480c1574e809ae95a3eda58188ff42a5e41 | /src/util/data/sum.lean | f1072f55a0faac2954013590ae6d6608ef9442cb | [] | no_license | unitb/lean-lib | 560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e | 439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9 | refs/heads/master | 1,610,706,025,400 | 1,570,144,245,000 | 1,570,144,245,000 | 99,579,229 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 600 | lean |
universe variables u v u' v'
namespace sum
variables {α : Type u} {β : Type v}
{α' : Type u'} {β' : Type v'}
def is_left : α ⊕ β → bool
| (sum.inl _) := tt
| (sum.inr _) := ff
def is_right : α ⊕ β → bool
| (sum.inl _) := ff
| (sum.inr _) := tt
instance {α : Type u} : functor (sum α) :=
{ map := λ β γ f x, sum.rec_on x sum.inl (sum.inr ∘ f) }
def bimap (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β'
| (inl x) := inl $ f x
| (inr x) := inr $ g x
def swap : α ⊕ β → β ⊕ α
| (inl x) := inr x
| (inr x) := inl x
end sum
|
3246c73995356724f32898973c18a6ce740faabc | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/analysis/convex/extreme.lean | 5142870d5581f492c456a6d0555501b5d6b8e479 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,612 | 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 analysis.convex.hull
/-!
# Extreme sets
This file defines extreme sets and extreme points for sets in a module.
An extreme set of `A` is a subset of `A` that is as far as it can get in any outward direction: If
point `x` is in it and point `y ∈ A`, then the line passing through `x` and `y` leaves `A` at `x`.
This is an analytic notion of "being on the side of". It is weaker than being exposed (see
`is_exposed.is_extreme`).
## Main declarations
* `is_extreme 𝕜 A B`: States that `B` is an extreme set of `A` (in the literature, `A` is often
implicit).
* `set.extreme_points 𝕜 A`: Set of extreme points of `A` (corresponding to extreme singletons).
* `convex.mem_extreme_points_iff_convex_diff`: A useful equivalent condition to being an extreme
point: `x` is an extreme point iff `A \ {x}` is convex.
## Implementation notes
The exact definition of extremeness has been carefully chosen so as to make as many lemmas
unconditional (in particular, the Krein-Milman theorem doesn't need the set to be convex!).
In practice, `A` is often assumed to be a convex set.
## References
See chapter 8 of [Barry Simon, *Convexity*][simon2011]
## TODO
Define intrinsic frontier and prove lemmas related to extreme sets and points.
More not-yet-PRed stuff is available on the branch `sperner_again`.
-/
open_locale classical affine
open set
variables (𝕜 : Type*) {E : Type*}
section has_scalar
variables [ordered_semiring 𝕜] [add_comm_group E] [has_scalar 𝕜 E]
/-- A set `B` is an extreme subset of `A` if `B ⊆ A` and all points of `B` only belong to open
segments whose ends are in `B`. -/
def is_extreme (A B : set E) : Prop :=
B ⊆ A ∧ ∀ x₁ x₂ ∈ A, ∀ x ∈ B, x ∈ open_segment 𝕜 x₁ x₂ → x₁ ∈ B ∧ x₂ ∈ B
/-- A point `x` is an extreme point of a set `A` if `x` belongs to no open segment with ends in
`A`, except for the obvious `open_segment x x`. -/
def set.extreme_points (A : set E) : set E :=
{x ∈ A | ∀ (x₁ x₂ ∈ A), x ∈ open_segment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x}
@[refl] protected lemma is_extreme.refl (A : set E) :
is_extreme 𝕜 A A :=
⟨subset.rfl, λ x₁ x₂ hx₁A hx₂A x hxA hx, ⟨hx₁A, hx₂A⟩⟩
variables {𝕜} {A B C : set E} {x : E}
protected lemma is_extreme.rfl :
is_extreme 𝕜 A A :=
is_extreme.refl 𝕜 A
@[trans] protected lemma is_extreme.trans (hAB : is_extreme 𝕜 A B) (hBC : is_extreme 𝕜 B C) :
is_extreme 𝕜 A C :=
begin
use subset.trans hBC.1 hAB.1,
rintro x₁ x₂ hx₁A hx₂A x hxC hx,
obtain ⟨hx₁B, hx₂B⟩ := hAB.2 x₁ x₂ hx₁A hx₂A x (hBC.1 hxC) hx,
exact hBC.2 x₁ x₂ hx₁B hx₂B x hxC hx,
end
protected lemma is_extreme.antisymm :
anti_symmetric (is_extreme 𝕜 : set E → set E → Prop) :=
λ A B hAB hBA, subset.antisymm hBA.1 hAB.1
instance : is_partial_order (set E) (is_extreme 𝕜) :=
{ refl := is_extreme.refl 𝕜,
trans := λ A B C, is_extreme.trans,
antisymm := is_extreme.antisymm }
lemma is_extreme.inter (hAB : is_extreme 𝕜 A B) (hAC : is_extreme 𝕜 A C) :
is_extreme 𝕜 A (B ∩ C) :=
begin
use subset.trans (inter_subset_left _ _) hAB.1,
rintro x₁ x₂ hx₁A hx₂A x ⟨hxB, hxC⟩ hx,
obtain ⟨hx₁B, hx₂B⟩ := hAB.2 x₁ x₂ hx₁A hx₂A x hxB hx,
obtain ⟨hx₁C, hx₂C⟩ := hAC.2 x₁ x₂ hx₁A hx₂A x hxC hx,
exact ⟨⟨hx₁B, hx₁C⟩, hx₂B, hx₂C⟩,
end
protected lemma is_extreme.mono (hAC : is_extreme 𝕜 A C) (hBA : B ⊆ A) (hCB : C ⊆ B) :
is_extreme 𝕜 B C :=
⟨hCB, λ x₁ x₂ hx₁B hx₂B x hxC hx, hAC.2 x₁ x₂ (hBA hx₁B) (hBA hx₂B) x hxC hx⟩
lemma is_extreme_Inter {ι : Type*} [nonempty ι] {F : ι → set E}
(hAF : ∀ i : ι, is_extreme 𝕜 A (F i)) :
is_extreme 𝕜 A (⋂ i : ι, F i) :=
begin
obtain i := classical.arbitrary ι,
use Inter_subset_of_subset i (hAF i).1,
rintro x₁ x₂ hx₁A hx₂A x hxF hx,
simp_rw mem_Inter at ⊢ hxF,
have h := λ i, (hAF i).2 x₁ x₂ hx₁A hx₂A x (hxF i) hx,
exact ⟨λ i, (h i).1, λ i, (h i).2⟩,
end
lemma is_extreme_bInter {F : set (set E)} (hF : F.nonempty)
(hAF : ∀ B ∈ F, is_extreme 𝕜 A B) :
is_extreme 𝕜 A (⋂ B ∈ F, B) :=
begin
obtain ⟨B, hB⟩ := hF,
refine ⟨(bInter_subset_of_mem hB).trans (hAF B hB).1, λ x₁ x₂ hx₁A hx₂A x hxF hx, _⟩,
simp_rw mem_bInter_iff at ⊢ hxF,
have h := λ B hB, (hAF B hB).2 x₁ x₂ hx₁A hx₂A x (hxF B hB) hx,
exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩,
end
lemma is_extreme_sInter {F : set (set E)} (hF : F.nonempty)
(hAF : ∀ B ∈ F, is_extreme 𝕜 A B) :
is_extreme 𝕜 A (⋂₀ F) :=
begin
obtain ⟨B, hB⟩ := hF,
refine ⟨(sInter_subset_of_mem hB).trans (hAF B hB).1, λ x₁ x₂ hx₁A hx₂A x hxF hx, _⟩,
simp_rw mem_sInter at ⊢ hxF,
have h := λ B hB, (hAF B hB).2 x₁ x₂ hx₁A hx₂A x (hxF B hB) hx,
exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩,
end
lemma extreme_points_def :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ open_segment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x :=
iff.rfl
/-- x is an extreme point to A iff {x} is an extreme set of A. -/
lemma mem_extreme_points_iff_extreme_singleton :
x ∈ A.extreme_points 𝕜 ↔ is_extreme 𝕜 A {x} :=
begin
refine ⟨_, λ hx, ⟨singleton_subset_iff.1 hx.1, λ x₁ x₂ hx₁ hx₂, hx.2 x₁ x₂ hx₁ hx₂ x rfl⟩⟩,
rintro ⟨hxA, hAx⟩,
use singleton_subset_iff.2 hxA,
rintro x₁ x₂ hx₁A hx₂A y (rfl : y = x),
exact hAx x₁ x₂ hx₁A hx₂A,
end
lemma extreme_points_subset : A.extreme_points 𝕜 ⊆ A := λ x hx, hx.1
@[simp] lemma extreme_points_empty :
(∅ : set E).extreme_points 𝕜 = ∅ :=
subset_empty_iff.1 extreme_points_subset
@[simp] lemma extreme_points_singleton :
({x} : set E).extreme_points 𝕜 = {x} :=
extreme_points_subset.antisymm $ singleton_subset_iff.2
⟨mem_singleton x, λ x₁ x₂ hx₁ hx₂ _, ⟨hx₁, hx₂⟩⟩
lemma inter_extreme_points_subset_extreme_points_of_subset (hBA : B ⊆ A) :
B ∩ A.extreme_points 𝕜 ⊆ B.extreme_points 𝕜 :=
λ x ⟨hxB, hxA⟩, ⟨hxB, λ x₁ x₂ hx₁ hx₂ hx, hxA.2 x₁ x₂ (hBA hx₁) (hBA hx₂) hx⟩
lemma is_extreme.extreme_points_subset_extreme_points (hAB : is_extreme 𝕜 A B) :
B.extreme_points 𝕜 ⊆ A.extreme_points 𝕜 :=
λ x hx, mem_extreme_points_iff_extreme_singleton.2 (hAB.trans
(mem_extreme_points_iff_extreme_singleton.1 hx))
lemma is_extreme.extreme_points_eq (hAB : is_extreme 𝕜 A B) :
B.extreme_points 𝕜 = B ∩ A.extreme_points 𝕜 :=
subset.antisymm (λ x hx, ⟨hx.1, hAB.extreme_points_subset_extreme_points hx⟩)
(inter_extreme_points_subset_extreme_points_of_subset hAB.1)
end has_scalar
section ordered_semiring
variables {𝕜} [ordered_semiring 𝕜] [add_comm_group E] [module 𝕜 E] {A B : set E} {x : E}
lemma is_extreme.convex_diff (hA : convex 𝕜 A) (hAB : is_extreme 𝕜 A B) :
convex 𝕜 (A \ B) :=
convex_iff_open_segment_subset.2 (λ x₁ x₂ ⟨hx₁A, hx₁B⟩ ⟨hx₂A, hx₂B⟩ x hx,
⟨hA.open_segment_subset hx₁A hx₂A hx, λ hxB, hx₁B (hAB.2 x₁ x₂ hx₁A hx₂A x hxB hx).1⟩)
end ordered_semiring
section linear_ordered_field
variables {𝕜} [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] {A B : set E} {x : E}
/-- A useful restatement using `segment`: `x` is an extreme point iff the only (closed) segments
that contain it are those with `x` as one of their endpoints. -/
lemma mem_extreme_points_iff_forall_segment [no_zero_smul_divisors 𝕜 E] :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x :=
begin
split,
{ rintro ⟨hxA, hAx⟩,
use hxA,
rintro x₁ x₂ hx₁ hx₂ hx,
by_contra,
push_neg at h,
exact h.1 (hAx _ _ hx₁ hx₂ (mem_open_segment_of_ne_left_right 𝕜 h.1 h.2 hx)).1 },
rintro ⟨hxA, hAx⟩,
use hxA,
rintro x₁ x₂ hx₁ hx₂ hx,
obtain rfl | rfl := hAx x₁ x₂ hx₁ hx₂ (open_segment_subset_segment 𝕜 _ _ hx),
{ exact ⟨rfl, (left_mem_open_segment_iff.1 hx).symm⟩ },
exact ⟨right_mem_open_segment_iff.1 hx, rfl⟩,
end
lemma convex.mem_extreme_points_iff_convex_diff (hA : convex 𝕜 A) :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ convex 𝕜 (A \ {x}) :=
begin
use λ hx, ⟨hx.1, (mem_extreme_points_iff_extreme_singleton.1 hx).convex_diff hA⟩,
rintro ⟨hxA, hAx⟩,
refine mem_extreme_points_iff_forall_segment.2 ⟨hxA, λ x₁ x₂ hx₁ hx₂ hx, _⟩,
rw convex_iff_segment_subset at hAx,
by_contra,
push_neg at h,
exact (hAx ⟨hx₁, λ hx₁, h.1 (mem_singleton_iff.2 hx₁)⟩
⟨hx₂, λ hx₂, h.2 (mem_singleton_iff.2 hx₂)⟩ hx).2 rfl,
end
lemma convex.mem_extreme_points_iff_mem_diff_convex_hull_diff (hA : convex 𝕜 A) :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A \ convex_hull 𝕜 (A \ {x}) :=
by rw [hA.mem_extreme_points_iff_convex_diff, hA.convex_remove_iff_not_mem_convex_hull_remove,
mem_diff]
lemma extreme_points_convex_hull_subset :
(convex_hull 𝕜 A).extreme_points 𝕜 ⊆ A :=
begin
rintro x hx,
rw (convex_convex_hull 𝕜 _).mem_extreme_points_iff_convex_diff at hx,
by_contra,
exact (convex_hull_min (subset_diff.2 ⟨subset_convex_hull 𝕜 _, disjoint_singleton_right.2 h⟩) hx.2
hx.1).2 rfl,
end
end linear_ordered_field
|
e5baec9738b5c397cbc4ad4a8f0f0eb267956c9e | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /stage0/src/Lean/ReducibilityAttrs.lean | cfc5f04b4daf32e98db3a2e3b6f7ca52f1b1c138 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,937 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Attributes
namespace Lean
inductive ReducibilityStatus
| reducible | semireducible | irreducible
instance : Inhabited ReducibilityStatus := ⟨ReducibilityStatus.semireducible⟩
builtin_initialize reducibilityAttrs : EnumAttributes ReducibilityStatus ←
registerEnumAttributes `reducibility
[(`reducible, "reducible", ReducibilityStatus.reducible),
(`semireducible, "semireducible", ReducibilityStatus.semireducible),
(`irreducible, "irreducible", ReducibilityStatus.irreducible)]
@[export lean_get_reducibility_status]
def getReducibilityStatusImp (env : Environment) (declName : Name) : ReducibilityStatus :=
match reducibilityAttrs.getValue env declName with
| some s => s
| none => ReducibilityStatus.semireducible
@[export lean_set_reducibility_status]
def setReducibilityStatusImp (env : Environment) (declName : Name) (s : ReducibilityStatus) : Environment :=
match reducibilityAttrs.setValue env declName s with
| Except.ok env => env
| _ => env -- TODO(Leo): we should extend EnumAttributes.setValue in the future and ensure it never fails
def getReducibilityStatus {m} [Monad m] [MonadEnv m] (declName : Name) : m ReducibilityStatus := do
return getReducibilityStatusImp (← getEnv) declName
def setReducibilityStatus {m} [Monad m] [MonadEnv m] (declName : Name) (s : ReducibilityStatus) : m Unit := do
modifyEnv fun env => setReducibilityStatusImp env declName s
def setReducibleAttribute {m} [Monad m] [MonadEnv m] (declName : Name) : m Unit := do
setReducibilityStatus declName ReducibilityStatus.reducible
def isReducible {m} [Monad m] [MonadEnv m] (declName : Name) : m Bool := do
match ← getReducibilityStatus declName with
| ReducibilityStatus.reducible => true
| _ => false
end Lean
|
fcb8d77210c8dc804a5f72a62e3807b3053aeb00 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/quasi_pattern_unification_approx_issue.lean | 87c1ed19d996cc269af427fbf1ffebabd53c548f | [
"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 | 272 | lean | new_frontend
variables {δ σ : Type}
def foo0 : StateT δ (StateT σ Id) σ :=
getThe σ
def foo1 : StateT δ (StateT σ Id) σ :=
monadLift (get : StateT σ Id σ)
def foo2 : StateT δ (StateT σ Id) σ := do
let s : σ ← monadLift (get : StateT σ Id σ)
pure s
|
903125a4285cf4692fe9056514c87d5b9727587d | 4c630d016e43ace8c5f476a5070a471130c8a411 | /ring_theory/principal_ideal_domain.lean | da08a12aeb445fd55a62e485431af162a5379b55 | [
"Apache-2.0"
] | permissive | ngamt/mathlib | 9a510c391694dc43eec969914e2a0e20b272d172 | 58909bd424209739a2214961eefaa012fb8a18d2 | refs/heads/master | 1,585,942,993,674 | 1,540,739,585,000 | 1,540,916,815,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,199 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Chris Hughes, Morenikeji Neri
-/
import algebra.euclidean_domain
import ring_theory.ideals ring_theory.noetherian ring_theory.unique_factorization_domain
variables {α : Type*}
open set function is_ideal
local attribute [instance] classical.prop_decidable
class is_principal_ideal [comm_ring α] (S : set α) : Prop :=
(principal : ∃ a : α, S = {x | a ∣ x})
class principal_ideal_domain (α : Type*) extends integral_domain α :=
(principal : ∀ (S : set α) [is_ideal S], is_principal_ideal S)
namespace is_principal_ideal
variable [comm_ring α]
noncomputable def generator (S : set α) [is_principal_ideal S] : α :=
classical.some (principal S)
lemma generator_generates (S : set α) [is_principal_ideal S] : {x | generator S ∣ x} = S :=
eq.symm (classical.some_spec (principal S))
@[simp] lemma generator_mem (S : set α) [is_principal_ideal S] : generator S ∈ S :=
by conv {to_rhs, rw ← generator_generates S}; exact dvd_refl _
lemma mem_iff_generator_dvd (S : set α) [is_principal_ideal S] {x : α} : x ∈ S ↔ generator S ∣ x :=
by conv {to_lhs, rw ← generator_generates S}; refl
lemma eq_trivial_iff_generator_eq_zero (S : set α) [is_principal_ideal S] :
S = trivial α ↔ generator S = 0 :=
⟨λ h, by rw [← mem_trivial, ← h]; exact generator_mem S,
λ h, set.ext $ λ x, by rw [mem_iff_generator_dvd S, h, zero_dvd_iff, mem_trivial]⟩
instance to_is_ideal (S : set α) [is_principal_ideal S] : is_ideal S :=
{ to_is_submodule :=
{ zero_ := by rw ← generator_generates S; simp,
add_ := λ x y h, by rw ← generator_generates S at *; exact (dvd_add_iff_right h).1,
smul := λ c x h, by rw ← generator_generates S at h ⊢; exact dvd_mul_of_dvd_right h _ } }
end is_principal_ideal
namespace is_prime_ideal
open is_principal_ideal is_ideal
lemma to_maximal_ideal [principal_ideal_domain α] {S : set α}
[hpi : is_prime_ideal S] (hS : S ≠ trivial α) : is_maximal_ideal S :=
is_maximal_ideal.mk _ (is_proper_ideal_iff_one_not_mem.1 (by apply_instance))
begin
assume x T i hST hxS hxT,
haveI := principal_ideal_domain.principal S,
haveI := principal_ideal_domain.principal T,
cases (mem_iff_generator_dvd _).1 (hST ((mem_iff_generator_dvd _).2 (dvd_refl _))) with z hz,
cases is_prime_ideal.mem_or_mem_of_mul_mem (show generator T * z ∈ S,
by rw [mem_iff_generator_dvd S, ← hz]),
{ have hST' : S = T := set.subset.antisymm hST
(λ y hyT, (mem_iff_generator_dvd _).2
(dvd.trans ((mem_iff_generator_dvd _).1 h) ((mem_iff_generator_dvd _).1 hyT))),
cc },
{ cases (mem_iff_generator_dvd _).1 h with y hy,
rw [← mul_one (generator S), hy, mul_left_comm,
domain.mul_left_inj (mt (eq_trivial_iff_generator_eq_zero S).2 hS)] at hz,
exact hz.symm ▸ is_ideal.mul_right (generator_mem T) }
end
end is_prime_ideal
section
open euclidean_domain
variable [euclidean_domain α]
lemma mod_mem_iff {S : set α} [is_ideal S] {x y : α} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S :=
⟨λ hxy, div_add_mod x y ▸ is_ideal.add (is_ideal.mul_right hy) hxy,
λ hx, (mod_eq_sub_mul_div x y).symm ▸ is_ideal.sub hx (is_ideal.mul_right hy)⟩
instance euclidean_domain.to_principal_ideal_domain : principal_ideal_domain α :=
{ principal := λ S h, by exactI
⟨if h : {x : α | x ∈ S ∧ x ≠ 0} = ∅
then ⟨0, set.ext $ λ a, ⟨by finish [set.ext_iff],
λ h₁, (show a = 0, by simpa using h₁).symm ▸ is_ideal.zero S⟩⟩
else
have wf : well_founded euclidean_domain.r := euclidean_domain.r_well_founded α,
have hmin : well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h ∈ S ∧
well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h ≠ 0,
from well_founded.min_mem wf {x : α | x ∈ S ∧ x ≠ 0} h,
⟨well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h,
set.ext $ λ x,
⟨λ hx, div_add_mod x (well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h) ▸
dvd_add (dvd_mul_right _ _)
(have (x % (well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h) ∉ {x : α | 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 : α | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx],
by simp *),
λ hx, let ⟨y, hy⟩ := hx in hy.symm ▸ is_ideal.mul_right hmin.1⟩⟩⟩ }
end
namespace principal_ideal_domain
variables [principal_ideal_domain α]
lemma is_noetherian_ring : is_noetherian_ring α :=
assume ⟨s, hs⟩,
begin
letI := classical.dec_eq α,
have : is_ideal s := {.. hs},
rcases (principal s).principal with ⟨a, rfl⟩,
refine ⟨{a}, show span (↑({a} : finset α)) = {x : α | a ∣ x}, from _⟩,
simp [span_singleton, set.range, has_dvd.dvd, eq_comm, mul_comm]
end
section
local attribute [instance] classical.prop_decidable
open submodule
lemma factors_decreasing (b₁ b₂ : α) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) :
submodule.span {b₁} > submodule.span ({b₁ * b₂} : set α) :=
lt_of_le_not_le (span_singleton_subset.2 $ mem_span_singleton.2 $ ⟨b₂, by simp [mul_comm]⟩) $
assume (h : submodule.span {b₁} ⊆ submodule.span ({b₁ * b₂} : set α)),
have ∃ (c : α), b₁ * (b₂ * c) = b₁ * 1,
{ simpa [span_singleton_subset, mem_span_singleton, mul_left_comm, mul_comm, mul_assoc, eq_comm] using h },
let ⟨c, eq⟩ := this in
have b₂ * c = 1, from eq_of_mul_eq_mul_left h₁ eq,
h₂ ⟨units.mk_of_mul_eq_one _ _ this, rfl⟩
lemma exists_factors (a : α) : a ≠ 0 → ∃f:multiset α, (∀b∈f, irreducible b) ∧ associated a f.prod :=
have well_founded (inv_image (>) (λb, submodule.span ({b} : set α))), from
inv_image.wf _ $ is_noetherian_iff_well_founded.1 $ is_noetherian_ring,
this.induction a
begin
assume a ih ha,
by_cases h_unit : is_unit a,
{ exact match a, h_unit with _, ⟨u, rfl⟩ := ⟨∅, by simp, u⁻¹, by simp⟩ end },
by_cases h_irreducible : irreducible a,
{ exact ⟨{a}, by simp [h_irreducible]⟩ },
have : ∃b₁ b₂, a = b₁ * b₂ ∧ ¬ is_unit b₁ ∧ ¬ is_unit b₂,
{ simp [irreducible, not_or_distrib, not_forall] at h_irreducible; from h_irreducible h_unit },
rcases this with ⟨b₁, b₂, eq, h₁, h₂⟩,
have hb₁ : b₁ ≠ 0, { assume eq, simp * at * },
have : submodule.span {b₁} > submodule.span ({a} : set α),
by rw [eq]; from factors_decreasing b₁ b₂ hb₁ h₂,
rcases ih b₁ this hb₁ with ⟨f₁, hf₁, ha₁⟩,
have hb₂ : b₂ ≠ 0, { assume eq, simp * at * },
have : submodule.span {b₂} > submodule.span ({a} : set α),
by rw [eq, mul_comm]; from factors_decreasing b₂ b₁ hb₂ h₁,
rcases ih b₂ this hb₂ with ⟨f₂, hf₂, ha₂⟩,
refine ⟨f₁ + f₂, _⟩,
simpa [or_imp_distrib, forall_and_distrib, eq, associated_mul_mul ha₁ ha₂] using and.intro hf₁ hf₂
end
end
lemma is_maximal_ideal_of_irreducible {p : α} (hp : irreducible p) :
is_maximal_ideal {a | p ∣ a} :=
begin
letI h : is_ideal {a | p ∣ a} := @is_principal_ideal.to_is_ideal _ _ _ ⟨⟨p, rfl⟩⟩,
refine is_maximal_ideal.mk _ (assume ⟨q, hq⟩, hp.1 ⟨units.mk_of_mul_eq_one _ q hq.symm, rfl⟩) _,
assume x T i hT hxp hx,
rcases (principal T).principal with ⟨q, rfl⟩,
rcases hT (dvd_refl p) with ⟨c, rfl⟩,
rcases hp.2 _ _ rfl with ⟨q, rfl⟩ | ⟨c, rfl⟩,
{ exact units.coe_dvd _ _ },
{ simp at hxp hx, exact (hxp hx).elim }
end
lemma prime_of_irreducible {p : α} (hp : irreducible p) : prime p :=
have is_prime_ideal {a | p ∣ a}, from
@is_maximal_ideal.is_prime_ideal α _ _ (is_maximal_ideal_of_irreducible hp),
⟨assume h, not_irreducible_zero (show irreducible (0:α), from h ▸ hp), hp.1, this.mem_or_mem_of_mul_mem⟩
lemma associates_prime_of_irreducible : ∀{p : associates α}, irreducible p → p.prime :=
associates.forall_associated.2 $ assume a,
begin
rw [associates.irreducible_mk_iff, associates.prime_mk],
exact prime_of_irreducible
end
lemma eq_of_prod_eq_associates {s : multiset (associates α)} :
∀{t:multiset (associates α)}, (∀a∈s, irreducible a) → (∀a∈t, irreducible a) → s.prod = t.prod →
s = t :=
begin
letI := classical.dec_eq (associates α),
refine s.induction_on _ _,
{ assume t _ ht eq,
have : ∀a∈t, (a:associates α) = 1, from associates.prod_eq_one_iff.1 eq.symm,
have : ∀a∈t, irreducible (1 : associates α), from assume a ha, this a ha ▸ ht a ha,
exact (multiset.eq_zero_of_forall_not_mem $ assume a ha, not_irreducible_one $ this a ha).symm },
{ assume a s ih t hs ht h,
have ha : a.prime, from associates_prime_of_irreducible (hs a $ multiset.mem_cons_self a s),
rcases associates.exists_mem_multiset_le_of_prime ha ⟨s.prod, by simpa using h⟩
with ⟨x, hx, hxa⟩,
have : x.prime, from associates_prime_of_irreducible (ht x hx),
have : a = x := (associates.one_or_eq_of_le_of_prime _ _ this hxa).resolve_left ha.2.1,
subst this,
have : s.prod = (t.erase a).prod,
{ rw ← multiset.cons_erase hx at h,
simp at h,
exact associates.eq_of_mul_eq_mul_left a _ _ ha.1 h },
have : s = t.erase a, from ih
(assume x hxs, hs x $ multiset.mem_cons_of_mem hxs)
(assume x hxt, ht x $ classical.by_cases
(assume h : x = a, h.symm ▸ hx)
(assume ne, (multiset.mem_erase_of_ne ne).1 hxt))
this,
rw [this, multiset.cons_erase hx] }
end
lemma associated_of_associated_prod_prod {s t : multiset α}
(hs : ∀a∈s, irreducible a) (ht : ∀a∈t, irreducible a) (h : associated s.prod t.prod) :
multiset.rel associated s t :=
begin
refine (associates.rel_associated_iff_map_eq_map.2 $ eq_of_prod_eq_associates _ _ _),
{ assume a ha,
rcases multiset.mem_map.1 ha with ⟨x, hx, rfl⟩,
simpa [associates.irreducible_mk_iff] using hs x hx },
{ assume a ha,
rcases multiset.mem_map.1 ha with ⟨x, hx, rfl⟩,
simpa [associates.irreducible_mk_iff] using ht x hx },
rwa [associates.prod_mk, associates.prod_mk, associates.mk_eq_mk_iff_associated]
end
section
local attribute [instance] classical.prop_decidable
noncomputable def factors (a : α) : multiset α :=
if h : a = 0 then ∅ else classical.some (exists_factors a h)
lemma factors_spec (a : α) (h : a ≠ 0) :
(∀b∈factors a, irreducible b) ∧ associated a (factors a).prod :=
begin
unfold factors, rw [dif_neg h],
exact classical.some_spec (exists_factors a h)
end
/-- The unique factorization domain structure given by the principal ideal domain.
This is not added as type class instance, since the `factors` might be computed in a different way.
E.g. factors could return normalized values.
-/
noncomputable def to_unique_factorization_domain : unique_factorization_domain α :=
{ factors := factors,
factors_prod := assume a ha, associated.symm (factors_spec a ha).2,
irreducible_factors := assume a ha, (factors_spec a ha).1,
unique := assume s t, associated_of_associated_prod_prod }
end
end principal_ideal_domain
|
eef8ac2ed4de6fa008a64bb51f78bc83226ae9cb | 4bddde0d06fbd53be6f23d7f5899998e8f63410b | /src/tactic/iconfig/cfgopt.lean | f8d6da831c3fd87319d52feabf47e7c3cc1de776 | [] | no_license | khoek/libiconfig | 4816290a5862af14b07683b3d2663e8e62832ef4 | 6f55c50bc5d852d26ee5ee4c5b52b2cda2a852e5 | refs/heads/master | 1,586,109,683,212 | 1,559,567,916,000 | 1,559,567,916,000 | 157,085,466 | 0 | 1 | null | 1,559,567,917,000 | 1,541,945,134,000 | Lean | UTF-8 | Lean | false | false | 2,979 | lean | import .lib
namespace cfgopt
@[derive [has_reflect, decidable_eq]]
inductive type
| bool
| nat
| enat
| string
| name
| pexpr
| list (t : type)
namespace type
meta def to_pexpr : type → _root_.pexpr
| bool := ``(_root_.bool)
| nat := ``(_root_.nat)
| enat := ``(with_top ℕ)
| string := ``(_root_.string)
| name := ``(_root_.name)
| pexpr := ``(_root_.pexpr)
| (list t) := ``(_root_.list) t.to_pexpr
meta def to_Type : type → Type
| bool := _root_.bool
| nat := _root_.nat
| enat := with_top ℕ
| string := _root_.string
| name := _root_.name
| pexpr := _root_.pexpr
| (list t) := _root_.list t.to_Type
meta mutual def from_expr, get_list_type
with from_expr : expr → option type | e :=
if e = `(_root_.bool) then type.bool else
if e = `(_root_.nat) then type.nat else
if e = `(_root_.string) then type.string else
if e = `(_root_.name) then type.name else
if e = `(_root_.pexpr) then type.pexpr else
match get_list_type e with
| some t := type.list t
| none := none
end
with get_list_type : expr → option type | e :=
if e.app_fn.const_name = `list then from_expr e.app_arg
else none
def to_string : type → _root_.string
| bool := "bool"
| nat := "ℕ"
| enat := "eℕ"
| string := "string"
| name := "name"
| pexpr := "pexpr"
| (list t) := "(list " ++ t.to_string ++ ")"
instance : has_to_string type := ⟨type.to_string⟩
meta instance : has_to_format type := ⟨format.of_string ∘ type.to_string⟩
end type
@[derive has_reflect]
meta inductive value
| bool : bool → value
| nat : ℕ → value
| enat : with_top ℕ → value
| string : string → value
| name : name → value
| pexpr : pexpr → value
| list : type → expr → value
open value
namespace value
meta def to_type : value → type
| (bool _) := type.bool
| (nat _) := type.nat
| (enat _) := type.enat
| (string _) := type.string
| (name _) := type.name
| (pexpr _) := type.pexpr
| (list t _) := type.list t
meta def to_Type : value → Type := type.to_Type ∘ to_type
meta def to_expr : value → expr
| (bool b) := `(b)
| (nat n) := `(n)
| (enat e) := `(e)
| (string s) := `(s)
| (name n) := `(n)
| (pexpr p) := `(p)
| (list _ l) := l
meta def to_value_string : value → _root_.string
| (bool b) := sformat!"{b}"
| (nat n) := sformat!"{n}"
| (enat none) := sformat!"∞"
| (enat (some n)) := sformat!"{n}"
| (string s) := sformat!"{s}"
| (name n) := sformat!"{n}"
| (pexpr p) := sformat!"{p}"
| (list _ l) := sformat!"{l}"
meta def to_string (v : value) : _root_.string :=
sformat!"{v.to_value_string}:{v.to_type}"
meta instance has_to_string : has_to_string value := ⟨to_string⟩
end value
end cfgopt
@[derive has_reflect]
meta structure cfgopt :=
(key : name)
(val : cfgopt.value)
namespace cfgopt
meta instance has_to_string : has_to_string cfgopt :=
⟨λ v, sformat!"{v.key}={v.val}"⟩
meta instance has_to_tactic_format : has_to_tactic_format cfgopt :=
⟨λ v, return $ to_string v⟩
end cfgopt
|
a08251ae0ddcf5159b05b8823458abdcf970dcaf | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /data/vector2.lean | d3d077cc704dd7d4a05573251409aa7613122073 | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 7,268 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Additional theorems about the `vector` type.
-/
import data.vector data.list.basic data.sigma data.equiv.basic
category.traversable
namespace vector
variables {α : Type*} {n : ℕ}
attribute [simp] head_cons tail_cons
instance [inhabited α] : inhabited (vector α n) :=
⟨of_fn (λ _, default α)⟩
theorem to_list_injective : function.injective (@to_list α n) :=
subtype.val_injective
@[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f
| 0 f := rfl
| (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn]
@[simp] theorem mk_to_list :
∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v
| ⟨l, h₁⟩ h₂ := rfl
theorem nth_eq_nth_le : ∀ (v : vector α n) (i),
nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2)
| ⟨l, h⟩ i := rfl
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i :=
by rw [nth_eq_nth_le, ← list.nth_le_of_fn f];
congr; apply to_list_of_fn
@[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v :=
begin
rcases v with ⟨l, rfl⟩,
apply to_list_injective,
change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i,
simp [nth, list.of_fn_nth_le]
end
@[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n),
nth (tail v) i = nth v i.succ
| ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl
@[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) :
tail (of_fn f) = of_fn (λ i, f i.succ) :=
(of_fn_nth _).symm.trans $ by congr; funext i; simp
theorem head'_to_list : ∀ (v : vector α n.succ),
(to_list v).head' = some (head v)
| ⟨a::l, e⟩ := rfl
def reverse (v : vector α n) : vector α n :=
⟨v.to_list.reverse, by simp⟩
@[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v
| ⟨a::l, e⟩ := rfl
@[simp] theorem head_of_fn
{n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 :=
by rw [← nth_zero, nth_of_fn]
@[simp] theorem nth_cons_zero
(a : α) (v : vector α n) : nth (a :: v) 0 = a :=
by simp [nth_zero]
@[simp] theorem nth_cons_succ
(a : α) (v : vector α n) (i : fin n) : nth (a :: v) i.succ = nth v i :=
by rw [← nth_tail, tail_cons]
def {u} m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n)
| 0 f := pure nil
| (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a :: v)
theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} :
∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f)
| 0 f := rfl
| (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn]
def {u} mmap {m} [monad m] {α} {β : Type u} (f : α → m β) :
∀ {n}, vector α n → m (vector β n)
| _ ⟨[], rfl⟩ := pure nil
| _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' :: t')
@[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) :
mmap f nil = pure nil := rfl
@[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) :
∀ {n} (v : vector α n), mmap f (a::v) =
do h' ← f a, t' ← mmap f v, pure (h' :: t')
| _ ⟨l, rfl⟩ := rfl
@[extensionality] theorem ext : ∀ {v w : vector α n}
(h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w
| ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw])
(λ m hm hn, h ⟨m, hv ▸ hm⟩))
end vector
namespace vector
universes u
variables {n : ℕ}
section traverse
variables {f f' : Type u → Type u}
variables [applicative f] [applicative f']
open applicative functor
open list (cons) nat
private def traverse_aux {α β : Type u} (g : α → f β) :
Π (x : list α), f (vector β x.length)
| [] := pure vector.nil
| (x::xs) := vector.cons <$> g x <*> traverse_aux xs
protected def traverse {α β : Type u} (g : α → f β) :
vector α n → f (vector β n)
| ⟨v,Hv⟩ := cast (by rw Hv) $ traverse_aux g v
protected def to_array {α : Type u} {n} : vector α n → array n α
| ⟨xs,h⟩ := cast (by rw h) xs.to_array
variables [is_lawful_applicative f] [is_lawful_applicative f']
variables {α β η : Type u}
@[simp]
protected lemma traverse_def (g : α → f β) (x : α) (xs : vector α n) :
vector.traverse g (x :: xs) = cons <$> g x <*> vector.traverse g xs :=
begin
cases xs, simp!,
h_generalize _ : _ == i,
h_generalize _ : _ == j, subst n,
simp at *, subst i, subst j
end
protected lemma id_traverse (x : vector α n) :
vector.traverse id.mk x = x :=
begin
cases x with x, subst n,
dsimp [vector.traverse,cast],
induction x with x xs, refl,
simp! [x_ih], refl
end
open function
protected lemma comp_traverse (g : α → f β) (h : β → f' η) (x : vector α n) :
vector.traverse (comp.mk ∘ functor.map h ∘ g) x =
comp.mk (vector.traverse h <$> vector.traverse g x) :=
begin
cases x with x,
dunfold vector.traverse, subst n, dsimp [cast],
induction x with x xs; simp! [cast,*] with functor_norm, refl,
congr' 2, ext, simp [function.comp,flip]
end
protected lemma map_traverse
(g : α → f' β) (f : β → η)
(x : vector α n) :
map f <$> vector.traverse g x = vector.traverse (functor.map f ∘ g) x :=
begin
symmetry,
cases x with x,
subst n, unfold vector.traverse cast,
induction x; simp! [*,cast,map,flip,function.comp,vector.map] with functor_norm,
{ refl },
{ congr' 2, ext, cases x_1, refl }
end
protected lemma traverse_map
(g : α → β) (f : β → f' η)
(x : vector α n) :
vector.traverse f (map g x) = vector.traverse (f ∘ g) x :=
begin
symmetry,
cases x with x, subst n,
induction x; simp! [*,map,flip,vector.map] with norm,
{ refl },
{ congr' 1, simp, simp,
congr' 1, simp, simp,
{ dsimp [list.length],
rw list.length_map },
simp [vector.traverse,map] at x_ih,
transitivity, apply heq_of_eq, apply x_ih,
apply cast_heq }
end
variable (eta : applicative_transformation f f')
protected lemma naturality {α β : Type*}
(F : α → f β) (x : vector α n) :
eta (vector.traverse F x) = vector.traverse (@eta _ ∘ F) x :=
begin
cases x;
simp! [vector.traverse] with norm,
induction x_val with x xs generalizing n,
{ h_generalize Hi : _ == i,
h_generalize Hj : _ == j,
simp! at Hi Hj; subst n; cases Hi; cases Hj,
simp [*] with functor_norm },
{ specialize x_val_ih rfl, subst n,
revert x_val_ih,
h_generalize Hi : _ == i, h_generalize _ : _ == j,
h_generalize _ : _ == k, h_generalize _ : _ == h,
intros, simp! at *,
subst k, subst h, simp with functor_norm,
subst i, subst j, rw [x_val_ih] }
end
end traverse
instance : traversable.{u} (flip vector n) :=
{ traverse := @vector.traverse n
, map := λ α β, @vector.map.{u u} α β n }
instance : is_lawful_traversable.{u} (flip vector n) :=
{ id_traverse := @vector.id_traverse n,
comp_traverse := @vector.comp_traverse n,
map_traverse := @vector.map_traverse.{u} n,
traverse_map := @vector.traverse_map n,
naturality := @vector.naturality.{u} n,
id_map := by intros; cases x; simp! [functor.map],
comp_map := by intros; cases x; simp! [functor.map] }
end vector
|
c3adb4326ed3525d27cf4e821812f06b59a4cc18 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Init/Tactics.lean | 2da5f260125b56bf4358db895bcaa55b17c82326 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 35,363 | 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, Mario Carneiro
-/
prelude
import Init.Notation
set_option linter.missingDocs true -- keep it documented
namespace Lean.Parser.Tactic
/--
`with_annotate_state stx t` annotates the lexical range of `stx : Syntax` with
the initial and final state of running tactic `t`.
-/
scoped syntax (name := withAnnotateState)
"with_annotate_state " rawStx ppSpace tactic : tactic
/--
Introduces one or more hypotheses, optionally naming and/or pattern-matching them.
For each hypothesis to be introduced, the remaining main goal's target type must
be a `let` or function type.
* `intro` by itself introduces one anonymous hypothesis, which can be accessed
by e.g. `assumption`.
* `intro x y` introduces two hypotheses and names them. Individual hypotheses
can be anonymized via `_`, or matched against a pattern:
```lean
-- ... ⊢ α × β → ...
intro (a, b)
-- ..., a : α, b : β ⊢ ...
```
* Alternatively, `intro` can be combined with pattern matching much like `fun`:
```lean
intro
| n + 1, 0 => tac
| ...
```
-/
syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic
/--
`intros x...` behaves like `intro x...`, but then keeps introducing (anonymous)
hypotheses until goal is not of a function type.
-/
syntax (name := intros) "intros " (colGt (ident <|> hole))* : tactic
/--
`rename t => x` renames the most recent hypothesis whose type matches `t`
(which may contain placeholders) to `x`, or fails if no such hypothesis could be found.
-/
syntax (name := rename) "rename " term " => " ident : tactic
/--
`revert x...` is the inverse of `intro x...`: it moves the given hypotheses
into the main goal's target type.
-/
syntax (name := revert) "revert " (colGt term:max)+ : tactic
/--
`clear x...` removes the given hypotheses, or fails if there are remaining
references to a hypothesis.
-/
syntax (name := clear) "clear " (colGt term:max)+ : tactic
/--
`subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis
of type `x = e` or `e = x`.
If `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead.
-/
syntax (name := subst) "subst " (colGt term:max)+ : tactic
/--
Applies `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.
-/
syntax (name := substVars) "subst_vars" : tactic
/--
`assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails.
Note also the `‹t›` term notation, which is a shorthand for `show t by assumption`.
-/
syntax (name := assumption) "assumption" : tactic
/--
`contradiction` closes the main goal if its hypotheses are "trivially contradictory".
- Inductive type/family with no applicable constructors
```lean
example (h : False) : p := by contradiction
```
- Injectivity of constructors
```lean
example (h : none = some true) : p := by contradiction --
```
- Decidable false proposition
```lean
example (h : 2 + 2 = 3) : p := by contradiction
```
- Contradictory hypotheses
```lean
example (h : p) (h' : ¬ p) : q := by contradiction
```
- Other simple contradictions such as
```lean
example (x : Nat) (h : x ≠ x) : p := by contradiction
```
-/
syntax (name := contradiction) "contradiction" : tactic
/--
`apply e` tries to match the current goal against the conclusion of `e`'s type.
If it succeeds, then the tactic returns as many subgoals as the number of premises that
have not been fixed by type inference or type class resolution.
Non-dependent premises are added before dependent ones.
The `apply` tactic uses higher-order pattern matching, type class resolution,
and first-order unification with dependent types.
-/
syntax (name := apply) "apply " term : tactic
/--
`exact e` closes the main goal if its target type matches that of `e`.
-/
syntax (name := exact) "exact " term : tactic
/--
`refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`)
holes in `e` that are not solved by unification with the main goal's target type
are converted into new goals, using the hole's name, if any, as the goal case name.
-/
syntax (name := refine) "refine " term : tactic
/--
`refine' e` behaves like `refine e`, except that unsolved placeholders (`_`)
and implicit parameters are also converted into new goals.
-/
syntax (name := refine') "refine' " term : tactic
/--
If the main goal's target type is an inductive type, `constructor` solves it with
the first matching constructor, or else fails.
-/
syntax (name := constructor) "constructor" : tactic
/--
* `case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`,
or else fails.
* `case tag x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses
with inaccessible names to the given names.
* `case tag₁ | tag₂ => tac` is equivalent to `(case tag₁ => tac); (case tag₂ => tac)`.
-/
syntax (name := case) "case " sepBy1(caseArg, " | ") " => " tacticSeq : tactic
/--
`case'` is similar to the `case tag => tac` tactic, but does not ensure the goal
has been solved after applying `tac`, nor admits the goal if `tac` failed.
Recall that `case` closes the goal using `sorry` when `tac` fails, and
the tactic execution is not interrupted.
-/
syntax (name := case') "case' " sepBy1(caseArg, " | ") " => " tacticSeq : tactic
/--
`next => tac` focuses on the next goal and solves it using `tac`, or else fails.
`next x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with
inaccessible names to the given names.
-/
macro "next " args:binderIdent* " => " tac:tacticSeq : tactic => `(tactic| case _ $args* => $tac)
/-- `all_goals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/
syntax (name := allGoals) "all_goals " tacticSeq : tactic
/--
`any_goals tac` applies the tactic `tac` to every goal, and succeeds if at
least one application succeeds.
-/
syntax (name := anyGoals) "any_goals " tacticSeq : tactic
/--
`focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it.
Usually `· tac`, which enforces that the goal is closed by `tac`, should be preferred.
-/
syntax (name := focus) "focus " tacticSeq : tactic
/-- `skip` does nothing. -/
syntax (name := skip) "skip" : tactic
/-- `done` succeeds iff there are no remaining goals. -/
syntax (name := done) "done" : tactic
/-- `trace_state` displays the current state in the info view. -/
syntax (name := traceState) "trace_state" : tactic
/-- `trace msg` displays `msg` in the info view. -/
syntax (name := traceMessage) "trace " str : tactic
/-- `fail_if_success t` fails if the tactic `t` succeeds. -/
syntax (name := failIfSuccess) "fail_if_success " tacticSeq : tactic
/--
`(tacs)` executes a list of tactics in sequence, without requiring that
the goal be closed at the end like `· tacs`. Like `by` itself, the tactics
can be either separated by newlines or `;`.
-/
syntax (name := paren) "(" tacticSeq ")" : tactic
/--
`with_reducible tacs` excutes `tacs` using the reducible transparency setting.
In this setting only definitions tagged as `[reducible]` are unfolded.
-/
syntax (name := withReducible) "with_reducible " tacticSeq : tactic
/--
`with_reducible_and_instances tacs` excutes `tacs` using the `.instances` transparency setting.
In this setting only definitions tagged as `[reducible]` or type class instances are unfolded.
-/
syntax (name := withReducibleAndInstances) "with_reducible_and_instances " tacticSeq : tactic
/--
`with_unfolding_all tacs` excutes `tacs` using the `.all` transparency setting.
In this setting all definitions that are not opaque are unfolded.
-/
syntax (name := withUnfoldingAll) "with_unfolding_all " tacticSeq : tactic
/-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/
syntax (name := first) "first " withPosition((colGe "|" tacticSeq)+) : tactic
/--
`rotate_left n` rotates goals to the left by `n`. That is, `rotate_left 1`
takes the main goal and puts it to the back of the subgoal list.
If `n` is omitted, it defaults to `1`.
-/
syntax (name := rotateLeft) "rotate_left" (num)? : tactic
/--
Rotate the goals to the right by `n`. That is, take the goal at the back
and push it to the front `n` times. If `n` is omitted, it defaults to `1`.
-/
syntax (name := rotateRight) "rotate_right" (num)? : tactic
/-- `try tac` runs `tac` and succeeds even if `tac` failed. -/
macro "try " t:tacticSeq : tactic => `(first | $t | skip)
/--
`tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal,
concatenating all goals produced by `tac'`.
-/
macro:1 x:tactic tk:" <;> " y:tactic:0 : tactic => `(tactic|
focus
$x:tactic
-- annotate token with state after executing `x`
with_annotate_state $tk skip
all_goals $y:tactic)
/-- `eq_refl` is equivalent to `exact rfl`, but has a few optimizations. -/
syntax (name := refl) "eq_refl" : tactic
/--
`rfl` tries to close the current goal using reflexivity.
This is supposed to be an extensible tactic and users can add their own support
for new reflexive relations.
-/
macro "rfl" : tactic => `(eq_refl)
/--
`rfl'` is similar to `rfl`, but disables smart unfolding and unfolds all kinds of definitions,
theorems included (relevant for declarations defined by well-founded recursion).
-/
macro "rfl'" : tactic => `(set_option smartUnfolding false in with_unfolding_all rfl)
/--
`ac_rfl` proves equalities up to application of an associative and commutative operator.
```
instance : IsAssociative (α := Nat) (.+.) := ⟨Nat.add_assoc⟩
instance : IsCommutative (α := Nat) (.+.) := ⟨Nat.add_comm⟩
example (a b c d : Nat) : a + b + c + d = d + (b + c) + a := by ac_rfl
```
-/
syntax (name := acRfl) "ac_rfl" : tactic
/--
The `sorry` tactic closes the goal using `sorryAx`. This is intended for stubbing out incomplete
parts of a proof while still having a syntactically correct proof skeleton. Lean will give
a warning whenever a proof uses `sorry`, so you aren't likely to miss it, but
you can double check if a theorem depends on `sorry` by using
`#print axioms my_thm` and looking for `sorryAx` in the axiom list.
-/
macro "sorry" : tactic => `(exact @sorryAx _ false)
/-- `admit` is a shorthand for `exact sorry`. -/
macro "admit" : tactic => `(exact @sorryAx _ false)
/--
`infer_instance` is an abbreviation for `exact inferInstance`.
It synthesizes a value of any target type by typeclass inference.
-/
macro "infer_instance" : tactic => `(exact inferInstance)
/-- Optional configuration option for tactics -/
syntax config := atomic(" (" &"config") " := " term ")"
/-- The `*` location refers to all hypotheses and the goal. -/
syntax locationWildcard := "*"
/--
A hypothesis location specification consists of 1 or more hypothesis references
and optionally `⊢` denoting the goal.
-/
syntax locationHyp := (colGt term:max)+ ("⊢" <|> "|-")?
/--
Location specifications are used by many tactics that can operate on either the
hypotheses or the goal. It can have one of the forms:
* 'empty' is not actually present in this syntax, but most tactics use
`(location)?` matchers. It means to target the goal only.
* `at h₁ ... hₙ`: target the hypotheses `h₁`, ..., `hₙ`
* `at h₁ h₂ ⊢`: target the hypotheses `h₁` and `h₂`, and the goal
* `at *`: target all hypotheses and the goal
-/
syntax location := withPosition(" at " (locationWildcard <|> locationHyp))
/--
* `change tgt'` will change the goal from `tgt` to `tgt'`,
assuming these are definitionally equal.
* `change t' at h` will change hypothesis `h : t` to have type `t'`, assuming
assuming `t` and `t'` are definitionally equal.
-/
syntax (name := change) "change " term (location)? : tactic
/--
* `change a with b` will change occurrences of `a` to `b` in the goal,
assuming `a` and `b` are are definitionally equal.
* `change a with b at h` similarly changes `a` to `b` in the type of hypothesis `h`.
-/
syntax (name := changeWith) "change " term " with " term (location)? : tactic
/--
If `thm` is a theorem `a = b`, then as a rewrite rule,
* `thm` means to replace `a` with `b`, and
* `← thm` means to replace `b` with `a`.
-/
syntax rwRule := ("← " <|> "<- ")? term
/-- A `rwRuleSeq` is a list of `rwRule` in brackets. -/
syntax rwRuleSeq := " [" rwRule,*,? "]"
/--
`rewrite [e]` applies identity `e` as a rewrite rule to the target of the main goal.
If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction.
If `e` is a defined constant, then the equational theorems associated with `e` are used.
This provides a convenient way to unfold `e`.
- `rewrite [e₁, ..., eₙ]` applies the given rules sequentially.
- `rewrite [e] at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a
list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-`
can also be used, to signify the target of the goal.
-/
syntax (name := rewriteSeq) "rewrite" (config)? rwRuleSeq (location)? : tactic
/--
`rw` is like `rewrite`, but also tries to close the goal by "cheap" (reducible) `rfl` afterwards.
-/
macro (name := rwSeq) "rw" c:(config)? s:rwRuleSeq l:(location)? : tactic =>
match s with
| `(rwRuleSeq| [$rs,*]%$rbrak) =>
-- We show the `rfl` state on `]`
`(tactic| rewrite $(c)? [$rs,*] $(l)?; with_annotate_state $rbrak (try (with_reducible rfl)))
| _ => Macro.throwUnsupported
/--
The `injection` tactic is based on the fact that constructors of inductive data
types are injections.
That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)`
and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too.
If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies
injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in
the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`.
To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor.
Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types
`a = c` and `b = d` to the main goal.
The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses.
-/
syntax (name := injection) "injection " term (" with " (colGt (ident <|> hole))+)? : tactic
/-- `injections` applies `injection` to all hypotheses recursively
(since `injection` can produce new hypotheses). Useful for destructing nested
constructor equalities like `(a::b::c) = (d::e::f)`. -/
-- TODO: add with
syntax (name := injections) "injections" (colGt (ident <|> hole))* : tactic
/--
The discharger clause of `simp` and related tactics.
This is a tactic used to discharge the side conditions on conditional rewrite rules.
-/
syntax discharger := atomic(" (" (&"discharger" <|> &"disch")) " := " tacticSeq ")"
/-- Use this rewrite rule before entering the subterms -/
syntax simpPre := "↓"
/-- Use this rewrite rule after entering the subterms -/
syntax simpPost := "↑"
/--
A simp lemma specification is:
* optional `↑` or `↓` to specify use before or after entering the subterm
* optional `←` to use the lemma backward
* `thm` for the theorem to rewrite with
-/
syntax simpLemma := (simpPre <|> simpPost)? ("← " <|> "<- ")? term
/-- An erasure specification `-thm` says to remove `thm` from the simp set -/
syntax simpErase := "-" term:max
/-- The simp lemma specification `*` means to rewrite with all hypotheses -/
syntax simpStar := "*"
/--
The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or
non-dependent hypotheses. It has many variants:
- `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.
- `simp [h₁, h₂, ..., hₙ]` simplifies the main goal target using the lemmas tagged
with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions.
If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with
`f` are used. This provides a convenient way to unfold `f`.
- `simp [*]` simplifies the main goal target using the lemmas tagged with the
attribute `[simp]` and all hypotheses.
- `simp only [h₁, h₂, ..., hₙ]` is like `simp [h₁, h₂, ..., hₙ]` but does not use `[simp]` lemmas.
- `simp [-id₁, ..., -idₙ]` simplifies the main goal target using the lemmas tagged
with the attribute `[simp]`, but removes the ones named `idᵢ`.
- `simp at h₁ h₂ ... hₙ` simplifies the hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. If
the target or another hypothesis depends on `hᵢ`, a new simplified hypothesis
`hᵢ` is introduced, but the old one remains in the local context.
- `simp at *` simplifies all the hypotheses and the target.
- `simp [*] at *` simplifies target and all (propositional) hypotheses using the
other hypotheses.
-/
syntax (name := simp) "simp" (config)? (discharger)? (&" only")?
(" [" (simpStar <|> simpErase <|> simpLemma),* "]")? (location)? : tactic
/--
`simp_all` is a stronger version of `simp [*] at *` where the hypotheses and target
are simplified multiple times until no simplication is applicable.
Only non-dependent propositional hypotheses are considered.
-/
syntax (name := simpAll) "simp_all" (config)? (discharger)? (&" only")?
(" [" (simpErase <|> simpLemma),* "]")? : tactic
/--
The `dsimp` tactic is the definitional simplifier. It is similar to `simp` but only
applies theorems that hold by reflexivity. Thus, the result is guaranteed to be
definitionally equal to the input.
-/
syntax (name := dsimp) "dsimp" (config)? (discharger)? (&" only")?
(" [" (simpErase <|> simpLemma),* "]")? (location)? : tactic
/--
`delta id1 id2 ...` delta-expands the definitions `id1`, `id2`, ....
This is a low-level tactic, it will expose how recursive definitions have been
compiled by Lean.
-/
syntax (name := delta) "delta " (colGt ident)+ (location)? : tactic
/--
* `unfold id` unfolds definition `id`.
* `unfold id1 id2 ...` is equivalent to `unfold id1; unfold id2; ...`.
For non-recursive definitions, this tactic is identical to `delta`.
For definitions by pattern matching, it uses "equation lemmas" which are
autogenerated for each match arm.
-/
syntax (name := unfold) "unfold " (colGt ident)+ (location)? : tactic
/--
Auxiliary macro for lifting have/suffices/let/...
It makes sure the "continuation" `?_` is the main goal after refining.
-/
macro "refine_lift " e:term : tactic => `(focus (refine no_implicit_lambda% $e; rotate_right))
/--
`have h : t := e` adds the hypothesis `h : t` to the current goal if `e` a term
of type `t`.
* If `t` is omitted, it will be inferred.
* If `h` is omitted, the name `this` is used.
* The variant `have pattern := e` is equivalent to `match e with | pattern => _`,
and it is convenient for types that have only one applicable constructor.
For example, given `h : p ∧ q ∧ r`, `have ⟨h₁, h₂, h₃⟩ := h` produces the
hypotheses `h₁ : p`, `h₂ : q`, and `h₃ : r`.
-/
macro "have " d:haveDecl : tactic => `(refine_lift have $d:haveDecl; ?_)
/--
Given a main goal `ctx ⊢ t`, `suffices h : t' from e` replaces the main goal with `ctx ⊢ t'`,
`e` must have type `t` in the context `ctx, h : t'`.
The variant `suffices h : t' by tac` is a shorthand for `suffices h : t' from by tac`.
If `h :` is omitted, the name `this` is used.
-/
macro "suffices " d:sufficesDecl : tactic => `(refine_lift suffices $d; ?_)
/--
`let h : t := e` adds the hypothesis `h : t := e` to the current goal if `e` a term of type `t`.
If `t` is omitted, it will be inferred.
The variant `let pattern := e` is equivalent to `match e with | pattern => _`,
and it is convenient for types that have only applicable constructor.
Example: given `h : p ∧ q ∧ r`, `let ⟨h₁, h₂, h₃⟩ := h` produces the hypotheses
`h₁ : p`, `h₂ : q`, and `h₃ : r`.
-/
macro "let " d:letDecl : tactic => `(refine_lift let $d:letDecl; ?_)
/--
`show t` finds the first goal whose target unifies with `t`. It makes that the main goal,
performs the unification, and replaces the target with the unified version of `t`.
-/
macro "show " e:term : tactic => `(refine_lift show $e from ?_) -- TODO: fix, see comment
/-- `let rec f : t := e` adds a recursive definition `f` to the current goal.
The syntax is the same as term-mode `let rec`. -/
syntax (name := letrec) withPosition(atomic("let " &"rec ") letRecDecls) : tactic
macro_rules
| `(tactic| let rec $d) => `(tactic| refine_lift let rec $d; ?_)
/-- Similar to `refine_lift`, but using `refine'` -/
macro "refine_lift' " e:term : tactic => `(focus (refine' no_implicit_lambda% $e; rotate_right))
/-- Similar to `have`, but using `refine'` -/
macro "have' " d:haveDecl : tactic => `(refine_lift' have $d:haveDecl; ?_)
/-- Similar to `have`, but using `refine'` -/
macro (priority := high) "have'" x:ident " := " p:term : tactic => `(have' $x : _ := $p)
/-- Similar to `let`, but using `refine'` -/
macro "let' " d:letDecl : tactic => `(refine_lift' let $d:letDecl; ?_)
/--
The left hand side of an induction arm, `| foo a b c` or `| @foo a b c`
where `foo` is a constructor of the inductive type and `a b c` are the arguments
to the contstructor.
-/
syntax inductionAltLHS := "| " (("@"? ident) <|> hole) (ident <|> hole)*
/--
In induction alternative, which can have 1 or more cases on the left
and `_`, `?_`, or a tactic sequence after the `=>`.
-/
syntax inductionAlt := ppDedent(ppLine) inductionAltLHS+ " => " (hole <|> syntheticHole <|> tacticSeq)
/--
After `with`, there is an optional tactic that runs on all branches, and
then a list of alternatives.
-/
syntax inductionAlts := "with " (tactic)? withPosition((colGe inductionAlt)+)
/--
Assuming `x` is a variable in the local context with an inductive type,
`induction x` applies induction on `x` to the main goal,
producing one goal for each constructor of the inductive type,
in which the target is replaced by a general instance of that constructor
and an inductive hypothesis is added for each recursive argument to the constructor.
If the type of an element in the local context depends on `x`,
that element is reverted and reintroduced afterward,
so that the inductive hypothesis incorporates that hypothesis as well.
For example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`,
`induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`,
and one goal with hypotheses `h : P (Nat.succ a)` and `ih₁ : P a → Q a` and target `Q (Nat.succ a)`.
Here the names `a` and `ih₁` are chosen automatically and are not accessible.
You can use `with` to provide the variables names for each constructor.
- `induction e`, where `e` is an expression instead of a variable,
generalizes `e` in the goal, and then performs induction on the resulting variable.
- `induction e using r` allows the user to specify the principle of induction that should be used.
Here `r` should be a theorem whose result type must be of the form `C t`,
where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables
- `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context,
generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal.
In other words, the net effect is that each inductive hypothesis is generalized.
- Given `x : Nat`, `induction x with | zero => tac₁ | succ x' ih => tac₂`
uses tactic `tac₁` for the `zero` case, and `tac₂` for the `succ` case.
-/
syntax (name := induction) "induction " term,+ (" using " ident)?
("generalizing " (colGt term:max)+)? (inductionAlts)? : tactic
/-- A `generalize` argument, of the form `term = x` or `h : term = x`. -/
syntax generalizeArg := atomic(ident " : ")? term:51 " = " ident
/--
* `generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal
with a fresh hypothesis `x`s. If `h` is given, `h : e = x` is introduced as well.
* `generalize e = x at h₁ ... hₙ` also generalizes occurrences of `e`
inside `h₁`, ..., `hₙ`.
* `generalize e = x at *` will generalize occurrences of `e` everywhere.
-/
syntax (name := generalize) "generalize " generalizeArg,+ (location)? : tactic
/--
A `cases` argument, of the form `e` or `h : e` (where `h` asserts that
`e = cᵢ a b` for each constructor `cᵢ` of the inductive).
-/
syntax casesTarget := atomic(ident " : ")? term
/--
Assuming `x` is a variable in the local context with an inductive type,
`cases x` splits the main goal, producing one goal for each constructor of the
inductive type, in which the target is replaced by a general instance of that constructor.
If the type of an element in the local context depends on `x`,
that element is reverted and reintroduced afterward,
so that the case split affects that hypothesis as well.
`cases` detects unreachable cases and closes them automatically.
For example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`,
`cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`,
and one goal with hypothesis `h : P (Nat.succ a)` and target `Q (Nat.succ a)`.
Here the name `a` is chosen automatically and is not accessible.
You can use `with` to provide the variables names for each constructor.
- `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal,
and then cases on the resulting variable.
- Given `as : List α`, `cases as with | nil => tac₁ | cons a as' => tac₂`,
uses tactic `tac₁` for the `nil` case, and `tac₂` for the `cons` case,
and `a` and `as'` are used as names for the new variables introduced.
- `cases h : e`, where `e` is a variable or an expression,
performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis,
where `...` is the constructor instance for that particular case.
-/
syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic
/-- `rename_i x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/
syntax (name := renameI) "rename_i " (colGt binderIdent)+ : tactic
/--
`repeat tac` applies `tac` to main goal. If the application succeeds,
the tactic is applied recursively to the generated subgoals until it eventually fails.
-/
syntax "repeat " tacticSeq : tactic
macro_rules
| `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip)
/--
`trivial` tries different simple tactics (e.g., `rfl`, `contradiction`, ...)
to close the current goal.
You can use the command `macro_rules` to extend the set of tactics used. Example:
```
macro_rules | `(tactic| trivial) => `(tactic| simp)
```
-/
syntax "trivial" : tactic
/--
The `split` tactic is useful for breaking nested if-then-else and match expressions in cases.
For a `match` expression with `n` cases, the `split` tactic generates at most `n` subgoals
-/
syntax (name := split) "split " (colGt term)? (location)? : tactic
/-- `dbg_trace "foo"` prints `foo` when elaborated.
Useful for debugging tactic control flow:
```
example : False ∨ True := by
first
| apply Or.inl; trivial; dbg_trace "left"
| apply Or.inr; trivial; dbg_trace "right"
```
-/
syntax (name := dbgTrace) "dbg_trace " str : tactic
/--
`stop` is a helper tactic for "discarding" the rest of a proof:
it is defined as `repeat sorry`.
It is useful when working on the middle of a complex proofs,
and less messy than commenting the remainder of the proof.
-/
macro "stop" tacticSeq : tactic => `(repeat sorry)
/--
The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`.
The premises of this hypothesis, either universal quantifications or
non-dependent implications, are instantiated by concrete terms coming
from arguments `a₁` ... `aₙ`.
The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ`
and tries to clear the previous one.
-/
syntax (name := specialize) "specialize " term : tactic
macro_rules | `(tactic| trivial) => `(tactic| assumption)
macro_rules | `(tactic| trivial) => `(tactic| rfl)
macro_rules | `(tactic| trivial) => `(tactic| contradiction)
macro_rules | `(tactic| trivial) => `(tactic| decide)
macro_rules | `(tactic| trivial) => `(tactic| apply True.intro)
macro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial)
/--
`unhygienic tacs` runs `tacs` with name hygiene disabled.
This means that tactics that would normally create inaccessible names will instead
make regular variables. **Warning**: Tactics may change their variable naming
strategies at any time, so code that depends on autogenerated names is brittle.
Users should try not to use `unhygienic` if possible.
```
example : ∀ x : Nat, x = x := by unhygienic
intro -- x would normally be intro'd as inaccessible
exact Eq.refl x -- refer to x
```
-/
macro "unhygienic " t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t)
/-- `fail msg` is a tactic that always fails, and produces an error using the given message. -/
syntax (name := fail) "fail " (str)? : tactic
/--
`checkpoint tac` acts the same as `tac`, but it caches the input and output of `tac`,
and if the file is re-elaborated and the input matches, the tactic is not re-run and
its effects are reapplied to the state. This is useful for improving responsiveness
when working on a long tactic proof, by wrapping expensive tactics with `checkpoint`.
See the `save` tactic, which may be more convenient to use.
(TODO: do this automatically and transparently so that users don't have to use
this combinator explicitly.)
-/
syntax (name := checkpoint) "checkpoint " tacticSeq : tactic
/--
`save` is defined to be the same as `skip`, but the elaborator has
special handling for occurrences of `save` in tactic scripts and will transform
`by tac1; save; tac2` to `by (checkpoint tac1); tac2`, meaning that the effect of `tac1`
will be cached and replayed. This is useful for improving responsiveness
when working on a long tactic proof, by using `save` after expensive tactics.
(TODO: do this automatically and transparently so that users don't have to use
this combinator explicitly.)
-/
macro (name := save) "save" : tactic => `(skip)
/--
The tactic `sleep ms` sleeps for `ms` milliseconds and does nothing.
It is used for debugging purposes only.
-/
syntax (name := sleep) "sleep" num : tactic
/--
`exists e₁, e₂, ...` is shorthand for `refine ⟨e₁, e₂, ...⟩; try trivial`.
It is useful for existential goals.
-/
macro "exists " es:term,+ : tactic =>
`(tactic| (refine ⟨$es,*, ?_⟩; try trivial))
/--
Apply congruence (recursively) to goals of the form `⊢ f as = f bs` and `⊢ HEq (f as) (f bs)`.
The optional parameter is the depth of the recursive applications.
This is useful when `congr` is too aggressive in breaking down the goal.
For example, given `⊢ f (g (x + y)) = f (g (y + x))`,
`congr` produces the goals `⊢ x = y` and `⊢ y = x`,
while `congr 2` produces the intended `⊢ x + y = y + x`.
-/
syntax (name := congr) "congr " (num)? : tactic
end Tactic
namespace Attr
/--
Theorems tagged with the `simp` attribute are by the simplifier
(i.e., the `simp` tactic, and its variants) to simplify expressions occurring in your goals.
We call theorems tagged with the `simp` attribute "simp theorems" or "simp lemmas".
Lean maintains a database/index containing all active simp theorems.
Here is an example of a simp theorem.
```lean
@[simp] theorem ne_eq (a b : α) : (a ≠ b) = Not (a = b) := rfl
```
This simp theorem instructs the simplifier to replace instances of the term
`a ≠ b` (e.g. `x + 0 ≠ y`) with `Not (a = b)` (e.g., `Not (x + 0 = y)`).
The simplifier applies simp theorems in one direction only:
if `A = B` is a simp theorem, then `simp` replaces `A`s with `B`s,
but it doesn't replace `B`s with `A`s. Hence a simp theorem should have the
property that its right-hand side is "simpler" than its left-hand side.
In particular, `=` and `↔` should not be viewed as symmetric operators in this situation.
The following would be a terrible simp theorem (if it were even allowed):
```lean
@[simp] lemma mul_right_inv_bad (a : G) : 1 = a * a⁻¹ := ...
```
Replacing 1 with a * a⁻¹ is not a sensible default direction to travel.
Even worse would be a theorem that causes expressions to grow without bound,
causing simp to loop forever.
By default the simplifier applies `simp` theorems to an expression `e`
after its sub-expressions have been simplified.
We say it performs a bottom-up simplification.
You can instruct the simplifier to apply a theorem before its sub-expressions
have been simplified by using the modifier `↓`. Here is an example
```lean
@[simp↓] theorem not_and_eq (p q : Prop) : (¬ (p ∧ q)) = (¬p ∨ ¬q) :=
```
When multiple simp theorems are applicable, the simplifier uses the one with highest priority.
If there are several with the same priority, it is uses the "most recent one". Example:
```lean
@[simp high] theorem cond_true (a b : α) : cond true a b = a := rfl
@[simp low+1] theorem or_true (p : Prop) : (p ∨ True) = True :=
propext <| Iff.intro (fun _ => trivial) (fun _ => Or.inr trivial)
@[simp 100] theorem ite_self {d : Decidable c} (a : α) : ite c a a = a := by
cases d <;> rfl
```
-/
syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr
end Attr
end Parser
end Lean
/--
`‹t›` resolves to an (arbitrary) hypothesis of type `t`.
It is useful for referring to hypotheses without accessible names.
`t` may contain holes that are solved by unification with the expected type;
in particular, `‹_›` is a shortcut for `by assumption`.
-/
macro "‹" type:term "›" : term => `((by assumption : $type))
/--
`get_elem_tactic_trivial` is an extensible tactic automatically called
by the notation `arr[i]` to prove any side conditions that arise when
constructing the term (e.g. the index is in bounds of the array).
The default behavior is to just try `trivial` (which handles the case
where `i < arr.size` is in the context) and `simp_arith`
(for doing linear arithmetic in the index).
-/
syntax "get_elem_tactic_trivial" : tactic
macro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| trivial)
macro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| simp (config := { arith := true }); done)
/--
`get_elem_tactic` is the tactic automatically called by the notation `arr[i]`
to prove any side conditions that arise when constructing the term
(e.g. the index is in bounds of the array). It just delegates to
`get_elem_tactic_trivial` and gives a diagnostic error message otherwise;
users are encouraged to extend `get_elem_tactic_trivial` instead of this tactic.
-/
macro "get_elem_tactic" : tactic =>
`(first
| get_elem_tactic_trivial
| fail "failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is perfomed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid"
)
@[inheritDoc getElem]
macro:max x:term noWs "[" i:term "]" : term => `(getElem $x $i (by get_elem_tactic))
@[inheritDoc getElem]
macro x:term noWs "[" i:term "]'" h:term:max : term => `(getElem $x $i $h)
|
87bf19717025812268f58158b8f565507a890df8 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Data/Occurrences.lean | 91e5680500a61740cfb1614b79c3dd7d97fcfaae | [
"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 | 789 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
namespace Lean
inductive Occurrences
| all
| pos (idxs : List Nat)
| neg (idxs : List Nat)
namespace Occurrences
instance : Inhabited Occurrences := ⟨all⟩
def contains : Occurrences → Nat → Bool
| all, _ => true
| pos idxs, idx => idxs.contains idx
| neg idxs, idx => !idxs.contains idx
def isAll : Occurrences → Bool
| all => true
| _ => false
def beq : Occurrences → Occurrences → Bool
| all, all => true
| pos is₁, pos is₂ => is₁ == is₂
| neg is₁, neg is₂ => is₁ == is₂
| _, _ => false
instance : HasBeq Occurrences := ⟨beq⟩
end Occurrences
end Lean
|
5b77014499d485420f01921089f4dbc0dba259e7 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/category/Group/default_auto.lean | 986dd3879c00e7b53c1bba082455bf529e141a65 | [] | 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 | 300 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.category.Group.limits
import Mathlib.algebra.category.Group.colimits
import Mathlib.algebra.category.Group.preadditive
import Mathlib.algebra.category.Group.zero
import Mathlib.PostPort
namespace Mathlib
end Mathlib |
11f2609d155b6bddabffbe07dfbe8234daba99d6 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/propagateExpectedType.lean | 4ac15af34be714ec998b54a9413c3913164e9529 | [
"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 | 1,582 | lean | variable {α : Type _} (r : α → α → Prop) (π : α → α)
inductive rel : α → α → Prop
| of {x y} : r x y → rel x y
| compat {x y} : rel x y → rel (π x) (π y)
| refl (x) : rel x x
| symm {x y} : rel x y → rel y x
| trans {x y z} : rel x y → rel y z → rel x z
def thing : Setoid α := ⟨rel r π, ⟨rel.refl, rel.symm, rel.trans⟩⟩
def β := Quotient (thing r π)
variable {γ : Type _}
def Quotient.mk' {s : Setoid α} (a : α) : Quotient s :=
Quotient.mk a
def Quotient.sound' {s : Setoid α} {a b : α} (h : a ≈ b) : Quotient.mk a = Quotient.mk b :=
Quotient.sound h
def δ0 : β r π → β r π :=
Quotient.lift
(s := thing r π)
(Quotient.mk' $ π ·)
fun x y h => Quotient.sound' (by exact rel.compat h)
def δ1 : β r π → β r π :=
Quotient.lift
(s := thing r π)
(Quotient.mk' $ π ·)
fun x y h => Quotient.sound' (rel.compat h)
def δ2 : β r π → β r π :=
Quotient.lift
(s := thing r π)
(Quotient.mk' $ π ·)
(by exact fun x y h => Quotient.sound' (rel.compat h))
def Quotient.lift' {α β} {s : Setoid α} (f : α → β) (h : (a b : α) → a ≈ b → f a = f b) (q : Quotient s) : β :=
Quotient.lift f h q
def δ3 : β r π → β r π :=
Quotient.lift'
(Quotient.mk' $ π ·)
fun x y h => Quotient.sound' (rel.compat h)
def δ4 : β r π → β r π :=
@Quotient.lift _ _
(thing r π)
(Quotient.mk' $ π ·)
(fun x y h => Quotient.sound' (rel.compat h))
def δ5 : β r π → β r π :=
@Quotient.lift' _ _ _
(Quotient.mk' $ π ·)
(fun x y h => Quotient.sound' (rel.compat h))
|
01b9cd17e594908452703ab8b6eb6235dc2000d7 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/order/bounded_order.lean | 11ae36605b5690891d19aa59523874c3f2dff7d4 | [
"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 | 46,371 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.option.basic
import logic.nontrivial
import order.lattice
import order.max
import tactic.pi_instances
/-!
# ⊤ and ⊥, bounded lattices and variants
This file defines top and bottom elements (greatest and least elements) of a type, the bounded
variants of different kinds of lattices, sets up the typeclass hierarchy between them and provides
instances for `Prop` and `fun`.
## Main declarations
* `has_<top/bot> α`: Typeclasses to declare the `⊤`/`⊥` notation.
* `order_<top/bot> α`: Order with a top/bottom element.
* `bounded_order α`: Order with a top and bottom element.
* `with_<top/bot> α`: Equips `option α` with the order on `α` plus `none` as the top/bottom element.
* `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a
non distributive lattice, an element can have several complements.
* `is_complemented α`: Typeclass stating that any element of a lattice has a complement.
## Common lattices
* Distributive lattices with a bottom element. Notated by `[distrib_lattice α] [order_bot α]`
It captures the properties of `disjoint` that are common to `generalized_boolean_algebra` and
`distrib_lattice` when `order_bot`.
* Bounded and distributive lattice. Notated by `[distrib_lattice α] [bounded_order α]`.
Typical examples include `Prop` and `set α`.
## Implementation notes
We didn't prove things about `[distrib_lattice α] [order_top α]` because the dual notion of
`disjoint` isn't really used anywhere.
-/
/-! ### Top, bottom element -/
set_option old_structure_cmd true
universes u v
variables {α : Type u} {β : Type v}
/-- Typeclass for the `⊤` (`\top`) notation -/
@[notation_class] class has_top (α : Type u) := (top : α)
/-- Typeclass for the `⊥` (`\bot`) notation -/
@[notation_class] class has_bot (α : Type u) := (bot : α)
notation `⊤` := has_top.top
notation `⊥` := has_bot.bot
@[priority 100] instance has_top_nonempty (α : Type u) [has_top α] : nonempty α := ⟨⊤⟩
@[priority 100] instance has_bot_nonempty (α : Type u) [has_bot α] : nonempty α := ⟨⊥⟩
attribute [pattern] has_bot.bot has_top.top
/-- An order is an `order_top` if it has a greatest element.
We state this using a data mixin, holding the value of `⊤` and the greatest element constraint. -/
@[ancestor has_top]
class order_top (α : Type u) [has_le α] extends has_top α :=
(le_top : ∀ a : α, a ≤ ⊤)
section order_top
section has_le
variables [has_le α] [order_top α] {a : α}
@[simp] lemma le_top : a ≤ ⊤ := order_top.le_top a
@[simp] lemma is_top_top : is_top (⊤ : α) := λ _, le_top
end has_le
section preorder
variables [preorder α] [order_top α] {a b : α}
@[simp] lemma is_max_top : is_max (⊤ : α) := is_top_top.is_max
@[simp] lemma not_top_lt : ¬ ⊤ < a := is_max_top.not_lt
lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := (h.trans_le le_top).ne
alias ne_top_of_lt ← has_lt.lt.ne_top
end preorder
variables [partial_order α] [order_top α] {a b : α}
@[simp] lemma is_max_iff_eq_top : is_max a ↔ a = ⊤ :=
⟨λ h, h.eq_of_le le_top, λ h b _, h.symm ▸ le_top⟩
@[simp] lemma is_top_iff_eq_top : is_top a ↔ a = ⊤ :=
⟨λ h, h.is_max.eq_of_le le_top, λ h b, h.symm ▸ le_top⟩
alias is_max_iff_eq_top ↔ _ is_max.eq_top
alias is_top_iff_eq_top ↔ _ is_top.eq_top
@[simp] lemma top_le_iff : ⊤ ≤ a ↔ a = ⊤ := le_top.le_iff_eq.trans eq_comm
lemma top_unique (h : ⊤ ≤ a) : a = ⊤ := le_top.antisymm h
lemma eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := top_le_iff.symm
lemma eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_unique $ h₂ ▸ h
lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := le_top.lt_iff_ne
lemma eq_top_or_lt_top (a : α) : a = ⊤ ∨ a < ⊤ := le_top.eq_or_lt
lemma ne.lt_top (h : a ≠ ⊤) : a < ⊤ := lt_top_iff_ne_top.mpr h
lemma ne.lt_top' (h : ⊤ ≠ a) : a < ⊤ := h.symm.lt_top
lemma ne_top_of_le_ne_top (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := (hab.trans_lt hb.lt_top).ne
lemma eq_top_of_maximal (h : ∀ b, ¬ a < b) : a = ⊤ :=
or.elim (lt_or_eq_of_le le_top) (λ hlt, absurd hlt (h ⊤)) (λ he, he)
end order_top
lemma strict_mono.maximal_preimage_top [linear_order α] [preorder β] [order_top β]
{f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) :
x ≤ a :=
H.maximal_of_maximal_image (λ p, by { rw h_top, exact le_top }) x
theorem order_top.ext_top {α} {hA : partial_order α} (A : order_top α)
{hB : partial_order α} (B : order_top α)
(H : ∀ x y : α, (by haveI := hA; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊤ : α) = ⊤ :=
top_unique $ by rw ← H; apply le_top
theorem order_top.ext {α} [partial_order α] {A B : order_top α} : A = B :=
begin
have tt := order_top.ext_top A B (λ _ _, iff.rfl),
casesI A with _ ha, casesI B with _ hb,
congr,
exact le_antisymm (hb _) (ha _)
end
/-- An order is an `order_bot` if it has a least element.
We state this using a data mixin, holding the value of `⊥` and the least element constraint. -/
@[ancestor has_bot]
class order_bot (α : Type u) [has_le α] extends has_bot α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section order_bot
section has_le
variables [has_le α] [order_bot α] {a : α}
@[simp] lemma bot_le : ⊥ ≤ a := order_bot.bot_le a
@[simp] lemma is_bot_bot : is_bot (⊥ : α) := λ _, bot_le
end has_le
section preorder
variables [preorder α] [order_bot α] {a b : α}
@[simp] lemma is_min_bot : is_min (⊥ : α) := is_bot_bot.is_min
@[simp] lemma not_lt_bot : ¬ a < ⊥ := is_min_bot.not_lt
lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := (bot_le.trans_lt h).ne'
alias ne_bot_of_gt ← has_lt.lt.ne_bot
end preorder
variables [partial_order α] [order_bot α] {a b : α}
@[simp] lemma is_min_iff_eq_bot : is_min a ↔ a = ⊥ :=
⟨λ h, h.eq_of_ge bot_le, λ h b _, h.symm ▸ bot_le⟩
@[simp] lemma is_bot_iff_eq_bot : is_bot a ↔ a = ⊥ :=
⟨λ h, h.is_min.eq_of_ge bot_le, λ h b, h.symm ▸ bot_le⟩
alias is_min_iff_eq_bot ↔ _ is_min.eq_bot
alias is_bot_iff_eq_bot ↔ _ is_bot.eq_bot
@[simp] lemma le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := bot_le.le_iff_eq
lemma bot_unique (h : a ≤ ⊥) : a = ⊥ := h.antisymm bot_le
lemma eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := le_bot_iff.symm
lemma eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := bot_unique $ h₂ ▸ h
lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := bot_le.lt_iff_ne.trans ne_comm
lemma eq_bot_or_bot_lt (a : α) : a = ⊥ ∨ ⊥ < a := bot_le.eq_or_gt
lemma eq_bot_of_minimal (h : ∀ b, ¬ b < a) : a = ⊥ := (eq_bot_or_bot_lt a).resolve_right (h ⊥)
lemma ne.bot_lt (h : a ≠ ⊥) : ⊥ < a := bot_lt_iff_ne_bot.mpr h
lemma ne.bot_lt' (h : ⊥ ≠ a) : ⊥ < a := h.symm.bot_lt
lemma ne_bot_of_le_ne_bot (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := (hb.bot_lt.trans_le hab).ne'
end order_bot
lemma strict_mono.minimal_preimage_bot [linear_order α] [partial_order β] [order_bot β]
{f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) :
a ≤ x :=
H.minimal_of_minimal_image (λ p, by { rw h_bot, exact bot_le }) x
theorem order_bot.ext_bot {α} {hA : partial_order α} (A : order_bot α)
{hB : partial_order α} (B : order_bot α)
(H : ∀ x y : α, (by haveI := hA; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊥ : α) = ⊥ :=
bot_unique $ by rw ← H; apply bot_le
theorem order_bot.ext {α} [partial_order α] {A B : order_bot α} : A = B :=
begin
have tt := order_bot.ext_bot A B (λ _ _, iff.rfl),
casesI A with a ha, casesI B with b hb,
congr,
exact le_antisymm (ha _) (hb _)
end
section semilattice_sup_top
variables [semilattice_sup α] [order_top α] {a : α}
@[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
section semilattice_sup_bot
variables [semilattice_sup α] [order_bot α] {a b : α}
@[simp] theorem bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp] theorem sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by rw [eq_bot_iff, sup_le_iff]; simp
end semilattice_sup_bot
section semilattice_inf_top
variables [semilattice_inf α] [order_top α] {a b : α}
@[simp] theorem top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp] theorem inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by rw [eq_top_iff, le_inf_iff]; simp
end semilattice_inf_top
section semilattice_inf_bot
variables [semilattice_inf α] [order_bot α] {a : α}
@[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/-! ### Bounded order -/
/-- A bounded order describes an order `(≤)` with a top and bottom element,
denoted `⊤` and `⊥` respectively. -/
@[ancestor order_top order_bot]
class bounded_order (α : Type u) [has_le α] extends order_top α, order_bot α.
theorem bounded_order.ext {α} [partial_order α] {A B : bounded_order α} : A = B :=
begin
have ht : @bounded_order.to_order_top α _ A = @bounded_order.to_order_top α _ B := order_top.ext,
have hb : @bounded_order.to_order_bot α _ A = @bounded_order.to_order_bot α _ B := order_bot.ext,
casesI A,
casesI B,
injection ht with h,
injection hb with h',
convert rfl,
{ exact h.symm },
{ exact h'.symm }
end
/-- Propositions form a distributive lattice. -/
instance Prop.distrib_lattice : distrib_lattice Prop :=
{ le := λ a b, a → b,
le_refl := λ _, id,
le_trans := λ a b c f g, g ∘ f,
le_antisymm := λ a b Hab Hba, propext ⟨Hab, Hba⟩,
sup := or,
le_sup_left := @or.inl,
le_sup_right := @or.inr,
sup_le := λ a b c, or.rec,
inf := and,
inf_le_left := @and.left,
inf_le_right := @and.right,
le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha),
le_sup_inf := λ a b c H, or_iff_not_imp_left.2 $
λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩ }
/-- Propositions form a bounded order. -/
instance Prop.bounded_order : bounded_order Prop :=
{ top := true,
le_top := λ a Ha, true.intro,
bot := false,
bot_le := @false.elim }
instance Prop.le_is_total : is_total Prop (≤) :=
⟨λ p q, by { change (p → q) ∨ (q → p), tauto! }⟩
noncomputable instance Prop.linear_order : linear_order Prop :=
by classical; exact lattice.to_linear_order Prop
@[simp] lemma le_Prop_eq : ((≤) : Prop → Prop → Prop) = (→) := rfl
@[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl
@[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl
section logic
variable [preorder α]
theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λ x, p x ∧ q x) :=
λ a b h, and.imp (m_p h) (m_q h)
-- Note: by finish [monotone] doesn't work
theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λ x, p x ∨ q x) :=
λ a b h, or.imp (m_p h) (m_q h)
end logic
/-! ### Function lattices -/
namespace pi
variables {ι : Type*} {α' : ι → Type*}
instance [Π i, has_bot (α' i)] : has_bot (Π i, α' i) := ⟨λ i, ⊥⟩
@[simp] lemma bot_apply [Π i, has_bot (α' i)] (i : ι) : (⊥ : Π i, α' i) i = ⊥ := rfl
lemma bot_def [Π i, has_bot (α' i)] : (⊥ : Π i, α' i) = λ i, ⊥ := rfl
instance [Π i, has_top (α' i)] : has_top (Π i, α' i) := ⟨λ i, ⊤⟩
@[simp] lemma top_apply [Π i, has_top (α' i)] (i : ι) : (⊤ : Π i, α' i) i = ⊤ := rfl
lemma top_def [Π i, has_top (α' i)] : (⊤ : Π i, α' i) = λ i, ⊤ := rfl
instance [Π i, has_le (α' i)] [Π i, order_top (α' i)] : order_top (Π i, α' i) :=
{ le_top := λ _ _, le_top, ..pi.has_top }
instance [Π i, has_le (α' i)] [Π i, order_bot (α' i)] : order_bot (Π i, α' i) :=
{ bot_le := λ _ _, bot_le, ..pi.has_bot }
instance [Π i, has_le (α' i)] [Π i, bounded_order (α' i)] :
bounded_order (Π i, α' i) :=
{ ..pi.order_top, ..pi.order_bot }
end pi
section subsingleton
variables [partial_order α] [bounded_order α]
lemma eq_bot_of_bot_eq_top (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊥ : α) :=
eq_bot_mono le_top (eq.symm hα)
lemma eq_top_of_bot_eq_top (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊤ : α) :=
eq_top_mono bot_le hα
lemma subsingleton_of_top_le_bot (h : (⊤ : α) ≤ (⊥ : α)) :
subsingleton α :=
⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩
lemma subsingleton_of_bot_eq_top (hα : (⊥ : α) = (⊤ : α)) :
subsingleton α :=
subsingleton_of_top_le_bot (ge_of_eq hα)
lemma subsingleton_iff_bot_eq_top :
(⊥ : α) = (⊤ : α) ↔ subsingleton α :=
⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩
end subsingleton
/-! ### `with_bot`, `with_top` -/
/-- Attach `⊥` to a type. -/
def with_bot (α : Type*) := option α
namespace with_bot
meta instance {α} [has_to_format α] : has_to_format (with_bot α) :=
{ to_format := λ x,
match x with
| none := "⊥"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_bot α) := ⟨some⟩
instance has_bot : has_bot (with_bot α) := ⟨none⟩
instance : inhabited (with_bot α) := ⟨⊥⟩
lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl
lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl
@[simp] theorem bot_ne_coe (a : α) : ⊥ ≠ (a : with_bot α) .
@[simp] theorem coe_ne_bot (a : α) : (a : with_bot α) ≠ ⊥ .
/-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/
@[elab_as_eliminator]
def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) :
Π (n : with_bot α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
lemma ne_bot_iff_exists {x : with_bot α} : x ≠ ⊥ ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
/-- Deconstruct a `x : with_bot α` to the underlying value in `α`, given a proof that `x ≠ ⊥`. -/
def unbot : Π (x : with_bot α), x ≠ ⊥ → α
| ⊥ h := absurd rfl h
| (some x) h := x
@[simp] lemma coe_unbot {α : Type*} (x : with_bot α) (h : x ≠ ⊥) :
(x.unbot h : with_bot α) = x :=
by { cases x, simpa using h, refl, }
@[simp] lemma unbot_coe (x : α) (h : (x : with_bot α) ≠ ⊥ := coe_ne_bot _) :
(x : with_bot α).unbot h = x := rfl
@[priority 10]
instance has_le [has_le α] : has_le (with_bot α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b }
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_bot α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
lemma none_lt_some [has_lt α] (a : α) :
@has_lt.lt (with_bot α) _ none (some a) :=
⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩
lemma not_lt_none [has_lt α] (a : option α) : ¬ @has_lt.lt (with_bot α) _ a none :=
λ ⟨_, h, _⟩, option.not_mem_none _ h
lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := none_lt_some a
instance : can_lift (with_bot α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊥,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_bot α) :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := by intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(≤), (<)];
split; refl,
le_refl := λ o a ha, ⟨a, ha, le_rfl⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha,
let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in
⟨c, hc, le_trans ab bc⟩ }
instance partial_order [partial_order α] : partial_order (with_bot α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₁ with a,
{ cases o₂ with b, {refl},
rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩,
rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_bot.preorder }
instance order_bot [has_le α] : order_bot (with_bot α) :=
{ bot_le := λ a a' h, option.no_confusion h,
..with_bot.has_bot }
@[simp, norm_cast] theorem coe_le_coe [has_le α] {a b : α} :
(a : with_bot α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe
theorem coe_le [has_le α] {a b : α} :
∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b)
| _ rfl := coe_le_coe
@[norm_cast]
lemma coe_lt_coe [has_lt α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some
lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b
| (some a) b := le_refl a
| none b := λ _ h, option.no_confusion h
@[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl
lemma get_or_else_bot_le_iff [has_le α] [order_bot α] {a : with_bot α} {b : α} :
a.get_or_else ⊥ ≤ b ↔ a ≤ b :=
by cases a; simp [none_eq_bot, some_eq_coe]
instance decidable_le [has_le α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤)
| none x := is_true $ λ a h, option.no_confusion h
| (some x) (some y) :=
if h : x ≤ y
then is_true (some_le_some.2 h)
else is_false $ by simp *
| (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<)
| none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩
| (some x) (some y) :=
if h : x < y
then is_true $ by simp *
else is_false $ by simp *
| x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩
instance [partial_order α] [is_total α (≤)] : is_total (with_bot α) (≤) :=
{ total := λ a b, match a, b with
| none , _ := or.inl bot_le
| _ , none := or.inr bot_le
| some x, some y := by simp only [some_le_some, total_of]
end }
instance semilattice_sup [semilattice_sup α] : semilattice_sup (with_bot α) :=
{ sup := option.lift_or_get (⊔),
le_sup_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
le_sup_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₁ with b; cases o₂ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, sup_le h₁' h₂⟩ }
end,
..with_bot.order_bot,
..with_bot.partial_order }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_bot α) = a ⊔ b := rfl
instance semilattice_inf [semilattice_inf α] : semilattice_inf (with_bot α) :=
{ inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)),
inf_le_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_left⟩
end,
inf_le_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_right⟩
end,
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, le_inf ab ac⟩
end,
..with_bot.order_bot,
..with_bot.partial_order }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_bot α) = a ⊓ b := rfl
instance lattice [lattice α] : lattice (with_bot α) :=
{ ..with_bot.semilattice_sup, ..with_bot.semilattice_inf }
instance le_is_total [preorder α] [is_total α (≤)] : is_total (with_bot α) (≤) :=
⟨λ o₁ o₂,
begin
cases o₁ with a, {exact or.inl bot_le},
cases o₂ with b, {exact or.inr bot_le},
exact (total_of (≤) a b).imp some_le_some.mpr some_le_some.mpr,
end⟩
instance linear_order [linear_order α] : linear_order (with_bot α) :=
lattice.to_linear_order _
@[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used
lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_bot α) = min x y := rfl
@[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used
lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_bot α) = max x y := rfl
instance order_top [has_le α] [order_top α] : order_top (with_bot α) :=
{ top := some ⊤,
le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩ }
instance bounded_order [has_le α] [order_top α] : bounded_order (with_bot α) :=
{ ..with_bot.order_top, ..with_bot.order_bot }
lemma well_founded_lt [preorder α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_bot α → with_bot α → Prop) :=
have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ :=
acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim),
⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot)
(λ b, well_founded.induction h b
(show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) b,
from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot)
(λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩
instance densely_ordered [has_lt α] [densely_ordered α] [no_min_order α] :
densely_ordered (with_bot α) :=
⟨ λ a b,
match a, b with
| a, none := λ h : a < ⊥, (not_lt_none _ h).elim
| none, some b := λ h, let ⟨a, ha⟩ := exists_lt b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩
| some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
instance [has_lt α] [no_max_order α] [nonempty α] : no_max_order (with_bot α) :=
⟨begin
apply with_bot.rec_bot_coe,
{ apply ‹nonempty α›.elim,
exact λ a, ⟨a, with_bot.bot_lt_coe a⟩, },
{ intro a,
obtain ⟨b, ha⟩ := exists_gt a,
exact ⟨b, with_bot.coe_lt_coe.mpr ha⟩, }
end⟩
end with_bot
--TODO(Mario): Construct using order dual on with_bot
/-- Attach `⊤` to a type. -/
def with_top (α : Type*) := option α
namespace with_top
meta instance {α} [has_to_format α] : has_to_format (with_top α) :=
{ to_format := λ x,
match x with
| none := "⊤"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_top α) := ⟨some⟩
instance has_top : has_top (with_top α) := ⟨none⟩
instance : inhabited (with_top α) := ⟨⊤⟩
lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl
lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl
/-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/
@[elab_as_eliminator]
def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) :
Π (n : with_top α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) .
@[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ .
lemma ne_top_iff_exists {x : with_top α} : x ≠ ⊤ ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
/-- Deconstruct a `x : with_top α` to the underlying value in `α`, given a proof that `x ≠ ⊤`. -/
def untop : Π (x : with_top α), x ≠ ⊤ → α :=
with_bot.unbot
@[simp] lemma coe_untop {α : Type*} (x : with_top α) (h : x ≠ ⊤) :
(x.untop h : with_top α) = x :=
by { cases x, simpa using h, refl, }
@[simp] lemma untop_coe (x : α) (h : (x : with_top α) ≠ ⊤ := coe_ne_top) :
(x : with_top α).untop h = x := rfl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_top α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a }
@[priority 10]
instance has_le [has_le α] : has_le (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b :=
by simp [(≤)]
@[simp] theorem le_none [has_le α] {a : with_top α} :
@has_le.le (with_top α) _ a none :=
by simp [(≤)]
@[simp] theorem some_lt_none [has_lt α] (a : α) :
@has_lt.lt (with_top α) _ (some a) none :=
by simp [(<)]; existsi a; refl
@[simp] theorem not_none_lt [has_lt α] (a : option α) : ¬ @has_lt.lt (with_top α) _ none a :=
λ ⟨_, h, _⟩, option.not_mem_none _ h
instance : can_lift (with_top α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊤,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a,
lt := (<),
lt_iff_le_not_le := by { intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<),(≤)] },
le_refl := λ o a ha, ⟨a, ha, le_rfl⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc,
let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in
⟨a, ha, le_trans ab bc⟩, }
instance partial_order [partial_order α] : partial_order (with_top α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₂ with b,
{ cases o₁ with a, {refl},
rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩,
rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_top.preorder }
instance order_top [has_le α] : order_top (with_top α) :=
{ le_top := λ a a' h, option.no_confusion h,
.. with_top.has_top }
@[simp, norm_cast] theorem coe_le_coe [has_le α] {a b : α} :
(a : with_top α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩
theorem le_coe [has_le α] {a b : α} :
∀ {o : option α}, a ∈ o →
(@has_le.le (with_top α) _ o b ↔ a ≤ b)
| _ rfl := coe_le_coe
theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b)
| (some a) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b)
| (some b) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b)
| (some a) b := by simp [some_eq_coe, coe_eq_coe]
| none b := by simp [none_eq_top]
@[norm_cast]
lemma coe_lt_coe [has_lt α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some
lemma coe_lt_top [has_lt α] (a : α) : (a : with_top α) < ⊤ := some_lt_none a
theorem coe_lt_iff [preorder α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b)
| (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe]
| none := by simp [none_eq_top, coe_lt_top]
lemma not_top_le_coe [preorder α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a :=
λ h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim
instance decidable_le [has_le α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) :=
λ x y, @with_bot.decidable_le (order_dual α) _ _ y x
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) :=
λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x
instance [partial_order α] [is_total α (≤)] : is_total (with_top α) (≤) :=
{ total := λ a b, match a, b with
| none , _ := or.inr le_top
| _ , none := or.inl le_top
| some x, some y := by simp only [some_le_some, total_of]
end }
instance semilattice_inf [semilattice_inf α] : semilattice_inf (with_top α) :=
{ inf := option.lift_or_get (⊓),
inf_le_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
inf_le_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₂ with b; cases o₃ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, le_inf h₁' h₂⟩ }
end,
..with_top.partial_order }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl
instance semilattice_sup [semilattice_sup α] : semilattice_sup (with_top α) :=
{ sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)),
le_sup_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_left⟩
end,
le_sup_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_right⟩
end,
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, sup_le ab ac⟩
end,
..with_top.partial_order }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl
instance lattice [lattice α] : lattice (with_top α) :=
{ ..with_top.semilattice_sup, ..with_top.semilattice_inf }
instance le_is_total [preorder α] [is_total α (≤)] : is_total (with_top α) (≤) :=
⟨λ o₁ o₂,
begin
cases o₁ with a, {exact or.inr le_top},
cases o₂ with b, {exact or.inl le_top},
exact (total_of (≤) a b).imp some_le_some.mpr some_le_some.mpr,
end⟩
instance linear_order [linear_order α] : linear_order (with_top α) :=
lattice.to_linear_order _
@[simp, norm_cast]
lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_top α) = min x y := rfl
@[simp, norm_cast]
lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_top α) = max x y := rfl
instance order_bot [has_le α] [order_bot α] : order_bot (with_top α) :=
{ bot := some ⊥,
bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩ }
instance bounded_order [has_le α] [order_bot α] : bounded_order (with_top α) :=
{ ..with_top.order_top, ..with_top.order_bot }
lemma well_founded_lt {α : Type*} [preorder α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_top α → with_top α → Prop) :=
have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) :=
λ a, acc.intro _ (well_founded.induction h a
(show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) →
∀ y : with_top α, y < some b → acc (<) y,
from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim)
(λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))),
⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim)
(λ _ _, acc_some _))) acc_some⟩
instance densely_ordered [has_lt α] [densely_ordered α] [no_max_order α] :
densely_ordered (with_top α) :=
⟨ λ a b,
match a, b with
| none, a := λ h : ⊤ < a, (not_none_lt _ h).elim
| some a, none := λ h, let ⟨b, hb⟩ := exists_gt a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩
| some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_max_order α]
{a b : with_top α} :
(a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) :=
⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩,
λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩
instance [has_lt α] [no_min_order α] [nonempty α] : no_min_order (with_top α) :=
⟨begin
apply with_top.rec_top_coe,
{ apply ‹nonempty α›.elim,
exact λ a, ⟨a, with_top.coe_lt_top a⟩, },
{ intro a,
obtain ⟨b, ha⟩ := exists_lt a,
exact ⟨b, with_top.coe_lt_coe.mpr ha⟩, }
end⟩
end with_top
/-! ### Subtype, order dual, product lattices -/
namespace subtype
/-- A subtype remains a `⊥`-order if the property holds at `⊥`.
See note [reducible non-instances]. -/
@[reducible]
protected def order_bot [preorder α] [order_bot α] {P : α → Prop} (Pbot : P ⊥) :
order_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ _, bot_le }
/-- A subtype remains a `⊤`-order if the property holds at `⊤`.
See note [reducible non-instances]. -/
@[reducible]
protected def order_top [preorder α] [order_top α] {P : α → Prop} (Ptop : P ⊤) :
order_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ _, le_top }
end subtype
namespace order_dual
variable (α)
instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩
instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩
instance [has_le α] [order_bot α] : order_top (order_dual α) :=
{ le_top := @bot_le α _ _,
.. order_dual.has_top α }
instance [has_le α] [order_top α] : order_bot (order_dual α) :=
{ bot_le := @le_top α _ _,
.. order_dual.has_bot α }
instance [has_le α] [bounded_order α] : bounded_order (order_dual α) :=
{ .. order_dual.order_top α, .. order_dual.order_bot α }
end order_dual
namespace prod
variables (α β)
instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩
instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩
instance [has_le α] [has_le β] [order_top α] [order_top β] : order_top (α × β) :=
{ le_top := λ a, ⟨le_top, le_top⟩,
.. prod.has_top α β }
instance [has_le α] [has_le β] [order_bot α] [order_bot β] : order_bot (α × β) :=
{ bot_le := λ a, ⟨bot_le, bot_le⟩,
.. prod.has_bot α β }
instance [has_le α] [has_le β] [bounded_order α] [bounded_order β] : bounded_order (α × β) :=
{ .. prod.order_top α β, .. prod.order_bot α β }
end prod
/-! ### Disjointness and complements -/
section disjoint
section semilattice_inf_bot
variables [semilattice_inf α] [order_bot α]
/-- Two elements of a lattice are disjoint if their inf is the bottom element.
(This generalizes disjoint sets, viewed as members of the subset lattice.) -/
def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥
theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ :=
eq_bot_iff.2 h
theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ :=
eq_bot_iff.symm
theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a :=
by rw [disjoint, disjoint, inf_comm]
@[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a :=
disjoint.comm.1
lemma symmetric_disjoint : symmetric (disjoint : α → α → Prop) := disjoint.symm
@[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left
@[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right
theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂)
theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c :=
disjoint.mono h le_rfl
theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b :=
disjoint.mono le_rfl h
@[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ :=
by simp [disjoint]
lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b :=
by { intro h, rw [←h, disjoint_self] at hab, exact ha hab }
lemma disjoint.eq_bot_of_le {a b : α} (hab : disjoint a b) (h : a ≤ b) : a = ⊥ :=
eq_bot_iff.2 (by rwa ←inf_eq_left.2 h)
lemma disjoint_assoc {a b c : α} : disjoint (a ⊓ b) c ↔ disjoint a (b ⊓ c) :=
by rw [disjoint, disjoint, inf_assoc]
lemma disjoint.of_disjoint_inf_of_le {a b c : α} (h : disjoint (a ⊓ b) c) (hle : a ≤ c) :
disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_left.trans hle)]
lemma disjoint.of_disjoint_inf_of_le' {a b c : α} (h : disjoint (a ⊓ b) c) (hle : b ≤ c) :
disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_right.trans hle)]
end semilattice_inf_bot
section bounded_order
variables [lattice α] [bounded_order α] {a : α}
@[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff]
@[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff]
lemma eq_bot_of_disjoint_absorbs
{a b : α} (w : disjoint a b) (h : a ⊔ b = a) : b = ⊥ :=
begin
rw disjoint_iff at w,
rw [←w, right_eq_inf],
rwa sup_eq_left at h,
end
end bounded_order
section linear_order
variables [linear_order α]
lemma min_top_left [order_top α] (a : α) : min (⊤ : α) a = a := min_eq_right le_top
lemma min_top_right [order_top α] (a : α) : min a ⊤ = a := min_eq_left le_top
lemma max_bot_left [order_bot α] (a : α) : max (⊥ : α) a = a := max_eq_right bot_le
lemma max_bot_right [order_bot α] (a : α) : max a ⊥ = a := max_eq_left bot_le
-- `simp` can prove these, so they shouldn't be simp-lemmas.
lemma min_bot_left [order_bot α] (a : α) : min ⊥ a = ⊥ := min_eq_left bot_le
lemma min_bot_right [order_bot α] (a : α) : min a ⊥ = ⊥ := min_eq_right bot_le
lemma max_top_left [order_top α] (a : α) : max ⊤ a = ⊤ := max_eq_left le_top
lemma max_top_right [order_top α] (a : α) : max a ⊤ = ⊤ := max_eq_right le_top
@[simp] lemma min_eq_bot [order_bot α] {a b : α} : min a b = ⊥ ↔ a = ⊥ ∨ b = ⊥ :=
by { symmetry, cases le_total a b; simpa [*, min_eq_left, min_eq_right] using eq_bot_mono h }
@[simp] lemma max_eq_top [order_top α] {a b : α} : max a b = ⊤ ↔ a = ⊤ ∨ b = ⊤ :=
@min_eq_bot (order_dual α) _ _ a b
@[simp] lemma max_eq_bot [order_bot α] {a b : α} : max a b = ⊥ ↔ a = ⊥ ∧ b = ⊥ := sup_eq_bot_iff
@[simp] lemma min_eq_top [order_top α] {a b : α} : min a b = ⊤ ↔ a = ⊤ ∧ b = ⊤ := inf_eq_top_iff
end linear_order
section distrib_lattice_bot
variables [distrib_lattice α] [order_bot α] {a b c : α}
@[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c :=
by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff]
@[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c :=
by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff]
lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c :=
disjoint_sup_left.2 ⟨ha, hb⟩
lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) :=
disjoint_sup_right.2 ⟨hb, hc⟩
lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b :=
(λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le)
lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b :=
@le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le)
((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left))
end distrib_lattice_bot
section semilattice_inf_bot
variables [semilattice_inf α] [order_bot α] {a b : α} (c : α)
lemma disjoint.inf_left (h : disjoint a b) : disjoint (a ⊓ c) b :=
h.mono_left inf_le_left
lemma disjoint.inf_left' (h : disjoint a b) : disjoint (c ⊓ a) b :=
h.mono_left inf_le_right
lemma disjoint.inf_right (h : disjoint a b) : disjoint a (b ⊓ c) :=
h.mono_right inf_le_left
lemma disjoint.inf_right' (h : disjoint a b) : disjoint a (c ⊓ b) :=
h.mono_right inf_le_right
end semilattice_inf_bot
end disjoint
lemma inf_eq_bot_iff_le_compl [distrib_lattice α] [bounded_order α] {a b c : α}
(h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c :=
⟨λ h,
calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁]
... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left]
... ≤ c : by simp [h, inf_le_right],
λ h,
bot_unique $
calc a ⊓ b ≤ b ⊓ c : by { rw inf_comm, exact inf_le_inf_left _ h }
... = ⊥ : h₂⟩
section is_compl
/-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/
structure is_compl [lattice α] [bounded_order α] (x y : α) : Prop :=
(inf_le_bot : x ⊓ y ≤ ⊥)
(top_le_sup : ⊤ ≤ x ⊔ y)
namespace is_compl
section bounded_order
variables [lattice α] [bounded_order α] {x y z : α}
protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1
@[symm] protected lemma symm (h : is_compl x y) : is_compl y x :=
⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩
lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y :=
⟨le_of_eq h₁, le_of_eq h₂.symm⟩
lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot
lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup
open order_dual (to_dual)
lemma to_order_dual (h : is_compl x y) : is_compl (to_dual x) (to_dual y) := ⟨h.2, h.1⟩
end bounded_order
variables [distrib_lattice α] [bounded_order α] {a b x y z : α}
lemma inf_left_le_of_le_sup_right (h : is_compl x y) (hle : a ≤ b ⊔ y) : a ⊓ x ≤ b :=
calc a ⊓ x ≤ (b ⊔ y) ⊓ x : inf_le_inf hle le_rfl
... = (b ⊓ x) ⊔ (y ⊓ x) : inf_sup_right
... = b ⊓ x : by rw [h.symm.inf_eq_bot, sup_bot_eq]
... ≤ b : inf_le_left
lemma le_sup_right_iff_inf_left_le {a b} (h : is_compl x y) : a ≤ b ⊔ y ↔ a ⊓ x ≤ b :=
⟨h.inf_left_le_of_le_sup_right, h.symm.to_order_dual.inf_left_le_of_le_sup_right⟩
lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z :=
by rw [← le_bot_iff, ← h.le_sup_right_iff_inf_left_le, bot_sup_eq]
lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y :=
h.symm.inf_left_eq_bot_iff
lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z :=
by { rw disjoint_iff, exact h.inf_left_eq_bot_iff }
lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y :=
h.symm.disjoint_left_iff
lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y :=
h.disjoint_right_iff.symm
lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x :=
h.symm.le_left_iff
lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y :=
h.to_order_dual.le_left_iff
lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x :=
h.symm.left_le_iff
protected lemma antitone {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') :
y' ≤ y :=
h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _)
lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) :
y = z :=
le_antisymm (hxz.antitone hxy $ le_refl x) (hxy.antitone hxz $ le_refl x)
lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) :
x = y :=
hxz.symm.right_unique hyz.symm
lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊔ x') (y ⊓ y') :=
of_eq
(by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm,
h'.inf_eq_bot, inf_bot_eq])
(by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq,
sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq])
lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊓ x') (y ⊔ y') :=
(h.symm.sup_inf h'.symm).symm
end is_compl
lemma is_compl_bot_top [lattice α] [bounded_order α] : is_compl (⊥ : α) ⊤ :=
is_compl.of_eq bot_inf_eq sup_top_eq
lemma is_compl_top_bot [lattice α] [bounded_order α] : is_compl (⊤ : α) ⊥ :=
is_compl.of_eq inf_bot_eq top_sup_eq
section
variables [lattice α] [bounded_order α] {x : α}
lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ :=
sup_bot_eq.symm.trans h.sup_eq_top
lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ :=
eq_top_of_is_compl_bot h.symm
lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ :=
eq_top_of_is_compl_bot h.to_order_dual
lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ :=
eq_top_of_bot_is_compl h.to_order_dual
end
/-- A complemented bounded lattice is one where every element has a (not necessarily unique)
complement. -/
class is_complemented (α) [lattice α] [bounded_order α] : Prop :=
(exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b)
export is_complemented (exists_is_compl)
namespace is_complemented
variables [lattice α] [bounded_order α] [is_complemented α]
instance : is_complemented (order_dual α) :=
⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.to_order_dual⟩⟩
end is_complemented
end is_compl
section nontrivial
variables [partial_order α] [bounded_order α] [nontrivial α]
lemma bot_ne_top : (⊥ : α) ≠ ⊤ :=
λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_›
lemma top_ne_bot : (⊤ : α) ≠ ⊥ := bot_ne_top.symm
lemma bot_lt_top : (⊥ : α) < ⊤ := lt_top_iff_ne_top.2 bot_ne_top
end nontrivial
namespace bool
-- TODO: is this comment relevant now that `bounded_order` is factored out?
-- Could be generalised to `bounded_distrib_lattice` and `is_complemented`
instance : bounded_order bool :=
{ top := tt,
le_top := λ x, le_tt,
bot := ff,
bot_le := λ x, ff_le }
end bool
section bool
@[simp] lemma top_eq_tt : ⊤ = tt := rfl
@[simp] lemma bot_eq_ff : ⊥ = ff := rfl
end bool
|
dddb4bdbf73f2598e2f26b87a1fae3de7af94e4f | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /test/norm_num.lean | 5e7d81457b5ec5e10c6c9ffda743217539337f62 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 11,860 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Mario Carneiro
Tests for norm_num
-/
import tactic.norm_num data.complex.basic
-- constant real : Type
-- notation `ℝ` := real
-- @[instance] constant real.linear_ordered_ring : linear_ordered_field ℝ
-- constant complex : Type
-- notation `ℂ` := complex
-- @[instance] constant complex.field : field ℂ
-- @[instance] constant complex.char_zero : char_zero ℂ
example : 374 + (32 - (2 * 8123) : ℤ) - 61 * 50 = 86 + 32 * 32 - 4 * 5000
∧ 43 ≤ 74 + (33 : ℤ) := by norm_num
example : ¬ (7-2)/(2*3) ≥ (1:ℝ) + 2/(3^2) := by norm_num
example : (6:real) + 9 = 15 := by norm_num
example : (2:real)/4 + 4 = 3*3/2 := by norm_num
example : (((3:real)/4)-12)<6 := by norm_num
example : (5:real) ≠ 8 := by norm_num
example : (10:real) > 7 := by norm_num
example : (2:real) * 2 + 3 = 7 := by norm_num
example : (6:real) < 10 := by norm_num
example : (7:real)/2 > 3 := by norm_num
example : (4:real)⁻¹ < 1 := by norm_num
example : ((1:real) / 2)⁻¹ = 2 := by norm_num
example : 2 ^ 17 - 1 = 131071 :=
by {norm_num, tactic.try_for 200 (tactic.result >>= tactic.type_check)}
example : (1:complex) ≠ 2 := by norm_num
example : (1:complex) / 3 ≠ 2 / 7 := by norm_num
example {α} [semiring α] [char_zero α] : (1:α) ≠ 2 := by norm_num
example {α} [ring α] [char_zero α] : (-1:α) ≠ 2 := by norm_num
example {α} [division_ring α] [char_zero α] : (-1:α) ≠ 2 := by norm_num
example {α} [division_ring α] [char_zero α] : (1:α) / 3 ≠ 2 / 7 := by norm_num
example : (5 / 2:ℕ) = 2 := by norm_num
example : (5 / -2:ℤ) < -1 := by norm_num
example : (0 + 1) / 2 < 0 + 1 := by norm_num
example : nat.succ (nat.succ (2 ^ 3)) = 10 := by norm_num
example (x : ℤ) (h : 1000 + 2000 < x) : 100 * 30 < x :=
by norm_num at *; try_for 100 {exact h}
example : (1103 : ℤ) ≤ (2102 : ℤ) := by norm_num
example : (110474 : ℤ) ≤ (210485 : ℤ) := by norm_num
example : (11047462383473829263 : ℤ) ≤ (21048574677772382462 : ℤ) := by norm_num
example : (210485742382937847263 : ℤ) ≤ (1104857462382937847262 : ℤ) := by norm_num
example : (210485987642382937847263 : ℕ) ≤ (11048512347462382937847262 : ℕ) := by norm_num
example : (210485987642382937847263 : ℚ) ≤ (11048512347462382937847262 : ℚ) := by norm_num
example : (2 * 12868 + 25705) * 11621 ^ 2 ≤ 23235 ^ 2 * 12868 := by norm_num
example (x : ℕ) : ℕ := begin
let n : ℕ, {apply_normed (2^32 - 71)},
exact n
end
example : nat.prime 1277 := by norm_num
example : nat.min_fac 221 = 13 := by norm_num
example (h : (5 : ℤ) ∣ 2) : false := by norm_num at h
example : 10 + 2 = 1 + 11 := by norm_num
example : 10 - 1 = 9 := by norm_num
example : 12 - 5 = 3 + 4 := by norm_num
example : 5 - 20 = 0 := by norm_num
example : 0 - 2 = 0 := by norm_num
example : 4 - (5 - 10) = 2 + (3 - 1) := by norm_num
example : 0 - 0 = 0 := by norm_num
example : 100 - 100 = 0 := by norm_num
example : 5 * (2 - 3) = 0 := by norm_num
example : 10 - 5 * 5 + (7 - 3) * 6 = 27 - 3 := by norm_num
-- ordered field examples
variable {α : Type}
variable [linear_ordered_field α]
example : (-1 :α) * 1 = -1 := by norm_num
example : (-2 :α) * 1 = -2 := by norm_num
example : (-2 :α) * -1 = 2 := by norm_num
example : (-2 :α) * -2 = 4 := by norm_num
example : (1 : α) * 0 = 0 := by norm_num
example : ((1 : α) + 1) * 5 = 6 + 4 := by norm_num
example : (1 : α) = 0 + 1 := by norm_num
example : (1 : α) = 1 + 0 := by norm_num
example : (2 : α) = 1 + 1 := by norm_num
example : (2 : α) = 0 + 2 := by norm_num
example : (3 : α) = 1 + 2 := by norm_num
example : (3 : α) = 2 + 1 := by norm_num
example : (4 : α) = 3 + 1 := by norm_num
example : (4 : α) = 2 + 2 := by norm_num
example : (5 : α) = 4 + 1 := by norm_num
example : (5 : α) = 3 + 2 := by norm_num
example : (5 : α) = 2 + 3 := by norm_num
example : (6 : α) = 0 + 6 := by norm_num
example : (6 : α) = 3 + 3 := by norm_num
example : (6 : α) = 4 + 2 := by norm_num
example : (6 : α) = 5 + 1 := by norm_num
example : (7 : α) = 4 + 3 := by norm_num
example : (7 : α) = 1 + 6 := by norm_num
example : (7 : α) = 6 + 1 := by norm_num
example : 33 = 5 + (28 : α) := by norm_num
example : (12 : α) = 0 + (2 + 3) + 7 := by norm_num
example : (105 : α) = 70 + (33 + 2) := by norm_num
example : (45000000000 : α) = 23000000000 + 22000000000 := by norm_num
example : (0 : α) - 3 = -3 := by norm_num
example : (0 : α) - 2 = -2 := by norm_num
example : (1 : α) - 3 = -2 := by norm_num
example : (1 : α) - 1 = 0 := by norm_num
example : (0 : α) - 3 = -3 := by norm_num
example : (0 : α) - 3 = -3 := by norm_num
example : (12 : α) - 4 - (5 + -2) = 5 := by norm_num
example : (12 : α) - 4 - (5 + -2) - 20 = -15 := by norm_num
example : (0 : α) * 0 = 0 := by norm_num
example : (0 : α) * 1 = 0 := by norm_num
example : (0 : α) * 2 = 0 := by norm_num
example : (2 : α) * 0 = 0 := by norm_num
example : (1 : α) * 0 = 0 := by norm_num
example : (1 : α) * 1 = 1 := by norm_num
example : (2 : α) * 1 = 2 := by norm_num
example : (1 : α) * 2 = 2 := by norm_num
example : (2 : α) * 2 = 4 := by norm_num
example : (3 : α) * 2 = 6 := by norm_num
example : (2 : α) * 3 = 6 := by norm_num
example : (4 : α) * 1 = 4 := by norm_num
example : (1 : α) * 4 = 4 := by norm_num
example : (3 : α) * 3 = 9 := by norm_num
example : (3 : α) * 4 = 12 := by norm_num
example : (4 : α) * 4 = 16 := by norm_num
example : (11 : α) * 2 = 22 := by norm_num
example : (15 : α) * 6 = 90 := by norm_num
example : (123456 : α) * 123456 = 15241383936 := by norm_num
example : (4 : α) / 2 = 2 := by norm_num
example : (4 : α) / 1 = 4 := by norm_num
example : (4 : α) / 3 = 4 / 3 := by norm_num
example : (50 : α) / 5 = 10 := by norm_num
example : (1056 : α) / 1 = 1056 := by norm_num
example : (6 : α) / 4 = 3/2 := by norm_num
example : (0 : α) / 3 = 0 := by norm_num
example : (3 : α) / 0 = 0 := by norm_num -- this should fail
example : (9 * 9 * 9) * (12 : α) / 27 = 81 * (2 + 2) := by norm_num
example : (-2 : α) * 4 / 3 = -8 / 3 := by norm_num
example : - (-4 / 3) = 1 / (3 / (4 : α)) := by norm_num
-- auto gen tests
example : ((25 * (1 / 1)) + (30 - 16)) = (39 : α) := by norm_num
example : ((19 * (- 2 - 3)) / 6) = (-95/6 : α) := by norm_num
example : - (3 * 28) = (-84 : α) := by norm_num
example : - - (16 / ((11 / (- - (6 * 19) + 12)) * 21)) = (96/11 : α) := by norm_num
example : (- (- 21 + 24) - - (- - (28 + (- 21 / - (16 / ((1 * 26) * ((0 * - 11) + 13))))) * 21)) = (79209/8 : α) := by norm_num
example : (27 * (((16 + - (12 + 4)) + (22 - - 19)) - 23)) = (486 : α) := by norm_num
example : - (13 * (- 30 / ((7 / 24) + - 7))) = (-9360/161 : α) := by norm_num
example : - (0 + 20) = (-20 : α) := by norm_num
example : (- 2 - (27 + (((2 / 14) - (7 + 21)) + (16 - - - 14)))) = (-22/7 : α) := by norm_num
example : (25 + ((8 - 2) + 16)) = (47 : α) := by norm_num
example : (- - 26 / 27) = (26/27 : α) := by norm_num
example : ((((16 * (22 / 14)) - 18) / 11) + 30) = (2360/77 : α) := by norm_num
example : (((- 28 * 28) / (29 - 24)) * 24) = (-18816/5 : α) := by norm_num
example : ((- (18 - ((- - (10 + - 2) - - (23 / 5)) / 5)) - (21 * 22)) - (((20 / - ((((19 + 18) + 15) + 3) + - 22)) + 14) / 17)) = (-394571/825 : α) := by norm_num
example : ((3 + 25) - - 4) = (32 : α) := by norm_num
example : ((1 - 0) - 22) = (-21 : α) := by norm_num
example : (((- (8 / 7) / 14) + 20) + 22) = (2054/49 : α) := by norm_num
example : ((21 / 20) - 29) = (-559/20 : α) := by norm_num
example : - - 20 = (20 : α) := by norm_num
example : (24 - (- 9 / 4)) = (105/4 : α) := by norm_num
example : (((7 / ((23 * 19) + (27 * 10))) - ((28 - - 15) * 24)) + (9 / - (10 * - 3))) = (-1042007/1010 : α) := by norm_num
example : (26 - (- 29 + (12 / 25))) = (1363/25 : α) := by norm_num
example : ((11 * 27) / (4 - 5)) = (-297 : α) := by norm_num
example : (24 - (9 + 15)) = (0 : α) := by norm_num
example : (- 9 - - 0) = (-9 : α) := by norm_num
example : (- 10 / (30 + 10)) = (-1/4 : α) := by norm_num
example : (22 - (6 * (28 * - 8))) = (1366 : α) := by norm_num
example : ((- - 2 * (9 * - 3)) + (22 / 30)) = (-799/15 : α) := by norm_num
example : - (26 / ((3 + 7) / - (27 * (12 / - 16)))) = (-1053/20 : α) := by norm_num
example : ((- 29 / 1) + 28) = (-1 : α) := by norm_num
example : ((21 * ((10 - (((17 + 28) - - 0) + 20)) + 26)) + ((17 + - 16) * 7)) = (-602 : α) := by norm_num
example : (((- 5 - ((24 + - - 8) + 3)) + 20) + - 23) = (-43 : α) := by norm_num
example : ((- ((14 - 15) * (14 + 8)) + ((- (18 - 27) - 0) + 12)) - 11) = (32 : α) := by norm_num
example : (((15 / 17) * (26 / 27)) + 28) = (4414/153 : α) := by norm_num
example : (14 - ((- 16 - 3) * - (20 * 19))) = (-7206 : α) := by norm_num
example : (21 - - - (28 - (12 * 11))) = (125 : α) := by norm_num
example : ((0 + (7 + (25 + 8))) * - (11 * 27)) = (-11880 : α) := by norm_num
example : (19 * - 5) = (-95 : α) := by norm_num
example : (29 * - 8) = (-232 : α) := by norm_num
example : ((22 / 9) - 29) = (-239/9 : α) := by norm_num
example : (3 + (19 / 12)) = (55/12 : α) := by norm_num
example : - (13 + 30) = (-43 : α) := by norm_num
example : - - - (((21 * - - ((- 25 - (- (30 - 5) / (- 5 - 5))) / (((6 + ((25 * - 13) + 22)) - 3) / 2))) / (- 3 / 10)) * (- 8 - 0)) = (-308/3 : α) := by norm_num
example : - (2 * - (- 24 * 22)) = (-1056 : α) := by norm_num
example : - - (((28 / - ((- 13 * - 5) / - (((7 - 30) / 16) + 6))) * 0) - 24) = (-24 : α) := by norm_num
example : ((13 + 24) - (27 / (21 * 13))) = (3358/91 : α) := by norm_num
example : ((3 / - 21) * 25) = (-25/7 : α) := by norm_num
example : (17 - (29 - 18)) = (6 : α) := by norm_num
example : ((28 / 20) * 15) = (21 : α) := by norm_num
example : ((((26 * (- (23 - 13) - 3)) / 20) / (14 - (10 + 20))) / ((16 / 6) / (16 * - (3 / 28)))) = (-1521/2240 : α) := by norm_num
example : (46 / (- ((- 17 * 28) - 77) + 87)) = (23/320 : α) := by norm_num
example : (73 * - (67 - (74 * - - 11))) = (54531 : α) := by norm_num
example : ((8 * (25 / 9)) + 59) = (731/9 : α) := by norm_num
example : - ((59 + 85) * - 70) = (10080 : α) := by norm_num
example : (66 + (70 * 58)) = (4126 : α) := by norm_num
example : (- - 49 * 0) = (0 : α) := by norm_num
example : ((- 78 - 69) * 9) = (-1323 : α) := by norm_num
example : - - (7 - - (50 * 79)) = (3957 : α) := by norm_num
example : - (85 * (((4 * 93) * 19) * - 31)) = (18624180 : α) := by norm_num
example : (21 + (- 5 / ((74 * 85) / 45))) = (26373/1258 : α) := by norm_num
example : (42 - ((27 + 64) + 26)) = (-75 : α) := by norm_num
example : (- ((38 - - 17) + 86) - (74 + 58)) = (-273 : α) := by norm_num
example : ((29 * - (75 + - 68)) + (- 41 / 28)) = (-5725/28 : α) := by norm_num
example : (- - (40 - 11) - (68 * 86)) = (-5819 : α) := by norm_num
example : (6 + ((65 - 14) + - 89)) = (-32 : α) := by norm_num
example : (97 * - (29 * 35)) = (-98455 : α) := by norm_num
example : - (66 / 33) = (-2 : α) := by norm_num
example : - ((94 * 89) + (79 - (23 - (((- 1 / 55) + 95) * (28 - (54 / - - - 22)))))) = (-1369070/121 : α) := by norm_num
example : (- 23 + 61) = (38 : α) := by norm_num
example : - (93 / 69) = (-31/23 : α) := by norm_num
example : (- - ((68 / (39 + (((45 * - (59 - (37 + 35))) / (53 - 75)) - - (100 + - (50 / (- 30 - 59)))))) - (69 - (23 * 30))) / (57 + 17)) = (137496481/16368578 : α) := by norm_num
example : (- 19 * - - (75 * - - 41)) = (-58425 : α) := by norm_num
example : ((3 / ((- 28 * 45) * (19 + ((- (- 88 - (- (- 1 + 90) + 8)) + 87) * 48)))) + 1) = (1903019/1903020 : α) := by norm_num
example : ((- - (28 + 48) / 75) + ((- 59 - 14) - 0)) = (-5399/75 : α) := by norm_num
example : (- ((- (((66 - 86) - 36) / 94) - 3) / - - (77 / (56 - - - 79))) + 87) = (312254/3619 : α) := by norm_num
|
ca76b345368281a3c5056f58417fe2876be42e09 | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love02_tactical_proofs_exercise_sheet.lean | 45194c2816a9f1d4bee0eb1eaf9fa3fd9ded78dc | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 2,931 | lean | /- LoVe Exercise 2: Tactical Proofs -/
import .love02_tactical_proofs_demo
namespace LoVe
/- Question 1: Connectives and Quantifiers -/
/- 1.1. Carry out the following proofs using basic tactics. -/
lemma I (a : Prop) :
a → a :=
sorry
lemma K (a b : Prop) :
a → b → b :=
sorry
lemma C (a b c : Prop) :
(a → b → c) → b → a → c :=
sorry
lemma proj_1st (a : Prop) :
a → a → a :=
sorry
-- please give a different answer than for `proj_1st`
lemma proj_2nd (a : Prop) :
a → a → a :=
sorry
lemma some_nonsense (a b c : Prop) :
(a → b → c) → a → (a → c) → b → c :=
sorry
/- 1.2. Prove the contraposition rule using basic tactics. -/
lemma contrapositive (a b : Prop) :
(a → b) → ¬ b → ¬ a :=
sorry
/- 1.3. Prove the distributivity of `∀` over `∧` using basic tactics. -/
lemma forall_and {α : Type} (p q : α → Prop) :
(∀x, p x ∧ q x) ↔ (∀x, p x) ∧ (∀x, q x) :=
sorry
/- Question 2: Natural Numbers -/
/- 2.1. Prove the following recursive equations on the first argument of the
`mul` operator defined in lecture 1. -/
#check mul
lemma mul_zero (n : ℕ) :
mul 0 n = 0 :=
sorry
lemma mul_succ (m n : ℕ) :
mul (nat.succ m) n = add (mul m n) n :=
sorry
/- 2.2. Prove commutativity and associativity of multiplication using the
`induction` tactic. Choose the induction variable carefully. -/
lemma mul_comm (m n : ℕ) :
mul m n = mul n m :=
sorry
lemma mul_assoc (l m n : ℕ) :
mul (mul l m) n = mul l (mul m n) :=
:= sorry
/- 2.3. Prove the symmetric variant of `mul_add` using `rw`. To apply
commutativity at a specific position, instantiate the rule by passing some
arguments (e.g., `mul_comm _ l`). -/
lemma add_mul (l m n : ℕ) : mul (add l m) n = add (mul n l) (mul n m) :=
sorry
/- Question 3 (**optional**): Intuitionistic Logic -/
/- Intuitionistic logic is extended to classical logic by assuming a classical
axiom. There are several possibilities for the choice of axiom. In this
question, we are concerned with the logical equivalence of three different
axioms: -/
def excluded_middle := ∀a : Prop, a ∨ ¬ a
def peirce := ∀a b : Prop, ((a → b) → a) → a
def double_negation := ∀a : Prop, ¬¬ a → a
/- For the proofs below, please avoid using lemmas from Lean's `classical`
namespace, because this would defeat the purpose of the exercise. -/
/- 3.1 (**optional**). Prove the following implication using tactics.
Hint: You will need `or.elim` and `false.elim`. -/
lemma peirce_of_em : excluded_middle → peirce :=
sorry
/- 3.2 (**optional**). Prove the following implication using tactics.
Hint: Try instantiating `b` with `false` in Peirce's law. -/
lemma dn_of_peirce : peirce → double_negation :=
sorry
/- We leave the missing implication for the homework: -/
namespace sorry_lemmas
lemma em_of_dn :
double_negation → excluded_middle :=
sorry
end sorry_lemmas
end LoVe
|
a6e7a29bea0957063933dc33ed821db5b23ec07c | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /tests/lean/run/eq12.lean | 1b6310b519ee583717537ce1027615604992d5ab | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 494 | lean | open nat bool inhabited
definition diag : bool → bool → bool → nat,
diag _ tt ff := 1,
diag ff _ tt := 2,
diag tt ff _ := 3,
diag _ _ _ := arbitrary nat
theorem diag1 (a : bool) : diag a tt ff = 1 :=
bool.cases_on a rfl rfl
theorem diag2 (a : bool) : diag ff a tt = 2 :=
bool.cases_on a rfl rfl
theorem diag3 (a : bool) : diag tt ff a = 3 :=
bool.cases_on a rfl rfl
theorem diag4_1 : diag ff ff ff = arbitrary nat :=
rfl
theorem diag4_2 : diag tt tt tt = arbitrary nat :=
rfl
|
f58940882da3c89a8f196e8ca6f04a44a8e0d204 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/ring_theory/subring.lean | b843d16620be7aacbbfdb43475f35bdc120ab759 | [
"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 | 31,981 | lean | /-
Copyright (c) 2020 Ashvni Narayanan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ashvni Narayanan
-/
import deprecated.subring
import group_theory.subgroup
import ring_theory.subsemiring
/-!
# Subrings
Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type
whose terms correspond to subrings of `R`. This is the preferred way to talk
about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`)
are not in this file, and they will ultimately be deprecated.
We prove that subrings are a complete lattice, and that you can `map` (pushforward) and
`comap` (pull back) them along ring homomorphisms.
We define the `closure` construction from `set R` to `subring R`, sending a subset of `R`
to the subring it generates, and prove that it is a Galois insertion.
## Main definitions
Notation used here:
`(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)`
`(A : subring R) (B : subring S) (s : set R)`
* `subring R` : the type of subrings of a ring `R`.
* `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings.
* `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set.
* `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M`
form a `galois_insertion`.
* `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f`
* `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`.
* `prod A B : subring (R × S)` : the product of subrings
* `f.range : subring B` : the range of the ring homomorphism `f`.
* `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`,
the subring of `R` where `f x = g x`
## Implementation notes
A subring is implemented as a subsemiring which is also an additive subgroup.
The initial PR was as a submonoid which is also an additive subgroup.
Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although
`∈` is defined as membership of a subring's underlying set.
## Tags
subring, subrings
-/
open_locale big_operators
universes u v w
variables {R : Type u} {S : Type v} {T : Type w} [ring R] [ring S] [ring T]
set_option old_structure_cmd true
/-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a
multiplicative submonoid and an additive subgroup. Note in particular that it shares the
same 0 and 1 as R. -/
structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R
/-- Reinterpret a `subring` as a `subsemiring`. -/
add_decl_doc subring.to_subsemiring
/-- Reinterpret a `subring` as an `add_subgroup`. -/
add_decl_doc subring.to_add_subgroup
namespace subring
/-- The underlying submonoid of a subring. -/
def to_submonoid (s : subring R) : submonoid R :=
{ carrier := s.carrier,
..s.to_subsemiring.to_submonoid }
instance : set_like (subring R) R :=
⟨subring.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp]
lemma mem_carrier {s : subring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
/-- Two subrings are equal if they have the same elements. -/
@[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive
subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/
protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R)
(hm : ↑sm = s) (ha : ↑sa = s) :
subring R :=
{ carrier := s,
zero_mem' := ha ▸ sa.zero_mem,
one_mem' := hm ▸ sm.one_mem,
add_mem' := λ x y, by simpa only [← ha] using sa.add_mem,
mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem,
neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, }
@[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) :
(subring.mk' s sm sa hm ha : set R) = s := rfl
@[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) {x : R} :
x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s :=
iff.rfl
@[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) :
(subring.mk' s sm sa hm ha).to_submonoid = sm :=
set_like.coe_injective hm.symm
@[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa =s) :
(subring.mk' s sm sa hm ha).to_add_subgroup = sa :=
set_like.coe_injective ha.symm
end subring
/-- Construct a `subring` from a set satisfying `is_subring`. -/
def set.to_subring (S : set R) [is_subring S] : subring R :=
{ carrier := S,
one_mem' := is_submonoid.one_mem,
mul_mem' := λ a b, is_submonoid.mul_mem,
zero_mem' := is_add_submonoid.zero_mem,
add_mem' := λ a b, is_add_submonoid.add_mem,
neg_mem' := λ a, is_add_subgroup.neg_mem }
/-- A `subsemiring` containing -1 is a `subring`. -/
def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R :=
{ neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, }
..s.to_submonoid, ..s.to_add_submonoid }
namespace subring
variables (s : subring R)
/-- A subring contains the ring's 1. -/
theorem one_mem : (1 : R) ∈ s := s.one_mem'
/-- A subring contains the ring's 0. -/
theorem zero_mem : (0 : R) ∈ s := s.zero_mem'
/-- A subring is closed under multiplication. -/
theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem'
/-- A subring is closed under addition. -/
theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem'
/-- A subring is closed under negation. -/
theorem neg_mem : ∀ {x : R}, x ∈ s → -x ∈ s := s.neg_mem'
/-- A subring is closed under subtraction -/
theorem sub_mem {x y : R} (hx : x ∈ s) (hy : y ∈ s) : x - y ∈ s :=
by { rw sub_eq_add_neg, exact s.add_mem hx (s.neg_mem hy) }
/-- Product of a list of elements in a subring is in the subring. -/
lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s :=
s.to_submonoid.list_prod_mem
/-- Sum of a list of elements in a subring is in the subring. -/
lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s :=
s.to_add_subgroup.list_sum_mem
/-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/
lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.prod ∈ s :=
s.to_submonoid.multiset_prod_mem m
/-- Sum of a multiset of elements in an `subring` of a `ring` is
in the `subring`. -/
lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.sum ∈ s :=
s.to_add_subgroup.multiset_sum_mem m
/-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the
subring. -/
lemma prod_mem {R : Type*} [comm_ring R] (s : subring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∏ i in t, f i ∈ s :=
s.to_submonoid.prod_mem h
/-- Sum of elements in a `subring` of a `ring` indexed by a `finset`
is in the `subring`. -/
lemma sum_mem {R : Type*} [ring R] (s : subring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
s.to_add_subgroup.sum_mem h
lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n
lemma gsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) :
n •ℤ x ∈ s := s.to_add_subgroup.gsmul_mem hx n
lemma coe_int_mem (n : ℤ) : (n : R) ∈ s :=
by simp only [← gsmul_one, gsmul_mem, one_mem]
/-- A subring of a ring inherits a ring structure -/
instance to_ring : ring s :=
{ right_distrib := λ x y z, subtype.eq $ right_distrib x y z,
left_distrib := λ x y z, subtype.eq $ left_distrib x y z,
.. s.to_submonoid.to_monoid, .. s.to_add_subgroup.to_add_comm_group }
@[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl
@[simp, norm_cast] lemma coe_pow (x : s) (n : ℕ) : (↑(x ^ n) : R) = x ^ n :=
s.to_submonoid.coe_pow x n
@[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 :=
⟨λ h, subtype.ext (trans h s.coe_zero.symm),
λ h, h.symm ▸ s.coe_zero⟩
/-- A subring of a `comm_ring` is a `comm_ring`. -/
instance to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s :=
{ mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring s}
/-- A subring of a non-trivial ring is non-trivial. -/
instance {R} [ring R] [nontrivial R] (s : subring R) : nontrivial s :=
s.to_subsemiring.nontrivial
/-- A subring of a ring with no zero divisors has no zero divisors. -/
instance {R} [ring R] [no_zero_divisors R] (s : subring R) : no_zero_divisors s :=
s.to_subsemiring.no_zero_divisors
/-- A subring of an integral domain is an integral domain. -/
instance {R} [integral_domain R] (s : subring R) : integral_domain s :=
{ .. s.nontrivial, .. s.no_zero_divisors, .. s.to_comm_ring }
/-- A subring of an `ordered_ring` is an `ordered_ring`. -/
instance to_ordered_ring {R} [ordered_ring R] (s : subring R) : ordered_ring s :=
subtype.coe_injective.ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subring of an `ordered_comm_ring` is an `ordered_comm_ring`. -/
instance to_ordered_comm_ring {R} [ordered_comm_ring R] (s : subring R) : ordered_comm_ring s :=
subtype.coe_injective.ordered_comm_ring coe rfl rfl
(λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subring of a `linear_ordered_ring` is a `linear_ordered_ring`. -/
instance to_linear_ordered_ring {R} [linear_ordered_ring R] (s : subring R) :
linear_ordered_ring s :=
subtype.coe_injective.linear_ordered_ring coe rfl rfl
(λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subring of a `linear_ordered_comm_ring` is a `linear_ordered_comm_ring`. -/
instance to_linear_ordered_comm_ring {R} [linear_ordered_comm_ring R] (s : subring R) :
linear_ordered_comm_ring s :=
subtype.coe_injective.linear_ordered_comm_ring coe rfl rfl
(λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- The natural ring hom from a subring of ring `R` to `R`. -/
def subtype (s : subring R) : s →+* R :=
{ to_fun := coe,
.. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype }
@[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl
@[simp, norm_cast] lemma coe_nat_cast (n : ℕ) : ((n : s) : R) = n :=
s.subtype.map_nat_cast n
@[simp, norm_cast] lemma coe_int_cast (n : ℤ) : ((n : s) : R) = n :=
s.subtype.map_int_cast n
/-! # Partial order -/
@[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl
@[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} :
x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl
/-! # top -/
/-- The subring `R` of the ring `R`. -/
instance : has_top (subring R) :=
⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩
@[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl
/-! # comap -/
/-- The preimage of a subring along a ring homomorphism is a subring. -/
def comap {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) (s : subring S) : subring R :=
{ carrier := f ⁻¹' s.carrier,
.. s.to_submonoid.comap (f : R →* S),
.. s.to_add_subgroup.comap (f : R →+ S) }
@[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl
@[simp]
lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-! # map -/
/-- The image of a subring along a ring homomorphism is a subring. -/
def map {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) (s : subring R) : subring S :=
{ carrier := f '' s.carrier,
.. s.to_submonoid.map (f : R →* S),
.. s.to_add_subgroup.map (f : R →+ S) }
@[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl
@[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} :
y ∈ s.map f ↔ ∃ x ∈ s, f x = y :=
set.mem_image_iff_bex
lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) :=
set_like.coe_injective $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} :
s.map f ≤ t ↔ s ≤ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
end subring
namespace ring_hom
variables (g : S →+* T) (f : R →+* S)
/-! # range -/
/-- The range of a ring homomorphism, as a subring of the target. -/
def range {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) : subring S := (⊤ : subring R).map f
@[simp] lemma coe_range : (f.range : set S) = set.range f := set.image_univ
@[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y :=
by simp [range]
lemma mem_range_self (f : R →+* S) (x : R) : f x ∈ f.range :=
mem_range.mpr ⟨x, rfl⟩
lemma map_range : f.range.map g = (g.comp f).range :=
(⊤ : subring R).map_map g f
-- TODO -- rename to `cod_restrict` when is_ring_hom is deprecated
/-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/
def cod_restrict' {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S)
(s : subring S) (h : ∀ x, f x ∈ s) : R →+* s :=
{ to_fun := λ x, ⟨f x, h x⟩,
map_add' := λ x y, subtype.eq $ f.map_add x y,
map_zero' := subtype.eq f.map_zero,
map_mul' := λ x y, subtype.eq $ f.map_mul x y,
map_one' := subtype.eq f.map_one }
end ring_hom
namespace subring
/-! # bot -/
instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩
instance : inhabited (subring R) := ⟨⊥⟩
lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) :=
ring_hom.coe_range (int.cast_ring_hom R)
lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x :=
ring_hom.mem_range
/-! # inf -/
/-- The inf of two subrings is their intersection. -/
instance : has_inf (subring R) :=
⟨λ s t,
{ carrier := s ∩ t,
.. s.to_submonoid ⊓ t.to_submonoid,
.. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩
@[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl
@[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
instance : has_Inf (subring R) :=
⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t )
(⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩
@[simp, norm_cast] lemma coe_Inf (S : set (subring R)) :
((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
@[simp] lemma Inf_to_submonoid (s : set (subring R)) :
(Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _
@[simp] lemma Inf_to_add_subgroup (s : set (subring R)) :
(Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _
/-- Subrings of a ring form a complete lattice. -/
instance : complete_lattice (subring R) :=
{ bot := (⊥),
bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_int_mem n,
top := (⊤),
le_top := λ s x hx, trivial,
inf := (⊓),
inf_le_left := λ s t x, and.left,
inf_le_right := λ s t x, and.right,
le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩,
.. complete_lattice_of_Inf (subring R)
(λ s, is_glb.of_image (λ s t,
show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)}
lemma eq_top_iff' (A : subring R) : A = ⊤ ↔ ∀ x : R, x ∈ A :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
/-! # subring closure of a subset -/
/-- The `subring` generated by a set. -/
def closure (s : set R) : subring R := Inf {S | s ⊆ S}
lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S :=
mem_Inf
/-- The subring generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
/-- A subring `t` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, λ h, Inf_le h⟩
/-- Subring closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) :
closure s = t :=
le_antisymm (closure_le.2 h₁) h₂
/-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements
of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all
elements of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1)
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hneg : ∀ (x : R), p x → p (-x))
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd, Hneg⟩).2 Hs h
lemma mem_closure_iff {s : set R} {x} :
x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) :=
⟨ λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx )
(add_subgroup.zero_mem _)
(add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) )
(λ x y hx hy, add_subgroup.add_mem _ hx hy )
(λ x hx, add_subgroup.neg_mem _ hx )
( λ x y hx hy, add_subgroup.closure_induction hy
(λ q hq, add_subgroup.closure_induction hx
( λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq) )
( begin rw zero_mul q, apply add_subgroup.zero_mem _, end )
( λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end )
( λ x hx, begin have f : -x * q = -(x*q) :=
by simp, rw f, apply add_subgroup.neg_mem _ hx, end ) )
( begin rw mul_zero x, apply add_subgroup.zero_mem _, end )
( λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end )
( λ z hz, begin have f : x * -z = -(x*z) := by simp,
rw f, apply add_subgroup.neg_mem _ hz, end ) ),
λ h, add_subgroup.closure_induction h
( λ x hx, submonoid.closure_induction hx
( λ x hx, subset_closure hx )
( one_mem _ )
( λ x y hx hy, mul_mem _ hx hy ) )
( zero_mem _ )
(λ x y hx hy, add_mem _ hx hy)
( λ x hx, neg_mem _ hx ) ⟩
theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) :
(∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) :=
add_subgroup.closure_induction (mem_closure_iff.1 h)
(λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h];
clear_aux_decl; tauto!⟩)
⟨[], by simp⟩
(λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t),
by simp [hl2, hm2]⟩)
(λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2
⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp)
(by simp [list.map_cons, add_comm] {contextual := tt})⟩)
variable (R)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure R _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {R}
/-- Closure of a subring `S` equals `S`. -/
lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s
@[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤
lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t :=
(subring.gi R).gc.l_sup
lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subring.gi R).gc.l_supr
lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t :=
(subring.gi R).gc.l_Sup
lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s × t`
as a subring of `R × S`. -/
def prod (s : subring R) (t : subring S) : subring (R × S) :=
{ carrier := (s : set R).prod t,
.. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup}
@[norm_cast]
lemma coe_prod (s : subring R) (t : subring S) :
(s.prod t : set (R × S)) = (s : set R).prod (t : set S) :=
rfl
lemma mem_prod {s : subring R} {t : subring S} {p : R × S} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄
(ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) :=
prod_mono (le_refl s)
lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) :=
λ s₁ s₂ hs, prod_mono hs (le_refl t)
lemma prod_top (s : subring R) :
s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
lemma top_prod (s : subring S) :
(⊤ : subring R).prod s = s.comap (ring_hom.snd R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp]
lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ :=
(top_prod _).trans $ comap_top _
/-- Product of subrings is isomorphic to their product as rings. -/
def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t :=
{ map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
/-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings.
Note that this fails without the directedness assumption (the union of two subrings is
typically not a subring) -/
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S)
{x : R} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
let U : subring R := subring.mk' (⋃ i, (S i : set R))
(⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup)
(submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id))
(add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)),
suffices : (⨆ i, S i) ≤ U, by simpa using @this x,
exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩),
end
lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) :
((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : R} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set R) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
end subring
namespace ring_hom
variables [ring T] {s : subring R}
open subring
/-- Restriction of a ring homomorphism to a subring of the domain. -/
def restrict (f : R →+* S) (s : subring R) : s →+* S := f.comp s.subtype
@[simp] lemma restrict_apply (f : R →+* S) (x : s) : f.restrict s x = f x := rfl
/-- Restriction of a ring homomorphism to its range interpreted as a subsemiring.
This is the bundled version of `set.range_factorization`. -/
def range_restrict (f : R →+* S) : R →+* f.range :=
f.cod_restrict' f.range $ λ x, ⟨x, subring.mem_top x, rfl⟩
@[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl
lemma range_restrict_surjective (f : R →+* S) : function.surjective f.range_restrict :=
λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_range.mp hy in ⟨x, subtype.ext hx⟩
lemma range_top_iff_surjective {f : R →+* S} :
f.range = (⊤ : subring S) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective
/-- The range of a surjective ring homomorphism is the whole of the codomain. -/
lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) :
f.range = (⊤ : subring S) :=
range_top_iff_surjective.2 hf
/-- The subring of elements `x : R` such that `f x = g x`, i.e.,
the equalizer of f and g as a subring of R -/
def eq_locus (f g : R →+* S) : subring R :=
{ carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g }
/-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/
lemma eq_on_set_closure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_locus g, from closure_le.2 h
lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) :
f = g :=
ext $ λ x, h trivial
lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h
lemma closure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subring generated by a set equals
the subring generated by the image of the set. -/
lemma map_closure (f : R →+* S) (s : set R) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(closure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subring
open ring_hom
/-- The ring homomorphism associated to an inclusion of subrings. -/
def inclusion {S T : subring R} (h : S ≤ T) : S →* T :=
S.subtype.cod_restrict' _ (λ x, h x.2)
@[simp] lemma range_subtype (s : subring R) : s.subtype.range = s :=
set_like.coe_injective $ (coe_srange _).trans subtype.range_coe
@[simp]
lemma range_fst : (fst R S).srange = ⊤ :=
(fst R S).srange_top_of_surjective $ prod.fst_surjective
@[simp]
lemma range_snd : (snd R S).srange = ⊤ :=
(snd R S).srange_top_of_surjective $ prod.snd_surjective
@[simp]
lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem _
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩)
end subring
namespace ring_equiv
variables {s t : subring R}
/-- Makes the identity isomorphism from a proof two subrings of a multiplicative
monoid are equal. -/
def subring_congr (h : s = t) : s ≃+* t :=
{ map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
/-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its
`ring_hom.range`. -/
def of_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) :
R ≃+* f.range :=
{ to_fun := λ x, f.range_restrict x,
inv_fun := λ x, (g ∘ f.range.subtype) x,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := ring_hom.mem_range.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
..f.range_restrict }
@[simp] lemma of_left_inverse_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) :
↑(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
end ring_equiv
namespace subring
variables {s : set R}
local attribute [reducible] closure
@[elab_as_eliminator]
protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s)
(h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n))
(ha : ∀ {x y}, C x → C y → C (x + y)) : C x :=
begin
have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1,
rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx,
induction L with hd tl ih, { exact h0 },
rw list.forall_mem_cons at HL,
suffices : C (list.prod hd),
{ rw [list.map_cons, list.sum_cons],
exact ha this (ih HL.2) },
replace HL := HL.1, clear ih tl,
suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧
(list.prod hd = list.prod L ∨ list.prod hd = -list.prod L),
{ rcases this with ⟨L, HL', HP | HP⟩,
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 },
rw list.forall_mem_cons at HL',
rw list.prod_cons,
exact hs _ HL'.1 _ (ih HL'.2) },
rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 },
rw [list.prod_cons, neg_mul_eq_mul_neg],
rw list.forall_mem_cons at HL',
exact hs _ HL'.1 _ (ih HL'.2) },
induction hd with hd tl ih,
{ exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ },
rw list.forall_mem_cons at HL,
rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd,
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $
by rw [list.prod_cons, list.prod_cons, HP]⟩ },
{ exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ },
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $
by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ },
{ exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ }
end
lemma closure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
end subring
lemma add_subgroup.int_mul_mem {G : add_subgroup R} (k : ℤ) {g : R} (h : g ∈ G) :
(k : R) * g ∈ G :=
by { convert add_subgroup.gsmul_mem G h k, simp }
|
eb3ff96159dd9017bbe6189e87eaa09de1d36f7f | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/init/logic.lean | 947bd4e4a345c93ec3feb08538466764cb1be4ab | [
"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 | 34,060 | 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, Floris van Doorn
-/
prelude
import init.datatypes init.reserved_notation init.tactic
definition id [reducible] [unfold_full] {A : Type} (a : A) : A :=
a
/- implication -/
definition implies (a b : Prop) := a → b
lemma implies.trans [trans] {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r :=
assume hp, h₂ (h₁ hp)
definition trivial := true.intro
definition not (a : Prop) := a → false
prefix `¬` := not
definition absurd {a : Prop} {b : Type} (H1 : a) (H2 : ¬a) : b :=
false.rec b (H2 H1)
lemma not.intro [intro!] {a : Prop} (H : a → false) : ¬ a :=
H
theorem mt {a b : Prop} (H1 : a → b) (H2 : ¬b) : ¬a :=
assume Ha : a, absurd (H1 Ha) H2
definition implies.resolve {a b : Prop} (H : a → b) (nb : ¬ b) : ¬ a := assume Ha, nb (H Ha)
/- not -/
theorem not_false : ¬false :=
assume H : false, H
definition non_contradictory (a : Prop) : Prop := ¬¬a
theorem non_contradictory_intro {a : Prop} (Ha : a) : ¬¬a :=
assume Hna : ¬a, absurd Ha Hna
/- false -/
theorem false.elim {c : Prop} (H : false) : c :=
false.rec c H
/- eq -/
notation a = b := eq a b
definition rfl {A : Type} {a : A} : a = a := eq.refl a
definition id.def [defeq] {A : Type} (a : A) : id a = a := rfl
-- proof irrelevance is built in
theorem proof_irrel {a : Prop} (H₁ H₂ : a) : H₁ = H₂ :=
rfl
-- Remark: we provide the universe levels explicitly to make sure `eq.drec` has the same type of `eq.rec` in the HoTT library
protected theorem eq.drec.{l₁ l₂} {A : Type.{l₂}} {a : A} {C : Π (x : A), a = x → Type.{l₁}} (h₁ : C a (eq.refl a)) {b : A} (h₂ : a = b) : C b h₂ :=
eq.rec (λh₂ : a = a, show C a h₂, from h₁) h₂ h₂
namespace eq
variables {A : Type}
variables {a b c a': A}
protected theorem drec_on {a : A} {C : Π (x : A), a = x → Type} {b : A} (h₂ : a = b) (h₁ : C a (refl a)) : C b h₂ :=
eq.drec h₁ h₂
theorem subst {P : A → Prop} (H₁ : a = b) (H₂ : P a) : P b :=
eq.rec H₂ H₁
theorem trans (H₁ : a = b) (H₂ : b = c) : a = c :=
subst H₂ H₁
theorem symm : a = b → b = a :=
eq.rec (refl a)
theorem substr {P : A → Prop} (H₁ : b = a) : P a → P b :=
subst (symm H₁)
theorem mp {a b : Type} : (a = b) → a → b :=
eq.rec_on
theorem mpr {a b : Type} : (a = b) → b → a :=
assume H₁ H₂, eq.rec_on (eq.symm H₁) H₂
namespace ops
notation H `⁻¹` := symm H --input with \sy or \-1 or \inv
notation H1 ⬝ H2 := trans H1 H2
notation H1 ▸ H2 := subst H1 H2
notation H1 ▹ H2 := eq.rec H2 H1
end ops
end eq
theorem congr {A B : Type} {f₁ f₂ : A → B} {a₁ a₂ : A} (H₁ : f₁ = f₂) (H₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ :=
eq.subst H₁ (eq.subst H₂ rfl)
theorem congr_fun {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a :=
eq.subst H (eq.refl (f a))
theorem congr_arg {A B : Type} {a₁ a₂ : A} (f : A → B) : a₁ = a₂ → f a₁ = f a₂ :=
congr rfl
section
variables {A : Type} {a b c: A}
open eq.ops
theorem trans_rel_left (R : A → A → Prop) (H₁ : R a b) (H₂ : b = c) : R a c :=
H₂ ▸ H₁
theorem trans_rel_right (R : A → A → Prop) (H₁ : a = b) (H₂ : R b c) : R a c :=
H₁⁻¹ ▸ H₂
end
section
variable {p : Prop}
open eq.ops
theorem of_eq_true (H : p = true) : p :=
H⁻¹ ▸ trivial
theorem not_of_eq_false (H : p = false) : ¬p :=
assume Hp, H ▸ Hp
end
attribute eq.subst [subst]
attribute eq.refl [refl]
attribute eq.trans [trans]
attribute eq.symm [symm]
definition cast {A B : Type} (H : A = B) (a : A) : B :=
eq.rec a H
theorem cast_proof_irrel {A B : Type} (H₁ H₂ : A = B) (a : A) : cast H₁ a = cast H₂ a :=
rfl
theorem cast_eq {A : Type} (H : A = A) (a : A) : cast H a = a :=
rfl
/- ne -/
definition ne [reducible] {A : Type} (a b : A) := ¬(a = b)
definition ne.def [defeq] {A : Type} (a b : A) : ne a b = ¬ (a = b) := rfl
notation a ≠ b := ne a b
namespace ne
open eq.ops
variable {A : Type}
variables {a b : A}
theorem intro (H : a = b → false) : a ≠ b := H
theorem elim (H : a ≠ b) : a = b → false := H
theorem irrefl (H : a ≠ a) : false := H rfl
theorem symm (H : a ≠ b) : b ≠ a :=
assume (H₁ : b = a), H (H₁⁻¹)
end ne
theorem false_of_ne {A : Type} {a : A} : a ≠ a → false := ne.irrefl
section
open eq.ops
variables {p : Prop}
theorem ne_false_of_self : p → p ≠ false :=
assume (Hp : p) (Heq : p = false), Heq ▸ Hp
theorem ne_true_of_not : ¬p → p ≠ true :=
assume (Hnp : ¬p) (Heq : p = true), (Heq ▸ Hnp) trivial
theorem true_ne_false : ¬true = false :=
ne_false_of_self trivial
end
infixl ` == `:50 := heq
section
universe variable u
variables {A B C : Type.{u}} {a a' : A} {b b' : B} {c : C}
theorem eq_of_heq (H : a == a') : a = a' :=
have H₁ : ∀ (Ht : A = A), eq.rec a Ht = a, from
λ Ht, eq.refl a,
heq.rec H₁ H (eq.refl A)
theorem heq.elim {A : Type} {a : A} {P : A → Type} {b : A} (H₁ : a == b)
: P a → P b := eq.rec_on (eq_of_heq H₁)
theorem heq.subst {P : ∀T : Type, T → Prop} : a == b → P A a → P B b :=
heq.rec_on
theorem heq.symm (H : a == b) : b == a :=
heq.rec_on H (heq.refl a)
theorem heq_of_eq (H : a = a') : a == a' :=
eq.subst H (heq.refl a)
theorem heq.trans (H₁ : a == b) (H₂ : b == c) : a == c :=
heq.subst H₂ H₁
theorem heq_of_heq_of_eq (H₁ : a == b) (H₂ : b = b') : a == b' :=
heq.trans H₁ (heq_of_eq H₂)
theorem heq_of_eq_of_heq (H₁ : a = a') (H₂ : a' == b) : a == b :=
heq.trans (heq_of_eq H₁) H₂
definition type_eq_of_heq (H : a == b) : A = B :=
heq.rec_on H (eq.refl A)
end
open eq.ops
theorem eq_rec_heq {A : Type} {P : A → Type} {a a' : A} (H : a = a') (p : P a) : H ▹ p == p :=
eq.drec_on H !heq.refl
theorem heq_of_eq_rec_left {A : Type} {P : A → Type} : ∀ {a a' : A} {p₁ : P a} {p₂ : P a'} (e : a = a') (h₂ : e ▹ p₁ = p₂), p₁ == p₂
| a a p₁ p₂ (eq.refl a) h := eq.rec_on h !heq.refl
theorem heq_of_eq_rec_right {A : Type} {P : A → Type} : ∀ {a a' : A} {p₁ : P a} {p₂ : P a'} (e : a' = a) (h₂ : p₁ = e ▹ p₂), p₁ == p₂
| a a p₁ p₂ (eq.refl a) h := eq.rec_on h !heq.refl
theorem of_heq_true {a : Prop} (H : a == true) : a :=
of_eq_true (eq_of_heq H)
theorem eq_rec_compose : ∀ {A B C : Type} (p₁ : B = C) (p₂ : A = B) (a : A), p₁ ▹ (p₂ ▹ a : B) = (p₂ ⬝ p₁) ▹ a
| A A A (eq.refl A) (eq.refl A) a := calc
eq.refl A ▹ eq.refl A ▹ a = eq.refl A ▹ a : rfl
... = (eq.refl A ⬝ eq.refl A) ▹ a : {proof_irrel (eq.refl A) (eq.refl A ⬝ eq.refl A)}
theorem eq_rec_eq_eq_rec {A₁ A₂ : Type} {p : A₁ = A₂} : ∀ {a₁ : A₁} {a₂ : A₂}, p ▹ a₁ = a₂ → a₁ = p⁻¹ ▹ a₂ :=
eq.drec_on p (λ a₁ a₂ h, eq.drec_on h rfl)
theorem eq_rec_of_heq_left : ∀ {A₁ A₂ : Type} {a₁ : A₁} {a₂ : A₂} (h : a₁ == a₂), type_eq_of_heq h ▹ a₁ = a₂
| A A a a (heq.refl a) := rfl
theorem eq_rec_of_heq_right {A₁ A₂ : Type} {a₁ : A₁} {a₂ : A₂} (h : a₁ == a₂) : a₁ = (type_eq_of_heq h)⁻¹ ▹ a₂ :=
eq_rec_eq_eq_rec (eq_rec_of_heq_left h)
attribute heq.refl [refl]
attribute heq.trans [trans]
attribute heq_of_heq_of_eq [trans]
attribute heq_of_eq_of_heq [trans]
attribute heq.symm [symm]
theorem cast_heq : ∀ {A B : Type} (H : A = B) (a : A), cast H a == a
| A A (eq.refl A) a := !heq.refl
/- and -/
notation a /\ b := and a b
notation a ∧ b := and a b
variables {a b c d : Prop}
attribute and.rec [elim]
attribute and.intro [intro!]
theorem and.elim (H₁ : a ∧ b) (H₂ : a → b → c) : c :=
and.rec H₂ H₁
theorem and.swap : a ∧ b → b ∧ a :=
and.rec (λHa Hb, and.intro Hb Ha)
/- or -/
notation a \/ b := or a b
notation a ∨ b := or a b
attribute or.rec [elim]
namespace or
theorem elim (H₁ : a ∨ b) (H₂ : a → c) (H₃ : b → c) : c :=
or.rec H₂ H₃ H₁
end or
theorem non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) :=
assume not_em : ¬(a ∨ ¬a),
have neg_a : ¬a, from
assume pos_a : a, absurd (or.inl pos_a) not_em,
absurd (or.inr neg_a) not_em
theorem or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl
/- iff -/
definition iff (a b : Prop) := (a → b) ∧ (b → a)
notation a <-> b := iff a b
notation a ↔ b := iff a b
theorem iff.intro : (a → b) → (b → a) → (a ↔ b) := and.intro
attribute iff.intro [intro!]
theorem iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := and.rec
attribute iff.elim [recursor 5] [elim]
theorem iff.elim_left : (a ↔ b) → a → b := and.left
definition iff.mp := @iff.elim_left
theorem iff.elim_right : (a ↔ b) → b → a := and.right
definition iff.mpr := @iff.elim_right
theorem iff.refl [refl] (a : Prop) : a ↔ a :=
iff.intro (assume H, H) (assume H, H)
theorem iff.rfl {a : Prop} : a ↔ a :=
iff.refl a
theorem iff.trans [trans] (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c :=
iff.intro
(assume Ha, iff.mp H₂ (iff.mp H₁ Ha))
(assume Hc, iff.mpr H₁ (iff.mpr H₂ Hc))
theorem iff.symm [symm] (H : a ↔ b) : b ↔ a :=
iff.intro (iff.elim_right H) (iff.elim_left H)
theorem iff.comm : (a ↔ b) ↔ (b ↔ a) :=
iff.intro iff.symm iff.symm
theorem iff.of_eq {a b : Prop} (H : a = b) : a ↔ b :=
eq.rec_on H iff.rfl
theorem not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b :=
iff.intro
(assume (Hna : ¬ a) (Hb : b), Hna (iff.elim_right H₁ Hb))
(assume (Hnb : ¬ b) (Ha : a), Hnb (iff.elim_left H₁ Ha))
theorem of_iff_true (H : a ↔ true) : a :=
iff.mp (iff.symm H) trivial
theorem not_of_iff_false : (a ↔ false) → ¬a := iff.mp
theorem iff_true_intro (H : a) : a ↔ true :=
iff.intro
(λ Hl, trivial)
(λ Hr, H)
theorem iff_false_intro (H : ¬a) : a ↔ false :=
iff.intro H !false.rec
theorem not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a :=
iff.intro
(λ (Hl : ¬¬¬a) (Ha : a), Hl (non_contradictory_intro Ha))
absurd
theorem imp_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a → b) ↔ (c → d) :=
iff.intro
(λHab Hc, iff.mp H2 (Hab (iff.mpr H1 Hc)))
(λHcd Ha, iff.mpr H2 (Hcd (iff.mp H1 Ha)))
theorem imp_congr_right (H : a → (b ↔ c)) : (a → b) ↔ (a → c) :=
iff.intro
(take Hab Ha, iff.elim_left (H Ha) (Hab Ha))
(take Hab Ha, iff.elim_right (H Ha) (Hab Ha))
theorem not_not_intro (Ha : a) : ¬¬a :=
assume Hna : ¬a, Hna Ha
theorem not_of_not_not_not (H : ¬¬¬a) : ¬a :=
λ Ha, absurd (not_not_intro Ha) H
theorem not_true [simp] : (¬ true) ↔ false :=
iff_false_intro (not_not_intro trivial)
theorem not_false_iff [simp] : (¬ false) ↔ true :=
iff_true_intro not_false
theorem not_congr [congr] (H : a ↔ b) : ¬a ↔ ¬b :=
iff.intro (λ H₁ H₂, H₁ (iff.mpr H H₂)) (λ H₁ H₂, H₁ (iff.mp H H₂))
theorem ne_self_iff_false [simp] {A : Type} (a : A) : (not (a = a)) ↔ false :=
iff.intro false_of_ne false.elim
theorem eq_self_iff_true [simp] {A : Type} (a : A) : (a = a) ↔ true :=
iff_true_intro rfl
theorem heq_self_iff_true [simp] {A : Type} (a : A) : (a == a) ↔ true :=
iff_true_intro (heq.refl a)
theorem iff_not_self [simp] (a : Prop) : (a ↔ ¬a) ↔ false :=
iff_false_intro (λ H,
have H' : ¬a, from (λ Ha, (iff.mp H Ha) Ha),
H' (iff.mpr H H'))
theorem not_iff_self [simp] (a : Prop) : (¬a ↔ a) ↔ false :=
iff_false_intro (λ H,
have H' : ¬a, from (λ Ha, (iff.mpr H Ha) Ha),
H' (iff.mp H H'))
theorem true_iff_false [simp] : (true ↔ false) ↔ false :=
iff_false_intro (λ H, iff.mp H trivial)
theorem false_iff_true [simp] : (false ↔ true) ↔ false :=
iff_false_intro (λ H, iff.mpr H trivial)
theorem false_of_true_iff_false : (true ↔ false) → false :=
assume H, iff.mp H trivial
/- and simp rules -/
theorem and.imp (H₂ : a → c) (H₃ : b → d) : a ∧ b → c ∧ d :=
and.rec (λHa Hb, and.intro (H₂ Ha) (H₃ Hb))
theorem and_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ∧ b) ↔ (c ∧ d) :=
iff.intro (and.imp (iff.mp H1) (iff.mp H2)) (and.imp (iff.mpr H1) (iff.mpr H2))
theorem and_congr_right (H : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) :=
iff.intro
(take Hab, obtain `a` `b`, from Hab, and.intro `a` (iff.elim_left (H `a`) `b`))
(take Hac, obtain `a` `c`, from Hac, and.intro `a` (iff.elim_right (H `a`) `c`))
theorem and.comm [simp] : a ∧ b ↔ b ∧ a :=
iff.intro and.swap and.swap
theorem and.assoc [simp] : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) :=
iff.intro
(and.rec (λ H' Hc, and.rec (λ Ha Hb, and.intro Ha (and.intro Hb Hc)) H'))
(and.rec (λ Ha, and.rec (λ Hb Hc, and.intro (and.intro Ha Hb) Hc)))
theorem and.left_comm [simp] : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) :=
iff.trans (iff.symm !and.assoc) (iff.trans (and_congr !and.comm !iff.refl) !and.assoc)
theorem and_iff_left {a b : Prop} (Hb : b) : (a ∧ b) ↔ a :=
iff.intro and.left (λHa, and.intro Ha Hb)
theorem and_iff_right {a b : Prop} (Ha : a) : (a ∧ b) ↔ b :=
iff.intro and.right (and.intro Ha)
theorem and_true [simp] (a : Prop) : a ∧ true ↔ a :=
and_iff_left trivial
theorem true_and [simp] (a : Prop) : true ∧ a ↔ a :=
and_iff_right trivial
theorem and_false [simp] (a : Prop) : a ∧ false ↔ false :=
iff_false_intro and.right
theorem false_and [simp] (a : Prop) : false ∧ a ↔ false :=
iff_false_intro and.left
theorem not_and_self [simp] (a : Prop) : (¬a ∧ a) ↔ false :=
iff_false_intro (λ H, and.elim H (λ H₁ H₂, absurd H₂ H₁))
theorem and_not_self [simp] (a : Prop) : (a ∧ ¬a) ↔ false :=
iff_false_intro (λ H, and.elim H (λ H₁ H₂, absurd H₁ H₂))
theorem and_self [simp] (a : Prop) : a ∧ a ↔ a :=
iff.intro and.left (assume H, and.intro H H)
/- or simp rules -/
theorem or.imp (H₂ : a → c) (H₃ : b → d) : a ∨ b → c ∨ d :=
or.rec (λ H, or.inl (H₂ H)) (λ H, or.inr (H₃ H))
theorem or.imp_left (H : a → b) : a ∨ c → b ∨ c :=
or.imp H id
theorem or.imp_right (H : a → b) : c ∨ a → c ∨ b :=
or.imp id H
theorem or_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ∨ b) ↔ (c ∨ d) :=
iff.intro (or.imp (iff.mp H1) (iff.mp H2)) (or.imp (iff.mpr H1) (iff.mpr H2))
theorem or.comm [simp] : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap
theorem or.assoc [simp] : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) :=
iff.intro
(or.rec (or.imp_right or.inl) (λ H, or.inr (or.inr H)))
(or.rec (λ H, or.inl (or.inl H)) (or.imp_left or.inr))
theorem or.left_comm [simp] : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) :=
iff.trans (iff.symm !or.assoc) (iff.trans (or_congr !or.comm !iff.refl) !or.assoc)
theorem or_true [simp] (a : Prop) : a ∨ true ↔ true :=
iff_true_intro (or.inr trivial)
theorem true_or [simp] (a : Prop) : true ∨ a ↔ true :=
iff_true_intro (or.inl trivial)
theorem or_false [simp] (a : Prop) : a ∨ false ↔ a :=
iff.intro (or.rec id false.elim) or.inl
theorem false_or [simp] (a : Prop) : false ∨ a ↔ a :=
iff.trans or.comm !or_false
theorem or_self [simp] (a : Prop) : a ∨ a ↔ a :=
iff.intro (or.rec id id) or.inl
/- or resolution rulse -/
definition or.resolve_left {a b : Prop} (H : a ∨ b) (na : ¬ a) : b :=
or.elim H (λ Ha, absurd Ha na) id
definition or.neg_resolve_left {a b : Prop} (H : ¬ a ∨ b) (Ha : a) : b :=
or.elim H (λ na, absurd Ha na) id
definition or.resolve_right {a b : Prop} (H : a ∨ b) (nb : ¬ b) : a :=
or.elim H id (λ Hb, absurd Hb nb)
definition or.neg_resolve_right {a b : Prop} (H : a ∨ ¬ b) (Hb : b) : a :=
or.elim H id (λ nb, absurd Hb nb)
/- iff simp rules -/
theorem iff_true [simp] (a : Prop) : (a ↔ true) ↔ a :=
iff.intro (assume H, iff.mpr H trivial) iff_true_intro
theorem true_iff [simp] (a : Prop) : (true ↔ a) ↔ a :=
iff.trans iff.comm !iff_true
theorem iff_false [simp] (a : Prop) : (a ↔ false) ↔ ¬ a :=
iff.intro and.left iff_false_intro
theorem false_iff [simp] (a : Prop) : (false ↔ a) ↔ ¬ a :=
iff.trans iff.comm !iff_false
theorem iff_self [simp] (a : Prop) : (a ↔ a) ↔ true :=
iff_true_intro iff.rfl
theorem iff_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ↔ b) ↔ (c ↔ d) :=
and_congr (imp_congr H1 H2) (imp_congr H2 H1)
/- exists -/
inductive Exists {A : Type} (P : A → Prop) : Prop :=
intro : ∀ (a : A), P a → Exists P
attribute Exists.intro [intro]
definition exists.intro := @Exists.intro
notation `exists` binders `, ` r:(scoped P, Exists P) := r
notation `∃` binders `, ` r:(scoped P, Exists P) := r
attribute Exists.rec [elim]
theorem exists.elim {A : Type} {p : A → Prop} {B : Prop}
(H1 : ∃x, p x) (H2 : ∀ (a : A), p a → B) : B :=
Exists.rec H2 H1
/- exists unique -/
definition exists_unique {A : Type} (p : A → Prop) :=
∃x, p x ∧ ∀y, p y → y = x
notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r
theorem exists_unique.intro [intro] {A : Type} {p : A → Prop} (w : A) (H1 : p w) (H2 : ∀y, p y → y = w) :
∃!x, p x :=
exists.intro w (and.intro H1 H2)
theorem exists_unique.elim [recursor 4] [elim] {A : Type} {p : A → Prop} {b : Prop}
(H2 : ∃!x, p x) (H1 : ∀x, p x → (∀y, p y → y = x) → b) : b :=
exists.elim H2 (λ w Hw, H1 w (and.left Hw) (and.right Hw))
theorem exists_unique_of_exists_of_unique {A : Type} {p : A → Prop}
(Hex : ∃ x, p x) (Hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x :=
exists.elim Hex (λ x px, exists_unique.intro x px (take y, suppose p y, Hunique y x this px))
theorem exists_of_exists_unique {A : Type} {p : A → Prop} (H : ∃! x, p x) : ∃ x, p x :=
exists.elim H (λ x Hx, exists.intro x (and.left Hx))
theorem unique_of_exists_unique {A : Type} {p : A → Prop}
(H : ∃! x, p x) {y₁ y₂ : A} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=
exists_unique.elim H
(take x, suppose p x,
assume unique : ∀ y, p y → y = x,
show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂)))
/- exists, forall, exists unique congruences -/
section
variables {A : Type} {p₁ p₂ : A → Prop}
theorem forall_congr [congr] {A : Type} {P Q : A → Prop} (H : ∀a, (P a ↔ Q a)) : (∀a, P a) ↔ ∀a, Q a :=
iff.intro (λp a, iff.mp (H a) (p a)) (λq a, iff.mpr (H a) (q a))
theorem exists_imp_exists {A : Type} {P Q : A → Prop} (H : ∀a, (P a → Q a)) (p : ∃a, P a) : ∃a, Q a :=
exists.elim p (λa Hp, exists.intro a (H a Hp))
theorem exists_congr [congr] {A : Type} {P Q : A → Prop} (H : ∀a, (P a ↔ Q a)) : (∃a, P a) ↔ ∃a, Q a :=
iff.intro
(exists_imp_exists (λa, iff.mp (H a)))
(exists_imp_exists (λa, iff.mpr (H a)))
theorem exists_unique_congr [congr] (H : ∀ x, p₁ x ↔ p₂ x) : (∃! x, p₁ x) ↔ (∃! x, p₂ x) :=
exists_congr (λx, and_congr (H x) (forall_congr (λy, imp_congr (H y) iff.rfl)))
end
/- decidable -/
inductive decidable [class] (p : Prop) : Type :=
| inl : p → decidable p
| inr : ¬p → decidable p
definition decidable_true [instance] : decidable true :=
decidable.inl trivial
definition decidable_false [instance] : decidable false :=
decidable.inr not_false
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
definition dite (c : Prop) [H : decidable c] {A : Type} : (c → A) → (¬ c → A) → A :=
decidable.rec_on H
/- if-then-else -/
definition ite (c : Prop) [H : decidable c] {A : Type} (t e : A) : A :=
decidable.rec_on H (λ Hc, t) (λ Hnc, e)
namespace decidable
variables {p q : Prop}
definition rec_on_true [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : p) (H4 : H1 H3)
: decidable.rec_on H H1 H2 :=
decidable.rec_on H (λh, H4) (λh, !false.rec (h H3))
definition rec_on_false [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : ¬p) (H4 : H2 H3)
: decidable.rec_on H H1 H2 :=
decidable.rec_on H (λh, false.rec _ (H3 h)) (λh, H4)
definition by_cases {q : Type} [C : decidable p] : (p → q) → (¬p → q) → q := !dite
theorem em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr
theorem by_contradiction [decidable p] (H : ¬p → false) : p :=
if H1 : p then H1 else false.rec _ (H H1)
end decidable
section
variables {p q : Prop}
open decidable
definition decidable_of_decidable_of_iff (Hp : decidable p) (H : p ↔ q) : decidable q :=
if Hp : p then inl (iff.mp H Hp)
else inr (iff.mp (not_iff_not_of_iff H) Hp)
definition decidable_of_decidable_of_eq (Hp : decidable p) (H : p = q) : decidable q :=
decidable_of_decidable_of_iff Hp (iff.of_eq H)
protected definition or.by_cases [decidable p] [decidable q] {A : Type}
(h : p ∨ q) (h₁ : p → A) (h₂ : q → A) : A :=
if hp : p then h₁ hp else
if hq : q then h₂ hq else
false.rec _ (or.elim h hp hq)
end
section
variables {p q : Prop}
open decidable (rec_on inl inr)
definition decidable_and [instance] [decidable p] [decidable q] : decidable (p ∧ q) :=
if hp : p then
if hq : q then inl (and.intro hp hq)
else inr (assume H : p ∧ q, hq (and.right H))
else inr (assume H : p ∧ q, hp (and.left H))
definition decidable_or [instance] [decidable p] [decidable q] : decidable (p ∨ q) :=
if hp : p then inl (or.inl hp) else
if hq : q then inl (or.inr hq) else
inr (or.rec hp hq)
definition decidable_not [instance] [decidable p] : decidable (¬p) :=
if hp : p then inr (absurd hp) else inl hp
definition decidable_implies [instance] [decidable p] [decidable q] : decidable (p → q) :=
if hp : p then
if hq : q then inl (assume H, hq)
else inr (assume H : p → q, absurd (H hp) hq)
else inl (assume Hp, absurd Hp hp)
definition decidable_iff [instance] [decidable p] [decidable q] : decidable (p ↔ q) :=
decidable_and
end
definition decidable_pred [reducible] {A : Type} (R : A → Prop) := Π (a : A), decidable (R a)
definition decidable_rel [reducible] {A : Type} (R : A → A → Prop) := Π (a b : A), decidable (R a b)
definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A)
definition decidable_ne [instance] {A : Type} [decidable_eq A] (a b : A) : decidable (a ≠ b) :=
decidable_implies
namespace bool
theorem ff_ne_tt : ff = tt → false
| [none]
end bool
open bool
definition is_dec_eq {A : Type} (p : A → A → bool) : Prop := ∀ ⦃x y : A⦄, p x y = tt → x = y
definition is_dec_refl {A : Type} (p : A → A → bool) : Prop := ∀x, p x x = tt
open decidable
protected definition bool.has_decidable_eq [instance] : ∀a b : bool, decidable (a = b)
| ff ff := inl rfl
| ff tt := inr ff_ne_tt
| tt ff := inr (ne.symm ff_ne_tt)
| tt tt := inl rfl
definition decidable_eq_of_bool_pred {A : Type} {p : A → A → bool} (H₁ : is_dec_eq p) (H₂ : is_dec_refl p) : decidable_eq A :=
take x y : A, if Hp : p x y = tt then inl (H₁ Hp)
else inr (assume Hxy : x = y, (eq.subst Hxy Hp) (H₂ y))
theorem decidable_eq_inl_refl {A : Type} [H : decidable_eq A] (a : A) : H a a = inl (eq.refl a) :=
match H a a with
| inl e := rfl
| inr n := absurd rfl n
end
open eq.ops
theorem decidable_eq_inr_neg {A : Type} [H : decidable_eq A] {a b : A} : Π n : a ≠ b, H a b = inr n :=
assume n,
match H a b with
| inl e := absurd e n
| inr n₁ := proof_irrel n n₁ ▸ rfl
end
/- inhabited -/
inductive inhabited [class] (A : Type) : Type :=
mk : A → inhabited A
protected definition inhabited.value {A : Type} : inhabited A → A :=
inhabited.rec (λa, a)
protected definition inhabited.destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B :=
inhabited.rec H2 H1
definition default (A : Type) [H : inhabited A] : A :=
inhabited.value H
definition arbitrary [irreducible] (A : Type) [H : inhabited A] : A :=
inhabited.value H
definition Prop.is_inhabited [instance] : inhabited Prop :=
inhabited.mk true
definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) :=
inhabited.rec_on H (λb, inhabited.mk (λa, b))
definition inhabited_Pi [instance] (A : Type) {B : A → Type} [Πx, inhabited (B x)] :
inhabited (Πx, B x) :=
inhabited.mk (λa, !default)
protected definition bool.is_inhabited [instance] : inhabited bool :=
inhabited.mk ff
protected definition pos_num.is_inhabited [instance] : inhabited pos_num :=
inhabited.mk pos_num.one
protected definition num.is_inhabited [instance] : inhabited num :=
inhabited.mk num.zero
inductive nonempty [class] (A : Type) : Prop :=
intro : A → nonempty A
protected definition nonempty.elim {A : Type} {B : Prop} (H1 : nonempty A) (H2 : A → B) : B :=
nonempty.rec H2 H1
theorem nonempty_of_inhabited [instance] {A : Type} [inhabited A] : nonempty A :=
nonempty.intro !default
theorem nonempty_of_exists {A : Type} {P : A → Prop} : (∃x, P x) → nonempty A :=
Exists.rec (λw H, nonempty.intro w)
/- subsingleton -/
inductive subsingleton [class] (A : Type) : Prop :=
intro : (∀ a b : A, a = b) → subsingleton A
protected definition subsingleton.elim {A : Type} [H : subsingleton A] : ∀(a b : A), a = b :=
subsingleton.rec (λp, p) H
protected definition subsingleton.helim {A B : Type} [H : subsingleton A] (h : A = B) (a : A) (b : B) : a == b :=
by induction h; apply heq_of_eq; apply subsingleton.elim
definition subsingleton_prop [instance] (p : Prop) : subsingleton p :=
subsingleton.intro (λa b, !proof_irrel)
definition subsingleton_decidable [instance] (p : Prop) : subsingleton (decidable p) :=
subsingleton.intro (λ d₁,
match d₁ with
| inl t₁ := (λ d₂,
match d₂ with
| inl t₂ := eq.rec_on (proof_irrel t₁ t₂) rfl
| inr f₂ := absurd t₁ f₂
end)
| inr f₁ := (λ d₂,
match d₂ with
| inl t₂ := absurd t₂ f₁
| inr f₂ := eq.rec_on (proof_irrel f₁ f₂) rfl
end)
end)
protected theorem rec_subsingleton {p : Prop} [H : decidable p]
{H1 : p → Type} {H2 : ¬p → Type}
[H3 : Π(h : p), subsingleton (H1 h)] [H4 : Π(h : ¬p), subsingleton (H2 h)]
: subsingleton (decidable.rec_on H H1 H2) :=
decidable.rec_on H (λh, H3 h) (λh, H4 h) --this can be proven using dependent version of "by_cases"
theorem if_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (ite c t e) = t :=
decidable.rec
(λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e))
(λ Hnc : ¬c, absurd Hc Hnc)
H
theorem if_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (ite c t e) = e :=
decidable.rec
(λ Hc : c, absurd Hc Hnc)
(λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e))
H
theorem if_t_t [simp] (c : Prop) [H : decidable c] {A : Type} (t : A) : (ite c t t) = t :=
decidable.rec
(λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t))
(λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t))
H
theorem implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t :=
assume Hc, eq.rec_on (if_pos Hc) h
theorem implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e :=
assume Hnc, eq.rec_on (if_neg Hnc) h
theorem if_ctx_congr {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c]
{x y u v : A}
(h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) :
ite b x y = ite c u v :=
decidable.rec_on dec_b
(λ hp : b, calc
ite b x y = x : if_pos hp
... = u : h_t (iff.mp h_c hp)
... = ite c u v : if_pos (iff.mp h_c hp))
(λ hn : ¬b, calc
ite b x y = y : if_neg hn
... = v : h_e (iff.mp (not_iff_not_of_iff h_c) hn)
... = ite c u v : if_neg (iff.mp (not_iff_not_of_iff h_c) hn))
theorem if_congr [congr] {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c]
{x y u v : A}
(h_c : b ↔ c) (h_t : x = u) (h_e : y = v) :
ite b x y = ite c u v :=
@if_ctx_congr A b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e)
theorem if_ctx_simp_congr {A : Type} {b c : Prop} [dec_b : decidable b] {x y u v : A}
(h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) :
ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) :=
@if_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x y u v h_c h_t h_e
theorem if_simp_congr [congr] {A : Type} {b c : Prop} [dec_b : decidable b] {x y u v : A}
(h_c : b ↔ c) (h_t : x = u) (h_e : y = v) :
ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) :=
@if_ctx_simp_congr A b c dec_b x y u v h_c (λ h, h_t) (λ h, h_e)
definition if_true [simp] {A : Type} (t e : A) : (if true then t else e) = t :=
if_pos trivial
definition if_false [simp] {A : Type} (t e : A) : (if false then t else e) = e :=
if_neg not_false
theorem if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c]
(h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) :
ite b x y ↔ ite c u v :=
decidable.rec_on dec_b
(λ hp : b, calc
ite b x y ↔ x : iff.of_eq (if_pos hp)
... ↔ u : h_t (iff.mp h_c hp)
... ↔ ite c u v : iff.of_eq (if_pos (iff.mp h_c hp)))
(λ hn : ¬b, calc
ite b x y ↔ y : iff.of_eq (if_neg hn)
... ↔ v : h_e (iff.mp (not_iff_not_of_iff h_c) hn)
... ↔ ite c u v : iff.of_eq (if_neg (iff.mp (not_iff_not_of_iff h_c) hn)))
theorem if_congr_prop [congr] {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c]
(h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) :
ite b x y ↔ ite c u v :=
if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e)
theorem if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b]
(h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) :
ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) :=
@if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e
theorem if_simp_congr_prop [congr] {b c x y u v : Prop} [dec_b : decidable b]
(h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) :
ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) :=
@if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e)
theorem dif_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : dite c t e = t Hc :=
decidable.rec
(λ Hc : c, eq.refl (@dite c (decidable.inl Hc) A t e))
(λ Hnc : ¬c, absurd Hc Hnc)
H
theorem dif_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : dite c t e = e Hnc :=
decidable.rec
(λ Hc : c, absurd Hc Hnc)
(λ Hnc : ¬c, eq.refl (@dite c (decidable.inr Hnc) A t e))
H
theorem dif_ctx_congr {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c]
{x : b → A} {u : c → A} {y : ¬b → A} {v : ¬c → A}
(h_c : b ↔ c)
(h_t : ∀ (h : c), x (iff.mpr h_c h) = u h)
(h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) :
(@dite b dec_b A x y) = (@dite c dec_c A u v) :=
decidable.rec_on dec_b
(λ hp : b, calc
dite b x y = x hp : dif_pos hp
... = x (iff.mpr h_c (iff.mp h_c hp)) : proof_irrel
... = u (iff.mp h_c hp) : h_t
... = dite c u v : dif_pos (iff.mp h_c hp))
(λ hn : ¬b, let h_nc : ¬b ↔ ¬c := not_iff_not_of_iff h_c in calc
dite b x y = y hn : dif_neg hn
... = y (iff.mpr h_nc (iff.mp h_nc hn)) : proof_irrel
... = v (iff.mp h_nc hn) : h_e
... = dite c u v : dif_neg (iff.mp h_nc hn))
theorem dif_ctx_simp_congr {A : Type} {b c : Prop} [dec_b : decidable b]
{x : b → A} {u : c → A} {y : ¬b → A} {v : ¬c → A}
(h_c : b ↔ c)
(h_t : ∀ (h : c), x (iff.mpr h_c h) = u h)
(h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) :
(@dite b dec_b A x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) A u v) :=
@dif_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e
-- Remark: dite and ite are "definitionally equal" when we ignore the proofs.
theorem dite_ite_eq (c : Prop) [decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e :=
rfl
definition is_true (c : Prop) [decidable c] : Prop :=
if c then true else false
definition is_false (c : Prop) [decidable c] : Prop :=
if c then false else true
definition of_is_true {c : Prop} [H₁ : decidable c] (H₂ : is_true c) : c :=
decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, !false.rec (if_neg Hnc ▸ H₂))
notation `dec_trivial` := of_is_true trivial
theorem not_of_not_is_true {c : Prop} [decidable c] (H : ¬ is_true c) : ¬ c :=
if Hc : c then absurd trivial (if_pos Hc ▸ H) else Hc
theorem not_of_is_false {c : Prop} [decidable c] (H : is_false c) : ¬ c :=
if Hc : c then !false.rec (if_pos Hc ▸ H) else Hc
theorem of_not_is_false {c : Prop} [decidable c] (H : ¬ is_false c) : c :=
if Hc : c then Hc else absurd trivial (if_neg Hc ▸ H)
-- The following symbols should not be considered in the pattern inference procedure used by
-- heuristic instantiation.
attribute and or not iff ite dite eq ne heq [no_pattern]
-- namespace used to collect congruence rules for "contextual simplification"
namespace contextual
attribute if_ctx_simp_congr [congr]
attribute if_ctx_simp_congr_prop [congr]
attribute dif_ctx_simp_congr [congr]
end contextual
|
1ff77f030b78e67f0b9524c049e7059ad3fc0323 | 556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e | /src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_ec_double_soundness.lean | c4d6b2b1d6b376e28cde0ba4420ec48d40313301 | [] | permissive | starkware-libs/formal-proofs | d6b731604461bf99e6ba820e68acca62a21709e8 | f5fa4ba6a471357fd171175183203d0b437f6527 | refs/heads/master | 1,691,085,444,753 | 1,690,507,386,000 | 1,690,507,386,000 | 410,476,629 | 32 | 9 | Apache-2.0 | 1,690,506,773,000 | 1,632,639,790,000 | Lean | UTF-8 | Lean | false | false | 32,087 | lean | /-
File: signature_recover_public_key_ec_double_soundness.lean
Autogenerated file.
-/
import starkware.cairo.lean.semantics.soundness.hoare
import .signature_recover_public_key_code
import ..signature_recover_public_key_spec
import .signature_recover_public_key_compute_doubling_slope_soundness
open tactic
open starkware.cairo.common.cairo_secp.ec
open starkware.cairo.common.cairo_secp.bigint
open starkware.cairo.common.cairo_secp.field
variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]
variable mem : F → F
variable σ : register_state F
/- starkware.cairo.common.cairo_secp.ec.ec_double autogenerated soundness theorem -/
theorem auto_sound_ec_double_block5
-- An independent ap variable.
(ap : F)
-- arguments
(range_check_ptr : F) (point : EcPoint F)
-- code is in memory at σ.pc
(h_mem : mem_at mem code_ec_double σ.pc)
-- all dependencies are in memory
(h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 244))
(h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 232))
(h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 212))
(h_mem_7 : mem_at mem code_verify_zero (σ.pc - 196))
(h_mem_12 : mem_at mem code_compute_doubling_slope (σ.pc - 68))
-- input arguments on the stack
(hin_range_check_ptr : range_check_ptr = mem (σ.fp - 9))
(hin_point : point = cast_EcPoint mem (σ.fp - 8))
(νbound : ℕ)
-- conclusion
: ensuresb_ret νbound mem
{pc := σ.pc + 14, ap := ap, fp := σ.fp}
(λ κ τ,
∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 9)) (mem $ τ.ap - 7)
(auto_spec_ec_double_block5 mem κ range_check_ptr point (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) :=
begin
have h_mem_rec := h_mem,
unpack_memory code_ec_double at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72⟩,
-- function call
step_assert_eq hpc14 with arg0,
step_assert_eq hpc15 with arg1,
step_assert_eq hpc16 with arg2,
step_assert_eq hpc17 with arg3,
step_assert_eq hpc18 with arg4,
step_assert_eq hpc19 with arg5,
step_assert_eq hpc20 with arg6,
step_sub hpc21 (auto_sound_compute_doubling_slope mem _ range_check_ptr point _ _ _ _ _ _ _),
{ rw hpc22, norm_num2, exact h_mem_12 },
{ rw hpc22, norm_num2, exact h_mem_4 },
{ rw hpc22, norm_num2, exact h_mem_5 },
{ rw hpc22, norm_num2, exact h_mem_6 },
{ rw hpc22, norm_num2, exact h_mem_7 },
{ try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
intros κ_call23 ap23 h_call23,
rcases h_call23 with ⟨h_call23_ap_offset, h_call23⟩,
rcases h_call23 with ⟨rc_m23, rc_mle23, hl_range_check_ptr₁, h_call23⟩,
generalize' hr_rev_range_check_ptr₁: mem (ap23 - 4) = range_check_ptr₁,
have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,
generalize' hr_rev_slope: cast_BigInt3 mem (ap23 - 3) = slope,
simp only [hr_rev_slope] at h_call23,
have htv_slope := hr_rev_slope.symm, clear hr_rev_slope,
try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at hl_range_check_ptr₁ },
rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,
try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at h_call23 },
rw [hin_range_check_ptr] at h_call23,
clear arg0 arg1 arg2 arg3 arg4 arg5 arg6,
-- function call
step_sub hpc23 (auto_sound_unreduced_sqr mem _ slope _ _),
{ rw hpc24, norm_num2, exact h_mem_6 },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { simp only [h_call23_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
intros κ_call25 ap25 h_call25,
rcases h_call25 with ⟨h_call25_ap_offset, h_call25⟩,
generalize' hr_rev_slope_sqr: cast_UnreducedBigInt3 mem (ap25 - 3) = slope_sqr,
simp only [hr_rev_slope_sqr] at h_call25,
have htv_slope_sqr := hr_rev_slope_sqr.symm, clear hr_rev_slope_sqr,
clear ,
-- function call
step_assert_eq hpc25 with arg0,
step_sub hpc26 (auto_sound_nondet_bigint3 mem _ range_check_ptr₁ _ _),
{ rw hpc27, norm_num2, exact h_mem_4 },
{ try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr] },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [arg0] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
intros κ_call28 ap28 h_call28,
rcases h_call28 with ⟨h_call28_ap_offset, h_call28⟩,
rcases h_call28 with ⟨rc_m28, rc_mle28, hl_range_check_ptr₂, h_call28⟩,
generalize' hr_rev_range_check_ptr₂: mem (ap28 - 4) = range_check_ptr₂,
have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,
generalize' hr_rev_new_x: cast_BigInt3 mem (ap28 - 3) = new_x,
simp only [hr_rev_new_x] at h_call28,
have htv_new_x := hr_rev_new_x.symm, clear hr_rev_new_x,
try { simp only [arg0] at hl_range_check_ptr₂ },
try { rw [h_call25_ap_offset] at hl_range_check_ptr₂ }, try { arith_simps at hl_range_check_ptr₂ },
rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,
try { simp only [arg0] at h_call28 },
try { rw [h_call25_ap_offset] at h_call28 }, try { arith_simps at h_call28 },
rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call28,
clear arg0,
-- function call
step_assert_eq hpc28 with arg0,
step_sub hpc29 (auto_sound_nondet_bigint3 mem _ range_check_ptr₂ _ _),
{ rw hpc30, norm_num2, exact h_mem_4 },
{ try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x] },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [arg0] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset, h_call28_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
intros κ_call31 ap31 h_call31,
rcases h_call31 with ⟨h_call31_ap_offset, h_call31⟩,
rcases h_call31 with ⟨rc_m31, rc_mle31, hl_range_check_ptr₃, h_call31⟩,
generalize' hr_rev_range_check_ptr₃: mem (ap31 - 4) = range_check_ptr₃,
have htv_range_check_ptr₃ := hr_rev_range_check_ptr₃.symm, clear hr_rev_range_check_ptr₃,
generalize' hr_rev_new_y: cast_BigInt3 mem (ap31 - 3) = new_y,
simp only [hr_rev_new_y] at h_call31,
have htv_new_y := hr_rev_new_y.symm, clear hr_rev_new_y,
try { simp only [arg0] at hl_range_check_ptr₃ },
rw [←htv_range_check_ptr₃, ←htv_range_check_ptr₂] at hl_range_check_ptr₃,
try { simp only [arg0] at h_call31 },
rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call31,
clear arg0,
-- function call
step_assert_eq hpc31 with arg0,
step_assert_eq hpc32 hpc33 with arg1,
step_assert_eq hpc34 with arg2,
step_assert_eq hpc35 with arg3,
step_assert_eq hpc36 hpc37 with arg4,
step_assert_eq hpc38 with arg5,
step_assert_eq hpc39 with arg6,
step_assert_eq hpc40 hpc41 with arg7,
step_assert_eq hpc42 with arg8,
step_assert_eq hpc43 with arg9,
step_assert_eq hpc44 with arg10,
step_assert_eq hpc45 with arg11,
step_assert_eq hpc46 with arg12,
step_sub hpc47 (auto_sound_verify_zero mem _ range_check_ptr₃ {
d0 := slope_sqr.d0 - new_x.d0 - 2 * point.x.d0,
d1 := slope_sqr.d1 - new_x.d1 - 2 * point.x.d1,
d2 := slope_sqr.d2 - new_x.d2 - 2 * point.x.d2
} _ _ _),
{ rw hpc48, norm_num2, exact h_mem_7 },
{ try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y] },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), arg1, arg2, (eq_sub_of_eq_add arg3), arg4, arg5, (eq_sub_of_eq_add arg6), arg7, arg8, arg9, (eq_sub_of_eq_add arg10), (eq_sub_of_eq_add arg11), (eq_sub_of_eq_add arg12)] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset, h_call28_ap_offset, h_call31_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y] },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), arg1, arg2, (eq_sub_of_eq_add arg3), arg4, arg5, (eq_sub_of_eq_add arg6), arg7, arg8, arg9, (eq_sub_of_eq_add arg10), (eq_sub_of_eq_add arg11), (eq_sub_of_eq_add arg12)] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset, h_call28_ap_offset, h_call31_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
intros κ_call49 ap49 h_call49,
rcases h_call49 with ⟨h_call49_ap_offset, h_call49⟩,
rcases h_call49 with ⟨rc_m49, rc_mle49, hl_range_check_ptr₄, h_call49⟩,
generalize' hr_rev_range_check_ptr₄: mem (ap49 - 1) = range_check_ptr₄,
have htv_range_check_ptr₄ := hr_rev_range_check_ptr₄.symm, clear hr_rev_range_check_ptr₄,
try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at hl_range_check_ptr₄ },
rw [←htv_range_check_ptr₄, ←htv_range_check_ptr₃] at hl_range_check_ptr₄,
try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at h_call49 },
rw [←htv_range_check_ptr₃, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call49,
clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 arg11 arg12,
-- function call
step_assert_eq hpc49 with arg0,
step_assert_eq hpc50 with arg1,
step_assert_eq hpc51 with arg2,
step_assert_eq hpc52 with arg3,
step_assert_eq hpc53 with arg4,
step_assert_eq hpc54 with arg5,
step_sub hpc55 (auto_sound_unreduced_mul mem _ {
d0 := point.x.d0 - new_x.d0,
d1 := point.x.d1 - new_x.d1,
d2 := point.x.d2 - new_x.d2
} slope _ _ _),
{ rw hpc56, norm_num2, exact h_mem_5 },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄] },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset, h_call28_ap_offset, h_call31_ap_offset, h_call49_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄] },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset, h_call28_ap_offset, h_call31_ap_offset, h_call49_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
intros κ_call57 ap57 h_call57,
rcases h_call57 with ⟨h_call57_ap_offset, h_call57⟩,
generalize' hr_rev_x_diff_slope: cast_UnreducedBigInt3 mem (ap57 - 3) = x_diff_slope,
simp only [hr_rev_x_diff_slope] at h_call57,
have htv_x_diff_slope := hr_rev_x_diff_slope.symm, clear hr_rev_x_diff_slope,
clear arg0 arg1 arg2 arg3 arg4 arg5,
-- function call
step_assert_eq hpc57 with arg0,
step_assert_eq hpc58 with arg1,
step_assert_eq hpc59 with arg2,
step_assert_eq hpc60 with arg3,
step_assert_eq hpc61 with arg4,
step_assert_eq hpc62 with arg5,
step_assert_eq hpc63 with arg6,
step_sub hpc64 (auto_sound_verify_zero mem _ range_check_ptr₄ {
d0 := x_diff_slope.d0 - point.y.d0 - new_y.d0,
d1 := x_diff_slope.d1 - point.y.d1 - new_y.d1,
d2 := x_diff_slope.d2 - point.y.d2 - new_y.d2
} _ _ _),
{ rw hpc65, norm_num2, exact h_mem_7 },
{ try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope] },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), (eq_sub_of_eq_add arg6)] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset, h_call28_ap_offset, h_call31_ap_offset, h_call49_ap_offset, h_call57_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope] },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), (eq_sub_of_eq_add arg6)] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset, h_call28_ap_offset, h_call31_ap_offset, h_call49_ap_offset, h_call57_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
intros κ_call66 ap66 h_call66,
rcases h_call66 with ⟨h_call66_ap_offset, h_call66⟩,
rcases h_call66 with ⟨rc_m66, rc_mle66, hl_range_check_ptr₅, h_call66⟩,
generalize' hr_rev_range_check_ptr₅: mem (ap66 - 1) = range_check_ptr₅,
have htv_range_check_ptr₅ := hr_rev_range_check_ptr₅.symm, clear hr_rev_range_check_ptr₅,
try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at hl_range_check_ptr₅ },
try { rw [h_call57_ap_offset] at hl_range_check_ptr₅ }, try { arith_simps at hl_range_check_ptr₅ },
rw [←htv_range_check_ptr₅, ←htv_range_check_ptr₄] at hl_range_check_ptr₅,
try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at h_call66 },
try { rw [h_call57_ap_offset] at h_call66 }, try { arith_simps at h_call66 },
rw [←htv_range_check_ptr₄, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call66,
clear arg0 arg1 arg2 arg3 arg4 arg5 arg6,
-- return
step_assert_eq hpc66 with hret0,
step_assert_eq hpc67 with hret1,
step_assert_eq hpc68 with hret2,
step_assert_eq hpc69 with hret3,
step_assert_eq hpc70 with hret4,
step_assert_eq hpc71 with hret5,
step_ret hpc72,
-- finish
step_done, use_only [rfl, rfl],
-- range check condition
use_only (rc_m23+rc_m28+rc_m31+rc_m49+rc_m66+0+0), split,
linarith [rc_mle23, rc_mle28, rc_mle31, rc_mle49, rc_mle66],
split,
{ arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5] },
rw [←htv_range_check_ptr₅, hl_range_check_ptr₅, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],
try { arith_simps, refl <|> norm_cast }, try { refl } },
intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },
have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,
-- Final Proof
dsimp [auto_spec_ec_double_block5],
try { norm_num1 }, try { arith_simps },
use_only [κ_call23],
use_only [range_check_ptr₁],
use_only [slope],
have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,
have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },
have spec23 := h_call23 rc_h_range_check_ptr',
rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec23,
try { dsimp at spec23, arith_simps at spec23 },
use_only [spec23],
use_only [κ_call25],
use_only [slope_sqr],
try { dsimp at h_call25, arith_simps at h_call25 },
try { use_only [h_call25] },
use_only [κ_call28],
use_only [range_check_ptr₂],
use_only [new_x],
have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,
have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },
have spec28 := h_call28 rc_h_range_check_ptr₁',
rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec28,
try { dsimp at spec28, arith_simps at spec28 },
use_only [spec28],
use_only [κ_call31],
use_only [range_check_ptr₃],
use_only [new_y],
have rc_h_range_check_ptr₃ := range_checked_offset' rc_h_range_check_ptr₂,
have rc_h_range_check_ptr₃' := range_checked_add_right rc_h_range_check_ptr₃, try { norm_cast at rc_h_range_check_ptr₃' },
have spec31 := h_call31 rc_h_range_check_ptr₂',
rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←htv_range_check_ptr₃] at spec31,
try { dsimp at spec31, arith_simps at spec31 },
use_only [spec31],
use_only [κ_call49],
use_only [range_check_ptr₄],
have rc_h_range_check_ptr₄ := range_checked_offset' rc_h_range_check_ptr₃,
have rc_h_range_check_ptr₄' := range_checked_add_right rc_h_range_check_ptr₄, try { norm_cast at rc_h_range_check_ptr₄' },
have spec49 := h_call49 rc_h_range_check_ptr₃',
rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←htv_range_check_ptr₄] at spec49,
try { dsimp at spec49, arith_simps at spec49 },
use_only [spec49],
use_only [κ_call57],
use_only [x_diff_slope],
try { dsimp at h_call57, arith_simps at h_call57 },
try { use_only [h_call57] },
use_only [κ_call66],
use_only [range_check_ptr₅],
have rc_h_range_check_ptr₅ := range_checked_offset' rc_h_range_check_ptr₄,
have rc_h_range_check_ptr₅' := range_checked_add_right rc_h_range_check_ptr₅, try { norm_cast at rc_h_range_check_ptr₅' },
have spec66 := h_call66 rc_h_range_check_ptr₄',
rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←hl_range_check_ptr₄, ←htv_range_check_ptr₅] at spec66,
try { dsimp at spec66, arith_simps at spec66 },
use_only [spec66],
try { split, linarith },
try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope, htv_range_check_ptr₅] }, },
try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },
try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5] },
try { simp only [h_call23_ap_offset, h_call25_ap_offset, h_call28_ap_offset, h_call31_ap_offset, h_call49_ap_offset, h_call57_ap_offset, h_call66_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
end
theorem auto_sound_ec_double
-- arguments
(range_check_ptr : F) (point : EcPoint F)
-- code is in memory at σ.pc
(h_mem : mem_at mem code_ec_double σ.pc)
-- all dependencies are in memory
(h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 244))
(h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 232))
(h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 212))
(h_mem_7 : mem_at mem code_verify_zero (σ.pc - 196))
(h_mem_12 : mem_at mem code_compute_doubling_slope (σ.pc - 68))
-- input arguments on the stack
(hin_range_check_ptr : range_check_ptr = mem (σ.fp - 9))
(hin_point : point = cast_EcPoint mem (σ.fp - 8))
-- conclusion
: ensures_ret mem σ (λ κ τ,
∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 9)) (mem $ τ.ap - 7)
(spec_ec_double mem κ range_check_ptr point (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) :=
begin
apply ensures_of_ensuresb, intro νbound,
have h_mem_rec := h_mem,
unpack_memory code_ec_double at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72⟩,
-- if statement
step_jnz hpc0 hpc1 with hcond hcond,
{
-- if: positive branch
have a0 : point.x.d0 = 0, {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [hcond] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a0 }, try { arith_simps at a0 },
clear hcond,
-- if statement
step_jnz hpc2 hpc3 with hcond hcond,
{
-- if: positive branch
have a2 : point.x.d1 = 0, {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [hcond] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a2 }, try { arith_simps at a2 },
clear hcond,
-- if statement
step_jnz hpc4 hpc5 with hcond hcond,
{
-- if: positive branch
have a4 : point.x.d2 = 0, {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [hcond] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a4 }, try { arith_simps at a4 },
clear hcond,
-- return
step_assert_eq hpc6 with hret0,
step_assert_eq hpc7 with hret1,
step_assert_eq hpc8 with hret2,
step_assert_eq hpc9 with hret3,
step_assert_eq hpc10 with hret4,
step_assert_eq hpc11 with hret5,
step_assert_eq hpc12 with hret6,
step_ret hpc13,
-- finish
step_done, use_only [rfl, rfl],
-- range check condition
use_only (0+0), split,
linarith [],
split,
{ arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5 ,hret6] },
try { arith_simps, refl <|> norm_cast }, try { refl } },
intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },
have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,
-- Final Proof
-- user-provided reduction
suffices auto_spec: auto_spec_ec_double mem _ range_check_ptr point _ _,
{ apply sound_ec_double, apply auto_spec },
-- prove the auto generated assertion
dsimp [auto_spec_ec_double],
try { norm_num1 }, try { arith_simps },
left,
use_only [a0],
left,
use_only [a2],
left,
use_only [a4],
try { split, linarith },
try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] }, },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5, hret6] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
{
-- if: negative branch
have a4 : point.x.d2 ≠ 0, {
try { simp only [ne.def] },
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [hcond] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a4 }, try { arith_simps at a4 },
clear hcond,
-- Use the block soundness theorem.
apply ensuresb_ret_trans (auto_sound_ec_double_block5 mem σ _ range_check_ptr point h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_12 hin_range_check_ptr hin_point νbound),
intros κ_block5 τ, try { arith_simps },
intro h_block5,
rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩,
-- range check condition
use_only (rc_m_block5+0+0), split,
linarith [rc_m_le_block5],
split,
{ arith_simps, try { simp only [hblk_range_check_ptr₁] },
try { arith_simps, refl <|> norm_cast }, try { refl } },
intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },
have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,
-- Final Proof
-- user-provided reduction
suffices auto_spec: auto_spec_ec_double mem _ range_check_ptr point _ _,
{ apply sound_ec_double, apply auto_spec },
-- prove the auto generated assertion
dsimp [auto_spec_ec_double],
try { norm_num1 }, try { arith_simps },
left,
use_only [a0],
left,
use_only [a2],
right,
use_only [a4],
have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,
have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },
have h_block5' := h_block5 rc_h_range_check_ptr',
try { rw [←hin_range_check_ptr] at h_block5' },
try { dsimp at h_block5, arith_simps at h_block5' },
have h_block5 := h_block5',
use_only[κ_block5],
use [h_block5],
try { linarith }
}
},
{
-- if: negative branch
have a2 : point.x.d1 ≠ 0, {
try { simp only [ne.def] },
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [hcond] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a2 }, try { arith_simps at a2 },
clear hcond,
-- Use the block soundness theorem.
apply ensuresb_ret_trans (auto_sound_ec_double_block5 mem σ _ range_check_ptr point h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_12 hin_range_check_ptr hin_point νbound),
intros κ_block5 τ, try { arith_simps },
intro h_block5,
rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩,
-- range check condition
use_only (rc_m_block5+0+0), split,
linarith [rc_m_le_block5],
split,
{ arith_simps, try { simp only [hblk_range_check_ptr₁] },
try { arith_simps, refl <|> norm_cast }, try { refl } },
intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },
have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,
-- Final Proof
-- user-provided reduction
suffices auto_spec: auto_spec_ec_double mem _ range_check_ptr point _ _,
{ apply sound_ec_double, apply auto_spec },
-- prove the auto generated assertion
dsimp [auto_spec_ec_double],
try { norm_num1 }, try { arith_simps },
left,
use_only [a0],
right,
use_only [a2],
have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,
have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },
have h_block5' := h_block5 rc_h_range_check_ptr',
try { rw [←hin_range_check_ptr] at h_block5' },
try { dsimp at h_block5, arith_simps at h_block5' },
have h_block5 := h_block5',
use_only[κ_block5],
use [h_block5],
try { linarith }
}
},
{
-- if: negative branch
have a0 : point.x.d0 ≠ 0, {
try { simp only [ne.def] },
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point] },
try { dsimp [cast_EcPoint, cast_BigInt3] },
try { arith_simps }, try { simp only [hcond] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a0 }, try { arith_simps at a0 },
clear hcond,
-- Use the block soundness theorem.
apply ensuresb_ret_trans (auto_sound_ec_double_block5 mem σ _ range_check_ptr point h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_12 hin_range_check_ptr hin_point νbound),
intros κ_block5 τ, try { arith_simps },
intro h_block5,
rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩,
-- range check condition
use_only (rc_m_block5+0+0), split,
linarith [rc_m_le_block5],
split,
{ arith_simps, try { simp only [hblk_range_check_ptr₁] },
try { arith_simps, refl <|> norm_cast }, try { refl } },
intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },
have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,
-- Final Proof
-- user-provided reduction
suffices auto_spec: auto_spec_ec_double mem _ range_check_ptr point _ _,
{ apply sound_ec_double, apply auto_spec },
-- prove the auto generated assertion
dsimp [auto_spec_ec_double],
try { norm_num1 }, try { arith_simps },
right,
use_only [a0],
have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,
have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },
have h_block5' := h_block5 rc_h_range_check_ptr',
try { rw [←hin_range_check_ptr] at h_block5' },
try { dsimp at h_block5, arith_simps at h_block5' },
have h_block5 := h_block5',
use_only[κ_block5],
use [h_block5],
try { linarith }
}
end
|
60d8bdc08a6095d35ab250c9d00a7e4081120320 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/lazyListRotateUnfoldProof.lean | 517181cb66c77e8b7b99e906a2b9370160fa909e | [
"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,922 | lean | inductive LazyList (α : Type u)
| nil : LazyList α
| cons (hd : α) (tl : LazyList α) : LazyList α
| delayed (t : Thunk (LazyList α)) : LazyList α
namespace LazyList
def length : LazyList α → Nat
| nil => 0
| cons _ as => length as + 1
| delayed as => length as.get
def force : LazyList α → Option (α × LazyList α)
| delayed as => force as.get
| nil => none
| cons a as => some (a,as)
end LazyList
def rotate (f : LazyList τ) (r : List τ) (a : LazyList τ)
(h : f.length + 1 = r.length) : LazyList τ :=
match r with
| List.nil => False.elim (by simp_arith [LazyList.length] at h)
| y::r' =>
match f.force with
| none => LazyList.cons y a
| some (x, f') => LazyList.cons x (rotate f' r' (LazyList.cons y a) (sorry))
theorem rotate_inv {F : LazyList τ} {R : List τ} : (h : F.length + 1 = R.length) → (rotate F R nil h).length = F.length + R.length := by
match F with
| LazyList.nil => intro h; unfold rotate; sorry
| LazyList.cons Fh Ft => sorry
| LazyList.delayed Ft => sorry
theorem LazyList.ind {α : Type u} {motive : LazyList α → Sort v}
(nil : motive LazyList.nil)
(cons : (hd : α) → (tl : LazyList α) → motive tl → motive (LazyList.cons hd tl))
(delayed : (t : Thunk (LazyList α)) → motive t.get → motive (LazyList.delayed t))
(t : LazyList α) : motive t :=
match t with
| LazyList.nil => nil
| LazyList.cons h t => cons h t (ind nil cons delayed t)
| LazyList.delayed t => delayed t (ind nil cons delayed t.get)
-- Remark: Lean used well-founded recursion behind the scenes to define LazyList.ind
theorem rotate_inv' {F : LazyList τ} {R : List τ} : (h : F.length + 1 = R.length) → (rotate F R nil h).length = F.length + R.length := by
induction F using LazyList.ind with
| nil => intro h; unfold rotate; sorry
| cons h t ih => trace_state; sorry
| delayed t => trace_state; sorry
|
6f36ee8b6a6479d696eaa10bf637b2fcf48596a3 | 968e2f50b755d3048175f176376eff7139e9df70 | /examples/pred_logic/unnamed_371.lean | 9b06492b23b9bc3f9d13d9f11f18d64852d18c41 | [] | no_license | gihanmarasingha/mth1001_sphinx | 190a003269ba5e54717b448302a27ca26e31d491 | 05126586cbf5786e521be1ea2ef5b4ba3c44e74a | refs/heads/master | 1,672,913,933,677 | 1,604,516,583,000 | 1,604,516,583,000 | 309,245,750 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 326 | lean | variables (U : Type*) (S T : U → Prop) (u : U)
-- BEGIN
example (h : ∀ x, (S x) ∧ (T x)) : S u :=
begin
have h₂ : (S u) ∧ (T u), from h u, -- We have `h₂ : (S u) ∧ (T u)` by for all elimination on `h` and `u`.
show (S u), from h₂.left, -- We show `S u` by left conjunction elimination on `h₂`.
end
-- END |
4dbdb251f95e3357b3b8942289072d4e7b3e76bd | 968e2f50b755d3048175f176376eff7139e9df70 | /examples/prop_logic_theory/unnamed_1901.lean | 2bf452d5fe2d643e63c028c85408e46776540c5f | [] | no_license | gihanmarasingha/mth1001_sphinx | 190a003269ba5e54717b448302a27ca26e31d491 | 05126586cbf5786e521be1ea2ef5b4ba3c44e74a | refs/heads/master | 1,672,913,933,677 | 1,604,516,583,000 | 1,604,516,583,000 | 309,245,750 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 290 | lean | variables p q s t : Prop
theorem or_of_or (h : s ∨ t) : t ∨ s :=
begin
cases h with h₁ h₂,
{ exact or.inr h₁,},
{ show t ∨ s, from or.inl h₂, },
end
namespace hidden
-- BEGIN
theorem or_comm : p ∨ q ↔ q ∨ p :=
begin
split;
apply or_of_or
end
-- END
end hidden |
17a7628b6e5717121c46b729deb0d58b1b445055 | 93b17e1ec33b7fd9fb0d8f958cdc9f2214b131a2 | /src/sep/prod.lean | 9fc3683241c8264ecca98fd350aa560ec1d44286 | [] | no_license | intoverflow/timesink | 93f8535cd504bc128ba1b57ce1eda4efc74e5136 | c25be4a2edb866ad0a9a87ee79e209afad6ab303 | refs/heads/master | 1,620,033,920,087 | 1,524,995,105,000 | 1,524,995,105,000 | 120,576,102 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 833 | lean | import .basic
namespace Sep
universes ℓ₁ ℓ₂
def Alg.Prod (A : Alg.{ℓ₁}) (B : Alg.{ℓ₂})
: Alg.{max ℓ₁ ℓ₂}
:= { τ := A.τ × B.τ
, join := λ x₁ x₂ x₃
, (A.join x₁.1 x₂.1 x₃.1) ∧ (B.join x₁.2 x₂.2 x₃.2)
, comm := λ x₁ x₂ x₃ J
, and.intro (A.comm J.1) (B.comm J.2)
, assoc := λ x₁ x₂ x₃ x₁₂ x₁₂₃ J₁₂ J₁₂₃ P C
, begin
apply A.assoc J₁₂.1 J₁₂₃.1, intro a,
apply B.assoc J₁₂.2 J₁₂₃.2, intro b,
exact C { x := (a.x, b.x)
, J₁ := and.intro a.J₁ b.J₁
, J₂ := and.intro a.J₂ b.J₂
}
end
}
end Sep
|
92049f6dc8f28d6adf37d7e5be006e7d3b7616c1 | 618003631150032a5676f229d13a079ac875ff77 | /src/analysis/normed_space/finite_dimension.lean | 5b2c91d975eb16b8830a3ef2d17624b1b0e944b5 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 12,366 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.normed_space.operator_norm
import linear_algebra.finite_dimensional
import tactic.omega
/-!
# Finite dimensional normed spaces over complete fields
Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps
are continuous. Moreover, a finite-dimensional subspace is always complete and closed.
## Main results:
* `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a
complete field is continuous.
* `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This
is not registered as an instance, as the field would be an unknown metavariable in typeclass
resolution.
* `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is
closed
* `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This
is not registered as an instance, as the field would be an unknown metavariable in typeclass
resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness
implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or
`ℂ`.
## Implementation notes
The fact that all norms are equivalent is not written explicitly, as it would mean having two norms
on a single space, which is not the way type classes work. However, if one has a
finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm,
then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to
`linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence.
-/
universes u v w x
open set finite_dimensional
open_locale classical
/-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/
lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜]
{E : Type v} [add_comm_group E] [vector_space 𝕜 E] [topological_space E]
[topological_add_group E] [topological_vector_space 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f :=
begin
-- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous
-- function.
have : (f : (ι → 𝕜) → E) =
(λx, finset.sum finset.univ (λi:ι, x i • (f (λj, if i = j then 1 else 0)))),
by { ext x, exact f.pi_apply_eq_sum_univ x },
rw this,
refine continuous_finset_sum _ (λi hi, _),
exact (continuous_apply i).smul continuous_const
end
section complete_field
variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E]
{F : Type w} [normed_group F] [normed_space 𝕜 F]
{F' : Type x} [add_comm_group F'] [vector_space 𝕜 F'] [topological_space F']
[topological_add_group F'] [topological_vector_space 𝕜 F']
[complete_space 𝕜]
/-- In finite dimension over a complete field, the canonical identification (in terms of a basis)
with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that
all norms are equivalent in finite dimension.
This statement is superceded by the fact that every linear map on a finite-dimensional space is
continuous, in `linear_map.continuous_of_finite_dimensional`. -/
lemma continuous_equiv_fun_basis {ι : Type v} [fintype ι] (ξ : ι → E) (hξ : is_basis 𝕜 ξ) :
continuous (equiv_fun_basis hξ) :=
begin
unfreezeI,
induction hn : fintype.card ι with n IH generalizing ι E,
{ apply linear_map.continuous_of_bound _ 0 (λx, _),
have : equiv_fun_basis hξ x = 0,
by { ext i, exact (fintype.card_eq_zero_iff.1 hn i).elim },
change ∥equiv_fun_basis hξ x∥ ≤ 0 * ∥x∥,
rw this,
simp [norm_nonneg] },
{ haveI : finite_dimensional 𝕜 E := of_finite_basis hξ,
-- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent
-- to a standard space of dimension n, hence it is complete and therefore closed.
have H₁ : ∀s : submodule 𝕜 E, findim 𝕜 s = n → is_closed (s : set E),
{ assume s s_dim,
rcases exists_is_basis_finite 𝕜 s with ⟨b, b_basis, b_finite⟩,
letI : fintype b := finite.fintype b_finite,
have U : uniform_embedding (equiv_fun_basis b_basis).symm.to_equiv,
{ have : fintype.card b = n,
by { rw ← s_dim, exact (findim_eq_card_basis b_basis).symm },
have : continuous (equiv_fun_basis b_basis) := IH (subtype.val : b → s) b_basis this,
exact (equiv_fun_basis b_basis).symm.uniform_embedding (linear_map.continuous_on_pi _) this },
have : is_complete (s : set E),
from complete_space_coe_iff_is_complete.1 ((complete_space_congr U).1 (by apply_instance)),
exact is_closed_of_is_complete this },
-- second step: any linear form is continuous, as its kernel is closed by the first step
have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f,
{ assume f,
have : findim 𝕜 f.ker = n ∨ findim 𝕜 f.ker = n.succ,
{ have Z := f.findim_range_add_findim_ker,
rw [findim_eq_card_basis hξ, hn] at Z,
have : findim 𝕜 f.range = 0 ∨ findim 𝕜 f.range = 1,
{ have I : ∀(k : ℕ), k ≤ 1 ↔ k = 0 ∨ k = 1, by omega manual,
have : findim 𝕜 f.range ≤ findim 𝕜 𝕜 := submodule.findim_le _,
rwa [findim_of_field, I] at this },
cases this,
{ rw this at Z,
right,
simpa using Z },
{ left,
rw [this, add_comm, nat.add_one] at Z,
exact nat.succ_inj Z } },
have : is_closed (f.ker : set E),
{ cases this,
{ exact H₁ _ this },
{ have : f.ker = ⊤,
by { apply eq_top_of_findim_eq, rw [findim_eq_card_basis hξ, hn, this] },
simp [this] } },
exact linear_map.continuous_iff_is_closed_ker.2 this },
-- third step: applying the continuity to the linear form corresponding to a coefficient in the
-- basis decomposition, deduce that all such coefficients are controlled in terms of the norm
have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥equiv_fun_basis hξ x i∥ ≤ C * ∥x∥,
{ assume i,
let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i).comp (equiv_fun_basis hξ),
let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f },
exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ },
-- fourth step: combine the bound on each coefficient to get a global bound and the continuity
choose C0 hC0 using this,
let C := finset.sum finset.univ C0,
have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1),
have C0_le : ∀i, C0 i ≤ C :=
λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _),
apply linear_map.continuous_of_bound _ C (λx, _),
rw pi_norm_le_iff,
{ exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) },
{ exact mul_nonneg C_nonneg (norm_nonneg _) } }
end
/-- Any linear map on a finite dimensional space over a complete field is continuous. -/
theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') :
continuous f :=
begin
-- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and
-- argue that all linear maps there are continuous.
rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩,
letI : fintype b := finite.fintype b_finite,
have A : continuous (equiv_fun_basis b_basis) :=
continuous_equiv_fun_basis _ b_basis,
have B : continuous (f.comp ((equiv_fun_basis b_basis).symm : (b → 𝕜) →ₗ[𝕜] E)) :=
linear_map.continuous_on_pi _,
have : continuous ((f.comp ((equiv_fun_basis b_basis).symm : (b → 𝕜) →ₗ[𝕜] E))
∘ (equiv_fun_basis b_basis)) := B.comp A,
convert this,
ext x,
dsimp,
rw linear_equiv.symm_apply_apply
end
/-- The continuous linear map induced by a linear map on a finite dimensional space -/
def linear_map.to_continuous_linear_map [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') : E →L[𝕜] F' :=
{ cont := f.continuous_of_finite_dimensional, ..f }
/-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional space. -/
def linear_equiv.to_continuous_linear_equiv [finite_dimensional 𝕜 E] (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F :=
{ continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional,
continuous_inv_fun := begin
haveI : finite_dimensional 𝕜 F := e.finite_dimensional,
exact e.symm.to_linear_map.continuous_of_finite_dimensional
end,
..e }
/-- Any finite-dimensional vector space over a complete field is complete.
We do not register this as an instance to avoid an instance loop when trying to prove the
completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance
explicitly when needed. -/
variables (𝕜 E)
lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E :=
begin
rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩,
letI : fintype b := finite.fintype b_finite,
have : uniform_embedding (equiv_fun_basis b_basis).symm :=
linear_equiv.uniform_embedding _ (linear_map.continuous_of_finite_dimensional _)
(linear_map.continuous_of_finite_dimensional _),
change uniform_embedding (equiv_fun_basis b_basis).symm.to_equiv at this,
exact (complete_space_congr this).1 (by apply_instance)
end
variables {𝕜 E}
/-- A finite-dimensional subspace is complete. -/
lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] :
is_complete (s : set E) :=
complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s)
/-- A finite-dimensional subspace is closed. -/
lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] :
is_closed (s : set E) :=
is_closed_of_is_complete s.complete_of_finite_dimensional
lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F]
(f : E →L[𝕜] F) (hf : f.range = ⊤) :
∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F :=
let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in
⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩
end complete_field
section proper_field
variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜]
(E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜]
/-- Any finite-dimensional vector space over a proper field is proper.
We do not register this as an instance to avoid an instance loop when trying to prove the
properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance
explicitly when needed. -/
lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E :=
begin
rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩,
letI : fintype b := finite.fintype b_finite,
let e := equiv_fun_basis b_basis,
let f : E →L[𝕜] (b → 𝕜) :=
{ cont := linear_map.continuous_of_finite_dimensional _, ..e.to_linear_map },
refine metric.proper_image_of_proper e.symm
(linear_map.continuous_of_finite_dimensional _) _ (∥f∥) (λx y, _),
{ exact equiv.range_eq_univ e.symm.to_equiv },
{ have A : e (e.symm x) = x := linear_equiv.apply_symm_apply _ _,
have B : e (e.symm y) = y := linear_equiv.apply_symm_apply _ _,
conv_lhs { rw [← A, ← B] },
change dist (f (e.symm x)) (f (e.symm y)) ≤ ∥f∥ * dist (e.symm x) (e.symm y),
exact f.lipschitz.dist_le_mul _ _ }
end
end proper_field
/- Over the real numbers, we can register the previous statement as an instance as it will not
cause problems in instance resolution since the properness of `ℝ` is already known. -/
instance finite_dimensional.proper_real
(E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E :=
finite_dimensional.proper ℝ E
attribute [instance, priority 900] finite_dimensional.proper_real
|
c3201bb0833f9632f0c8b9196ea641bd1d83e724 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/empty_eq.lean | 68da9fbb3f33f5302b0d77feed3eb652454ebcc8 | [
"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 | open nat
inductive Fin : nat → Type
| fz : Π n, Fin (succ n)
| fs : Π {n}, Fin n → Fin (succ n)
open Fin
definition case0 {C : Fin 0 → Type} : Π (f : Fin 0), C f
.
#print definition case0
|
ad293244e760baeae137980479ed662938385427 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/smt_not_exists.lean | dadc141daefc78f2b9c61f78f2cda008449014eb | [
"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 | 381 | lean | universe variables u
def ex (p q : nat → nat → Prop) (h : ∃ x, p x x ∧ q x x) : ∃ x y, p x y :=
begin [smt]
by_contra,
destruct h,
smt_tactic.add_lemmas_from_facts,
ematch
end
#print ex
lemma ex2 (p q : nat → nat → Prop) (h : ∃ x, p x x ∧ q x x) : ∃ x, p x x :=
begin [smt]
by_contra,
destruct h,
smt_tactic.add_lemmas_from_facts,
ematch
end
|
a3b6796fd8321cb0d404ac73b7c8404cefcfae52 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/finset/nat_antidiagonal_auto.lean | e29f7d9b064ce478f1e88bb808a50f6bf4db3e30 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,667 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.finset.basic
import Mathlib.data.multiset.nat_antidiagonal
import Mathlib.PostPort
namespace Mathlib
/-!
# The "antidiagonal" {(0,n), (1,n-1), ..., (n,0)} as a finset.
-/
namespace finset
namespace nat
/-- The antidiagonal of a natural number `n` is
the finset of pairs `(i,j)` such that `i+j = n`. -/
def antidiagonal (n : ℕ) : finset (ℕ × ℕ) :=
mk (multiset.nat.antidiagonal n) (multiset.nat.nodup_antidiagonal n)
/-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/
@[simp] theorem mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ prod.fst x + prod.snd x = n :=
sorry
/-- The cardinality of the antidiagonal of `n` is `n+1`. -/
@[simp] theorem card_antidiagonal (n : ℕ) : card (antidiagonal n) = n + 1 := sorry
/-- The antidiagonal of `0` is the list `[(0,0)]` -/
@[simp] theorem antidiagonal_zero : antidiagonal 0 = singleton (0, 0) := rfl
theorem antidiagonal_succ {n : ℕ} :
antidiagonal (n + 1) =
insert (0, n + 1)
(map
(function.embedding.prod_map (function.embedding.mk Nat.succ nat.succ_injective)
(function.embedding.refl ℕ))
(antidiagonal n)) :=
sorry
theorem map_swap_antidiagonal {n : ℕ} :
map (function.embedding.mk prod.swap (function.right_inverse.injective prod.swap_right_inverse))
(antidiagonal n) =
antidiagonal n :=
sorry
end Mathlib |
04500b3325ff67654571c5ae56afdfcdbe0715e6 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/combinatorics/partition.lean | 715a41e69f58d18c699a2d33f8e79923bde87a23 | [
"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,323 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import combinatorics.composition
import data.nat.parity
import tactic.apply_fun
/-!
# Partitions
A partition of a natural number `n` is a way of writing `n` as a sum of positive integers, where the
order does not matter: two sums that differ only in the order of their summands are considered the
same partition. This notion is closely related to that of a composition of `n`, but in a composition
of `n` the order does matter.
A summand of the partition is called a part.
## Main functions
* `p : partition n` is a structure, made of a multiset of integers which are all positive and
add up to `n`.
## Implementation details
The main motivation for this structure and its API is to show Euler's partition theorem, and
related results.
The representation of a partition as a multiset is very handy as multisets are very flexible and
already have a well-developed API.
## Tags
Partition
## References
<https://en.wikipedia.org/wiki/Partition_(number_theory)>
-/
variables {α : Type*}
open multiset nat
open_locale big_operators
/-- A partition of `n` is a multiset of positive integers summing to `n`. -/
@[ext, derive decidable_eq] structure partition (n : ℕ) :=
(parts : multiset ℕ)
(parts_pos : ∀ {i}, i ∈ parts → 0 < i)
(parts_sum : parts.sum = n)
namespace partition
/-- A composition induces a partition (just convert the list to a multiset). -/
def of_composition (n : ℕ) (c : composition n) : partition n :=
{ parts := c.blocks,
parts_pos := λ i hi, c.blocks_pos hi,
parts_sum := by rw [multiset.coe_sum, c.blocks_sum] }
lemma of_composition_surj {n : ℕ} : function.surjective (of_composition n) :=
begin
rintro ⟨b, hb₁, hb₂⟩,
rcases quotient.exists_rep b with ⟨b, rfl⟩,
refine ⟨⟨b, λ i hi, hb₁ hi, _⟩, partition.ext _ _ rfl⟩,
simpa using hb₂
end
/--
Given a multiset which sums to `n`, construct a partition of `n` with the same multiset, but
without the zeros.
-/
-- The argument `n` is kept explicit here since it is useful in tactic mode proofs to generate the
-- proof obligation `l.sum = n`.
def of_sums (n : ℕ) (l : multiset ℕ) (hl : l.sum = n) : partition n :=
{ parts := l.filter (≠ 0),
parts_pos := λ i hi, nat.pos_of_ne_zero $ by apply of_mem_filter hi,
parts_sum :=
begin
have lt : l.filter (= 0) + l.filter (≠ 0) = l := filter_add_not _ l,
apply_fun multiset.sum at lt,
have lz : (l.filter (= 0)).sum = 0,
{ rw multiset.sum_eq_zero_iff,
simp },
simpa [lz, hl] using lt,
end }
/-- A `multiset ℕ` induces a partition on its sum. -/
def of_multiset (l : multiset ℕ) : partition l.sum :=
of_sums _ l rfl
/-- The partition of exactly one part. -/
def indiscrete_partition (n : ℕ) : partition n :=
of_sums n {n} rfl
instance {n : ℕ} : inhabited (partition n) := ⟨indiscrete_partition n⟩
/--
The number of times a positive integer `i` appears in the partition `of_sums n l hl` is the same
as the number of times it appears in the multiset `l`.
(For `i = 0`, `partition.non_zero` combined with `multiset.count_eq_zero_of_not_mem` gives that
this is `0` instead.)
-/
lemma count_of_sums_of_ne_zero {n : ℕ} {l : multiset ℕ} (hl : l.sum = n) {i : ℕ} (hi : i ≠ 0) :
(of_sums n l hl).parts.count i = l.count i :=
count_filter_of_pos hi
lemma count_of_sums_zero {n : ℕ} {l : multiset ℕ} (hl : l.sum = n) :
(of_sums n l hl).parts.count 0 = 0 :=
count_filter_of_neg (λ h, h rfl)
/--
Show there are finitely many partitions by considering the surjection from compositions to
partitions.
-/
instance (n : ℕ) : fintype (partition n) :=
fintype.of_surjective (of_composition n) of_composition_surj
/-- The finset of those partitions in which every part is odd. -/
def odds (n : ℕ) : finset (partition n) :=
finset.univ.filter (λ c, ∀ i ∈ c.parts, ¬ even i)
/-- The finset of those partitions in which each part is used at most once. -/
def distincts (n : ℕ) : finset (partition n) :=
finset.univ.filter (λ c, c.parts.nodup)
/-- The finset of those partitions in which every part is odd and used at most once. -/
def odd_distincts (n : ℕ) : finset (partition n) := odds n ∩ distincts n
end partition
|
cf58717cfd30b0e663620d9bee0a862e98c5d433 | 8e2026ac8a0660b5a490dfb895599fb445bb77a0 | /tests/lean/interactive/field_info.lean | 831005b55db5d81e6d5673ab329fd58deccc3c4b | [
"Apache-2.0"
] | permissive | pcmoritz/lean | 6a8575115a724af933678d829b4f791a0cb55beb | 35eba0107e4cc8a52778259bb5392300267bfc29 | refs/heads/master | 1,607,896,326,092 | 1,490,752,175,000 | 1,490,752,175,000 | 86,612,290 | 0 | 0 | null | 1,490,809,641,000 | 1,490,809,641,000 | null | UTF-8 | Lean | false | false | 393 | lean | def f (n : ℕ) := n^.to_string
--^ "command": "info"
def g (l : list ℕ) := l^.all
--^ "command": "info"
-- elaborated, not locally inferable
def h : list ℕ → (ℕ → bool) → bool :=
λ l, (l ++ l)^.all
--^ "command": "info"
-- not elaborated, locally inferable
def j := (list.nil^.all
--^ "command": "info"
|
f29a542edced205eed553d3b7e3a52e92bbd2b6b | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/myfield/basic.lean | bd7f47bc956d87857f5669fb8335cfa33f25fa25 | [] | no_license | Sterrs/leaning | 8fd80d1f0a6117a220bb2e57ece639b9a63deadc | 3901cc953694b33adda86cb88ca30ba99594db31 | refs/heads/master | 1,627,023,822,744 | 1,616,515,221,000 | 1,616,515,221,000 | 245,512,190 | 2 | 0 | null | 1,616,429,050,000 | 1,583,527,118,000 | Lean | UTF-8 | Lean | false | false | 3,635 | lean | import ..myring.order
import ..myring.integral_domain
namespace hidden
class myfield (α : Type) extends myring α, has_inv α :=
(mul_inv {x : α}: x ≠ 0 → x * x⁻¹ = 1)
(nontrivial: (0: α) ≠ 1)
namespace myfield
open myring
variables {α : Type} [myfield α] (x y z : α)
theorem one_ne_zero : (1 : α) ≠ 0 :=
begin
assume h,
apply @nontrivial α,
symmetry,
assumption,
end
theorem zero_ne_one : (0 : α) ≠ 1 := nontrivial
theorem inv_mul {x : α} (hx : x ≠ 0) : x⁻¹ * x = 1 :=
begin
rw [mul_comm],
apply mul_inv hx,
end
theorem nzero_impl_inv_nzero (hx : x ≠ 0) : x⁻¹ ≠ 0 :=
begin
assume hinv0,
apply hx,
apply one_eq_zero_impl_all_zero,
rw [←mul_inv hx, hinv0, myring.mul_zero],
end
instance: integral_domain α := ⟨begin
intros a b ha hba,
rw [←myring.mul_one b, ←mul_inv ha, ←myring.mul_assoc, hba, myring.zero_mul],
end⟩
open integral_domain
theorem inv_unique {x : α} (y : α) (hx : x ≠ 0) : x * y = 1 → y = x⁻¹ :=
begin
intro hxy,
apply mul_cancel_left x,
exact hx,
rw hxy,
symmetry,
exact mul_inv hx,
end
@[simp] theorem one_inv : 1⁻¹ = (1 : α) := begin
symmetry,
apply inv_unique,
exact one_ne_zero,
rw one_mul,
end
theorem inv_nzero {x : α} (hx : x ≠ 0) : x⁻¹ ≠ 0 :=
begin
intro hx0,
apply @nontrivial α,
rw [←mul_inv hx, ←mul_zero x, hx0],
end
theorem inv_inv {x : α} (hx : x ≠ 0) : x⁻¹⁻¹ = x :=
begin
apply mul_cancel_right _ x⁻¹,
exact inv_nzero hx,
rw mul_comm,
transitivity (1 : α),
apply mul_inv,
exact inv_nzero hx,
symmetry,
apply mul_inv hx,
end
theorem inv_inj {x y : α} (hx : x ≠ 0) (hy : y ≠ 0): x⁻¹ = y⁻¹ → x = y :=
begin
intro hxy,
rw [←inv_inv hx, ←inv_inv hy],
congr,
assumption,
end
theorem inv_distr {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : (x * y)⁻¹ = x⁻¹ * y⁻¹ :=
begin
have hxy : x * y ≠ 0 := mul_nzero hx hy,
apply mul_cancel_right _ (x * y),
exact hxy,
rw [mul_comm, mul_inv hxy, mul_comm x, mul_assoc, ←mul_assoc y⁻¹, mul_comm y⁻¹,
mul_inv hy, one_mul, inv_mul hx],
end
def div : α → α → α := λ a b, a * b⁻¹
instance: has_div α := ⟨div⟩
-- -- Division
theorem div_def : x / y = x * y⁻¹ := rfl
@[simp] theorem div_one : x / 1 = x :=
begin
change x * 1⁻¹ = x,
rw [one_inv, mul_one],
end
theorem one_div : 1 / x = x⁻¹ :=
begin
change 1 * x⁻¹ = x⁻¹,
rw one_mul,
end
@[simp] theorem zero_div : 0 / x = 0 :=
begin
change 0 * x⁻¹ = 0,
rw zero_mul,
end
theorem mul_div_cancel : y ≠ 0 → (x * y) / y = x :=
begin
intro hy,
change x * y * y⁻¹ = x,
rw [mul_assoc, mul_inv hy, mul_one],
end
theorem div_mul_cancel : y ≠ 0 → (x / y) * y = x :=
begin
intro hy,
change x * y⁻¹ * y = x,
rw [mul_assoc, inv_mul hy, mul_one],
end
theorem div_self {x : α} : x ≠ 0 → x / x = 1 :=
begin
intro hx,
change x * x⁻¹ = 1,
exact mul_inv hx,
end
theorem div_inv_switch {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : x / y = (y / x)⁻¹ :=
begin
change x * y⁻¹ = (y * x⁻¹)⁻¹,
rw [inv_distr hy (inv_nzero hx), inv_inv hx, mul_comm],
end
theorem add_div : (x + y) / z = x / z + y / z :=
begin
change (x + y) * z⁻¹ = x * z⁻¹ + y * z⁻¹,
apply add_mul,
end
-- Handy
theorem half_plus_half (water : 2 ≠ (0 : α)) (ε : α) : ε / 2 + ε / 2 = ε :=
begin
rw [div_def, ←mul_add, ←one_div, ←add_div],
change ε * (2 / 2) = ε,
rw [div_self water, mul_one],
end
theorem minus_half (water : 2 ≠ (0 : α)) (ε : α) : ε - ε /2 = ε / 2 := sorry
end myfield
end hidden
|
70a57f176a43fd0eced51e64a91d006d7b4ad3f0 | 1a61aba1b67cddccce19532a9596efe44be4285f | /hott/types/univ.hlean | f4771b9bc4ce52910d7599f0e21c4ec6466e9cbc | [
"Apache-2.0"
] | permissive | eigengrau/lean | 07986a0f2548688c13ba36231f6cdbee82abf4c6 | f8a773be1112015e2d232661ce616d23f12874d0 | refs/heads/master | 1,610,939,198,566 | 1,441,352,386,000 | 1,441,352,494,000 | 41,903,576 | 0 | 0 | null | 1,441,352,210,000 | 1,441,352,210,000 | null | UTF-8 | Lean | false | false | 2,420 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about the universe
-/
-- see also init.ua
import .bool .trunc .lift
open is_trunc bool lift unit eq pi equiv equiv.ops sum
namespace univ
universe variable u
variables {A B : Type.{u}} {a : A} {b : B}
/- Pathovers -/
definition eq_of_pathover_ua {f : A ≃ B} (p : a =[ua f] b) : f a = b :=
!cast_ua⁻¹ ⬝ tr_eq_of_pathover p
definition pathover_ua {f : A ≃ B} (p : f a = b) : a =[ua f] b :=
pathover_of_tr_eq (!cast_ua ⬝ p)
definition pathover_ua_equiv (f : A ≃ B) : (a =[ua f] b) ≃ (f a = b) :=
equiv.MK eq_of_pathover_ua
pathover_ua
abstract begin
intro p, unfold [pathover_ua,eq_of_pathover_ua],
rewrite [to_right_inv !pathover_equiv_tr_eq, inv_con_cancel_left]
end end
abstract begin
intro p, unfold [pathover_ua,eq_of_pathover_ua],
rewrite [con_inv_cancel_left, to_left_inv !pathover_equiv_tr_eq]
end end
/- Properties which can be disproven for the universe -/
definition not_is_hset_type0 : ¬is_hset Type₀ :=
assume H : is_hset Type₀,
absurd !is_hset.elim eq_bnot_ne_idp
definition not_is_hset_type.{v} : ¬is_hset Type.{v} :=
assume H : is_hset Type,
absurd (is_trunc_is_embedding_closed lift star) not_is_hset_type0
--set_option pp.notation false
definition not_double_negation_elimination0 : ¬Π(A : Type₀), ¬¬A → A :=
begin
intro f,
have u : ¬¬bool, by exact (λg, g tt),
let H1 := apdo f eq_bnot,
let H2 := apo10 H1 u,
have p : eq_bnot ▸ u = u, from !is_hprop.elim,
rewrite p at H2,
let H3 := eq_of_pathover_ua H2, esimp at H3, --TODO: use apply ... at after #700
exact absurd H3 (bnot_ne (f bool u)),
end
definition not_double_negation_elimination : ¬Π(A : Type), ¬¬A → A :=
begin
intro f,
apply not_double_negation_elimination0,
intro A nna, refine down (f _ _),
intro na,
have ¬A, begin intro a, exact absurd (up a) na end,
exact absurd this nna
end
definition not_excluded_middle : ¬Π(A : Type), A + ¬A :=
begin
intro f,
apply not_double_negation_elimination,
intro A nna,
induction (f A) with a na,
exact a,
exact absurd na nna
end
end univ
|
cb95d678b5183ecec33ed60b300eb1097ef425e6 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/sites/sieves.lean | bdf51586cefae045000352b8747b8df941549c7e | [] | 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 | 15,566 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, E. W. Ayers
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.over
import Mathlib.category_theory.limits.shapes.finite_limits
import Mathlib.category_theory.yoneda
import Mathlib.order.complete_lattice
import Mathlib.data.set.lattice
import Mathlib.PostPort
universes v u l
namespace Mathlib
/-!
# Theory of sieves
- For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X`
which is closed under left-composition.
- The complete lattice structure on sieves is given, as well as the Galois insertion
given by downward-closing.
- A `sieve X` (functorially) induces a presheaf on `C` together with a monomorphism to
the yoneda embedding of `X`.
## Tags
sieve, pullback
-/
namespace category_theory
/-- A set of arrows all with codomain `X`. -/
def presieve {C : Type u} [category C] (X : C) :=
{Y : C} → set (Y ⟶ X)
namespace presieve
protected instance inhabited {C : Type u} [category C] {X : C} : Inhabited (presieve X) :=
{ default := ⊤ }
/--
Given a set of arrows `S` all with codomain `X`, and a set of arrows with codomain `Y` for each
`f : Y ⟶ X` in `S`, produce a set of arrows with codomain `X`:
`{ g ≫ f | (f : Y ⟶ X) ∈ S, (g : Z ⟶ Y) ∈ R f }`.
-/
def bind {C : Type u} [category C] {X : C} (S : presieve X) (R : {Y : C} → {f : Y ⟶ X} → S f → presieve Y) : presieve X :=
fun (Z : C) (h : Z ⟶ X) => ∃ (Y : C), ∃ (g : Z ⟶ Y), ∃ (f : Y ⟶ X), ∃ (H : S f), R H g ∧ g ≫ f = h
@[simp] theorem bind_comp {C : Type u} [category C] {X : C} {Y : C} {Z : C} (f : Y ⟶ X) {S : presieve X} {R : {Y : C} → {f : Y ⟶ X} → S f → presieve Y} {g : Z ⟶ Y} (h₁ : S f) (h₂ : R h₁ g) : bind S R (g ≫ f) :=
Exists.intro Y (Exists.intro g (Exists.intro f (Exists.intro h₁ { left := h₂, right := rfl })))
/-- The singleton presieve. -/
-- Note we can't make this into `has_singleton` because of the out-param.
structure singleton {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) : presieve X
where
@[simp] theorem singleton_eq_iff_domain {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) (g : Y ⟶ X) : singleton f g ↔ f = g := sorry
theorem singleton_self {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) : singleton f f :=
singleton.mk
end presieve
/--
For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under
left-composition.
-/
structure sieve {C : Type u} [category C] (X : C)
where
arrows : presieve X
downward_closed' : ∀ {Y Z : C} {f : Y ⟶ X}, arrows f → ∀ (g : Z ⟶ Y), arrows (g ≫ f)
namespace sieve
protected instance has_coe_to_fun {C : Type u} [category C] {X : C} : has_coe_to_fun (sieve X) :=
has_coe_to_fun.mk (fun (x : sieve X) => presieve X) arrows
@[simp] theorem downward_closed {C : Type u} [category C] {X : C} {Y : C} {Z : C} (S : sieve X) {f : Y ⟶ X} (hf : coe_fn S Y f) (g : Z ⟶ Y) : coe_fn S Z (g ≫ f) :=
downward_closed' S hf g
theorem arrows_ext {C : Type u} [category C] {X : C} {R : sieve X} {S : sieve X} : arrows R = arrows S → R = S := sorry
protected theorem ext {C : Type u} [category C] {X : C} {R : sieve X} {S : sieve X} (h : ∀ {Y : C} (f : Y ⟶ X), coe_fn R Y f ↔ coe_fn S Y f) : R = S :=
arrows_ext (funext fun (x : C) => funext fun (f : x ⟶ X) => propext (h f))
protected theorem ext_iff {C : Type u} [category C] {X : C} {R : sieve X} {S : sieve X} : R = S ↔ ∀ {Y : C} (f : Y ⟶ X), coe_fn R Y f ↔ coe_fn S Y f :=
{ mp := fun (h : R = S) (Y : C) (f : Y ⟶ X) => h ▸ iff.rfl, mpr := sieve.ext }
/-- The supremum of a collection of sieves: the union of them all. -/
protected def Sup {C : Type u} [category C] {X : C} (𝒮 : set (sieve X)) : sieve X :=
mk (fun (Y : C) => set_of fun (f : Y ⟶ X) => ∃ (S : sieve X), ∃ (H : S ∈ 𝒮), arrows S f) sorry
/-- The infimum of a collection of sieves: the intersection of them all. -/
protected def Inf {C : Type u} [category C] {X : C} (𝒮 : set (sieve X)) : sieve X :=
mk (fun (Y : C) => set_of fun (f : Y ⟶ X) => ∀ (S : sieve X), S ∈ 𝒮 → arrows S f) sorry
/-- The union of two sieves is a sieve. -/
protected def union {C : Type u} [category C] {X : C} (S : sieve X) (R : sieve X) : sieve X :=
mk (fun (Y : C) (f : Y ⟶ X) => coe_fn S Y f ∨ coe_fn R Y f) sorry
/-- The intersection of two sieves is a sieve. -/
protected def inter {C : Type u} [category C] {X : C} (S : sieve X) (R : sieve X) : sieve X :=
mk (fun (Y : C) (f : Y ⟶ X) => coe_fn S Y f ∧ coe_fn R Y f) sorry
/--
Sieves on an object `X` form a complete lattice.
We generate this directly rather than using the galois insertion for nicer definitional properties.
-/
protected instance complete_lattice {C : Type u} [category C] {X : C} : complete_lattice (sieve X) :=
complete_lattice.mk sieve.union (fun (S R : sieve X) => ∀ {Y : C} (f : Y ⟶ X), coe_fn S Y f → coe_fn R Y f)
(bounded_lattice.lt._default fun (S R : sieve X) => ∀ {Y : C} (f : Y ⟶ X), coe_fn S Y f → coe_fn R Y f) sorry sorry
sorry sorry sorry sorry sieve.inter sorry sorry sorry (mk (fun (_x : C) => set.univ) sorry) sorry
(mk (fun (_x : C) => ∅) sorry) sorry sieve.Sup sieve.Inf sorry sorry sorry sorry
/-- The maximal sieve always exists. -/
protected instance sieve_inhabited {C : Type u} [category C] {X : C} : Inhabited (sieve X) :=
{ default := ⊤ }
@[simp] theorem Inf_apply {C : Type u} [category C] {X : C} {Ss : set (sieve X)} {Y : C} (f : Y ⟶ X) : coe_fn (Inf Ss) Y f ↔ ∀ (S : sieve X), S ∈ Ss → coe_fn S Y f :=
iff.rfl
@[simp] theorem Sup_apply {C : Type u} [category C] {X : C} {Ss : set (sieve X)} {Y : C} (f : Y ⟶ X) : coe_fn (Sup Ss) Y f ↔ ∃ (S : sieve X), ∃ (H : S ∈ Ss), coe_fn S Y f :=
iff.rfl
@[simp] theorem inter_apply {C : Type u} [category C] {X : C} {R : sieve X} {S : sieve X} {Y : C} (f : Y ⟶ X) : coe_fn (R ⊓ S) Y f ↔ coe_fn R Y f ∧ coe_fn S Y f :=
iff.rfl
@[simp] theorem union_apply {C : Type u} [category C] {X : C} {R : sieve X} {S : sieve X} {Y : C} (f : Y ⟶ X) : coe_fn (R ⊔ S) Y f ↔ coe_fn R Y f ∨ coe_fn S Y f :=
iff.rfl
@[simp] theorem top_apply {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) : coe_fn ⊤ Y f :=
trivial
/-- Generate the smallest sieve containing the given set of arrows. -/
@[simp] theorem generate_apply {C : Type u} [category C] {X : C} (R : presieve X) (Z : C) (f : Z ⟶ X) : coe_fn (generate R) Z f = ∃ (Y : C), ∃ (h : Z ⟶ Y), ∃ (g : Y ⟶ X), R g ∧ h ≫ g = f :=
Eq.refl (coe_fn (generate R) Z f)
/--
Given a presieve on `X`, and a sieve on each domain of an arrow in the presieve, we can bind to
produce a sieve on `X`.
-/
@[simp] theorem bind_apply {C : Type u} [category C] {X : C} (S : presieve X) (R : {Y : C} → {f : Y ⟶ X} → S f → sieve Y) : ⇑(bind S R) = presieve.bind S fun (Y : C) (f : Y ⟶ X) (h : S f) => ⇑(R h) :=
Eq.refl ⇑(bind S R)
theorem sets_iff_generate {C : Type u} [category C] {X : C} (R : presieve X) (S : sieve X) : generate R ≤ S ↔ R ≤ ⇑S := sorry
/-- Show that there is a galois insertion (generate, set_over). -/
def gi_generate {C : Type u} [category C] {X : C} : galois_insertion generate arrows :=
galois_insertion.mk (fun (𝒢 : presieve X) (_x : arrows (generate 𝒢) ≤ 𝒢) => generate 𝒢) sets_iff_generate sorry sorry
theorem le_generate {C : Type u} [category C] {X : C} (R : presieve X) : R ≤ ⇑(generate R) :=
galois_connection.le_u_l (galois_insertion.gc gi_generate) R
/-- If the identity arrow is in a sieve, the sieve is maximal. -/
theorem id_mem_iff_eq_top {C : Type u} [category C] {X : C} {S : sieve X} : coe_fn S X 𝟙 ↔ S = ⊤ := sorry
/-- If an arrow set contains a split epi, it generates the maximal sieve. -/
theorem generate_of_contains_split_epi {C : Type u} [category C] {X : C} {Y : C} {R : presieve X} (f : Y ⟶ X) [split_epi f] (hf : R f) : generate R = ⊤ := sorry
@[simp] theorem generate_of_singleton_split_epi {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) [split_epi f] : generate (presieve.singleton f) = ⊤ :=
generate_of_contains_split_epi f (presieve.singleton_self f)
@[simp] theorem generate_top {C : Type u} [category C] {X : C} : generate ⊤ = ⊤ :=
generate_of_contains_split_epi 𝟙 True.intro
/-- Given a morphism `h : Y ⟶ X`, send a sieve S on X to a sieve on Y
as the inverse image of S with `_ ≫ h`.
That is, `sieve.pullback S h := (≫ h) '⁻¹ S`. -/
def pullback {C : Type u} [category C] {X : C} {Y : C} (h : Y ⟶ X) (S : sieve X) : sieve Y :=
mk (fun (Y_1 : C) (sl : Y_1 ⟶ Y) => coe_fn S Y_1 (sl ≫ h)) sorry
@[simp] theorem pullback_id {C : Type u} [category C] {X : C} {S : sieve X} : pullback 𝟙 S = S := sorry
@[simp] theorem pullback_top {C : Type u} [category C] {X : C} {Y : C} {f : Y ⟶ X} : pullback f ⊤ = ⊤ :=
top_unique fun (_x : C) (g : _x ⟶ Y) => id
theorem pullback_comp {C : Type u} [category C] {X : C} {Y : C} {Z : C} {f : Y ⟶ X} {g : Z ⟶ Y} (S : sieve X) : pullback (g ≫ f) S = pullback g (pullback f S) := sorry
@[simp] theorem pullback_inter {C : Type u} [category C] {X : C} {Y : C} {f : Y ⟶ X} (S : sieve X) (R : sieve X) : pullback f (S ⊓ R) = pullback f S ⊓ pullback f R := sorry
theorem pullback_eq_top_iff_mem {C : Type u} [category C] {X : C} {Y : C} {S : sieve X} (f : Y ⟶ X) : coe_fn S Y f ↔ pullback f S = ⊤ := sorry
theorem pullback_eq_top_of_mem {C : Type u} [category C] {X : C} {Y : C} (S : sieve X) {f : Y ⟶ X} : coe_fn S Y f → pullback f S = ⊤ :=
iff.mp (pullback_eq_top_iff_mem f)
/--
Push a sieve `R` on `Y` forward along an arrow `f : Y ⟶ X`: `gf : Z ⟶ X` is in the sieve if `gf`
factors through some `g : Z ⟶ Y` which is in `R`.
-/
@[simp] theorem pushforward_apply {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) (R : sieve Y) (Z : C) (gf : Z ⟶ X) : coe_fn (pushforward f R) Z gf = ∃ (g : Z ⟶ Y), g ≫ f = gf ∧ coe_fn R Z g :=
Eq.refl (coe_fn (pushforward f R) Z gf)
theorem pushforward_apply_comp {C : Type u} [category C] {X : C} {Y : C} {R : sieve Y} {Z : C} {g : Z ⟶ Y} (hg : coe_fn R Z g) (f : Y ⟶ X) : coe_fn (pushforward f R) Z (g ≫ f) :=
Exists.intro g { left := rfl, right := hg }
theorem pushforward_comp {C : Type u} [category C] {X : C} {Y : C} {Z : C} {f : Y ⟶ X} {g : Z ⟶ Y} (R : sieve Z) : pushforward (g ≫ f) R = pushforward f (pushforward g R) := sorry
theorem galois_connection {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) : galois_connection (pushforward f) (pullback f) := sorry
theorem pullback_monotone {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) : monotone (pullback f) :=
galois_connection.monotone_u (galois_connection f)
theorem pushforward_monotone {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) : monotone (pushforward f) :=
galois_connection.monotone_l (galois_connection f)
theorem le_pushforward_pullback {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) (R : sieve Y) : R ≤ pullback f (pushforward f R) :=
galois_connection.le_u_l (galois_connection f) R
theorem pullback_pushforward_le {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) (R : sieve X) : pushforward f (pullback f R) ≤ R :=
galois_connection.l_u_le (galois_connection f) R
theorem pushforward_union {C : Type u} [category C] {X : C} {Y : C} {f : Y ⟶ X} (S : sieve Y) (R : sieve Y) : pushforward f (S ⊔ R) = pushforward f S ⊔ pushforward f R :=
galois_connection.l_sup (galois_connection f)
theorem pushforward_le_bind_of_mem {C : Type u} [category C] {X : C} {Y : C} (S : presieve X) (R : {Y : C} → {f : Y ⟶ X} → S f → sieve Y) (f : Y ⟶ X) (h : S f) : pushforward f (R h) ≤ bind S R := sorry
theorem le_pullback_bind {C : Type u} [category C] {X : C} {Y : C} (S : presieve X) (R : {Y : C} → {f : Y ⟶ X} → S f → sieve Y) (f : Y ⟶ X) (h : S f) : R h ≤ pullback f (bind S R) :=
eq.mpr
(id (Eq._oldrec (Eq.refl (R h ≤ pullback f (bind S R))) (Eq.symm (propext (galois_connection f (R h) (bind S R))))))
(pushforward_le_bind_of_mem (fun {Y : C} (f : Y ⟶ X) => S f) R f h)
/-- If `f` is a monomorphism, the pushforward-pullback adjunction on sieves is coreflective. -/
def galois_coinsertion_of_mono {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) [mono f] : galois_coinsertion (pushforward f) (pullback f) :=
galois_connection.to_galois_coinsertion (galois_connection f) sorry
/-- If `f` is a split epi, the pushforward-pullback adjunction on sieves is reflective. -/
def galois_insertion_of_split_epi {C : Type u} [category C] {X : C} {Y : C} (f : Y ⟶ X) [split_epi f] : galois_insertion (pushforward f) (pullback f) :=
galois_connection.to_galois_insertion (galois_connection f) sorry
/-- A sieve induces a presheaf. -/
@[simp] theorem functor_obj {C : Type u} [category C] {X : C} (S : sieve X) (Y : Cᵒᵖ) : functor.obj (functor S) Y = Subtype fun (g : opposite.unop Y ⟶ X) => coe_fn S (opposite.unop Y) g :=
Eq.refl (functor.obj (functor S) Y)
/--
If a sieve S is contained in a sieve T, then we have a morphism of presheaves on their induced
presheaves.
-/
def nat_trans_of_le {C : Type u} [category C] {X : C} {S : sieve X} {T : sieve X} (h : S ≤ T) : functor S ⟶ functor T :=
nat_trans.mk fun (Y : Cᵒᵖ) (f : functor.obj (functor S) Y) => { val := subtype.val f, property := sorry }
/-- The natural inclusion from the functor induced by a sieve to the yoneda embedding. -/
@[simp] theorem functor_inclusion_app {C : Type u} [category C] {X : C} (S : sieve X) (Y : Cᵒᵖ) (f : functor.obj (functor S) Y) : nat_trans.app (functor_inclusion S) Y f = subtype.val f :=
Eq.refl (nat_trans.app (functor_inclusion S) Y f)
theorem nat_trans_of_le_comm {C : Type u} [category C] {X : C} {S : sieve X} {T : sieve X} (h : S ≤ T) : nat_trans_of_le h ≫ functor_inclusion T = functor_inclusion S :=
rfl
/-- The presheaf induced by a sieve is a subobject of the yoneda embedding. -/
protected instance functor_inclusion_is_mono {C : Type u} [category C] {X : C} {S : sieve X} : mono (functor_inclusion S) :=
mono.mk
fun (Z : Cᵒᵖ ⥤ Type v) (f g : Z ⟶ functor S) (h : f ≫ functor_inclusion S = g ≫ functor_inclusion S) =>
nat_trans.ext f g
(funext fun (Y : Cᵒᵖ) => funext fun (y : functor.obj Z Y) => subtype.ext (congr_fun (nat_trans.congr_app h Y) y))
/--
A natural transformation to a representable functor induces a sieve. This is the left inverse of
`functor_inclusion`, shown in `sieve_of_functor_inclusion`.
-/
-- TODO: Show that when `f` is mono, this is right inverse to `functor_inclusion` up to isomorphism.
@[simp] theorem sieve_of_subfunctor_apply {C : Type u} [category C] {X : C} {R : Cᵒᵖ ⥤ Type v} (f : R ⟶ functor.obj yoneda X) (Y : C) (g : Y ⟶ X) : coe_fn (sieve_of_subfunctor f) Y g = ∃ (t : functor.obj R (opposite.op Y)), nat_trans.app f (opposite.op Y) t = g :=
Eq.refl (coe_fn (sieve_of_subfunctor f) Y g)
theorem sieve_of_subfunctor_functor_inclusion {C : Type u} [category C] {X : C} {S : sieve X} : sieve_of_subfunctor (functor_inclusion S) = S := sorry
protected instance functor_inclusion_top_is_iso {C : Type u} [category C] {X : C} : is_iso (functor_inclusion ⊤) :=
is_iso.mk
(nat_trans.mk fun (Y : Cᵒᵖ) (a : functor.obj (functor.obj yoneda X) Y) => { val := a, property := True.intro })
|
cced3b488a6f027ba599debb96dfc1cbe9075c7c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/default_auto.lean | dd9f9229ec153a984125ddd062aafb63ab330654 | [] | 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 | 151 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.linear_algebra.basic
import Mathlib.PostPort
namespace Mathlib
end Mathlib |
d7b7b9e1f0cfa0934af77805b7b0273a339c27d5 | 05b503addd423dd68145d68b8cde5cd595d74365 | /src/algebra/punit_instances.lean | 7244a741eff7c81746e72bf164eda786173cdb5c | [
"Apache-2.0"
] | permissive | aestriplex/mathlib | 77513ff2b176d74a3bec114f33b519069788811d | e2fa8b2b1b732d7c25119229e3cdfba8370cb00f | refs/heads/master | 1,621,969,960,692 | 1,586,279,279,000 | 1,586,279,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,426 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Instances on punit.
-/
import algebra.module
universes u
namespace punit
variables (x y : punit.{u+1}) (s : set punit.{u+1})
@[to_additive add_comm_group]
instance : comm_group punit :=
by refine
{ mul := λ _ _, star,
one := star,
inv := λ _, star, .. };
intros; exact subsingleton.elim _ _
instance : comm_ring punit :=
by refine
{ .. punit.comm_group,
.. punit.add_comm_group,
.. };
intros; exact subsingleton.elim _ _
instance : complete_boolean_algebra punit :=
by refine
{ le := λ _ _, true,
le_antisymm := λ _ _ _ _, subsingleton.elim _ _,
lt := λ _ _, false,
lt_iff_le_not_le := λ _ _, iff_of_false not_false (λ H, H.2 trivial),
top := star,
bot := star,
sup := λ _ _, star,
inf := λ _ _, star,
Sup := λ _, star,
Inf := λ _, star,
sub := λ _ _, star,
.. punit.comm_ring, .. };
intros; trivial
instance : canonically_ordered_monoid punit :=
by refine
{ lt_of_add_lt_add_left := λ _ _ _, id,
le_iff_exists_add := λ _ _, iff_of_true _ ⟨star, subsingleton.elim _ _⟩,
.. punit.comm_ring, .. punit.complete_boolean_algebra, .. };
intros; trivial
instance : decidable_linear_ordered_cancel_comm_monoid punit :=
{ add_left_cancel := λ _ _ _ _, subsingleton.elim _ _,
add_right_cancel := λ _ _ _ _, subsingleton.elim _ _,
le_of_add_le_add_left := λ _ _ _ _, trivial,
le_total := λ _ _, or.inl trivial,
decidable_le := λ _ _, decidable.true,
decidable_eq := punit.decidable_eq,
decidable_lt := λ _ _, decidable.false,
.. punit.canonically_ordered_monoid }
instance (R : Type u) [ring R] : module R punit := module.of_core $
by refine
{ smul := λ _ _, star,
.. punit.comm_ring, .. };
intros; exact subsingleton.elim _ _
@[simp] lemma zero_eq : (0 : punit) = star := rfl
@[simp, to_additive] lemma one_eq : (1 : punit) = star := rfl
@[simp] lemma add_eq : x + y = star := rfl
@[simp, to_additive] lemma mul_eq : x * y = star := rfl
@[simp] lemma neg_eq : -x = star := rfl
@[simp, to_additive] lemma inv_eq : x⁻¹ = star := rfl
lemma smul_eq : x • y = star := rfl
@[simp] lemma top_eq : (⊤ : punit) = star := rfl
@[simp] lemma bot_eq : (⊥ : punit) = star := rfl
@[simp] lemma sup_eq : x ⊔ y = star := rfl
@[simp] lemma inf_eq : x ⊓ y = star := rfl
@[simp] lemma Sup_eq : Sup s = star := rfl
@[simp] lemma Inf_eq : Inf s = star := rfl
@[simp] protected lemma le : x ≤ y := trivial
@[simp] lemma not_lt : ¬(x < y) := not_false
instance {α : Type*} [has_mul α] (f : α → punit) : is_mul_hom f :=
⟨λ _ _, subsingleton.elim _ _⟩
instance {α : Type*} [has_add α] (f : α → punit) : is_add_hom f :=
⟨λ _ _, subsingleton.elim _ _⟩
instance {α : Type*} [monoid α] (f : α → punit) : is_monoid_hom f :=
{ map_one := subsingleton.elim _ _ }
instance {α : Type*} [add_monoid α] (f : α → punit) : is_add_monoid_hom f :=
{ map_zero := subsingleton.elim _ _ }
instance {α : Type*} [group α] (f : α → punit) : is_group_hom f :=
{ }
instance {α : Type*} [add_group α] (f : α → punit) : is_add_group_hom f :=
{ }
instance {α : Type*} [semiring α] (f : α → punit) : is_semiring_hom f :=
{ .. punit.is_monoid_hom f, .. punit.is_add_monoid_hom f }
instance {α : Type*} [ring α] (f : α → punit) : is_ring_hom f :=
{ .. punit.is_semiring_hom f }
end punit
|
a55096a9a45e6e88fcbafab7eb37e5ef52e5d2d8 | 54deab7025df5d2df4573383df7e1e5497b7a2c2 | /order/filter.lean | a55c2411e4f75f94c360e2a35cbe5da6257d766a | [
"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 | 62,467 | 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
Theory of filters on sets.
-/
import order.complete_lattice order.galois_connection data.set order.zorn
open lattice set
universes u v w x y
open set classical
local attribute [instance] decidable_inhabited
local attribute [instance] prop_decidable
-- should be handled by implies_true_iff
namespace lattice
variables {α : Type u} {ι : Sort v} [complete_lattice α]
lemma Inf_eq_finite_sets {s : set α} :
Inf s = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t) :=
le_antisymm
(le_infi $ assume t, le_infi $ assume ⟨_, h⟩, Inf_le_Inf h)
(le_Inf $ assume b h, infi_le_of_le {b} $ infi_le_of_le (by simp [h]) $ Inf_le $ by simp)
end lattice
namespace set
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y}
theorem monotone_inter [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ∩ (g x)) :=
assume a b h x ⟨h₁, h₂⟩, ⟨hf h h₁, hg h h₂⟩
theorem monotone_set_of [preorder α] {p : α → β → Prop}
(hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) :=
assume a a' h b, hp b h
end set
section order
variables {α : Type u} (r : α → α → Prop)
local infix `≼` : 50 := r
def directed {ι : Sort v} (f : ι → α) := ∀x, ∀y, ∃z, f z ≼ f x ∧ f z ≼ f y
def directed_on (s : set α) := ∀x ∈ s, ∀y ∈ s, ∃z ∈ s, z ≼ x ∧ z ≼ y
lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊇) f)
(h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) :=
by simp [directed_on]; exact
assume a₁ ⟨b₁, fb₁⟩ a₂ ⟨b₂, fb₂⟩,
let
⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂)
in
⟨x, xa₁, xa₂, z, xf⟩
def upwards (s : set α) := ∀{x y}, x ∈ s → x ≼ y → y ∈ s
end order
theorem directed_of_chain {α : Type u} {β : Type v} [preorder β] {f : α → β} {c : set α}
(h : @zorn.chain α (λa b, f b ≤ f a) c) :
directed (≤) (λx:{a:α // a ∈ c}, f (x.val)) :=
assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases
(assume : a = b, begin simp [this]; exact ⟨⟨b, hb⟩, le_refl _⟩ end)
(assume : a ≠ b,
have f b ≤ f a ∨ f a ≤ f b, from h a ha b hb this,
or.elim this
(assume : f b ≤ f a, ⟨⟨b, hb⟩, this, le_refl _⟩)
(assume : f a ≤ f b, ⟨⟨a, ha⟩, le_refl _, this⟩))
structure filter (α : Type u) :=
(sets : set (set α))
(inhabited : ∃x, x ∈ sets)
(upwards_sets : upwards (⊆) sets)
(directed_sets : directed_on (⊆) sets)
namespace filter
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g
| ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl
lemma univ_mem_sets' {f : filter α} {s : set α} (h : ∀ a, a ∈ s): s ∈ f.sets :=
let ⟨x, x_in_s⟩ := f.inhabited in
f.upwards_sets x_in_s (assume x _, h x)
lemma univ_mem_sets {f : filter α} : univ ∈ f.sets :=
univ_mem_sets' mem_univ
lemma inter_mem_sets {f : filter α} {x y : set α} (hx : x ∈ f.sets) (hy : y ∈ f.sets) :
x ∩ y ∈ f.sets :=
let ⟨z, ⟨z_in_s, z_le_x, z_le_y⟩⟩ := f.directed_sets _ hx _ hy in
f.upwards_sets z_in_s (subset_inter z_le_x z_le_y)
lemma Inter_mem_sets {f : filter α} {s : β → set α}
{is : set β} (hf : finite is) (hs : ∀i∈is, s i ∈ f.sets) : (⋂i∈is, s i) ∈ f.sets :=
begin /- equation compiler complains that this requires well-founded recursion -/
induction hf with i is _ hf hi,
{ simp [univ_mem_sets] },
begin
simp,
apply inter_mem_sets,
apply hs i,
simp,
exact (hi $ assume a ha, hs _ $ by simp [ha])
end
end
lemma exists_sets_subset_iff {f : filter α} {x : set α} :
(∃y∈f.sets, y ⊆ x) ↔ x ∈ f.sets :=
⟨assume ⟨y, hy, yx⟩, f.upwards_sets hy yx,
assume hx, ⟨x, hx, subset.refl _⟩⟩
lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f.sets) :=
assume s t hst h, f.upwards_sets h hst
def principal (s : set α) : filter α :=
{ filter .
sets := {t | s ⊆ t},
inhabited := ⟨s, subset.refl _⟩,
upwards_sets := assume x y hx hy, subset.trans hx hy,
directed_sets := assume x hx y hy, ⟨s, subset.refl _, hx, hy⟩ }
def join (f : filter (filter α)) : filter α :=
{ filter .
sets := {s | {t : filter α | s ∈ t.sets} ∈ f.sets},
inhabited := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩,
upwards_sets := assume x y hx xy, f.upwards_sets hx $ assume a h, a.upwards_sets h xy,
directed_sets := assume x hx y hy, ⟨x ∩ y,
f.upwards_sets (inter_mem_sets hx hy) $ assume z ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def map (m : α → β) (f : filter α) : filter β :=
{ filter .
sets := preimage (preimage m) f.sets,
inhabited := ⟨univ, univ_mem_sets⟩,
upwards_sets := assume s t hs st, f.upwards_sets hs (assume x h, st h),
directed_sets := assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def vmap (m : α → β) (f : filter β) : filter α :=
{ filter .
sets := { s | ∃t∈f.sets, preimage m t ⊆ s },
inhabited := ⟨univ, univ, univ_mem_sets, by simp⟩,
upwards_sets := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩,
directed_sets := assume a ⟨a', ha₁, ha₂⟩ b ⟨b', hb₁, hb₂⟩,
⟨preimage m (a' ∩ b'),
⟨a' ∩ b', inter_mem_sets ha₁ hb₁, subset.refl _⟩,
subset.trans (preimage_mono $ inter_subset_left _ _) ha₂,
subset.trans (preimage_mono $ inter_subset_right _ _) hb₂⟩ }
protected def sup (f g : filter α) : filter α :=
{ filter .
sets := f.sets ∩ g.sets,
inhabited := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩,
upwards_sets := assume x y hx xy,
and.imp (assume h, f.upwards_sets h xy) (assume h, g.upwards_sets h xy) hx,
directed_sets := assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y,
⟨inter_mem_sets hx₁ hy₁, inter_mem_sets hx₂ hy₂⟩,
inter_subset_left _ _, inter_subset_right _ _⟩ }
protected def inf (f g : filter α) :=
{ filter .
sets := {s | ∃ a ∈ f.sets, ∃ b ∈ g.sets, a ∩ b ⊆ s },
inhabited := ⟨univ, univ, univ_mem_sets, univ, univ_mem_sets, subset_univ _⟩,
upwards_sets := assume x y ⟨a, ha, b, hb, h⟩ xy,
⟨a, ha, b, hb, subset.trans h xy⟩,
directed_sets := assume x ⟨a₁, ha₁, b₁, hb₁, h₁⟩ y ⟨a₂, ha₂, b₂, hb₂, h₂⟩,
⟨x ∩ y,
⟨_, inter_mem_sets ha₁ ha₂, _, inter_mem_sets hb₁ hb₂,
calc (a₁ ⊓ a₂) ⊓ (b₁ ⊓ b₂) = (a₁ ⊓ b₁) ⊓ (a₂ ⊓ b₂) : by ac_refl
... ≤ x ∩ y : inf_le_inf h₁ h₂ ⟩,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def cofinite : filter α :=
{ filter .
sets := {s | finite (- s)},
inhabited := ⟨univ, by simp⟩,
upwards_sets := assume s t, assume hs : finite (-s), assume st: s ⊆ t,
finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st,
directed_sets := assume s, assume hs : finite (-s), assume t, assume ht : finite (-t),
⟨s ∩ t, by simp [compl_inter, finite_union, ht, hs],
inter_subset_left _ _, inter_subset_right _ _⟩ }
instance partial_order_filter : partial_order (filter α) :=
{ partial_order .
le := λf g, g.sets ⊆ f.sets,
le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁,
le_refl := assume a, subset.refl _,
le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ }
instance : has_Sup (filter α) := ⟨join ∘ principal⟩
instance inhabited' : _root_.inhabited (filter α) :=
⟨principal ∅⟩
protected lemma le_Sup {s : set (filter α)} {f : filter α} : f ∈ s → f ≤ Sup s :=
assume f_in_s t' h, h f_in_s
protected lemma Sup_le {s : set (filter α)} {f : filter α} : (∀g∈s, g ≤ f) → Sup s ≤ f :=
assume h a ha g hg, h g hg ha
@[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} :
s ∈ (join f).sets = ({t | s ∈ filter.sets t} ∈ f.sets) := rfl
@[simp] lemma mem_principal_sets {s t : set α} : s ∈ (principal t).sets = (t ⊆ s) := rfl
@[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f.sets :=
show (∀{t}, s ⊆ t → t ∈ f.sets) ↔ s ∈ f.sets,
from ⟨assume h, h (subset.refl s), assume hs t ht, f.upwards_sets hs ht⟩
lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t :=
by simp
lemma monotone_principal : monotone (principal : set α → filter α) :=
by simp [monotone, principal_mono]; exact assume a b h, h
@[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t :=
by simp [eq_iff_le_and_le]; refl
instance complete_lattice_filter : complete_lattice (filter α) :=
{ filter.partial_order_filter with
sup := filter.sup,
le_sup_left := assume a b, inter_subset_left _ _,
le_sup_right := assume a b, inter_subset_right _ _,
sup_le := assume a b c h₁ h₂, subset_inter h₁ h₂,
inf := filter.inf,
le_inf := assume f g h fg fh s ⟨a, ha, b, hb, h⟩,
f.upwards_sets (inter_mem_sets (fg ha) (fh hb)) h,
inf_le_left := assume f g s h, ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩,
inf_le_right := assume f g s h, ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩,
top := principal univ,
le_top := assume a, show a ≤ principal univ, by simp [univ_mem_sets],
bot := principal ∅,
bot_le := assume a, show a.sets ⊆ {x | ∅ ⊆ x}, by simp; apply subset_univ,
Sup := Sup,
le_Sup := assume s f, filter.le_Sup,
Sup_le := assume s f, filter.Sup_le,
Inf := λs, Sup {x | ∀y∈s, x ≤ y},
le_Inf := assume s a h, filter.le_Sup h,
Inf_le := assume s a ha, filter.Sup_le $ assume b h, h _ ha }
@[simp] lemma map_principal {s : set α} {f : α → β} :
map f (principal s) = principal (set.image f s) :=
filter_eq $ set.ext $ assume a, image_subset_iff_subset_preimage.symm
@[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl
instance monad_filter : monad filter :=
{ monad .
bind := λ(α β : Type u) f m, join (map m f),
pure := λ(α : Type u) x, principal {x},
map := λ(α β : Type u), filter.map,
id_map := assume α f, filter_eq $ rfl,
pure_bind := assume α β a f, by simp [Sup_image],
bind_assoc := assume α β γ f m₁ m₂, filter_eq $ rfl,
bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp [join, map, preimage, principal] }
@[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl
@[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = join (map m f) := rfl
instance : alternative filter :=
{ filter.monad_filter with
failure := λα, ⊥,
orelse := λα x y, x ⊔ y }
def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b}
def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a}
/- lattice equations -/
lemma mem_inf_sets_of_left {f g : filter α} {s : set α} :
s ∈ f.sets → s ∈ (f ⊓ g).sets :=
have f ⊓ g ≤ f, from inf_le_left,
assume hs, this hs
lemma mem_inf_sets_of_right {f g : filter α} {s : set α} :
s ∈ g.sets → s ∈ (f ⊓ g).sets :=
have f ⊓ g ≤ g, from inf_le_right,
assume hs, this hs
@[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α).sets :=
assume x, false.elim
lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f.sets ↔ f = ⊥ :=
⟨assume h, bot_unique $ assume s _, f.upwards_sets h (empty_subset s),
assume : f = ⊥, this.symm ▸ mem_bot_sets⟩
lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f.sets) :
∃x, x ∈ s :=
have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h,
have s ≠ ∅, from assume h, this (h ▸ hs),
exists_mem_of_ne_empty this
lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ :=
empty_in_sets_eq_bot.mp $ f.upwards_sets univ_mem_sets $
assume x, false.elim (ne ⟨x⟩)
lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} :
(∀ (s : set α), s ∈ f.sets → s ≠ ∅) ↔ f ≠ ⊥ :=
by
simp [(@empty_in_sets_eq_bot α f).symm];
exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩
lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f.sets :=
have ∅ ∈ (f ⊓ principal (- s)).sets, from h.symm ▸ mem_bot_sets,
let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in
have s₁ ⊆ s, from assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩,
f.upwards_sets hs₁ this
@[simp] lemma mem_sup_sets {f g : filter α} {s : set α} :
s ∈ (f ⊔ g).sets = (s ∈ f.sets ∧ s ∈ g.sets) := rfl
@[simp] lemma mem_inf_sets {f g : filter α} {s : set α} :
s ∈ (f ⊓ g).sets = (∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s) :=
by refl
lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α}
(hs : s ∈ f.sets) (ht : t ∈ g.sets) : s ∩ t ∈ (f ⊓ g).sets :=
inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht)
lemma infi_sets_eq {f : ι → filter α} (h : directed (≤) f) (ne : nonempty ι) :
(infi f).sets = (⋃ i, (f i).sets) :=
let
⟨i⟩ := ne,
u := { filter .
sets := (⋃ i, (f i).sets),
inhabited := ⟨univ, begin simp, exact ⟨i, univ_mem_sets⟩ end⟩,
directed_sets := directed_on_Union (show directed (≤) f, from h) (assume i, (f i).directed_sets),
upwards_sets := by simp [upwards]; exact assume x y ⟨j, xf⟩ xy, ⟨j, (f j).upwards_sets xf xy⟩ }
in
subset.antisymm
(show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i)
(Union_subset $ assume i, infi_le f i)
lemma infi_sets_eq' {f : β → filter α} {s : set β} (h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) :
(⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) :=
let ⟨i, hi⟩ := ne in
calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by simp [infi_subtype]; refl
... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq
(assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by simp [supr_subtype]; refl
lemma Inf_sets_eq_finite {s : set (filter α)} :
(complete_lattice.Inf s).sets = (⋃ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) :=
calc (Inf s).sets = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t).sets : by rw [lattice.Inf_eq_finite_sets]
... = (⨆ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) : infi_sets_eq'
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∪ y, ⟨finite_union hx₁ hy₁, union_subset hx₂ hy₂⟩,
Inf_le_Inf $ subset_union_left _ _, Inf_le_Inf $ subset_union_right _ _⟩)
⟨∅, by simp⟩
lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) :=
set.ext $ assume s,
show s ∈ (join (principal {a : filter α | ∃i : ι, a = f i})).sets ↔ s ∈ (⋂i, (f i).sets),
begin
rw [mem_join_sets],
simp,
exact ⟨assume h i, h (f i) ⟨_, rfl⟩, assume h x ⟨i, eq⟩, eq.symm ▸ h i⟩
end
@[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) :=
filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join]
@[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) :=
filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join]
instance : bounded_distrib_lattice (filter α) :=
{ filter.complete_lattice_filter with
le_sup_inf := assume x y z s h,
begin
cases h with h₁ h₂, revert h₂,
simp,
exact assume ⟨t₁, ht₁, t₂, ht₂, hs⟩, ⟨s ∪ t₁,
x.upwards_sets h₁ $ subset_union_left _ _,
y.upwards_sets ht₁ $ subset_union_right _ _,
s ∪ t₂,
x.upwards_sets h₁ $ subset_union_left _ _,
z.upwards_sets ht₂ $ subset_union_right _ _,
subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hs)⟩
end }
private lemma infi_finite_distrib {s : set (filter α)} {f : filter α} (h : finite s) :
(⨅ a ∈ s, f ⊔ a) = f ⊔ (Inf s) :=
begin
induction h with a s hn hs hi,
{ simp },
{ rw [infi_insert], simp [hi, infi_or, sup_inf_left] }
end
/- the complementary version with ⨆ g∈s, f ⊓ g does not hold! -/
lemma binfi_sup_eq { f : filter α } {s : set (filter α)} :
(⨅ g∈s, f ⊔ g) = f ⊔ complete_lattice.Inf s :=
le_antisymm
begin
intros t h,
cases h with h₁ h₂,
rw [Inf_sets_eq_finite] at h₂,
simp at h₂,
cases h₂ with s' hs', cases hs' with hs' hs'', cases hs'' with hs's ht',
have ht : t ∈ (⨅ a ∈ s', f ⊔ a).sets,
{ rw [infi_finite_distrib], exact ⟨h₁, ht'⟩, exact hs' },
clear h₁ ht',
revert ht t,
change (⨅ a ∈ s, f ⊔ a) ≤ (⨅ a ∈ s', f ⊔ a),
apply infi_le_infi2 _,
exact assume i, ⟨i, infi_le_infi2 $ assume h, ⟨hs's h, le_refl _⟩⟩
end
(le_infi $ assume g, le_infi $ assume h, sup_le_sup (le_refl f) $ Inf_le h)
lemma infi_sup_eq { f : filter α } {g : ι → filter α} :
(⨅ x, f ⊔ g x) = f ⊔ infi g :=
calc (⨅ x, f ⊔ g x) = (⨅ x (h : ∃i, g i = x), f ⊔ x) : by simp; rw [infi_comm]; simp
... = f ⊔ Inf {x | ∃i, g i = x} : binfi_sup_eq
... = f ⊔ infi g : by rw [Inf_eq_infi]; dsimp; simp; rw [infi_comm]; simp
/- principal equations -/
@[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) :=
le_antisymm
(by simp; exact ⟨s, subset.refl s, t, subset.refl t, subset.refl _⟩)
(by simp [le_inf_iff, inter_subset_left, inter_subset_right])
@[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) :=
filter_eq $ set.ext $ by simp [union_subset_iff]
@[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) :=
filter_eq $ set.ext $ assume x, by simp [supr_sets_eq]; exact (@supr_le_iff (set α) _ _ _ _).symm
lemma principal_univ : principal (univ : set α) = ⊤ := rfl
lemma principal_empty : principal (∅ : set α) = ⊥ := rfl
@[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ :=
⟨assume h, principal_eq_iff_eq.mp $ by simp [principal_empty, h], assume h, by simp [*, principal_empty]⟩
@[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α).sets :=
by simp; exact id
/- map and vmap equations -/
section map
variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β}
@[simp] lemma mem_map : (t ∈ (map m f).sets) = ({x | m x ∈ t} ∈ f.sets) := rfl
lemma image_mem_map (hs : s ∈ f.sets) : m '' s ∈ (map m f).sets :=
f.upwards_sets hs $ assume x hx, ⟨x, hx, rfl⟩
@[simp] lemma map_id : filter.map id f = f :=
filter_eq $ rfl
@[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) :=
funext $ assume _, filter_eq $ rfl
@[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f :=
congr_fun (@@filter.map_compose m m') f
theorem mem_vmap : s ∈ (vmap m g).sets = (∃t∈g.sets, m ⁻¹' t ⊆ s) := rfl
theorem preimage_mem_vmap (ht : t ∈ g.sets) : m ⁻¹' t ∈ (vmap m g).sets :=
⟨t, ht, subset.refl _⟩
lemma vmap_id : vmap id f = f :=
le_antisymm (assume s, preimage_mem_vmap) (assume s ⟨t, ht, hst⟩, f.upwards_sets ht hst)
lemma vmap_vmap_comp {m : γ → β} {n : β → α} : vmap m (vmap n f) = vmap (n ∘ m) f :=
le_antisymm
(assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_vmap hb, h⟩)
(assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩,
⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩)
@[simp] theorem vmap_principal {t : set β} : vmap m (principal t) = principal (m ⁻¹' t) :=
filter_eq $ set.ext $ assume s,
⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b,
assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩
lemma map_le_iff_vmap_le : map m f ≤ g ↔ f ≤ vmap m g :=
⟨assume h s ⟨t, ht, hts⟩, f.upwards_sets (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩
lemma gc_map_vmap (m : α → β) : galois_connection (map m) (vmap m) :=
assume f g, map_le_iff_vmap_le
lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_vmap m).monotone_l h
lemma monotone_map : monotone (map m) := assume a b h, map_mono h
lemma vmap_mono (h : g₁ ≤ g₂) : vmap m g₁ ≤ vmap m g₂ := (gc_map_vmap m).monotone_u h
lemma monotone_vmap : monotone (vmap m) := assume a b h, vmap_mono h
@[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_vmap m).l_bot
@[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_vmap m).l_sup
@[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) :=
(gc_map_vmap m).l_supr
@[simp] lemma vmap_top : vmap m ⊤ = ⊤ := (gc_map_vmap m).u_top
@[simp] lemma vmap_inf : vmap m (g₁ ⊓ g₂) = vmap m g₁ ⊓ vmap m g₂ := (gc_map_vmap m).u_inf
@[simp] lemma vmap_infi {f : ι → filter β} : vmap m (⨅i, f i) = (⨅i, vmap m (f i)) :=
(gc_map_vmap m).u_infi
lemma map_vmap_le : map m (vmap m g) ≤ g := (gc_map_vmap m).decreasing_l_u _
lemma le_vmap_map : f ≤ vmap m (map m f) := (gc_map_vmap m).increasing_u_l _
@[simp] lemma vmap_bot : vmap m ⊥ = ⊥ :=
bot_unique $ assume s _, ⟨∅, by simp, by simp⟩
lemma vmap_sup : vmap m (g₁ ⊔ g₂) = vmap m g₁ ⊔ vmap m g₂ :=
le_antisymm
(assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩,
⟨t₁ ∪ t₂,
⟨g₁.upwards_sets ht₁ (subset_union_left _ _), g₂.upwards_sets ht₂ (subset_union_right _ _)⟩,
union_subset hs₁ hs₂⟩)
(sup_le (vmap_mono le_sup_left) (vmap_mono le_sup_right))
lemma le_map_vmap' {f : filter β} {m : α → β} {s : set β}
(hs : s ∈ f.sets) (hm : ∀b∈s, ∃a, m a = b) : f ≤ map m (vmap m f) :=
assume t' ⟨t, ht, (sub : ∀x, m x ∈ t → m x ∈ t')⟩,
f.upwards_sets (inter_mem_sets ht hs) $
assume x ⟨hxt, hxs⟩,
let ⟨y, (hy : m y = x)⟩ := hm x hxs in
hy ▸ sub _ (show m y ∈ t, from hy.symm ▸ hxt)
lemma le_map_vmap {f : filter β} {m : α → β} (hm : ∀x, ∃y, m y = x) : f ≤ map m (vmap m f) :=
le_map_vmap' univ_mem_sets (assume b _, hm b)
lemma vmap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
vmap m (map m f) = f :=
have ∀s, preimage m (image m s) = s,
from assume s, preimage_image_eq h,
le_antisymm
(assume s hs, ⟨
image m s,
f.upwards_sets hs $ by simp [this, subset.refl],
by simp [this, subset.refl]⟩)
(assume s ⟨t, (h₁ : preimage m t ∈ f.sets), (h₂ : preimage m t ⊆ s)⟩,
f.upwards_sets h₁ h₂)
lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) :
f = g :=
have vmap m (map m f) = vmap m (map m g), by rw h,
by rwa [vmap_map hm, vmap_map hm] at this
lemma vmap_neq_bot {f : filter β} {m : α → β}
(hm : ∀t∈f.sets, ∃a, m a ∈ t) : vmap m f ≠ ⊥ :=
forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩,
let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in
neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s
lemma vmap_neq_bot_of_surj {f : filter β} {m : α → β}
(hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : vmap m f ≠ ⊥ :=
vmap_neq_bot $ assume t ht,
let
⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht,
⟨a, (ha : m a = b)⟩ := hm b
in ⟨a, ha.symm ▸ hx⟩
lemma le_vmap_iff_map_le {f : filter α} {g : filter β} {m : α → β} :
f ≤ vmap m g ↔ map m f ≤ g :=
⟨assume h, le_trans (map_mono h) map_vmap_le,
assume h, le_trans le_vmap_map (vmap_mono h)⟩
@[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ :=
⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id,
assume h, by simp [*]⟩
lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ :=
assume h, hf $ by rwa [map_eq_bot_iff] at h
end map
lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f.sets) :
map m₁ f = map m₂ f :=
have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f.sets), map m₁ f ≤ map m₂ f,
from assume m₁ m₂ h s (hs : {x | m₂ x ∈ s} ∈ f.sets),
show {x | m₁ x ∈ s} ∈ f.sets,
from f.upwards_sets (inter_mem_sets hs h) $
assume x ⟨(h₁ : m₂ x ∈ s), (h₂ : m₁ x = m₂ x)⟩, show m₁ x ∈ s, from h₂.symm ▸ h₁,
le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ f.upwards_sets h $ assume x, eq.symm)
-- this is a generic rule for monotone functions:
lemma map_infi_le {f : ι → filter α} {m : α → β} :
map m (infi f) ≤ (⨅ i, map m (f i)) :=
le_infi $ assume i, map_mono $ infi_le _ _
lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≤) f) (hι : nonempty ι) :
map m (infi f) = (⨅ i, map m (f i)) :=
le_antisymm
map_infi_le
(assume s (hs : preimage m s ∈ (infi f).sets),
have ∃i, preimage m s ∈ (f i).sets,
by simp [infi_sets_eq hf hι] at hs; assumption,
let ⟨i, hi⟩ := this in
have (⨅ i, map m (f i)) ≤ principal s,
from infi_le_of_le i $ by simp; assumption,
by simp at this; assumption)
lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {s : set ι}
(h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) : map m (⨅i∈s, f i) = (⨅i∈s, map m (f i)) :=
let ⟨i, hi⟩ := ne in
calc map m (⨅i∈s, f i) = map m (⨅i:{i // i ∈ s}, f i.val) : by simp [infi_subtype]
... = (⨅i:{i // i ∈ s}, map m (f i.val)) : map_infi_eq
(assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨅i∈s, map m (f i)) : by simp [infi_subtype]
lemma map_inf {f g : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
map m (f ⊓ g) = map m f ⊓ map m g :=
le_antisymm
(le_inf (map_mono inf_le_left) (map_mono inf_le_right))
(assume s hs,
begin
simp [map, mem_inf_sets] at hs,
simp [map, mem_inf_sets],
exact (let ⟨t₁, h₁, t₂, h₂, hs⟩ := hs in
⟨m '' t₁, f.upwards_sets h₁ $ image_subset_iff_subset_preimage.mp $ subset.refl _,
m '' t₂,
by rwa [set.image_inter h, image_subset_iff_subset_preimage],
g.upwards_sets h₂ $ image_subset_iff_subset_preimage.mp $ subset.refl _⟩)
end)
/- bind equations -/
lemma mem_bind_sets {β : Type u} {s : set β} {f : filter α} {m : α → filter β} :
s ∈ (f >>= m).sets ↔ (∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets) :=
calc s ∈ (f >>= m).sets ↔ {a | s ∈ (m a).sets} ∈ f.sets : by simp
... ↔ (∃t ∈ f.sets, t ⊆ {a | s ∈ (m a).sets}) : exists_sets_subset_iff.symm
... ↔ (∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets) : iff.refl _
lemma bind_mono {β : Type u} {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f.sets) :
f >>= g ≤ f >>= h :=
assume x h₂, f.upwards_sets (inter_mem_sets h₁ h₂) $ assume s ⟨gh', h'⟩, gh' h'
lemma bind_sup {β : Type u} {f g : filter α} {h : α → filter β} :
(f ⊔ g) >>= h = (f >>= h) ⊔ (g >>= h) :=
by simp
lemma bind_mono2 {β : Type u} {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) :
f >>= h ≤ g >>= h :=
assume s h', h₁ h'
lemma principal_bind {β : Type u} {s : set α} {f : α → filter β} :
(principal s >>= f) = (⨆x ∈ s, f x) :=
show join (map f (principal s)) = (⨆x ∈ s, f x),
by simp [Sup_image]
lemma seq_mono {β : Type u} {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α}
(hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ <*> g₁ ≤ f₂ <*> g₂ :=
le_trans (bind_mono2 hf) (bind_mono $ univ_mem_sets' $ assume f, map_mono hg)
@[simp] lemma fmap_principal {β : Type u} {s : set α} {f : α → β} :
f <$> principal s = principal (set.image f s) :=
filter_eq $ set.ext $ assume a, image_subset_iff_subset_preimage.symm
lemma mem_return_sets {a : α} {s : set α} : s ∈ (return a : filter α).sets ↔ a ∈ s :=
show s ∈ (principal {a}).sets ↔ a ∈ s,
by simp
lemma infi_neq_bot_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≤) f) (hb : ∀i, f i ≠ ⊥): (infi f) ≠ ⊥ :=
let ⟨x⟩ := hn in
assume h, have he: ∅ ∈ (infi f).sets, from h.symm ▸ mem_bot_sets,
classical.by_cases
(assume : nonempty ι,
have ∃i, ∅ ∈ (f i).sets,
by rw [infi_sets_eq hd this] at he; simp at he; assumption,
let ⟨i, hi⟩ := this in
hb i $ bot_unique $
assume s _, (f i).upwards_sets hi $ empty_subset _)
(assume : ¬ nonempty ι,
have univ ⊆ (∅ : set α),
begin
rw [←principal_mono, principal_univ, principal_empty, ←h],
exact (le_infi $ assume i, false.elim $ this ⟨i⟩)
end,
this $ mem_univ x)
lemma infi_neq_bot_iff_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≤) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) :=
⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _,
infi_neq_bot_of_directed hn hd⟩
@[simp] lemma return_neq_bot {α : Type u} {a : α} : return a ≠ (⊥ : filter α) :=
by simp [return]
/- tendsto -/
def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := filter.map f l₁ ≤ l₂
lemma tendsto_cong {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(h : tendsto f₁ l₁ l₂) (hl : {x | f₁ x = f₂ x} ∈ l₁.sets) : tendsto f₂ l₁ l₂ :=
by rwa [tendsto, ←map_cong hl]
lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y :=
by simp [tendsto] { contextual := tt }
lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x
lemma tendsto_compose {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ}
(hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g ∘ f) x z :=
calc map (g ∘ f) x = map g (map f x) : by rw [map_map]
... ≤ map g y : map_mono hf
... ≤ z : hg
lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x)
lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ}
(h : tendsto (f ∘ g) x y) : tendsto f (map g x) y :=
by rwa [tendsto, map_map]
lemma tendsto_vmap {f : α → β} {x : filter β} : tendsto f (vmap f x) x :=
map_vmap_le
lemma tendsto_vmap' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ}
(h : tendsto (f ∘ g) x y) : tendsto g x (vmap f y) :=
le_vmap_iff_map_le.mpr $ by rwa [map_map]
lemma tendsto_vmap'' {m : α → β} {f : filter α} {g : filter β} (s : set α)
{i : γ → α} (hs : s ∈ f.sets) (hi : ∀a∈s, ∃c, i c = a)
(h : tendsto (m ∘ i) (vmap i f) g) : tendsto m f g :=
have tendsto m (map i $ vmap i $ f) g,
by rwa [tendsto, ←map_compose] at h,
le_trans (map_mono $ le_map_vmap' hs hi) this
lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β}
(h₁ : tendsto f x y₁) (h₂ : tendsto f x y₂) : tendsto f x (y₁ ⊓ y₂) :=
le_inf h₁ h₂
section lift
protected def lift (f : filter α) (g : set α → filter β) :=
(⨅s ∈ f.sets, g s)
section
variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β}
lemma lift_sets_eq (hg : monotone g) : (f.lift g).sets = (⋃t∈f.sets, (g t).sets) :=
infi_sets_eq'
(assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht,
hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩)
⟨univ, univ_mem_sets⟩
lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f.sets) (hs : s ∈ (g t).sets) :
s ∈ (f.lift g).sets :=
le_principal_iff.mp $ show f.lift g ≤ principal s,
from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs
lemma mem_lift_iff (hg : monotone g) {s : set β} :
s ∈ (f.lift g).sets ↔ (∃t∈f.sets, s ∈ (g t).sets) :=
by rw [lift_sets_eq hg]; simp
lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α}
(hs : s ∈ f.sets) (hg : g s ≤ h) : f.lift g ≤ h :=
infi_le_of_le s $ infi_le_of_le hs $ hg
lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩
lemma lift_mono' (hg : ∀s∈f.sets, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs
lemma map_lift_eq {m : β → γ} (hg : monotone g) :
map m (f.lift g) = f.lift (map m ∘ g) :=
have monotone (map m ∘ g),
from monotone_comp hg monotone_map,
filter_eq $ set.ext $
by simp [mem_lift_iff, hg, @mem_lift_iff _ _ f _ this]
lemma vmap_lift_eq {m : γ → β} (hg : monotone g) :
vmap m (f.lift g) = f.lift (vmap m ∘ g) :=
have monotone (vmap m ∘ g),
from monotone_comp hg monotone_vmap,
filter_eq $ set.ext $
begin
simp [vmap, mem_lift_iff, hg, @mem_lift_iff _ _ f _ this],
simp [vmap, function.comp],
exact assume s, ⟨assume ⟨t₁, hs, t₂, ht, ht₁⟩, ⟨t₂, ht, t₁, hs, ht₁⟩,
assume ⟨t₂, ht, t₁, hs, ht₁⟩, ⟨t₁, hs, t₂, ht, ht₁⟩⟩
end
theorem vmap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) :
(vmap m f).lift g = f.lift (g ∘ preimage m) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs,
infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩)
(le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩,
infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub)
lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) :
(map m f).lift g = f.lift (g ∘ image m) :=
le_antisymm
(infi_le_infi2 $ assume s, ⟨image m s,
infi_le_infi2 $ assume hs, ⟨
f.upwards_sets hs $ assume a h, mem_image_of_mem _ h,
le_refl _⟩⟩)
(infi_le_infi2 $ assume t, ⟨preimage m t,
infi_le_infi2 $ assume ht, ⟨ht,
hg $ assume x, assume h : x ∈ m '' preimage m t,
let ⟨y, hy, h_eq⟩ := h in
show x ∈ t, from h_eq ▸ hy⟩⟩)
lemma lift_comm {g : filter β} {h : set α → set β → filter γ} :
f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
lemma lift_assoc {h : set β → filter γ} (hg : monotone g) :
(f.lift g).lift h = f.lift (λs, (g s).lift h) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le _ $ (mem_lift_iff hg).mpr ⟨_, hs, ht⟩)
(le_infi $ assume t, le_infi $ assume ht,
let ⟨s, hs, h'⟩ := (mem_lift_iff hg).mp ht in
infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h')
lemma lift_lift_same_le_lift {g : set α → set α → filter β} :
f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) :=
le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs
lemma lift_lift_same_eq_lift {g : set α → set α → filter β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)):
f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) :=
le_antisymm
lift_lift_same_le_lift
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le (s ∩ t) $
infi_le_of_le (inter_mem_sets hs ht) $
calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _)
... ≤ g s t : hg₁ s (inter_subset_right _ _))
lemma lift_principal {s : set α} (hg : monotone g) :
(principal s).lift g = g s :=
le_antisymm
(infi_le_of_le s $ infi_le _ $ subset.refl _)
(le_infi $ assume t, le_infi $ assume hi, hg hi)
theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) :=
assume a b h, lift_mono (hf h) (hg h)
lemma lift_neq_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) :=
classical.by_cases
(assume hn : nonempty β,
calc f.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f.sets}, g s.val) ≠ ⊥ : by simp [filter.lift, infi_subtype]
... ↔ (∀s:{ s // s ∈ f.sets}, g s.val ≠ ⊥) :
infi_neq_bot_iff_of_directed hn
(assume ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩,
hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩)
... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨assume h s hs, h ⟨s, hs⟩, assume h ⟨s, hs⟩, h s hs⟩)
(assume hn : ¬ nonempty β,
have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn,
have h₂ : ∀s, g s = ⊥, from assume s, filter_eq_bot_of_not_nonempty hn,
calc (f.lift g ≠ ⊥) ↔ false : by simp [h₁]
... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩
... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp [h₂])
end
section
protected def lift' (f : filter α) (h : set α → set β) :=
f.lift (principal ∘ h)
variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β}
lemma mem_lift' {t : set α} (ht : t ∈ f.sets) : h t ∈ (f.lift' h).sets :=
le_principal_iff.mp $ show f.lift' h ≤ principal (h t),
from infi_le_of_le t $ infi_le_of_le ht $ le_refl _
lemma mem_lift'_iff (hh : monotone h) {s : set β} : s ∈ (f.lift' h).sets ↔ (∃t∈f.sets, h t ⊆ s) :=
have monotone (principal ∘ h),
from assume a b h, principal_mono.mpr $ hh h,
by simp [filter.lift', @mem_lift_iff α β f _ this]
lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α}
(hs : s ∈ f.sets) (hg : principal (g s) ≤ h) : f.lift' g ≤ h :=
lift_le hs hg
lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ :=
lift_mono hf $ assume s, principal_mono.mpr $ hh s
lemma lift'_mono' (hh : ∀s∈f.sets, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs
lemma lift'_cong (hh : ∀s∈f.sets, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ :=
le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm)
lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) :=
calc map m (f.lift' h) = f.lift (map m ∘ principal ∘ h) :
map_lift_eq $ monotone_comp hh monotone_principal
... = f.lift' (image m ∘ h) : by simp [function.comp, filter.lift']
lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) :
(map m f).lift' g = f.lift' (g ∘ image m) :=
map_lift_eq2 $ monotone_comp hg monotone_principal
theorem vmap_lift'_eq {m : γ → β} (hh : monotone h) :
vmap m (f.lift' h) = f.lift' (preimage m ∘ h) :=
calc vmap m (f.lift' h) = f.lift (vmap m ∘ principal ∘ h) :
vmap_lift_eq $ monotone_comp hh monotone_principal
... = f.lift' (preimage m ∘ h) : by simp [function.comp, filter.lift']
theorem vmap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) :
(vmap m f).lift' g = f.lift' (g ∘ preimage m) :=
vmap_lift_eq2 $ monotone_comp hg monotone_principal
lemma lift'_principal {s : set α} (hh : monotone h) :
(principal s).lift' h = principal (h s) :=
lift_principal $ monotone_comp hh monotone_principal
lemma principal_le_lift' {t : set β} (hh : ∀s∈f.sets, t ⊆ h s) :
principal t ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs)
theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) :=
assume a b h, lift'_mono (hf h) (hg h)
lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift h = f.lift (λs, h (g s)) :=
calc (f.lift' g).lift h = f.lift (λs, (principal (g s)).lift h) :
lift_assoc (monotone_comp hg monotone_principal)
... = f.lift (λs, h (g s)) : by simp [lift_principal, hh]
lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift' h = f.lift' (λs, h (g s)) :=
lift_lift'_assoc hg (monotone_comp hh monotone_principal)
lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ}
(hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) :=
lift_assoc hg
lemma lift_lift'_same_le_lift' {g : set α → set α → set β} :
f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) :=
lift_lift_same_le_lift
lemma lift_lift'_same_eq_lift' {g : set α → set α → set β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)):
f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) :=
lift_lift_same_eq_lift
(assume s, monotone_comp monotone_id $ monotone_comp (hg₁ s) monotone_principal)
(assume t, monotone_comp (hg₂ t) monotone_principal)
lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} :
f.lift' h ⊓ principal s = f.lift' (λt, h t ∩ s) :=
le_antisymm
(le_infi $ assume t, le_infi $ assume ht,
calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s :
inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _)
... = _ : by simp)
(le_inf
(le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le_of_le ht $ by simp; exact inter_subset_right _ _)
(infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp; exact inter_subset_left _ _))
lemma lift'_neq_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) :=
calc (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) :
lift_neq_bot_iff (monotone_comp hh monotone_principal)
... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp [principal_eq_bot_iff]
@[simp] lemma lift'_id {f : filter α} : f.lift' id = f :=
le_antisymm
(assume s hs, mem_lift' hs)
(le_infi $ assume s, le_infi $ assume hs, by simp [hs])
lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β}
(h_le : ∀s∈f.sets, h s ∈ g.sets) : g ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, by simp [h_le]; exact h_le s hs
end
end lift
theorem vmap_eq_lift' {f : filter β} {m : α → β} :
vmap m f = f.lift' (preimage m) :=
filter_eq $ set.ext $ by simp [mem_lift'_iff, monotone_preimage, vmap]
/- product filter -/
/- The product filter cannot be defined using the monad structure on filters. For example:
F := do {x <- seq, y <- top, return (x, y)}
hence:
s ∈ F <-> ∃n, [n..∞] × univ ⊆ s
G := do {y <- top, x <- seq, return (x, y)}
hence:
s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s
Now ⋃i, [i..∞] × {i} is in G but not in F.
As product filter we want to have F as result.
-/
/- Alternative definition of the product:
protected def prod (f : filter α) (g : filter β) : filter (α × β) :=
f.vmap prod.fst ⊓ g.vmap prod.snd
lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β}
(hs : s ∈ f.sets) (ht : t ∈ g.sets) : set.prod s t ∈ (filter.prod f g).sets :=
inter_mem_inf_sets (preimage_mem_vmap hs) (preimage_mem_vmap ht)
lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} :
s ∈ (filter.prod f g).sets ↔ (∃t₁∈f.sets, ∃t₂∈g.sets, set.prod t₁ t₂ ⊆ s) :=
by simp [filter.prod, mem_inf_sets, mem_vmap];
exact ⟨assume ⟨t₁', ⟨t₁, ht₁, h₁⟩, t₂', hst, ⟨t₂, ht₂, h₂⟩⟩,
⟨t₁, ht₁, t₂, ht₂, subset.trans (inter_subset_inter h₁ h₂) hst⟩,
assume ⟨t₁, ht₁, t₂, ht₂, h⟩,
⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, h, t₂, ht₂, subset.refl _⟩⟩
#exit
-/
section prod
protected def prod (f : filter α) (g : filter β) : filter (α × β) :=
f.lift $ λs, g.lift' $ λt, set.prod s t
lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β}
(hs : s ∈ f.sets) (ht : t ∈ g.sets) : set.prod s t ∈ (filter.prod f g).sets :=
le_principal_iff.mp $ show filter.prod f g ≤ principal (set.prod s t),
from infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ ht
lemma prod_same_eq {f : filter α} : filter.prod f f = f.lift' (λt, set.prod t t) :=
lift_lift'_same_eq_lift'
(assume s, set.monotone_prod monotone_const monotone_id)
(assume t, set.monotone_prod monotone_id monotone_const)
lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} :
s ∈ (filter.prod f g).sets ↔ (∃t₁∈f.sets, ∃t₂∈g.sets, set.prod t₁ t₂ ⊆ s) :=
begin
delta filter.prod,
rw [mem_lift_iff],
apply exists_congr, intro t₁,
apply exists_congr, intro ht₁,
rw [mem_lift'_iff],
exact set.monotone_prod monotone_const monotone_id,
exact (monotone_lift' monotone_const $ monotone_lam $ assume b, set.monotone_prod monotone_id monotone_const)
end
lemma mem_prod_same_iff {s : set (α×α)} {f : filter α} :
s ∈ (filter.prod f f).sets ↔ (∃t∈f.sets, set.prod t t ⊆ s) :=
by rw [prod_same_eq, mem_lift'_iff]; exact set.monotone_prod monotone_id monotone_id
lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) :
filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ :=
lift_mono hf $ assume s, lift'_mono hg $ le_refl _
lemma prod_comm {f : filter α} {g : filter β} :
filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) :=
eq.symm $ calc map (λp:β×α, (p.2, p.1)) (filter.prod g f) =
(g.lift $ λt, map (λp:β×α, (p.2, p.1)) (f.lift' $ λs, set.prod t s)) :
map_lift_eq $ assume a b h, lift'_mono (le_refl f) (assume t, set.prod_mono h (subset.refl t))
... = (g.lift $ λt, f.lift' $ λs, image (λp:β×α, (p.2, p.1)) (set.prod t s)) :
congr_arg (filter.lift g) $ funext $ assume s, map_lift'_eq $ assume a b h, set.prod_mono (subset.refl s) h
... = (g.lift $ λt, f.lift' $ λs, set.prod s t) : by simp [set.image_swap_prod]
... = filter.prod f g : lift_comm
lemma prod_lift_lift {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) :=
begin
delta filter.prod,
rw [lift_assoc],
apply congr_arg, apply funext, intro x,
rw [lift_comm],
apply congr_arg, apply funext, intro y,
rw [lift'_lift_assoc],
exact hg₂,
exact hg₁
end
lemma prod_lift'_lift' {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) :=
begin
delta filter.prod,
rw [lift_lift'_assoc],
apply congr_arg, apply funext, intro x,
rw [lift'_lift'_assoc],
exact hg₂,
exact set.monotone_prod monotone_const monotone_id,
exact hg₁,
exact (monotone_lift' monotone_const $ monotone_lam $
assume x, set.monotone_prod monotone_id monotone_const)
end
lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f :=
assume s hs, (filter.prod f g).upwards_sets (prod_mem_prod hs univ_mem_sets) $
show set.prod s univ ⊆ preimage prod.fst s, by simp [set.prod, preimage] {contextual := tt}
lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g :=
assume s hs, (filter.prod f g).upwards_sets (prod_mem_prod univ_mem_sets hs) $
show set.prod univ s ⊆ preimage prod.snd s, by simp [set.prod, preimage] {contextual := tt}
lemma tendsto_prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ}
(h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) :=
assume s hs,
let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in
f.upwards_sets (inter_mem_sets (h₁ hs₁) (h₂ hs₂)) $
calc preimage m₁ s₁ ∩ preimage m₂ s₂ ⊆ preimage (λx, (m₁ x, m₂ x)) (set.prod s₁ s₂) : λx ⟨h₁, h₂⟩, ⟨h₁, h₂⟩
... ⊆ preimage (λx, (m₁ x, m₂ x)) s : preimage_mono h
lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} :
filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
le_antisymm
(assume s hs,
let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in
filter.upwards_sets _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $
calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ :
set.prod_image_image_eq
... ⊆ _ : by rwa [image_subset_iff_subset_preimage])
(tendsto_prod_mk (tendsto_compose tendsto_fst (le_refl _)) (tendsto_compose tendsto_snd (le_refl _)))
lemma prod_vmap_vmap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} :
filter.prod (vmap m₁ f₁) (vmap m₂ f₂) = vmap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
have ∀s t, set.prod (preimage m₁ s) (preimage m₂ t) = preimage (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (set.prod s t),
from assume s t, rfl,
begin
rw [vmap_eq_lift', vmap_eq_lift', prod_lift'_lift'],
simp [this, filter.prod],
rw [vmap_lift_eq], tactic.swap, exact (monotone_lift' monotone_const $
monotone_lam $ assume t, set.monotone_prod monotone_id monotone_const),
apply congr_arg, apply funext, intro t',
dsimp [function.comp],
rw [vmap_lift'_eq],
exact set.monotone_prod monotone_const monotone_id,
exact monotone_preimage,
exact monotone_preimage
end
lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} :
filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
begin
revert s hs t ht,
simp,
exact assume s ⟨s₁, hs₁, s₂, hs₂, hs⟩ t ⟨t₁, ht₁, t₂, ht₂, ht⟩,
⟨set.prod s₁ t₁, prod_mem_prod hs₁ ht₁, set.prod s₂ t₂, prod_mem_prod hs₂ ht₂,
by rw [set.prod_inter_prod]; exact set.prod_mono hs ht⟩
end)
(le_inf (prod_mono inf_le_left inf_le_left) (prod_mono inf_le_right inf_le_right))
lemma prod_neq_bot {f : filter α} {g : filter β} :
filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) :=
calc filter.prod f g ≠ ⊥ ↔ (∀s∈f.sets, g.lift' (set.prod s) ≠ ⊥) :
begin
delta filter.prod,
rw [lift_neq_bot_iff],
exact (monotone_lift' monotone_const $ monotone_lam $ assume s, set.monotone_prod monotone_id monotone_const)
end
... ↔ (∀s∈f.sets, ∀t∈g.sets, s ≠ ∅ ∧ t ≠ ∅) :
begin
apply forall_congr, intro s,
apply forall_congr, intro hs,
rw [lift'_neq_bot_iff],
apply forall_congr, intro t,
apply forall_congr, intro ht,
rw [set.prod_neq_empty_iff],
exact set.monotone_prod monotone_const monotone_id
end
... ↔ (∀s∈f.sets, s ≠ ∅) ∧ (∀t∈g.sets, t ≠ ∅) :
⟨assume h, ⟨assume s hs, (h s hs univ univ_mem_sets).left,
assume t ht, (h univ univ_mem_sets t ht).right⟩,
assume ⟨h₁, h₂⟩ s hs t ht, ⟨h₁ s hs, h₂ t ht⟩⟩
... ↔ _ : by simp [forall_sets_neq_empty_iff_neq_bot]
lemma prod_principal_principal {s : set α} {t : set β} :
filter.prod (principal s) (principal t) = principal (set.prod s t) :=
begin
delta filter.prod,
rw [lift_principal, lift'_principal],
exact set.monotone_prod monotone_const monotone_id,
exact (monotone_lift' monotone_const $ monotone_lam $
assume s, set.monotone_prod monotone_id monotone_const)
end
end prod
lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ (f i).sets → s ∈ (⨅i, f i).sets :=
show (⨅i, f i) ≤ f i, from infi_le _ _
@[simp] lemma mem_top_sets_iff {s : set α} : s ∈ (⊤ : filter α).sets ↔ s = univ :=
⟨assume h, top_unique $ h, assume h, h.symm ▸ univ_mem_sets⟩
@[elab_as_eliminator]
lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ (infi f).sets) {p : set α → Prop}
(uni : p univ)
(ins : ∀{i s₁ s₂}, s₁ ∈ (f i).sets → p s₂ → p (s₁ ∩ s₂))
(upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s :=
begin
have hs' : s ∈ (complete_lattice.Inf {a : filter α | ∃ (i : ι), a = f i}).sets := hs,
rw [Inf_sets_eq_finite] at hs',
simp at hs',
cases hs' with is hs, cases hs with fin_is hs, cases hs with hs his,
induction fin_is generalizing s,
case finite.empty hs' s hs' hs {
simp at hs, subst hs, assumption },
case finite.insert fi is fi_ne_is fin_is ih fi_sub s hs' hs {
simp at hs,
cases hs with s₁ hs, cases hs with hs₁ hs, cases hs with s₂ hs, cases hs with hs hs₂,
have hi : ∃i, fi = f i := fi_sub (mem_insert _ _),
cases hi with i hi,
exact have hs₁ : s₁ ∈ (f i).sets, from hi ▸ hs₁,
have hs₂ : p s₂, from
have his : is ⊆ {x | ∃i, x = f i}, from assume i hi, fi_sub $ mem_insert_of_mem _ hi,
have infi f ≤ Inf is, from Inf_le_Inf his,
ih his (this hs₂) hs₂,
show p s, from upw hs $ ins hs₁ hs₂ }
end
lemma lift_infi {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
have g_mono : monotone g,
from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h,
have ∀t∈(infi f).sets, (⨅ (i : ι), filter.lift (f i) g) ≤ g t,
from assume t ht, infi_sets_induct ht
(let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets)
(assume i s₁ s₂ hs₁ hs₂,
@hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂)
(assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁),
by rw [lift_sets_eq g_mono]; simp; exact assume ⟨t, hs, ht⟩, this t ht hs)
lemma lift_infi' {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hf : directed (≤) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
begin
rw [lift_sets_eq hg],
simp [infi_sets_eq hf hι],
exact assume ⟨t, hs, i, ht⟩, mem_infi_sets i $ mem_lift ht hs
end)
lemma lift'_infi {f : ι → filter α} {g : set α → set β}
(hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) :=
lift_infi hι $ by simp; apply assume s t, hg
lemma map_eq_vmap_of_inverse {f : filter α} {m : α → β} {n : β → α}
(h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = vmap n f :=
le_antisymm
(assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.upwards_sets ha $
calc a = preimage (n ∘ m) a : by simp [h₂, preimage_id]
... ⊆ preimage m b : preimage_mono h)
(assume b (hb : preimage m b ∈ f.sets),
⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp [h₁]; apply subset.refl⟩)
lemma map_swap_vmap_swap_eq {f : filter (α × β)} : prod.swap <$> f = vmap prod.swap f :=
map_eq_vmap_of_inverse prod.swap_swap_eq prod.swap_swap_eq
/- ultrafilter -/
section ultrafilter
open classical zorn
local attribute [instance] prop_decidable
variables {f g : filter α}
def ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g
lemma ultrafilter_pure {a : α} : ultrafilter (pure a) :=
⟨return_neq_bot,
assume g hg ha,
have {a} ∈ g.sets, by simp at ha; assumption,
show ∀s∈g.sets, {a} ⊆ s, from classical.by_contradiction $
begin
simp [classical.not_forall_iff, not_implies_iff],
exact assume ⟨s, hna, hs⟩,
have {a} ∩ s ∈ g.sets, from inter_mem_sets ‹{a} ∈ g.sets› hs,
have ∅ ∈ g.sets, from g.upwards_sets this $
assume x ⟨hxa, hxs⟩, begin simp at hxa; simp [hxa] at hxs, exact hna hxs end,
have g = ⊥, from empty_in_sets_eq_bot.mp this,
hg this
end⟩
lemma ultrafilter_unique (hg : ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g :=
le_antisymm h (hg.right _ hf h)
lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ ultrafilter u :=
let
τ := {f' // f' ≠ ⊥ ∧ f' ≤ f},
r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val,
⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets,
top : τ := ⟨f, h, le_refl f⟩,
sup : Π(c:set τ), chain c → τ :=
λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val,
infi_neq_bot_of_directed ⟨a⟩
(directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb)
(assume ⟨⟨a, ha, _⟩, _⟩, ha),
infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩
in
have ∀c (hc: chain c) a (ha : a ∈ c), r a (sup c hc),
from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _),
have (∃ (u : τ), ∀ (a : τ), r u a → r a u),
from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁),
let ⟨uτ, hmin⟩ := this in
⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂,
hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩
lemma le_of_ultrafilter {g : filter α} (hf : ultrafilter f) (h : f ⊓ g ≠ ⊥) :
f ≤ g :=
le_of_inf_eq $ ultrafilter_unique hf h inf_le_left
lemma mem_or_compl_mem_of_ultrafilter (hf : ultrafilter f) (s : set α) :
s ∈ f.sets ∨ - s ∈ f.sets :=
or_of_not_implies' $ assume : - s ∉ f.sets,
have f ≤ principal s,
from le_of_ultrafilter hf $ assume h, this $ mem_sets_of_neq_bot $ by simp [*],
by simp at this; assumption
lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : ultrafilter f) (h : s ∪ t ∈ f.sets) :
s ∈ f.sets ∨ t ∈ f.sets :=
(mem_or_compl_mem_of_ultrafilter hf s).imp_right
(assume : -s ∈ f.sets, f.upwards_sets (inter_mem_sets this h) $
assume x ⟨hnx, hx⟩, hx.resolve_left hnx)
lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : ultrafilter f) (hs : finite s)
: ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets :=
begin
induction hs,
case finite.empty { simp [empty_in_sets_eq_bot, hf.left] },
case finite.insert t s' ht' hs' ih {
simp,
exact assume h, (mem_or_mem_of_ultrafilter hf h).elim
(assume : t ∈ f.sets, ⟨t, this, or.inl rfl⟩)
(assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, ht, or.inr hts'⟩) }
end
lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α}
(hf : ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f.sets) : ∃i∈is, s i ∈ f.sets :=
have his : finite (image s is), from finite_image his,
have h : (⋃₀ image s is) ∈ f.sets, from by simp [sUnion_image]; assumption,
let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f.sets)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in
⟨i, hi, h_eq.symm ▸ ht⟩
lemma ultrafilter_of_split {f : filter α} (hf : f ≠ ⊥) (h : ∀s, s ∈ f.sets ∨ - s ∈ f.sets) :
ultrafilter f :=
⟨hf, assume g hg g_le s hs, (h s).elim id $
assume : - s ∈ f.sets,
have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this),
by simp [empty_in_sets_eq_bot, hg] at this; contradiction⟩
lemma ultrafilter_map {f : filter α} {m : α → β} (h : ultrafilter f) : ultrafilter (map m f) :=
ultrafilter_of_split (by simp [map_eq_bot_iff, h.left]) $
assume s, show preimage m s ∈ f.sets ∨ - preimage m s ∈ f.sets,
from mem_or_compl_mem_of_ultrafilter h (preimage m s)
noncomputable def ultrafilter_of (f : filter α) : filter α :=
if h : f = ⊥ then ⊥ else epsilon (λu, u ≤ f ∧ ultrafilter u)
lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ ultrafilter (ultrafilter_of f) :=
begin
have h' := epsilon_spec (exists_ultrafilter h),
simp [ultrafilter_of, dif_neg, h],
simp at h',
assumption
end
lemma ultrafilter_of_le : ultrafilter_of f ≤ f :=
if h : f = ⊥ then by simp [ultrafilter_of, dif_pos, h]; exact le_refl _
else (ultrafilter_of_spec h).left
lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : ultrafilter (ultrafilter_of f) :=
(ultrafilter_of_spec h).right
lemma ultrafilter_of_ultrafilter (h : ultrafilter f) : ultrafilter_of f = f :=
ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le
end ultrafilter
end filter
|
e0645ab881c4f32e9f6fbcad3cd2b8d7cc240fba | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/algebra/field_power.lean | d16d553ac4980cf9328b2b924f16c016c4fa41c7 | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 6,214 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
Integer power operation on fields.
-/
import algebra.group_power tactic.wlog
universe u
section field_power
open int nat
variables {α : Type u} [division_ring α]
@[simp] lemma zero_gpow : ∀ z : ℕ, z ≠ 0 → (0 : α)^z = 0
| 0 h := absurd rfl h
| (k+1) h := zero_mul _
def fpow (a : α) : ℤ → α
| (of_nat n) := a ^ n
| -[1+n] := 1/(a ^ (n+1))
instance : has_pow α ℤ := ⟨fpow⟩
@[simp] lemma fpow_of_nat (a : α) (n : ℕ) : a ^ (n : ℤ) = a ^ n := rfl
lemma fpow_neg_succ_of_nat (a : α) (n : ℕ) : a ^ (-[1+ n]) = 1 / (a ^ (n + 1)) := rfl
lemma unit_pow {a : α} (ha : a ≠ 0) : ∀ n : ℕ, a ^ n = ↑((units.mk0 a ha)^n)
| 0 := units.coe_one.symm
| (k+1) := by simp only [_root_.pow_succ, units.coe_mul, units.mk0_val]; rw unit_pow
lemma fpow_eq_gpow {a : α} (h : a ≠ 0) : ∀ (z : ℤ), a ^ z = ↑(gpow (units.mk0 a h) z)
| (of_nat k) := unit_pow _ _
| -[1+k] := by rw [fpow_neg_succ_of_nat, gpow, one_div_eq_inv, units.inv_eq_inv, unit_pow]
lemma fpow_inv (a : α) : a ^ (-1 : ℤ) = a⁻¹ :=
show 1*(a*1)⁻¹ = a⁻¹, by rw [one_mul, mul_one]
lemma fpow_ne_zero_of_ne_zero {a : α} (ha : a ≠ 0) : ∀ (z : ℤ), a ^ z ≠ 0
| (of_nat n) := pow_ne_zero _ ha
| -[1+n] := one_div_ne_zero $ pow_ne_zero _ ha
@[simp] lemma fpow_zero {a : α} : a ^ (0 : ℤ) = 1 :=
pow_zero a
lemma fpow_add {a : α} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 + z2) = a ^ z1 * a ^ z2 :=
begin simp only [fpow_eq_gpow ha], rw ← units.coe_mul, congr, apply gpow_add end
@[simp] lemma one_fpow : ∀(i : ℤ), (1 : α) ^ i = 1
| (int.of_nat n) := _root_.one_pow n
| -[1+n] := show 1/(1 ^ (n+1) : α) = 1, by simp
@[simp] lemma fpow_one (a : α) : a^(1:ℤ) = a :=
pow_one a
end field_power
namespace is_field_hom
lemma map_fpow {α β : Type*} [discrete_field α] [discrete_field β] (f : α → β) [is_field_hom f]
(a : α) : ∀ (n : ℤ), f (a ^ n) = f a ^ n
| (n : ℕ) := is_semiring_hom.map_pow f a n
| -[1+ n] := by simp [fpow_neg_succ_of_nat, is_semiring_hom.map_pow f, is_field_hom.map_inv f]
end is_field_hom
section discrete_field_power
open int
variables {α : Type u} [discrete_field α]
lemma zero_fpow : ∀ z : ℤ, z ≠ 0 → (0 : α) ^ z = 0
| (of_nat n) h := zero_gpow _ $ by rintro rfl; exact h rfl
| -[1+n] h := show 1/(0*0^n)=(0:α), by rw [zero_mul, one_div_zero]
lemma fpow_neg (a : α) : ∀ n : ℤ, a ^ (-n) = 1 / a ^ n
| (0) := by simp
| (of_nat (n+1)) := rfl
| -[1+n] := show fpow a (n+1) = 1 / (1 / fpow a (n+1)), by rw one_div_one_div
lemma fpow_sub {a : α} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 :=
by rw [sub_eq_add_neg, fpow_add ha, fpow_neg, ←div_eq_mul_one_div]
lemma fpow_mul (a : α) (i j : ℤ) : a ^ (i * j) = (a ^ i) ^ j :=
begin
by_cases a = 0,
{ subst h,
have : ¬ i = 0 → ¬ j = 0 → ¬ i * j = 0, begin rw [mul_eq_zero, not_or_distrib], exact and.intro end,
by_cases hi : i = 0; by_cases hj : j = 0;
simp [hi, hj, zero_fpow i, zero_fpow j, zero_fpow _ (this _ _), one_fpow] },
rw [fpow_eq_gpow h, fpow_eq_gpow h, fpow_eq_gpow (units.ne_zero _), units.mk0_coe],
fapply congr_arg coe _, -- TODO: uh oh
exact gpow_mul (units.mk0 a h) i j
end
lemma mul_fpow (a b : α) : ∀(i : ℤ), (a * b) ^ i = (a ^ i) * (b ^ i)
| (int.of_nat n) := _root_.mul_pow a b n
| -[1+n] :=
by rw [fpow_neg_succ_of_nat, fpow_neg_succ_of_nat, fpow_neg_succ_of_nat,
mul_pow, div_mul_div, one_mul]
end discrete_field_power
section ordered_field_power
open int
variables {α : Type u} [discrete_linear_ordered_field α]
lemma fpow_nonneg_of_nonneg {a : α} (ha : a ≥ 0) : ∀ (z : ℤ), a ^ z ≥ 0
| (of_nat n) := pow_nonneg ha _
| -[1+n] := div_nonneg' zero_le_one $ pow_nonneg ha _
lemma fpow_pos_of_pos {a : α} (ha : a > 0) : ∀ (z : ℤ), a ^ z > 0
| (of_nat n) := pow_pos ha _
| -[1+n] := div_pos zero_lt_one $ pow_pos ha _
lemma fpow_le_of_le {x : α} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b :=
begin
induction a with a a; induction b with b b,
{ simp only [fpow_of_nat, of_nat_eq_coe],
apply pow_le_pow hx,
apply le_of_coe_nat_le_coe_nat h },
{ apply absurd h,
apply not_le_of_gt,
exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) },
{ simp only [fpow_neg_succ_of_nat, one_div_eq_inv],
apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx },
{ simp only [fpow_neg_succ_of_nat],
apply (one_div_le_one_div _ _).2,
{ apply pow_le_pow hx,
have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h,
have h' := le_of_neg_le_neg this,
apply le_of_coe_nat_le_coe_nat h' },
repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } }
end
lemma pow_le_max_of_min_le {x : α} (hx : x ≥ 1) {a b c : ℤ} (h : min a b ≤ c) :
x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) :=
begin
wlog hle : a ≤ b,
have hnle : -b ≤ -a, from neg_le_neg hle,
have hfle : x ^ (-b) ≤ x ^ (-a), from fpow_le_of_le hx hnle,
have : x ^ (-c) ≤ x ^ (-a),
{ apply fpow_le_of_le hx,
simpa only [min_eq_left hle, neg_le_neg_iff] using h },
simpa only [max_eq_left hfle]
end
lemma fpow_le_one_of_nonpos {p : α} (hp : p ≥ 1) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 :=
calc p ^ z ≤ p ^ 0 : fpow_le_of_le hp hz
... = 1 : by simp
lemma fpow_ge_one_of_nonneg {p : α} (hp : p ≥ 1) {z : ℤ} (hz : z ≥ 0) : p ^ z ≥ 1 :=
calc p ^ z ≥ p ^ 0 : fpow_le_of_le hp hz
... = 1 : by simp
end ordered_field_power
lemma one_lt_pow {α} [linear_ordered_semiring α] {p : α} (hp : p > 1) : ∀ {n : ℕ}, 1 ≤ n → 1 < p ^ n
| 1 h := by simp; assumption
| (k+2) h :=
begin
rw ←one_mul (1 : α),
apply mul_lt_mul,
{ assumption },
{ apply le_of_lt, simpa using one_lt_pow (nat.le_add_left 1 k)},
{ apply zero_lt_one },
{ apply le_of_lt (lt_trans zero_lt_one hp) }
end
lemma one_lt_fpow {α} [discrete_linear_ordered_field α] {p : α} (hp : p > 1) :
∀ z : ℤ, z > 0 → 1 < p ^ z
| (int.of_nat n) h := one_lt_pow hp (nat.succ_le_of_lt (int.lt_of_coe_nat_lt_coe_nat h))
|
1ae0240cd50d95068ad89c53c866a26120f4742a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/options.lean | 719accecc86a0d4932ef5ed8885b2588ef199f23 | [] | 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 | 248 | 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
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.name
namespace Mathlib
|
5914b4a31a51046eaf68ac5e305edf7c8d5b1545 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/data/polynomial/reverse.lean | 302faad60e393846447048b8cc04af29ae216968 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,193 | lean | /-
Copyright (c) 2020 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import data.polynomial.erase_lead
import data.polynomial.eval
/-!
# Reverse of a univariate polynomial
The main definition is `reverse`. Applying `reverse` to a polynomial `f : polynomial R` produces
the polynomial with a reversed list of coefficients, equivalent to `X^f.nat_degree * f(1/X)`.
The main result is that `reverse (f * g) = reverse f * reverse g`, provided the leading
coefficients of `f` and `g` do not multiply to zero.
-/
namespace polynomial
open polynomial finsupp finset
open_locale classical
section semiring
variables {R : Type*} [semiring R] {f : polynomial R}
/-- If `i ≤ N`, then `rev_at_fun N i` returns `N - i`, otherwise it returns `i`.
This is the map used by the embedding `rev_at`.
-/
def rev_at_fun (N i : ℕ) : ℕ := ite (i ≤ N) (N-i) i
lemma rev_at_fun_invol {N i : ℕ} : rev_at_fun N (rev_at_fun N i) = i :=
begin
unfold rev_at_fun,
split_ifs with h j,
{ exact nat.sub_sub_self h, },
{ exfalso,
apply j,
exact nat.sub_le N i, },
{ refl, },
end
lemma rev_at_fun_inj {N : ℕ} : function.injective (rev_at_fun N) :=
begin
intros a b hab,
rw [← @rev_at_fun_invol N a, hab, rev_at_fun_invol],
end
/-- If `i ≤ N`, then `rev_at N i` returns `N - i`, otherwise it returns `i`.
Essentially, this embedding is only used for `i ≤ N`.
The advantage of `rev_at N i` over `N - i` is that `rev_at` is an involution.
-/
def rev_at (N : ℕ) : function.embedding ℕ ℕ :=
{ to_fun := λ i , (ite (i ≤ N) (N-i) i),
inj' := rev_at_fun_inj }
/-- We prefer to use the bundled `rev_at` over unbundled `rev_at_fun`. -/
@[simp] lemma rev_at_fun_eq (N i : ℕ) : rev_at_fun N i = rev_at N i := rfl
@[simp] lemma rev_at_invol {N i : ℕ} : (rev_at N) (rev_at N i) = i :=
rev_at_fun_invol
@[simp] lemma rev_at_le {N i : ℕ} (H : i ≤ N) : rev_at N i = N - i :=
if_pos H
lemma rev_at_add {N O n o : ℕ} (hn : n ≤ N) (ho : o ≤ O) :
rev_at (N + O) (n + o) = rev_at N n + rev_at O o :=
begin
rcases nat.le.dest hn with ⟨n', rfl⟩,
rcases nat.le.dest ho with ⟨o', rfl⟩,
repeat { rw rev_at_le (le_add_right rfl.le) },
rw [add_assoc, add_left_comm n' o, ← add_assoc, rev_at_le (le_add_right rfl.le)],
repeat {rw nat.add_sub_cancel_left},
end
/-- `reflect N f` is the polynomial such that `(reflect N f).coeff i = f.coeff (rev_at N i)`.
In other words, the terms with exponent `[0, ..., N]` now have exponent `[N, ..., 0]`.
In practice, `reflect` is only used when `N` is at least as large as the degree of `f`.
Eventually, it will be used with `N` exactly equal to the degree of `f`. -/
noncomputable def reflect (N : ℕ) : polynomial R → polynomial R
| ⟨f⟩ := ⟨finsupp.emb_domain (rev_at N) f⟩
lemma reflect_support (N : ℕ) (f : polynomial R) :
(reflect N f).support = image (rev_at N) f.support :=
begin
rcases f,
ext1,
rw [reflect, mem_image, support, support, support_emb_domain, mem_map],
end
@[simp] lemma coeff_reflect (N : ℕ) (f : polynomial R) (i : ℕ) :
coeff (reflect N f) i = f.coeff (rev_at N i) :=
begin
rcases f,
simp only [reflect, coeff],
calc finsupp.emb_domain (rev_at N) f i
= finsupp.emb_domain (rev_at N) f (rev_at N (rev_at N i)) : by rw rev_at_invol
... = f (rev_at N i) : finsupp.emb_domain_apply _ _ _
end
@[simp] lemma reflect_zero {N : ℕ} : reflect N (0 : polynomial R) = 0 := rfl
@[simp] lemma reflect_eq_zero_iff {N : ℕ} {f : polynomial R} :
reflect N (f : polynomial R) = 0 ↔ f = 0 :=
by { rcases f, simp [reflect, ← zero_to_finsupp] }
@[simp] lemma reflect_add (f g : polynomial R) (N : ℕ) :
reflect N (f + g) = reflect N f + reflect N g :=
by { ext, simp only [coeff_add, coeff_reflect], }
@[simp] lemma reflect_C_mul (f : polynomial R) (r : R) (N : ℕ) :
reflect N (C r * f) = C r * (reflect N f) :=
by { ext, simp only [coeff_reflect, coeff_C_mul], }
@[simp] lemma reflect_C_mul_X_pow (N n : ℕ) {c : R} :
reflect N (C c * X ^ n) = C c * X ^ (rev_at N n) :=
begin
ext,
rw [reflect_C_mul, coeff_C_mul, coeff_C_mul, coeff_X_pow, coeff_reflect],
split_ifs with h j,
{ rw [h, rev_at_invol, coeff_X_pow_self], },
{ rw [not_mem_support_iff.mp],
intro a,
rw [← one_mul (X ^ n), ← C_1] at a,
apply h,
rw [← (mem_support_C_mul_X_pow a), rev_at_invol], },
end
@[simp] lemma reflect_monomial (N n : ℕ) : reflect N ((X : polynomial R) ^ n) = X ^ (rev_at N n) :=
by rw [← one_mul (X ^ n), ← one_mul (X ^ (rev_at N n)), ← C_1, reflect_C_mul_X_pow]
lemma reflect_mul_induction (cf cg : ℕ) :
∀ N O : ℕ, ∀ f g : polynomial R,
f.support.card ≤ cf.succ → g.support.card ≤ cg.succ → f.nat_degree ≤ N → g.nat_degree ≤ O →
(reflect (N + O) (f * g)) = (reflect N f) * (reflect O g) :=
begin
induction cf with cf hcf,
--first induction (left): base case
{ induction cg with cg hcg,
-- second induction (right): base case
{ intros N O f g Cf Cg Nf Og,
rw [← C_mul_X_pow_eq_self Cf, ← C_mul_X_pow_eq_self Cg],
simp only [mul_assoc, X_pow_mul, ← pow_add X, reflect_C_mul, reflect_monomial,
add_comm, rev_at_add Nf Og] },
-- second induction (right): induction step
{ intros N O f g Cf Cg Nf Og,
by_cases g0 : g = 0,
{ rw [g0, reflect_zero, mul_zero, mul_zero, reflect_zero], },
rw [← erase_lead_add_C_mul_X_pow g, mul_add, reflect_add, reflect_add, mul_add, hcg, hcg];
try { assumption },
{ exact le_add_left card_support_C_mul_X_pow_le_one },
{ exact (le_trans (nat_degree_C_mul_X_pow_le g.leading_coeff g.nat_degree) Og) },
{ exact nat.lt_succ_iff.mp (gt_of_ge_of_gt Cg (erase_lead_support_card_lt g0)) },
{ exact le_trans erase_lead_nat_degree_le Og } } },
--first induction (left): induction step
{ intros N O f g Cf Cg Nf Og,
by_cases f0 : f = 0,
{ rw [f0, reflect_zero, zero_mul, zero_mul, reflect_zero], },
rw [← erase_lead_add_C_mul_X_pow f, add_mul, reflect_add, reflect_add, add_mul, hcf, hcf];
try { assumption },
{ exact le_add_left card_support_C_mul_X_pow_le_one },
{ exact (le_trans (nat_degree_C_mul_X_pow_le f.leading_coeff f.nat_degree) Nf) },
{ exact nat.lt_succ_iff.mp (gt_of_ge_of_gt Cf (erase_lead_support_card_lt f0)) },
{ exact (le_trans erase_lead_nat_degree_le Nf) } },
end
@[simp] theorem reflect_mul
(f g : polynomial R) {F G : ℕ} (Ff : f.nat_degree ≤ F) (Gg : g.nat_degree ≤ G) :
reflect (F + G) (f * g) = reflect F f * reflect G g :=
reflect_mul_induction _ _ F G f g f.support.card.le_succ g.support.card.le_succ Ff Gg
/-- The reverse of a polynomial f is the polynomial obtained by "reading f backwards".
Even though this is not the actual definition, reverse f = f (1/X) * X ^ f.nat_degree. -/
noncomputable def reverse (f : polynomial R) : polynomial R := reflect f.nat_degree f
lemma coeff_reverse (f : polynomial R) (n : ℕ) :
f.reverse.coeff n = f.coeff (rev_at f.nat_degree n) :=
by rw [reverse, coeff_reflect]
@[simp] lemma coeff_zero_reverse (f : polynomial R) : coeff (reverse f) 0 = leading_coeff f :=
by rw [coeff_reverse, rev_at_le (zero_le f.nat_degree), nat.sub_zero, leading_coeff]
@[simp] lemma reverse_zero : reverse (0 : polynomial R) = 0 := rfl
@[simp] lemma reverse_eq_zero : f.reverse = 0 ↔ f = 0 :=
by simp [reverse]
lemma reverse_nat_degree_le (f : polynomial R) : f.reverse.nat_degree ≤ f.nat_degree :=
begin
rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero],
intros n hn,
rw with_bot.coe_lt_coe at hn,
rw [coeff_reverse, rev_at, function.embedding.coe_fn_mk,
if_neg (not_le_of_gt hn), coeff_eq_zero_of_nat_degree_lt hn],
end
lemma nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree (f : polynomial R) :
f.nat_degree = f.reverse.nat_degree + f.nat_trailing_degree :=
begin
by_cases hf : f = 0,
{ rw [hf, reverse_zero, nat_degree_zero, nat_trailing_degree_zero] },
apply le_antisymm,
{ apply nat.le_add_of_sub_le_right,
apply le_nat_degree_of_ne_zero,
rw [reverse, coeff_reflect, ←rev_at_le f.nat_trailing_degree_le_nat_degree, rev_at_invol],
exact trailing_coeff_nonzero_iff_nonzero.mpr hf },
{ rw ← nat.le_sub_left_iff_add_le f.reverse_nat_degree_le,
apply nat_trailing_degree_le_of_ne_zero,
have key := mt leading_coeff_eq_zero.mp (mt reverse_eq_zero.mp hf),
rwa [leading_coeff, coeff_reverse, rev_at_le f.reverse_nat_degree_le] at key },
end
lemma reverse_nat_degree (f : polynomial R) :
f.reverse.nat_degree = f.nat_degree - f.nat_trailing_degree :=
by rw [f.nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree, nat.add_sub_cancel]
lemma reverse_leading_coeff (f : polynomial R) : f.reverse.leading_coeff = f.trailing_coeff :=
by rw [leading_coeff, reverse_nat_degree, ←rev_at_le f.nat_trailing_degree_le_nat_degree,
coeff_reverse, rev_at_invol, trailing_coeff]
lemma reverse_nat_trailing_degree (f : polynomial R) : f.reverse.nat_trailing_degree = 0 :=
begin
by_cases hf : f = 0,
{ rw [hf, reverse_zero, nat_trailing_degree_zero] },
{ rw ← nat.le_zero_iff,
apply nat_trailing_degree_le_of_ne_zero,
rw [coeff_zero_reverse],
exact mt leading_coeff_eq_zero.mp hf },
end
lemma reverse_trailing_coeff (f : polynomial R) : f.reverse.trailing_coeff = f.leading_coeff :=
by rw [trailing_coeff, reverse_nat_trailing_degree, coeff_zero_reverse]
theorem reverse_mul {f g : polynomial R} (fg : f.leading_coeff * g.leading_coeff ≠ 0) :
reverse (f * g) = reverse f * reverse g :=
begin
unfold reverse,
rw [nat_degree_mul' fg, reflect_mul f g rfl.le rfl.le],
end
@[simp] lemma reverse_mul_of_domain {R : Type*} [domain R] (f g : polynomial R) :
reverse (f * g) = reverse f * reverse g :=
begin
by_cases f0 : f=0,
{ simp only [f0, zero_mul, reverse_zero], },
by_cases g0 : g=0,
{ rw [g0, mul_zero, reverse_zero, mul_zero], },
simp [reverse_mul, *],
end
lemma trailing_coeff_mul {R : Type*} [integral_domain R] (p q : polynomial R) :
(p * q).trailing_coeff = p.trailing_coeff * q.trailing_coeff :=
by rw [←reverse_leading_coeff, reverse_mul_of_domain, leading_coeff_mul,
reverse_leading_coeff, reverse_leading_coeff]
@[simp] lemma coeff_one_reverse (f : polynomial R) : coeff (reverse f) 1 = next_coeff f :=
begin
rw [coeff_reverse, next_coeff],
split_ifs with hf,
{ have : coeff f 1 = 0 := coeff_eq_zero_of_nat_degree_lt (by simp only [hf, zero_lt_one]),
simp [*, rev_at] },
{ rw rev_at_le,
exact nat.succ_le_iff.2 (pos_iff_ne_zero.2 hf) }
end
end semiring
section ring
variables {R : Type*} [ring R]
@[simp] lemma reflect_neg (f : polynomial R) (N : ℕ) :
reflect N (- f) = - reflect N f :=
by rw [neg_eq_neg_one_mul, ←C_1, ←C_neg, reflect_C_mul, C_neg, C_1, ←neg_eq_neg_one_mul]
@[simp] lemma reflect_sub (f g : polynomial R) (N : ℕ) :
reflect N (f - g) = reflect N f - reflect N g :=
by rw [sub_eq_add_neg, sub_eq_add_neg, reflect_add, reflect_neg]
@[simp] lemma reverse_neg (f : polynomial R) :
reverse (- f) = - reverse f :=
by rw [reverse, reverse, reflect_neg, nat_degree_neg]
end ring
end polynomial
|
4d8c48be593a3edd9378fe285ae2ca3baf2a0a4c | a4673261e60b025e2c8c825dfa4ab9108246c32e | /src/Lean/Meta/WHNF.lean | 2c4e4127774c11fde2691d8a32967e264c65f2c4 | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,837 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.ToExpr
import Lean.AuxRecursor
import Lean.Meta.Basic
import Lean.Meta.LevelDefEq
import Lean.Meta.Match.MatcherInfo
namespace Lean.Meta
/- ===========================
Smart unfolding support
=========================== -/
def smartUnfoldingSuffix := "_sunfold"
@[inline] def mkSmartUnfoldingNameFor (n : Name) : Name :=
Name.mkStr n smartUnfoldingSuffix
def smartUnfoldingDefault := true
builtin_initialize
registerOption `smartUnfolding { defValue := smartUnfoldingDefault, group := "", descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion" }
private def useSmartUnfolding (opts : Options) : Bool :=
opts.getBool `smartUnfolding smartUnfoldingDefault
/- ===========================
Helper methods
=========================== -/
variables {m : Type → Type} [MonadLiftT MetaM m]
private def isAuxDefImp? (constName : Name) : MetaM Bool := do
let env ← getEnv
pure (isAuxRecursor env constName || isNoConfusion env constName)
@[inline] def isAuxDef? (constName : Name) : m Bool :=
liftMetaM $ isAuxDefImp? constName
@[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α :=
match e with
| Expr.const name lvls _ => do
let (some cinfo) ← getConst? name | failK ()
k cinfo lvls
| _ => failK ()
/- ===========================
Helper functions for reducing recursors
=========================== -/
private def getFirstCtor (d : Name) : MetaM (Option Name) := do
let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none
pure (some ctor)
private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) :=
match type.getAppFn with
| Expr.const d lvls _ => do
let (some ctor) ← getFirstCtor d | pure none
pure $ mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams)
| _ => pure none
def toCtorIfLit : Expr → Expr
| Expr.lit (Literal.natVal v) _ =>
if v == 0 then mkConst `Nat.zero
else mkApp (mkConst `Nat.succ) (mkNatLit (v-1))
| Expr.lit (Literal.strVal v) _ =>
mkApp (mkConst `String.mk) (toExpr v.toList)
| e => e
private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule :=
match major.getAppFn with
| Expr.const fn _ _ => recVal.rules.find? $ fun r => r.ctor == fn
| _ => none
private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM (Option Expr) := do
let majorType ← inferType major
let majorType ← whnf majorType
let majorTypeI := majorType.getAppFn
if !majorTypeI.isConstOf recVal.getInduct then
pure none
else if majorType.hasExprMVar && majorType.getAppArgs[recVal.nparams:].any Expr.hasExprMVar then
pure none
else do
let (some newCtorApp) ← mkNullaryCtor majorType recVal.nparams | pure none
let newType ← inferType newCtorApp
if (← isDefEq majorType newType) then
pure newCtorApp
else
pure none
/-- Auxiliary function for reducing recursor applications. -/
private def reduceRec {α} (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α :=
let majorIdx := recVal.getMajorIdx
if h : majorIdx < recArgs.size then do
let major := recArgs.get ⟨majorIdx, h⟩
let mut major ← whnf major
if recVal.k then
let newMajor ← toCtorWhenK recVal major
major := newMajor.getD major
let major := toCtorIfLit major
match getRecRuleFor recVal major with
| some rule =>
let majorArgs := major.getAppArgs
if recLvls.length != recVal.lparams.length then
failK ()
else
let rhs := rule.rhs.instantiateLevelParams recVal.lparams recLvls
-- Apply parameters, motives and minor premises from recursor application.
let rhs := mkAppRange rhs 0 (recVal.nparams+recVal.nmotives+recVal.nminors) recArgs
/- The number of parameters in the constructor is not necessarily
equal to the number of parameters in the recursor when we have
nested inductive types. -/
let nparams := majorArgs.size - rule.nfields
let rhs := mkAppRange rhs nparams majorArgs.size majorArgs
let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs
successK rhs
| none => failK ()
else
failK ()
/- ===========================
Helper functions for reducing Quot.lift and Quot.ind
=========================== -/
/-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/
private def reduceQuotRec {α} (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α :=
let process (majorPos argPos : Nat) : MetaM α :=
if h : majorPos < recArgs.size then do
let major := recArgs.get ⟨majorPos, h⟩
let major ← whnf major
match major with
| Expr.app (Expr.app (Expr.app (Expr.const majorFn _ _) _ _) _ _) majorArg _ => do
let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK ()
let f := recArgs[argPos]
let r := mkApp f majorArg
let recArity := majorPos + 1
successK $ mkAppRange r recArity recArgs.size recArgs
| _ => failK ()
else
failK ()
match recVal.kind with
| QuotKind.lift => process 5 3
| QuotKind.ind => process 4 3
| _ => failK ()
/- ===========================
Helper function for extracting "stuck term"
=========================== -/
mutual
private partial def isRecStuck? (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) :=
if recVal.k then
-- TODO: improve this case
pure none
else do
let majorIdx := recVal.getMajorIdx
if h : majorIdx < recArgs.size then do
let major := recArgs.get ⟨majorIdx, h⟩
let major ← whnf major
getStuckMVarImp? major
else
pure none
private partial def isQuotRecStuck? (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) :=
let process? (majorPos : Nat) : MetaM (Option MVarId) :=
if h : majorPos < recArgs.size then do
let major := recArgs.get ⟨majorPos, h⟩
let major ← whnf major
getStuckMVarImp? major
else
pure none
match recVal.kind with
| QuotKind.lift => process? 5
| QuotKind.ind => process? 4
| _ => pure none
/-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/
private partial def getStuckMVarImp? : Expr → MetaM (Option MVarId)
| Expr.mdata _ e _ => getStuckMVarImp? e
| Expr.proj _ _ e _ => do getStuckMVarImp? (← whnf e)
| e@(Expr.mvar mvarId _) => pure (some mvarId)
| e@(Expr.app f _ _) =>
let f := f.getAppFn
match f with
| Expr.mvar mvarId _ => pure (some mvarId)
| Expr.const fName fLvls _ => do
let cinfo? ← getConstNoEx? fName
match cinfo? with
| some $ ConstantInfo.recInfo recVal => isRecStuck? recVal fLvls e.getAppArgs
| some $ ConstantInfo.quotInfo recVal => isQuotRecStuck? recVal fLvls e.getAppArgs
| _ => pure none
| _ => pure none
| _ => pure none
end
@[inline] def getStuckMVar? (e : Expr) : m (Option MVarId) :=
liftM $ getStuckMVarImp? e
/- ===========================
Weak Head Normal Form auxiliary combinators
=========================== -/
/-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/
@[specialize] private partial def whnfEasyCases : Expr → (Expr → MetaM Expr) → MetaM Expr
| e@(Expr.forallE _ _ _ _), _ => pure e
| e@(Expr.lam _ _ _ _), _ => pure e
| e@(Expr.sort _ _), _ => pure e
| e@(Expr.lit _ _), _ => pure e
| e@(Expr.bvar _ _), _ => unreachable!
| Expr.mdata _ e _, k => whnfEasyCases e k
| e@(Expr.letE _ _ _ _ _), k => k e
| e@(Expr.fvar fvarId _), k => do
let decl ← getLocalDecl fvarId
match decl with
| LocalDecl.cdecl _ _ _ _ _ => pure e
| LocalDecl.ldecl _ _ _ _ v nonDep =>
let cfg ← getConfig
if nonDep && !cfg.zetaNonDep then
pure e
else
when cfg.trackZeta do
modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId }
whnfEasyCases v k
| e@(Expr.mvar mvarId _), k => do
match (← getExprMVarAssignment? mvarId) with
| some v => whnfEasyCases v k
| none => pure e
| e@(Expr.const _ _ _), k => k e
| e@(Expr.app _ _ _), k => k e
| e@(Expr.proj _ _ _ _), k => k e
/-- Return true iff term is of the form `idRhs ...` -/
private def isIdRhsApp (e : Expr) : Bool :=
e.isAppOf `idRhs
/-- (@idRhs T f a_1 ... a_n) ==> (f a_1 ... a_n) -/
private def extractIdRhs (e : Expr) : Expr :=
if !isIdRhsApp e then e
else
let args := e.getAppArgs
if args.size < 2 then e
else mkAppRange args[1] 2 args.size args
@[specialize] private def deltaDefinition {α} (c : ConstantInfo) (lvls : List Level)
(failK : Unit → α) (successK : Expr → α) : α :=
if c.lparams.length != lvls.length then failK ()
else
let val := c.instantiateValueLevelParams lvls
successK (extractIdRhs val)
@[specialize] private def deltaBetaDefinition {α} (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr)
(failK : Unit → α) (successK : Expr → α) : α :=
if c.lparams.length != lvls.length then failK ()
else
let val := c.instantiateValueLevelParams lvls
let val := val.betaRev revArgs
successK (extractIdRhs val)
inductive ReduceMatcherResult :=
| reduced (val : Expr)
| stuck (val : Expr)
| notMatcher
| partialApp
def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do
match e.getAppFn with
| Expr.const declName declLevels _ => do
let some info ← getMatcherInfo? declName | pure ReduceMatcherResult.notMatcher
let args := e.getAppArgs
let prefixSz := info.numParams + 1 + info.numDiscrs
if args.size < prefixSz + info.numAlts then
pure ReduceMatcherResult.partialApp
else
let constInfo ← getConstInfo declName
let f := constInfo.instantiateValueLevelParams declLevels
let auxApp := mkAppN f args[0:prefixSz]
let auxAppType ← inferType auxApp
forallBoundedTelescope auxAppType info.numAlts fun hs _ => do
let auxApp := mkAppN auxApp hs
let auxApp ← whnf auxApp
let auxAppFn := auxApp.getAppFn
let mut i := prefixSz
for h in hs do
if auxAppFn == h then
let result := mkAppN args[i] auxApp.getAppArgs
let result := mkAppN result args[prefixSz + info.numAlts:args.size]
return ReduceMatcherResult.reduced result.headBeta
i := i + 1
return ReduceMatcherResult.stuck auxApp
| _ => pure ReduceMatcherResult.notMatcher
/--
Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction,
expand let-expressions, expand assigned meta-variables. -/
private partial def whnfCoreImp (e : Expr) : MetaM Expr :=
whnfEasyCases e fun e => do
trace[Meta.whnf]! e
match e with
| e@(Expr.const _ _ _) => pure e
| e@(Expr.letE _ _ v b _) => whnfCoreImp $ b.instantiate1 v
| e@(Expr.app f _ _) =>
let f := f.getAppFn
let f' ← whnfCoreImp f
if f'.isLambda then
let revArgs := e.getAppRevArgs
whnfCoreImp $ f'.betaRev revArgs
else match (← reduceMatcher? e) with
| ReduceMatcherResult.reduced eNew => whnfCoreImp eNew
| ReduceMatcherResult.partialApp => pure e
| ReduceMatcherResult.stuck _ => pure e
| ReduceMatcherResult.notMatcher =>
let done : Unit → MetaM Expr := fun _ =>
if f == f' then pure e else pure $ e.updateFn f'
matchConstAux f' done fun cinfo lvls =>
match cinfo with
| ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs done whnfCoreImp
| ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs done whnfCoreImp
| c@(ConstantInfo.defnInfo _) => do
let unfold? ← isAuxDef? c.name
if unfold? then
deltaBetaDefinition c lvls e.getAppRevArgs done whnfCoreImp
else
done ()
| _ => done ()
| e@(Expr.proj _ i c _) =>
let c ← whnf c
matchConstAux c.getAppFn (fun _ => pure e) fun cinfo lvls =>
match cinfo with
| ConstantInfo.ctorInfo ctorVal =>
let argIdx := ctorVal.nparams + i
if argIdx < c.getAppNumArgs then
whnfCoreImp $ c.getArg! argIdx
else
pure e
| _ => pure e
| _ => unreachable!
@[inline] def whnfCore (e : Expr) : m Expr :=
liftMetaM $ whnfCoreImp e
mutual
/-- Reduce `e` until `idRhs` application is exposed or it gets stuck.
This is a helper method for implementing smart unfolding. -/
private partial def whnfUntilIdRhs (e : Expr) : MetaM Expr := do
let e ← whnfCoreImp e
match (← getStuckMVar? e) with
| some mvarId =>
/- Try to "unstuck" by resolving pending TC problems -/
if (← Meta.synthPending mvarId) then
whnfUntilIdRhs e
else
pure e -- failed because metavariable is blocking reduction
| _ =>
if isIdRhsApp e then
pure e -- done
else
match (← unfoldDefinitionImp? e) with
| some e => whnfUntilIdRhs e
| none => pure e -- failed because of symbolic argument
/-- Unfold definition using "smart unfolding" if possible. -/
private partial def unfoldDefinitionImp? (e : Expr) : MetaM (Option Expr) :=
match e with
| Expr.app f _ _ =>
matchConstAux f.getAppFn (fun _ => pure none) fun fInfo fLvls => do
if fInfo.lparams.length != fLvls.length then
pure none
else
let unfoldDefault (_ : Unit) : MetaM (Option Expr) :=
if fInfo.hasValue then
deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e))
else
pure none
if useSmartUnfolding (← getOptions) then
let fAuxInfo? ← getConstNoEx? (mkSmartUnfoldingNameFor fInfo.name)
match fAuxInfo? with
| some $ fAuxInfo@(ConstantInfo.defnInfo _) =>
deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (fun _ => pure none) $ fun e₁ => do
let e₂ ← whnfUntilIdRhs e₁
if isIdRhsApp e₂ then
pure (some (extractIdRhs e₂))
else
pure none
| _ => unfoldDefault ()
else
unfoldDefault ()
| Expr.const name lvls _ => do
let (some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? name | pure none
deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e))
| _ => pure none
end
@[specialize] partial def whnfHeadPredImp (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr :=
whnfEasyCases e fun e => do
let e ← whnfCoreImp e
if (← pred e) then
match (← unfoldDefinitionImp? e) with
| some e => whnfHeadPredImp e pred
| none => pure e
else
pure e
@[inline] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : m Expr :=
liftMetaM $ whnfHeadPredImp e pred
def whnfUntil (e : Expr) (declName : Name) : m (Option Expr) := liftMetaM do
let e ← whnfHeadPredImp e (fun e => pure $ !e.isAppOf declName)
if e.isAppOf declName then pure e
else pure none
@[inline] def unfoldDefinition? (e : Expr) : m (Option Expr) :=
liftMetaM $ unfoldDefinitionImp? e
unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName
unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName
@[implementedBy reduceBoolNativeUnsafe] constant reduceBoolNative (constName : Name) : MetaM Bool
@[implementedBy reduceNatNativeUnsafe] constant reduceNatNative (constName : Name) : MetaM Nat
def reduceNative? (e : Expr) : MetaM (Option Expr) :=
match e with
| Expr.app (Expr.const fName _ _) (Expr.const argName _ _) _ =>
if fName == `Lean.reduceBool then do
let b ← reduceBoolNative argName
pure $ toExpr b
else if fName == `Lean.reduceNat then do
let n ← reduceNatNative argName
pure $ toExpr n
else
pure none
| _ => pure none
@[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do
let a ← whnf a
match a with
| Expr.const `Nat.zero _ _ => k 0
| Expr.lit (Literal.natVal v) _ => k v
| _ => pure none
def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) :=
withNatValue a fun a =>
pure $ mkNatLit $ f a
def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) :=
withNatValue a fun a =>
withNatValue b fun b => do
trace[Meta.isDefEq.whnf.reduceBinOp]! "{a} op {b}"
pure $ mkNatLit $ f a b
def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do
withNatValue a fun a =>
withNatValue b fun b =>
pure $ toExpr $ f a b
def reduceNat? (e : Expr) : MetaM (Option Expr) :=
if e.hasFVar || e.hasMVar then
pure none
else match e with
| Expr.app (Expr.const fn _ _) a _ =>
if fn == `Nat.succ then reduceUnaryNatOp Nat.succ a
else pure none
| Expr.app (Expr.app (Expr.const fn _ _) a1 _) a2 _ =>
if fn == `Nat.add then reduceBinNatOp Nat.add a1 a2
else if fn == `Nat.sub then reduceBinNatOp Nat.sub a1 a2
else if fn == `Nat.mul then reduceBinNatOp Nat.mul a1 a2
else if fn == `Nat.div then reduceBinNatOp Nat.div a1 a2
else if fn == `Nat.mod then reduceBinNatOp Nat.mod a1 a2
else if fn == `Nat.beq then reduceBinNatPred Nat.beq a1 a2
else if fn == `Nat.ble then reduceBinNatPred Nat.ble a1 a2
else pure none
| _ => pure none
@[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do
-- We cache only closed terms without expr metavars.
-- Potential refinement: cache if `e` is not stuck at a metavariable
if e.hasFVar || e.hasExprMVar then
pure false
else
let ctx ← read
pure $ ctx.config.transparency != TransparencyMode.reducible
@[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do
if useCache then
let ctx ← read
let s ← get
match ctx.config.transparency with
| TransparencyMode.default => pure $ s.cache.whnfDefault.find? e
| TransparencyMode.all => pure $ s.cache.whnfAll.find? e
| _ => unreachable!
else
pure none
private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do
let ctx ← read
if useCache then
match ctx.config.transparency with
| TransparencyMode.default => modify fun s => { s with cache := { s.cache with whnfDefault := s.cache.whnfDefault.insert e r } }
| TransparencyMode.all => modify fun s => { s with cache := { s.cache with whnfAll := s.cache.whnfAll.insert e r } }
| _ => unreachable!
pure r
partial def whnfImp (e : Expr) : MetaM Expr :=
whnfEasyCases e fun e => do
let useCache ← useWHNFCache e
match (← cached? useCache e) with
| some e' => pure e'
| none =>
let e' ← whnfCoreImp e
match (← reduceNat? e') with
| some v => cache useCache e v
| none =>
match (← reduceNative? e') with
| some v => cache useCache e v
| none =>
match (← unfoldDefinition? e') with
| some e => whnfImp e
| none => cache useCache e e'
@[builtinInit] def setWHNFRef : IO Unit :=
whnfRef.set whnfImp
/- Given an expression `e`, compute its WHNF and if the result is a constructor, return field #i. -/
def reduceProj? (e : Expr) (i : Nat) : MetaM (Option Expr) := do
let e ← whnf e
matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ =>
let numArgs := e.getAppNumArgs
let idx := ctorVal.nparams + i
if idx < numArgs then
pure (some (e.getArg! idx))
else
pure none
builtin_initialize
registerTraceClass `Meta.whnf
end Lean.Meta
|
ceefa09676de07c984b3861e598ec6d0d30b0596 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/ring_theory/algebra_operations.lean | 7b4a758a5354fb1da98d007a548a4b5b3a3d3632 | [
"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 | 9,153 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Multiplication and division of submodules of an algebra.
-/
import ring_theory.algebra ring_theory.ideals algebra.pointwise
import tactic.chain
import tactic.monotonicity.basic
universes u v
open algebra
local attribute [instance] set.pointwise_mul_semiring
namespace submodule
variables {R : Type u} [comm_ring R]
section ring
variables {A : Type v} [ring A] [algebra R A]
variables (S T : set A) {M N P Q : submodule R A} {m n : A}
instance : has_one (submodule R A) :=
⟨submodule.map (of_id R A).to_linear_map (⊤ : ideal R)⟩
theorem one_eq_map_top :
(1 : submodule R A) = submodule.map (of_id R A).to_linear_map (⊤ : ideal R) := rfl
theorem one_eq_span : (1 : submodule R A) = span R {1} :=
begin
apply submodule.ext,
intro a,
erw [mem_map, mem_span_singleton],
apply exists_congr,
intro r,
simpa [smul_def],
end
theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P :=
by simpa only [one_eq_span, span_le, set.singleton_subset_iff]
set_option class.instance_max_depth 50
instance : has_mul (submodule R A) :=
⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩
set_option class.instance_max_depth 32
theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N :=
(le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩
theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P :=
⟨λ H m hm n hn, H $ mul_mem_mul hm hn,
λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩
@[elab_as_eliminator] protected theorem mul_induction_on
{C : A → Prop} {r : A} (hr : r ∈ M * N)
(hm : ∀ (m ∈ M) (n ∈ N), C (m * n))
(h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y))
(hs : ∀ (r : R) x, C x → C (r • x)) : C r :=
(@mul_le _ _ _ _ _ _ _ ⟨C, h0, ha, hs⟩).2 hm hr
variables R
theorem span_mul_span : span R S * span R T = span R (S * T) :=
begin
apply le_antisymm,
{ rw mul_le, intros a ha b hb,
apply span_induction ha,
work_on_goal 0 { intros, apply span_induction hb,
work_on_goal 0 { intros, exact subset_span ⟨_, ‹_›, _, ‹_›, rfl⟩ } },
all_goals { intros, simp only [mul_zero, zero_mul, zero_mem,
left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc],
try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' },
{ rw span_le, rintros _ ⟨a, ha, b, hb, rfl⟩,
exact mul_mem_mul (subset_span ha) (subset_span hb) }
end
variables {R}
variables (M N P Q)
set_option class.instance_max_depth 50
protected theorem mul_assoc : (M * N) * P = M * (N * P) :=
le_antisymm (mul_le.2 $ λ mn hmn p hp, suffices M * N ≤ (M * (N * P)).comap ((algebra.lmul R A).flip p), from this hmn,
mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from
(mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp))
(mul_le.2 $ λ m hm np hnp, suffices N * P ≤ (M * N * P).comap (algebra.lmul R A m), from this hnp,
mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from
mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp)
set_option class.instance_max_depth 32
@[simp] theorem mul_bot : M * ⊥ = ⊥ :=
eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero]
@[simp] theorem bot_mul : ⊥ * M = ⊥ :=
eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul]
@[simp] protected theorem one_mul : (1 : submodule R A) * M = M :=
by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] }
@[simp] protected theorem mul_one : M * 1 = M :=
by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] }
variables {M N P Q}
@[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q :=
mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn)
theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P :=
mul_le_mul h (le_refl P)
theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P :=
mul_le_mul (le_refl M) h
variables (M N P)
theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P :=
le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in
mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩)
(sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right))
theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P :=
le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in
mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩)
(sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right))
lemma mul_subset_mul :
(↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) :=
begin
rintros _ ⟨i, hi, j, hj, rfl⟩,
exact mul_mem_mul hi hj
end
variables {M N P}
instance : semiring (submodule R A) :=
{ one_mul := submodule.one_mul,
mul_one := submodule.mul_one,
mul_assoc := submodule.mul_assoc,
zero_mul := bot_mul,
mul_zero := mul_bot,
left_distrib := mul_sup,
right_distrib := sup_mul,
..submodule.add_comm_monoid,
..submodule.has_one,
..submodule.has_mul }
variables (M)
lemma pow_subset_pow {n : ℕ} :
(↑M : set A)^n ⊆ ↑(M^n : submodule R A) :=
begin
induction n with n ih,
{ erw [pow_zero, pow_zero, set.singleton_subset_iff], rw [mem_coe, ← one_le], exact le_refl _ },
{ rw [pow_succ, pow_succ],
refine set.subset.trans (set.pointwise_mul_subset_mul (set.subset.refl _) ih) _,
apply mul_subset_mul }
end
instance span.is_semiring_hom : is_semiring_hom (submodule.span R : set A → submodule R A) :=
{ map_zero := span_empty,
map_one := show _ = map _ ⊤,
by erw [← ideal.span_singleton_one, ← span_image, set.image_singleton, alg_hom.map_one]; refl,
map_add := span_union,
map_mul := λ s t, by erw [span_mul_span, set.pointwise_mul_eq_image] }
end ring
section comm_ring
variables {A : Type v} [comm_ring A] [algebra R A]
variables {M N : submodule R A} {m n : A}
theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N :=
mul_comm m n ▸ mul_mem_mul hm hn
variables (M N)
protected theorem mul_comm : M * N = N * M :=
le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm)
(mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn)
instance : comm_semiring (submodule R A) :=
{ mul_comm := submodule.mul_comm,
.. submodule.semiring }
variables (R A)
instance semimodule_set : semimodule (set A) (submodule R A) :=
{ smul := λ s P, span R s * P,
smul_add := λ _ _ _, mul_add _ _ _,
add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] },
mul_smul := λ s t P, show _ = _ * (_ * _),
by { rw [← mul_assoc, span_mul_span, set.pointwise_mul_eq_image] },
one_smul := λ P, show span R {(1 : A)} * P = _,
by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] },
zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul],
smul_zero := λ _, mul_bot _ }
set_option class.instance_max_depth 45
variables {R A}
lemma smul_def {s : set A} {P : submodule R A} :
s • P = span R s * P := rfl
lemma smul_le_smul {s t : set A} {M N : submodule R A} (h₁ : s ≤ t) (h₂ : M ≤ N) :
s • M ≤ t • N :=
mul_le_mul (span_mono h₁) h₂
lemma smul_singleton (a : A) (M : submodule R A) :
({a} : set A) • M = M.map (lmul_left _ _ a) :=
begin
conv_lhs {rw ← span_eq M},
change span _ _ * span _ _ = _,
rw [span_mul_span],
apply le_antisymm,
{ rw span_le,
rintros _ ⟨b, hb, m, hm, rfl⟩,
erw [mem_map, set.mem_singleton_iff.mp hb],
exact ⟨m, hm, rfl⟩ },
{ rintros _ ⟨m, hm, rfl⟩,
exact subset_span ⟨a, set.mem_singleton a, m, hm, rfl⟩ }
end
section quotient
local attribute [instance] set.smul_set_action
/-- The elements of `I / J` are the `x` such that `x • J ⊆ I`.
In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`),
which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs.
This is the general form of the ideal quotient, traditionally written $I : J$.
-/
instance : has_div (submodule R A) :=
⟨ λ I J, {
carrier := { x | ∀ y ∈ J, x * y ∈ I },
zero := λ y hy, by { rw zero_mul, apply submodule.zero },
add := λ a b ha hb y hy, by { rw add_mul, exact submodule.add _ (ha _ hy) (hb _ hy) },
smul := λ r x hx y hy, by { rw algebra.smul_mul_assoc, exact submodule.smul _ _ (hx _ hy) } } ⟩
lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} :
x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I :=
iff.refl _
lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I :=
⟨ λ h y ⟨y', hy', y_eq_xy'⟩, by { rw y_eq_xy', apply h, assumption },
λ h y hy, h (set.smul_mem_smul_set _ hy)⟩
lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _
end quotient
end comm_ring
end submodule
|
567b570a93fcce2937cd69aba67880bd4b51f0b8 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/algebra/group/units.lean | 3bbc12ec811022f915190f29b4a5c89ed279a270 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 19,566 | lean | /-
Copyright (c) 2017 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker, Jon Eugster
-/
import algebra.group.basic
import logic.nontrivial
/-!
# Units (i.e., invertible elements) of a monoid
An element of a `monoid` is a unit if it has a two-sided inverse.
## Main declarations
* `units M`: the group of units (i.e., invertible elements) of a monoid.
* `is_unit x`: a predicate asserting that `x` is a unit (i.e., invertible element) of a monoid.
For both declarations, there is an additive counterpart: `add_units` and `is_add_unit`.
## Notation
We provide `Mˣ` as notation for `units M`,
resembling the notation $R^{\times}$ for the units of a ring, which is common in mathematics.
-/
open function
universe u
variable {α : Type u}
/-- Units of a `monoid`, bundled version. Notation: `αˣ`.
An element of a `monoid` is a unit if it has a two-sided inverse.
This version bundles the inverse element so that it can be computed.
For a predicate see `is_unit`. -/
structure units (α : Type u) [monoid α] :=
(val : α)
(inv : α)
(val_inv : val * inv = 1)
(inv_val : inv * val = 1)
postfix `ˣ`:1025 := units
-- We don't provide notation for the additive version, because its use is somewhat rare.
/-- Units of an `add_monoid`, bundled version.
An element of an `add_monoid` is a unit if it has a two-sided additive inverse.
This version bundles the inverse element so that it can be computed.
For a predicate see `is_add_unit`. -/
structure add_units (α : Type u) [add_monoid α] :=
(val : α)
(neg : α)
(val_neg : val + neg = 0)
(neg_val : neg + val = 0)
attribute [to_additive] units
section has_elem
@[to_additive] lemma unique_has_one {α : Type*} [unique α] [has_one α] :
default = (1 : α) :=
unique.default_eq 1
end has_elem
namespace units
variables [monoid α]
@[to_additive] instance : has_coe αˣ α := ⟨val⟩
@[to_additive] instance : has_inv αˣ := ⟨λ u, ⟨u.2, u.1, u.4, u.3⟩⟩
/-- See Note [custom simps projection] -/
@[to_additive /-" See Note [custom simps projection] "-/]
def simps.coe (u : αˣ) : α := u
/-- See Note [custom simps projection] -/
@[to_additive /-" See Note [custom simps projection] "-/]
def simps.coe_inv (u : αˣ) : α := ↑(u⁻¹)
initialize_simps_projections units (val → coe as_prefix, inv → coe_inv as_prefix)
initialize_simps_projections add_units (val → coe as_prefix, neg → coe_neg as_prefix)
@[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl
@[ext, to_additive] theorem ext :
function.injective (coe : αˣ → α)
| ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e :=
by change v = v' at e; subst v'; congr;
simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁
@[norm_cast, to_additive] theorem eq_iff {a b : αˣ} :
(a : α) = b ↔ a = b := ext.eq_iff
@[to_additive] theorem ext_iff {a b : αˣ} :
a = b ↔ (a : α) = b := eq_iff.symm
@[to_additive] instance [decidable_eq α] : decidable_eq αˣ :=
λ a b, decidable_of_iff' _ ext_iff
@[simp, to_additive] theorem mk_coe (u : αˣ) (y h₁ h₂) :
mk (u : α) y h₁ h₂ = u :=
ext rfl
/-- Copy a unit, adjusting definition equalities. -/
@[to_additive /-"Copy an `add_unit`, adjusting definitional equalities."-/, simps]
def copy (u : αˣ) (val : α) (hv : val = u) (inv : α) (hi : inv = ↑(u⁻¹)) : αˣ :=
{ val := val, inv := inv,
inv_val := hv.symm ▸ hi.symm ▸ u.inv_val, val_inv := hv.symm ▸ hi.symm ▸ u.val_inv }
@[to_additive]
lemma copy_eq (u : αˣ) (val hv inv hi) :
u.copy val hv inv hi = u :=
ext hv
@[to_additive] instance : mul_one_class αˣ :=
{ mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv,
by rw [mul_assoc, ←mul_assoc u₂.val, val_inv, one_mul, val_inv],
by rw [mul_assoc, ←mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩,
one := ⟨1, 1, one_mul 1, one_mul 1⟩,
one_mul := λ u, ext $ one_mul u,
mul_one := λ u, ext $ mul_one u }
/-- Units of a monoid form a group. -/
@[to_additive "Additive units of an additive monoid form an additive group."]
instance : group αˣ :=
{ mul := (*),
one := 1,
mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃,
inv := has_inv.inv,
mul_left_inv := λ u, ext u.inv_val,
..units.mul_one_class }
@[to_additive] instance {α} [comm_monoid α] : comm_group αˣ :=
{ mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group }
@[to_additive] instance : inhabited αˣ := ⟨1⟩
@[to_additive] instance [has_repr α] : has_repr αˣ := ⟨repr ∘ val⟩
variables (a b c : αˣ) {u : αˣ}
@[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl
@[simp, norm_cast, to_additive] lemma coe_one : ((1 : αˣ) : α) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_eq_one {a : αˣ} : (a : α) = 1 ↔ a = 1 :=
by rw [←units.coe_one, eq_iff]
@[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl
@[simp, to_additive] lemma val_eq_coe : a.val = (↑a : α) := rfl
@[simp, to_additive] lemma inv_eq_coe_inv : a.inv = ((a⁻¹ : αˣ) : α) := rfl
@[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _
@[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _
@[to_additive] lemma inv_mul_of_eq {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by rw [←h, u.inv_mul]
@[to_additive] lemma mul_inv_of_eq {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by rw [←h, u.mul_inv]
@[simp, to_additive] lemma mul_inv_cancel_left (a : αˣ) (b : α) : (a:α) * (↑a⁻¹ * b) = b :=
by rw [← mul_assoc, mul_inv, one_mul]
@[simp, to_additive] lemma inv_mul_cancel_left (a : αˣ) (b : α) : (↑a⁻¹:α) * (a * b) = b :=
by rw [← mul_assoc, inv_mul, one_mul]
@[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : αˣ) : a * b * ↑b⁻¹ = a :=
by rw [mul_assoc, mul_inv, mul_one]
@[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : αˣ) : a * ↑b⁻¹ * b = a :=
by rw [mul_assoc, inv_mul, mul_one]
@[simp, to_additive] theorem mul_right_inj (a : αˣ) {b c : α} : (a:α) * b = a * c ↔ b = c :=
⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : αˣ)) h, congr_arg _⟩
@[simp, to_additive] theorem mul_left_inj (a : αˣ) {b c : α} : b * a = c * a ↔ b = c :=
⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : αˣ)) h, congr_arg _⟩
@[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : 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 c : α} : 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 {b c : α} : ↑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 c : α} : a * ↑b⁻¹ = c ↔ a = c * b :=
⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩
@[to_additive] protected lemma inv_eq_of_mul_eq_one_left {a : α} (h : a * u = 1) : ↑u⁻¹ = a :=
calc ↑u⁻¹ = 1 * ↑u⁻¹ : by rw one_mul
... = a : by rw [←h, mul_inv_cancel_right]
@[to_additive] protected lemma inv_eq_of_mul_eq_one_right {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a :=
calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one
... = a : by rw [←h, inv_mul_cancel_left]
@[to_additive] protected lemma eq_inv_of_mul_eq_one_left {a : α} (h : ↑u * a = 1) : a = ↑u⁻¹ :=
(units.inv_eq_of_mul_eq_one_right h).symm
@[to_additive] protected lemma eq_inv_of_mul_eq_one_right {a : α} (h : a * u = 1) : a = ↑u⁻¹ :=
(units.inv_eq_of_mul_eq_one_left h).symm
@[simp, to_additive] lemma mul_inv_eq_one {a : α} : a * ↑u⁻¹ = 1 ↔ a = u :=
⟨inv_inv u ▸ units.eq_inv_of_mul_eq_one_right, λ h, mul_inv_of_eq h.symm⟩
@[simp, to_additive] lemma inv_mul_eq_one {a : α} : ↑u⁻¹ * a = 1 ↔ ↑u = a :=
⟨inv_inv u ▸ units.inv_eq_of_mul_eq_one_right, inv_mul_of_eq⟩
@[to_additive] lemma mul_eq_one_iff_eq_inv {a : α} : a * u = 1 ↔ a = ↑u⁻¹ :=
by rw [←mul_inv_eq_one, inv_inv]
@[to_additive] lemma mul_eq_one_iff_inv_eq {a : α} : ↑u * a = 1 ↔ ↑u⁻¹ = a :=
by rw [←inv_mul_eq_one, inv_inv]
@[to_additive] lemma inv_unique {u₁ u₂ : αˣ} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ :=
units.inv_eq_of_mul_eq_one_right $ by rw [h, u₂.mul_inv]
end units
/-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/
@[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit
out of `a`."]
def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) :
αˣ :=
⟨a, b, hab, (mul_comm b a).trans hab⟩
@[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) :
(units.mk_of_mul_eq_one a b h : α) = a := rfl
section monoid
variables [monoid α] {a b c : α}
/-- Partial division. It is defined when the
second argument is invertible, and unlike the division operator
in `division_ring` it is not totalized at zero. -/
def divp (a : α) (u) : α := a * (u⁻¹ : αˣ)
infix ` /ₚ `:70 := divp
@[simp] theorem divp_self (u : αˣ) : (u : α) /ₚ u = 1 := units.mul_inv _
@[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _
theorem divp_assoc (a b : α) (u : αˣ) : a * b /ₚ u = a * (b /ₚ u) :=
mul_assoc _ _ _
/-- `field_simp` needs the reverse direction of `divp_assoc` to move all `/ₚ` to the right. -/
@[field_simps] lemma divp_assoc' (x y : α) (u : αˣ) : x * (y /ₚ u) = (x * y) /ₚ u :=
(divp_assoc _ _ _).symm
@[simp] theorem divp_inv (u : αˣ) : a /ₚ u⁻¹ = a * u := rfl
@[simp] theorem divp_mul_cancel (a : α) (u : αˣ) : a /ₚ u * u = a :=
(mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one]
@[simp] theorem mul_divp_cancel (a : α) (u : αˣ) : (a * u) /ₚ u = a :=
(mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one]
@[simp] theorem divp_left_inj (u : αˣ) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b :=
units.mul_left_inj _
@[field_simps] theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : αˣ) :
(x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) :=
by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc]
@[field_simps] theorem divp_eq_iff_mul_eq {x : α} {u : αˣ} {y : α} : x /ₚ u = y ↔ y * u = x :=
u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩
@[field_simps] theorem eq_divp_iff_mul_eq {x : α} {u : αˣ} {y : α} : x = y /ₚ u ↔ x * u = y :=
by rw [eq_comm, divp_eq_iff_mul_eq]
theorem divp_eq_one_iff_eq {a : α} {u : αˣ} : a /ₚ u = 1 ↔ a = u :=
(units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul]
@[simp] theorem one_divp (u : αˣ) : 1 /ₚ u = ↑u⁻¹ :=
one_mul _
/-- Used for `field_simp` to deal with inverses of units. -/
@[field_simps] lemma inv_eq_one_divp (u : αˣ) : ↑u⁻¹ = 1 /ₚ u :=
by rw one_divp
/--
Used for `field_simp` to deal with inverses of units. This form of the lemma
is essential since `field_simp` likes to use `inv_eq_one_div` to rewrite
`↑u⁻¹ = ↑(1 / u)`.
-/
@[field_simps] lemma inv_eq_one_divp' (u : αˣ) :
((1 / u : αˣ) : α) = 1 /ₚ u :=
by rw [one_div, one_divp]
/--
`field_simp` moves division inside `αˣ` to the right, and this lemma
lifts the calculation to `α`.
-/
@[field_simps] lemma coe_div_eq_divp (u₁ u₂ : αˣ) : ↑(u₁ / u₂) = ↑u₁ /ₚ u₂ :=
by rw [divp, division_def, units.coe_mul]
end monoid
section comm_monoid
variables [comm_monoid α]
@[field_simps] theorem divp_mul_eq_mul_divp (x y : α) (u : αˣ) : x /ₚ u * y = x * y /ₚ u :=
by simp_rw [divp, mul_assoc, mul_comm]
-- Theoretically redundant as `field_simp` lemma.
@[field_simps] lemma divp_eq_divp_iff {x y : α} {ux uy : αˣ} :
x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux :=
by rw [divp_eq_iff_mul_eq, divp_mul_eq_mul_divp, divp_eq_iff_mul_eq]
-- Theoretically redundant as `field_simp` lemma.
@[field_simps] lemma divp_mul_divp (x y : α) (ux uy : αˣ) :
(x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) :=
by rw [divp_mul_eq_mul_divp, divp_assoc', divp_divp_eq_divp_mul]
end comm_monoid
/-!
# `is_unit` predicate
In this file we define the `is_unit` predicate on a `monoid`, and
prove a few basic properties. For the bundled version see `units`. See
also `prime`, `associated`, and `irreducible` in `algebra/associated`.
-/
section is_unit
variables {M : Type*} {N : Type*}
/-- An element `a : M` of a monoid is a unit if it has a two-sided inverse.
The actual definition says that `a` is equal to some `u : Mˣ`, where
`Mˣ` is a bundled version of `is_unit`. -/
@[to_additive "An element `a : M` of an add_monoid is an `add_unit` if it has
a two-sided additive inverse. The actual definition says that `a` is equal to some
`u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."]
def is_unit [monoid M] (a : M) : Prop := ∃ u : Mˣ, (u : M) = a
@[nontriviality, to_additive]
lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a :=
⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩
attribute [nontriviality] is_add_unit_of_subsingleton
@[to_additive] instance [monoid M] : can_lift M Mˣ :=
{ coe := coe,
cond := is_unit,
prf := λ _, id }
@[to_additive] instance [monoid M] [subsingleton M] : unique Mˣ :=
{ default := 1,
uniq := λ a, units.coe_eq_one.mp $ subsingleton.elim (a : M) 1 }
@[simp, to_additive is_add_unit_add_unit]
protected lemma units.is_unit [monoid M] (u : Mˣ) : is_unit (u : M) := ⟨u, rfl⟩
@[simp, to_additive]
theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩
@[to_additive] theorem is_unit_of_mul_eq_one [comm_monoid M]
(a b : M) (h : a * b = 1) : is_unit a :=
⟨units.mk_of_mul_eq_one a b h, rfl⟩
@[to_additive is_add_unit.exists_neg] theorem is_unit.exists_right_inv [monoid M]
{a : M} (h : is_unit a) : ∃ b, a * b = 1 :=
by { rcases h with ⟨⟨a, b, hab, _⟩, rfl⟩, exact ⟨b, hab⟩ }
@[to_additive is_add_unit.exists_neg'] theorem is_unit.exists_left_inv [monoid M]
{a : M} (h : is_unit a) : ∃ b, b * a = 1 :=
by { rcases h with ⟨⟨a, b, _, hba⟩, rfl⟩, exact ⟨b, hba⟩ }
@[to_additive] theorem is_unit_iff_exists_inv [comm_monoid M]
{a : M} : is_unit a ↔ ∃ b, a * b = 1 :=
⟨λ h, h.exists_right_inv,
λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩
@[to_additive] theorem is_unit_iff_exists_inv' [comm_monoid M]
{a : M} : is_unit a ↔ ∃ b, b * a = 1 :=
by simp [is_unit_iff_exists_inv, mul_comm]
@[to_additive]
lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) :=
by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ }
/-- Multiplication by a `u : Mˣ` on the right doesn't affect `is_unit`. -/
@[simp, to_additive "Addition of a `u : add_units M` on the right doesn't
affect `is_add_unit`."]
theorem units.is_unit_mul_units [monoid M] (a : M) (u : Mˣ) :
is_unit (a * u) ↔ is_unit a :=
iff.intro
(assume ⟨v, hv⟩,
have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul],
by rwa [mul_assoc, units.mul_inv, mul_one] at this)
(λ v, v.mul u.is_unit)
/-- Multiplication by a `u : Mˣ` on the left doesn't affect `is_unit`. -/
@[simp, to_additive "Addition of a `u : add_units M` on the left doesn't affect `is_add_unit`."]
theorem units.is_unit_units_mul {M : Type*} [monoid M] (u : Mˣ) (a : M) :
is_unit (↑u * a) ↔ is_unit a :=
iff.intro
(assume ⟨v, hv⟩,
have is_unit (↑u⁻¹ * (↑u * a)), by existsi u⁻¹ * v; rw [←hv, units.coe_mul],
by rwa [←mul_assoc, units.inv_mul, one_mul] at this)
u.is_unit.mul
@[to_additive]
theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M}
(hu : is_unit (x * y)) : is_unit x :=
let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in
is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩
@[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M}
(hu : is_unit (x * y)) : is_unit y :=
@is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm
@[simp, to_additive]
lemma is_unit.mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y :=
⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩,
λ h, is_unit.mul h.1 h.2⟩
/-- The element of the group of units, corresponding to an element of a monoid which is a unit. When
`α` is a `division_monoid`, use `is_unit.unit'` instead. -/
@[to_additive "The element of the additive group of additive units, corresponding to an element of
an additive monoid which is an additive unit. When `α` is a `subtraction_monoid`, use
`is_add_unit.add_unit'` instead."]
noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : Mˣ :=
(classical.some h).copy a (classical.some_spec h).symm _ rfl
@[simp, to_additive]
lemma is_unit.unit_of_coe_units [monoid M] {a : Mˣ} (h : is_unit (a : M)) : h.unit = a :=
units.ext $ rfl
@[simp, to_additive]
lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a :=
rfl
@[simp, to_additive]
lemma is_unit.coe_inv_mul [monoid M] {a : M} (h : is_unit a) :
↑(h.unit)⁻¹ * a = 1 :=
units.mul_inv _
@[simp, to_additive]
lemma is_unit.mul_coe_inv [monoid M] {a : M} (h : is_unit a) :
a * ↑(h.unit)⁻¹ = 1 :=
begin
convert units.mul_inv _,
simp [h.unit_spec]
end
/-- `is_unit x` is decidable if we can decide if `x` comes from `Mˣ`. -/
instance [monoid M] (x : M) [h : decidable (∃ u : Mˣ, ↑u = x)] : decidable (is_unit x) := h
section monoid
variables [monoid M] {a b c : M}
@[to_additive] lemma is_unit.mul_left_inj (h : is_unit a) : b * a = c * a ↔ b = c :=
let ⟨u, hu⟩ := h in hu ▸ u.mul_left_inj
@[to_additive] lemma is_unit.mul_right_inj (h : is_unit a) : a * b = a * c ↔ b = c :=
let ⟨u, hu⟩ := h in hu ▸ u.mul_right_inj
@[to_additive] protected lemma is_unit.mul_left_cancel (h : is_unit a) : a * b = a * c → b = c :=
h.mul_right_inj.1
@[to_additive] protected lemma is_unit.mul_right_cancel (h : is_unit b) : a * b = c * b → a = c :=
h.mul_left_inj.1
@[to_additive] protected lemma is_unit.mul_right_injective (h : is_unit a) : injective ((*) a) :=
λ _ _, h.mul_left_cancel
@[to_additive] protected lemma is_unit.mul_left_injective (h : is_unit b) : injective (* b) :=
λ _ _, h.mul_right_cancel
end monoid
end is_unit
section noncomputable_defs
variables {M : Type*}
/-- Constructs a `group` structure on a `monoid` consisting only of units. -/
noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M :=
{ inv := λ a, ↑((h a).unit)⁻¹,
mul_left_inv := λ a, by
{ change ↑((h a).unit)⁻¹ * a = 1,
rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] },
.. hM }
/-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/
noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) :
comm_group M :=
{ inv := λ a, ↑((h a).unit)⁻¹,
mul_left_inv := λ a, by
{ change ↑((h a).unit)⁻¹ * a = 1,
rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] },
.. hM }
end noncomputable_defs
|
7338e06cd535656d47884b2c35bb44b94c8c7be6 | bb31430994044506fa42fd667e2d556327e18dfe | /src/order/well_founded_set.lean | f726237ba0da4caef2d82f638cd6c74bedaf61ae | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 29,842 | lean | /-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import order.antichain
import order.order_iso_nat
import order.well_founded
import tactic.tfae
/-!
# Well-founded sets
A well-founded subset of an ordered type is one on which the relation `<` is well-founded.
## Main Definitions
* `set.well_founded_on s r` indicates that the relation `r` is
well-founded when restricted to the set `s`.
* `set.is_wf s` indicates that `<` is well-founded when restricted to `s`.
* `set.partially_well_ordered_on s r` indicates that the relation `r` is
partially well-ordered (also known as well quasi-ordered) when restricted to the set `s`.
* `set.is_pwo s` indicates that any infinite sequence of elements in `s` contains an infinite
monotone subsequence. Note that this is equivalent to containing only two comparable elements.
## Main Results
* Higman's Lemma, `set.partially_well_ordered_on.partially_well_ordered_on_sublist_forall₂`,
shows that if `r` is partially well-ordered on `s`, then `list.sublist_forall₂` is partially
well-ordered on the set of lists of elements of `s`. The result was originally published by
Higman, but this proof more closely follows Nash-Williams.
* `set.well_founded_on_iff` relates `well_founded_on` to the well-foundedness of a relation on the
original type, to avoid dealing with subtypes.
* `set.is_wf.mono` shows that a subset of a well-founded subset is well-founded.
* `set.is_wf.union` shows that the union of two well-founded subsets is well-founded.
* `finset.is_wf` shows that all `finset`s are well-founded.
## TODO
Prove that `s` is partial well ordered iff it has no infinite descending chain or antichain.
## References
* [Higman, *Ordering by Divisibility in Abstract Algebras*][Higman52]
* [Nash-Williams, *On Well-Quasi-Ordering Finite Trees*][Nash-Williams63]
-/
variables {ι α β : Type*}
namespace set
/-! ### Relations well-founded on sets -/
/-- `s.well_founded_on r` indicates that the relation `r` is well-founded when restricted to `s`. -/
def well_founded_on (s : set α) (r : α → α → Prop) : Prop := well_founded $ λ a b : s, r a b
@[simp] lemma well_founded_on_empty (r : α → α → Prop) : well_founded_on ∅ r :=
well_founded_of_empty _
section well_founded_on
variables {r r' : α → α → Prop}
section any_rel
variables {s t : set α} {x y : α}
lemma well_founded_on_iff :
s.well_founded_on r ↔ well_founded (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) :=
begin
have f : rel_embedding (λ (a : s) (b : s), r a b) (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) :=
⟨⟨coe, subtype.coe_injective⟩, λ a b, by simp⟩,
refine ⟨λ h, _, f.well_founded⟩,
rw well_founded.well_founded_iff_has_min,
intros t ht,
by_cases hst : (s ∩ t).nonempty,
{ rw ← subtype.preimage_coe_nonempty at hst,
rcases h.has_min (coe ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩,
exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hm ⟨x, xs⟩ xt xm⟩ },
{ rcases ht with ⟨m, mt⟩,
exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hst ⟨m, ⟨ms, mt⟩⟩⟩ }
end
namespace well_founded_on
protected lemma induction (hs : s.well_founded_on r) (hx : x ∈ s) {P : α → Prop}
(hP : ∀ y ∈ s, (∀ z ∈ s, r z y → P z) → P y) : P x :=
begin
let Q : s → Prop := λ y, P y,
change Q ⟨x, hx⟩,
refine well_founded.induction hs ⟨x, hx⟩ _,
simpa only [subtype.forall]
end
protected lemma mono (h : t.well_founded_on r') (hle : r ≤ r') (hst : s ⊆ t) :
s.well_founded_on r :=
begin
rw well_founded_on_iff at *,
refine subrelation.wf (λ x y xy, _) h,
exact ⟨hle _ _ xy.1, hst xy.2.1, hst xy.2.2⟩
end
lemma subset (h : t.well_founded_on r) (hst : s ⊆ t) : s.well_founded_on r := h.mono le_rfl hst
open relation
/-- `a` is accessible under the relation `r` iff `r` is well-founded on the downward transitive
closure of `a` under `r` (including `a` or not). -/
lemma acc_iff_well_founded_on {α} {r : α → α → Prop} {a : α} :
[ acc r a,
{b | refl_trans_gen r b a}.well_founded_on r,
{b | trans_gen r b a}.well_founded_on r ].tfae :=
begin
tfae_have : 1 → 2,
{ refine λ h, ⟨λ b, _⟩, apply inv_image.accessible,
rw ← acc_trans_gen_iff at h ⊢,
obtain h'|h' := refl_trans_gen_iff_eq_or_trans_gen.1 b.2,
{ rwa h' at h }, { exact h.inv h' } },
tfae_have : 2 → 3,
{ exact λ h, h.subset (λ _, trans_gen.to_refl) },
tfae_have : 3 → 1,
{ refine λ h, acc.intro _ (λ b hb, (h.apply ⟨b, trans_gen.single hb⟩).of_fibration subtype.val _),
exact λ ⟨c, hc⟩ d h, ⟨⟨d, trans_gen.head h hc⟩, h, rfl⟩ },
tfae_finish,
end
end well_founded_on
end any_rel
section is_strict_order
variables [is_strict_order α r] {s t : set α}
instance is_strict_order.subset : is_strict_order α (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) :=
{ to_is_irrefl := ⟨λ a con, irrefl_of r a con.1 ⟩,
to_is_trans := ⟨λ a b c ab bc, ⟨trans_of r ab.1 bc.1, ab.2.1, bc.2.2⟩ ⟩ }
lemma well_founded_on_iff_no_descending_seq :
s.well_founded_on r ↔ ∀ (f : ((>) : ℕ → ℕ → Prop) ↪r r), ¬∀ n, f n ∈ s :=
begin
simp only [well_founded_on_iff, rel_embedding.well_founded_iff_no_descending_seq, ← not_exists,
← not_nonempty_iff, not_iff_not],
split,
{ rintro ⟨⟨f, hf⟩⟩,
have H : ∀ n, f n ∈ s, from λ n, (hf.2 n.lt_succ_self).2.2,
refine ⟨⟨f, _⟩, H⟩,
simpa only [H, and_true] using @hf },
{ rintro ⟨⟨f, hf⟩, hfs : ∀ n, f n ∈ s⟩,
refine ⟨⟨f, _⟩⟩,
simpa only [hfs, and_true] using @hf }
end
lemma well_founded_on.union (hs : s.well_founded_on r) (ht : t.well_founded_on r) :
(s ∪ t).well_founded_on r :=
begin
rw well_founded_on_iff_no_descending_seq at *,
rintro f hf,
rcases nat.exists_subseq_of_forall_mem_union f hf with ⟨g, hg|hg⟩,
exacts [hs (g.dual.lt_embedding.trans f) hg, ht (g.dual.lt_embedding.trans f) hg]
end
@[simp] lemma well_founded_on_union :
(s ∪ t).well_founded_on r ↔ s.well_founded_on r ∧ t.well_founded_on r :=
⟨λ h, ⟨h.subset $ subset_union_left _ _, h.subset $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩
end is_strict_order
end well_founded_on
/-! ### Sets well-founded w.r.t. the strict inequality -/
section has_lt
variables [has_lt α] {s t : set α}
/-- `s.is_wf` indicates that `<` is well-founded when restricted to `s`. -/
def is_wf (s : set α) : Prop := well_founded_on s (<)
@[simp] lemma is_wf_empty : is_wf (∅ : set α) := well_founded_of_empty _
lemma is_wf_univ_iff : is_wf (univ : set α) ↔ well_founded ((<) : α → α → Prop) :=
by simp [is_wf, well_founded_on_iff]
theorem is_wf.mono (h : is_wf t) (st : s ⊆ t) : is_wf s := h.subset st
end has_lt
section preorder
variables [preorder α] {s t : set α} {a : α}
protected lemma is_wf.union (hs : is_wf s) (ht : is_wf t) : is_wf (s ∪ t) := hs.union ht
@[simp] lemma is_wf_union : is_wf (s ∪ t) ↔ is_wf s ∧ is_wf t := well_founded_on_union
end preorder
section preorder
variables [preorder α] {s t : set α} {a : α}
theorem is_wf_iff_no_descending_seq :
is_wf s ↔ ∀ f : ℕ → α, strict_anti f → ¬(∀ n, f (order_dual.to_dual n) ∈ s) :=
well_founded_on_iff_no_descending_seq.trans
⟨λ H f hf, H ⟨⟨f, hf.injective⟩, λ a b, hf.lt_iff_lt⟩, λ H f, H f (λ _ _, f.map_rel_iff.2)⟩
end preorder
/-!
### Partially well-ordered sets
A set is partially well-ordered by a relation `r` when any infinite sequence contains two elements
where the first is related to the second by `r`. Equivalently, any antichain (see `is_antichain`) is
finite, see `set.partially_well_ordered_on_iff_finite_antichains`.
-/
/-- A subset is partially well-ordered by a relation `r` when any infinite sequence contains
two elements where the first is related to the second by `r`. -/
def partially_well_ordered_on (s : set α) (r : α → α → Prop) : Prop :=
∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ m n : ℕ, m < n ∧ r (f m) (f n)
section partially_well_ordered_on
variables {r : α → α → Prop} {r' : β → β → Prop} {f : α → β} {s : set α} {t : set α} {a : α}
lemma partially_well_ordered_on.mono (ht : t.partially_well_ordered_on r) (h : s ⊆ t) :
s.partially_well_ordered_on r :=
λ f hf, ht f $ λ n, h $ hf n
@[simp] lemma partially_well_ordered_on_empty (r : α → α → Prop) : partially_well_ordered_on ∅ r :=
λ f hf, (hf 0).elim
lemma partially_well_ordered_on.union (hs : s.partially_well_ordered_on r)
(ht : t.partially_well_ordered_on r) :
(s ∪ t).partially_well_ordered_on r :=
begin
rintro f hf,
rcases nat.exists_subseq_of_forall_mem_union f hf with ⟨g, hgs|hgt⟩,
{ rcases hs _ hgs with ⟨m, n, hlt, hr⟩,
exact ⟨g m, g n, g.strict_mono hlt, hr⟩ },
{ rcases ht _ hgt with ⟨m, n, hlt, hr⟩,
exact ⟨g m, g n, g.strict_mono hlt, hr⟩ }
end
@[simp] lemma partially_well_ordered_on_union :
(s ∪ t).partially_well_ordered_on r ↔
s.partially_well_ordered_on r ∧ t.partially_well_ordered_on r :=
⟨λ h, ⟨h.mono $ subset_union_left _ _, h.mono $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩
lemma partially_well_ordered_on.image_of_monotone_on (hs : s.partially_well_ordered_on r)
(hf : ∀ (a₁ ∈ s) (a₂ ∈ s), r a₁ a₂ → r' (f a₁) (f a₂)) :
(f '' s).partially_well_ordered_on r' :=
begin
intros g' hg',
choose g hgs heq using hg',
obtain rfl : f ∘ g = g', from funext heq,
obtain ⟨m, n, hlt, hmn⟩ := hs g hgs,
exact ⟨m, n, hlt, hf _ (hgs m) _ (hgs n) hmn⟩
end
lemma _root_.is_antichain.finite_of_partially_well_ordered_on (ha : is_antichain r s)
(hp : s.partially_well_ordered_on r) :
s.finite :=
begin
refine not_infinite.1 (λ hi, _),
obtain ⟨m, n, hmn, h⟩ := hp (λ n, hi.nat_embedding _ n) (λ n, (hi.nat_embedding _ n).2),
exact hmn.ne ((hi.nat_embedding _).injective $ subtype.val_injective $
ha.eq (hi.nat_embedding _ m).2 (hi.nat_embedding _ n).2 h),
end
section is_refl
variables [is_refl α r]
protected lemma finite.partially_well_ordered_on (hs : s.finite) : s.partially_well_ordered_on r :=
begin
intros f hf,
obtain ⟨m, n, hmn, h⟩ := hs.exists_lt_map_eq_of_forall_mem hf,
exact ⟨m, n, hmn, h.subst $ refl (f m)⟩,
end
lemma _root_.is_antichain.partially_well_ordered_on_iff (hs : is_antichain r s) :
s.partially_well_ordered_on r ↔ s.finite :=
⟨hs.finite_of_partially_well_ordered_on, finite.partially_well_ordered_on⟩
@[simp] lemma partially_well_ordered_on_singleton (a : α) : partially_well_ordered_on {a} r :=
(finite_singleton a).partially_well_ordered_on
@[simp] lemma partially_well_ordered_on_insert :
partially_well_ordered_on (insert a s) r ↔ partially_well_ordered_on s r :=
by simp only [← singleton_union, partially_well_ordered_on_union,
partially_well_ordered_on_singleton, true_and]
protected lemma partially_well_ordered_on.insert (h : partially_well_ordered_on s r) (a : α) :
partially_well_ordered_on (insert a s) r :=
partially_well_ordered_on_insert.2 h
lemma partially_well_ordered_on_iff_finite_antichains [is_symm α r] :
s.partially_well_ordered_on r ↔ ∀ t ⊆ s, is_antichain r t → t.finite :=
begin
refine ⟨λ h t ht hrt, hrt.finite_of_partially_well_ordered_on (h.mono ht), _⟩,
rintro hs f hf,
by_contra' H,
refine infinite_range_of_injective (λ m n hmn, _) (hs _ (range_subset_iff.2 hf) _),
{ obtain h | h | h := lt_trichotomy m n,
{ refine (H _ _ h _).elim,
rw hmn,
exact refl _ },
{ exact h },
{ refine (H _ _ h _).elim,
rw hmn,
exact refl _ } },
rintro _ ⟨m, hm, rfl⟩ _ ⟨n, hn, rfl⟩ hmn,
obtain h | h := (ne_of_apply_ne _ hmn).lt_or_lt,
{ exact H _ _ h },
{ exact mt symm (H _ _ h) }
end
variables [is_trans α r]
lemma partially_well_ordered_on.exists_monotone_subseq (h : s.partially_well_ordered_on r)
(f : ℕ → α) (hf : ∀ n, f n ∈ s) :
∃ g : ℕ ↪o ℕ, ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) :=
begin
obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq r f,
{ refine ⟨g, λ m n hle, _⟩,
obtain hlt | rfl := hle.lt_or_eq,
exacts [h1 m n hlt, refl_of r _] },
{ exfalso,
obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) (λ n, hf _),
exact h2 m n hlt hle }
end
lemma partially_well_ordered_on_iff_exists_monotone_subseq :
s.partially_well_ordered_on r ↔
∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) :=
begin
classical,
split; intros h f hf,
{ exact h.exists_monotone_subseq f hf },
{ obtain ⟨g, gmon⟩ := h f hf,
exact ⟨g 0, g 1, g.lt_iff_lt.2 zero_lt_one, gmon _ _ zero_le_one⟩ }
end
protected lemma partially_well_ordered_on.prod {t : set β} (hs : partially_well_ordered_on s r)
(ht : partially_well_ordered_on t r') :
partially_well_ordered_on (s ×ˢ t) (λ x y : α × β, r x.1 y.1 ∧ r' x.2 y.2) :=
begin
intros f hf,
obtain ⟨g₁, h₁⟩ := hs.exists_monotone_subseq (prod.fst ∘ f) (λ n, (hf n).1),
obtain ⟨m, n, hlt, hle⟩ := ht (prod.snd ∘ f ∘ g₁) (λ n, (hf _).2),
exact ⟨g₁ m, g₁ n, g₁.strict_mono hlt, h₁ _ _ hlt.le, hle⟩
end
end is_refl
lemma partially_well_ordered_on.well_founded_on [is_preorder α r]
(h : s.partially_well_ordered_on r) :
s.well_founded_on (λ a b, r a b ∧ ¬r b a) :=
begin
letI : preorder α := { le := r, le_refl := refl_of r, le_trans := λ _ _ _, trans_of r },
change s.well_founded_on (<), change s.partially_well_ordered_on (≤) at h,
rw well_founded_on_iff_no_descending_seq,
intros f hf,
obtain ⟨m, n, hlt, hle⟩ := h f hf,
exact (f.map_rel_iff.2 hlt).not_le hle,
end
end partially_well_ordered_on
section is_pwo
variables [preorder α] [preorder β] {s t : set α}
/-- A subset of a preorder is partially well-ordered when any infinite sequence contains
a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/
def is_pwo (s : set α) : Prop := partially_well_ordered_on s (≤)
lemma is_pwo.mono (ht : t.is_pwo) : s ⊆ t → s.is_pwo := ht.mono
theorem is_pwo.exists_monotone_subseq (h : s.is_pwo) (f : ℕ → α) (hf : ∀ n, f n ∈ s) :
∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) :=
h.exists_monotone_subseq f hf
theorem is_pwo_iff_exists_monotone_subseq :
s.is_pwo ↔ ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) :=
partially_well_ordered_on_iff_exists_monotone_subseq
protected lemma is_pwo.is_wf (h : s.is_pwo) : s.is_wf :=
by simpa only [← lt_iff_le_not_le] using h.well_founded_on
lemma is_pwo.prod {t : set β} (hs : s.is_pwo) (ht : t.is_pwo) : is_pwo (s ×ˢ t) := hs.prod ht
lemma is_pwo.image_of_monotone_on (hs : s.is_pwo) {f : α → β} (hf : monotone_on f s) :
is_pwo (f '' s) :=
hs.image_of_monotone_on hf
lemma is_pwo.image_of_monotone (hs : s.is_pwo) {f : α → β} (hf : monotone f) : is_pwo (f '' s) :=
hs.image_of_monotone_on (hf.monotone_on _)
protected lemma is_pwo.union (hs : is_pwo s) (ht : is_pwo t) : is_pwo (s ∪ t) := hs.union ht
@[simp] lemma is_pwo_union : is_pwo (s ∪ t) ↔ is_pwo s ∧ is_pwo t := partially_well_ordered_on_union
protected lemma finite.is_pwo (hs : s.finite) : is_pwo s := hs.partially_well_ordered_on
@[simp] lemma is_pwo_of_finite [finite α] : s.is_pwo := s.to_finite.is_pwo
@[simp] lemma is_pwo_singleton (a : α) : is_pwo ({a} : set α) := (finite_singleton a).is_pwo
@[simp] lemma is_pwo_empty : is_pwo (∅ : set α) := finite_empty.is_pwo
protected lemma subsingleton.is_pwo (hs : s.subsingleton) : is_pwo s := hs.finite.is_pwo
@[simp] lemma is_pwo_insert {a} : is_pwo (insert a s) ↔ is_pwo s :=
by simp only [←singleton_union, is_pwo_union, is_pwo_singleton, true_and]
protected lemma is_pwo.insert (h : is_pwo s) (a : α) : is_pwo (insert a s) := is_pwo_insert.2 h
protected lemma finite.is_wf (hs : s.finite) : is_wf s := hs.is_pwo.is_wf
@[simp] lemma is_wf_singleton {a : α} : is_wf ({a} : set α) := (finite_singleton a).is_wf
protected lemma subsingleton.is_wf (hs : s.subsingleton) : is_wf s := hs.is_pwo.is_wf
@[simp] lemma is_wf_insert {a} : is_wf (insert a s) ↔ is_wf s :=
by simp only [←singleton_union, is_wf_union, is_wf_singleton, true_and]
lemma is_wf.insert (h : is_wf s) (a : α) : is_wf (insert a s) := is_wf_insert.2 h
end is_pwo
section well_founded_on
variables {r : α → α → Prop} [is_strict_order α r] {s : set α} {a : α}
protected lemma finite.well_founded_on (hs : s.finite) : s.well_founded_on r :=
by { letI := partial_order_of_SO r, exact hs.is_wf }
@[simp] lemma well_founded_on_singleton : well_founded_on ({a} : set α) r :=
(finite_singleton a).well_founded_on
protected lemma subsingleton.well_founded_on (hs : s.subsingleton) : s.well_founded_on r :=
hs.finite.well_founded_on
@[simp] lemma well_founded_on_insert : well_founded_on (insert a s) r ↔ well_founded_on s r :=
by simp only [←singleton_union, well_founded_on_union, well_founded_on_singleton, true_and]
lemma well_founded_on.insert (h : well_founded_on s r) (a : α) : well_founded_on (insert a s) r :=
well_founded_on_insert.2 h
end well_founded_on
section linear_order
variables [linear_order α] {s : set α}
protected lemma is_wf.is_pwo (hs : s.is_wf) : s.is_pwo :=
begin
intros f hf,
lift f to ℕ → s using hf,
have hrange : (range f).nonempty := range_nonempty _,
rcases hs.has_min (range f) (range_nonempty _) with ⟨_, ⟨m, rfl⟩, hm⟩,
simp only [forall_range_iff, not_lt] at hm,
exact ⟨m, m + 1, lt_add_one m, hm _⟩,
end
/-- In a linear order, the predicates `set.is_wf` and `set.is_pwo` are equivalent. -/
lemma is_wf_iff_is_pwo : s.is_wf ↔ s.is_pwo := ⟨is_wf.is_pwo, is_pwo.is_wf⟩
end linear_order
end set
namespace finset
variables {r : α → α → Prop}
@[simp] protected lemma partially_well_ordered_on [is_refl α r] (s : finset α) :
(s : set α).partially_well_ordered_on r :=
s.finite_to_set.partially_well_ordered_on
@[simp] protected lemma is_pwo [preorder α] (s : finset α) : set.is_pwo (↑s : set α) :=
s.partially_well_ordered_on
@[simp] protected lemma is_wf [preorder α] (s : finset α) : set.is_wf (↑s : set α) :=
s.finite_to_set.is_wf
@[simp] protected lemma well_founded_on [is_strict_order α r] (s : finset α) :
set.well_founded_on (↑s : set α) r :=
by { letI := partial_order_of_SO r, exact s.is_wf }
lemma well_founded_on_sup [is_strict_order α r] (s : finset ι) {f : ι → set α} :
(s.sup f).well_founded_on r ↔ ∀ i ∈ s, (f i).well_founded_on r :=
finset.cons_induction_on s (by simp) $ λ a s ha hs, by simp [-sup_set_eq_bUnion, hs]
lemma partially_well_ordered_on_sup (s : finset ι) {f : ι → set α} :
(s.sup f).partially_well_ordered_on r ↔ ∀ i ∈ s, (f i).partially_well_ordered_on r :=
finset.cons_induction_on s (by simp) $ λ a s ha hs, by simp [-sup_set_eq_bUnion, hs]
lemma is_wf_sup [preorder α] (s : finset ι) {f : ι → set α} :
(s.sup f).is_wf ↔ ∀ i ∈ s, (f i).is_wf :=
s.well_founded_on_sup
lemma is_pwo_sup [preorder α] (s : finset ι) {f : ι → set α} :
(s.sup f).is_pwo ↔ ∀ i ∈ s, (f i).is_pwo :=
s.partially_well_ordered_on_sup
@[simp] lemma well_founded_on_bUnion [is_strict_order α r] (s : finset ι) {f : ι → set α} :
(⋃ i ∈ s, f i).well_founded_on r ↔ ∀ i ∈ s, (f i).well_founded_on r :=
by simpa only [finset.sup_eq_supr] using s.well_founded_on_sup
@[simp] lemma partially_well_ordered_on_bUnion (s : finset ι) {f : ι → set α} :
(⋃ i ∈ s, f i).partially_well_ordered_on r ↔ ∀ i ∈ s, (f i).partially_well_ordered_on r :=
by simpa only [finset.sup_eq_supr] using s.partially_well_ordered_on_sup
@[simp] lemma is_wf_bUnion [preorder α] (s : finset ι) {f : ι → set α} :
(⋃ i ∈ s, f i).is_wf ↔ ∀ i ∈ s, (f i).is_wf :=
s.well_founded_on_bUnion
@[simp] lemma is_pwo_bUnion [preorder α] (s : finset ι) {f : ι → set α} :
(⋃ i ∈ s, f i).is_pwo ↔ ∀ i ∈ s, (f i).is_pwo :=
s.partially_well_ordered_on_bUnion
end finset
namespace set
section preorder
variables [preorder α] {s : set α} {a : α}
/-- `is_wf.min` returns a minimal element of a nonempty well-founded set. -/
noncomputable def is_wf.min (hs : is_wf s) (hn : s.nonempty) : α :=
hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)
lemma is_wf.min_mem (hs : is_wf s) (hn : s.nonempty) : hs.min hn ∈ s :=
(well_founded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2
lemma is_wf.not_lt_min (hs : is_wf s) (hn : s.nonempty) (ha : a ∈ s) : ¬ a < hs.min hn :=
hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s))
@[simp]
lemma is_wf_min_singleton (a) {hs : is_wf ({a} : set α)} {hn : ({a} : set α).nonempty} :
hs.min hn = a :=
eq_of_mem_singleton (is_wf.min_mem hs hn)
end preorder
section linear_order
variables [linear_order α] {s t : set α} {a : α}
lemma is_wf.min_le (hs : s.is_wf) (hn : s.nonempty) (ha : a ∈ s) : hs.min hn ≤ a :=
le_of_not_lt (hs.not_lt_min hn ha)
lemma is_wf.le_min_iff (hs : s.is_wf) (hn : s.nonempty) : a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b :=
⟨λ ha b hb, le_trans ha (hs.min_le hn hb), λ h, h _ (hs.min_mem _)⟩
lemma is_wf.min_le_min_of_subset
{hs : s.is_wf} {hsn : s.nonempty} {ht : t.is_wf} {htn : t.nonempty} (hst : s ⊆ t) :
ht.min htn ≤ hs.min hsn :=
(is_wf.le_min_iff _ _).2 (λ b hb, ht.min_le htn (hst hb))
lemma is_wf.min_union (hs : s.is_wf) (hsn : s.nonempty) (ht : t.is_wf) (htn : t.nonempty) :
(hs.union ht).min (union_nonempty.2 (or.intro_left _ hsn)) = min (hs.min hsn) (ht.min htn) :=
begin
refine le_antisymm (le_min (is_wf.min_le_min_of_subset (subset_union_left _ _))
(is_wf.min_le_min_of_subset (subset_union_right _ _))) _,
rw min_le_iff,
exact ((mem_union _ _ _).1 ((hs.union ht).min_mem
(union_nonempty.2 (or.intro_left _ hsn)))).imp (hs.min_le _) (ht.min_le _),
end
end linear_order
end set
open set
namespace set.partially_well_ordered_on
variables {r : α → α → Prop}
/-- In the context of partial well-orderings, a bad sequence is a nonincreasing sequence
whose range is contained in a particular set `s`. One exists if and only if `s` is not
partially well-ordered. -/
def is_bad_seq (r : α → α → Prop) (s : set α) (f : ℕ → α) : Prop :=
(∀ n, f n ∈ s) ∧ ∀ m n : ℕ, m < n → ¬ r (f m) (f n)
lemma iff_forall_not_is_bad_seq (r : α → α → Prop) (s : set α) :
s.partially_well_ordered_on r ↔ ∀ f, ¬ is_bad_seq r s f :=
forall_congr $ λ f, by simp [is_bad_seq]
/-- This indicates that every bad sequence `g` that agrees with `f` on the first `n`
terms has `rk (f n) ≤ rk (g n)`. -/
def is_min_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) : Prop :=
∀ g : ℕ → α, (∀ (m : ℕ), m < n → f m = g m) → rk (g n) < rk (f n) → ¬ is_bad_seq r s g
/-- Given a bad sequence `f`, this constructs a bad sequence that agrees with `f` on the first `n`
terms and is minimal at `n`.
-/
noncomputable def min_bad_seq_of_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α)
(n : ℕ) (f : ℕ → α) (hf : is_bad_seq r s f) :
{ g : ℕ → α // (∀ (m : ℕ), m < n → f m = g m) ∧ is_bad_seq r s g ∧ is_min_bad_seq r rk s n g } :=
begin
classical,
have h : ∃ (k : ℕ) (g : ℕ → α), (∀ m, m < n → f m = g m) ∧ is_bad_seq r s g
∧ rk (g n) = k :=
⟨_, f, λ _ _, rfl, hf, rfl⟩,
obtain ⟨h1, h2, h3⟩ := classical.some_spec (nat.find_spec h),
refine ⟨classical.some (nat.find_spec h), h1, by convert h2, λ g hg1 hg2 con, _⟩,
refine nat.find_min h _ ⟨g, λ m mn, (h1 m mn).trans (hg1 m mn), by convert con, rfl⟩,
rwa ← h3,
end
lemma exists_min_bad_of_exists_bad (r : α → α → Prop) (rk : α → ℕ) (s : set α) :
(∃ f, is_bad_seq r s f) → ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f :=
begin
rintro ⟨f0, (hf0 : is_bad_seq r s f0)⟩,
let fs : Π (n : ℕ), { f : ℕ → α // is_bad_seq r s f ∧ is_min_bad_seq r rk s n f },
{ refine nat.rec _ _,
{ exact ⟨(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).1,
(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).2.2⟩, },
{ exact λ n fn, ⟨(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).1,
(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).2.2⟩ } },
have h : ∀ m n, m ≤ n → (fs m).1 m = (fs n).1 m,
{ intros m n mn,
obtain ⟨k, rfl⟩ := exists_add_of_le mn,
clear mn,
induction k with k ih,
{ refl },
rw [ih, ((min_bad_seq_of_bad_seq r rk s (m + k).succ (fs (m + k)).1 (fs (m + k)).2.1).2.1 m
(nat.lt_succ_iff.2 (nat.add_le_add_left k.zero_le m)))],
refl },
refine ⟨λ n, (fs n).1 n, ⟨(λ n, ((fs n).2).1.1 n), λ m n mn, _⟩, λ n g hg1 hg2, _⟩,
{ dsimp,
rw [← subtype.val_eq_coe, h m n (le_of_lt mn)],
convert (fs n).2.1.2 m n mn },
{ convert (fs n).2.2 g (λ m mn, eq.trans _ (hg1 m mn)) (lt_of_lt_of_le hg2 le_rfl),
rw ← h m n (le_of_lt mn) },
end
lemma iff_not_exists_is_min_bad_seq (rk : α → ℕ) {s : set α} :
s.partially_well_ordered_on r ↔ ¬ ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f :=
begin
rw [iff_forall_not_is_bad_seq, ← not_exists, not_congr],
split,
{ apply exists_min_bad_of_exists_bad },
rintro ⟨f, hf1, hf2⟩,
exact ⟨f, hf1⟩,
end
/-- Higman's Lemma, which states that for any reflexive, transitive relation `r` which is
partially well-ordered on a set `s`, the relation `list.sublist_forall₂ r` is partially
well-ordered on the set of lists of elements of `s`. That relation is defined so that
`list.sublist_forall₂ r l₁ l₂` whenever `l₁` related pointwise by `r` to a sublist of `l₂`. -/
lemma partially_well_ordered_on_sublist_forall₂ (r : α → α → Prop) [is_refl α r] [is_trans α r]
{s : set α} (h : s.partially_well_ordered_on r) :
{ l : list α | ∀ x, x ∈ l → x ∈ s }.partially_well_ordered_on (list.sublist_forall₂ r) :=
begin
rcases s.eq_empty_or_nonempty with rfl | ⟨as, has⟩,
{ apply partially_well_ordered_on.mono (finset.partially_well_ordered_on {list.nil}),
{ intros l hl,
rw [finset.mem_coe, finset.mem_singleton, list.eq_nil_iff_forall_not_mem],
exact hl, },
apply_instance },
haveI : inhabited α := ⟨as⟩,
rw [iff_not_exists_is_min_bad_seq (list.length)],
rintro ⟨f, hf1, hf2⟩,
have hnil : ∀ n, f n ≠ list.nil :=
λ n con, (hf1).2 n n.succ n.lt_succ_self (con.symm ▸ list.sublist_forall₂.nil),
obtain ⟨g, hg⟩ := h.exists_monotone_subseq (list.head ∘ f) _,
swap, { simp only [set.range_subset_iff, function.comp_apply],
exact λ n, hf1.1 n _ (list.head_mem_self (hnil n)) },
have hf' := hf2 (g 0) (λ n, if n < g 0 then f n else list.tail (f (g (n - g 0))))
(λ m hm, (if_pos hm).symm) _,
swap, { simp only [if_neg (lt_irrefl (g 0)), tsub_self],
rw [list.length_tail, ← nat.pred_eq_sub_one],
exact nat.pred_lt (λ con, hnil _ (list.length_eq_zero.1 con)) },
rw [is_bad_seq] at hf',
push_neg at hf',
obtain ⟨m, n, mn, hmn⟩ := hf' _,
swap,
{ rintro n x hx,
split_ifs at hx with hn hn,
{ exact hf1.1 _ _ hx },
{ refine hf1.1 _ _ (list.tail_subset _ hx), } },
by_cases hn : n < g 0,
{ apply hf1.2 m n mn,
rwa [if_pos hn, if_pos (mn.trans hn)] at hmn },
{ obtain ⟨n', rfl⟩ := exists_add_of_le (not_lt.1 hn),
rw [if_neg hn, add_comm (g 0) n', add_tsub_cancel_right] at hmn,
split_ifs at hmn with hm hm,
{ apply hf1.2 m (g n') (lt_of_lt_of_le hm (g.monotone n'.zero_le)),
exact trans hmn (list.tail_sublist_forall₂_self _) },
{ rw [← (tsub_lt_iff_left (le_of_not_lt hm))] at mn,
apply hf1.2 _ _ (g.lt_iff_lt.2 mn),
rw [← list.cons_head_tail (hnil (g (m - g 0))), ← list.cons_head_tail (hnil (g n'))],
exact list.sublist_forall₂.cons (hg _ _ (le_of_lt mn)) hmn, } }
end
end set.partially_well_ordered_on
lemma well_founded.is_wf [has_lt α] (h : well_founded ((<) : α → α → Prop)) (s : set α) : s.is_wf :=
(set.is_wf_univ_iff.2 h).mono s.subset_univ
/-- A version of **Dickson's lemma** any subset of functions `Π s : σ, α s` is partially well
ordered, when `σ` is a `fintype` and each `α s` is a linear well order.
This includes the classical case of Dickson's lemma that `ℕ ^ n` is a well partial order.
Some generalizations would be possible based on this proof, to include cases where the target is
partially well ordered, and also to consider the case of `set.partially_well_ordered_on` instead of
`set.is_pwo`. -/
lemma pi.is_pwo {α : ι → Type*} [Π i, linear_order (α i)] [∀ i, is_well_order (α i) (<)] [finite ι]
(s : set (Π i, α i)) : s.is_pwo :=
begin
casesI nonempty_fintype ι,
suffices : ∀ s : finset ι, ∀ (f : ℕ → Π s, α s), ∃ g : ℕ ↪o ℕ,
∀ ⦃a b : ℕ⦄, a ≤ b → ∀ (x : ι) (hs : x ∈ s), (f ∘ g) a x ≤ (f ∘ g) b x,
{ refine is_pwo_iff_exists_monotone_subseq.2 (λ f hf, _),
simpa only [finset.mem_univ, true_implies_iff] using this finset.univ f },
refine finset.cons_induction _ _,
{ intros f, existsi rel_embedding.refl (≤),
simp only [is_empty.forall_iff, implies_true_iff, forall_const, finset.not_mem_empty], },
{ intros x s hx ih f,
obtain ⟨g, hg⟩ := (is_well_founded.wf.is_wf univ).is_pwo.exists_monotone_subseq (λ n, f n x)
mem_univ,
obtain ⟨g', hg'⟩ := ih (f ∘ g),
refine ⟨g'.trans g, λ a b hab, (finset.forall_mem_cons _ _).2 _⟩,
exact ⟨hg (order_hom_class.mono g' hab), hg' hab⟩ }
end
|
1f0fc176f76a01dbd933a1a5c8d0292c35274f7f | d9ed0fce1c218297bcba93e046cb4e79c83c3af8 | /library/init/data/int/default.lean | fe5a3c761e419f77adaf60a5fc6076954fe623f2 | [
"Apache-2.0"
] | permissive | leodemoura/lean_clone | 005c63aa892a6492f2d4741ee3c2cb07a6be9d7f | cc077554b584d39bab55c360bc12a6fe7957afe6 | refs/heads/master | 1,610,506,475,484 | 1,482,348,354,000 | 1,482,348,543,000 | 77,091,586 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 219 | 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.data.int.basic init.data.int.order
|
0d0666580f44b26944a333ac310f41abe2ae7e15 | f7315930643edc12e76c229a742d5446dad77097 | /library/data/int/order.lean | 498daab89d28b4023ee1e74e2fd11f06761576fb | [
"Apache-2.0"
] | permissive | bmalehorn/lean | 8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1 | 53653c352643751c4b62ff63ec5e555f11dae8eb | refs/heads/master | 1,610,945,684,489 | 1,429,681,220,000 | 1,429,681,449,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,017 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.int.order
Authors: Floris van Doorn, Jeremy Avigad
The order relation on the integers. We show that int is an instance of linear_comm_ordered_ring
and transfer the results.
-/
import .basic algebra.ordered_ring
open nat
open decidable
open fake_simplifier
open int eq.ops
namespace int
private definition nonneg (a : ℤ) : Prop := int.cases_on a (take n, true) (take n, false)
definition le (a b : ℤ) : Prop := nonneg (sub b a)
definition lt (a b : ℤ) : Prop := le (add a 1) b
infix - := int.sub
infix <= := int.le
infix ≤ := int.le
infix < := int.lt
local attribute nonneg [reducible]
private definition decidable_nonneg [instance] (a : ℤ) : decidable (nonneg a) := int.cases_on a _ _
definition decidable_le [instance] (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _
definition decidable_lt [instance] (a b : ℤ) : decidable (a < b) := decidable_nonneg _
private theorem nonneg.elim {a : ℤ} : nonneg a → ∃n : ℕ, a = n :=
int.cases_on a (take n H, exists.intro n rfl) (take n' H, false.elim H)
private theorem nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) :=
int.cases_on a (take n, or.inl trivial) (take n, or.inr trivial)
theorem le.intro {a b : ℤ} {n : ℕ} (H : a + n = b) : a ≤ b :=
have H1 : b - a = n, from (eq_add_neg_of_add_eq (!add.comm ▸ H))⁻¹,
have H2 : nonneg n, from true.intro,
show nonneg (b - a), from H1⁻¹ ▸ H2
theorem le.elim {a b : ℤ} (H : a ≤ b) : ∃n : ℕ, a + n = b :=
obtain (n : ℕ) (H1 : b - a = n), from nonneg.elim H,
exists.intro n (!add.comm ▸ iff.mp' !add_eq_iff_eq_add_neg (H1⁻¹))
theorem le.total (a b : ℤ) : a ≤ b ∨ b ≤ a :=
or.elim (nonneg_or_nonneg_neg (b - a))
(assume H, or.inl H)
(assume H : nonneg (-(b - a)),
have H0 : -(b - a) = a - b, from neg_sub b a,
have H1 : nonneg (a - b), from H0 ▸ H, -- too bad: can't do it in one step
or.inr H1)
theorem of_nat_le_of_nat {m n : ℕ} (H : #nat m ≤ n) : of_nat m ≤ of_nat n :=
obtain (k : ℕ) (Hk : m + k = n), from nat.le.elim H,
le.intro (Hk ▸ of_nat_add_of_nat m k)
theorem le_of_of_nat_le_of_nat {m n : ℕ} (H : of_nat m ≤ of_nat n) : (#nat m ≤ n) :=
obtain (k : ℕ) (Hk : of_nat m + of_nat k = of_nat n), from le.elim H,
have H1 : m + k = n, from of_nat.inj ((of_nat_add_of_nat m k)⁻¹ ⬝ Hk),
nat.le.intro H1
theorem of_nat_le_of_nat_iff (m n : ℕ) : of_nat m ≤ of_nat n ↔ m ≤ n :=
iff.intro le_of_of_nat_le_of_nat of_nat_le_of_nat
theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + succ n :=
le.intro (show a + 1 + n = a + succ n, from
calc
a + 1 + n = a + (1 + n) : add.assoc
... = a + (n + 1) : nat.add.comm
... = a + succ n : rfl)
theorem lt.intro {a b : ℤ} {n : ℕ} (H : a + succ n = b) : a < b :=
H ▸ lt_add_succ a n
theorem lt.elim {a b : ℤ} (H : a < b) : ∃n : ℕ, a + succ n = b :=
obtain (n : ℕ) (Hn : a + 1 + n = b), from le.elim H,
have H2 : a + succ n = b, from
calc
a + succ n = a + 1 + n : by simp
... = b : Hn,
exists.intro n H2
theorem of_nat_lt_of_nat_iff (n m : ℕ) : of_nat n < of_nat m ↔ n < m :=
calc
of_nat n < of_nat m ↔ of_nat n + 1 ≤ of_nat m : iff.refl
... ↔ of_nat (succ n) ≤ of_nat m : of_nat_succ n ▸ !iff.refl
... ↔ succ n ≤ m : of_nat_le_of_nat_iff
... ↔ n < m : iff.symm (lt_iff_succ_le _ _)
theorem lt_of_of_nat_lt_of_nat {m n : ℕ} (H : of_nat m < of_nat n) : #nat m < n :=
iff.mp !of_nat_lt_of_nat_iff H
theorem of_nat_lt_of_nat {m n : ℕ} (H : #nat m < n) : of_nat m < of_nat n :=
iff.mp' !of_nat_lt_of_nat_iff H
/- show that the integers form an ordered additive group -/
theorem le.refl (a : ℤ) : a ≤ a :=
le.intro (add_zero a)
theorem le.trans {a b c : ℤ} (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c :=
obtain (n : ℕ) (Hn : a + n = b), from le.elim H1,
obtain (m : ℕ) (Hm : b + m = c), from le.elim H2,
have H3 : a + of_nat (n + m) = c, from
calc
a + of_nat (n + m) = a + (of_nat n + m) : {(of_nat_add_of_nat n m)⁻¹}
... = a + n + m : (add.assoc a n m)⁻¹
... = b + m : {Hn}
... = c : Hm,
le.intro H3
theorem le.antisymm : ∀ {a b : ℤ}, a ≤ b → b ≤ a → a = b :=
take a b : ℤ, assume (H₁ : a ≤ b) (H₂ : b ≤ a),
obtain (n : ℕ) (Hn : a + n = b), from le.elim H₁,
obtain (m : ℕ) (Hm : b + m = a), from le.elim H₂,
have H₃ : a + of_nat (n + m) = a + 0, from
calc
a + of_nat (n + m) = a + (of_nat n + m) : of_nat_add_of_nat
... = a + n + m : add.assoc
... = b + m : Hn
... = a : Hm
... = a + 0 : add_zero,
have H₄ : of_nat (n + m) = of_nat 0, from add.left_cancel H₃,
have H₅ : n + m = 0, from of_nat.inj H₄,
have H₆ : n = 0, from nat.eq_zero_of_add_eq_zero_right H₅,
show a = b, from
calc
a = a + 0 : add_zero
... = a + n : H₆
... = b : Hn
theorem lt.irrefl (a : ℤ) : ¬ a < a :=
(assume H : a < a,
obtain (n : ℕ) (Hn : a + succ n = a), from lt.elim H,
have H2 : a + succ n = a + 0, from
calc
a + succ n = a : Hn
... = a + 0 : by simp,
have H3 : succ n = 0, from add.left_cancel H2,
have H4 : succ n = 0, from of_nat.inj H3,
absurd H4 !succ_ne_zero)
theorem ne_of_lt {a b : ℤ} (H : a < b) : a ≠ b :=
(assume H2 : a = b, absurd (H2 ▸ H) (lt.irrefl b))
theorem succ_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := H
theorem lt_of_le_succ {a b : ℤ} (H : a + 1 ≤ b) : a < b := H
theorem le_of_lt {a b : ℤ} (H : a < b) : a ≤ b :=
obtain (n : ℕ) (Hn : a + succ n = b), from lt.elim H,
le.intro Hn
theorem lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) :=
iff.intro
(assume H, and.intro (le_of_lt H) (ne_of_lt H))
(assume H,
have H1 : a ≤ b, from and.elim_left H,
have H2 : a ≠ b, from and.elim_right H,
obtain (n : ℕ) (Hn : a + n = b), from le.elim H1,
have H3 : n ≠ 0, from (assume H' : n = 0, H2 (!add_zero ▸ H' ▸ Hn)),
obtain (k : ℕ) (Hk : n = succ k), from nat.exists_eq_succ_of_ne_zero H3,
lt.intro (Hk ▸ Hn))
theorem le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) :=
iff.intro
(assume H,
by_cases
(assume H1 : a = b, or.inr H1)
(assume H1 : a ≠ b,
obtain (n : ℕ) (Hn : a + n = b), from le.elim H,
have H2 : n ≠ 0, from (assume H' : n = 0, H1 (!add_zero ▸ H' ▸ Hn)),
obtain (k : ℕ) (Hk : n = succ k), from nat.exists_eq_succ_of_ne_zero H2,
or.inl (lt.intro (Hk ▸ Hn))))
(assume H,
or.elim H
(assume H1, le_of_lt H1)
(assume H1, H1 ▸ !le.refl))
theorem lt_succ (a : ℤ) : a < a + 1 :=
le.refl (a + 1)
theorem add_le_add_left {a b : ℤ} (H : a ≤ b) (c : ℤ) : c + a ≤ c + b :=
obtain (n : ℕ) (Hn : a + n = b), from le.elim H,
have H2 : c + a + n = c + b, from
calc
c + a + n = c + (a + n) : add.assoc c a n
... = c + b : {Hn},
le.intro H2
theorem mul_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a * b :=
obtain (n : ℕ) (Hn : 0 + n = a), from le.elim Ha,
obtain (m : ℕ) (Hm : 0 + m = b), from le.elim Hb,
le.intro
(eq.symm
(calc
a * b = (0 + n) * b : Hn
... = n * b : nat.zero_add
... = n * (0 + m) : {Hm⁻¹}
... = n * m : nat.zero_add
... = 0 + n * m : zero_add))
theorem mul_pos {a b : ℤ} (Ha : 0 < a) (Hb : 0 < b) : 0 < a * b :=
obtain (n : ℕ) (Hn : 0 + succ n = a), from lt.elim Ha,
obtain (m : ℕ) (Hm : 0 + succ m = b), from lt.elim Hb,
lt.intro
(eq.symm
(calc
a * b = (0 + succ n) * b : Hn
... = succ n * b : nat.zero_add
... = succ n * (0 + succ m) : {Hm⁻¹}
... = succ n * succ m : nat.zero_add
... = of_nat (succ n * succ m) : of_nat_mul_of_nat
... = of_nat (succ n * m + succ n) : nat.mul_succ
... = of_nat (succ (succ n * m + n)) : nat.add_succ
... = 0 + succ (succ n * m + n) : zero_add))
section
open [classes] algebra
protected definition linear_ordered_comm_ring [instance] [reducible] :
algebra.linear_ordered_comm_ring int :=
⦃algebra.linear_ordered_comm_ring, int.integral_domain,
le := le,
le_refl := le.refl,
le_trans := @le.trans,
le_antisymm := @le.antisymm,
lt := lt,
lt_iff_le_ne := lt_iff_le_and_ne,
add_le_add_left := @add_le_add_left,
mul_nonneg := @mul_nonneg,
mul_pos := @mul_pos,
le_iff_lt_or_eq := le_iff_lt_or_eq,
le_total := le.total,
zero_ne_one := zero_ne_one⦄
protected definition decidable_linear_ordered_comm_ring [instance] [reducible] :
algebra.decidable_linear_ordered_comm_ring int :=
⦃algebra.decidable_linear_ordered_comm_ring,
int.linear_ordered_comm_ring,
decidable_lt := decidable_lt⦄
end
/- instantiate ordered ring theorems to int -/
section port_algebra
open [classes] algebra
definition ge [reducible] (a b : ℤ) := algebra.has_le.ge a b
definition gt [reducible] (a b : ℤ) := algebra.has_lt.gt a b
infix >= := int.ge
infix ≥ := int.ge
infix > := int.gt
definition decidable_ge [instance] (a b : ℤ) : decidable (a ≥ b) :=
show decidable (b ≤ a), from _
definition decidable_gt [instance] (a b : ℤ) : decidable (a > b) :=
show decidable (b < a), from _
theorem ge.trans: ∀{a b c : ℤ}, a ≥ b → b ≥ c → a ≥ c := @algebra.ge.trans _ _
theorem gt.trans: ∀{a b c : ℤ}, a > b → b > c → a > c := @algebra.gt.trans _ _
theorem ne_of_gt: ∀{a b : ℤ}, a > b → a ≠ b := @algebra.ne_of_gt _ _
theorem gt_of_gt_of_ge : ∀{a b c : ℤ}, a > b → b ≥ c → a > c := @algebra.gt_of_gt_of_ge _ _
theorem gt_of_ge_of_gt : ∀{a b c : ℤ}, a ≥ b → b > c → a > c := @algebra.gt_of_ge_of_gt _ _
theorem lt.asymm : ∀{a b : ℤ}, a < b → ¬ b < a := @algebra.lt.asymm _ _
theorem lt_of_le_of_ne : ∀{a b : ℤ}, a ≤ b → a ≠ b → a < b := @algebra.lt_of_le_of_ne _ _
theorem lt_of_lt_of_le : ∀{a b c : ℤ}, a < b → b ≤ c → a < c := @algebra.lt_of_lt_of_le _ _
theorem lt_of_le_of_lt : ∀{a b c : ℤ}, a ≤ b → b < c → a < c := @algebra.lt_of_le_of_lt _ _
theorem not_le_of_lt : ∀{a b : ℤ}, a < b → ¬ b ≤ a := @algebra.not_le_of_lt _ _
theorem not_lt_of_le : ∀{a b : ℤ}, a ≤ b → ¬ b < a := @algebra.not_lt_of_le _ _
theorem lt_or_eq_of_le : ∀{a b : ℤ}, a ≤ b → a < b ∨ a = b := @algebra.lt_or_eq_of_le _ _
theorem lt.trichotomy : ∀a b : ℤ, a < b ∨ a = b ∨ b < a := algebra.lt.trichotomy
theorem lt.by_cases : ∀{a b : ℤ} {P : Prop}, (a < b → P) → (a = b → P) → (b < a → P) → P :=
@algebra.lt.by_cases _ _
theorem le_of_not_lt : ∀{a b : ℤ}, ¬ a < b → b ≤ a := @algebra.le_of_not_lt _ _
theorem lt_of_not_le : ∀{a b : ℤ}, ¬ a ≤ b → b < a := @algebra.lt_of_not_le _ _
theorem lt_or_ge : ∀a b : ℤ, a < b ∨ a ≥ b := @algebra.lt_or_ge _ _
theorem le_or_gt : ∀a b : ℤ, a ≤ b ∨ a > b := @algebra.le_or_gt _ _
theorem lt_or_gt_of_ne : ∀{a b : ℤ}, a ≠ b → a < b ∨ a > b := @algebra.lt_or_gt_of_ne _ _
theorem add_le_add_right : ∀{a b : ℤ}, a ≤ b → ∀c : ℤ, a + c ≤ b + c :=
@algebra.add_le_add_right _ _
theorem add_le_add : ∀{a b c d : ℤ}, a ≤ b → c ≤ d → a + c ≤ b + d := @algebra.add_le_add _ _
theorem add_lt_add_left : ∀{a b : ℤ}, a < b → ∀c : ℤ, c + a < c + b :=
@algebra.add_lt_add_left _ _
theorem add_lt_add_right : ∀{a b : ℤ}, a < b → ∀c : ℤ, a + c < b + c :=
@algebra.add_lt_add_right _ _
theorem le_add_of_nonneg_right : ∀{a b : ℤ}, b ≥ 0 → a ≤ a + b :=
@algebra.le_add_of_nonneg_right _ _
theorem le_add_of_nonneg_left : ∀{a b : ℤ}, b ≥ 0 → a ≤ b + a :=
@algebra.le_add_of_nonneg_left _ _
theorem add_lt_add : ∀{a b c d : ℤ}, a < b → c < d → a + c < b + d := @algebra.add_lt_add _ _
theorem add_lt_add_of_le_of_lt : ∀{a b c d : ℤ}, a ≤ b → c < d → a + c < b + d :=
@algebra.add_lt_add_of_le_of_lt _ _
theorem add_lt_add_of_lt_of_le : ∀{a b c d : ℤ}, a < b → c ≤ d → a + c < b + d :=
@algebra.add_lt_add_of_lt_of_le _ _
theorem lt_add_of_pos_right : ∀{a b : ℤ}, b > 0 → a < a + b := @algebra.lt_add_of_pos_right _ _
theorem lt_add_of_pos_left : ∀{a b : ℤ}, b > 0 → a < b + a := @algebra.lt_add_of_pos_left _ _
theorem le_of_add_le_add_left : ∀{a b c : ℤ}, a + b ≤ a + c → b ≤ c :=
@algebra.le_of_add_le_add_left _ _
theorem le_of_add_le_add_right : ∀{a b c : ℤ}, a + b ≤ c + b → a ≤ c :=
@algebra.le_of_add_le_add_right _ _
theorem lt_of_add_lt_add_left : ∀{a b c : ℤ}, a + b < a + c → b < c :=
@algebra.lt_of_add_lt_add_left _ _
theorem lt_of_add_lt_add_right : ∀{a b c : ℤ}, a + b < c + b → a < c :=
@algebra.lt_of_add_lt_add_right _ _
theorem add_le_add_left_iff : ∀a b c : ℤ, a + b ≤ a + c ↔ b ≤ c := algebra.add_le_add_left_iff
theorem add_le_add_right_iff : ∀a b c : ℤ, a + b ≤ c + b ↔ a ≤ c := algebra.add_le_add_right_iff
theorem add_lt_add_left_iff : ∀a b c : ℤ, a + b < a + c ↔ b < c := algebra.add_lt_add_left_iff
theorem add_lt_add_right_iff : ∀a b c : ℤ, a + b < c + b ↔ a < c := algebra.add_lt_add_right_iff
theorem add_nonneg : ∀{a b : ℤ}, 0 ≤ a → 0 ≤ b → 0 ≤ a + b := @algebra.add_nonneg _ _
theorem add_pos : ∀{a b : ℤ}, 0 < a → 0 < b → 0 < a + b := @algebra.add_pos _ _
theorem add_pos_of_pos_of_nonneg : ∀{a b : ℤ}, 0 < a → 0 ≤ b → 0 < a + b :=
@algebra.add_pos_of_pos_of_nonneg _ _
theorem add_pos_of_nonneg_of_pos : ∀{a b : ℤ}, 0 ≤ a → 0 < b → 0 < a + b :=
@algebra.add_pos_of_nonneg_of_pos _ _
theorem add_nonpos : ∀{a b : ℤ}, a ≤ 0 → b ≤ 0 → a + b ≤ 0 :=
@algebra.add_nonpos _ _
theorem add_neg : ∀{a b : ℤ}, a < 0 → b < 0 → a + b < 0 :=
@algebra.add_neg _ _
theorem add_neg_of_neg_of_nonpos : ∀{a b : ℤ}, a < 0 → b ≤ 0 → a + b < 0 :=
@algebra.add_neg_of_neg_of_nonpos _ _
theorem add_neg_of_nonpos_of_neg : ∀{a b : ℤ}, a ≤ 0 → b < 0 → a + b < 0 :=
@algebra.add_neg_of_nonpos_of_neg _ _
theorem add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg : ∀{a b : ℤ},
0 ≤ a → 0 ≤ b → a + b = 0 ↔ a = 0 ∧ b = 0 :=
@algebra.add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg _ _
theorem le_add_of_nonneg_of_le : ∀{a b c : ℤ}, 0 ≤ a → b ≤ c → b ≤ a + c :=
@algebra.le_add_of_nonneg_of_le _ _
theorem le_add_of_le_of_nonneg : ∀{a b c : ℤ}, b ≤ c → 0 ≤ a → b ≤ c + a :=
@algebra.le_add_of_le_of_nonneg _ _
theorem lt_add_of_pos_of_le : ∀{a b c : ℤ}, 0 < a → b ≤ c → b < a + c :=
@algebra.lt_add_of_pos_of_le _ _
theorem lt_add_of_le_of_pos : ∀{a b c : ℤ}, b ≤ c → 0 < a → b < c + a :=
@algebra.lt_add_of_le_of_pos _ _
theorem add_le_of_nonpos_of_le : ∀{a b c : ℤ}, a ≤ 0 → b ≤ c → a + b ≤ c :=
@algebra.add_le_of_nonpos_of_le _ _
theorem add_le_of_le_of_nonpos : ∀{a b c : ℤ}, b ≤ c → a ≤ 0 → b + a ≤ c :=
@algebra.add_le_of_le_of_nonpos _ _
theorem add_lt_of_neg_of_le : ∀{a b c : ℤ}, a < 0 → b ≤ c → a + b < c :=
@algebra.add_lt_of_neg_of_le _ _
theorem add_lt_of_le_of_neg : ∀{a b c : ℤ}, b ≤ c → a < 0 → b + a < c :=
@algebra.add_lt_of_le_of_neg _ _
theorem lt_add_of_nonneg_of_lt : ∀{a b c : ℤ}, 0 ≤ a → b < c → b < a + c :=
@algebra.lt_add_of_nonneg_of_lt _ _
theorem lt_add_of_lt_of_nonneg : ∀{a b c : ℤ}, b < c → 0 ≤ a → b < c + a :=
@algebra.lt_add_of_lt_of_nonneg _ _
theorem lt_add_of_pos_of_lt : ∀{a b c : ℤ}, 0 < a → b < c → b < a + c :=
@algebra.lt_add_of_pos_of_lt _ _
theorem lt_add_of_lt_of_pos : ∀{a b c : ℤ}, b < c → 0 < a → b < c + a :=
@algebra.lt_add_of_lt_of_pos _ _
theorem add_lt_of_nonpos_of_lt : ∀{a b c : ℤ}, a ≤ 0 → b < c → a + b < c :=
@algebra.add_lt_of_nonpos_of_lt _ _
theorem add_lt_of_lt_of_nonpos : ∀{a b c : ℤ}, b < c → a ≤ 0 → b + a < c :=
@algebra.add_lt_of_lt_of_nonpos _ _
theorem add_lt_of_neg_of_lt : ∀{a b c : ℤ}, a < 0 → b < c → a + b < c :=
@algebra.add_lt_of_neg_of_lt _ _
theorem add_lt_of_lt_of_neg : ∀{a b c : ℤ}, b < c → a < 0 → b + a < c :=
@algebra.add_lt_of_lt_of_neg _ _
theorem neg_le_neg : ∀{a b : ℤ}, a ≤ b → -b ≤ -a := @algebra.neg_le_neg _ _
theorem le_of_neg_le_neg : ∀{a b : ℤ}, -b ≤ -a → a ≤ b := @algebra.le_of_neg_le_neg _ _
theorem neg_le_neg_iff_le : ∀a b : ℤ, -a ≤ -b ↔ b ≤ a := algebra.neg_le_neg_iff_le
theorem nonneg_of_neg_nonpos : ∀{a : ℤ}, -a ≤ 0 → 0 ≤ a := @algebra.nonneg_of_neg_nonpos _ _
theorem neg_nonpos_of_nonneg : ∀{a : ℤ}, 0 ≤ a → -a ≤ 0 := @algebra.neg_nonpos_of_nonneg _ _
theorem neg_nonpos_iff_nonneg : ∀a : ℤ, -a ≤ 0 ↔ 0 ≤ a := algebra.neg_nonpos_iff_nonneg
theorem nonpos_of_neg_nonneg : ∀{a : ℤ}, 0 ≤ -a → a ≤ 0 := @algebra.nonpos_of_neg_nonneg _ _
theorem neg_nonneg_of_nonpos : ∀{a : ℤ}, a ≤ 0 → 0 ≤ -a := @algebra.neg_nonneg_of_nonpos _ _
theorem neg_nonneg_iff_nonpos : ∀a : ℤ, 0 ≤ -a ↔ a ≤ 0 := algebra.neg_nonneg_iff_nonpos
theorem neg_lt_neg : ∀{a b : ℤ}, a < b → -b < -a := @algebra.neg_lt_neg _ _
theorem lt_of_neg_lt_neg : ∀{a b : ℤ}, -b < -a → a < b := @algebra.lt_of_neg_lt_neg _ _
theorem neg_lt_neg_iff_lt : ∀a b : ℤ, -a < -b ↔ b < a := algebra.neg_lt_neg_iff_lt
theorem pos_of_neg_neg : ∀{a : ℤ}, -a < 0 → 0 < a := @algebra.pos_of_neg_neg _ _
theorem neg_neg_of_pos : ∀{a : ℤ}, 0 < a → -a < 0 := @algebra.neg_neg_of_pos _ _
theorem neg_neg_iff_pos : ∀a : ℤ, -a < 0 ↔ 0 < a := algebra.neg_neg_iff_pos
theorem neg_of_neg_pos : ∀{a : ℤ}, 0 < -a → a < 0 := @algebra.neg_of_neg_pos _ _
theorem neg_pos_of_neg : ∀{a : ℤ}, a < 0 → 0 < -a := @algebra.neg_pos_of_neg _ _
theorem neg_pos_iff_neg : ∀a : ℤ, 0 < -a ↔ a < 0 := algebra.neg_pos_iff_neg
theorem le_neg_iff_le_neg : ∀a b : ℤ, a ≤ -b ↔ b ≤ -a := algebra.le_neg_iff_le_neg
theorem neg_le_iff_neg_le : ∀a b : ℤ, -a ≤ b ↔ -b ≤ a := algebra.neg_le_iff_neg_le
theorem lt_neg_iff_lt_neg : ∀a b : ℤ, a < -b ↔ b < -a := algebra.lt_neg_iff_lt_neg
theorem neg_lt_iff_neg_lt : ∀a b : ℤ, -a < b ↔ -b < a := algebra.neg_lt_iff_neg_lt
theorem sub_nonneg_iff_le : ∀a b : ℤ, 0 ≤ a - b ↔ b ≤ a := algebra.sub_nonneg_iff_le
theorem sub_nonpos_iff_le : ∀a b : ℤ, a - b ≤ 0 ↔ a ≤ b := algebra.sub_nonpos_iff_le
theorem sub_pos_iff_lt : ∀a b : ℤ, 0 < a - b ↔ b < a := algebra.sub_pos_iff_lt
theorem sub_neg_iff_lt : ∀a b : ℤ, a - b < 0 ↔ a < b := algebra.sub_neg_iff_lt
theorem add_le_iff_le_neg_add : ∀a b c : ℤ, a + b ≤ c ↔ b ≤ -a + c :=
algebra.add_le_iff_le_neg_add
theorem add_le_iff_le_sub_left : ∀a b c : ℤ, a + b ≤ c ↔ b ≤ c - a :=
algebra.add_le_iff_le_sub_left
theorem add_le_iff_le_sub_right : ∀a b c : ℤ, a + b ≤ c ↔ a ≤ c - b :=
algebra.add_le_iff_le_sub_right
theorem le_add_iff_neg_add_le : ∀a b c : ℤ, a ≤ b + c ↔ -b + a ≤ c :=
algebra.le_add_iff_neg_add_le
theorem le_add_iff_sub_left_le : ∀a b c : ℤ, a ≤ b + c ↔ a - b ≤ c :=
algebra.le_add_iff_sub_left_le
theorem le_add_iff_sub_right_le : ∀a b c : ℤ, a ≤ b + c ↔ a - c ≤ b :=
algebra.le_add_iff_sub_right_le
theorem add_lt_iff_lt_neg_add_left : ∀a b c : ℤ, a + b < c ↔ b < -a + c :=
algebra.add_lt_iff_lt_neg_add_left
theorem add_lt_iff_lt_neg_add_right : ∀a b c : ℤ, a + b < c ↔ a < -b + c :=
algebra.add_lt_iff_lt_neg_add_right
theorem add_lt_iff_lt_sub_left : ∀a b c : ℤ, a + b < c ↔ b < c - a :=
algebra.add_lt_iff_lt_sub_left
theorem add_lt_add_iff_lt_sub_right : ∀a b c : ℤ, a + b < c ↔ a < c - b :=
algebra.add_lt_add_iff_lt_sub_right
theorem lt_add_iff_neg_add_lt_left : ∀a b c : ℤ, a < b + c ↔ -b + a < c :=
algebra.lt_add_iff_neg_add_lt_left
theorem lt_add_iff_neg_add_lt_right : ∀a b c : ℤ, a < b + c ↔ -c + a < b :=
algebra.lt_add_iff_neg_add_lt_right
theorem lt_add_iff_sub_lt_left : ∀a b c : ℤ, a < b + c ↔ a - b < c :=
algebra.lt_add_iff_sub_lt_left
theorem lt_add_iff_sub_lt_right : ∀a b c : ℤ, a < b + c ↔ a - c < b :=
algebra.lt_add_iff_sub_lt_right
theorem le_iff_le_of_sub_eq_sub : ∀{a b c d : ℤ}, a - b = c - d → a ≤ b ↔ c ≤ d :=
@algebra.le_iff_le_of_sub_eq_sub _ _
theorem lt_iff_lt_of_sub_eq_sub : ∀{a b c d : ℤ}, a - b = c - d → a < b ↔ c < d :=
@algebra.lt_iff_lt_of_sub_eq_sub _ _
theorem sub_le_sub_left : ∀{a b : ℤ}, a ≤ b → ∀c : ℤ, c - b ≤ c - a :=
@algebra.sub_le_sub_left _ _
theorem sub_le_sub_right : ∀{a b : ℤ}, a ≤ b → ∀c : ℤ, a - c ≤ b - c :=
@algebra.sub_le_sub_right _ _
theorem sub_le_sub : ∀{a b c d : ℤ}, a ≤ b → c ≤ d → a - d ≤ b - c :=
@algebra.sub_le_sub _ _
theorem sub_lt_sub_left : ∀{a b : ℤ}, a < b → ∀c : ℤ, c - b < c - a :=
@algebra.sub_lt_sub_left _ _
theorem sub_lt_sub_right : ∀{a b : ℤ}, a < b → ∀c : ℤ, a - c < b - c :=
@algebra.sub_lt_sub_right _ _
theorem sub_lt_sub : ∀{a b c d : ℤ}, a < b → c < d → a - d < b - c :=
@algebra.sub_lt_sub _ _
theorem sub_lt_sub_of_le_of_lt : ∀{a b c d : ℤ}, a ≤ b → c < d → a - d < b - c :=
@algebra.sub_lt_sub_of_le_of_lt _ _
theorem sub_lt_sub_of_lt_of_le : ∀{a b c d : ℤ}, a < b → c ≤ d → a - d < b - c :=
@algebra.sub_lt_sub_of_lt_of_le _ _
theorem sub_le_self : ∀(a : ℤ) {b : ℤ}, b ≥ 0 → a - b ≤ a := algebra.sub_le_self
theorem sub_lt_self : ∀(a : ℤ) {b : ℤ}, b > 0 → a - b < a := algebra.sub_lt_self
theorem eq_zero_of_neg_eq : ∀{a : ℤ}, -a = a → a = 0 := @algebra.eq_zero_of_neg_eq _ _
definition abs : ℤ → ℤ := algebra.abs
theorem abs_of_nonneg : ∀{a : ℤ}, a ≥ 0 → abs a = a := @algebra.abs_of_nonneg _ _
theorem abs_of_pos : ∀{a : ℤ}, a > 0 → abs a = a := @algebra.abs_of_pos _ _
theorem abs_of_neg : ∀{a : ℤ}, a < 0 → abs a = -a := @algebra.abs_of_neg _ _
theorem abs_zero : abs 0 = 0 := algebra.abs_zero
theorem abs_of_nonpos : ∀{a : ℤ}, a ≤ 0 → abs a = -a := @algebra.abs_of_nonpos _ _
theorem abs_neg : ∀a : ℤ, abs (-a) = abs a := algebra.abs_neg
theorem abs_nonneg : ∀a : ℤ, abs a ≥ 0 := algebra.abs_nonneg
theorem abs_abs : ∀a : ℤ, abs (abs a) = abs a := algebra.abs_abs
theorem le_abs_self : ∀a : ℤ, a ≤ abs a := algebra.le_abs_self
theorem neg_le_abs_self : ∀a : ℤ, -a ≤ abs a := algebra.neg_le_abs_self
theorem eq_zero_of_abs_eq_zero : ∀{a : ℤ}, abs a = 0 → a = 0 := @algebra.eq_zero_of_abs_eq_zero _ _
theorem abs_eq_zero_iff_eq_zero : ∀a : ℤ, abs a = 0 ↔ a = 0 := algebra.abs_eq_zero_iff_eq_zero
theorem abs_pos_of_pos : ∀{a : ℤ}, a > 0 → abs a > 0 := @algebra.abs_pos_of_pos _ _
theorem abs_pos_of_neg : ∀{a : ℤ}, a < 0 → abs a > 0 := @algebra.abs_pos_of_neg _ _
theorem abs_pos_of_ne_zero : ∀{a : ℤ}, a ≠ 0 → abs a > 0 := @algebra.abs_pos_of_ne_zero _ _
theorem abs_sub : ∀a b : ℤ, abs (a - b) = abs (b - a) := algebra.abs_sub
theorem abs.by_cases : ∀{P : ℤ → Prop}, ∀{a : ℤ}, P a → P (-a) → P (abs a) :=
@algebra.abs.by_cases _ _
theorem abs_le_of_le_of_neg_le : ∀{a b : ℤ}, a ≤ b → -a ≤ b → abs a ≤ b :=
@algebra.abs_le_of_le_of_neg_le _ _
theorem abs_lt_of_lt_of_neg_lt : ∀{a b : ℤ}, a < b → -a < b → abs a < b :=
@algebra.abs_lt_of_lt_of_neg_lt _ _
theorem abs_add_le_abs_add_abs : ∀a b : ℤ, abs (a + b) ≤ abs a + abs b :=
algebra.abs_add_le_abs_add_abs
theorem abs_sub_abs_le_abs_sub : ∀a b : ℤ, abs a - abs b ≤ abs (a - b) :=
algebra.abs_sub_abs_le_abs_sub
theorem mul_le_mul_of_nonneg_left : ∀{a b c : ℤ}, a ≤ b → 0 ≤ c → c * a ≤ c * b :=
@algebra.mul_le_mul_of_nonneg_left _ _
theorem mul_le_mul_of_nonneg_right : ∀{a b c : ℤ}, a ≤ b → 0 ≤ c → a * c ≤ b * c :=
@algebra.mul_le_mul_of_nonneg_right _ _
theorem mul_le_mul : ∀{a b c d : ℤ}, a ≤ c → b ≤ d → 0 ≤ b → 0 ≤ c → a * b ≤ c * d :=
@algebra.mul_le_mul _ _
theorem mul_nonpos_of_nonneg_of_nonpos : ∀{a b : ℤ}, a ≥ 0 → b ≤ 0 → a * b ≤ 0 :=
@algebra.mul_nonpos_of_nonneg_of_nonpos _ _
theorem mul_nonpos_of_nonpos_of_nonneg : ∀{a b : ℤ}, a ≤ 0 → b ≥ 0 → a * b ≤ 0 :=
@algebra.mul_nonpos_of_nonpos_of_nonneg _ _
theorem mul_lt_mul_of_pos_left : ∀{a b c : ℤ}, a < b → 0 < c → c * a < c * b :=
@algebra.mul_lt_mul_of_pos_left _ _
theorem mul_lt_mul_of_pos_right : ∀{a b c : ℤ}, a < b → 0 < c → a * c < b * c :=
@algebra.mul_lt_mul_of_pos_right _ _
theorem mul_lt_mul : ∀{a b c d : ℤ}, a < c → b ≤ d → 0 < b → 0 ≤ c → a * b < c * d :=
@algebra.mul_lt_mul _ _
theorem mul_neg_of_pos_of_neg : ∀{a b : ℤ}, a > 0 → b < 0 → a * b < 0 :=
@algebra.mul_neg_of_pos_of_neg _ _
theorem mul_neg_of_neg_of_pos : ∀{a b : ℤ}, a < 0 → b > 0 → a * b < 0 :=
@algebra.mul_neg_of_neg_of_pos _ _
theorem lt_of_mul_lt_mul_left : ∀{a b c : ℤ}, c * a < c * b → c ≥ 0 → a < b :=
@algebra.lt_of_mul_lt_mul_left _ _
theorem lt_of_mul_lt_mul_right : ∀{a b c : ℤ}, a * c < b * c → c ≥ 0 → a < b :=
@algebra.lt_of_mul_lt_mul_right _ _
theorem le_of_mul_le_mul_left : ∀{a b c : ℤ}, c * a ≤ c * b → c > 0 → a ≤ b :=
@algebra.le_of_mul_le_mul_left _ _
theorem le_of_mul_le_mul_right : ∀{a b c : ℤ}, a * c ≤ b * c → c > 0 → a ≤ b :=
@algebra.le_of_mul_le_mul_right _ _
theorem pos_of_mul_pos_left : ∀{a b : ℤ}, 0 < a * b → 0 ≤ a → 0 < b :=
@algebra.pos_of_mul_pos_left _ _
theorem pos_of_mul_pos_right : ∀{a b : ℤ}, 0 < a * b → 0 ≤ b → 0 < a :=
@algebra.pos_of_mul_pos_right _ _
theorem mul_le_mul_of_nonpos_left : ∀{a b c : ℤ}, b ≤ a → c ≤ 0 → c * a ≤ c * b :=
@algebra.mul_le_mul_of_nonpos_left _ _
theorem mul_le_mul_of_nonpos_right : ∀{a b c : ℤ}, b ≤ a → c ≤ 0 → a * c ≤ b * c :=
@algebra.mul_le_mul_of_nonpos_right _ _
theorem mul_nonneg_of_nonpos_of_nonpos : ∀{a b : ℤ}, a ≤ 0 → b ≤ 0 → 0 ≤ a * b :=
@algebra.mul_nonneg_of_nonpos_of_nonpos _ _
theorem mul_lt_mul_of_neg_left : ∀{a b c : ℤ}, b < a → c < 0 → c * a < c * b :=
@algebra.mul_lt_mul_of_neg_left _ _
theorem mul_lt_mul_of_neg_right : ∀{a b c : ℤ}, b < a → c < 0 → a * c < b * c :=
@algebra.mul_lt_mul_of_neg_right _ _
theorem mul_pos_of_neg_of_neg : ∀{a b : ℤ}, a < 0 → b < 0 → 0 < a * b :=
@algebra.mul_pos_of_neg_of_neg _ _
theorem mul_self_nonneg : ∀a : ℤ, a * a ≥ 0 := algebra.mul_self_nonneg
theorem zero_le_one : #int 0 ≤ 1 := trivial
theorem zero_lt_one : #int 0 < 1 := trivial
theorem pos_and_pos_or_neg_and_neg_of_mul_pos : ∀{a b : ℤ}, a * b > 0 →
(a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := @algebra.pos_and_pos_or_neg_and_neg_of_mul_pos _ _
definition sign : ∀a : ℤ, ℤ := algebra.sign
theorem sign_of_neg : ∀{a : ℤ}, a < 0 → sign a = -1 := @algebra.sign_of_neg _ _
theorem sign_zero : sign 0 = 0 := algebra.sign_zero
theorem sign_of_pos : ∀{a : ℤ}, a > 0 → sign a = 1 := @algebra.sign_of_pos _ _
theorem sign_one : sign 1 = 1 := algebra.sign_one
theorem sign_neg_one : sign (-1) = -1 := algebra.sign_neg_one
theorem sign_sign : ∀a : ℤ, sign (sign a) = sign a := algebra.sign_sign
theorem pos_of_sign_eq_one : ∀{a : ℤ}, sign a = 1 → a > 0 := @algebra.pos_of_sign_eq_one _ _
theorem eq_zero_of_sign_eq_zero : ∀{a : ℤ}, sign a = 0 → a = 0 :=
@algebra.eq_zero_of_sign_eq_zero _ _
theorem neg_of_sign_eq_neg_one : ∀{a : ℤ}, sign a = -1 → a < 0 :=
@algebra.neg_of_sign_eq_neg_one _ _
theorem sign_neg : ∀a : ℤ, sign (-a) = -(sign a) := algebra.sign_neg
theorem sign_mul : ∀a b : ℤ, sign (a * b) = sign a * sign b := algebra.sign_mul
theorem abs_eq_sign_mul : ∀a : ℤ, abs a = sign a * a := algebra.abs_eq_sign_mul
theorem eq_sign_mul_abs : ∀a : ℤ, a = sign a * abs a := algebra.eq_sign_mul_abs
theorem abs_dvd_iff_dvd : ∀a b : ℤ, abs a ∣ b ↔ a ∣ b := algebra.abs_dvd_iff_dvd
theorem dvd_abs_iff : ∀a b : ℤ, a ∣ abs b ↔ a ∣ b := algebra.dvd_abs_iff
theorem abs_mul : ∀a b : ℤ, abs (a * b) = abs a * abs b := algebra.abs_mul
theorem abs_mul_self : ∀a : ℤ, abs a * abs a = a * a := algebra.abs_mul_self
end port_algebra
/- more facts specific to int -/
theorem nonneg_of_nat (n : ℕ) : 0 ≤ of_nat n := trivial
theorem exists_eq_of_nat {a : ℤ} (H : 0 ≤ a) : ∃n : ℕ, a = of_nat n :=
obtain (n : ℕ) (H1 : 0 + of_nat n = a), from le.elim H,
exists.intro n (!zero_add ▸ (H1⁻¹))
theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -(of_nat n) :=
have H2 : -a ≥ 0, from iff.mp' !neg_nonneg_iff_nonpos H,
obtain (n : ℕ) (Hn : -a = of_nat n), from exists_eq_of_nat H2,
exists.intro n (eq_neg_of_eq_neg (Hn⁻¹))
theorem of_nat_nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : of_nat (nat_abs a) = a :=
obtain (n : ℕ) (Hn : a = of_nat n), from exists_eq_of_nat H,
Hn⁻¹ ▸ congr_arg of_nat (nat_abs_of_nat n)
theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : of_nat (nat_abs a) = -a :=
have H1 : (-a) ≥ 0, from iff.mp' !neg_nonneg_iff_nonpos H,
calc
of_nat (nat_abs a) = of_nat (nat_abs (-a)) : nat_abs_neg
... = -a : of_nat_nat_abs_of_nonneg H1
theorem of_nat_nat_abs (b : ℤ) : nat_abs b = abs b :=
or.elim (le.total 0 b)
(assume H : b ≥ 0, of_nat_nat_abs_of_nonneg H ⬝ (abs_of_nonneg H)⁻¹)
(assume H : b ≤ 0, of_nat_nat_abs_of_nonpos H ⬝ (abs_of_nonpos H)⁻¹)
theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b :=
obtain n (H1 : a + 1 + n = b), from le.elim H,
have H2 : a + succ n = b, by rewrite [-H1, add.assoc, add.comm 1],
lt.intro H2
theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b :=
obtain n (H1 : a + succ n = b), from lt.elim H,
have H2 : a + 1 + n = b, by rewrite [-H1, add.assoc, add.comm 1],
le.intro H2
theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 :=
lt_add_of_le_of_pos H trivial
theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b :=
have H1 : a + 1 ≤ b + 1, from add_one_le_of_lt H,
le_of_add_le_add_right H1
theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b :=
lt_of_add_one_le (!sub_add_cancel⁻¹ ▸ H)
theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b :=
!sub_add_cancel ▸ add_one_le_of_lt H
theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 :=
le_of_lt_add_one (!sub_add_cancel⁻¹ ▸ H)
theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b :=
!sub_add_cancel ▸ (lt_add_one_of_le H)
theorem of_nat_nonneg (n : ℕ) : of_nat n ≥ 0 := trivial
theorem of_nat_pos {n : ℕ} (Hpos : #nat n > 0) : of_nat n > 0 :=
of_nat_lt_of_nat Hpos
theorem sign_of_succ (n : nat) : sign (succ n) = 1 :=
sign_of_pos (of_nat_pos !nat.succ_pos)
theorem exists_eq_neg_succ_of_nat {a : ℤ} : a < 0 → ∃m : ℕ, a = -[m +1] :=
int.cases_on a
(take m H, absurd (of_nat_nonneg m) (not_le_of_lt H))
(take m H, exists.intro m rfl)
end int
|
c72aee0fbe9c95d63fe3bcf031763e8096406dcc | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /analysis/measure_theory/outer_measure.lean | 44a67e4bce010bc2f98f4c00f16d56c50036676c | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 18,501 | 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
Outer measures -- overapproximations of measures
-/
import order.galois_connection algebra.big_operators
analysis.ennreal analysis.limits
analysis.measure_theory.measurable_space
noncomputable theory
open set lattice finset function filter encodable
local attribute [instance] classical.prop_decidable
namespace measure_theory
structure outer_measure (α : Type*) :=
(measure_of : set α → ennreal)
(empty : measure_of ∅ = 0)
(mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂)
(Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑i, measure_of (s i)))
namespace outer_measure
instance {α} : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩
section basic
variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α}
@[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty
theorem mono' (m : outer_measure α) {s₁ s₂}
(h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h
theorem Union_aux (m : set α → ennreal) (m0 : m ∅ = 0)
{β} [encodable β] (s : β → set α) :
(∑ b, m (s b)) = ∑ i, m (⋃ b ∈ decode2 β i, s b) :=
begin
have H : ∀ n, m (⋃ b ∈ decode2 β n, s b) ≠ 0 → (decode2 β n).is_some,
{ intros n h,
cases decode2 β n with b,
{ exact (h (by simp [m0])).elim },
{ exact rfl } },
refine tsum_eq_tsum_of_ne_zero_bij (λ n h, option.get (H n h)) _ _ _,
{ intros m n hm hn e,
have := mem_decode2.1 (option.get_mem (H n hn)),
rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this },
{ intros b h,
refine ⟨encode b, _, _⟩,
{ convert h, simp [ext_iff, encodek2] },
{ exact option.get_of_mem _ (encodek2 _) } },
{ intros n h,
transitivity, swap,
rw [show decode2 β n = _, from option.get_mem (H n h)],
congr, simp [ext_iff] }
end
protected theorem Union (m : outer_measure α)
{β} [encodable β] (s : β → set α) :
m (⋃i, s i) ≤ (∑i, m (s i)) :=
by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _
lemma Union_null (m : outer_measure α)
{β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 :=
by simpa [h] using m.Union s
protected lemma union (m : outer_measure α) (s₁ s₂ : set α) :
m (s₁ ∪ s₂) ≤ m s₁ + m s₂ :=
begin
convert m.Union (λ b, cond b s₁ s₂),
{ simp [union_eq_Union] },
{ rw tsum_fintype, change _ = _ + _, simp }
end
lemma union_null (m : outer_measure α) {s₁ s₂ : set α}
(h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 :=
by simpa [h₁, h₂] using m.union s₁ s₂
@[extensionality] lemma ext : ∀{μ₁ μ₂ : outer_measure α},
(∀s, μ₁ s = μ₂ s) → μ₁ = μ₂
| ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := by congr; exact funext h
instance : has_zero (outer_measure α) :=
⟨{ measure_of := λ_, 0,
empty := rfl,
mono := assume _ _ _, le_refl 0,
Union_nat := assume s, zero_le _ }⟩
@[simp] theorem zero_apply (s : set α) : (0 : outer_measure α) s = 0 := rfl
instance : inhabited (outer_measure α) := ⟨0⟩
instance : has_add (outer_measure α) :=
⟨λm₁ m₂,
{ measure_of := λs, m₁ s + m₂ s,
empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty],
mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h),
Union_nat := assume s,
calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤
(∑i, m₁ (s i)) + (∑i, m₂ (s i)) :
add_le_add' (m₁.Union_nat s) (m₂.Union_nat s)
... = _ : ennreal.tsum_add.symm}⟩
@[simp] theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) :
(m₁ + m₂) s = m₁ s + m₂ s := rfl
instance : add_comm_monoid (outer_measure α) :=
{ zero := 0,
add := (+),
add_comm := assume a b, ext $ assume s, add_comm _ _,
add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _,
add_zero := assume a, ext $ assume s, add_zero _,
zero_add := assume a, ext $ assume s, zero_add _ }
instance : has_bot (outer_measure α) := ⟨0⟩
instance outer_measure.order_bot : order_bot (outer_measure α) :=
{ le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s,
bot := 0,
le_refl := assume a s, le_refl _,
le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s),
le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s),
bot_le := assume a s, zero_le _ }
section supremum
instance : has_Sup (outer_measure α) :=
⟨λms, {
measure_of := λs, ⨆m:ms, m.val s,
empty := le_zero_iff_eq.1 $ supr_le $ λ ⟨m, h⟩, le_of_eq m.empty,
mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs,
Union_nat := assume f, supr_le $ assume m,
calc m.val (⋃i, f i) ≤ (∑ (i : ℕ), m.val (f i)) : m.val.Union_nat _
... ≤ (∑i, ⨆m:ms, m.val (f i)) :
ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val (f i)) m }⟩
private lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms :=
λ s, le_supr (λm:ms, m.val s) ⟨m, hm⟩
private lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m :=
λ s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s)
instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩
private lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := Sup_le $ assume m' h', h' _ hm
private lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := le_Sup hm
instance : complete_lattice (outer_measure α) :=
{ top := Sup univ,
le_top := assume a, le_Sup (mem_univ a),
Sup := Sup,
Sup_le := assume s m, Sup_le,
le_Sup := assume s m, le_Sup,
Inf := Inf,
Inf_le := assume s m, Inf_le,
le_Inf := assume s m, le_Inf,
sup := λa b, Sup {a, b},
le_sup_left := assume a b, le_Sup $ by simp,
le_sup_right := assume a b, le_Sup $ by simp,
sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
inf := λa b, Inf {a, b},
inf_le_left := assume a b, Inf_le $ by simp,
inf_le_right := assume a b, Inf_le $ by simp,
le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
.. outer_measure.order_bot }
@[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) :
(Sup ms) s = ⨆ m : ms, m s := rfl
@[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) :
(⨆ i : ι, f i) s = ⨆ i, f i s :=
le_antisymm
(supr_le $ λ ⟨_, i, rfl⟩, le_supr _ i)
(supr_le $ λ i, le_supr
(λ (m : {a : outer_measure α // ∃ i, a = f i}), m.1 s)
⟨f i, i, rfl⟩)
@[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) :
(m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s :=
by have := supr_apply (λ b, cond b m₁ m₂) s;
rwa [supr_bool_eq, supr_bool_eq] at this
end supremum
def map {β} (f : α → β) (m : outer_measure α) : outer_measure β :=
{ measure_of := λs, m (f ⁻¹' s),
empty := m.empty,
mono := λ s t h, m.mono (preimage_mono h),
Union_nat := λ s, by rw [preimage_Union]; exact
m.Union_nat (λ i, f ⁻¹' s i) }
@[simp] theorem map_apply {β} (f : α → β)
(m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl
@[simp] theorem map_id (m : outer_measure α) : map id m = m :=
ext $ λ s, rfl
@[simp] theorem map_map {β γ} (f : α → β) (g : β → γ)
(m : outer_measure α) : map g (map f m) = map (g ∘ f) m :=
ext $ λ s, rfl
instance : functor outer_measure := {map := λ α β, map}
instance : is_lawful_functor outer_measure :=
{ id_map := λ α, map_id,
comp_map := λ α β γ f g m, (map_map f g m).symm }
/-- The dirac outer measure. -/
def dirac (a : α) : outer_measure α :=
{ measure_of := λs, ⨆ h : a ∈ s, 1,
empty := by simp,
mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩),
Union_nat := λ s, supr_le $ λ h,
let ⟨i, h⟩ := mem_Union.1 h in
le_trans (by exact le_supr _ h) (ennreal.le_tsum i) }
@[simp] theorem dirac_apply (a : α) (s : set α) :
dirac a s = ⨆ h : a ∈ s, 1 := rfl
def sum {ι} (f : ι → outer_measure α) : outer_measure α :=
{ measure_of := λs, ∑ i, f i s,
empty := by simp,
mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h),
Union_nat := λ s, by rw ennreal.tsum_comm; exact
ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) }
@[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) :
sum f s = ∑ i, f i s := rfl
def smul (a : ennreal) (m : outer_measure α) : outer_measure α :=
{ measure_of := λs, a * m s,
empty := by simp,
mono := λ s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h),
Union_nat := λ s, by rw ennreal.mul_tsum; exact
canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }
local infixr ` • ` := smul
@[simp] theorem smul_apply (a : ennreal) (m : outer_measure α) (s : set α) :
(a • m) s = a * m s := rfl
theorem smul_add (a : ennreal) (m₁ m₂ : outer_measure α) :
a • (m₁ + m₂) = a • m₁ + a • m₂ := ext $ λ s, mul_add _ _ _
theorem add_smul (a b : ennreal) (m : outer_measure α) :
(a + b) • m = a • m + b • m := ext $ λ s, add_mul _ _ _
theorem mul_smul (a b : ennreal) (m : outer_measure α) :
(a * b) • m = a • b • m := ext $ λ s, mul_assoc _ _ _
@[simp] theorem one_smul (m : outer_measure α) :
1 • m = m := ext $ λ s, one_mul _
@[simp] theorem zero_smul (m : outer_measure α) :
0 • m = 0 := ext $ λ s, zero_mul _
@[simp] theorem smul_zero (a : ennreal) :
a • (0 : outer_measure α) = 0 := ext $ λ s, mul_zero _
theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) :
(a • dirac b) s = ⨆ h : b ∈ s, a :=
by by_cases b ∈ s; simp [h]
theorem top_apply {s : set α} (h : s ≠ ∅) : (⊤ : outer_measure α) s = ⊤ :=
let ⟨a, as⟩ := set.exists_mem_of_ne_empty h in
top_unique $ le_supr_of_le ⟨⊤ • dirac a, trivial⟩ $
by simp [smul_dirac_apply, as]
end basic
section of_function
set_option eqn_compiler.zeta true
/-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is
a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/
protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) :
outer_measure α :=
let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑i, m (f i) in
{ measure_of := μ,
empty := le_antisymm
(infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty])
(zero_le _),
mono := assume s₁ s₂ hs, infi_le_infi $ assume f,
infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩,
Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin
assume ε hε (hb : (∑i, μ (s i)) < ⊤),
rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩,
refine le_trans _ (add_le_add_left' (le_of_lt hl)),
rw ← ennreal.tsum_add,
have : ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑i, m (f i)) < μ (s i) + ε' i,
{ intro,
have : μ (s i) < μ (s i) + ε' i :=
ennreal.lt_add_right
(lt_of_le_of_lt (by apply ennreal.le_tsum) hb)
(by simpa using hε' i),
simpa [μ, infi_lt_iff] },
cases classical.axiom_of_choice this with f hf,
dsimp at f hf, clear this,
refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2),
rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm],
swap, {apply_instance},
refine infi_le_of_le _ (infi_le _ _),
exact Union_subset (λ i, subset.trans (hf i).1 $
Union_subset $ λ j, subset.trans (by simp) $
subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)),
end }
theorem of_function_le {α : Type*} (m : set α → ennreal) (m_empty s) :
outer_measure.of_function m m_empty s ≤ m s :=
let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in
infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $
calc (∑i, m (f i)) = ({0} : finset ℕ).sum (λi, m (f i)) :
tsum_eq_sum $ by intro i; cases i; simp [m_empty]
... = m s : by simp; refl
theorem le_of_function {α : Type*} {m m_empty} {μ : outer_measure α} :
μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s :=
⟨λ H s, le_trans (H _) (of_function_le _ _ _),
λ H s, le_infi $ λ f, le_infi $ λ hs,
le_trans (μ.mono hs) $ le_trans (μ.Union f) $
ennreal.tsum_le_tsum $ λ i, H _⟩
end of_function
section caratheodory_measurable
universe u
parameters {α : Type u} (m : outer_measure α)
include m
local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc
variables {s s₁ s₂ : set α}
private def C (s : set α) := ∀t, m t = m (t ∩ s) + m (t \ s)
private lemma C_iff_le {s : set α} : C s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t :=
forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $
by convert m.union _ _; rw inter_union_diff t s
@[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, diff_empty]
private lemma C_compl : C s₁ → C (- s₁) := by simp [C, diff_eq]
@[simp] private lemma C_compl_iff : C (- s) ↔ C s :=
⟨λ h, by simpa using C_compl m h, C_compl⟩
private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) :=
λ t, begin
rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)),
inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁,
inter_eq_self_of_subset_right (set.subset_union_left _ _),
union_diff_left, h₂ (t ∩ s₁)],
simp [diff_eq]
end
private lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : C s₁) {t : set α} :
m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) :=
by rw [h₁, set.inter_assoc, union_inter_cancel_left h,
inter_diff_assoc, union_diff_cancel_left h]
private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i)
| 0 h := by simp [nat.not_lt_zero]
| (n + 1) h := by rw Union_lt_succ; exact C_union m
(h n (le_refl (n + 1)))
(C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _)
private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) :=
by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂)
private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {t : set α} :
∀ {n}, (finset.range n).sum (λi, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i)
| 0 := by simp [nat.not_lt_zero, m.empty]
| (nat.succ n) := begin
simp [Union_lt_succ],
rw [measure_inter_union m _ (h n), C_sum],
intro a, simpa using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩
end
private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i))
(hd : pairwise (disjoint on s)) : C (⋃i, s i) :=
C_iff_le.2 $ λ t, begin
have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)),
{ convert m.Union (λ i, t ∩ s i),
{ rw inter_Union_left },
{ simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } },
refine le_trans (add_le_add_right' hp) _,
rw ennreal.supr_add,
refine supr_le (λ n, le_trans (add_le_add_left' _)
(ge_of_eq (C_Union_lt m (λ i _, h i) _))),
refine m.mono (diff_subset_diff_right _),
exact bUnion_subset (λ i _, subset_Union _ i),
end
private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i))
(hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑i, m (s i) :=
begin
refine le_antisymm (m.Union_nat s) _,
rw ennreal.tsum_eq_supr_nat,
refine supr_le (λ n, _),
have := @C_sum _ m _ h hd univ n,
simp at this, simp [this],
exact m.mono (bUnion_subset (λ i _, subset_Union _ i)),
end
private def caratheodory_dynkin : measurable_space.dynkin_system α :=
{ has := C,
has_empty := C_empty,
has_compl := assume s, C_compl,
has_Union_nat := assume f hf hn, C_Union_nat hn hf }
/-- Given an outer measure `μ`, the Caratheodory measurable space is
defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/
protected def caratheodory : measurable_space α :=
caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter
lemma is_caratheodory {s : set α} :
caratheodory.is_measurable s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) :=
iff.rfl
lemma is_caratheodory_le {s : set α} :
caratheodory.is_measurable s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t :=
C_iff_le
protected lemma Union_eq_of_caratheodory {s : ℕ → set α}
(h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) :
m (⋃i, s i) = ∑i, m (s i) :=
f_Union h hd
end caratheodory_measurable
variables {α : Type*}
lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α}
{h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) :
(outer_measure.of_function m h₀).caratheodory.is_measurable s :=
let o := (outer_measure.of_function m h₀) in
(is_caratheodory_le o).2 $ λ t,
le_infi $ λ f, le_infi $ λ hf, begin
refine le_trans (add_le_add'
(infi_le_of_le (λi, f i ∩ s) $ infi_le _ _)
(infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _,
{ rw ← inter_Union_right,
exact inter_subset_inter_left _ hf },
{ rw ← diff_Union_right,
exact diff_subset_diff_left hf },
{ rw ← ennreal.tsum_add,
exact ennreal.tsum_le_tsum (λ i, hs _) }
end
@[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ :=
top_unique $ λ s _ t, (add_zero _).symm
theorem le_add_caratheodory (m₁ m₂ : outer_measure α) :
m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory :=
λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t]
theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) :
(⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory :=
λ s h t, by simp [λ i,
measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add]
theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) :
m.caratheodory ≤ (smul a m).caratheodory :=
λ s h t, by simp [h t, mul_add]
@[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ :=
top_unique $ λ s _ t, begin
by_cases a ∈ t; simp [h],
by_cases a ∈ s; simp [h]
end
end outer_measure
end measure_theory
|
2a3207c517478bf1ae3e3c8174d4ede937ab3457 | c46a31beec236d29b6c02e7d7683691bcfbb3014 | /src/utils/default.lean | ad7fe7a27190e3c95ab09721e5551f07f7eb9db6 | [] | no_license | UVM-M52/quiz-5-maddiestrauss | a88b9bfbdd486a521ee280f9b7b551bcb48f23c6 | 214529615e08bbcdd3d6600c89432ec985e6ba3a | refs/heads/master | 1,617,897,187,103 | 1,584,922,038,000 | 1,584,922,038,000 | 248,787,429 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 57 | lean |
import .cmp
import .int_refl
import .real
import .logic
|
934dee38db0ba1b35b959e2b8cf281d81e850c83 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/677.lean | 46302b5cea2c5fa9408f2a62d36a87f219923028 | [
"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 | 269 | lean | import Lean
open Lean
def encodeDecode [ToJson α] [FromJson α] (x : α) : Except String α := do
let json ← toJson x
fromJson? json
#eval IO.ofExcept <| encodeDecode (Name.mkNum Name.anonymous 5)
#eval IO.ofExcept <| encodeDecode (Name.mkStr `bla "foo.boo")
|
b752ab963f4a0e5a6b632d45c103cc97a24603ef | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Config/ExternLibConfig.lean | 71ba1b692887a8f3163f0cde880792f4153dc46d | [
"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 | 618 | lean | /-
Copyright (c) 2022 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Build.Job
namespace Lake
open Lean System
/-- A external library's declarative configuration. -/
structure ExternLibConfig (pkgName name : Name) where
/-- The library's build data. -/
getJob : CustomData (pkgName, .str name "static") → BuildJob FilePath
deriving Inhabited
/-- A dependently typed configuration based on its registered package and name. -/
structure ExternLibDecl where
pkg : Name
name : Name
config : ExternLibConfig pkg name
|
bb4e5a01f6332cd4bdcd7ae08e56d3168c0a2c59 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/PreDefinition/WF/PackDomain.lean | dd4d1caa24fac360ff13df2f6e7151e3dfaa7ff0 | [
"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 | 5,226 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.PreDefinition.Basic
namespace Lean.Elab.WF
open Meta
/--
Given a (dependent) tuple `t` (using `PSigma`) of the given arity.
Return an array containing its "elements".
Example: `mkTupleElems a 4` returns `#[a.1, a.2.1, a.2.2.1, a.2.2.2]`.
-/
private def mkTupleElems (t : Expr) (arity : Nat) : Array Expr := Id.run <| do
let mut result := #[]
let mut t := t
for i in [:arity - 1] do
result := result.push (mkProj ``PSigma 0 t)
t := mkProj ``PSigma 1 t
result.push t
/-- Create a unary application by packing the given arguments using `PSigma.mk` -/
partial def mkUnaryArg (type : Expr) (args : Array Expr) : MetaM Expr := do
go 0 type
where
go (i : Nat) (type : Expr) : MetaM Expr := do
if i < args.size - 1 then
let arg := args[i]
assert! type.isAppOfArity ``PSigma 2
let us := type.getAppFn.constLevels!
let α := type.appFn!.appArg!
let β := type.appArg!
assert! β.isLambda
let type := β.bindingBody!.instantiate1 arg
let rest ← go (i+1) type
return mkApp4 (mkConst ``PSigma.mk us) α β arg rest
else
return args[i]
private partial def mkPSigmaCasesOn (y : Expr) (codomain : Expr) (xs : Array Expr) (value : Expr) : MetaM Expr := do
let mvar ← mkFreshExprSyntheticOpaqueMVar codomain
let rec go (mvarId : MVarId) (y : FVarId) (ys : Array Expr) : MetaM Unit := do
if ys.size < xs.size - 1 then
let xDecl ← getLocalDecl xs[ys.size].fvarId!
let xDecl' ← getLocalDecl xs[ys.size + 1].fvarId!
let #[s] ← cases mvarId y #[{ varNames := [xDecl.userName, xDecl'.userName] }] | unreachable!
go s.mvarId s.fields[1].fvarId! (ys.push s.fields[0])
else
let ys := ys.push (mkFVar y)
assignExprMVar mvarId (value.replaceFVars xs ys)
go mvar.mvarId! y.fvarId! #[]
instantiateMVars mvar
/--
Convert the given pre-definitions into unary functions.
We "pack" the arguments using `PSigma`.
-/
def packDomain (preDefs : Array PreDefinition) : MetaM (Array PreDefinition) := do
let mut preDefsNew := #[]
let mut arities := #[]
let mut modified := false
for preDef in preDefs do
let (preDefNew, arity, modifiedCurr) ← lambdaTelescope preDef.value fun xs body => do
if xs.size == 0 then
throwError "well-founded recursion cannot be used, '{preDef.declName}' does not take any arguments"
if xs.size > 1 then
let bodyType ← instantiateForall preDef.type xs
let mut d ← inferType xs.back
for x in xs.pop.reverse do
d ← mkAppOptM ``PSigma #[some (← inferType x), some (← mkLambdaFVars #[x] d)]
withLocalDeclD (← mkFreshUserName `_x) d fun tuple => do
let elems := mkTupleElems tuple xs.size
let codomain := bodyType.replaceFVars xs elems
let preDefNew:= { preDef with
declName := preDef.declName ++ `_unary
type := (← mkForallFVars #[tuple] codomain)
}
addAsAxiom preDefNew
return (preDefNew, xs.size, true)
else
return (preDef, 1, false)
modified := modified || modifiedCurr
arities := arities.push arity
preDefsNew := preDefsNew.push preDefNew
if !modified then
return preDefs
/- Return `some i` if `e` is a `preDefs[i]` application -/
let isAppOfPreDef? (e : Expr) : OptionM Nat := do
let f := e.getAppFn
guard f.isConst
preDefs.findIdx? (·.declName == f.constName!)
/- Return `some i` if `e` is a `preDefs[i]` application with `arities[i]` arguments. -/
let isTargetApp? (e : Expr) : OptionM Nat := do
let i ← isAppOfPreDef? e
guard (e.getAppNumArgs == arities[i])
return i
-- Update values
for i in [:preDefs.size] do
let preDef := preDefs[i]
let preDefNew := preDefsNew[i]
let arity := arities[i]
let valueNew ← lambdaTelescope preDef.value fun xs body => do
forallBoundedTelescope preDefNew.type (some 1) fun y codomain => do
let y := y[0]
let newBody ← mkPSigmaCasesOn y codomain xs body
let visit (e : Expr) : MetaM TransformStep := do
if let some idx := isTargetApp? e |>.run then
let f := e.getAppFn
let fNew := mkConst preDefsNew[idx].declName f.constLevels!
let Expr.forallE _ d .. ← inferType fNew | unreachable!
let argNew ← mkUnaryArg d e.getAppArgs
return TransformStep.done <| mkApp fNew argNew
else
return TransformStep.done e
mkLambdaFVars #[y] (← transform newBody (post := visit))
if let some bad := valueNew.find? fun e => (isAppOfPreDef? e).isSome && e.getAppNumArgs > 1 then
if let some i := isAppOfPreDef? bad then
throwErrorAt preDef.ref "well-founded recursion cannot be used, function '{preDef.declName}' contains application of function '{preDefs[i].declName}' with #{bad.getAppNumArgs} argument(s), but function has arity {arities[i]}"
preDefsNew := preDefsNew.set! i { preDefNew with value := valueNew }
return preDefsNew
end Lean.Elab.WF
|
957c3bf7ca9aa5c4ab7ac5fa37752605d2c340b4 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/polynomial/integral_normalization.lean | 05c3df02a5c3064e4e8ae85917b7769e84d66a55 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 5,304 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.algebra_map
import data.polynomial.monic
/-!
# Theory of monic polynomials
We define `integral_normalization`, which relate arbitrary polynomials to monic ones.
-/
noncomputable theory
open finsupp
namespace polynomial
universes u v y
variables {R : Type u} {S : Type v} {a b : R} {m n : ℕ} {ι : Type y}
section integral_normalization
section semiring
variables [semiring R]
/-- If `f : polynomial R` is a nonzero polynomial with root `z`, `integral_normalization f` is
a monic polynomial with root `leading_coeff f * z`.
Moreover, `integral_normalization 0 = 0`.
-/
noncomputable def integral_normalization (f : polynomial R) : polynomial R :=
on_finset f.support
(λ i, if f.degree = i then 1 else coeff f i * f.leading_coeff ^ (f.nat_degree - 1 - i))
begin
intros i h,
apply mem_support_iff.mpr,
split_ifs at h with hi,
{ exact coeff_ne_zero_of_eq_degree hi },
{ exact left_ne_zero_of_mul h },
end
lemma integral_normalization_coeff_degree {f : polynomial R} {i : ℕ} (hi : f.degree = i) :
(integral_normalization f).coeff i = 1 :=
if_pos hi
lemma integral_normalization_coeff_nat_degree {f : polynomial R} (hf : f ≠ 0) :
(integral_normalization f).coeff (nat_degree f) = 1 :=
integral_normalization_coeff_degree (degree_eq_nat_degree hf)
lemma integral_normalization_coeff_ne_degree {f : polynomial R} {i : ℕ} (hi : f.degree ≠ i) :
coeff (integral_normalization f) i = coeff f i * f.leading_coeff ^ (f.nat_degree - 1 - i) :=
if_neg hi
lemma integral_normalization_coeff_ne_nat_degree {f : polynomial R} {i : ℕ} (hi : i ≠ nat_degree f) :
coeff (integral_normalization f) i = coeff f i * f.leading_coeff ^ (f.nat_degree - 1 - i) :=
integral_normalization_coeff_ne_degree (degree_ne_of_nat_degree_ne hi.symm)
lemma monic_integral_normalization {f : polynomial R} (hf : f ≠ 0) :
monic (integral_normalization f) :=
begin
apply monic_of_degree_le f.nat_degree,
{ refine finset.sup_le (λ i h, _),
rw [integral_normalization, mem_support_iff, on_finset_apply] at h,
split_ifs at h with hi,
{ exact le_trans (le_of_eq hi.symm) degree_le_nat_degree },
{ erw [with_bot.some_le_some],
apply le_nat_degree_of_ne_zero,
exact left_ne_zero_of_mul h } },
{ exact integral_normalization_coeff_nat_degree hf }
end
end semiring
section domain
variables [integral_domain R]
@[simp] lemma support_integral_normalization {f : polynomial R} (hf : f ≠ 0) :
(integral_normalization f).support = f.support :=
begin
ext i,
simp only [integral_normalization, on_finset_apply, mem_support_iff],
split_ifs with hi,
{ simp only [ne.def, not_false_iff, true_iff, one_ne_zero, hi],
exact coeff_ne_zero_of_eq_degree hi },
split,
{ intro h,
exact left_ne_zero_of_mul h },
{ intro h,
refine mul_ne_zero h (pow_ne_zero _ _),
exact λ h, hf (leading_coeff_eq_zero.mp h) }
end
variables [comm_ring S]
lemma integral_normalization_eval₂_eq_zero {p : polynomial R} (hp : p ≠ 0) (f : R →+* S)
{z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) :
eval₂ f (z * f p.leading_coeff) (integral_normalization p) = 0 :=
calc eval₂ f (z * f p.leading_coeff) (integral_normalization p)
= p.support.attach.sum
(λ i, f (coeff (integral_normalization p) i.1 * p.leading_coeff ^ i.1) * z ^ i.1) :
by { rw [eval₂, finsupp.sum, support_integral_normalization hp],
simp only [mul_comm z, mul_pow, mul_assoc, ring_hom.map_pow, ring_hom.map_mul],
exact finset.sum_attach.symm }
... = p.support.attach.sum
(λ i, f (coeff p i.1 * p.leading_coeff ^ (nat_degree p - 1)) * z ^ i.1) :
begin
have one_le_deg : 1 ≤ nat_degree p :=
nat.succ_le_of_lt (nat_degree_pos_of_eval₂_root hp f hz inj),
congr' with i,
congr' 2,
by_cases hi : i.1 = nat_degree p,
{ rw [hi, integral_normalization_coeff_degree, one_mul, leading_coeff, ←pow_succ,
nat.sub_add_cancel one_le_deg],
exact degree_eq_nat_degree hp },
{ have : i.1 ≤ p.nat_degree - 1 := nat.le_pred_of_lt (lt_of_le_of_ne
(le_nat_degree_of_ne_zero (finsupp.mem_support_iff.mp i.2)) hi),
rw [integral_normalization_coeff_ne_nat_degree hi, mul_assoc, ←pow_add,
nat.sub_add_cancel this] }
end
... = f p.leading_coeff ^ (nat_degree p - 1) * eval₂ f z p :
by { simp_rw [eval₂, finsupp.sum, λ i, mul_comm (coeff p i), ring_hom.map_mul,
ring_hom.map_pow, mul_assoc, ←finset.mul_sum],
congr' 1,
exact @finset.sum_attach _ _ p.support _ (λ i, f (p.coeff i) * z ^ i) }
... = 0 : by rw [hz, _root_.mul_zero]
lemma integral_normalization_aeval_eq_zero [algebra R S] {f : polynomial R} (hf : f ≠ 0)
{z : S} (hz : aeval z f = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) :
aeval (z * algebra_map R S f.leading_coeff) (integral_normalization f) = 0 :=
integral_normalization_eval₂_eq_zero hf (algebra_map R S) hz inj
end domain
end integral_normalization
end polynomial
|
c33f5b0f119c97a46d43163a101b9d79bdf67ff2 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/continuous_function/compact.lean | 6a1ebce892a68c836ff391cb11b58df3f04d7d0d | [
"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 | 14,397 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import topology.continuous_function.bounded
import topology.uniform_space.compact_separated
import tactic.equiv_rw
/-!
# Continuous functions on a compact space
Continuous functions `C(α, β)` from a compact space `α` to a metric space `β`
are automatically bounded, and so acquire various structures inherited from `α →ᵇ β`.
This file transfers these structures, and restates some lemmas
characterising these structures.
If you need a lemma which is proved about `α →ᵇ β` but not for `C(α, β)` when `α` is compact,
you should restate it here. You can also use
`bounded_continuous_function.equiv_continuous_map_of_compact` to move functions back and forth.
-/
noncomputable theory
open_locale topological_space classical nnreal bounded_continuous_function
open set filter metric
open bounded_continuous_function
namespace continuous_map
variables {α β E : Type*} [topological_space α] [compact_space α] [metric_space β] [normed_group E]
section
variables (α β)
/--
When `α` is compact, the bounded continuous maps `α →ᵇ β` are
equivalent to `C(α, β)`.
-/
@[simps { fully_applied := ff }]
def equiv_bounded_of_compact : C(α, β) ≃ (α →ᵇ β) :=
⟨mk_of_compact, forget_boundedness α β, λ f, by { ext, refl, }, λ f, by { ext, refl, }⟩
/--
When `α` is compact, the bounded continuous maps `α →ᵇ 𝕜` are
additively equivalent to `C(α, 𝕜)`.
-/
@[simps apply symm_apply { fully_applied := ff }]
def add_equiv_bounded_of_compact [add_monoid β] [has_lipschitz_add β] :
C(α, β) ≃+ (α →ᵇ β) :=
({ .. forget_boundedness_add_hom α β,
.. (equiv_bounded_of_compact α β).symm, } : (α →ᵇ β) ≃+ C(α, β)).symm
instance : metric_space C(α, β) :=
metric_space.induced
(equiv_bounded_of_compact α β)
(equiv_bounded_of_compact α β).injective
(by apply_instance)
/--
When `α` is compact, and `β` is a metric space, the bounded continuous maps `α →ᵇ β` are
isometric to `C(α, β)`.
-/
@[simps to_equiv apply symm_apply { fully_applied := ff }]
def isometric_bounded_of_compact :
C(α, β) ≃ᵢ (α →ᵇ β) :=
{ isometry_to_fun := λ x y, rfl,
to_equiv := equiv_bounded_of_compact α β }
end
@[simp] lemma _root_.bounded_continuous_function.dist_mk_of_compact (f g : C(α, β)) :
dist (mk_of_compact f) (mk_of_compact g) = dist f g := rfl
@[simp] lemma _root_.bounded_continuous_function.dist_forget_boundedness (f g : α →ᵇ β) :
dist (f.forget_boundedness _ _) (g.forget_boundedness _ _) = dist f g := rfl
open bounded_continuous_function
section
variables {α β} {f g : C(α, β)} {C : ℝ}
/-- The pointwise distance is controlled by the distance between functions, by definition. -/
lemma dist_apply_le_dist (x : α) : dist (f x) (g x) ≤ dist f g :=
by simp only [← dist_mk_of_compact, dist_coe_le_dist, ← mk_of_compact_apply]
/-- The distance between two functions is controlled by the supremum of the pointwise distances -/
lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C :=
by simp only [← dist_mk_of_compact, dist_le C0, mk_of_compact_apply]
lemma dist_le_iff_of_nonempty [nonempty α] :
dist f g ≤ C ↔ ∀ x, dist (f x) (g x) ≤ C :=
by simp only [← dist_mk_of_compact, dist_le_iff_of_nonempty, mk_of_compact_apply]
lemma dist_lt_iff_of_nonempty [nonempty α] :
dist f g < C ↔ ∀x:α, dist (f x) (g x) < C :=
by simp only [← dist_mk_of_compact, dist_lt_iff_of_nonempty_compact, mk_of_compact_apply]
lemma dist_lt_of_nonempty [nonempty α] (w : ∀x:α, dist (f x) (g x) < C) : dist f g < C :=
(dist_lt_iff_of_nonempty).2 w
lemma dist_lt_iff (C0 : (0 : ℝ) < C) :
dist f g < C ↔ ∀x:α, dist (f x) (g x) < C :=
by simp only [← dist_mk_of_compact, dist_lt_iff_of_compact C0, mk_of_compact_apply]
end
instance [complete_space β] : complete_space (C(α, β)) :=
(isometric_bounded_of_compact α β).complete_space
@[continuity] lemma continuous_eval : continuous (λ p : C(α, β) × α, p.1 p.2) :=
continuous_eval.comp ((isometric_bounded_of_compact α β).continuous.prod_map continuous_id)
@[continuity] lemma continuous_evalx (x : α) : continuous (λ f : C(α, β), f x) :=
continuous_eval.comp (continuous_id.prod_mk continuous_const)
lemma continuous_coe : @continuous (C(α, β)) (α → β) _ _ coe_fn :=
continuous_pi continuous_evalx
-- TODO at some point we will need lemmas characterising this norm!
-- At the moment the only way to reason about it is to transfer `f : C(α,E)` back to `α →ᵇ E`.
instance : has_norm C(α, E) :=
{ norm := λ x, dist x 0 }
@[simp] lemma _root_.bounded_continuous_function.norm_mk_of_compact (f : C(α, E)) :
∥mk_of_compact f∥ = ∥f∥ := rfl
@[simp] lemma _root_.bounded_continuous_function.norm_forget_boundedness_eq (f : α →ᵇ E) :
∥forget_boundedness α E f∥ = ∥f∥ :=
rfl
open bounded_continuous_function
instance : normed_group C(α, E) :=
{ dist_eq := λ x y,
begin
rw [← norm_mk_of_compact, ← dist_mk_of_compact, dist_eq_norm],
congr' 1,
exact ((add_equiv_bounded_of_compact α E).map_sub _ _).symm
end, }
section
variables (f : C(α, E))
-- The corresponding lemmas for `bounded_continuous_function` are stated with `{f}`,
-- and so can not be used in dot notation.
lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ :=
(mk_of_compact f).norm_coe_le_norm x
/-- Distance between the images of any two points is at most twice the norm of the function. -/
lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ :=
(mk_of_compact f).dist_le_two_norm x y
/-- The norm of a function is controlled by the supremum of the pointwise norms -/
lemma norm_le {C : ℝ} (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C :=
@bounded_continuous_function.norm_le _ _ _ _
(mk_of_compact f) _ C0
lemma norm_le_of_nonempty [nonempty α] {M : ℝ} : ∥f∥ ≤ M ↔ ∀ x, ∥f x∥ ≤ M :=
@bounded_continuous_function.norm_le_of_nonempty _ _ _ _ _ (mk_of_compact f) _
lemma norm_lt_iff {M : ℝ} (M0 : 0 < M) : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M :=
@bounded_continuous_function.norm_lt_iff_of_compact _ _ _ _ _ (mk_of_compact f) _ M0
lemma norm_lt_iff_of_nonempty [nonempty α] {M : ℝ} :
∥f∥ < M ↔ ∀ x, ∥f x∥ < M :=
@bounded_continuous_function.norm_lt_iff_of_nonempty_compact _ _ _ _ _ _ (mk_of_compact f) _
lemma apply_le_norm (f : C(α, ℝ)) (x : α) : f x ≤ ∥f∥ :=
le_trans (le_abs.mpr (or.inl (le_refl (f x)))) (f.norm_coe_le_norm x)
lemma neg_norm_le_apply (f : C(α, ℝ)) (x : α) : -∥f∥ ≤ f x :=
le_trans (neg_le_neg (f.norm_coe_le_norm x)) (neg_le.mp (neg_le_abs_self (f x)))
lemma norm_eq_supr_norm : ∥f∥ = ⨆ x : α, ∥f x∥ :=
(mk_of_compact f).norm_eq_supr_norm
end
section
variables {R : Type*} [normed_ring R]
instance : normed_ring C(α,R) :=
{ norm_mul := λ f g, norm_mul_le (mk_of_compact f) (mk_of_compact g),
..(infer_instance : normed_group C(α,R)) }
end
section
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E]
instance : normed_space 𝕜 C(α,E) :=
{ norm_smul_le := λ c f, le_of_eq (norm_smul c (mk_of_compact f)) }
section
variables (α 𝕜 E)
/--
When `α` is compact and `𝕜` is a normed field,
the `𝕜`-algebra of bounded continuous maps `α →ᵇ β` is
`𝕜`-linearly isometric to `C(α, β)`.
-/
def linear_isometry_bounded_of_compact :
C(α, E) ≃ₗᵢ[𝕜] (α →ᵇ E) :=
{ map_smul' := λ c f, by { ext, simp, },
norm_map' := λ f, rfl,
.. add_equiv_bounded_of_compact α E }
end
-- this lemma and the next are the analogues of those autogenerated by `@[simps]` for
-- `equiv_bounded_of_compact`, `add_equiv_bounded_of_compact`
@[simp] lemma linear_isometry_bounded_of_compact_symm_apply (f : α →ᵇ E) :
(linear_isometry_bounded_of_compact α E 𝕜).symm f = f.forget_boundedness α E :=
rfl
@[simp] lemma linear_isometry_bounded_of_compact_apply_apply (f : C(α, E)) (a : α) :
(linear_isometry_bounded_of_compact α E 𝕜 f) a = f a :=
rfl
@[simp]
lemma linear_isometry_bounded_of_compact_to_isometric :
(linear_isometry_bounded_of_compact α E 𝕜).to_isometric = (isometric_bounded_of_compact α E) :=
rfl
@[simp]
lemma linear_isometry_bounded_of_compact_to_add_equiv :
(linear_isometry_bounded_of_compact α E 𝕜).to_linear_equiv.to_add_equiv =
(add_equiv_bounded_of_compact α E) :=
rfl
@[simp]
lemma linear_isometry_bounded_of_compact_of_compact_to_equiv :
(linear_isometry_bounded_of_compact α E 𝕜).to_linear_equiv.to_equiv =
(equiv_bounded_of_compact α E) :=
rfl
end
section
variables {𝕜 : Type*} {γ : Type*} [normed_field 𝕜] [normed_ring γ] [normed_algebra 𝕜 γ]
instance [nonempty α] : normed_algebra 𝕜 C(α, γ) :=
{ norm_algebra_map_eq := λ c, (norm_algebra_map_eq (α →ᵇ γ) c : _), }
end
end continuous_map
namespace continuous_map
section uniform_continuity
variables {α β : Type*}
variables [metric_space α] [compact_space α] [metric_space β]
/-!
We now set up some declarations making it convenient to use uniform continuity.
-/
lemma uniform_continuity
(f : C(α, β)) (ε : ℝ) (h : 0 < ε) :
∃ δ > 0, ∀ {x y}, dist x y < δ → dist (f x) (f y) < ε :=
metric.uniform_continuous_iff.mp
(compact_space.uniform_continuous_of_continuous f.continuous) ε h
/--
An arbitrarily chosen modulus of uniform continuity for a given function `f` and `ε > 0`.
-/
-- This definition allows us to separate the choice of some `δ`,
-- and the corresponding use of `dist a b < δ → dist (f a) (f b) < ε`,
-- even across different declarations.
def modulus (f : C(α, β)) (ε : ℝ) (h : 0 < ε) : ℝ :=
classical.some (uniform_continuity f ε h)
lemma modulus_pos (f : C(α, β)) {ε : ℝ} {h : 0 < ε} : 0 < f.modulus ε h :=
(classical.some_spec (uniform_continuity f ε h)).fst
lemma dist_lt_of_dist_lt_modulus
(f : C(α, β)) (ε : ℝ) (h : 0 < ε) {a b : α} (w : dist a b < f.modulus ε h) :
dist (f a) (f b) < ε :=
(classical.some_spec (uniform_continuity f ε h)).snd w
end uniform_continuity
end continuous_map
section comp_left
variables (X : Type*) {𝕜 β γ : Type*} [topological_space X] [compact_space X]
[nondiscrete_normed_field 𝕜]
variables [normed_group β] [normed_space 𝕜 β] [normed_group γ] [normed_space 𝕜 γ]
open continuous_map
/--
Postcomposition of continuous functions into a normed module by a continuous linear map is a
continuous linear map.
Transferred version of `continuous_linear_map.comp_left_continuous_bounded`,
upgraded version of `continuous_linear_map.comp_left_continuous`,
similar to `linear_map.comp_left`. -/
protected def continuous_linear_map.comp_left_continuous_compact (g : β →L[𝕜] γ) :
C(X, β) →L[𝕜] C(X, γ) :=
(linear_isometry_bounded_of_compact X γ 𝕜).symm.to_linear_isometry.to_continuous_linear_map.comp $
(g.comp_left_continuous_bounded X).comp $
(linear_isometry_bounded_of_compact X β 𝕜).to_linear_isometry.to_continuous_linear_map
@[simp] lemma continuous_linear_map.to_linear_comp_left_continuous_compact (g : β →L[𝕜] γ) :
(g.comp_left_continuous_compact X : C(X, β) →ₗ[𝕜] C(X, γ)) = g.comp_left_continuous 𝕜 X :=
by { ext f, refl }
@[simp] lemma continuous_linear_map.comp_left_continuous_compact_apply (g : β →L[𝕜] γ)
(f : C(X, β)) (x : X) :
g.comp_left_continuous_compact X f x = g (f x) :=
rfl
end comp_left
namespace continuous_map
/-!
We now setup variations on `comp_right_* f`, where `f : C(X, Y)`
(that is, precomposition by a continuous map),
as a morphism `C(Y, T) → C(X, T)`, respecting various types of structure.
In particular:
* `comp_right_continuous_map`, the bundled continuous map (for this we need `X Y` compact).
* `comp_right_homeomorph`, when we precompose by a homeomorphism.
* `comp_right_alg_hom`, when `T = R` is a topological ring.
-/
section comp_right
/--
Precomposition by a continuous map is itself a continuous map between spaces of continuous maps.
-/
def comp_right_continuous_map {X Y : Type*} (T : Type*)
[topological_space X] [compact_space X] [topological_space Y] [compact_space Y] [normed_group T]
(f : C(X, Y)) : C(C(Y, T), C(X, T)) :=
{ to_fun := λ g, g.comp f,
continuous_to_fun :=
begin
refine metric.continuous_iff.mpr _,
intros g ε ε_pos,
refine ⟨ε, ε_pos, λ g' h, _⟩,
rw continuous_map.dist_lt_iff ε_pos at h ⊢,
{ exact λ x, h (f x), },
end }
@[simp] lemma comp_right_continuous_map_apply {X Y : Type*} (T : Type*)
[topological_space X] [compact_space X] [topological_space Y] [compact_space Y] [normed_group T]
(f : C(X, Y)) (g : C(Y, T)) :
(comp_right_continuous_map T f) g = g.comp f :=
rfl
/--
Precomposition by a homeomorphism is itself a homeomorphism between spaces of continuous maps.
-/
def comp_right_homeomorph {X Y : Type*} (T : Type*)
[topological_space X] [compact_space X] [topological_space Y] [compact_space Y] [normed_group T]
(f : X ≃ₜ Y) : C(Y, T) ≃ₜ C(X, T) :=
{ to_fun := comp_right_continuous_map T f.to_continuous_map,
inv_fun := comp_right_continuous_map T f.symm.to_continuous_map,
left_inv := by tidy,
right_inv := by tidy, }
/--
Precomposition of functions into a normed ring by continuous map is an algebra homomorphism.
-/
def comp_right_alg_hom {X Y : Type*} (R : Type*)
[topological_space X] [topological_space Y] [normed_comm_ring R] (f : C(X, Y)) :
C(Y, R) →ₐ[R] C(X, R) :=
{ to_fun := λ g, g.comp f,
map_zero' := by { ext, simp, },
map_add' := λ g₁ g₂, by { ext, simp, },
map_one' := by { ext, simp, },
map_mul' := λ g₁ g₂, by { ext, simp, },
commutes' := λ r, by { ext, simp, }, }
@[simp] lemma comp_right_alg_hom_apply {X Y : Type*} (R : Type*)
[topological_space X] [topological_space Y] [normed_comm_ring R] (f : C(X, Y)) (g : C(Y, R)) :
(comp_right_alg_hom R f) g = g.comp f :=
rfl
lemma comp_right_alg_hom_continuous {X Y : Type*} (R : Type*)
[topological_space X] [compact_space X] [topological_space Y] [compact_space Y]
[normed_comm_ring R] (f : C(X, Y)) :
continuous (comp_right_alg_hom R f) :=
begin
change continuous (comp_right_continuous_map R f),
continuity,
end
end comp_right
end continuous_map
|
ac82671045b89bd5193d4e60de9207a0fc77775b | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/valid/mathd-algebra-206.lean | a95c7e46e7b4ee00ae50d49e874afacb25f9c61a | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 341 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.real.basic
example (a b : ℝ) (f : ℝ → ℝ) (h₀ : ∀ x, f x = x ^ 2 + a * x + b) (h₁ : 2 * a ≠ b) (h₂ : f (2 * a) = 0) (h₃ : f b = 0) : a + b = -1 :=
begin
sorry
end
|
0b4058839a5509ae3c299deb291ff940d49cc58f | 35677d2df3f081738fa6b08138e03ee36bc33cad | /test/tidy.lean | 17513e7c4b5fff8f656e64a4fe318d941e3252ec | [
"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 | 1,136 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.tidy
open tactic
namespace tidy.test
meta def interactive_simp := `[simp]
def tidy_test_0 : ∀ x : unit, x = unit.star :=
begin
success_if_fail { chain [ interactive_simp ] },
intro1,
induction x,
refl
end
def tidy_test_1 (a : string) : ∀ x : unit, x = unit.star :=
begin
tidy -- intros x, exact dec_trivial
end
structure A :=
(z : ℕ)
structure B :=
(a : A)
(aa : a.z = 0)
structure C :=
(a : A)
(b : B)
(ab : a.z = b.a.z)
structure D :=
(a : B)
(b : C)
(ab : a.a.z = b.a.z)
open tactic
def d : D :=
begin
tidy,
-- Try this: fsplit, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl } }, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl } }, work_on_goal 1 { refl } }, refl
end.
def f : unit → unit → unit := by tidy -- intros a a_1, cases a_1, cases a, fsplit
def g (P Q : Prop) (p : P) (h : P ↔ Q) : Q := by tidy
end tidy.test
|
e636302ba9526f934a74a8ea8bb879c87d7b2ccc | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /data/sum.lean | 8059a96e9be9b2684fbe6099c4dee497da085de3 | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 3,196 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
More theorems about the sum type.
-/
universes u v
variables {α : Type u} {β : Type v}
open sum
attribute [derive decidable_eq] sum
@[simp] theorem sum.forall {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ (∀ b, p (inr b)) :=
⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩
@[simp] theorem sum.exists {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) :=
⟨λ h, match h with
| ⟨inl a, h⟩ := or.inl ⟨a, h⟩
| ⟨inr b, h⟩ := or.inr ⟨b, h⟩
end, λ h, match h with
| or.inl ⟨a, h⟩ := ⟨inl a, h⟩
| or.inr ⟨b, h⟩ := ⟨inr b, h⟩
end⟩
namespace sum
@[simp] theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b :=
⟨inl.inj, congr_arg _⟩
@[simp] theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b :=
⟨inr.inj, congr_arg _⟩
@[simp] theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b.
@[simp] theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a.
section
variables (ra : α → α → Prop) (rb : β → β → Prop)
/-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`,
otherwise use the respective order on `α` or `β`. -/
inductive lex : α ⊕ β → α ⊕ β → Prop
| inl {a₁ a₂} (h : ra a₁ a₂) : lex (inl a₁) (inl a₂)
| inr {b₁ b₂} (h : rb b₁ b₂) : lex (inr b₁) (inr b₂)
| sep (a b) : lex (inl a) (inr b)
variables {ra rb}
@[simp] theorem lex_inl_inl {a₁ a₂} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ :=
⟨λ h, by cases h; assumption, lex.inl _⟩
@[simp] theorem lex_inr_inr {b₁ b₂} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ :=
⟨λ h, by cases h; assumption, lex.inr _⟩
@[simp] theorem lex_inr_inl {b a} : ¬ lex ra rb (inr b) (inl a) :=
λ h, by cases h
attribute [simp] lex.sep
theorem lex_acc_inl {a} (aca : acc ra a) : acc (lex ra rb) (inl a) :=
begin
induction aca with a H IH,
constructor, intros y h,
cases h with a' _ h',
exact IH _ h'
end
theorem lex_acc_inr (aca : ∀ a, acc (lex ra rb) (inl a)) {b} (acb : acc rb b) : acc (lex ra rb) (inr b) :=
begin
induction acb with b H IH,
constructor, intros y h,
cases h with _ _ _ b' _ h' a,
{ exact IH _ h' },
{ exact aca _ }
end
theorem lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) :=
have aca : ∀ a, acc (lex ra rb) (inl a), from λ a, lex_acc_inl (ha.apply a),
⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩
end
/-- Swap the factors of a sum type -/
@[simp] def swap : α ⊕ β → β ⊕ α
| (inl a) := inr a
| (inr b) := inl b
@[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x :=
by cases x; refl
@[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) :=
funext $ swap_swap
@[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap :=
swap_swap
@[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap :=
swap_swap
end sum
|
69603cad52a4830e26265dc14c9cbc9ab22eb1f9 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/field_theory/is_alg_closed/classification.lean | e5531dbd147b42f1f293e0969b01291340ce055a | [
"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 | 8,657 | lean | /-
Copyright (c) 2022 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.W.cardinal
import ring_theory.algebraic_independent
import field_theory.is_alg_closed.basic
import field_theory.intermediate_field
import data.polynomial.cardinal
import data.mv_polynomial.cardinal
import data.zmod.algebra
/-!
# Classification of Algebraically closed fields
This file contains results related to classifying algebraically closed fields.
## Main statements
* `is_alg_closed.equiv_of_transcendence_basis` Two fields with the same characteristic and the same
cardinality of transcendence basis are isomorphic.
* `is_alg_closed.ring_equiv_of_cardinal_eq_of_char_eq` Two uncountable algebraically closed fields
are isomorphic if they have the same characteristic and the same cardinality.
-/
universe u
open_locale cardinal
open cardinal
section algebraic_closure
namespace algebra.is_algebraic
variables (R L : Type u) [comm_ring R] [comm_ring L] [is_domain L] [algebra R L]
variables [no_zero_smul_divisors R L] (halg : algebra.is_algebraic R L)
lemma cardinal_mk_le_sigma_polynomial :
#L ≤ #(Σ p : polynomial R, { x : L // x ∈ (p.map (algebra_map R L)).roots }) :=
@mk_le_of_injective L (Σ p : polynomial R, { x : L | x ∈ (p.map (algebra_map R L)).roots })
(λ x : L, let p := classical.indefinite_description _ (halg x) in
⟨p.1, x,
begin
dsimp,
have h : p.1.map (algebra_map R L) ≠ 0,
{ rw [ne.def, ← polynomial.degree_eq_bot, polynomial.degree_map_eq_of_injective
(no_zero_smul_divisors.algebra_map_injective R L), polynomial.degree_eq_bot],
exact p.2.1 },
erw [polynomial.mem_roots h, polynomial.is_root, polynomial.eval_map,
← polynomial.aeval_def, p.2.2],
end⟩) (λ x y, begin
intro h,
simp only at h,
refine (subtype.heq_iff_coe_eq _).1 h.2,
simp only [h.1, iff_self, forall_true_iff]
end)
/--The cardinality of an algebraic extension is at most the maximum of the cardinality
of the base ring or `ω` -/
lemma cardinal_mk_le_max : #L ≤ max (#R) ω :=
calc #L ≤ #(Σ p : polynomial R, { x : L // x ∈ (p.map (algebra_map R L)).roots }) :
cardinal_mk_le_sigma_polynomial R L halg
... = cardinal.sum (λ p : polynomial R, #{ x : L | x ∈ (p.map (algebra_map R L)).roots }) :
by rw ← mk_sigma; refl
... ≤ cardinal.sum.{u u} (λ p : polynomial R, ω) : sum_le_sum _ _
(λ p, le_of_lt begin
rw [lt_omega_iff_finite],
classical,
simp only [← @multiset.mem_to_finset _ _ _ (p.map (algebra_map R L)).roots],
exact set.finite_mem_finset _,
end)
... = #(polynomial R) * ω : sum_const' _ _
... ≤ max (max (#(polynomial R)) ω) ω : mul_le_max _ _
... ≤ max (max (max (#R) ω) ω) ω :
max_le_max (max_le_max polynomial.cardinal_mk_le_max le_rfl) le_rfl
... = max (#R) ω : by simp only [max_assoc, max_comm omega.{u}, max_left_comm omega.{u}, max_self]
end algebra.is_algebraic
end algebraic_closure
namespace is_alg_closed
section classification
noncomputable theory
variables {R L K : Type*} [comm_ring R]
variables [field K] [algebra R K]
variables [field L] [algebra R L]
variables {ι : Type*} (v : ι → K)
variables {κ : Type*} (w : κ → L)
variables (hv : algebraic_independent R v)
lemma is_alg_closure_of_transcendence_basis [is_alg_closed K] (hv : is_transcendence_basis R v) :
is_alg_closure (algebra.adjoin R (set.range v)) K :=
by letI := ring_hom.domain_nontrivial (algebra_map R K); exact
{ alg_closed := by apply_instance,
algebraic := hv.is_algebraic }
variables (hw : algebraic_independent R w)
/-- setting `R` to be `zmod (ring_char R)` this result shows that if two algebraically
closed fields have equipotent transcendence bases and the same characteristic then they are
isomorphic. -/
def equiv_of_transcendence_basis [is_alg_closed K] [is_alg_closed L] (e : ι ≃ κ)
(hv : is_transcendence_basis R v) (hw : is_transcendence_basis R w) : K ≃+* L :=
begin
letI := is_alg_closure_of_transcendence_basis v hv;
letI := is_alg_closure_of_transcendence_basis w hw;
have e : algebra.adjoin R (set.range v) ≃+* algebra.adjoin R (set.range w),
{ refine hv.1.aeval_equiv.symm.to_ring_equiv.trans _,
refine (alg_equiv.of_alg_hom
(mv_polynomial.rename e)
(mv_polynomial.rename e.symm)
_ _).to_ring_equiv.trans _,
{ ext, simp },
{ ext, simp },
exact hw.1.aeval_equiv.to_ring_equiv },
exact is_alg_closure.equiv_of_equiv K L e
end
end classification
section cardinal
variables {R L K : Type u} [comm_ring R]
variables [field K] [algebra R K] [is_alg_closed K]
variables {ι : Type u} (v : ι → K)
variable (hv : is_transcendence_basis R v)
lemma cardinal_le_max_transcendence_basis (hv : is_transcendence_basis R v) :
#K ≤ max (max (#R) (#ι)) ω :=
calc #K ≤ max (#(algebra.adjoin R (set.range v))) ω :
by letI := is_alg_closure_of_transcendence_basis v hv;
exact algebra.is_algebraic.cardinal_mk_le_max _ _ is_alg_closure.algebraic
... = max (#(mv_polynomial ι R)) ω : by rw [cardinal.eq.2 ⟨(hv.1.aeval_equiv).to_equiv⟩]
... ≤ max (max (max (#R) (#ι)) ω) ω : max_le_max mv_polynomial.cardinal_mk_le_max le_rfl
... = _ : by simp [max_assoc]
/-- If `K` is an uncountable algebraically closed field, then its
cardinality is the same as that of a transcendence basis. -/
lemma cardinal_eq_cardinal_transcendence_basis_of_omega_lt [nontrivial R]
(hv : is_transcendence_basis R v) (hR : #R ≤ ω) (hK : ω < #K) : #K = #ι :=
have ω ≤ #ι,
from le_of_not_lt (λ h,
not_le_of_gt hK $ calc
#K ≤ max (max (#R) (#ι)) ω : cardinal_le_max_transcendence_basis v hv
... ≤ _ : max_le (max_le hR (le_of_lt h)) le_rfl),
le_antisymm
(calc #K ≤ max (max (#R) (#ι)) ω : cardinal_le_max_transcendence_basis v hv
... = #ι : begin
rw [max_eq_left, max_eq_right],
{ exact le_trans hR this },
{ exact le_max_of_le_right this }
end)
(mk_le_of_injective (show function.injective v, from hv.1.injective))
end cardinal
variables {K L : Type} [field K] [field L] [is_alg_closed K] [is_alg_closed L]
/-- Two uncountable algebraically closed fields of characteristic zero are isomorphic
if they have the same cardinality. -/
@[nolint def_lemma] lemma ring_equiv_of_cardinal_eq_of_char_zero [char_zero K] [char_zero L]
(hK : ω < #K) (hKL : #K = #L) : K ≃+* L :=
begin
apply classical.choice,
cases exists_is_transcendence_basis ℤ
(show function.injective (algebra_map ℤ K),
from int.cast_injective) with s hs,
cases exists_is_transcendence_basis ℤ
(show function.injective (algebra_map ℤ L),
from int.cast_injective) with t ht,
have : #s = #t,
{ rw [← cardinal_eq_cardinal_transcendence_basis_of_omega_lt _ hs (le_of_eq mk_int) hK,
← cardinal_eq_cardinal_transcendence_basis_of_omega_lt _ ht (le_of_eq mk_int), hKL],
rwa ← hKL },
cases cardinal.eq.1 this with e,
exact ⟨equiv_of_transcendence_basis _ _ e hs ht⟩
end
private lemma ring_equiv_of_cardinal_eq_of_char_p (p : ℕ) [fact p.prime]
[char_p K p] [char_p L p] (hK : ω < #K) (hKL : #K = #L) : K ≃+* L :=
begin
apply classical.choice,
cases exists_is_transcendence_basis (zmod p)
(show function.injective (algebra_map (zmod p) K),
from ring_hom.injective _) with s hs,
cases exists_is_transcendence_basis (zmod p)
(show function.injective (algebra_map (zmod p) L),
from ring_hom.injective _) with t ht,
have : #s = #t,
{ rw [← cardinal_eq_cardinal_transcendence_basis_of_omega_lt _ hs
(le_of_lt $ lt_omega_iff_fintype.2 ⟨infer_instance⟩) hK,
← cardinal_eq_cardinal_transcendence_basis_of_omega_lt _ ht
(le_of_lt $ lt_omega_iff_fintype.2 ⟨infer_instance⟩), hKL],
rwa ← hKL },
cases cardinal.eq.1 this with e,
exact ⟨equiv_of_transcendence_basis _ _ e hs ht⟩
end
/-- Two uncountable algebraically closed fields are isomorphic
if they have the same cardinality and the same characteristic. -/
@[nolint def_lemma] lemma ring_equiv_of_cardinal_eq_of_char_eq (p : ℕ) [char_p K p] [char_p L p]
(hK : ω < #K) (hKL : #K = #L) : K ≃+* L :=
begin
apply classical.choice,
rcases char_p.char_is_prime_or_zero K p with hp | hp,
{ haveI : fact p.prime := ⟨hp⟩,
exact ⟨ring_equiv_of_cardinal_eq_of_char_p p hK hKL⟩ },
{ rw [hp] at *,
resetI,
letI : char_zero K := char_p.char_p_to_char_zero K,
letI : char_zero L := char_p.char_p_to_char_zero L,
exact ⟨ring_equiv_of_cardinal_eq_of_char_zero hK hKL⟩ }
end
end is_alg_closed
|
f7fda414494aa432f51c1abdaf74fdbf6c847e48 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/algebra/spectrum.lean | cb2b97534386c475cba746ad19b170c8816b9017 | [
"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 | 19,351 | lean | /-
Copyright (c) 2021 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import tactic.noncomm_ring
import field_theory.is_alg_closed.basic
import algebra.star.pointwise
/-!
# Spectrum of an element in an algebra
This file develops the basic theory of the spectrum of an element of an algebra.
This theory will serve as the foundation for spectral theory in Banach algebras.
## Main definitions
* `resolvent_set a : set R`: the resolvent set of an element `a : A` where
`A` is an `R`-algebra.
* `spectrum a : set R`: the spectrum of an element `a : A` where
`A` is an `R`-algebra.
* `resolvent : R → A`: the resolvent function is `λ r, ring.inverse (↑ₐr - a)`, and hence
when `r ∈ resolvent R A`, it is actually the inverse of the unit `(↑ₐr - a)`.
## Main statements
* `spectrum.unit_smul_eq_smul` and `spectrum.smul_eq_smul`: units in the scalar ring commute
(multiplication) with the spectrum, and over a field even `0` commutes with the spectrum.
* `spectrum.left_add_coset_eq`: elements of the scalar ring commute (addition) with the spectrum.
* `spectrum.unit_mem_mul_iff_mem_swap_mul` and `spectrum.preimage_units_mul_eq_swap_mul`: the
units (of `R`) in `σ (a*b)` coincide with those in `σ (b*a)`.
* `spectrum.scalar_eq`: in a nontrivial algebra over a field, the spectrum of a scalar is
a singleton.
* `spectrum.subset_polynomial_aeval`, `spectrum.map_polynomial_aeval_of_degree_pos`,
`spectrum.map_polynomial_aeval_of_nonempty`: variations on the spectral mapping theorem.
## Notations
* `σ a` : `spectrum R a` of `a : A`
-/
open set
universes u v
section defs
variables (R : Type u) {A : Type v}
variables [comm_semiring R] [ring A] [algebra R A]
local notation `↑ₐ` := algebra_map R A
-- definition and basic properties
/-- Given a commutative ring `R` and an `R`-algebra `A`, the *resolvent set* of `a : A`
is the `set R` consisting of those `r : R` for which `r•1 - a` is a unit of the
algebra `A`. -/
def resolvent_set (a : A) : set R :=
{ r : R | is_unit (↑ₐr - a) }
/-- Given a commutative ring `R` and an `R`-algebra `A`, the *spectrum* of `a : A`
is the `set R` consisting of those `r : R` for which `r•1 - a` is not a unit of the
algebra `A`.
The spectrum is simply the complement of the resolvent set. -/
def spectrum (a : A) : set R :=
(resolvent_set R a)ᶜ
variable {R}
/-- Given an `a : A` where `A` is an `R`-algebra, the *resolvent* is
a map `R → A` which sends `r : R` to `(algebra_map R A r - a)⁻¹` when
`r ∈ resolvent R A` and `0` when `r ∈ spectrum R A`. -/
noncomputable def resolvent (a : A) (r : R) : A :=
ring.inverse (↑ₐr - a)
/-- The unit `1 - r⁻¹ • a` constructed from `r • 1 - a` when the latter is a unit. -/
@[simps]
noncomputable def is_unit.sub_inv_smul {r : Rˣ} {s : R} {a : A}
(h : is_unit $ r • ↑ₐs - a) : Aˣ :=
{ val := ↑ₐs - r⁻¹ • a,
inv := r • ↑h.unit⁻¹,
val_inv := by rw [mul_smul_comm, ←smul_mul_assoc, smul_sub, smul_inv_smul, h.mul_coe_inv],
inv_val := by rw [smul_mul_assoc, ←mul_smul_comm, smul_sub, smul_inv_smul, h.coe_inv_mul], }
end defs
namespace spectrum
open_locale polynomial
section scalar_semiring
variables {R : Type u} {A : Type v}
variables [comm_semiring R] [ring A] [algebra R A]
local notation `σ` := spectrum R
local notation `↑ₐ` := algebra_map R A
lemma mem_iff {r : R} {a : A} :
r ∈ σ a ↔ ¬ is_unit (↑ₐr - a) :=
iff.rfl
lemma not_mem_iff {r : R} {a : A} :
r ∉ σ a ↔ is_unit (↑ₐr - a) :=
by { apply not_iff_not.mp, simp [set.not_not_mem, mem_iff] }
lemma mem_resolvent_set_of_left_right_inverse {r : R} {a b c : A}
(h₁ : (↑ₐr - a) * b = 1) (h₂ : c * (↑ₐr - a) = 1) :
r ∈ resolvent_set R a :=
units.is_unit ⟨↑ₐr - a, b, h₁, by rwa ←left_inv_eq_right_inv h₂ h₁⟩
lemma mem_resolvent_set_iff {r : R} {a : A} :
r ∈ resolvent_set R a ↔ is_unit (↑ₐr - a) :=
iff.rfl
@[simp] lemma resolvent_set_of_subsingleton [subsingleton A] (a : A) :
resolvent_set R a = set.univ :=
by simp_rw [resolvent_set, subsingleton.elim (algebra_map R A _ - a) 1, is_unit_one,
set.set_of_true]
@[simp] lemma of_subsingleton [subsingleton A] (a : A) :
spectrum R a = ∅ :=
by rw [spectrum, resolvent_set_of_subsingleton, set.compl_univ]
lemma resolvent_eq {a : A} {r : R} (h : r ∈ resolvent_set R a) :
resolvent a r = ↑h.unit⁻¹ :=
ring.inverse_unit h.unit
lemma units_smul_resolvent {r : Rˣ} {s : R} {a : A} :
r • resolvent a (s : R) = resolvent (r⁻¹ • a) (r⁻¹ • s : R) :=
begin
by_cases h : s ∈ spectrum R a,
{ rw [mem_iff] at h,
simp only [resolvent, algebra.algebra_map_eq_smul_one] at *,
rw [smul_assoc, ←smul_sub],
have h' : ¬ is_unit (r⁻¹ • (s • 1 - a)),
from λ hu, h (by simpa only [smul_inv_smul] using is_unit.smul r hu),
simp only [ring.inverse_non_unit _ h, ring.inverse_non_unit _ h', smul_zero] },
{ simp only [resolvent],
have h' : is_unit (r • (algebra_map R A (r⁻¹ • s)) - a),
{ simpa [algebra.algebra_map_eq_smul_one, smul_assoc] using not_mem_iff.mp h },
rw [←h'.coe_sub_inv_smul, ←(not_mem_iff.mp h).unit_spec, ring.inverse_unit, ring.inverse_unit,
h'.coe_inv_sub_inv_smul],
simp only [algebra.algebra_map_eq_smul_one, smul_assoc, smul_inv_smul], },
end
lemma units_smul_resolvent_self {r : Rˣ} {a : A} :
r • resolvent a (r : R) = resolvent (r⁻¹ • a) (1 : R) :=
by simpa only [units.smul_def, algebra.id.smul_eq_mul, units.inv_mul]
using @units_smul_resolvent _ _ _ _ _ r r a
/-- The resolvent is a unit when the argument is in the resolvent set. -/
lemma is_unit_resolvent {r : R} {a : A} :
r ∈ resolvent_set R a ↔ is_unit (resolvent a r) :=
is_unit_ring_inverse.symm
lemma inv_mem_resolvent_set {r : Rˣ} {a : Aˣ} (h : (r : R) ∈ resolvent_set R (a : A)) :
(↑r⁻¹ : R) ∈ resolvent_set R (↑a⁻¹ : A) :=
begin
rw [mem_resolvent_set_iff, algebra.algebra_map_eq_smul_one, ←units.smul_def] at h ⊢,
rw [is_unit.smul_sub_iff_sub_inv_smul, inv_inv, is_unit.sub_iff],
have h₁ : (a : A) * (r • (↑a⁻¹ : A) - 1) = r • 1 - a,
{ rw [mul_sub, mul_smul_comm, a.mul_inv, mul_one], },
have h₂ : (r • (↑a⁻¹ : A) - 1) * a = r • 1 - a,
{ rw [sub_mul, smul_mul_assoc, a.inv_mul, one_mul], },
have hcomm : commute (a : A) (r • (↑a⁻¹ : A) - 1), { rwa ←h₂ at h₁ },
exact (hcomm.is_unit_mul_iff.mp (h₁.symm ▸ h)).2,
end
lemma inv_mem_iff {r : Rˣ} {a : Aˣ} :
(r : R) ∈ σ (a : A) ↔ (↑r⁻¹ : R) ∈ σ (↑a⁻¹ : A) :=
begin
simp only [mem_iff, not_iff_not, ←mem_resolvent_set_iff],
exact ⟨λ h, inv_mem_resolvent_set h, λ h, by simpa using inv_mem_resolvent_set h⟩,
end
lemma zero_mem_resolvent_set_of_unit (a : Aˣ) : 0 ∈ resolvent_set R (a : A) :=
by { rw [mem_resolvent_set_iff, is_unit.sub_iff], simp }
lemma ne_zero_of_mem_of_unit {a : Aˣ} {r : R} (hr : r ∈ σ (a : A)) : r ≠ 0 :=
λ hn, (hn ▸ hr) (zero_mem_resolvent_set_of_unit a)
lemma add_mem_iff {a : A} {r s : R} :
r ∈ σ a ↔ r + s ∈ σ (↑ₐs + a) :=
begin
apply not_iff_not.mpr,
simp only [mem_resolvent_set_iff],
have h_eq : ↑ₐ(r + s) - (↑ₐs + a) = ↑ₐr - a,
{ simp, noncomm_ring },
rw h_eq,
end
lemma smul_mem_smul_iff {a : A} {s : R} {r : Rˣ} :
r • s ∈ σ (r • a) ↔ s ∈ σ a :=
begin
apply not_iff_not.mpr,
simp only [mem_resolvent_set_iff, algebra.algebra_map_eq_smul_one],
have h_eq : (r • s) • (1 : A) = r • s • 1, by simp,
rw [h_eq, ←smul_sub, is_unit_smul_iff],
end
open_locale pointwise polynomial
theorem unit_smul_eq_smul (a : A) (r : Rˣ) :
σ (r • a) = r • σ a :=
begin
ext,
have x_eq : x = r • r⁻¹ • x, by simp,
nth_rewrite 0 x_eq,
rw smul_mem_smul_iff,
split,
{ exact λ h, ⟨r⁻¹ • x, ⟨h, by simp⟩⟩},
{ rintros ⟨_, _, x'_eq⟩, simpa [←x'_eq],}
end
-- `r ∈ σ(a*b) ↔ r ∈ σ(b*a)` for any `r : Rˣ`
theorem unit_mem_mul_iff_mem_swap_mul {a b : A} {r : Rˣ} :
↑r ∈ σ (a * b) ↔ ↑r ∈ σ (b * a) :=
begin
apply not_iff_not.mpr,
simp only [mem_resolvent_set_iff, algebra.algebra_map_eq_smul_one],
have coe_smul_eq : ↑r • 1 = r • (1 : A), from rfl,
rw coe_smul_eq,
simp only [is_unit.smul_sub_iff_sub_inv_smul],
have right_inv_of_swap : ∀ {x y z : A} (h : (1 - x * y) * z = 1),
(1 - y * x) * (1 + y * z * x) = 1, from λ x y z h,
calc (1 - y * x) * (1 + y * z * x) = 1 - y * x + y * ((1 - x * y) * z) * x : by noncomm_ring
... = 1 : by simp [h],
have left_inv_of_swap : ∀ {x y z : A} (h : z * (1 - x * y) = 1),
(1 + y * z * x) * (1 - y * x) = 1, from λ x y z h,
calc (1 + y * z * x) * (1 - y * x) = 1 - y * x + y * (z * (1 - x * y)) * x : by noncomm_ring
... = 1 : by simp [h],
have is_unit_one_sub_mul_of_swap : ∀ {x y : A} (h : is_unit (1 - x * y)),
is_unit (1 - y * x), from λ x y h, by
{ let h₁ := right_inv_of_swap h.unit.val_inv,
let h₂ := left_inv_of_swap h.unit.inv_val,
exact ⟨⟨1 - y * x, 1 + y * h.unit.inv * x, h₁, h₂⟩, rfl⟩, },
have is_unit_one_sub_mul_iff_swap : ∀ {x y : A},
is_unit (1 - x * y) ↔ is_unit (1 - y * x), by
{ intros, split, repeat {apply is_unit_one_sub_mul_of_swap}, },
rw [←smul_mul_assoc, ←mul_smul_comm r⁻¹ b a, is_unit_one_sub_mul_iff_swap],
end
theorem preimage_units_mul_eq_swap_mul {a b : A} :
(coe : Rˣ → R) ⁻¹' σ (a * b) = coe ⁻¹' σ (b * a) :=
by { ext, exact unit_mem_mul_iff_mem_swap_mul, }
section star
variables [has_involutive_star R] [star_ring A] [star_module R A]
lemma star_mem_resolvent_set_iff {r : R} {a : A} :
star r ∈ resolvent_set R a ↔ r ∈ resolvent_set R (star a) :=
by refine ⟨λ h, _, λ h, _⟩;
simpa only [mem_resolvent_set_iff, algebra.algebra_map_eq_smul_one, star_sub, star_smul,
star_star, star_one] using is_unit.star h
protected lemma map_star (a : A) : σ (star a) = star (σ a) :=
by { ext, simpa only [set.mem_star, mem_iff, not_iff_not] using star_mem_resolvent_set_iff.symm }
end star
end scalar_semiring
section scalar_ring
variables {R : Type u} {A : Type v}
variables [comm_ring R] [ring A] [algebra R A]
local notation `σ` := spectrum R
local notation `↑ₐ` := algebra_map R A
theorem left_add_coset_eq (a : A) (r : R) :
left_add_coset r (σ a) = σ (↑ₐr + a) :=
by { ext, rw [mem_left_add_coset_iff, neg_add_eq_sub, add_mem_iff],
nth_rewrite 1 ←sub_add_cancel x r, }
open polynomial
lemma exists_mem_of_not_is_unit_aeval_prod [is_domain R] {p : R[X]} {a : A} (hp : p ≠ 0)
(h : ¬is_unit (aeval a (multiset.map (λ (x : R), X - C x) p.roots).prod)) :
∃ k : R, k ∈ σ a ∧ eval k p = 0 :=
begin
rw [←multiset.prod_to_list, alg_hom.map_list_prod] at h,
replace h := mt list.prod_is_unit h,
simp only [not_forall, exists_prop, aeval_C, multiset.mem_to_list,
list.mem_map, aeval_X, exists_exists_and_eq_and, multiset.mem_map, alg_hom.map_sub] at h,
rcases h with ⟨r, r_mem, r_nu⟩,
exact ⟨r, by rwa [mem_iff, ←is_unit.sub_iff], by rwa [←is_root.def, ←mem_roots hp]⟩
end
end scalar_ring
section scalar_field
variables {𝕜 : Type u} {A : Type v}
variables [field 𝕜] [ring A] [algebra 𝕜 A]
local notation `σ` := spectrum 𝕜
local notation `↑ₐ` := algebra_map 𝕜 A
/-- Without the assumption `nontrivial A`, then `0 : A` would be invertible. -/
@[simp] lemma zero_eq [nontrivial A] : σ (0 : A) = {0} :=
begin
refine set.subset.antisymm _ (by simp [algebra.algebra_map_eq_smul_one, mem_iff]),
rw [spectrum, set.compl_subset_comm],
intros k hk,
rw set.mem_compl_singleton_iff at hk,
have : is_unit (units.mk0 k hk • (1 : A)) := is_unit.smul (units.mk0 k hk) is_unit_one,
simpa [mem_resolvent_set_iff, algebra.algebra_map_eq_smul_one]
end
@[simp] theorem scalar_eq [nontrivial A] (k : 𝕜) : σ (↑ₐk) = {k} :=
begin
have coset_eq : left_add_coset k {0} = {k}, by
{ ext, split,
{ intro hx, simp [left_add_coset] at hx, exact hx, },
{ intro hx, simp at hx, exact ⟨0, ⟨set.mem_singleton 0, by simp [hx]⟩⟩, }, },
calc σ (↑ₐk) = σ (↑ₐk + 0) : by simp
... = left_add_coset k (σ (0 : A)) : by rw ←left_add_coset_eq
... = left_add_coset k {0} : by rw zero_eq
... = {k} : coset_eq,
end
@[simp] lemma one_eq [nontrivial A] : σ (1 : A) = {1} :=
calc σ (1 : A) = σ (↑ₐ1) : by simp [algebra.algebra_map_eq_smul_one]
... = {1} : scalar_eq 1
open_locale pointwise
/-- the assumption `(σ a).nonempty` is necessary and cannot be removed without
further conditions on the algebra `A` and scalar field `𝕜`. -/
theorem smul_eq_smul [nontrivial A] (k : 𝕜) (a : A) (ha : (σ a).nonempty) :
σ (k • a) = k • (σ a) :=
begin
rcases eq_or_ne k 0 with rfl | h,
{ simpa [ha, zero_smul_set] },
{ exact unit_smul_eq_smul a (units.mk0 k h) },
end
theorem nonzero_mul_eq_swap_mul (a b : A) : σ (a * b) \ {0} = σ (b * a) \ {0} :=
begin
suffices h : ∀ (x y : A), σ (x * y) \ {0} ⊆ σ (y * x) \ {0},
{ exact set.eq_of_subset_of_subset (h a b) (h b a) },
{ rintros _ _ k ⟨k_mem, k_neq⟩,
change k with ↑(units.mk0 k k_neq) at k_mem,
exact ⟨unit_mem_mul_iff_mem_swap_mul.mp k_mem, k_neq⟩ },
end
protected lemma map_inv (a : Aˣ) : (σ (a : A))⁻¹ = σ (↑a⁻¹ : A) :=
begin
refine set.eq_of_subset_of_subset (λ k hk, _) (λ k hk, _),
{ rw set.mem_inv at hk,
have : k ≠ 0,
{ simpa only [inv_inv] using inv_ne_zero (ne_zero_of_mem_of_unit hk), },
lift k to 𝕜ˣ using is_unit_iff_ne_zero.mpr this,
rw ←units.coe_inv k at hk,
exact inv_mem_iff.mp hk },
{ lift k to 𝕜ˣ using is_unit_iff_ne_zero.mpr (ne_zero_of_mem_of_unit hk),
simpa only [units.coe_inv] using inv_mem_iff.mp hk, }
end
open polynomial
/-- Half of the spectral mapping theorem for polynomials. We prove it separately
because it holds over any field, whereas `spectrum.map_polynomial_aeval_of_degree_pos` and
`spectrum.map_polynomial_aeval_of_nonempty` need the field to be algebraically closed. -/
theorem subset_polynomial_aeval (a : A) (p : 𝕜[X]) :
(λ k, eval k p) '' (σ a) ⊆ σ (aeval a p) :=
begin
rintros _ ⟨k, hk, rfl⟩,
let q := C (eval k p) - p,
have hroot : is_root q k, by simp only [eval_C, eval_sub, sub_self, is_root.def],
rw [←mul_div_eq_iff_is_root, ←neg_mul_neg, neg_sub] at hroot,
have aeval_q_eq : ↑ₐ(eval k p) - aeval a p = aeval a q,
by simp only [aeval_C, alg_hom.map_sub, sub_left_inj],
rw [mem_iff, aeval_q_eq, ←hroot, aeval_mul],
have hcomm := (commute.all (C k - X) (- (q / (X - C k)))).map (aeval a),
apply mt (λ h, (hcomm.is_unit_mul_iff.mp h).1),
simpa only [aeval_X, aeval_C, alg_hom.map_sub] using hk,
end
/-- The *spectral mapping theorem* for polynomials. Note: the assumption `degree p > 0`
is necessary in case `σ a = ∅`, for then the left-hand side is `∅` and the right-hand side,
assuming `[nontrivial A]`, is `{k}` where `p = polynomial.C k`. -/
theorem map_polynomial_aeval_of_degree_pos [is_alg_closed 𝕜] (a : A) (p : 𝕜[X])
(hdeg : 0 < degree p) : σ (aeval a p) = (λ k, eval k p) '' (σ a) :=
begin
/- handle the easy direction via `spectrum.subset_polynomial_aeval` -/
refine set.eq_of_subset_of_subset (λ k hk, _) (subset_polynomial_aeval a p),
/- write `C k - p` product of linear factors and a constant; show `C k - p ≠ 0`. -/
have hprod := eq_prod_roots_of_splits_id (is_alg_closed.splits (C k - p)),
have h_ne : C k - p ≠ 0, from ne_zero_of_degree_gt
(by rwa [degree_sub_eq_right_of_degree_lt (lt_of_le_of_lt degree_C_le hdeg)]),
have lead_ne := leading_coeff_ne_zero.mpr h_ne,
have lead_unit := (units.map (↑ₐ).to_monoid_hom (units.mk0 _ lead_ne)).is_unit,
/- leading coefficient is a unit so product of linear factors is not a unit;
apply `exists_mem_of_not_is_unit_aeval_prod`. -/
have p_a_eq : aeval a (C k - p) = ↑ₐk - aeval a p,
by simp only [aeval_C, alg_hom.map_sub, sub_left_inj],
rw [mem_iff, ←p_a_eq, hprod, aeval_mul,
((commute.all _ _).map (aeval a)).is_unit_mul_iff, aeval_C] at hk,
replace hk := exists_mem_of_not_is_unit_aeval_prod h_ne (not_and.mp hk lead_unit),
rcases hk with ⟨r, r_mem, r_ev⟩,
exact ⟨r, r_mem, symm (by simpa [eval_sub, eval_C, sub_eq_zero] using r_ev)⟩,
end
/-- In this version of the spectral mapping theorem, we assume the spectrum
is nonempty instead of assuming the degree of the polynomial is positive. Note: the
assumption `[nontrivial A]` is necessary for the same reason as in `spectrum.zero_eq`. -/
theorem map_polynomial_aeval_of_nonempty [is_alg_closed 𝕜] [nontrivial A] (a : A) (p : 𝕜[X])
(hnon : (σ a).nonempty) : σ (aeval a p) = (λ k, eval k p) '' (σ a) :=
begin
refine or.elim (le_or_gt (degree p) 0) (λ h, _) (map_polynomial_aeval_of_degree_pos a p),
{ rw eq_C_of_degree_le_zero h,
simp only [set.image_congr, eval_C, aeval_C, scalar_eq, set.nonempty.image_const hnon] },
end
variable (𝕜)
/--
Every element `a` in a nontrivial finite-dimensional algebra `A`
over an algebraically closed field `𝕜` has non-empty spectrum. -/
-- We will use this both to show eigenvalues exist, and to prove Schur's lemma.
lemma nonempty_of_is_alg_closed_of_finite_dimensional [is_alg_closed 𝕜]
[nontrivial A] [I : finite_dimensional 𝕜 A] (a : A) :
∃ k : 𝕜, k ∈ σ a :=
begin
obtain ⟨p, ⟨h_mon, h_eval_p⟩⟩ := is_integral_of_noetherian (is_noetherian.iff_fg.2 I) a,
have nu : ¬ is_unit (aeval a p), { rw [←aeval_def] at h_eval_p, rw h_eval_p, simp, },
rw [eq_prod_roots_of_monic_of_splits_id h_mon (is_alg_closed.splits p)] at nu,
obtain ⟨k, hk, _⟩ := exists_mem_of_not_is_unit_aeval_prod (monic.ne_zero h_mon) nu,
exact ⟨k, hk⟩
end
end scalar_field
end spectrum
namespace alg_hom
section comm_semiring
variables {R : Type*} {A B : Type*} [comm_ring R] [ring A] [algebra R A] [ring B] [algebra R B]
local notation `σ` := spectrum R
local notation `↑ₐ` := algebra_map R A
lemma mem_resolvent_set_apply (φ : A →ₐ[R] B) {a : A} {r : R} (h : r ∈ resolvent_set R a) :
r ∈ resolvent_set R (φ a) :=
by simpa only [map_sub, commutes] using h.map φ
lemma spectrum_apply_subset (φ : A →ₐ[R] B) (a : A) : σ (φ a) ⊆ σ a :=
λ _, mt (mem_resolvent_set_apply φ)
end comm_semiring
section comm_ring
variables {R : Type*} {A B : Type*} [comm_ring R] [ring A] [algebra R A] [ring B] [algebra R B]
local notation `σ` := spectrum R
local notation `↑ₐ` := algebra_map R A
lemma apply_mem_spectrum [nontrivial R] (φ : A →ₐ[R] R) (a : A) : φ a ∈ σ a :=
begin
have h : ↑ₐ(φ a) - a ∈ φ.to_ring_hom.ker,
{ simp only [ring_hom.mem_ker, coe_to_ring_hom, commutes, algebra.id.map_eq_id,
to_ring_hom_eq_coe, ring_hom.id_apply, sub_self, map_sub] },
simp only [spectrum.mem_iff, ←mem_nonunits_iff,
coe_subset_nonunits (φ.to_ring_hom.ker_ne_top) h],
end
end comm_ring
end alg_hom
|
09091e89a8908755d095ade84f9bd70eabd4d25c | fef48cac17c73db8662678da38fd75888db97560 | /src/squares_in_fibonacci.lean | 52e95e3617a02e2047843a1745dec684f984c086 | [] | no_license | kbuzzard/lean-squares-in-fibonacci | 6c0d924f799d6751e19798bb2530ee602ec7087e | 8cea20e5ce88ab7d17b020932d84d316532a84a8 | refs/heads/master | 1,584,524,504,815 | 1,582,387,156,000 | 1,582,387,156,000 | 134,576,655 | 3 | 1 | null | 1,541,538,497,000 | 1,527,083,406,000 | Lean | UTF-8 | Lean | false | false | 570 | lean |
/-
Copyright (c) 2018 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kevin Buzzard, Kenny Lau,
144 is the largest square in the Fibonacci sequence.
-/
/- 144 is the largest square in the Fibonacci sequence.
Copyright Kevin Buzzard.
Authors :
Kevin Buzzard
Nicholas Scheel
Kenny Lau
Reid Barton
-/
-- definition of Fibonacci sequence
import definitions
-- Statement of main theorem
theorem largest_square_in_fibonacci_sequence (n d : ℕ) : fib n = d ^ 2 → fib n ≤ 144 := sorry
|
d2394de6c9b5a2eb22c6553d50e48b2bb9323c55 | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /tactic/norm_num.lean | 1431f5aecc7154734094077ae4914feffc52e730 | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 12,172 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Mario Carneiro
Evaluating arithmetic expressions including *, +, -, ^, ≤
-/
import algebra.group_power data.rat tactic.interactive
universes u v w
open tactic
namespace expr
protected meta def to_pos_rat : expr → option ℚ
| `(%%e₁ / %%e₂) := do m ← e₁.to_nat, n ← e₂.to_nat, some (rat.mk m n)
| e := do n ← e.to_nat, return (rat.of_int n)
protected meta def to_rat : expr → option ℚ
| `(has_neg.neg %%e) := do q ← e.to_pos_rat, some (-q)
| e := e.to_pos_rat
protected meta def of_rat (α : expr) : ℚ → tactic expr
| ⟨(n:ℕ), d, h, c⟩ := do
e₁ ← expr.of_nat α n,
if d = 1 then return e₁ else
do e₂ ← expr.of_nat α d,
tactic.mk_app ``has_div.div [e₁, e₂]
| ⟨-[1+n], d, h, c⟩ := do
e₁ ← expr.of_nat α (n+1),
e ← (if d = 1 then return e₁ else do
e₂ ← expr.of_nat α d,
tactic.mk_app ``has_div.div [e₁, e₂]),
tactic.mk_app ``has_neg.neg [e]
end expr
namespace norm_num
variable {α : Type u}
theorem bit0_zero [add_group α] : bit0 (0 : α) = 0 := add_zero _
theorem bit1_zero [add_group α] [has_one α] : bit1 (0 : α) = 1 :=
by rw [bit1, bit0_zero, zero_add]
lemma pow_bit0_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) :
a ^ bit0 b = t * t :=
by simp [pow_bit0, h]
lemma pow_bit1_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) :
a ^ bit1 b = t * t * a :=
by simp [pow_bit1, h]
lemma lt_add_of_pos_helper [ordered_cancel_comm_monoid α]
(a b c : α) (h : a + b = c) (h₂ : 0 < b) : a < c :=
h ▸ (lt_add_iff_pos_right _).2 h₂
lemma nat_div_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a / b = q :=
by rw [← h, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂),
nat.div_eq_of_lt h₂, zero_add]
lemma int_div_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q :=
by rw [← h, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)),
int.div_eq_zero_of_lt h₁ h₂, zero_add]
lemma nat_mod_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a % b = r :=
by rw [← h, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂]
lemma int_mod_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r :=
by rw [← h, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂]
meta def eval_pow (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr)
| `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) :=
match m with
| `(nat.has_pow) :=
mk_app ``nat.pow [e₁, e₂] >>= eval_pow
| `(@monoid.has_pow %%α %%m) :=
mk_app ``monoid.pow [e₁, e₂] >>= eval_pow
| _ := failed
end
| `(monoid.pow %%e₁ 0) := do
p ← mk_app ``pow_zero [e₁],
a ← infer_type e₁,
o ← mk_app ``has_one.one [a],
return (o, p)
| `(monoid.pow %%e₁ 1) := do
p ← mk_app ``pow_one [e₁],
return (e₁, p)
| `(monoid.pow %%e₁ (bit0 %%e₂)) := do
e ← mk_app ``monoid.pow [e₁, e₂],
(e', p) ← simp e,
p' ← mk_app ``norm_num.pow_bit0_helper [e₁, e', e₂, p],
e'' ← to_expr ``(%%e' * %%e'),
return (e'', p')
| `(monoid.pow %%e₁ (bit1 %%e₂)) := do
e ← mk_app ``monoid.pow [e₁, e₂],
(e', p) ← simp e,
p' ← mk_app ``norm_num.pow_bit1_helper [e₁, e', e₂, p],
e'' ← to_expr ``(%%e' * %%e' * %%e₁),
return (e'', p')
| `(nat.pow %%e₁ %%e₂) := do
p₁ ← mk_app ``nat.pow_eq_pow [e₁, e₂],
e ← mk_app ``monoid.pow [e₁, e₂],
(e', p₂) ← simp e,
p ← mk_eq_trans p₁ p₂,
return (e', p)
| _ := failed
meta def prove_pos : instance_cache → expr → tactic (instance_cache × expr)
| c `(has_one.one _) := do (c, p) ← c.mk_app ``zero_lt_one [], return (c, p)
| c `(bit0 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit0_pos [e, p], return (c, p)
| c `(bit1 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit1_pos' [e, p], return (c, p)
| c `(%%e₁ / %%e₂) := do
(c, p₁) ← prove_pos c e₁, (c, p₂) ← prove_pos c e₂,
(c, p) ← c.mk_app ``div_pos_of_pos_of_pos [e₁, e₂, p₁, p₂],
return (c, p)
| c e := failed
meta def prove_lt (simp : expr → tactic (expr × expr)) : instance_cache → expr → expr → tactic (instance_cache × expr)
| c `(- %%e₁) `(- %%e₂) := do
(c, p) ← prove_lt c e₁ e₂,
(c, p) ← c.mk_app ``neg_lt_neg [e₁, e₂, p],
return (c, p)
| c `(- %%e₁) `(has_zero.zero _) := do
(c, p) ← prove_pos c e₁,
(c, p) ← c.mk_app ``neg_neg_of_pos [e₁, p],
return (c, p)
| c `(- %%e₁) e₂ := do
(c, p₁) ← prove_pos c e₁,
(c, me₁) ← c.mk_app ``has_neg.neg [e₁],
(c, p₁) ← c.mk_app ``neg_neg_of_pos [e₁, p₁],
(c, p₂) ← prove_pos c e₂,
(c, z) ← c.mk_app ``has_zero.zero [],
(c, p) ← c.mk_app ``lt_trans [me₁, z, e₂, p₁, p₂],
return (c, p)
| c `(has_zero.zero _) e₂ := prove_pos c e₂
| c e₁ e₂ := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
d ← expr.of_rat c.α (n₂ - n₁),
(c, e₃) ← c.mk_app ``has_add.add [e₁, d],
(e₂', p) ← norm_num e₃,
guard (e₂' =ₐ e₂),
(c, p') ← prove_pos c d,
(c, p) ← c.mk_app ``norm_num.lt_add_of_pos_helper [e₁, d, e₂, p, p'],
return (c, p)
private meta def true_intro (p : expr) : tactic (expr × expr) :=
prod.mk <$> mk_const `true <*> mk_app ``eq_true_intro [p]
private meta def false_intro (p : expr) : tactic (expr × expr) :=
prod.mk <$> mk_const `false <*> mk_app ``eq_false_intro [p]
meta def eval_ineq (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr)
| `(%%e₁ < %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ < n₂ then
do (_, p) ← prove_lt simp c e₁ e₂, true_intro p
else do
(c, p) ← if n₁ = n₂ then c.mk_app ``lt_irrefl [e₁] else
(do (c, p') ← prove_lt simp c e₂ e₁,
c.mk_app ``not_lt_of_gt [e₁, e₂, p']),
false_intro p
| `(%%e₁ ≤ %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ ≤ n₂ then do
(c, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else
(do (c, p') ← prove_lt simp c e₁ e₂,
c.mk_app ``le_of_lt [e₁, e₂, p']),
true_intro p
else do
(c, p) ← prove_lt simp c e₂ e₁,
(c, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p],
false_intro p
| `(%%e₁ = %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ < n₂ then do
(c, p) ← prove_lt simp c e₁ e₂,
(c, p) ← c.mk_app ``ne_of_lt [e₁, e₂, p],
false_intro p
else if n₂ < n₁ then do
(c, p) ← prove_lt simp c e₂ e₁,
(c, p) ← c.mk_app ``ne_of_gt [e₁, e₂, p],
false_intro p
else mk_eq_refl e₁ >>= true_intro
| `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= simp
| `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= simp
| `(%%e₁ ≠ %%e₂) := do e ← mk_app ``eq [e₁, e₂], mk_app ``not [e] >>= simp
| _ := failed
meta def eval_div_ext (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr)
| `(has_inv.inv %%e) := do
c ← infer_type e >>= mk_instance_cache,
(c, p₁) ← c.mk_app ``inv_eq_one_div [e],
(c, o) ← c.mk_app ``has_one.one [],
(c, e') ← c.mk_app ``has_div.div [o, e],
(do (e'', p₂) ← simp e',
p ← mk_eq_trans p₁ p₂,
return (e'', p)) <|> return (e', p₁)
| `(%%e₁ / %%e₂) := do
α ← infer_type e₁,
c ← mk_instance_cache α,
match α with
| `(nat) := do
n₁ ← e₁.to_nat, n₂ ← e₂.to_nat,
q ← expr.of_nat α (n₁ / n₂),
r ← expr.of_nat α (n₁ % n₂),
(c, e₃) ← c.mk_app ``has_mul.mul [q, e₂],
(c, e₃) ← c.mk_app ``has_add.add [r, e₃],
(e₁', p) ← norm_num e₃,
guard (e₁' =ₐ e₁),
(c, p') ← prove_lt simp c r e₂,
p ← mk_app ``norm_num.nat_div_helper [e₁, e₂, q, r, p, p'],
return (q, p)
| `(int) := match e₂ with
| `(- %%e₂') := do
(c, p₁) ← c.mk_app ``int.div_neg [e₁, e₂'],
(c, e) ← c.mk_app ``has_div.div [e₁, e₂'],
(c, e) ← c.mk_app ``has_neg.neg [e],
(e', p₂) ← simp e,
p ← mk_eq_trans p₁ p₂,
return (e', p)
| _ := do
n₁ ← e₁.to_int,
n₂ ← e₂.to_int,
q ← expr.of_rat α $ rat.of_int (n₁ / n₂),
r ← expr.of_rat α $ rat.of_int (n₁ % n₂),
(c, e₃) ← c.mk_app ``has_mul.mul [q, e₂],
(c, e₃) ← c.mk_app ``has_add.add [r, e₃],
(e₁', p) ← norm_num e₃,
guard (e₁' =ₐ e₁),
(c, r0) ← c.mk_app ``has_zero.zero [],
(c, r0) ← c.mk_app ``has_le.le [r0, r],
(_, p₁) ← simp r0,
p₁ ← mk_app ``of_eq_true [p₁],
(c, p₂) ← prove_lt simp c r e₂,
p ← mk_app ``norm_num.int_div_helper [e₁, e₂, q, r, p, p₁, p₂],
return (q, p)
end
| _ := failed
end
| `(%%e₁ % %%e₂) := do
α ← infer_type e₁,
c ← mk_instance_cache α,
match α with
| `(nat) := do
n₁ ← e₁.to_nat, n₂ ← e₂.to_nat,
q ← expr.of_nat α (n₁ / n₂),
r ← expr.of_nat α (n₁ % n₂),
(c, e₃) ← c.mk_app ``has_mul.mul [q, e₂],
(c, e₃) ← c.mk_app ``has_add.add [r, e₃],
(e₁', p) ← norm_num e₃,
guard (e₁' =ₐ e₁),
(c, p') ← prove_lt simp c r e₂,
p ← mk_app ``norm_num.nat_mod_helper [e₁, e₂, q, r, p, p'],
return (r, p)
| `(int) := match e₂ with
| `(- %%e₂') := do
(c, p₁) ← c.mk_app ``int.mod_neg [e₁, e₂'],
(c, e) ← c.mk_app ``has_mod.mod [e₁, e₂'],
(e', p₂) ← simp e,
p ← mk_eq_trans p₁ p₂,
return (e', p)
| _ := do
n₁ ← e₁.to_int,
n₂ ← e₂.to_int,
q ← expr.of_rat α $ rat.of_int (n₁ / n₂),
r ← expr.of_rat α $ rat.of_int (n₁ % n₂),
(c, e₃) ← c.mk_app ``has_mul.mul [q, e₂],
(c, e₃) ← c.mk_app ``has_add.add [r, e₃],
(e₁', p) ← norm_num e₃,
guard (e₁' =ₐ e₁),
(c, r0) ← c.mk_app ``has_zero.zero [],
(c, r0) ← c.mk_app ``has_le.le [r0, r],
(_, p₁) ← simp r0,
p₁ ← mk_app ``of_eq_true [p₁],
(c, p₂) ← prove_lt simp c r e₂,
p ← mk_app ``norm_num.int_mod_helper [e₁, e₂, q, r, p, p₁, p₂],
return (r, p)
end
| _ := failed
end
| _ := failed
meta def derive1 (simp : expr → tactic (expr × expr)) (e : expr) :
tactic (expr × expr) :=
norm_num e <|> eval_div_ext simp e <|> eval_pow simp e <|> eval_ineq simp e
meta def derive : expr → tactic (expr × expr) | e :=
do (_, e', pr) ←
ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed)
(λ _ _ _ _ e,
do (new_e, pr) ← derive1 derive e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, tt))
`eq e,
return (e', pr)
end norm_num
namespace tactic.interactive
open norm_num interactive interactive.types
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 (loc : parse location) : tactic unit :=
do ns ← loc.get_locals,
tt ← tactic.replace_at derive ns loc.include_goal
| fail "norm_num failed to simplify",
when loc.include_goal $ try tactic.triv,
when (¬ ns.empty) $ try tactic.contradiction
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` `<` `≤` over ordered fields (or other
appropriate classes), as well as `-` `/` `%` over `ℤ` and `ℕ`. -/
meta def norm_num (loc : parse location) : tactic unit :=
let t := orelse' (norm_num1 loc) $ simp_core {} failed ff [] [] loc in
t >> repeat t
meta def apply_normed (x : parse texpr) : tactic unit :=
do x₁ ← to_expr x,
(x₂,_) ← derive x₁,
tactic.exact x₂
end tactic.interactive
|
b55ff247937cf00b3f88448d97524686b0844527 | aa2345b30d710f7e75f13157a35845ee6d48c017 | /category_theory/examples/topological_spaces.lean | 2ef1e130d1123d1b4260403526014b390e7039a7 | [
"Apache-2.0"
] | permissive | CohenCyril/mathlib | 5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe | a12d5a192f5923016752f638d19fc1a51610f163 | refs/heads/master | 1,586,031,957,957 | 1,541,432,824,000 | 1,541,432,824,000 | 156,246,337 | 0 | 0 | Apache-2.0 | 1,541,434,514,000 | 1,541,434,513,000 | null | UTF-8 | Lean | false | false | 2,111 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Patrick Massot, Scott Morrison, Mario Carneiro
import category_theory.full_subcategory
import category_theory.functor_category
import category_theory.natural_isomorphism
import analysis.topology.topological_space
import analysis.topology.continuity
import order.galois_connection
open category_theory
open category_theory.nat_iso
open topological_space
universe u
namespace category_theory.examples
/-- The category of topological spaces and continuous maps. -/
@[reducible] def Top : Type (u+1) := bundled topological_space
instance (x : Top) : topological_space x := x.str
namespace Top
instance : concrete_category @continuous := ⟨@continuous_id, @continuous.comp⟩
-- local attribute [class] continuous
-- instance {R S : Top} (f : R ⟶ S) : continuous (f : R → S) := f.2
end Top
variables {X : Top.{u}}
instance : small_category (opens X) := by apply_instance
def nbhd (x : X.α) := { U : opens X // x ∈ U }
def nbhds (x : X.α) : small_category (nbhd x) := begin unfold nbhd, apply_instance end
/-- `opens.map f` gives the functor from open sets in Y to open set in X,
given by taking preimages under f. -/
def map
{X Y : Top.{u}} (f : X ⟶ Y) : opens Y ⥤ opens X :=
{ obj := λ U, ⟨ f.val ⁻¹' U, f.property _ U.property ⟩,
map' := λ U V i, ⟨ ⟨ λ a b, i.down.down b ⟩ ⟩ }.
@[simp] lemma map_id_obj (X : Top.{u}) (U : opens X) : map (𝟙 X) U = U := by tidy
@[simp] def map_id (X : Top.{u}) : map (𝟙 X) ≅ functor.id (opens X) :=
{ hom := { app := λ U, 𝟙 U },
inv := { app := λ U, 𝟙 U } }
-- We could make f g implicit here, but it's nice to be able to see when they are the identity (often!)
def map_iso {X Y : Top.{u}} (f g : X ⟶ Y) (h : f = g) : map f ≅ map g :=
nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg _ (congr_arg _ h)) _) ) (by obviously)
@[simp] def map_iso_id {X : Top.{u}} (h) : map_iso (𝟙 X) (𝟙 X) h = iso.refl (map _) := rfl
end category_theory.examples
|
e1f32506dd56991093085c49620d3dc192e5035b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/homology/homology_auto.lean | 78920898e18a15cfefa7f904526286e1489edd77 | [] | 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 | 15,139 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.homology.chain_complex
import Mathlib.algebra.homology.image_to_kernel_map
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# (Co)homology groups for complexes
We setup that part of the theory of homology groups which works in
any category with kernels and images.
We define the homology groups themselves, and show that they induce maps on kernels.
Under the additional assumption that our category has equalizers and functorial images, we construct
induced morphisms on images and functorial induced morphisms in homology.
## Chains and cochains
Throughout we work with complexes graded by an arbitrary `[add_comm_group β]`,
with a differential with grading `b : β`.
Thus we're simultaneously doing homology and cohomology groups
(and in future, e.g., enabling computing homologies for successive pages of spectral sequences).
At the end of the file we set up abbreviations `cohomology` and `graded_cohomology`,
so that when you're working with a `C : cochain_complex V`, you can write `C.cohomology i`
rather than the confusing `C.homology i`.
-/
namespace homological_complex
/-- The map induced by a chain map between the kernels of the differentials. -/
def kernel_map {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_kernels V] {C : homological_complex V b}
{C' : homological_complex V b} (f : C ⟶ C') (i : β) :
category_theory.limits.kernel (category_theory.differential_object.d C i) ⟶
category_theory.limits.kernel (category_theory.differential_object.d C' i) :=
category_theory.limits.kernel.lift (category_theory.differential_object.d C' i)
(category_theory.limits.kernel.ι (category_theory.differential_object.d C i) ≫
category_theory.differential_object.hom.f f i)
sorry
@[simp] theorem kernel_map_condition {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_kernels V] {C : homological_complex V b}
{C' : homological_complex V b} (f : C ⟶ C') (i : β) :
kernel_map f i ≫ category_theory.limits.kernel.ι (category_theory.differential_object.d C' i) =
category_theory.limits.kernel.ι (category_theory.differential_object.d C i) ≫
category_theory.differential_object.hom.f f i :=
sorry
@[simp] theorem kernel_map_id {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_kernels V] (C : homological_complex V b) (i : β) :
kernel_map 𝟙 i = 𝟙 :=
sorry
@[simp] theorem kernel_map_comp {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_kernels V] {C : homological_complex V b}
{C' : homological_complex V b} {C'' : homological_complex V b} (f : C ⟶ C') (g : C' ⟶ C'')
(i : β) : kernel_map (f ≫ g) i = kernel_map f i ≫ kernel_map g i :=
sorry
/-- The kernels of the differentials of a complex form a `β`-graded object. -/
def kernel_functor {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_kernels V] :
homological_complex V b ⥤ category_theory.graded_object β V :=
category_theory.functor.mk
(fun (C : homological_complex V b) (i : β) =>
category_theory.limits.kernel (category_theory.differential_object.d C i))
fun (X Y : homological_complex V b) (f : X ⟶ Y) (i : β) => kernel_map f i
/-- A morphism of complexes induces a morphism on the images of the differentials in every
degree. -/
def image_map {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_image_maps V]
{C : homological_complex V b} {C' : homological_complex V b} (f : C ⟶ C') (i : β) :
category_theory.limits.image (category_theory.differential_object.d C i) ⟶
category_theory.limits.image (category_theory.differential_object.d C' i) :=
category_theory.limits.image.map (category_theory.arrow.hom_mk' sorry)
@[simp] theorem image_map_ι {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_image_maps V]
{C : homological_complex V b} {C' : homological_complex V b} (f : C ⟶ C') (i : β) :
image_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 C C' f i ≫
category_theory.limits.image.ι (category_theory.differential_object.d C' i) =
category_theory.limits.image.ι (category_theory.differential_object.d C i) ≫
category_theory.differential_object.hom.f f (i + b) :=
category_theory.limits.image.map_hom_mk'_ι
(Eq.symm (comm_at V _inst_1 _inst_2 β _inst_3 b C C' f i))
/--
The connecting morphism from the image of `d i` to the kernel of `d (i ± 1)`.
-/
def image_to_kernel_map {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
(C : homological_complex V b) (i : β) :
category_theory.limits.image (category_theory.differential_object.d C i) ⟶
category_theory.limits.kernel (category_theory.differential_object.d C (i + b)) :=
category_theory.image_to_kernel_map (category_theory.differential_object.d C i)
(category_theory.differential_object.d C (i + b)) sorry
@[simp] theorem image_to_kernel_map_condition {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
(C : homological_complex V b) (i : β) :
image_to_kernel_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 C i ≫
category_theory.limits.kernel.ι (category_theory.differential_object.d C (i + b)) =
category_theory.limits.image.ι (category_theory.differential_object.d C i) :=
sorry
theorem image_to_kernel_map_comp_kernel_map {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
[category_theory.limits.has_image_maps V] {C : homological_complex V b}
{C' : homological_complex V b} (f : C ⟶ C') (i : β) :
image_to_kernel_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 C i ≫ kernel_map f (i + b) =
image_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_6 C C' f i ≫
image_to_kernel_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 C' i :=
sorry
/-- The `i`-th homology group of the complex `C`. -/
def homology_group {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
[category_theory.limits.has_cokernels V] (i : β) (C : homological_complex V b) : V :=
category_theory.limits.cokernel
(image_to_kernel_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 C (i - b))
/-- A chain map induces a morphism in homology at every degree. -/
def homology_map {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
[category_theory.limits.has_cokernels V] [category_theory.limits.has_image_maps V]
{C : homological_complex V b} {C' : homological_complex V b} (f : C ⟶ C') (i : β) :
homology_group V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 i C ⟶
homology_group V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 i C' :=
category_theory.limits.cokernel.desc
(image_to_kernel_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 C (i - b))
(kernel_map f (i - b + b) ≫
category_theory.limits.cokernel.π
(image_to_kernel_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 C' (i - b)))
sorry
@[simp] theorem homology_map_condition {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
[category_theory.limits.has_cokernels V] [category_theory.limits.has_image_maps V]
{C : homological_complex V b} {C' : homological_complex V b} (f : C ⟶ C') (i : β) :
category_theory.limits.cokernel.π
(image_to_kernel_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 C (i - b)) ≫
homology_map ((fun (_x : β) => V) (i - b)) _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5
_inst_6 _inst_7 C C' f i =
kernel_map f (i - b + b) ≫
category_theory.limits.cokernel.π
(image_to_kernel_map ((fun (_x : β) => V) (i - b)) _inst_1 _inst_2 β _inst_3 b _inst_4
_inst_5 C' (i - b)) :=
sorry
@[simp] theorem homology_map_id {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
[category_theory.limits.has_cokernels V] [category_theory.limits.has_image_maps V]
(C : homological_complex V b) (i : β) :
homology_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 _inst_7 C C 𝟙 i = 𝟙 :=
sorry
@[simp] theorem homology_map_comp {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
[category_theory.limits.has_cokernels V] [category_theory.limits.has_image_maps V]
{C : homological_complex V b} {C' : homological_complex V b} {C'' : homological_complex V b}
(f : C ⟶ C') (g : C' ⟶ C'') (i : β) :
homology_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 _inst_7 C C'' (f ≫ g) i =
homology_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 _inst_7 C C' f i ≫
homology_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 _inst_7 C' C'' g i :=
sorry
/-- The `i`-th homology functor from `β` graded complexes to `V`. -/
def homology (V : Type u) [category_theory.category V] [category_theory.limits.has_zero_morphisms V]
{β : Type} [add_comm_group β] {b : β} [category_theory.limits.has_images V]
[category_theory.limits.has_equalizers V] [category_theory.limits.has_cokernels V]
[category_theory.limits.has_image_maps V] (i : β) : homological_complex V b ⥤ V :=
category_theory.functor.mk
(fun (C : homological_complex V b) =>
homology_group V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 i C)
fun (C C' : homological_complex V b) (f : C ⟶ C') =>
homology_map V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 _inst_7 C C' f i
/-- The homology functor from `β` graded complexes to `β` graded objects in `V`. -/
def graded_homology (V : Type u) [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] {β : Type} [add_comm_group β] {b : β}
[category_theory.limits.has_images V] [category_theory.limits.has_equalizers V]
[category_theory.limits.has_cokernels V] [category_theory.limits.has_image_maps V] :
homological_complex V b ⥤ category_theory.graded_object β V :=
category_theory.functor.mk
(fun (C : homological_complex V b) (i : β) =>
homology_group V _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6 i C)
fun (C C' : homological_complex V b) (f : C ⟶ C') (i : β) =>
homology_map ((fun (_x : β) => V) i) _inst_1 _inst_2 β _inst_3 b _inst_4 _inst_5 _inst_6
_inst_7 C C' f i
end homological_complex
/-!
We now set up abbreviations so that you can write `C.cohomology i` or `(graded_cohomology V).map f`,
etc., when `C` is a cochain complex.
-/
namespace cochain_complex
/-- The `i`-th cohomology group of the cochain complex `C`. -/
def cohomology_group {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] [category_theory.limits.has_images V]
[category_theory.limits.has_equalizers V] [category_theory.limits.has_cokernels V]
(C : cochain_complex V) (i : ℤ) : V :=
homological_complex.homology_group V _inst_1 _inst_2 ℤ
(linear_ordered_add_comm_group.to_add_comm_group ℤ) 1 _inst_4 _inst_5 _inst_6 i C
/-- A chain map induces a morphism in cohomology at every degree. -/
def cohomology_map {V : Type u} [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] [category_theory.limits.has_images V]
[category_theory.limits.has_equalizers V] [category_theory.limits.has_cokernels V]
[category_theory.limits.has_image_maps V] {C : cochain_complex V} {C' : cochain_complex V}
(f : C ⟶ C') (i : ℤ) :
cohomology_group V _inst_1 _inst_2 _inst_4 _inst_5 _inst_6 C i ⟶
cohomology_group V _inst_1 _inst_2 _inst_4 _inst_5 _inst_6 C' i :=
homological_complex.homology_map V _inst_1 _inst_2 ℤ
(linear_ordered_add_comm_group.to_add_comm_group ℤ) 1 _inst_4 _inst_5 _inst_6 _inst_7 C C' f i
/-- The `i`-th homology functor from cohain complexes to `V`. -/
def cohomology (V : Type u) [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] [category_theory.limits.has_images V]
[category_theory.limits.has_equalizers V] [category_theory.limits.has_cokernels V]
[category_theory.limits.has_image_maps V] (i : ℤ) : cochain_complex V ⥤ V :=
homological_complex.homology V _inst_1 _inst_2 ℤ
(linear_ordered_add_comm_group.to_add_comm_group ℤ) 1 _inst_4 _inst_5 _inst_6 _inst_7 i
/-- The cohomology functor from cochain complexes to `ℤ`-graded objects in `V`. -/
def graded_cohomology (V : Type u) [category_theory.category V]
[category_theory.limits.has_zero_morphisms V] [category_theory.limits.has_images V]
[category_theory.limits.has_equalizers V] [category_theory.limits.has_cokernels V]
[category_theory.limits.has_image_maps V] :
cochain_complex V ⥤ category_theory.graded_object ℤ V :=
homological_complex.graded_homology V _inst_1 _inst_2 ℤ
(linear_ordered_add_comm_group.to_add_comm_group ℤ) 1 _inst_4 _inst_5 _inst_6 _inst_7
end Mathlib |
b682a976ad93a7e7b6a896bd6865075a0390eae7 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/dedekind_domain/adic_valuation.lean | a5d737de916734ae540dc4d7ab812657dd5cf605 | [
"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 | 19,319 | lean | /-
Copyright (c) 2022 María Inés de Frutos-Fernández. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: María Inés de Frutos-Fernández
-/
import ring_theory.dedekind_domain.ideal
import ring_theory.valuation.extend_to_localization
import ring_theory.valuation.valuation_subring
import topology.algebra.valued_field
import algebra.order.group.type_tags
/-!
# Adic valuations on Dedekind domains
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Given a Dedekind domain `R` of Krull dimension 1 and a maximal ideal `v` of `R`, we define the
`v`-adic valuation on `R` and its extension to the field of fractions `K` of `R`.
We prove several properties of this valuation, including the existence of uniformizers.
We define the completion of `K` with respect to the `v`-adic valuation, denoted
`v.adic_completion`,and its ring of integers, denoted `v.adic_completion_integers`.
## Main definitions
- `is_dedekind_domain.height_one_spectrum.int_valuation v` is the `v`-adic valuation on `R`.
- `is_dedekind_domain.height_one_spectrum.valuation v` is the `v`-adic valuation on `K`.
- `is_dedekind_domain.height_one_spectrum.adic_completion v` is the completion of `K` with respect
to its `v`-adic valuation.
- `is_dedekind_domain.height_one_spectrum.adic_completion_integers v` is the ring of integers of
`v.adic_completion`.
## Main results
- `is_dedekind_domain.height_one_spectrum.int_valuation_le_one` : The `v`-adic valuation on `R` is
bounded above by 1.
- `is_dedekind_domain.height_one_spectrum.int_valuation_lt_one_iff_dvd` : The `v`-adic valuation of
`r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`.
- `is_dedekind_domain.height_one_spectrum.int_valuation_le_pow_iff_dvd` : The `v`-adic valuation of
`r ∈ R` is less than or equal to `multiplicative.of_add (-n)` if and only if `vⁿ` divides the
ideal `(r)`.
- `is_dedekind_domain.height_one_spectrum.int_valuation_exists_uniformizer` : There exists `π ∈ R`
with `v`-adic valuation `multiplicative.of_add (-1)`.
- `is_dedekind_domain.height_one_spectrum.valuation_of_mk'` : The `v`-adic valuation of `r/s ∈ K`
is the valuation of `r` divided by the valuation of `s`.
- `is_dedekind_domain.height_one_spectrum.valuation_of_algebra_map` : The `v`-adic valuation on `K`
extends the `v`-adic valuation on `R`.
- `is_dedekind_domain.height_one_spectrum.valuation_exists_uniformizer` : There exists `π ∈ K` with
`v`-adic valuation `multiplicative.of_add (-1)`.
## Implementation notes
We are only interested in Dedekind domains with Krull dimension 1.
## References
* [G. J. Janusz, *Algebraic Number Fields*][janusz1996]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J. Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
dedekind domain, dedekind ring, adic valuation
-/
noncomputable theory
open_locale classical discrete_valuation
open multiplicative is_dedekind_domain
variables {R : Type*} [comm_ring R] [is_domain R] [is_dedekind_domain R] {K : Type*} [field K]
[algebra R K] [is_fraction_ring R K] (v : height_one_spectrum R)
namespace is_dedekind_domain.height_one_spectrum
/-! ### Adic valuations on the Dedekind domain R -/
/-- The additive `v`-adic valuation of `r ∈ R` is the exponent of `v` in the factorization of the
ideal `(r)`, if `r` is nonzero, or infinity, if `r = 0`. `int_valuation_def` is the corresponding
multiplicative valuation. -/
def int_valuation_def (r : R) : ℤₘ₀ :=
if r = 0 then 0 else multiplicative.of_add
(-(associates.mk v.as_ideal).count (associates.mk (ideal.span {r} : ideal R)).factors : ℤ)
lemma int_valuation_def_if_pos {r : R} (hr : r = 0) : v.int_valuation_def r = 0 := if_pos hr
lemma int_valuation_def_if_neg {r : R} (hr : r ≠ 0) : v.int_valuation_def r = (multiplicative.of_add
(-(associates.mk v.as_ideal).count (associates.mk (ideal.span {r} : ideal R)).factors : ℤ)) :=
if_neg hr
/-- Nonzero elements have nonzero adic valuation. -/
lemma int_valuation_ne_zero (x : R) (hx : x ≠ 0) : v.int_valuation_def x ≠ 0 :=
begin
rw [int_valuation_def, if_neg hx],
exact with_zero.coe_ne_zero,
end
/-- Nonzero divisors have nonzero valuation. -/
lemma int_valuation_ne_zero' (x : non_zero_divisors R) : v.int_valuation_def x ≠ 0 :=
v.int_valuation_ne_zero x (non_zero_divisors.coe_ne_zero x)
/-- Nonzero divisors have valuation greater than zero. -/
lemma int_valuation_zero_le (x : non_zero_divisors R) : 0 < v.int_valuation_def x :=
begin
rw [v.int_valuation_def_if_neg (non_zero_divisors.coe_ne_zero x)],
exact with_zero.zero_lt_coe _,
end
/-- The `v`-adic valuation on `R` is bounded above by 1. -/
lemma int_valuation_le_one (x : R) : v.int_valuation_def x ≤ 1 :=
begin
rw int_valuation_def,
by_cases hx : x = 0,
{ rw if_pos hx, exact with_zero.zero_le 1 },
{ rw [if_neg hx, ← with_zero.coe_one, ← of_add_zero, with_zero.coe_le_coe, of_add_le,
right.neg_nonpos_iff],
exact int.coe_nat_nonneg _ }
end
/-- The `v`-adic valuation of `r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`. -/
lemma int_valuation_lt_one_iff_dvd (r : R) :
v.int_valuation_def r < 1 ↔ v.as_ideal ∣ ideal.span {r} :=
begin
rw int_valuation_def,
split_ifs with hr,
{ simpa [hr] using (with_zero.zero_lt_coe _) },
{ rw [← with_zero.coe_one, ← of_add_zero, with_zero.coe_lt_coe, of_add_lt, neg_lt_zero,
← int.coe_nat_zero, int.coe_nat_lt, zero_lt_iff],
have h : (ideal.span {r} : ideal R) ≠ 0,
{ rw [ne.def, ideal.zero_eq_bot, ideal.span_singleton_eq_bot],
exact hr },
apply associates.count_ne_zero_iff_dvd h (by apply v.irreducible) }
end
/-- The `v`-adic valuation of `r ∈ R` is less than `multiplicative.of_add (-n)` if and only if
`vⁿ` divides the ideal `(r)`. -/
lemma int_valuation_le_pow_iff_dvd (r : R) (n : ℕ) :
v.int_valuation_def r ≤ multiplicative.of_add (-(n : ℤ)) ↔ v.as_ideal^n ∣ ideal.span {r} :=
begin
rw int_valuation_def,
split_ifs with hr,
{ simp_rw [hr, ideal.dvd_span_singleton, zero_le', submodule.zero_mem], },
{ rw [with_zero.coe_le_coe, of_add_le, neg_le_neg_iff, int.coe_nat_le, ideal.dvd_span_singleton,
← associates.le_singleton_iff, associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hr)
(by apply v.associates_irreducible)] }
end
/-- The `v`-adic valuation of `0 : R` equals 0. -/
lemma int_valuation.map_zero' : v.int_valuation_def 0 = 0 := v.int_valuation_def_if_pos (eq.refl 0)
/-- The `v`-adic valuation of `1 : R` equals 1. -/
lemma int_valuation.map_one' : v.int_valuation_def 1 = 1 :=
by rw [v.int_valuation_def_if_neg (zero_ne_one.symm : (1 : R) ≠ 0), ideal.span_singleton_one,
← ideal.one_eq_top, associates.mk_one, associates.factors_one, associates.count_zero
(by apply v.associates_irreducible), int.coe_nat_zero, neg_zero, of_add_zero, with_zero.coe_one]
/-- The `v`-adic valuation of a product equals the product of the valuations. -/
lemma int_valuation.map_mul' (x y : R) :
v.int_valuation_def (x * y) = v.int_valuation_def x * v.int_valuation_def y :=
begin
simp only [int_valuation_def],
by_cases hx : x = 0,
{ rw [hx, zero_mul, if_pos (eq.refl _), zero_mul] },
{ by_cases hy : y = 0,
{ rw [hy, mul_zero, if_pos (eq.refl _), mul_zero] },
{ rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_zero.coe_mul, with_zero.coe_inj,
← of_add_add, ← ideal.span_singleton_mul_span_singleton, ← associates.mk_mul_mk, ← neg_add,
associates.count_mul (by apply associates.mk_ne_zero'.mpr hx)
(by apply associates.mk_ne_zero'.mpr hy) (by apply v.associates_irreducible)],
refl }}
end
lemma int_valuation.le_max_iff_min_le {a b c : ℕ} : multiplicative.of_add(-c : ℤ) ≤
max (multiplicative.of_add(-a : ℤ)) (multiplicative.of_add(-b : ℤ)) ↔ min a b ≤ c :=
by rw [le_max_iff, of_add_le, of_add_le, neg_le_neg_iff, neg_le_neg_iff, int.coe_nat_le,
int.coe_nat_le, ← min_le_iff]
/-- The `v`-adic valuation of a sum is bounded above by the maximum of the valuations. -/
lemma int_valuation.map_add_le_max' (x y : R) : v.int_valuation_def (x + y) ≤
max (v.int_valuation_def x) (v.int_valuation_def y) :=
begin
by_cases hx : x = 0,
{ rw [hx, zero_add],
conv_rhs {rw [int_valuation_def, if_pos (eq.refl _)]},
rw max_eq_right (with_zero.zero_le (v.int_valuation_def y)),
exact le_refl _, },
{ by_cases hy : y = 0,
{ rw [hy, add_zero],
conv_rhs {rw [max_comm, int_valuation_def, if_pos (eq.refl _)]},
rw max_eq_right (with_zero.zero_le (v.int_valuation_def x)),
exact le_refl _ },
{ by_cases hxy : x + y = 0,
{ rw [int_valuation_def, if_pos hxy], exact zero_le',},
{ rw [v.int_valuation_def_if_neg hxy, v.int_valuation_def_if_neg hx,
v.int_valuation_def_if_neg hy, with_zero.le_max_iff, int_valuation.le_max_iff_min_le],
set nmin := min
((associates.mk v.as_ideal).count (associates.mk (ideal.span {x})).factors)
((associates.mk v.as_ideal).count (associates.mk (ideal.span {y})).factors),
have h_dvd_x : x ∈ v.as_ideal ^ (nmin),
{ rw [← associates.le_singleton_iff x nmin _,
associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hx) _],
exact min_le_left _ _,
apply v.associates_irreducible },
have h_dvd_y : y ∈ v.as_ideal ^ nmin,
{ rw [← associates.le_singleton_iff y nmin _,
associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hy) _],
exact min_le_right _ _,
apply v.associates_irreducible },
have h_dvd_xy : associates.mk v.as_ideal^nmin ≤ associates.mk (ideal.span {x + y}),
{ rw associates.le_singleton_iff,
exact ideal.add_mem (v.as_ideal^nmin) h_dvd_x h_dvd_y, },
rw (associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hxy) _) at h_dvd_xy,
exact h_dvd_xy,
apply v.associates_irreducible, }}}
end
/-- The `v`-adic valuation on `R`. -/
def int_valuation : valuation R ℤₘ₀ :=
{ to_fun := v.int_valuation_def,
map_zero' := int_valuation.map_zero' v,
map_one' := int_valuation.map_one' v,
map_mul' := int_valuation.map_mul' v,
map_add_le_max' := int_valuation.map_add_le_max' v }
/-- There exists `π ∈ R` with `v`-adic valuation `multiplicative.of_add (-1)`. -/
lemma int_valuation_exists_uniformizer :
∃ (π : R), v.int_valuation_def π = multiplicative.of_add (-1 : ℤ) :=
begin
have hv : _root_.irreducible (associates.mk v.as_ideal) := v.associates_irreducible,
have hlt : v.as_ideal^2 < v.as_ideal,
{ rw ← ideal.dvd_not_unit_iff_lt,
exact ⟨v.ne_bot, v.as_ideal,
(not_congr ideal.is_unit_iff).mpr (ideal.is_prime.ne_top v.is_prime), sq v.as_ideal⟩ } ,
obtain ⟨π, mem, nmem⟩ := set_like.exists_of_lt hlt,
have hπ : associates.mk (ideal.span {π}) ≠ 0,
{ rw associates.mk_ne_zero',
intro h,
rw h at nmem,
exact nmem (submodule.zero_mem (v.as_ideal^2)), },
use π,
rw [int_valuation_def, if_neg (associates.mk_ne_zero'.mp hπ), with_zero.coe_inj],
apply congr_arg,
rw [neg_inj, ← int.coe_nat_one, int.coe_nat_inj'],
rw [← ideal.dvd_span_singleton, ← associates.mk_le_mk_iff_dvd_iff] at mem nmem,
rw [← pow_one (associates.mk v.as_ideal), associates.prime_pow_dvd_iff_le hπ hv] at mem,
rw [associates.mk_pow, associates.prime_pow_dvd_iff_le hπ hv, not_le] at nmem,
exact nat.eq_of_le_of_lt_succ mem nmem,
end
/-! ### Adic valuations on the field of fractions `K` -/
/-- The `v`-adic valuation of `x ∈ K` is the valuation of `r` divided by the valuation of `s`,
where `r` and `s` are chosen so that `x = r/s`. -/
def valuation (v : height_one_spectrum R) : valuation K ℤₘ₀ :=
v.int_valuation.extend_to_localization (λ r hr, set.mem_compl $ v.int_valuation_ne_zero' ⟨r, hr⟩) K
lemma valuation_def (x : K) : v.valuation x = v.int_valuation.extend_to_localization
(λ r hr, set.mem_compl (v.int_valuation_ne_zero' ⟨r, hr⟩)) K x :=
rfl
/-- The `v`-adic valuation of `r/s ∈ K` is the valuation of `r` divided by the valuation of `s`. -/
lemma valuation_of_mk' {r : R} {s : non_zero_divisors R} :
v.valuation (is_localization.mk' K r s) = v.int_valuation r / v.int_valuation s :=
begin
erw [valuation_def, (is_localization.to_localization_map (non_zero_divisors R) K).lift_mk',
div_eq_mul_inv, mul_eq_mul_left_iff],
left,
rw [units.coe_inv, inv_inj],
refl,
end
/-- The `v`-adic valuation on `K` extends the `v`-adic valuation on `R`. -/
lemma valuation_of_algebra_map (r : R) :
v.valuation (algebra_map R K r) = v.int_valuation r :=
by rw [valuation_def, valuation.extend_to_localization_apply_map_apply]
/-- The `v`-adic valuation on `R` is bounded above by 1. -/
lemma valuation_le_one (r : R) : v.valuation (algebra_map R K r) ≤ 1 :=
by { rw valuation_of_algebra_map, exact v.int_valuation_le_one r }
/-- The `v`-adic valuation of `r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`. -/
lemma valuation_lt_one_iff_dvd (r : R) :
v.valuation (algebra_map R K r) < 1 ↔ v.as_ideal ∣ ideal.span {r} :=
by { rw valuation_of_algebra_map, exact v.int_valuation_lt_one_iff_dvd r }
variable (K)
/-- There exists `π ∈ K` with `v`-adic valuation `multiplicative.of_add (-1)`. -/
lemma valuation_exists_uniformizer :
∃ (π : K), v.valuation π = multiplicative.of_add (-1 : ℤ) :=
begin
obtain ⟨r, hr⟩ := v.int_valuation_exists_uniformizer,
use algebra_map R K r,
rw [valuation_def, valuation.extend_to_localization_apply_map_apply],
exact hr,
end
/-- Uniformizers are nonzero. -/
lemma valuation_uniformizer_ne_zero :
(classical.some (v.valuation_exists_uniformizer K)) ≠ 0 :=
begin
have hu := classical.some_spec (v.valuation_exists_uniformizer K),
exact (valuation.ne_zero_iff _).mp (ne_of_eq_of_ne hu with_zero.coe_ne_zero),
end
/-! ### Completions with respect to adic valuations
Given a Dedekind domain `R` with field of fractions `K` and a maximal ideal `v` of `R`, we define
the completion of `K` with respect to its `v`-adic valuation, denoted `v.adic_completion`, and its
ring of integers, denoted `v.adic_completion_integers`. -/
variable {K}
/-- `K` as a valued field with the `v`-adic valuation. -/
def adic_valued : valued K ℤₘ₀ := valued.mk' v.valuation
lemma adic_valued_apply {x : K} : (v.adic_valued.v : _) x = v.valuation x := rfl
variables (K)
/-- The completion of `K` with respect to its `v`-adic valuation. -/
def adic_completion := @uniform_space.completion K v.adic_valued.to_uniform_space
instance : field (v.adic_completion K) :=
@uniform_space.completion.field K _ v.adic_valued.to_uniform_space _ _
v.adic_valued.to_uniform_add_group
instance : inhabited (v.adic_completion K) := ⟨0⟩
instance valued_adic_completion : valued (v.adic_completion K) ℤₘ₀ :=
@valued.valued_completion _ _ _ _ v.adic_valued
lemma valued_adic_completion_def {x : v.adic_completion K} :
valued.v x = @valued.extension K _ _ _ (adic_valued v) x := rfl
instance adic_completion_complete_space : complete_space (v.adic_completion K) :=
@uniform_space.completion.complete_space K v.adic_valued.to_uniform_space
instance adic_completion.has_lift_t : has_lift_t K (v.adic_completion K) :=
(infer_instance : has_lift_t K (@uniform_space.completion K v.adic_valued.to_uniform_space))
/-- The ring of integers of `adic_completion`. -/
def adic_completion_integers : valuation_subring (v.adic_completion K) := valued.v.valuation_subring
instance : inhabited (adic_completion_integers K v) := ⟨0⟩
variables (R K)
lemma mem_adic_completion_integers {x : v.adic_completion K} :
x ∈ v.adic_completion_integers K ↔ (valued.v x : ℤₘ₀) ≤ 1 :=
iff.rfl
section algebra_instances
@[priority 100] instance adic_valued.has_uniform_continuous_const_smul' :
@has_uniform_continuous_const_smul R K v.adic_valued.to_uniform_space _ :=
@has_uniform_continuous_const_smul_of_continuous_const_smul R K _ _ _
v.adic_valued.to_uniform_space _ _
instance adic_valued.has_uniform_continuous_const_smul :
@has_uniform_continuous_const_smul K K v.adic_valued.to_uniform_space _ :=
@ring.has_uniform_continuous_const_smul K _ v.adic_valued.to_uniform_space _ _
instance adic_completion.algebra' : algebra R (v.adic_completion K) :=
@uniform_space.completion.algebra K _ v.adic_valued.to_uniform_space _ _ R _ _
(adic_valued.has_uniform_continuous_const_smul' R K v)
@[simp] lemma coe_smul_adic_completion (r : R) (x : K) :
(↑(r • x) : v.adic_completion K) = r • (↑x : v.adic_completion K) :=
@uniform_space.completion.coe_smul R K v.adic_valued.to_uniform_space _ _ r x
instance : algebra K (v.adic_completion K) :=
@uniform_space.completion.algebra' K _ v.adic_valued.to_uniform_space _ _
lemma algebra_map_adic_completion' :
⇑(algebra_map R $ v.adic_completion K) = coe ∘ algebra_map R K :=
rfl
lemma algebra_map_adic_completion :
⇑(algebra_map K $ v.adic_completion K) = coe :=
rfl
instance : is_scalar_tower R K (v.adic_completion K) :=
@uniform_space.completion.is_scalar_tower R K K v.adic_valued.to_uniform_space _ _ _
(adic_valued.has_uniform_continuous_const_smul' R K v) _ _
instance : algebra R (v.adic_completion_integers K) :=
{ smul := λ r x, ⟨r • (x : v.adic_completion K), begin
have h : ((algebra_map R (adic_completion K v)) r) = (coe $ algebra_map R K r) := rfl,
rw algebra.smul_def,
refine valuation_subring.mul_mem _ _ _ _ x.2,
rw [mem_adic_completion_integers, h, valued.valued_completion_apply],
exact v.valuation_le_one _,
end⟩,
to_fun := λ r, ⟨coe $ algebra_map R K r, by simpa only [mem_adic_completion_integers,
valued.valued_completion_apply] using v.valuation_le_one _⟩,
map_one' := by simp only [map_one]; refl,
map_mul' := λ x y,
begin
ext,
simp_rw [ring_hom.map_mul, subring.coe_mul, subtype.coe_mk, uniform_space.completion.coe_mul],
end,
map_zero' := by simp only [map_zero]; refl,
map_add' := λ x y,
begin
ext,
simp_rw [ring_hom.map_add, subring.coe_add, subtype.coe_mk, uniform_space.completion.coe_add],
end,
commutes' := λ r x, by rw mul_comm,
smul_def' := λ r x, begin
ext,
simp only [subring.coe_mul, set_like.coe_mk, algebra.smul_def],
refl,
end }
@[simp] lemma coe_smul_adic_completion_integers (r : R) (x : v.adic_completion_integers K) :
(↑(r • x) : v.adic_completion K) = r • (x : v.adic_completion K) :=
rfl
instance : no_zero_smul_divisors R (v.adic_completion_integers K) :=
{ eq_zero_or_eq_zero_of_smul_eq_zero := λ c x hcx,
begin
rw [algebra.smul_def, mul_eq_zero] at hcx,
refine hcx.imp_left (λ hc, _),
letI : uniform_space K := v.adic_valued.to_uniform_space,
rw ← map_zero (algebra_map R (v.adic_completion_integers K)) at hc,
exact (is_fraction_ring.injective R K
(uniform_space.completion.coe_injective K (subtype.ext_iff.mp hc)))
end }
instance adic_completion.is_scalar_tower' :
is_scalar_tower R (v.adic_completion_integers K) (v.adic_completion K) :=
{ smul_assoc := λ x y z, by {simp only [algebra.smul_def], apply mul_assoc, }}
end algebra_instances
end is_dedekind_domain.height_one_spectrum
|
9c3171cb089a7929ec287b2a61230d6581f38576 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/28.lean | c300f19b0c17704959bc74fad150ce83a12b8800 | [
"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,309 | lean |
structure bv (w : Nat) := (u:Unit)
inductive val : Type
| bv (w : Nat) : bv w → val
inductive memtype : Type
| ptr : Unit → memtype
inductive instr : Type
| load : memtype -> val -> instr
| store : Unit -> Unit -> Unit -> instr
structure sim (a:Type) :=
(runSim : {z:Type} → (IO.Error → z) /- error continuation -/ → (a → z) /- normal continuation -/ → z)
instance monad : Monad sim :=
{ bind := λ mx mf => sim.mk (λ kerr k =>
mx.runSim kerr (λx => (mf x).runSim kerr k)),
pure := fun a => sim.mk $ fun _ k => k a }
instance monadExcept : MonadExcept IO.Error sim :=
{ throw := λ err => sim.mk (λ kerr _k => kerr err),
tryCatch := λ m handle => sim.mk (λ kerr k =>
let kerr' := λerr => (handle err).runSim kerr k;
m.runSim kerr' k)
}
def f : sim val := throw (IO.userError "ASDF")
def g : sim Unit := throw (IO.userError "ASDF")
def evalInstr : instr → sim (Option val)
| instr.load mt pv =>
match mt, pv with
| memtype.ptr _, val.bv 27 _ => throw (IO.userError "ASDF")
| _, _ => throw (IO.userError "expected pointer value in load" )
| instr.store _ _ _ =>
do let pv <- f;
g;
(match pv with
| val.bv 27 _ => throw (IO.userError "asdf")
| _ => throw (IO.userError "expected pointer value in store" ))
|
c8fe5ec8cb043cbf08616337f9819f18821b6bc3 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/topology/metric_space/antilipschitz.lean | ad5b1f072f31d0ce52e8a3a3d27810ccf5eef334 | [
"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 | 7,534 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import topology.metric_space.lipschitz
import topology.uniform_space.complete_separated
/-!
# Antilipschitz functions
We say that a map `f : α → β` between two (extended) metric spaces is
`antilipschitz_with K`, `K ≥ 0`, if for all `x, y` we have `edist x y ≤ K * edist (f x) (f y)`.
For a metric space, the latter inequality is equivalent to `dist x y ≤ K * dist (f x) (f y)`.
## Implementation notes
The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have
coercions both to `ℝ` and `ℝ≥0∞`. We do not require `0 < K` in the definition, mostly because
we do not have a `posreal` type.
-/
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale nnreal
open set
/-- We say that `f : α → β` is `antilipschitz_with K` if for any two points `x`, `y` we have
`K * edist x y ≤ edist (f x) (f y)`. -/
def antilipschitz_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) :=
∀ x y, edist x y ≤ K * edist (f x) (f y)
lemma antilipschitz_with_iff_le_mul_dist [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0}
{f : α → β} : antilipschitz_with K f ↔ ∀ x y, dist x y ≤ K * dist (f x) (f y) :=
by { simp only [antilipschitz_with, edist_nndist, dist_nndist], norm_cast }
alias antilipschitz_with_iff_le_mul_dist ↔ antilipschitz_with.le_mul_dist
antilipschitz_with.of_le_mul_dist
lemma antilipschitz_with.mul_le_dist [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0}
{f : α → β} (hf : antilipschitz_with K f) (x y : α) : ↑K⁻¹ * dist x y ≤ dist (f x) (f y) :=
begin
by_cases hK : K = 0, by simp [hK, dist_nonneg],
rw [nnreal.coe_inv, ← div_eq_inv_mul],
rw div_le_iff' (nnreal.coe_pos.2 $ pos_iff_ne_zero.2 hK),
exact hf.le_mul_dist x y
end
namespace antilipschitz_with
variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ]
variables {K : ℝ≥0} {f : α → β}
/-- Extract the constant from `hf : antilipschitz_with K f`. This is useful, e.g.,
if `K` is given by a long formula, and we want to reuse this value. -/
@[nolint unused_arguments] -- uses neither `f` nor `hf`
protected def K (hf : antilipschitz_with K f) : ℝ≥0 := K
protected lemma injective {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β]
{K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) : function.injective f :=
λ x y h, by simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y
lemma mul_le_edist (hf : antilipschitz_with K f) (x y : α) :
↑K⁻¹ * edist x y ≤ edist (f x) (f y) :=
begin
by_cases hK : K = 0, by simp [hK],
rw [ennreal.coe_inv hK, mul_comm, ← div_eq_mul_inv],
apply ennreal.div_le_of_le_mul,
rw mul_comm,
exact hf x y
end
protected lemma id : antilipschitz_with 1 (id : α → α) :=
λ x y, by simp only [ennreal.coe_one, one_mul, id, le_refl]
lemma comp {Kg : ℝ≥0} {g : β → γ} (hg : antilipschitz_with Kg g)
{Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) :
antilipschitz_with (Kf * Kg) (g ∘ f) :=
λ x y,
calc edist x y ≤ Kf * edist (f x) (f y) : hf x y
... ≤ Kf * (Kg * edist (g (f x)) (g (f y))) : ennreal.mul_left_mono (hg _ _)
... = _ : by rw [ennreal.coe_mul, mul_assoc]
lemma restrict (hf : antilipschitz_with K f) (s : set α) :
antilipschitz_with K (s.restrict f) :=
λ x y, hf x y
lemma cod_restrict (hf : antilipschitz_with K f) {s : set β} (hs : ∀ x, f x ∈ s) :
antilipschitz_with K (s.cod_restrict f hs) :=
λ x y, hf x y
lemma to_right_inv_on' {s : set α} (hf : antilipschitz_with K (s.restrict f))
{g : β → α} {t : set β} (g_maps : maps_to g t s) (g_inv : right_inv_on g f t) :
lipschitz_with K (t.restrict g) :=
λ x y, by simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, subtype.edist_eq, subtype.coe_mk]
using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩
lemma to_right_inv_on (hf : antilipschitz_with K f) {g : β → α} {t : set β}
(h : right_inv_on g f t) :
lipschitz_with K (t.restrict g) :=
(hf.restrict univ).to_right_inv_on' (maps_to_univ g t) h
lemma to_right_inverse (hf : antilipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) :
lipschitz_with K g :=
begin
intros x y,
have := hf (g x) (g y),
rwa [hg x, hg y] at this
end
lemma uniform_embedding_of_injective (hfinj : function.injective f) (hf : antilipschitz_with K f)
(hfc : uniform_continuous f) : uniform_embedding f :=
begin
refine emetric.uniform_embedding_iff.2 ⟨hfinj, hfc, λ δ δ0, _⟩,
by_cases hK : K = 0,
{ refine ⟨1, ennreal.zero_lt_one, λ x y _, lt_of_le_of_lt _ δ0⟩,
simpa only [hK, ennreal.coe_zero, zero_mul] using hf x y },
{ refine ⟨K⁻¹ * δ, _, λ x y hxy, lt_of_le_of_lt (hf x y) _⟩,
{ exact canonically_ordered_semiring.mul_pos.2 ⟨ennreal.inv_pos.2 ennreal.coe_ne_top, δ0⟩ },
{ rw [mul_comm, ← div_eq_mul_inv] at hxy,
have := ennreal.mul_lt_of_lt_div hxy,
rwa mul_comm } }
end
lemma uniform_embedding {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0}
{f : α → β} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_embedding f :=
uniform_embedding_of_injective hf.injective hf hfc
lemma closed_embedding {α : Type*} {β : Type*} [emetric_space α] [emetric_space β] {K : ℝ≥0}
{f : α → β} [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) :
closed_embedding f :=
{ closed_range :=
begin
apply is_complete.is_closed,
rw ← complete_space_iff_is_complete_range (hf.uniform_embedding hfc),
apply_instance,
end,
.. (hf.uniform_embedding hfc).embedding }
lemma subtype_coe (s : set α) : antilipschitz_with 1 (coe : s → α) :=
antilipschitz_with.id.restrict s
lemma of_subsingleton [subsingleton α] {K : ℝ≥0} : antilipschitz_with K f :=
λ x y, by simp only [subsingleton.elim x y, edist_self, zero_le]
end antilipschitz_with
namespace antilipschitz_with
open metric
variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β}
lemma bounded_preimage (hf : antilipschitz_with K f)
{s : set β} (hs : bounded s) :
bounded (f ⁻¹' s) :=
exists.intro (K * diam s) $ λ x y hx hy,
calc dist x y ≤ K * dist (f x) (f y) : hf.le_mul_dist x y
... ≤ K * diam s : mul_le_mul_of_nonneg_left (dist_le_diam_of_mem hs hx hy) K.2
/-- The image of a proper space under an expanding onto map is proper. -/
protected lemma proper_space {α : Type*} [metric_space α] {K : ℝ≥0} {f : α → β} [proper_space α]
(hK : antilipschitz_with K f) (f_cont : continuous f) (hf : function.surjective f) :
proper_space β :=
begin
apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _),
let K := f ⁻¹' (closed_ball x₀ r),
have A : is_closed K := is_closed_ball.preimage f_cont,
have B : bounded K := hK.bounded_preimage bounded_closed_ball,
have : is_compact K := compact_iff_closed_bounded.2 ⟨A, B⟩,
convert this.image f_cont,
exact (hf.image_preimage _).symm
end
end antilipschitz_with
lemma lipschitz_with.to_right_inverse [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0}
{f : α → β} (hf : lipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) :
antilipschitz_with K g :=
λ x y, by simpa only [hg _] using hf (g x) (g y)
|
9fbd4653b3828150d58a12c8dc0f67f19b266d36 | d5ecf6c46a2f605470a4a7724909dc4b9e7350e0 | /analysis/measure_theory/lebesgue_measure.lean | c0be5cc72e6b4b674fc6393b5e0f07991a39ef4d | [
"Apache-2.0"
] | permissive | MonoidMusician/mathlib | 41f79df478987a636b735c338396813d2e8e44c4 | 72234ef1a050eea3a2197c23aeb345fc13c08ff3 | refs/heads/master | 1,583,672,205,771 | 1,522,892,143,000 | 1,522,892,143,000 | 128,144,032 | 0 | 0 | Apache-2.0 | 1,522,892,144,000 | 1,522,890,892,000 | Lean | UTF-8 | Lean | false | false | 12,558 | 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
Lebesgue measure on the real line
-/
import analysis.measure_theory.measure_space analysis.measure_theory.borel_space
noncomputable theory
open classical set lattice filter
open ennreal (of_real)
namespace measure_theory
/- "Lebesgue" lebesgue_length of an interval
Important: if `s` is not a interval [a, b) its value is `∞`. This is important to extend this to the
Lebesgue measure. -/
def lebesgue_length (s : set ℝ) : ennreal := ⨅a b (h₁ : a ≤ b) (h₂ : s = Ico a b), of_real (b - a)
@[simp] lemma lebesgue_length_Ico {a b : ℝ} (h : a ≤ b) :
lebesgue_length (Ico a b) = of_real (b - a) :=
le_antisymm
(infi_le_of_le a $ infi_le_of_le b $ infi_le_of_le h $ infi_le_of_le rfl $ le_refl _)
(le_infi $ assume a', le_infi $ assume b', le_infi $ assume h', le_infi $ assume eq,
match Ico_eq_Ico_iff.mp eq with
| or.inl ⟨h₁, h₂⟩ :=
have a = b, from le_antisymm h h₁,
have a' = b', from le_antisymm h' h₂,
by simp *
| or.inr ⟨h₁, h⟩ := by simp *
end)
@[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 :=
have ∅ = Ico 0 (0:ℝ),
from set.ext $ by simp [Ico, not_le],
by rw [this, lebesgue_length_Ico]; simp [le_refl]
lemma le_lebesgue_length {r : ennreal} {s : set ℝ } (h : ∀a b, a ≤ b → s ≠ Ico a b) :
r ≤ lebesgue_length s :=
le_infi $ assume a, le_infi $ assume b, le_infi $ assume hab, le_infi $ assume heq, (h a b hab heq).elim
lemma lebesgue_length_Ico_le_lebesgue_length_Ico {a₁ b₁ a₂ b₂ : ℝ} (ha : a₂ ≤ a₁) (hb : b₁ ≤ b₂) :
lebesgue_length (Ico a₁ b₁) ≤ lebesgue_length (Ico a₂ b₂) :=
(le_total b₁ a₁).elim
(assume : b₁ ≤ a₁, by simp [Ico_eq_empty_iff.mpr this])
(assume h₁ : a₁ ≤ b₁,
have h₂ : a₂ ≤ b₂, from le_trans (le_trans ha h₁) hb,
by simp [h₁, h₂, -sub_eq_add_neg]; exact sub_le_sub hb ha)
lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ}
(hab : a ≤ b) (hcd : ∀i, c i ≤ d i) (habcd : Ico a b ⊆ (⋃i, Ico (c i) (d i))) :
lebesgue_length (Ico a b) ≤ (∑i, lebesgue_length (Ico (c i) (d i))) :=
let
s := λx, ∑i, lebesgue_length (Ico (c i) (min (d i) x)),
M := {x : ℝ | a ≤ x ∧ x ≤ b ∧ of_real (x - a) ≤ s x }
in
have a ∈ M, by simp [M, le_refl, hab],
have b ∈ upper_bounds M, by simp [upper_bounds, M] {contextual:=tt},
let ⟨x, hx⟩ := exists_supremum_real ‹a ∈ M› ‹b ∈ upper_bounds M› in
have h' : is_lub ((λx, of_real (x - a)) '' M) (of_real (x - a)),
from is_lub_of_is_lub_of_tendsto
(assume x ⟨hx, _, _⟩ y ⟨hy, _, _⟩ h,
have hx : 0 ≤ x - a, by rw [le_sub_iff_add_le]; simp [hx],
have hy : 0 ≤ y - a, by rw [le_sub_iff_add_le]; simp [hy],
by rw [ennreal.of_real_le_of_real_iff hx hy]; from sub_le_sub h (le_refl a))
hx
(ne_empty_iff_exists_mem.mpr ⟨a, ‹_›⟩)
(tendsto.comp (tendsto_sub (tendsto_id' inf_le_left) tendsto_const_nhds) ennreal.tendsto_of_real),
have hax : a ≤ x, from hx.left a ‹a ∈ M›,
have hxb : x ≤ b, from hx.right b ‹b ∈ upper_bounds M›,
have hx_sx : of_real (x - a) ≤ s x,
from h'.right _ $ assume r ⟨y, hy, eq⟩,
have ∀i, lebesgue_length (Ico (c i) (min (d i) y)) ≤ lebesgue_length (Ico (c i) (min (d i) x)),
from assume i,
lebesgue_length_Ico_le_lebesgue_length_Ico (le_refl _) (inf_le_inf (le_refl _) (hx.left _ hy)),
eq ▸ le_trans hy.2.2 $ ennreal.tsum_le_tsum this,
have hxM : x ∈ M,
from ⟨hax, hxb, hx_sx⟩,
have x = b,
from le_antisymm hxb $ not_lt.mp $ assume hxb : x < b,
have ∃k, x ∈ Ico (c k) (d k), by simpa using habcd ⟨hxM.left, hxb⟩,
let ⟨k, hxc, hxd⟩ := this, y := min (d k) b in
have hxy' : x < y, from lt_min hxd hxb,
have hxy : x ≤ y, from le_of_lt hxy',
have of_real (y - a) ≤ s y,
from calc of_real (y - a) = of_real (x - a) + of_real (y - x) :
begin
rw [ennreal.of_real_add],
simp,
repeat { simp [hax, hxy, -sub_eq_add_neg] }
end
... ≤ s x + (∑i, ⨆ h : i = k, of_real (y - x)) :
add_le_add' hx_sx (le_trans (by simp) (@ennreal.le_tsum _ _ k))
... ≤ (∑i, lebesgue_length (Ico (c i) (min (d i) x)) + ⨆ h : i = k, of_real (y - x)) :
by rw [tsum_add]; simp [ennreal.has_sum]
... ≤ s y : ennreal.tsum_le_tsum $ assume i, by_cases
(assume : i = k,
have eq₁ : min (d k) y = y, from min_eq_right $ min_le_left _ _,
have eq₂ : min (d k) x = x, from min_eq_right $ le_of_lt hxd,
have h : c k ≤ y, from le_min (hcd _) (le_trans hxc $ le_of_lt hxb),
have eq: y - x + (x - c k) = y - c k, by rw [add_sub, sub_add_cancel],
by simp [h, hxy, hxc, eq, eq₁, eq₂, this, -sub_eq_add_neg, add_sub_cancel'_right, le_refl])
(assume h : i ≠ k, by simp [h, ennreal.bot_eq_zero];
from lebesgue_length_Ico_le_lebesgue_length_Ico (le_refl _) (inf_le_inf (le_refl _) hxy)),
have ¬ x < y, from not_lt.mpr $ hx.left y ⟨le_trans hax hxy, min_le_right _ _, this⟩,
this hxy',
have hbM : b ∈ M, from this ▸ hxM,
calc lebesgue_length (Ico a b) ≤ s b : by simp [hab]; exact hbM.right.right
... ≤ ∑i, lebesgue_length (Ico (c i) (d i)) : ennreal.tsum_le_tsum $ assume a,
lebesgue_length_Ico_le_lebesgue_length_Ico (le_refl _) (min_le_left _ _)
/-- The Lebesgue outer measure, as an outer measure of ℝ. -/
def lebesgue_outer : outer_measure ℝ :=
outer_measure.of_function lebesgue_length lebesgue_length_empty
lemma lebesgue_outer_Ico {a b : ℝ} (h : a ≤ b) :
lebesgue_outer.measure_of (Ico a b) = of_real (b - a) :=
le_antisymm
(let f : ℕ → set ℝ := λi, nat.rec_on i (Ico a b) (λn s, ∅) in
infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $
calc (∑i, lebesgue_length (f i)) = ({0} : finset ℕ).sum (λi, lebesgue_length (f i)) :
tsum_eq_sum $ by intro i; cases i; simp
... = lebesgue_length (Ico a b) : by simp; refl
... ≤ of_real (b - a) : by simp [h])
(le_infi $ assume f, le_infi $ assume hf, by_cases
(assume : ∀i, ∃p:ℝ×ℝ, p.1 ≤ p.2 ∧ f i = Ico p.1 p.2,
let ⟨cd, hcd⟩ := axiom_of_choice this in
have hcd₁ : ∀i, (cd i).1 ≤ (cd i).2, from assume i, (hcd i).1,
have hcd₂ : ∀i, f i = Ico (cd i).1 (cd i).2, from assume i, (hcd i).2,
calc of_real (b - a) = lebesgue_length (Ico a b) :
by simp [h]
... ≤ (∑i, lebesgue_length (Ico (cd i).1 (cd i).2)) :
lebesgue_length_subadditive h hcd₁ (by simpa [hcd₂] using hf)
... = _ :
by simp [hcd₂])
(assume h,
have ∃i, ∀(c d : ℝ), c ≤ d → f i ≠ Ico c d,
by simpa [classical.not_forall] using h,
let ⟨i, hi⟩ := this in
calc of_real (b - a) ≤ lebesgue_length (f i) : le_lebesgue_length hi
... ≤ (∑i, lebesgue_length (f i)) : ennreal.le_tsum))
lemma lebesgue_outer_is_measurable_Iio {c : ℝ} :
lebesgue_outer.caratheodory.is_measurable (Iio c) :=
outer_measure.caratheodory_is_measurable $ assume t, by_cases
(assume : ∃a b, a ≤ b ∧ t = Ico a b,
let ⟨a, b, hab, ht⟩ := this in
begin
cases le_total a c with hac hca; cases le_total b c with hbc hcb;
simp [*, max_eq_right, max_eq_left, min_eq_left, min_eq_right, le_refl,
-sub_eq_add_neg, sub_add_sub_cancel'],
show of_real (b - a + (b - a)) ≤ of_real (b - a),
rw [ennreal.of_real_of_nonpos],
{ apply zero_le },
{ have : b - a ≤ 0, from sub_nonpos.2 (le_trans hbc hca),
simpa using add_le_add this this }
end)
(assume h, by simp at h; from le_lebesgue_length h)
/-- Lebesgue measure on the Borel sets
The outer Lebesgue measure is the completion of this measure. (TODO: proof this)
-/
def lebesgue : measure_space ℝ :=
lebesgue_outer.to_measure $
calc measure_theory.borel ℝ = measurable_space.generate_from (⋃a:ℚ, {Iio a}) :
borel_eq_generate_from_Iio_rat
... ≤ lebesgue_outer.caratheodory :
measurable_space.generate_from_le $ by simp [lebesgue_outer_is_measurable_Iio] {contextual := tt}
lemma tendsto_of_nat_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top :=
tendsto_infi.2 $ assume r, tendsto_principal.2 $
let ⟨n, hn⟩ := exists_nat_gt r in
mem_at_top_sets.2 ⟨n, λ m h, le_trans (le_of_lt hn) (nat.cast_le.2 h)⟩
lemma lebesgue_Ico {a b : ℝ} : lebesgue.measure (Ico a b) = of_real (b - a) :=
match le_total a b with
| or.inl h :=
begin
rw [lebesgue.measure_eq is_measurable_Ico],
{ exact lebesgue_outer_Ico h },
repeat {apply_instance}
end
| or.inr h :=
have hba : b - a ≤ 0, by simp [-sub_eq_add_neg, h],
have eq : Ico a b = ∅, from Ico_eq_empty_iff.mpr h,
by simp [ennreal.of_real_of_nonpos, *] at *
end
lemma lebesgue_Ioo {a b : ℝ} : lebesgue.measure (Ioo a b) = of_real (b - a) :=
by_cases (assume h : b ≤ a, by simp [h, -sub_eq_add_neg, ennreal.of_real_of_nonpos]) $
assume : ¬ b ≤ a,
have h : a < b, from not_le.mp this,
let s := λn:ℕ, a + (b - a) * (↑(n + 1))⁻¹ in
have tendsto s at_top (nhds (a + (b - a) * 0)),
from tendsto_add tendsto_const_nhds $ tendsto_mul tendsto_const_nhds $
(tendsto_comp_succ_at_top_iff.mpr tendsto_of_nat_at_top_at_top).comp tendsto_inverse_at_top_nhds_0,
have hs : tendsto s at_top (nhds a), by simpa,
have hsm : ∀i j, j ≤ i → s i ≤ s j,
from assume i j hij,
have h₁ : ∀j:ℕ, (0:ℝ) < (j + 1),
from assume j, nat.cast_pos.2 $ add_pos_of_nonneg_of_pos (nat.zero_le j) zero_lt_one,
have h₂ : (↑(j + 1) : ℝ) ≤ ↑(i + 1), from nat.cast_le.2 $ add_le_add hij (le_refl _),
add_le_add (le_refl _) $
mul_le_mul (le_refl _) (inv_le_inv_of_le (h₁ j) h₂) (le_of_lt $ inv_pos $ h₁ i) $
by simp [le_sub_iff_add_le, -sub_eq_add_neg, le_of_lt h],
have has : ∀i, a < s i,
from assume i,
have (0:ℝ) < ↑(i + 1), from nat.cast_pos.2 $ lt_add_of_le_of_pos (nat.zero_le _) zero_lt_one,
(lt_add_iff_pos_right _).mpr $ mul_pos
(by simp [-sub_eq_add_neg, sub_lt_iff, (>), ‹a < b›]) (inv_pos this),
have eq₁ : Ioo a b = (⋃n, Ico (s n) b),
from set.ext $ assume x,
begin
simp [iff_def, Ico, Ioo, -sub_eq_add_neg] {contextual := tt},
constructor,
exact assume hax hxb,
have {a | a < x } ∈ (nhds a).sets, from mem_nhds_sets (is_open_gt' _) hax,
have {n | s n < x} ∈ at_top.sets, from hs this,
let ⟨n, hn⟩ := inhabited_of_mem_sets at_top_ne_bot this in
⟨n, le_of_lt hn⟩,
exact assume i hsx hxb, lt_of_lt_of_le (has i) hsx,
end,
have (⨆i, of_real (b - s i)) = of_real (b - a),
from is_lub_iff_supr_eq.mp $ is_lub_of_mem_nhds
(assume x ⟨i, eq⟩, eq ▸ ennreal.of_real_le_of_real $ sub_le_sub (le_refl _) $ le_of_lt $ has _)
begin
show range (λi, of_real (b - s i)) ∈ (at_top.map (λi, of_real (b - s i))).sets,
rw [← image_univ]; exact image_mem_map univ_mem_sets
end
begin
have : tendsto (λi, of_real (b - s i)) at_top (nhds (of_real (b - a))),
from (tendsto_sub tendsto_const_nhds hs).comp ennreal.tendsto_of_real,
rw [inf_of_le_left this],
exact map_ne_bot at_top_ne_bot
end,
have eq₂ : (⨆i, lebesgue.measure (Ico (s i) b)) = of_real (b - a),
by simp only [lebesgue_Ico, this],
begin
rw [eq₁, measure_Union_eq_supr_nat, eq₂],
show ∀i, is_measurable (Ico (s i) b), from assume i, is_measurable_Ico,
show monotone (λi, Ico (s i) b),
from assume i j hij x hx, ⟨le_trans (hsm _ _ hij) hx.1, hx.2⟩
end
lemma lebesgue_singleton {a : ℝ} : lebesgue.measure {a} = 0 :=
have Ico a (a + 1) \ Ioo a (a + 1) = {a},
from set.ext $ assume a',
begin
simp [iff_def, Ico, Ioo, lt_irrefl, le_refl, zero_lt_one,
le_iff_eq_or_lt, or_imp_distrib] {contextual := tt},
exact assume h₁ h₂,
⟨assume eq, by rw [eq] at h₂; exact (lt_irrefl _ h₂).elim,
assume h₃, (lt_irrefl a' $ lt_trans h₂ h₃).elim⟩
end,
calc lebesgue.measure {a} = lebesgue.measure (Ico a (a + 1) \ Ioo a (a + 1)) :
congr_arg _ this.symm
... = lebesgue.measure (Ico a (a + 1)) - lebesgue.measure (Ioo a (a + 1)) :
measure_sdiff (assume x, and.imp le_of_lt id) is_measurable_Ico is_measurable_Ioo $
by simp [lebesgue_Ico]; exact ennreal.of_real_lt_infty
... = 0 : by simp [lebesgue_Ico, lebesgue_Ioo]
end measure_theory
|
b46ebf45a21214a6209beb053f08f61a08004758 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/qpf/multivariate/constructions/quot.lean | 1c347b456054be7693d0e3dbef0ffa39045dfcf8 | [
"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 | 2,293 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Simon Hudon
-/
import data.qpf.multivariate.basic
/-!
# The quotient of QPF is itself a QPF
The quotients are here defined using a surjective function and
its right inverse. They are very similar to the `abs` and `repr`
functions found in the definition of `mvqpf`
-/
universes u
open_locale mvfunctor
namespace mvqpf
variables {n : ℕ}
variables {F : typevec.{u} n → Type u}
section repr
variables [mvfunctor F] [q : mvqpf F]
variables {G : typevec.{u} n → Type u} [mvfunctor G]
variable {FG_abs : Π {α}, F α → G α}
variable {FG_repr : Π {α}, G α → F α}
/-- If `F` is a QPF then `G` is a QPF as well. Can be used to
construct `mvqpf` instances by transporting them across
surjective functions -/
def quotient_qpf
(FG_abs_repr : Π {α} (x : G α), FG_abs (FG_repr x) = x)
(FG_abs_map : ∀ {α β} (f : α ⟹ β) (x : F α), FG_abs (f <$$> x) = f <$$> FG_abs x) :
mvqpf G :=
{ P := q.P,
abs := λ α p, FG_abs (abs p),
repr := λ α x, repr (FG_repr x),
abs_repr := λ α x, by rw [abs_repr,FG_abs_repr],
abs_map := λ α β f p, by rw [abs_map,FG_abs_map] }
end repr
section rel
variables (R : ∀ ⦃α⦄, F α → F α → Prop)
/-- Functorial quotient type -/
def quot1 (α : typevec n) :=
quot (@R α)
instance quot1.inhabited {α : typevec n} [inhabited $ F α] : inhabited (quot1 R α) :=
⟨ quot.mk _ (default _) ⟩
variables [mvfunctor F] [q : mvqpf F]
variables (Hfunc : ∀ ⦃α β⦄ (a b : F α) (f : α ⟹ β), R a b → R (f <$$> a) (f <$$> b))
/-- `map` of the `quot1` functor -/
def quot1.map ⦃α β⦄ (f : α ⟹ β) : quot1.{u} R α → quot1.{u} R β :=
quot.lift (λ x : F α, quot.mk _ (f <$$> x : F β)) $ λ a b h,
quot.sound $ Hfunc a b _ h
/-- `mvfunctor` instance for `quot1` with well-behaved `R` -/
def quot1.mvfunctor : mvfunctor (quot1 R) :=
{ map := quot1.map R Hfunc }
/-- `quot1` is a qpf -/
noncomputable def rel_quot : @mvqpf _ (quot1 R) (mvqpf.quot1.mvfunctor R Hfunc) :=
@quotient_qpf n F _ q _ (mvqpf.quot1.mvfunctor R Hfunc) (λ α x, quot.mk _ x) (λ α, quot.out)
(λ α x, quot.out_eq _)
(λ α β f x, rfl)
end rel
end mvqpf
|
60cff8ba96c710022da7e04ab79cf4ac6cb719c0 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/category/Rel.lean | 0c614339ae23f601df6ab65e67c6e2aa12170e58 | [] | 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 | 765 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.category.default
import Mathlib.PostPort
universes u u_1
namespace Mathlib
/-!
The category of types with binary relations as morphisms.
-/
namespace category_theory
/-- A type synonym for `Type`, which carries the category instance for which
morphisms are binary relations. -/
def Rel :=
Type u
protected instance Rel.inhabited : Inhabited Rel :=
eq.mpr sorry sort.inhabited
/-- The category of types with binary relations as morphisms. -/
protected instance rel : large_category Rel :=
category.mk
|
4f49e88f7030e4c4c44570fc90de9662073779cc | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/data/set/function.lean | aa418ac083502829e23fa0d8e5af9a1b0d775012 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 18,238 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov
-/
import data.set.basic
import logic.function.basic
/-! # Functions over sets
## Main definitions
### Predicate
* `eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`;
* `maps_to f s t` : `f` sends every point of `s` to a point of `t`;
* `inj_on f s` : restriction of `f` to `s` is injective;
* `surj_on f s t` : every point in `s` has a preimage in `s`;
* `bij_on f s t` : `f` is a bijection between `s` and `t`;
* `left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`;
* `right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`;
* `inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e.
we have `left_inv_on f' f s` and `right_inv_on f' f t`.
### Functions
* `restrict f s` : restrict the domain of `f` to the set `s`;
* `cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`;
* `maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s`
and the codomain to `t`.
-/
universes u v w x y
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
open function
namespace set
/-! ### Restrict -/
/-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version
takes an argument `↥s` instead of `subtype s`. -/
def restrict (f : α → β) (s : set α) : s → β := λ x, f x
lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl
@[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : restrict f s x = f x := rfl
@[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (restrict f s) = f '' s :=
range_comp.trans $ congr_arg (('') f) s.range_coe_subtype
/-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version
has codomain `↥s` instead of `subtype s`. -/
def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s :=
λ x, ⟨f x, h x⟩
@[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) :
(cod_restrict f s h x : β) = f x :=
rfl
variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g : β → γ}
{f' f₁' f₂' : β → α} {g' : γ → β}
/-! ### Equality on a set -/
/-- Two functions `f₁ f₂ : α → β` are equal on `s`
if `f₁ x = f₂ x` for all `x ∈ a`. -/
@[reducible] def eq_on (f₁ f₂ : α → β) (s : set α) : Prop :=
∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x
@[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s :=
λ x hx, (h hx).symm
lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s :=
⟨eq_on.symm, eq_on.symm⟩
@[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s :=
λ _ _, rfl
@[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s :=
λ x hx, (h₁ hx).trans (h₂ hx)
theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s :=
image_congr heq
lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ :=
λ x hx, hf (hs hx)
/-! ### maps to -/
/-- `maps_to f a b` means that the image of `a` is contained in `b`. -/
@[reducible] def maps_to (f : α → β) (s : set α) (t : set β) : Prop := s ⊆ f ⁻¹' t
/-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s`
and the codomain to `t`. Same as `subtype.map`. -/
def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) :
s → t :=
subtype.map f h
@[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) :
(h.restrict f s t x : β) = f x := rfl
theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t :=
image_subset_iff.symm
theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _
theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t :=
maps_to'.1 h
theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) :
maps_to f₂ s t :=
λ x hx, by rw [mem_preimage, ← h hx]; exact h₁ hx
theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p :=
λ x h, h₁ (h₂ h)
theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) :
∀ n, maps_to (f^[n]) s s
| 0 := λ _, id
| (n+1) := (maps_to.iterate n).comp h
theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) :
(h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ :=
begin
funext x,
rw [subtype.coe_ext, maps_to.coe_restrict_apply],
induction n with n ihn generalizing x,
{ refl },
{ simp [nat.iterate, ihn] }
end
theorem maps_to.mono (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) (hf : maps_to f s₁ t₁) :
maps_to f s₂ t₂ :=
λ x hx, ht (hf $ hs hx)
theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial
theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to'
theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _
theorem maps_to_range (f : set α) (s : set α) : maps_to f s (range f) :=
(maps_to_image f s).mono (subset.refl s) (image_subset_range _ _)
/-! ### Injectivity on a set -/
/-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/
@[reducible] def inj_on (f : α → β) (s : set α) : Prop :=
∀⦃x₁ x₂ : α⦄, x₁ ∈ s → x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂
theorem inj_on_empty (f : α → β) : inj_on f ∅ :=
λ _ _ h₁ _ _, false.elim h₁
theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) :
inj_on f₂ s :=
λ x y hx hy, h hx ▸ h hy ▸ h₁ hx hy
theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ :=
λ x y hx hy H, ht (h hx) (h hy) H
lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ :=
⟨λ h x y hx hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩
theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) :
inj_on (g ∘ f) s :=
λ x y hx hy heq, hf hx hy $ hg (h hx) (h hy) heq
lemma inj_on_iff_injective : inj_on f s ↔ injective (restrict f s) :=
⟨λ H a b h, subtype.eq $ H a.2 b.2 h,
λ H a b as bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩
lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) :
(inv_fun_on f s₂) '' (f '' s₁) = s₁ :=
begin
have : eq_on ((inv_fun_on f s₂) ∘ f) id s₁, from λz hz, inv_fun_on_eq' h (ht hz),
rw [← image_comp, this.image_eq, image_id]
end
lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ powerset (range f)) :
inj_on (preimage f) B :=
begin
intros s t hs ht hst,
rw [←image_preimage_eq_of_subset (hB hs), ←image_preimage_eq_of_subset (hB ht), hst]
end
/-! ### Surjectivity on a set -/
/-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/
@[reducible] def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s
theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _
theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty :=
(ht.mono h).of_image
theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t :=
by rwa [surj_on, ← H.image_eq]
theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t :=
⟨λ H, H.congr h, λ H, H.congr h.symm⟩
theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ :=
subset.trans ht $ subset.trans hf $ image_subset _ hs
theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p :=
subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _
lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ :=
by simp [surjective, surj_on, subset_def]
lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (restrict f s) :=
⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩,
λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩
lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) :
f '' s = t :=
eq_of_subset_of_subset h₂.image_subset h₁
/-! ### Bijectivity -/
/-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/
@[reducible] def bij_on (f : α → β) (s : set α) (t : set β) : Prop :=
maps_to f s t ∧ inj_on f s ∧ surj_on f s t
lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left
lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left
lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right
lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) :
bij_on f s t :=
⟨h₁, h₂, h₃⟩
lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ :=
⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩
lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) :=
bij_on.mk (maps_to_image f s) h (subset.refl _)
theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) :
bij_on f₂ s t :=
bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h)
theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
lemma bij_on.image_eq (h : bij_on f s t) :
f '' s = t :=
h.surj_on.image_eq_of_maps_to h.maps_to
theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p :=
bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to)
(hg.surj_on.comp hf.surj_on)
lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ :=
iff.intro
(λ h, let ⟨inj, surj⟩ := h in
⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩)
(λ h, let ⟨map, inj, surj⟩ := h in
⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩)
/-! ### left inverse -/
/-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/
@[reducible] def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop :=
∀ ⦃x⦄, x ∈ s → f' (f x) = x
lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h
lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx
lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s)
{t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s :=
λ x hx, heq (h₁' hx) ▸ h₁ hx
theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) :
left_inv_on f₁' f₂ s :=
λ x hx, heq hx ▸ h₁ hx
theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s :=
λ x₁ x₂ h₁ h₂ heq,
calc
x₁ = f₁' (f x₁) : eq.symm $ h h₁
... = f₁' (f x₂) : congr_arg f₁' heq
... = x₂ : h h₂
theorem left_inv_on.surj_on (h : left_inv_on f₁' f s) (hf : maps_to f s t) : surj_on f₁' t s :=
λ x hx, ⟨f x, hf hx, h hx⟩
theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) :
left_inv_on (f' ∘ g') (g ∘ f) s :=
λ x h,
calc
(f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h))
... = x : hf' h
/-! ### Right inverse -/
/-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/
@[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop :=
left_inv_on f f' t
lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h
lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy
theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) :
right_inv_on f₂' f t :=
h₁.congr_right heq
theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s)
(heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t :=
left_inv_on.congr_left h₁ hg heq
theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) :
surj_on f s t :=
hf.surj_on hf'
theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p)
(g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p :=
hg.comp hf g'pt
theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t)
(h₁ : maps_to f s t) (h₂ : maps_to f' t s) :
right_inv_on f f' s :=
λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h))
theorem eq_on_of_left_inv_of_right_inv (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t)
(h : maps_to f₂' t s) : eq_on f₁' f₂' t :=
λ y hy,
calc
f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm
... = f₂' y : h₁ (h hy)
theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) :
left_inv_on f f' t :=
λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx]
/-! ### Two-side inverses -/
/-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/
@[reducible] def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop :=
left_inv_on g f s ∧ right_inv_on g f t
lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩
theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) : bij_on f s t :=
⟨hf, h.left.inj_on, h.right.surj_on hf'⟩
/-! ### `inv_fun_on` is a left/right inverse -/
theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) :
left_inv_on (inv_fun_on f s) f s :=
λ x hx, inv_fun_on_eq' h hx
theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) :
right_inv_on (inv_fun_on f s) f t :=
λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy
theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) :
inv_on (inv_fun_on f s) f s t :=
⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩
theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) :
inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t :=
begin
refine ⟨_, h.right_inv_on_inv_fun_on⟩,
rintros _ ⟨y, hy, rfl⟩,
rw [h.right_inv_on_inv_fun_on hy]
end
theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) :
maps_to (inv_fun_on f s) t s :=
λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy
theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) :
bij_on f (inv_fun_on f s '' t) t :=
begin
refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _),
rintros _ ⟨y, hy, rfl⟩,
rwa [mem_preimage, h.right_inv_on_inv_fun_on hy]
end
theorem surj_on_iff_exists_bij_on_subset :
surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t :=
begin
split,
{ rcases eq_empty_or_nonempty t with rfl|ht,
{ exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ },
{ assume h,
haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩,
exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }},
{ rintros ⟨s', hs', hfs'⟩,
exact hfs'.surj_on.mono hs' (subset.refl _) }
end
end set
/-! ### Piecewise defined function -/
namespace set
variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i)
@[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] :
piecewise set.univ f g = f :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
variable [∀j, decidable (j ∈ s)]
lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) :=
begin
simp [piecewise],
ext i,
by_cases h : i = j,
{ rw h, simp },
{ by_cases h' : i ∈ s; simp [h, h'] }
end
@[simp, priority 990]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i :=
by simp [piecewise, hi]
@[simp, priority 990]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i :=
by simp [piecewise, hi]
@[simp, priority 990]
lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g i = s.piecewise f g i :=
by simp [piecewise, h]
end set
namespace function
open set
variables {f : α → β} {g : β → γ} {s : set α}
lemma injective.inj_on (h : injective f) (s : set α) : s.inj_on f :=
λ _ _ _ _ heq, h heq
lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) :=
(hg.inj_on univ).comp hf (maps_to_univ _ _)
lemma surjective.surj_on (hf : surjective f) (s : set β) :
surj_on f univ s :=
(surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _)
lemma update_comp_eq_of_not_mem_range [decidable_eq β]
(g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) :
(function.update g i a) ∘ f = g ∘ f :=
begin
ext p,
have : f p ≠ i,
{ by_contradiction H,
push_neg at H,
rw ← H at h,
exact h (set.mem_range_self _) },
simp [this],
end
lemma update_comp_eq_of_injective [decidable_eq α] [decidable_eq β]
(g : β → γ) {f : α → β} (hf : function.injective f) (i : α) (a : γ) :
(function.update g (f i) a) ∘ f = function.update (g ∘ f) i a :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp },
{ have : f j ≠ f i := hf.ne h,
simp [h, this] }
end
end function
|
58fcae9a405afc047c1f2a4e4a9649fbc5980776 | ecea1a568b8a7bdfef1206845f7dc2e62b85b6b3 | /library/init/data/nat/lemmas.lean | 24f014796ae30569cd259c9e0d6c962b3f6ce193 | [
"Apache-2.0"
] | permissive | ndcroos/lean | b1b6de42ee4d3ded05829373e505e09614d4acdf | 6919d231413705c892eec02bdacd7d7d916524c8 | refs/heads/master | 1,625,911,732,192 | 1,507,549,407,000 | 1,507,549,407,000 | 106,106,359 | 0 | 0 | null | 1,507,388,410,000 | 1,507,388,410,000 | null | UTF-8 | Lean | false | false | 50,473 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
-/
prelude
import init.data.nat.basic init.data.nat.div init.data.nat.pow init.meta init.algebra.functions
universes u
namespace nat
attribute [pre_smt] nat_zero_eq_zero
protected lemma zero_add : ∀ n : ℕ, 0 + n = n
| 0 := rfl
| (n+1) := congr_arg succ (zero_add n)
lemma succ_add : ∀ n m : ℕ, (succ n) + m = succ (n + m)
| n 0 := rfl
| n (m+1) := congr_arg succ (succ_add n m)
lemma add_succ (n m : ℕ) : n + succ m = succ (n + m) :=
rfl
protected lemma add_zero (n : ℕ) : n + 0 = n :=
rfl
lemma add_one (n : ℕ) : n + 1 = succ n :=
rfl
lemma succ_eq_add_one (n : ℕ) : succ n = n + 1 :=
rfl
protected lemma add_comm : ∀ n m : ℕ, n + m = m + n
| n 0 := eq.symm (nat.zero_add n)
| n (m+1) :=
suffices succ (n + m) = succ (m + n), from
eq.symm (succ_add m n) ▸ this,
congr_arg succ (add_comm n m)
protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k)
| n m 0 := rfl
| n m (succ k) := by rw [add_succ, add_succ, add_assoc]
protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) :=
left_comm nat.add nat.add_comm nat.add_assoc
protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k
| 0 m k := by simp [nat.zero_add] {contextual := tt}
| (succ n) m k := λ h,
have n+m = n+k, by simp [succ_add] at h; injection h,
add_left_cancel this
protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k :=
have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h,
nat.add_left_cancel this
lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 :=
assume h, nat.no_confusion h
lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n
| 0 h := absurd h (nat.succ_ne_zero 0)
| (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h))
protected lemma one_ne_zero : 1 ≠ (0 : ℕ) :=
assume h, nat.no_confusion h
protected lemma zero_ne_one : 0 ≠ (1 : ℕ) :=
assume h, nat.no_confusion h
instance : zero_ne_one_class ℕ :=
{ zero := 0, one := 1, zero_ne_one := nat.zero_ne_one }
lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0
| 0 m := by simp [nat.zero_add]
| (n+1) m := λ h,
begin
exfalso,
rw [add_one, succ_add] at h,
apply succ_ne_zero _ h
end
lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 :=
@eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h)
@[simp]
lemma pred_zero : pred 0 = 0 :=
rfl
@[simp]
lemma pred_succ (n : ℕ) : pred (succ n) = n :=
rfl
protected lemma mul_zero (n : ℕ) : n * 0 = 0 :=
rfl
lemma mul_succ (n m : ℕ) : n * succ m = n * m + n :=
rfl
protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0
| 0 := rfl
| (succ n) := by rw [mul_succ, zero_mul]
private meta def sort_add :=
`[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]]
lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m
| n 0 := rfl
| n (succ m) :=
begin
simp [mul_succ, add_succ, succ_mul n m],
sort_add
end
protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k
| n m 0 := rfl
| n m (succ k) :=
begin simp [mul_succ, right_distrib n m k], sort_add end
protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k
| 0 m k := by simp [nat.zero_mul]
| (succ n) m k :=
begin simp [succ_mul, left_distrib n m k], sort_add end
protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n
| n 0 := by rw [nat.zero_mul, nat.mul_zero]
| n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m]
protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k)
| n m 0 := rfl
| n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k]
protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add
protected lemma one_mul (n : ℕ) : 1 * n = n :=
by rw [nat.mul_comm, nat.mul_one]
instance : comm_semiring nat :=
{add := nat.add,
add_assoc := nat.add_assoc,
zero := nat.zero,
zero_add := nat.zero_add,
add_zero := nat.add_zero,
add_comm := nat.add_comm,
mul := nat.mul,
mul_assoc := nat.mul_assoc,
one := nat.succ nat.zero,
one_mul := nat.one_mul,
mul_one := nat.mul_one,
left_distrib := nat.left_distrib,
right_distrib := nat.right_distrib,
zero_mul := nat.zero_mul,
mul_zero := nat.mul_zero,
mul_comm := nat.mul_comm}
/- properties of inequality -/
protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m :=
p ▸ less_than_or_equal.refl n
lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m :=
nat.le_trans h (le_succ m)
lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m :=
nat.le_trans (le_succ n) h
protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m :=
le_of_succ_le h
def lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step
lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 :=
by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)}
protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → n > 0 :=
or.resolve_left (eq_zero_or_pos n)
protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k :=
nat.le_trans (less_than_or_equal.step h₁)
protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k :=
nat.le_trans (succ_le_succ h₁)
def lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n)
lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n
protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m :=
less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n))
protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ a ≥ b
| a 0 := or.inr (zero_le a)
| a (b+1) :=
match lt_or_ge a b with
| or.inl h := or.inl (le_succ_of_le h)
| or.inr h :=
match nat.eq_or_lt_of_le h with
| or.inl h1 := or.inl (h1 ▸ lt_succ_self b)
| or.inr h1 := or.inr h1
end
end
protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m :=
or.imp_left nat.le_of_lt (nat.lt_or_ge m n)
protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n :=
or.resolve_right (or.swap (nat.eq_or_lt_of_le h1))
protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) :=
⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩,
λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩
instance : linear_order ℕ :=
{ le := nat.less_than_or_equal,
le_refl := @nat.le_refl,
le_trans := @nat.le_trans,
le_antisymm := @nat.le_antisymm,
le_total := @nat.le_total,
lt := nat.lt,
lt_iff_le_not_le := @nat.lt_iff_le_not_le }
lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 :=
le_antisymm h (zero_le _)
lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b :=
succ_le_succ
lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b :=
le_of_succ_le
lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b :=
le_of_succ_le_succ
lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m
| 0 _ h₁ h := absurd rfl h₁
| _ 0 h₁ h := absurd h (not_lt_zero _)
| (succ n) (succ m) _ h := lt_of_succ_lt_succ h
lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h
lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h
lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k
| n 0 := nat.le_refl n
| n (k+1) := le_succ_of_le (le_add_right n k)
lemma le_add_left (n m : ℕ): n ≤ m + n :=
nat.add_comm n m ▸ le_add_right n m
lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m
| n ._ (less_than_or_equal.refl ._) := ⟨0, rfl⟩
| n ._ (@less_than_or_equal.step ._ m h) :=
match le.dest h with
| ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩
end
lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m :=
h ▸ le_add_right n k
protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end
end
protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k :=
begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end
protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w
begin
rw [nat.add_assoc] at hw,
apply nat.add_left_cancel hw
end
end
protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m :=
begin
rw [nat.add_comm _ k, nat.add_comm _ k],
apply nat.le_of_add_le_add_left
end
protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m :=
⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩
protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m :=
let h' := nat.le_of_lt h in
nat.lt_of_le_and_ne
(nat.le_of_add_le_add_left h')
(λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end)
protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m :=
lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k)
protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k :=
nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k
protected lemma lt_add_of_pos_right {n k : ℕ} (h : k > 0) : n < n + k :=
nat.add_lt_add_left h n
protected lemma lt_add_of_pos_left {n k : ℕ} (h : k > 0) : n < k + n :=
by rw add_comm; exact nat.lt_add_of_pos_right h
protected lemma zero_lt_one : 0 < (1:nat) :=
zero_lt_succ 0
lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m :=
match le.dest h with
| ⟨l, hl⟩ :=
have k * n + k * l = k * m, by rw [← left_distrib, hl],
le.intro this
end
lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k :=
mul_comm k m ▸ mul_comm k n ▸ mul_le_mul_left k h
protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : k > 0) : k * n < k * m :=
nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h))
protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : k > 0) : n * k < m * k :=
mul_comm k m ▸ mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk
instance : decidable_linear_ordered_semiring nat :=
{ nat.comm_semiring with
add_left_cancel := @nat.add_left_cancel,
add_right_cancel := @nat.add_right_cancel,
lt := nat.lt,
le := nat.le,
le_refl := nat.le_refl,
le_trans := @nat.le_trans,
le_antisymm := @nat.le_antisymm,
le_total := @nat.le_total,
lt_of_add_lt_add_left := @nat.lt_of_add_lt_add_left,
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
add_lt_add_left := @nat.add_lt_add_left,
add_le_add_left := @nat.add_le_add_left,
le_of_add_le_add_left := @nat.le_of_add_le_add_left,
zero_lt_one := zero_lt_succ 0,
mul_le_mul_of_nonneg_left := assume a b c h₁ h₂, nat.mul_le_mul_left c h₁,
mul_le_mul_of_nonneg_right := assume a b c h₁ h₂, nat.mul_le_mul_right c h₁,
mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left,
mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right,
decidable_lt := nat.decidable_lt,
decidable_le := nat.decidable_le,
decidable_eq := nat.decidable_eq }
-- all the fields are already included in the decidable_linear_ordered_semiring instance
instance : decidable_linear_ordered_cancel_comm_monoid ℕ :=
{ nat.decidable_linear_ordered_semiring with
add_left_cancel := @nat.add_left_cancel }
lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n :=
le_of_succ_le_succ
theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k :=
le_antisymm (le_of_mul_le_mul_left (le_of_eq H) Hn)
(le_of_mul_le_mul_left (le_of_eq H.symm) Hn)
theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k :=
by rw [mul_comm n m, mul_comm k m] at H; exact eq_of_mul_eq_mul_left Hm H
/- sub properties -/
@[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0
| 0 := rfl
| (a+1) := congr_arg pred (zero_sub a)
lemma sub_lt_succ (a b : ℕ) : a - b < succ a :=
lt_succ_of_le (sub_le a b)
protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k
| 0 := h
| (succ z) := pred_le_pred (sub_le_sub_right z)
/- bit0/bit1 properties -/
protected lemma bit0_succ_eq (n : ℕ) : bit0 (succ n) = succ (succ (bit0 n)) :=
show succ (succ n + n) = succ (succ (n + n)), from
congr_arg succ (succ_add n n)
protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) :=
rfl
protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) :=
eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n))
protected lemma bit0_ne_zero : ∀ {n : ℕ}, n ≠ 0 → bit0 n ≠ 0
| 0 h := absurd rfl h
| (n+1) h := succ_ne_zero _
protected lemma bit1_ne_zero (n : ℕ) : bit1 n ≠ 0 :=
show succ (n + n) ≠ 0, from
succ_ne_zero (n + n)
protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1
| 0 h h1 := absurd rfl h
| (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _))
protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1
| 0 h := absurd h (ne.symm nat.one_ne_zero)
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1
(λ h2, absurd h2 (succ_ne_zero (n + n)))
protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1
| 0 h := nat.no_confusion h
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n)))
protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m
| 0 m h := absurd h (ne.symm (nat.add_self_ne_one m))
| (n+1) 0 h :=
have h1 : succ (bit0 (succ n)) = 0, from h,
absurd h1 (nat.succ_ne_zero _)
| (n+1) (m+1) h :=
have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from
nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h,
have h2 : bit1 n = bit0 m, from
nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')),
absurd h2 (bit1_ne_bit0 n m)
protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m :=
λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n)
protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m
| 0 0 h := rfl
| 0 (m+1) h := by contradiction
| (n+1) 0 h := by contradiction
| (n+1) (m+1) h :=
have succ (succ (n + n)) = succ (succ (m + m)),
begin unfold bit0 at h, simp [add_one, add_succ, succ_add] at h, exact h end,
have n + n = m + m, by repeat {injection this with this},
have n = m, from bit0_inj this,
by rw this
protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m :=
λ n m h,
have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, assumption end,
have bit0 n = bit0 m, by injection this,
nat.bit0_inj this
protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m :=
λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁
protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m :=
λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁
protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n :=
λ h, ne.symm (nat.bit0_ne_zero h)
protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n :=
ne.symm (nat.bit1_ne_zero n)
protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n :=
ne.symm (nat.bit0_ne_one n)
protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n :=
λ h, ne.symm (nat.bit1_ne_one h)
protected lemma zero_lt_bit1 (n : nat) : 0 < bit1 n :=
zero_lt_succ _
protected lemma zero_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 0 < bit0 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit0_succ_eq,
apply zero_lt_succ
end
protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit1_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit0_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m :=
add_lt_add h h
protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m :=
succ_lt_succ (add_lt_add h h)
protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m :=
lt_succ_of_le (add_le_add h h)
protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m
| n 0 h := absurd h (not_lt_zero _)
| n (succ m) h :=
have n ≤ m, from le_of_lt_succ h,
have succ (n + n) ≤ succ (m + m), from succ_le_succ (add_le_add this this),
have succ (n + n) ≤ succ m + m, {rw succ_add, assumption},
show succ (n + n) < succ (succ m + m), from lt_succ_of_le this
protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n :=
show 1 ≤ succ (bit0 n), from
succ_le_succ (zero_le (bit0 n))
protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n
| 0 h := absurd rfl h
| (n+1) h :=
suffices 1 ≤ succ (succ (bit0 n)), from
eq.symm (nat.bit0_succ_eq n) ▸ this,
succ_le_succ (zero_le (succ (bit0 n)))
/- Extra instances to short-circuit type class resolution -/
instance : add_comm_monoid nat := by apply_instance
instance : add_monoid nat := by apply_instance
instance : monoid nat := by apply_instance
instance : comm_monoid nat := by apply_instance
instance : comm_semigroup nat := by apply_instance
instance : semigroup nat := by apply_instance
instance : add_comm_semigroup nat := by apply_instance
instance : add_semigroup nat := by apply_instance
instance : distrib nat := by apply_instance
instance : semiring nat := by apply_instance
instance : ordered_semiring nat := by apply_instance
/- subtraction -/
@[simp]
protected theorem sub_zero (n : ℕ) : n - 0 = n :=
rfl
theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) :=
rfl
theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m :=
succ_sub_succ_eq_sub n m
protected theorem sub_self : ∀ (n : ℕ), n - n = 0
| 0 := by rw nat.sub_zero
| (succ n) := by rw [succ_sub_succ, sub_self n]
/- TODO(Leo): remove the following ematch annotations as soon as we have
arithmetic theory in the smt_stactic -/
@[ematch_lhs]
protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m
| n 0 m := by rw [add_zero, add_zero]
| n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m]
@[ematch_lhs]
protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m :=
by rw [add_comm k n, add_comm k m, nat.add_sub_add_right]
@[ematch_lhs]
protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n :=
suffices n + m - (0 + m) = n, from
by rwa [zero_add] at this,
by rw [nat.add_sub_add_right, nat.sub_zero]
@[ematch_lhs]
protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m :=
show n + m - (n + 0) = m, from
by rw [nat.add_sub_add_left, nat.sub_zero]
protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k)
| n m 0 := by rw [add_zero, nat.sub_zero]
| n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k]
theorem le_of_le_of_sub_le_sub_right {n m k : ℕ}
(h₀ : k ≤ m)
(h₁ : n - k ≤ m - k)
: n ≤ m :=
begin
revert k m,
induction n with n ; intros k m h₀ h₁,
{ apply zero_le },
{ cases k with k,
{ apply h₁ },
cases m with m,
{ cases not_succ_le_zero _ h₀ },
{ simp [succ_sub_succ] at h₁,
apply succ_le_succ,
apply ih_1 _ h₁,
apply le_of_succ_le_succ h₀ }, }
end
protected theorem sub_le_sub_right_iff (n m k : ℕ)
(h : k ≤ m)
: n - k ≤ m - k ↔ n ≤ m :=
⟨ le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩
theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 :=
show (n + 0) - (n + m) = 0, from
by rw [nat.add_sub_add_left, nat.zero_sub]
theorem add_le_to_le_sub (x : ℕ) {y k : ℕ}
(h : k ≤ y)
: x + k ≤ y ↔ x ≤ y - k :=
by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel]
lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b)
: b - a < b :=
begin
apply sub_lt _ h₀,
apply lt_of_lt_of_le h₀ h₁
end
theorem sub_one (n : ℕ) : n - 1 = pred n :=
rfl
theorem succ_sub_one (n : ℕ) : succ n - 1 = n :=
rfl
theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, n > 0 → succ (pred n) = n
| 0 h := absurd h (lt_irrefl 0)
| (succ k) h := rfl
theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m, by rw [← hk, sub_self_add])
protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m
| n 0 H := begin rw [nat.sub_zero] at H, simp [H] end
| 0 (m+1) H := zero_le _
| (n+1) (m+1) H := add_le_add_right
(le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _
protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m :=
⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩
theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left])
protected theorem sub_add_cancel {n m : ℕ} (h : n ≥ m) : n - m + m = n :=
by rw [add_comm, add_sub_of_le h]
protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) :=
exists.elim (nat.le.dest h)
(assume l, assume hl : k + l = m,
by rw [← hl, nat.add_sub_cancel_left, add_comm k, ← add_assoc, nat.add_sub_cancel])
protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b :=
⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end,
assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩
protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m :=
lt_of_not_ge
(assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end)
@[simp] lemma zero_min (a : ℕ) : min 0 a = 0 :=
min_eq_left (zero_le a)
@[simp] lemma min_zero (a : ℕ) : min a 0 = 0 :=
min_eq_right (zero_le a)
-- Distribute succ over min
theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) :=
have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ x : if_pos (succ_le_succ p)
... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)),
have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ y : if_neg (λeq, p (pred_le_pred eq))
... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)),
decidable.by_cases f g
theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m :=
if h : n ≥ m then by rewrite [min_eq_right h]
else by rewrite [sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self]
@[simp] theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n :=
by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)]
/- TODO(Leo): sub + inequalities -/
protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _),
begin
intros n, induction n with n ih,
{intros m h₁, exact absurd h₁ (not_lt_zero _)},
{intros m h₁,
apply or.by_cases (lt_or_eq_of_le (le_of_lt_succ h₁)),
{intros, apply ih, assumption},
{intros, subst m, apply h _ ih}}
end
protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
nat.strong_rec_on n h
protected lemma case_strong_induction_on {p : nat → Prop} (a : nat)
(hz : p 0)
(hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a :=
nat.strong_induction_on a $ λ n,
match n with
| 0 := λ _, hz
| (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂))
end
/- mod -/
lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x :=
by have h := mod_def_aux x y; rwa [dif_eq_if] at h
@[simp] lemma mod_zero (a : nat) : a % 0 = a :=
begin
rw mod_def,
have h : ¬ (0 < 0 ∧ 0 ≤ a),
simp [lt_irrefl],
simp [if_neg, h]
end
lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a :=
begin
rw mod_def,
have h' : ¬(0 < b ∧ b ≤ a),
simp [not_le_of_gt h],
simp [if_neg, h']
end
@[simp] lemma zero_mod (b : nat) : 0 % b = 0 :=
begin
rw mod_def,
have h : ¬(0 < b ∧ b ≤ 0),
{intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)},
simp [if_neg, h]
end
lemma mod_eq_sub_mod {a b : nat} (h : a ≥ b) : a % b = (a - b) % b :=
or.elim (eq_zero_or_pos b)
(λb0, by rw [b0, nat.sub_zero])
(λh₂, by rw [mod_def, if_pos (and.intro h₂ h)])
lemma mod_lt (x : nat) {y : nat} (h : y > 0) : x % y < y :=
begin
induction x using nat.case_strong_induction_on with x ih,
{rw zero_mod, assumption},
{apply or.elim (decidable.em (succ x < y)),
{intro h₁, rwa [mod_eq_of_lt h₁]},
{intro h₁,
have h₁ : succ x % y = (succ x - y) % y, {exact mod_eq_sub_mod (le_of_not_gt h₁)},
have this : succ x - y ≤ x, {exact le_of_lt_succ (sub_lt (succ_pos x) h)},
have h₂ : (succ x - y) % y < y, {exact ih _ this},
rwa [← h₁] at h₂}}
end
@[simp] theorem mod_self (n : nat) : n % n = 0 :=
by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod]
@[simp] lemma mod_one (n : ℕ) : n % 1 = 0 :=
have n % 1 < 1, from (mod_lt n) (succ_pos 0),
eq_zero_of_le_zero (le_of_lt_succ this)
lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 :=
match n % 2, @nat.mod_lt n 2 dec_trivial with
| 0, _ := or.inl rfl
| 1, _ := or.inr rfl
| k+2, h := absurd h dec_trivial
end
/- div & mod -/
lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 :=
by have h := div_def_aux x y; rwa dif_eq_if at h
lemma mod_add_div (m k : ℕ)
: m % k + k * (m / k) = m :=
begin
apply nat.strong_induction_on m,
clear m,
intros m IH,
cases decidable.em (0 < k ∧ k ≤ m) with h h',
-- 0 < k ∧ k ≤ m
{ have h' : m - k < m,
{ apply nat.sub_lt _ h.left,
apply lt_of_lt_of_le h.left h.right },
rw [div_def, mod_def, if_pos h, if_pos h],
simp [left_distrib, IH _ h'],
rw [← nat.add_sub_assoc h.right, nat.add_sub_cancel_left] },
-- ¬ (0 < k ∧ k ≤ m)
{ rw [div_def, mod_def, if_neg h', if_neg h'], simp },
end
/- div -/
@[simp] protected lemma div_one (n : ℕ) : n / 1 = n :=
have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _,
by simp [mod_one] at this; assumption
@[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 :=
begin rw [div_def], simp [lt_irrefl] end
@[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 :=
eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt)
protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n
| 0 h := by simp [nat.div_zero]; apply zero_le
| (succ k) h :=
suffices succ k * (m / succ k) ≤ succ k * n, from le_of_mul_le_mul_left this (zero_lt_succ _),
calc
succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : le_add_left _ _
... = m : by rw mod_add_div
... ≤ succ k * n : h
protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m
| m 0 := by simp [nat.div_zero]; apply zero_le
| m (succ n) :=
have m ≤ succ n * m, from calc
m = 1 * m : by simp
... ≤ succ n * m : mul_le_mul_right _ (succ_le_succ (zero_le _)),
nat.div_le_of_le_mul this
lemma div_eq_sub_div {a b : nat} (h₁ : b > 0) (h₂ : a ≥ b) : a / b = (a - b) / b + 1 :=
begin
rw [div_def a, if_pos],
split ; assumption
end
lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 :=
begin
rw [div_def a, if_neg],
intro h₁,
apply not_le_of_gt h₀ h₁.right
end
-- this is a Galois connection
-- f x ≤ y ↔ x ≤ g y
-- with
-- f x = x * k
-- g y = y / k
theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ}
(Hk : k > 0)
: x ≤ y / k ↔ x * k ≤ y :=
begin
-- Hk is needed because, despite div being made total, y / 0 := 0
-- x * 0 ≤ y ↔ x ≤ y / 0
-- ↔ 0 ≤ y ↔ x ≤ 0
-- ↔ true ↔ x = 0
-- ↔ x = 0
revert x,
apply nat.strong_induction_on y _,
clear y,
intros y IH x,
cases lt_or_ge y k with h h,
-- base case: y < k
{ rw [div_eq_of_lt h],
cases x with x,
{ simp [zero_mul, zero_le] },
{ simp [succ_mul, not_succ_le_zero],
apply not_le_of_gt,
apply lt_of_lt_of_le h,
apply le_add_right } },
-- step: k ≤ y
{ rw [div_eq_sub_div Hk h],
cases x with x,
{ simp [zero_mul, zero_le] },
{ have Hlt : y - k < y,
{ apply sub_lt_of_pos_le ; assumption },
rw [ ← add_one
, nat.add_le_add_iff_le_right
, IH (y - k) Hlt x
, add_one
, succ_mul, add_le_to_le_sub _ h ]
} }
end
theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ}
(Hk : k > 0)
: x / k < y ↔ x < y * k :=
begin
simp [lt_iff_not_ge],
apply not_iff_not_of_iff,
apply le_div_iff_mul_le _ _ Hk
end
def iterate {A : Type} (op : A → A) : ℕ → A → A
| 0 := λ a, a
| (succ k) := λ a, op (iterate k a)
notation f`^[`n`]` := iterate f n
/- successor and predecessor -/
theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _
theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) :=
by cases n; simp
theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k :=
⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩
theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m :=
nat.succ.inj_arrow H id
theorem discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B :=
by ginduction n with h; [exact H1 h, exact H2 _ h]
theorem one_succ_zero : 1 = succ 0 := rfl
theorem two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a
| 0 := H1
| 1 := H2
| (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _)
theorem sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m
| 0 m := H1 _
| (succ n) 0 := H2 _
| (succ n) (succ m) := H3 _ _ (sub_induction n m)
/- addition -/
theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m :=
by simp [succ_add, add_succ]
theorem one_add (n : ℕ) : 1 + n = succ n := by simp
protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m :=
right_comm nat.add nat.add_comm nat.add_assoc
theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 :=
⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩
theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0
| 0 m := λ h, or.inl rfl
| (succ n) m :=
begin
rw succ_mul, intro h,
exact or.inr (eq_zero_of_add_eq_zero_left h)
end
/- properties of inequality -/
theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m :=
nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ)
theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false :=
nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂)
theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false :=
le_lt_antisymm h₂ h₁
protected theorem nat.lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n :=
le_lt_antisymm (nat.le_of_lt h₁)
protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a ≥ b → C) : C :=
decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a)))
protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C)
(h₃ : b < a → C) : C :=
nat.lt_ge_by_cases h₁ (λ h₁,
nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁)))
protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a :=
nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h))
protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a :=
(nat.lt_trichotomy a b).resolve_left hnlt
theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h
def one_pos := nat.zero_lt_one
theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m :=
mul_le_mul h h (zero_le _) (zero_le _)
theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m
| 0 m h := mul_pos h h
| (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _)
theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m :=
⟨mul_self_le_mul_self, λh, decidable.by_contradiction $
λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩
theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m :=
iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $
iff.symm (lt_iff_not_ge _ _)
theorem le_mul_self : Π (n : ℕ), n ≤ n * n
| 0 := le_refl _
| (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t
/- subtraction -/
protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n :=
by induction h; [refl, exact le_trans (pred_le _) ih_1]
theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k :=
by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ]
protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n :=
by rw [nat.sub_sub, nat.sub_sub, add_comm]
theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m
| 0 m := by simp [nat.zero_sub, pred_zero, zero_mul]
| (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel]
theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n :=
by rw [mul_comm, mul_pred_left, mul_comm]
protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k
| n 0 k := by simp [nat.sub_zero]
| n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub]
protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k :=
by rw [mul_comm, nat.mul_sub_right_distrib, mul_comm m n, mul_comm n k]
protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) :=
by rw [nat.mul_sub_left_distrib, right_distrib, right_distrib, mul_comm b a, add_comm (a*a) (a*b),
nat.add_sub_add_left]
theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a*b + a + b + 1 :=
begin rw [← add_one, ← add_one], simp [right_distrib, left_distrib] end
theorem succ_sub {m n : ℕ} (h : m ≥ n) : succ m - n = succ (m - n) :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left])
protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : n - m > 0 :=
have 0 + m < n - m + m, begin rw [zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end,
lt_of_add_lt_add_right this
protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m :=
(nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (eq.symm (add_sub_of_le h))
protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m :=
(nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2
(by rwa [nat.add_right_comm, nat.sub_add_cancel])
theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin
rw nat.sub_sub,
apply nat.sub_lt,
apply lt_of_lt_of_le (nat.zero_lt_succ _) h,
rw add_comm,
apply nat.zero_lt_succ
end
theorem pred_inj : ∀ {a b : nat}, a > 0 → b > 0 → nat.pred a = nat.pred b → a = b
| (succ a) (succ b) ha hb h := have a = b, from h, by rw this
| (succ a) 0 ha hb h := absurd hb (lt_irrefl _)
| 0 (succ b) ha hb h := absurd ha (lt_irrefl _)
| 0 0 ha hb h := rfl
/- find -/
section find
parameter {p : ℕ → Prop}
private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k
parameters [decidable_pred p] (H : ∃n, p n)
private def wf_lbp : well_founded lbp :=
⟨let ⟨n, pn⟩ := H in
suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _),
λm, nat.rec_on m
(λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩)
(λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩
protected def find_x : {n // p n ∧ ∀m < n, ¬p m} :=
@well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp
(λm IH al, if pm : p m then ⟨m, pm, al⟩ else
have ∀ n ≤ m, ¬p n, from λn h, or.elim (lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm),
IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h))
0 (λn h, absurd h (nat.not_lt_zero _))
protected def find : ℕ := nat.find_x.1
protected theorem find_spec : p nat.find := nat.find_x.2.left
protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right
protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m :=
le_of_not_gt (λ l, find_min l h)
end find
/- mod -/
theorem mod_le (x y : ℕ) : x % y ≤ x :=
or.elim (lt_or_ge x y)
(λxlty, by rw mod_eq_of_lt xlty; refl)
(λylex, or.elim (eq_zero_or_pos y)
(λy0, by rw [y0, mod_zero]; refl)
(λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex))
@[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z :=
by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x :=
by rw [add_comm, add_mod_right]
@[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y :=
by {induction z with z ih, simp, rw[mul_succ, ← add_assoc, add_mod_right, ih]}
@[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z :=
by rw [mul_comm, add_mul_mod_self_left]
@[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 :=
by rw [← zero_add (m*n), add_mul_mod_self_left, zero_mod]
@[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 :=
by rw [mul_comm, mul_mod_right]
theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) :=
if y0 : y = 0 then
by rw [y0, mul_zero, mod_zero, mod_zero]
else if z0 : z = 0 then
by rw [z0, zero_mul, zero_mul, zero_mul, mod_zero]
else x.strong_induction_on $ λn IH,
have y0 : y > 0, from nat.pos_of_ne_zero y0,
have z0 : z > 0, from nat.pos_of_ne_zero z0,
or.elim (le_or_gt y n)
(λyn, by rw [
mod_eq_sub_mod yn,
mod_eq_sub_mod (mul_le_mul_left z yn),
← nat.mul_sub_left_distrib];
exact IH _ (sub_lt (lt_of_lt_of_le y0 yn) y0))
(λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (mul_lt_mul_of_pos_left yn z0)])
theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z :=
by rw [mul_comm x z, mul_comm y z, mul_comm (x % y) z]; apply mul_mod_mul_left
theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)]
: cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 :=
begin
cases d with h h
; unfold decidable.to_bool cond,
{ cases mod_two_eq_zero_or_one x with h' h',
rw h', cases h h' },
{ rw h },
end
theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n :=
begin
induction k with k,
{ simp },
{ have h₂ : n * k ≤ x,
{ rw [mul_succ] at h₁,
apply nat.le_trans _ h₁,
apply le_add_right _ n },
have h₄ : x - n * k ≥ n,
{ apply @nat.le_of_add_le_add_right (n*k),
rw [nat.sub_add_cancel h₂],
simp [mul_succ] at h₁, simp [h₁] },
rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, ih_1 h₂] }
end
/- div -/
theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p :=
begin
cases eq_zero_or_pos n with h₀ h₀,
{ rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] },
{ induction p with p,
{ simp },
{ have h₂ : n*p ≤ x,
{ transitivity,
{ apply nat.mul_le_mul_left, apply le_succ },
{ apply h₁ } },
have h₃ : x - n * p ≥ n,
{ apply le_of_add_le_add_right,
rw [nat.sub_add_cancel h₂, add_comm],
rw [mul_succ] at h₁,
apply h₁ },
rw [sub_succ, ← ih_1 h₂],
rw [@div_eq_sub_div (x - n*p) _ h₀ h₃],
simp [add_one, pred_succ, mul_succ, nat.sub_sub] } }
end
theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m
| m 0 := by simp; apply zero_le
| m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _)
@[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) / z = succ (x / z) :=
by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : z > 0) : (z + x) / z = succ (x / z) :=
by rw [add_comm, add_div_right x H]
@[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : m > 0) : m * n / m = n :=
by {induction n; simp [*, mul_succ, -mul_comm]}
@[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m :=
by rw [mul_comm, mul_div_right _ H]
protected theorem div_self {n : ℕ} (H : n > 0) : n / n = 1 :=
let t := add_div_right 0 H in by rwa [zero_add, nat.zero_div] at t
theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) / y = x / y + z :=
by {induction z with z ih, simp, rw [mul_succ, ← add_assoc, add_div_right _ H, ih]}
theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : z > 0) : (x + y * z) / z = x / z + y :=
by rw [mul_comm, add_mul_div_left _ _ H]
protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m :=
let t := add_mul_div_right 0 m H in by rwa [zero_add, nat.zero_div, zero_add] at t
protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : n > 0) : n * m / n = m :=
by rw [mul_comm, nat.mul_div_cancel _ H]
protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : n > 0) (H2 : m = k * n) :
m / n = k :=
by rw [H2, nat.mul_div_cancel _ H1]
protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : n > 0) (H2 : m = n * k) :
m / n = k :=
by rw [H2, nat.mul_div_cancel_left _ H1]
protected theorem div_eq_of_lt_le {m n k : ℕ}
(lo : k * n ≤ m) (hi : m < succ k * n) :
m / n = k :=
have npos : n > 0, from (eq_zero_or_pos _).resolve_left $ λ hn,
by rw [hn, mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi),
le_antisymm
(le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi))
((nat.le_div_iff_mul_le _ _ npos).2 lo)
theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) :=
begin
have npos : n > 0 := (eq_zero_or_pos _).resolve_left (λ n0,
by rw [n0, zero_mul] at h₁; exact not_lt_zero _ h₁),
apply nat.div_eq_of_lt_le,
{ rw [nat.mul_sub_right_distrib, mul_comm],
apply nat.sub_le_sub_left,
exact (div_lt_iff_lt_mul _ _ npos).1 (lt_succ_self _) },
{ change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n,
rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁),
succ_pred_eq_of_pos (nat.sub_pos_of_lt _)],
{ rw [nat.mul_sub_right_distrib, mul_comm],
apply nat.sub_le_sub_left, apply div_mul_le_self },
{ apply (div_lt_iff_lt_mul _ _ npos).2, rwa mul_comm } }
end
protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) :=
begin
cases eq_zero_or_pos k with k0 kpos, {rw [k0, mul_zero, nat.div_zero, nat.div_zero]},
cases eq_zero_or_pos n with n0 npos, {rw [n0, zero_mul, nat.div_zero, nat.zero_div]},
apply le_antisymm,
{ apply (le_div_iff_mul_le _ _ (mul_pos npos kpos)).2,
rw [mul_comm n k, ← mul_assoc],
apply (le_div_iff_mul_le _ _ npos).1,
apply (le_div_iff_mul_le _ _ kpos).1,
refl },
{ apply (le_div_iff_mul_le _ _ kpos).2,
apply (le_div_iff_mul_le _ _ npos).2,
rw [mul_assoc, mul_comm n k],
apply (le_div_iff_mul_le _ _ (mul_pos kpos npos)).1,
refl }
end
protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : m > 0) : m * n / (m * k) = n / k :=
by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H]
/- dvd -/
protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n :=
⟨dvd_add h, dvd.elim h $ λd hd, match m, hd with
| ._, rfl := λh₂, dvd.elim h₂ $ λe he, ⟨e - d,
by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩
end⟩
protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n :=
by rw add_comm; exact nat.dvd_add_iff_right h
theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n :=
(nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁
theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m :=
let t := @nat.dvd_add_iff_left _ (m % n) _ (dvd_trans h (dvd_mul_right n (m / n))) in
by rwa mod_add_div at t
theorem le_of_dvd {m n : ℕ} (h : n > 0) : m ∣ n → m ≤ n :=
λ⟨k, e⟩, by {
revert h, rw e, refine k.cases_on _ _,
exact λhn, absurd hn (lt_irrefl _),
exact λk _, let t := mul_le_mul_left m (succ_pos k) in by rwa mul_one at t }
theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n
| m 0 h₁ h₂ := eq_zero_of_zero_dvd h₂
| 0 n h₁ h₂ := (eq_zero_of_zero_dvd h₁).symm
| (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂)
theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 :=
nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2
theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 :=
le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial)
theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n :=
dvd.intro (n / m) $ let t := mod_add_div n m in by simp [H] at t; exact t
theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 :=
dvd.elim H (λ z H1, by rw [H1, mul_mod_right])
theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
instance decidable_dvd : @decidable_rel ℕ (∣) :=
λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m :=
let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, zero_add] at t
protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m :=
by rw [mul_comm, nat.mul_div_cancel' H]
protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) :=
or.elim (eq_zero_or_pos k)
(λh, by rw [h, nat.div_zero, nat.div_zero, mul_zero])
(λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H,
by rw[this, ← mul_assoc, nat.mul_div_cancel _ h])
theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n :=
dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left kpos H1⟩)
theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n :=
by rw [mul_comm m k, mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H
/- pow -/
@[simp] theorem pow_one (b : ℕ) : b^1 = b := by simp [pow_succ]
theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i, x^i ≤ y^i
| 0 := le_refl _
| (succ i) := mul_le_mul (pow_le_pow_of_le_left i) H (zero_le _) (zero_le _)
theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i} : ∀ {j}, i ≤ j → x^i ≤ x^j
| 0 h := by rw eq_zero_of_le_zero h; apply le_refl
| (succ j) h := (lt_or_eq_of_le h).elim
(λhl, by rw [pow_succ, ← mul_one (x^i)]; exact
mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H (zero_le _) (zero_le _))
(λe, by rw e; refl)
theorem pos_pow_of_pos {b : ℕ} (n : ℕ) (h : 0 < b) : 0 < b^n :=
pow_le_pow_of_le_right h (zero_le _)
theorem zero_pow {n : ℕ} (h : 0 < n) : 0^n = 0 :=
by rw [← succ_pred_eq_of_pos h, pow_succ, mul_zero]
theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : i > 0) : x^i < y^i :=
begin
cases i with i, { exact absurd h (not_lt_zero _) },
rw [pow_succ, pow_succ],
exact mul_lt_mul' (pow_le_pow_of_le_left (le_of_lt H) _) H (zero_le _)
(pos_pow_of_pos _ $ lt_of_le_of_lt (zero_le _) H)
end
theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j} (h : i < j) : x^i < x^j :=
begin
have xpos := lt_of_succ_lt H,
refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h),
rw [← mul_one (x^i), pow_succ],
exact nat.mul_lt_mul_of_pos_left H (pos_pow_of_pos _ xpos)
end
/- mod / div / pow -/
theorem mod_pow_succ {b : ℕ} (b_pos : b > 0) (w m : ℕ)
: m % (b^succ w) = b * (m/b % b^w) + m % b :=
begin
apply nat.strong_induction_on m,
clear m,
intros p IH,
cases lt_or_ge p (b^succ w) with h₁ h₁,
-- base case: p < b^succ w
{ have h₂ : p / b < b^w,
{ rw [div_lt_iff_lt_mul p _ b_pos],
simp [pow_succ] at h₁,
simp [h₁] },
rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂],
simp [mod_add_div] },
-- step: p ≥ b^succ w
{ -- Generate condiition for induction principal
have h₂ : p - b^succ w < p,
{ apply sub_lt_of_pos_le _ _ (pos_pow_of_pos _ b_pos) h₁ },
-- Apply induction
rw [mod_eq_sub_mod h₁, IH _ h₂],
-- Normalize goal and h1
simp [pow_succ],
simp [ge, pow_succ] at h₁,
-- Pull subtraction outside mod and div
rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁],
-- Cancel subtraction inside mod b^w
have p_b_ge : b^w ≤ p / b,
{ rw [le_div_iff_mul_le _ _ b_pos],
simp [h₁] },
rw [eq.symm (mod_eq_sub_mod p_b_ge)] }
end
end nat
|
615ffe8bf79a4c132dfefa77af7eb8e44ae0d320 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/algebra/ordered_monoid.lean | 1e21f9dda62d4227d20de415b4cbbd02b655ecd2 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 39,836 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import algebra.group.with_one
import algebra.group.type_tags
import algebra.group.prod
import algebra.order_functions
import order.bounded_lattice
import algebra.ordered_monoid_lemmas
/-!
# Ordered monoids
This file develops the basics of ordered monoids.
## Implementation details
Unfortunately, the number of `'` appended to lemmas in this file
may differ between the multiplicative and the additive version of a lemma.
The reason is that we did not want to change existing names in the library.
-/
set_option old_structure_cmd true
universe u
variable {α : Type u}
/-- An ordered commutative monoid is a commutative monoid
with a partial order such that
* `a ≤ b → c * a ≤ c * b` (multiplication is monotone)
* `a * b < a * c → b < c`.
-/
@[protect_proj, ancestor comm_monoid partial_order]
class ordered_comm_monoid (α : Type*) extends comm_monoid α, partial_order α :=
(mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b)
(lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c)
/-- An ordered (additive) commutative monoid is a commutative monoid
with a partial order such that
* `a ≤ b → c + a ≤ c + b` (addition is monotone)
* `a + b < a + c → b < c`.
-/
@[protect_proj, ancestor add_comm_monoid partial_order]
class ordered_add_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
(lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c)
attribute [to_additive] ordered_comm_monoid
section ordered_instances
@[to_additive]
instance ordered_comm_monoid.to_covariant_class_left (M : Type*) [ordered_comm_monoid M] :
covariant_class M M (*) (≤) :=
{ elim := λ a b c bc, ordered_comm_monoid.mul_le_mul_left _ _ bc a }
@[to_additive]
instance ordered_comm_monoid.to_contravariant_class_left (M : Type*) [ordered_comm_monoid M] :
contravariant_class M M (*) (<) :=
{ elim := λ a b c, ordered_comm_monoid.lt_of_mul_lt_mul_left _ _ _ }
/- This instance can be proven with `by apply_instance`. However, `with_bot ℕ` does not
pick up a `covariant_class M M (function.swap (*)) (≤)` instance without it (see PR #7940). -/
@[to_additive]
instance ordered_comm_monoid.to_covariant_class_right (M : Type*) [ordered_comm_monoid M] :
covariant_class M M (function.swap (*)) (≤) :=
covariant_swap_mul_le_of_covariant_mul_le M
/- This instance can be proven with `by apply_instance`. However, by analogy with the
instance `ordered_comm_monoid.to_covariant_class_right` above, I imagine that without
this instance, some Type would not have a `contravariant_class M M (function.swap (*)) (≤)`
instance. -/
@[to_additive]
instance ordered_comm_monoid.to_contravariant_class_right (M : Type*) [ordered_comm_monoid M] :
contravariant_class M M (function.swap (*)) (<) :=
contravariant_swap_mul_lt_of_contravariant_mul_lt M
end ordered_instances
/-- An `ordered_comm_monoid` with one-sided 'division' in the sense that
if `a ≤ b`, there is some `c` for which `a * c = b`. This is a weaker version
of the condition on canonical orderings defined by `canonically_ordered_monoid`. -/
class has_exists_mul_of_le (α : Type u) [ordered_comm_monoid α] : Prop :=
(exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a * c)
/-- An `ordered_add_comm_monoid` with one-sided 'subtraction' in the sense that
if `a ≤ b`, then there is some `c` for which `a + c = b`. This is a weaker version
of the condition on canonical orderings defined by `canonically_ordered_add_monoid`. -/
class has_exists_add_of_le (α : Type u) [ordered_add_comm_monoid α] : Prop :=
(exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a + c)
attribute [to_additive] has_exists_mul_of_le
export has_exists_mul_of_le (exists_mul_of_le)
export has_exists_add_of_le (exists_add_of_le)
/-- A linearly ordered additive commutative monoid. -/
@[protect_proj, ancestor linear_order ordered_add_comm_monoid]
class linear_ordered_add_comm_monoid (α : Type*)
extends linear_order α, ordered_add_comm_monoid α :=
(lt_of_add_lt_add_left := λ x y z, by {
-- type-class inference uses `a : linear_order α` which it can't unfold, unless we provide this!
-- `lt_iff_le_not_le` gets filled incorrectly with `autoparam` if we don't provide that field.
letI : linear_order α := by refine { le := le, lt := lt, lt_iff_le_not_le := _, .. }; assumption,
apply lt_imp_lt_of_le_imp_le,
exact λ h, add_le_add_left _ _ h _ })
/-- A linearly ordered commutative monoid. -/
@[protect_proj, ancestor linear_order ordered_comm_monoid, to_additive]
class linear_ordered_comm_monoid (α : Type*)
extends linear_order α, ordered_comm_monoid α :=
(lt_of_mul_lt_mul_left := λ x y z, by {
-- type-class inference uses `a : linear_order α` which it can't unfold, unless we provide this!
-- `lt_iff_le_not_le` gets filled incorrectly with `autoparam` if we don't provide that field.
letI : linear_order α := by refine { le := le, lt := lt, lt_iff_le_not_le := _, .. }; assumption,
apply lt_imp_lt_of_le_imp_le,
exact λ h, mul_le_mul_left _ _ h _ })
/-- A linearly ordered commutative monoid with a zero element. -/
class linear_ordered_comm_monoid_with_zero (α : Type*)
extends linear_ordered_comm_monoid α, comm_monoid_with_zero α :=
(zero_le_one : (0 : α) ≤ 1)
/-- A linearly ordered commutative monoid with an additively absorbing `⊤` element.
Instances should include number systems with an infinite element adjoined.` -/
@[protect_proj, ancestor linear_ordered_add_comm_monoid order_top]
class linear_ordered_add_comm_monoid_with_top (α : Type*)
extends linear_ordered_add_comm_monoid α, order_top α :=
(top_add' : ∀ x : α, ⊤ + x = ⊤)
section linear_ordered_add_comm_monoid_with_top
variables [linear_ordered_add_comm_monoid_with_top α] {a b : α}
@[simp]
lemma top_add (a : α) : ⊤ + a = ⊤ := linear_ordered_add_comm_monoid_with_top.top_add' a
@[simp]
lemma add_top (a : α) : a + ⊤ = ⊤ :=
trans (add_comm _ _) (top_add _)
end linear_ordered_add_comm_monoid_with_top
/-- Pullback an `ordered_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.ordered_add_comm_monoid
"Pullback an `ordered_add_comm_monoid` under an injective map."]
def function.injective.ordered_comm_monoid [ordered_comm_monoid α] {β : Type*}
[has_one β] [has_mul β]
(f : β → α) (hf : function.injective f) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
ordered_comm_monoid β :=
{ mul_le_mul_left := λ a b ab c, show f (c * a) ≤ f (c * b), by
{ rw [mul, mul], apply mul_le_mul_left', exact ab },
lt_of_mul_lt_mul_left :=
λ a b c bc, show f b < f c, from lt_of_mul_lt_mul_left' (by rwa [← mul, ← mul] : (f a) * _ < _),
..partial_order.lift f hf,
..hf.comm_monoid f one mul }
/-- Pullback a `linear_ordered_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.linear_ordered_add_comm_monoid
"Pullback an `ordered_add_comm_monoid` under an injective map."]
def function.injective.linear_ordered_comm_monoid [linear_ordered_comm_monoid α] {β : Type*}
[has_one β] [has_mul β]
(f : β → α) (hf : function.injective f) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
linear_ordered_comm_monoid β :=
{ .. hf.ordered_comm_monoid f one mul,
.. linear_order.lift f hf }
lemma bit0_pos [ordered_add_comm_monoid α] {a : α} (h : 0 < a) : 0 < bit0 a :=
add_pos h h
namespace units
@[to_additive]
instance [monoid α] [preorder α] : preorder (units α) :=
preorder.lift (coe : units α → α)
@[simp, norm_cast, to_additive]
theorem coe_le_coe [monoid α] [preorder α] {a b : units α} :
(a : α) ≤ b ↔ a ≤ b := iff.rfl
-- should `to_additive` do this?
attribute [norm_cast] add_units.coe_le_coe
@[simp, norm_cast, to_additive]
theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} :
(a : α) < b ↔ a < b := iff.rfl
attribute [norm_cast] add_units.coe_lt_coe
@[to_additive]
instance [monoid α] [partial_order α] : partial_order (units α) :=
partial_order.lift coe units.ext
@[to_additive]
instance [monoid α] [linear_order α] : linear_order (units α) :=
linear_order.lift coe units.ext
@[simp, norm_cast, to_additive]
theorem max_coe [monoid α] [linear_order α] {a b : units α} :
(↑(max a b) : α) = max a b :=
by by_cases b ≤ a; simp [max, h]
attribute [norm_cast] add_units.max_coe
@[simp, norm_cast, to_additive]
theorem min_coe [monoid α] [linear_order α] {a b : units α} :
(↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [min, h]
attribute [norm_cast] add_units.min_coe
end units
namespace with_zero
local attribute [semireducible] with_zero
instance [preorder α] : preorder (with_zero α) := with_bot.preorder
instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order
instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot
lemma zero_le [partial_order α] (a : with_zero α) : 0 ≤ a := order_bot.bot_le a
lemma zero_lt_coe [preorder α] (a : α) : (0 : with_zero α) < a := with_bot.bot_lt_coe a
@[simp, norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_zero α) < b ↔ a < b :=
with_bot.coe_lt_coe
@[simp, norm_cast] lemma coe_le_coe [partial_order α] {a b : α} : (a : with_zero α) ≤ b ↔ a ≤ b :=
with_bot.coe_le_coe
instance [lattice α] : lattice (with_zero α) := with_bot.lattice
instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order
lemma mul_le_mul_left {α : Type u} [has_mul α] [preorder α]
[covariant_class α α (*) (≤)] :
∀ (a b : with_zero α),
a ≤ b → ∀ (c : with_zero α), c * a ≤ c * b :=
begin
rintro (_ | a) (_ | b) h (_ | c);
try { exact λ f hf, option.no_confusion hf },
{ exact false.elim (not_lt_of_le h (with_zero.zero_lt_coe a))},
{ simp_rw [some_eq_coe] at h ⊢,
norm_cast at h ⊢,
exact covariant_class.elim _ h }
end
lemma lt_of_mul_lt_mul_left {α : Type u} [has_mul α] [partial_order α]
[contravariant_class α α (*) (<)] :
∀ (a b c : with_zero α), a * b < a * c → b < c :=
begin
rintro (_ | a) (_ | b) (_ | c) h;
try { exact false.elim (lt_irrefl none h) },
{ exact with_zero.zero_lt_coe c },
{ exact false.elim (not_le_of_lt h (with_zero.zero_le _)) },
{ simp_rw [some_eq_coe] at h ⊢,
norm_cast at h ⊢,
apply lt_of_mul_lt_mul_left' h }
end
instance [ordered_comm_monoid α] : ordered_comm_monoid (with_zero α) :=
{ mul_le_mul_left := with_zero.mul_le_mul_left,
lt_of_mul_lt_mul_left := with_zero.lt_of_mul_lt_mul_left,
..with_zero.comm_monoid_with_zero,
..with_zero.partial_order }
/-
Note 1 : the below is not an instance because it requires `zero_le`. It seems
like a rather pathological definition because α already has a zero.
Note 2 : there is no multiplicative analogue because it does not seem necessary.
Mathematicians might be more likely to use the order-dual version, where all
elements are ≤ 1 and then 1 is the top element.
-/
/--
If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`.
-/
def ordered_add_comm_monoid [ordered_add_comm_monoid α]
(zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) :=
begin
suffices, refine {
add_le_add_left := this,
..with_zero.partial_order,
..with_zero.add_comm_monoid, .. },
{ intros a b c h,
have h' := lt_iff_le_not_le.1 h,
rw lt_iff_le_not_le at ⊢,
refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩,
cases h₂, cases c with c,
{ cases h'.2 (this _ _ bot_le a) },
{ refine ⟨_, rfl, _⟩,
cases a with a,
{ exact with_bot.some_le_some.1 h'.1 },
{ exact le_of_lt (lt_of_add_lt_add_left $
with_bot.some_lt_some.1 h), } } },
{ intros a b h c ca h₂,
cases b with b,
{ rw le_antisymm h bot_le at h₂,
exact ⟨_, h₂, le_refl _⟩ },
cases a with a,
{ change c + 0 = some ca at h₂,
simp at h₂, simp [h₂],
exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ },
{ simp at h,
cases c with c; change some _ = _ at h₂;
simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩,
{ exact h },
{ exact add_le_add_left h _ } } }
end
end with_zero
namespace with_top
section has_one
variables [has_one α]
@[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩
@[simp, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl
@[simp, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 :=
coe_eq_coe
@[simp, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 :=
trans eq_comm coe_eq_one
attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe
@[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) .
@[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ .
end has_one
instance [has_add α] : has_add (with_top α) :=
⟨λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b))⟩
local attribute [semireducible] with_zero
instance [add_semigroup α] : add_semigroup (with_top α) :=
{ add := (+),
..(infer_instance : add_semigroup (additive (with_zero (multiplicative α)))) }
@[norm_cast] lemma coe_add [has_add α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl
@[norm_cast] lemma coe_bit0 [has_add α] {a : α} : ((bit0 a : α) : with_top α) = bit0 a := rfl
@[norm_cast]
lemma coe_bit1 [has_add α] [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl
@[simp] lemma add_top [has_add α] : ∀{a : with_top α}, a + ⊤ = ⊤
| none := rfl
| (some a) := rfl
@[simp] lemma top_add [has_add α] {a : with_top α} : ⊤ + a = ⊤ := rfl
lemma add_eq_top [has_add α] {a b : with_top α} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ :=
by cases a; cases b; simp [none_eq_top, some_eq_coe, ←with_top.coe_add, ←with_zero.coe_add]
lemma add_lt_top [has_add α] [partial_order α] {a b : with_top α} : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ :=
by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib]
lemma add_eq_coe [has_add α] : ∀ {a b : with_top α} {c : α},
a + b = c ↔ ∃ (a' b' : α), ↑a' = a ∧ ↑b' = b ∧ a' + b' = c
| none b c := by simp [none_eq_top]
| (some a) none c := by simp [none_eq_top]
| (some a) (some b) c :=
by simp only [some_eq_coe, ← coe_add, coe_eq_coe, exists_and_distrib_left, exists_eq_left]
instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) :=
{ ..@additive.add_comm_semigroup _ $
@with_zero.comm_semigroup (multiplicative α) _ }
instance [add_monoid α] : add_monoid (with_top α) :=
{ zero := some 0,
add := (+),
..@additive.add_monoid _ $ @monoid_with_zero.to_monoid _ $
@with_zero.monoid_with_zero (multiplicative α) _ }
instance [add_comm_monoid α] : add_comm_monoid (with_top α) :=
{ zero := 0,
add := (+),
..@additive.add_comm_monoid _ $ @comm_monoid_with_zero.to_comm_monoid _ $
@with_zero.comm_monoid_with_zero (multiplicative α) _ }
instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) :=
{ add_le_add_left :=
begin
rintros a b h (_|c), { simp [none_eq_top] },
rcases b with (_|b), { simp [none_eq_top] },
rcases le_coe_iff.1 h with ⟨a, rfl, h⟩,
simp only [some_eq_coe, ← coe_add, coe_le_coe] at h ⊢,
exact add_le_add_left h c
end,
lt_of_add_lt_add_left :=
begin
intros a b c h,
rcases lt_iff_exists_coe.1 h with ⟨ab, hab, hlt⟩,
rcases add_eq_coe.1 hab with ⟨a, b, rfl, rfl, rfl⟩,
rw coe_lt_iff,
rintro c rfl,
exact lt_of_add_lt_add_left (coe_lt_coe.1 hlt)
end,
..with_top.partial_order, ..with_top.add_comm_monoid }
instance [linear_ordered_add_comm_monoid α] :
linear_ordered_add_comm_monoid_with_top (with_top α) :=
{ top_add' := λ x, with_top.top_add,
..with_top.order_top,
..with_top.linear_order,
..with_top.ordered_add_comm_monoid,
..option.nontrivial }
/-- Coercion from `α` to `with_top α` as an `add_monoid_hom`. -/
def coe_add_hom [add_monoid α] : α →+ with_top α :=
⟨coe, rfl, λ _ _, rfl⟩
@[simp] lemma coe_coe_add_hom [add_monoid α] : ⇑(coe_add_hom : α →+ with_top α) = coe := rfl
@[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ :=
coe_lt_top 0
@[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) :
(0 : with_top α) < a ↔ 0 < a :=
coe_lt_coe
end with_top
namespace with_bot
instance [has_zero α] : has_zero (with_bot α) := with_top.has_zero
instance [has_one α] : has_one (with_bot α) := with_top.has_one
instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup
instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup
instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid
instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid
instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) :=
begin
suffices, refine {
add_le_add_left := this,
..with_bot.partial_order,
..with_bot.add_comm_monoid, ..},
{ intros a b c h,
have h' := h,
rw lt_iff_le_not_le at h' ⊢,
refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩,
cases h₂, cases a with a,
{ exact (not_le_of_lt h).elim bot_le },
cases c with c,
{ exact (not_le_of_lt h).elim bot_le },
{ exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $
with_bot.some_lt_some.1 h)⟩ } },
{ intros a b h c ca h₂,
cases c with c, {cases h₂},
cases a with a; cases h₂,
cases b with b, {cases le_antisymm h bot_le},
simp at h,
exact ⟨_, rfl, add_le_add_left h _⟩, }
end
instance [linear_ordered_add_comm_monoid α] : linear_ordered_add_comm_monoid (with_bot α) :=
{ ..with_bot.linear_order,
..with_bot.ordered_add_comm_monoid }
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_zero [has_zero α] : ((0 : α) : with_bot α) = 0 := rfl
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_eq_zero {α : Type*}
[add_monoid α] {a : α} : (a : with_bot α) = 0 ↔ a = 0 :=
by norm_cast
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := by norm_cast
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_bit0 [add_semigroup α] {a : α} : ((bit0 a : α) : with_bot α) = bit0 a :=
by norm_cast
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_bit1 [add_semigroup α] [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a :=
by norm_cast
@[simp] lemma bot_add [add_semigroup α] (a : with_bot α) : ⊥ + a = ⊥ := rfl
@[simp] lemma add_bot [add_semigroup α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl
@[simp] lemma add_eq_bot [add_semigroup α] {m n : with_bot α} :
m + n = ⊥ ↔ m = ⊥ ∨ n = ⊥ :=
with_top.add_eq_top
end with_bot
/-- A canonically ordered additive monoid is an ordered commutative additive monoid
in which the ordering coincides with the subtractibility relation,
which is to say, `a ≤ b` iff there exists `c` with `b = a + c`.
This is satisfied by the natural numbers, for example, but not
the integers or other nontrivial `ordered_add_comm_group`s. -/
@[protect_proj, ancestor ordered_add_comm_monoid order_bot]
class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, order_bot α :=
(le_iff_exists_add : ∀ a b : α, a ≤ b ↔ ∃ c, b = a + c)
/-- A canonically ordered monoid is an ordered commutative monoid
in which the ordering coincides with the divisibility relation,
which is to say, `a ≤ b` iff there exists `c` with `b = a * c`.
Examples seem rare; it seems more likely that the `order_dual`
of a naturally-occurring lattice satisfies this than the lattice
itself (for example, dual of the lattice of ideals of a PID or
Dedekind domain satisfy this; collections of all things ≤ 1 seem to
be more natural that collections of all things ≥ 1).
-/
@[protect_proj, ancestor ordered_comm_monoid order_bot, to_additive]
class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α, order_bot α :=
(le_iff_exists_mul : ∀ a b : α, a ≤ b ↔ ∃ c, b = a * c)
section canonically_ordered_monoid
variables [canonically_ordered_monoid α] {a b c d : α}
@[to_additive]
lemma le_iff_exists_mul : a ≤ b ↔ ∃c, b = a * c :=
canonically_ordered_monoid.le_iff_exists_mul a b
@[to_additive]
lemma self_le_mul_right (a b : α) : a ≤ a * b :=
le_iff_exists_mul.mpr ⟨b, rfl⟩
@[to_additive]
lemma self_le_mul_left (a b : α) : a ≤ b * a :=
by { rw [mul_comm], exact self_le_mul_right a b }
@[simp, to_additive zero_le] lemma one_le (a : α) : 1 ≤ a :=
le_iff_exists_mul.mpr ⟨a, (one_mul _).symm⟩
@[simp, to_additive] lemma bot_eq_one : (⊥ : α) = 1 :=
le_antisymm bot_le (one_le ⊥)
@[simp, to_additive] lemma mul_eq_one_iff : a * b = 1 ↔ a = 1 ∧ b = 1 :=
mul_eq_one_iff' (one_le _) (one_le _)
@[simp, to_additive] lemma le_one_iff_eq_one : a ≤ 1 ↔ a = 1 :=
iff.intro
(assume h, le_antisymm h (one_le a))
(assume h, h ▸ le_refl a)
@[to_additive] lemma one_lt_iff_ne_one : 1 < a ↔ a ≠ 1 :=
iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (one_le _) hne.symm
@[to_additive] lemma exists_pos_mul_of_lt (h : a < b) : ∃ c > 1, a * c = b :=
begin
obtain ⟨c, hc⟩ := le_iff_exists_mul.1 h.le,
refine ⟨c, one_lt_iff_ne_one.2 _, hc.symm⟩,
rintro rfl,
simpa [hc, lt_irrefl] using h
end
@[to_additive] lemma le_mul_left (h : a ≤ c) : a ≤ b * c :=
calc a = 1 * a : by simp
... ≤ b * c : mul_le_mul' (one_le _) h
@[to_additive] lemma le_mul_self : a ≤ b * a :=
le_mul_left (le_refl a)
@[to_additive] lemma le_mul_right (h : a ≤ b) : a ≤ b * c :=
calc a = a * 1 : by simp
... ≤ b * c : mul_le_mul' h (one_le _)
@[to_additive] lemma le_self_mul : a ≤ a * c :=
le_mul_right (le_refl a)
@[to_additive]
lemma lt_iff_exists_mul [covariant_class α α (*) (<)] : a < b ↔ ∃ c > 1, b = a * c :=
begin
simp_rw [lt_iff_le_and_ne, and_comm, le_iff_exists_mul, ← exists_and_distrib_left, exists_prop],
apply exists_congr, intro c,
rw [and.congr_left_iff, gt_iff_lt], rintro rfl,
split,
{ rw [one_lt_iff_ne_one], apply mt, rintro rfl, rw [mul_one] },
{ rw [← (self_le_mul_right a c).lt_iff_ne], apply lt_mul_of_one_lt_right' }
end
local attribute [semireducible] with_zero
-- This instance looks absurd: a monoid already has a zero
/-- Adding a new zero to a canonically ordered additive monoid produces another one. -/
instance with_zero.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] :
canonically_ordered_add_monoid (with_zero α) :=
{ le_iff_exists_add := λ a b, begin
cases a with a,
{ exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ },
cases b with b,
{ exact iff_of_false
(mt (le_antisymm bot_le) (by simp))
(λ ⟨c, h⟩, by cases c; cases h) },
{ simp [le_iff_exists_add, -add_comm],
split; intro h; rcases h with ⟨c, h⟩,
{ exact ⟨some c, congr_arg some h⟩ },
{ cases c; cases h,
{ exact ⟨_, (add_zero _).symm⟩ },
{ exact ⟨_, rfl⟩ } } }
end,
bot := 0,
bot_le := assume a a' h, option.no_confusion h,
.. with_zero.ordered_add_comm_monoid zero_le }
instance with_top.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] :
canonically_ordered_add_monoid (with_top α) :=
{ le_iff_exists_add := assume a b,
match a, b with
| a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl
| (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c,
begin
simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm],
split,
{ rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast },
{ exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end }
end
| none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp
end,
.. with_top.order_bot,
.. with_top.ordered_add_comm_monoid }
@[priority 100, to_additive]
instance canonically_ordered_monoid.has_exists_mul_of_le (α : Type u)
[canonically_ordered_monoid α] : has_exists_mul_of_le α :=
{ exists_mul_of_le := λ a b hab, le_iff_exists_mul.mp hab }
end canonically_ordered_monoid
lemma pos_of_gt {M : Type*} [canonically_ordered_add_monoid M] {n m : M} (h : n < m) : 0 < m :=
lt_of_le_of_lt (zero_le _) h
/-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid
whose ordering is a linear order. -/
@[protect_proj, ancestor canonically_ordered_add_monoid linear_order]
class canonically_linear_ordered_add_monoid (α : Type*)
extends canonically_ordered_add_monoid α, linear_order α
/-- A canonically linear-ordered monoid is a canonically ordered monoid
whose ordering is a linear order. -/
@[protect_proj, ancestor canonically_ordered_monoid linear_order, to_additive]
class canonically_linear_ordered_monoid (α : Type*)
extends canonically_ordered_monoid α, linear_order α
section canonically_linear_ordered_monoid
variables [canonically_linear_ordered_monoid α]
@[priority 100, to_additive] -- see Note [lower instance priority]
instance canonically_linear_ordered_monoid.semilattice_sup_bot : semilattice_sup_bot α :=
{ ..lattice_of_linear_order, ..canonically_ordered_monoid.to_order_bot α }
instance with_top.canonically_linear_ordered_add_monoid
(α : Type*) [canonically_linear_ordered_add_monoid α] :
canonically_linear_ordered_add_monoid (with_top α) :=
{ .. (infer_instance : canonically_ordered_add_monoid (with_top α)),
.. (infer_instance : linear_order (with_top α)) }
@[to_additive]
lemma min_mul_distrib (a b c : α) : min a (b * c) = min a (min a b * min a c) :=
begin
cases le_total a b with hb hb,
{ simp [hb, le_mul_right] },
{ cases le_total a c with hc hc,
{ simp [hc, le_mul_left] },
{ simp [hb, hc] } }
end
@[to_additive]
lemma min_mul_distrib' (a b c : α) : min (a * b) c = min (min a c * min b c) c :=
by simpa [min_comm _ c] using min_mul_distrib c a b
@[simp, to_additive]
lemma one_min (a : α) : min 1 a = 1 :=
min_eq_left (one_le a)
@[simp, to_additive]
lemma min_one (a : α) : min a 1 = 1 :=
min_eq_right (one_le a)
end canonically_linear_ordered_monoid
/-- An ordered cancellative additive commutative monoid
is an additive commutative monoid with a partial order,
in which addition is cancellative and monotone. -/
@[protect_proj, ancestor add_cancel_comm_monoid partial_order]
class ordered_cancel_add_comm_monoid (α : Type u)
extends add_cancel_comm_monoid α, partial_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
(le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c)
/-- An ordered cancellative commutative monoid
is a commutative monoid with a partial order,
in which multiplication is cancellative and monotone. -/
@[protect_proj, ancestor cancel_comm_monoid partial_order, to_additive]
class ordered_cancel_comm_monoid (α : Type u)
extends cancel_comm_monoid α, partial_order α :=
(mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b)
(le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c)
section ordered_cancel_comm_monoid
variables [ordered_cancel_comm_monoid α] {a b c d : α}
@[priority 100, to_additive] -- see Note [lower instance priority]
instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid α :=
{ lt_of_mul_lt_mul_left := λ a b c h, lt_of_le_not_le
(ordered_cancel_comm_monoid.le_of_mul_le_mul_left a b c h.le) $
mt (λ h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h),
..‹ordered_cancel_comm_monoid α› }
/-- Pullback an `ordered_cancel_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.ordered_cancel_add_comm_monoid
"Pullback an `ordered_cancel_add_comm_monoid` under an injective map."]
def function.injective.ordered_cancel_comm_monoid {β : Type*}
[has_one β] [has_mul β]
(f : β → α) (hf : function.injective f) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
ordered_cancel_comm_monoid β :=
{ le_of_mul_le_mul_left := λ a b c (bc : f (a * b) ≤ f (a * c)),
(mul_le_mul_iff_left (f a)).mp (by rwa [← mul, ← mul]),
..hf.left_cancel_semigroup f mul,
..hf.ordered_comm_monoid f one mul }
end ordered_cancel_comm_monoid
section ordered_cancel_add_comm_monoid
variable [ordered_cancel_add_comm_monoid α]
lemma with_top.add_lt_add_iff_left :
∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b)
| none := assume b c h, (lt_irrefl ⊤ h).elim
| (some a) :=
begin
assume b c h,
cases b; cases c;
simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe],
{ norm_cast, exact with_top.coe_lt_top _ },
{ norm_cast, exact add_lt_add_iff_left _ }
end
lemma with_bot.add_lt_add_iff_left :
∀{a b c : with_bot α}, ⊥ < a → (a + c < a + b ↔ c < b)
| none := assume b c h, (lt_irrefl ⊥ h).elim
| (some a) :=
begin
assume b c h,
cases b; cases c;
simp [with_bot.none_eq_bot, with_bot.some_eq_coe, with_bot.bot_lt_coe, with_bot.coe_lt_coe],
{ norm_cast, exact with_bot.bot_lt_coe _ },
{ norm_cast, exact add_lt_add_iff_left _ }
end
local attribute [semireducible] with_zero
lemma with_top.add_lt_add_iff_right
{a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) :=
by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c
lemma with_bot.add_lt_add_iff_right
{a b c : with_bot α} : ⊥ < a → (c + a < b + a ↔ c < b) :=
by simpa [add_comm] using @with_bot.add_lt_add_iff_left _ _ a b c
end ordered_cancel_add_comm_monoid
/-! Some lemmas about types that have an ordering and a binary operation, with no
rules relating them. -/
@[to_additive]
lemma fn_min_mul_fn_max {β} [linear_order α] [comm_semigroup β] (f : α → β) (n m : α) :
f (min n m) * f (max n m) = f n * f m :=
by { cases le_total n m with h h; simp [h, mul_comm] }
@[to_additive]
lemma min_mul_max [linear_order α] [comm_semigroup α] (n m : α) :
min n m * max n m = n * m :=
fn_min_mul_fn_max id n m
/-- A linearly ordered cancellative additive commutative monoid
is an additive commutative monoid with a decidable linear order
in which addition is cancellative and monotone. -/
@[protect_proj, ancestor ordered_cancel_add_comm_monoid linear_ordered_add_comm_monoid]
class linear_ordered_cancel_add_comm_monoid (α : Type u)
extends ordered_cancel_add_comm_monoid α, linear_ordered_add_comm_monoid α
/-- A linearly ordered cancellative commutative monoid
is a commutative monoid with a linear order
in which multiplication is cancellative and monotone. -/
@[protect_proj, ancestor ordered_cancel_comm_monoid linear_ordered_comm_monoid, to_additive]
class linear_ordered_cancel_comm_monoid (α : Type u)
extends ordered_cancel_comm_monoid α, linear_ordered_comm_monoid α
section covariant_class_mul_le
variables [linear_order α]
section has_mul
variable [has_mul α]
section left
variable [covariant_class α α (*) (≤)]
@[to_additive] lemma min_mul_mul_left (a b c : α) : min (a * b) (a * c) = a * min b c :=
(monotone_id.const_mul' a).map_min.symm
@[to_additive]
lemma max_mul_mul_left (a b c : α) : max (a * b) (a * c) = a * max b c :=
(monotone_id.const_mul' a).map_max.symm
end left
section right
variable [covariant_class α α (function.swap (*)) (≤)]
@[to_additive]
lemma min_mul_mul_right (a b c : α) : min (a * c) (b * c) = min a b * c :=
(monotone_id.mul_const' c).map_min.symm
@[to_additive]
lemma max_mul_mul_right (a b c : α) : max (a * c) (b * c) = max a b * c :=
(monotone_id.mul_const' c).map_max.symm
end right
end has_mul
variable [monoid α]
@[to_additive]
lemma min_le_mul_of_one_le_right [covariant_class α α (*) (≤)] {a b : α} (hb : 1 ≤ b) :
min a b ≤ a * b :=
min_le_iff.2 $ or.inl $ le_mul_of_one_le_right' hb
@[to_additive]
lemma min_le_mul_of_one_le_left [covariant_class α α (function.swap (*)) (≤)] {a b : α}
(ha : 1 ≤ a) : min a b ≤ a * b :=
min_le_iff.2 $ or.inr $ le_mul_of_one_le_left' ha
@[to_additive]
lemma max_le_mul_of_one_le [covariant_class α α (*) (≤)]
[covariant_class α α (function.swap (*)) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) :
max a b ≤ a * b :=
max_le_iff.2 ⟨le_mul_of_one_le_right' hb, le_mul_of_one_le_left' ha⟩
end covariant_class_mul_le
section linear_ordered_cancel_comm_monoid
variables [linear_ordered_cancel_comm_monoid α]
/-- Pullback a `linear_ordered_cancel_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.linear_ordered_cancel_add_comm_monoid
"Pullback a `linear_ordered_cancel_add_comm_monoid` under an injective map."]
def function.injective.linear_ordered_cancel_comm_monoid {β : Type*}
[has_one β] [has_mul β]
(f : β → α) (hf : function.injective f) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
linear_ordered_cancel_comm_monoid β :=
{ ..hf.linear_ordered_comm_monoid f one mul,
..hf.ordered_cancel_comm_monoid f one mul }
end linear_ordered_cancel_comm_monoid
namespace order_dual
@[to_additive] instance [h : has_mul α] : has_mul (order_dual α) := h
@[to_additive] instance [h : has_one α] : has_one (order_dual α) := h
@[to_additive] instance [h : monoid α] : monoid (order_dual α) := h
@[to_additive] instance [h : comm_monoid α] : comm_monoid (order_dual α) := h
@[to_additive] instance [h : cancel_comm_monoid α] : cancel_comm_monoid (order_dual α) := h
@[to_additive]
instance contravariant_class_mul_le [has_le α] [has_mul α] [c : contravariant_class α α (*) (≤)] :
contravariant_class (order_dual α) (order_dual α) (*) (≤) :=
⟨c.1.flip⟩
@[to_additive]
instance covariant_class_mul_le [has_le α] [has_mul α] [c : covariant_class α α (*) (≤)] :
covariant_class (order_dual α) (order_dual α) (*) (≤) :=
⟨c.1.flip⟩
@[to_additive] instance contravariant_class_swap_mul_le [has_le α] [has_mul α]
[c : contravariant_class α α (function.swap (*)) (≤)] :
contravariant_class (order_dual α) (order_dual α) (function.swap (*)) (≤) :=
⟨c.1.flip⟩
@[to_additive]
instance covariant_class_swap_mul_le [has_le α] [has_mul α]
[c : covariant_class α α (function.swap (*)) (≤)] :
covariant_class (order_dual α) (order_dual α) (function.swap (*)) (≤) :=
⟨c.1.flip⟩
@[to_additive]
instance contravariant_class_mul_lt [has_lt α] [has_mul α] [c : contravariant_class α α (*) (<)] :
contravariant_class (order_dual α) (order_dual α) (*) (<) :=
⟨c.1.flip⟩
@[to_additive]
instance covariant_class_mul_lt [has_lt α] [has_mul α] [c : covariant_class α α (*) (<)] :
covariant_class (order_dual α) (order_dual α) (*) (<) :=
⟨c.1.flip⟩
@[to_additive] instance contravariant_class_swap_mul_lt [has_lt α] [has_mul α]
[c : contravariant_class α α (function.swap (*)) (<)] :
contravariant_class (order_dual α) (order_dual α) (function.swap (*)) (<) :=
⟨c.1.flip⟩
@[to_additive]
instance covariant_class_swap_mul_lt [has_lt α] [has_mul α]
[c : covariant_class α α (function.swap (*)) (<)] :
covariant_class (order_dual α) (order_dual α) (function.swap (*)) (<) :=
⟨c.1.flip⟩
@[to_additive]
instance [ordered_comm_monoid α] : ordered_comm_monoid (order_dual α) :=
{ mul_le_mul_left := λ a b h c, mul_le_mul_left' h c,
lt_of_mul_lt_mul_left := λ a b c, lt_of_mul_lt_mul_left',
.. order_dual.partial_order α,
.. order_dual.comm_monoid }
@[to_additive ordered_cancel_add_comm_monoid.to_contravariant_class]
instance ordered_cancel_comm_monoid.to_contravariant_class [ordered_cancel_comm_monoid α] :
contravariant_class (order_dual α) (order_dual α) has_mul.mul has_le.le :=
{ elim := λ a b c bc, (ordered_cancel_comm_monoid.le_of_mul_le_mul_left a c b (dual_le.mp bc)) }
@[to_additive]
instance [ordered_cancel_comm_monoid α] : ordered_cancel_comm_monoid (order_dual α) :=
{ le_of_mul_le_mul_left := λ a b c : α, le_of_mul_le_mul_left',
.. order_dual.ordered_comm_monoid, .. order_dual.cancel_comm_monoid }
@[to_additive]
instance [linear_ordered_cancel_comm_monoid α] :
linear_ordered_cancel_comm_monoid (order_dual α) :=
{ .. order_dual.linear_order α,
.. order_dual.ordered_cancel_comm_monoid }
@[to_additive]
instance [linear_ordered_comm_monoid α] :
linear_ordered_comm_monoid (order_dual α) :=
{ .. order_dual.linear_order α,
.. order_dual.ordered_comm_monoid }
end order_dual
namespace prod
variables {M N : Type*}
@[to_additive]
instance [ordered_cancel_comm_monoid M] [ordered_cancel_comm_monoid N] :
ordered_cancel_comm_monoid (M × N) :=
{ mul_le_mul_left := λ a b h c, ⟨mul_le_mul_left' h.1 _, mul_le_mul_left' h.2 _⟩,
le_of_mul_le_mul_left := λ a b c h, ⟨le_of_mul_le_mul_left' h.1, le_of_mul_le_mul_left' h.2⟩,
.. prod.cancel_comm_monoid, .. prod.partial_order M N }
end prod
section type_tags
instance : Π [preorder α], preorder (multiplicative α) := id
instance : Π [preorder α], preorder (additive α) := id
instance : Π [partial_order α], partial_order (multiplicative α) := id
instance : Π [partial_order α], partial_order (additive α) := id
instance : Π [linear_order α], linear_order (multiplicative α) := id
instance : Π [linear_order α], linear_order (additive α) := id
instance [ordered_add_comm_monoid α] : ordered_comm_monoid (multiplicative α) :=
{ mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left α _,
lt_of_mul_lt_mul_left := @ordered_add_comm_monoid.lt_of_add_lt_add_left α _,
..multiplicative.partial_order,
..multiplicative.comm_monoid }
instance [ordered_comm_monoid α] : ordered_add_comm_monoid (additive α) :=
{ add_le_add_left := @ordered_comm_monoid.mul_le_mul_left α _,
lt_of_add_lt_add_left := @ordered_comm_monoid.lt_of_mul_lt_mul_left α _,
..additive.partial_order,
..additive.add_comm_monoid }
instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_comm_monoid (multiplicative α) :=
{ le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left α _,
..multiplicative.left_cancel_semigroup,
..multiplicative.ordered_comm_monoid }
instance [ordered_cancel_comm_monoid α] : ordered_cancel_add_comm_monoid (additive α) :=
{ le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left α _,
..additive.add_left_cancel_semigroup,
..additive.ordered_add_comm_monoid }
instance [linear_ordered_add_comm_monoid α] : linear_ordered_comm_monoid (multiplicative α) :=
{ ..multiplicative.linear_order,
..multiplicative.ordered_comm_monoid }
instance [linear_ordered_comm_monoid α] : linear_ordered_add_comm_monoid (additive α) :=
{ ..additive.linear_order,
..additive.ordered_add_comm_monoid }
end type_tags
|
9729b438f8c60859fb5c56109c1cd45e21621425 | e4a7c8ab8b68ca0e53d2c21397320ea590fa01c6 | /src/data/polya/field/main.lean | 83ab7b6349a7e250ed8d7382a85e8964a65c4a7d | [] | no_license | lean-forward/field | 3ff5dc5f43de40f35481b375f8c871cd0a07c766 | 7e2127ad485aec25e58a1b9c82a6bb74a599467a | refs/heads/master | 1,590,947,010,909 | 1,563,811,881,000 | 1,563,811,881,000 | 190,415,651 | 1 | 0 | null | 1,563,643,371,000 | 1,559,746,688,000 | Lean | UTF-8 | Lean | false | false | 6,941 | lean | import .sform .pform .norm
namespace polya.field
--namespace nterm
--
--variables {α : Type} [discrete_field α]
--variables {γ : Type} [const_space γ]
--variables [morph γ α] {ρ : dict α}
--
--instance coe_atom : has_coe num (nterm γ) := ⟨atom⟩
--instance coe_const : has_coe γ (nterm γ) := ⟨const⟩
--
--instance : has_zero (nterm γ) := ⟨const 0⟩
--instance : has_one (nterm γ) := ⟨const 1⟩
--
--instance : has_add (nterm γ) := ⟨sform.add⟩
--instance : has_mul (nterm γ) := ⟨pform.mul⟩
--instance : has_pow (nterm γ) ℤ := ⟨λ (x : nterm γ) (n : ℤ), pow_mul (n : znum) x⟩
--
--instance : has_neg (nterm γ) := ⟨scale (-1)⟩
--instance : has_sub (nterm γ) := ⟨λ x y, x + -y⟩
--instance : has_inv (nterm γ) := ⟨λ x, x ^ (-1 : ℤ)⟩
--instance : has_div (nterm γ) := ⟨λ x y, x * y⁻¹⟩
--
--instance pow_nat : has_pow (nterm γ) ℕ := ⟨λ (x : nterm γ) (n : ℕ), x ^ (n : ℤ)⟩
--
--section
--
--variables {x y : nterm γ} {i : num} {n : ℤ} {c : γ}
--
--@[simp] theorem eval_zero : eval ρ (0 : nterm γ) = 0 := by apply morph.morph_zero'
--@[simp] theorem eval_one : eval ρ (1 : nterm γ) = 1 := by apply morph.morph_one'
--@[simp] theorem eval_const : eval ρ (const c) = c := rfl
--@[simp] theorem eval_atom : eval ρ (atom i : nterm γ) = ρ.val i := rfl
--
--@[simp] theorem eval_add : eval ρ (x + y) = eval ρ x + eval ρ y := sform.eval_add
--@[simp] theorem eval_mul : eval ρ (x * y) = eval ρ x * eval ρ y := pform.eval_mul
--@[simp] theorem eval_pow : eval ρ (x ^ n) = eval ρ x ^ n := by { convert eval_pow_mul, rw znum.to_of_int }
--
--@[simp] theorem eval_neg : eval ρ (-x) = - x.eval ρ := by { refine eq.trans eval_scale _, rw [morph.morph_neg, morph.morph_one', mul_neg_one] }
--@[simp] theorem eval_sub : eval ρ (x - y) = x.eval ρ - y.eval ρ := by { refine eq.trans eval_add _, rw [eval_neg, sub_eq_add_neg] }
--@[simp] theorem eval_inv : eval ρ (x⁻¹) = (x.eval ρ)⁻¹ := by { rw [← fpow_inv, ← eval_pow], refl }
--@[simp] theorem eval_div : eval ρ (x / y) = x.eval ρ / y.eval ρ := by { rw [division_def, ← eval_inv, ← eval_mul], refl }
--
--@[simp] theorem eval_pow_nat {n : ℕ} : eval ρ (x ^ n) = eval ρ x ^ n := eval_pow
--
--end
--
--end nterm
@[derive decidable_eq, derive has_reflect]
inductive term : Type
| atom : num → term
| add : term → term → term
| sub : term → term → term
| mul : term → term → term
| div : term → term → term
| neg : term → term
| inv : term → term
| numeral : ℕ → term
| pow_nat : term → ℕ → term
| pow_int : term → ℤ → term
namespace term
variables {α : Type} [discrete_field α]
variables {γ : Type} [const_space γ]
variables [morph γ α] {ρ : dict α}
def eval (ρ : dict α) : term → α
| (atom i) := ρ.val i
| (add x y) := eval x + eval y
| (sub x y) := eval x - eval y
| (mul x y) := eval x * eval y
| (div x y) := (eval x) / (eval y)
| (neg x) := - eval x
| (inv x) := (eval x)⁻¹
| (numeral n) := (n : α)
| (pow_nat x n) := eval x ^ n
| (pow_int x n) := eval x ^ n
def to_nterm : term → nterm γ
| (atom i) := ↑i
| (add x y) := to_nterm x + to_nterm y
| (sub x y) := to_nterm x - to_nterm y
| (mul x y) := to_nterm x * to_nterm y
| (div x y) := to_nterm x / to_nterm y
| (neg x) := - to_nterm x
| (inv x) := (to_nterm x)⁻¹
| (numeral n) := ↑(n : γ)
| (pow_nat x n) := to_nterm x ^ n
| (pow_int x n) := to_nterm x ^ n
theorem correctness {x : term} :
nterm.eval ρ (@to_nterm γ _ x) = eval ρ x :=
begin
induction x with
i --atom
x y ihx ihy --add
x y ihx ihy --sub
x y ihx ihy --mul
x y ihx ihy --div
x ihx --neg
x ihx --inv
n --numeral
x n ihx --pow_nat
x n ihx, --pow_int
repeat { unfold to_nterm, unfold eval },
repeat { simp [nterm.eval] },
repeat { simp [nterm.eval, ihx] },
repeat { simp [nterm.eval, ihx, ihy] },
--{ rw [fpow_inv, division_def] },
--{ rw fpow_inv }
end
end term
def norm (γ : Type) [const_space γ] (x : term) : nterm γ :=
nterm.norm $ @term.to_nterm γ _ x
def norm_hyps (γ : Type) [const_space γ] (x : term) : list (nterm γ) :=
nterm.norm_hyps $ @term.to_nterm γ _ x
variables {γ : Type} [const_space γ]
variables {α : Type} [discrete_field α]
variables [morph γ α] {ρ : dict α}
theorem correctness {x : term} {ρ : dict α} :
(∀ t ∈ norm_hyps γ x, nterm.eval ρ t ≠ 0) →
term.eval ρ x = nterm.eval ρ (norm γ x) :=
begin
intro H,
unfold norm,
apply eq.symm, apply eq.trans,
{ apply nterm.correctness, unfold nterm.nonzero,
intros t ht, apply H, exact ht },
{ apply term.correctness }
end
open nterm
def aux1 (t1 t2 : nterm γ) : nterm γ × nterm γ × γ :=
if t2.coeff = 0 then
(t1.term, 0, t1.coeff)
else
(t2.term, t1.scale (t2.coeff⁻¹), -t2.coeff)
def aux2 (t1 t2 : nterm γ) : nterm γ × nterm γ × γ :=
if t2.term < t1.term then
aux1 (t2.scale (-1)) (t1.scale (-1))
else
aux1 t1 t2
theorem eval_aux1 {t1 t2 t3 t4 : nterm γ} {c : γ} :
(t3, t4, c) = aux1 t1 t2 →
eval ρ t1 - eval ρ t2 = (eval ρ t3 - eval ρ t4) * c :=
begin
unfold aux1,
by_cases h1 : t2.coeff = 0,
{ rw if_pos h1, intro h2,
rw [prod.mk.inj_iff] at h2, cases h2 with h2 h3,
rw [prod.mk.inj_iff] at h3, cases h3 with h3 h4,
rw [eval_term_coeff t1, eval_term_coeff t2, h1, h2, h3, h4],
simp [morph.morph_neg] },
{ rw if_neg h1, intro h2,
rw [prod.mk.inj_iff] at h2, cases h2 with h2 h3,
rw [prod.mk.inj_iff] at h3, cases h3 with h3 h4,
rw [h2, h3, h4],
rw [morph.morph_neg, mul_neg_eq_neg_mul_symm, neg_mul_eq_neg_mul, neg_sub, sub_mul],
rw [← eval_term_coeff], congr' 1,
rw [eval_scale, mul_assoc, ← morph.morph_mul, inv_mul_cancel],
rw [morph.morph_one, mul_one], --simp
exact h1 }
end
theorem eval_aux2 {t1 t2 t3 t4 : nterm γ} {c : γ} :
(t3, t4, c) = aux2 t1 t2 →
eval ρ t1 - eval ρ t2 = (eval ρ t3 - eval ρ t4) * c :=
begin
unfold aux2,
by_cases h1 : t2.term < t1.term,
{ rw if_pos h1, intro h2,
have : eval ρ (t2.scale (-1)) - eval ρ (t1.scale (-1)) = (eval ρ t3 - eval ρ t4) * ↑c,
{ exact eval_aux1 h2 },
rw ← this, simp [morph.morph_neg] },
{ rw if_neg h1, intro h2, exact eval_aux1 h2 }
end
def norm2 (γ : Type) [const_space γ] (t1 t2 : term) : nterm γ × nterm γ × γ :=
aux2 (norm γ t1) (norm γ t2)
theorem eval_norm2 {t1 t2 : term} {nt1 nt2 : nterm γ} {c : γ} :
nonzero ρ (norm_hyps γ t1) →
nonzero ρ (norm_hyps γ t2) →
(nt1, nt2, c) = norm2 γ t1 t2 →
term.eval ρ t1 - term.eval ρ t2 =
(nterm.eval ρ nt1 - nterm.eval ρ nt2) * c :=
begin
unfold norm2,
intros h1 h2 h3,
apply eq.trans,
{ show _ = eval ρ (norm γ t1) - eval ρ (norm γ t2), rw [correctness h1, correctness h2] },
{ exact eval_aux2 h3 }
end
end polya.field |
4f9b6a66a128c2e1548147bea3d032ca3ad1f9dc | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /test/ext.lean | 390857100c547d934b724a09b114366161494f48 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 2,974 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic.ext
import tactic.solve_by_elim
import data.stream.basic
import data.finset.basic
@[ext] lemma unit.ext (x y : unit) : x = y :=
begin
cases x, cases y, refl
end
example : subsingleton unit :=
begin
split, intros, ext
end
example (x y : ℕ) : true :=
begin
have : x = y,
{ ext <|> admit },
have : x = y,
{ ext i <|> admit },
have : x = y,
{ ext : 1 <|> admit },
trivial
end
example (X Y : ℕ × ℕ) (h : X.1 = Y.1) (h : X.2 = Y.2) : X = Y :=
begin
ext; assumption
end
example (X Y : (ℕ → ℕ) × ℕ) (h : ∀ i, X.1 i = Y.1 i) (h : X.2 = Y.2) : X = Y :=
begin
ext x; solve_by_elim,
end
example (X Y : ℕ → ℕ × ℕ) (h : ∀ i, X i = Y i) : true :=
begin
have : X = Y,
{ ext i : 1,
guard_target X i = Y i,
admit },
have : X = Y,
{ ext i,
guard_target (X i).fst = (Y i).fst, admit,
guard_target (X i).snd = (Y i).snd, admit, },
have : X = Y,
{ ext : 1,
guard_target X x = Y x,
admit },
trivial,
end
example (s₀ s₁ : set ℕ) (h : s₁ = s₀) : s₀ = s₁ :=
by { ext1, guard_target x ∈ s₀ ↔ x ∈ s₁, simp * }
example (s₀ s₁ : stream ℕ) (h : s₁ = s₀) : s₀ = s₁ :=
by { ext1, guard_target s₀.nth n = s₁.nth n, simp * }
example (s₀ s₁ : ℤ → set (ℕ × ℕ))
(h : ∀ i a b, (a,b) ∈ s₀ i ↔ (a,b) ∈ s₁ i) : s₀ = s₁ :=
begin
ext i ⟨a,b⟩,
apply h
end
/- extensionality -/
example : true :=
begin
have : ∀ (s₀ s₁ : set ℤ), s₀ = s₁,
{ intros, ext1,
guard_target x ∈ s₀ ↔ x ∈ s₁,
admit },
have : ∀ (s₀ s₁ : finset ℕ), s₀ = s₁,
{ intros, ext1,
guard_target a ∈ s₀ ↔ a ∈ s₁,
admit },
have : ∀ (s₀ s₁ : multiset ℕ), s₀ = s₁,
{ intros, ext1,
guard_target multiset.count a s₀ = multiset.count a s₁,
admit },
have : ∀ (s₀ s₁ : list ℕ), s₀ = s₁,
{ intros, ext1,
guard_target list.nth s₀ n = list.nth s₁ n,
admit },
have : ∀ (s₀ s₁ : stream ℕ), s₀ = s₁,
{ intros, ext1,
guard_target stream.nth n s₀ = stream.nth n s₁,
admit },
have : ∀ n (s₀ s₁ : array n ℕ), s₀ = s₁,
{ intros, ext1,
guard_target array.read s₀ i = array.read s₁ i,
admit },
trivial
end
structure dependent_fields :=
(a : bool)
(v : if a then ℕ else ℤ)
@[ext] lemma df.ext (s t : dependent_fields) (h : s.a = t.a)
(w : (@eq.rec _ s.a (λ b, if b then ℕ else ℤ) s.v t.a h) = t.v) : s = t :=
begin
cases s, cases t,
dsimp at *,
congr,
exact h,
subst h,
simp,
simp at w,
exact w,
end
example (s : dependent_fields) : s = s :=
begin
tactic.ext1 [] {tactic.apply_cfg . new_goals := tactic.new_goals.all},
guard_target s.a = s.a,
refl,
refl,
end
@[ext] structure dumb (V : Type) := (val : V)
|
a18deb47995475ea85e2f5fd849495cb60461fff | 5ee26964f602030578ef0159d46145dd2e357ba5 | /src/for_mathlib/filter.lean | 1e63ede000cd7b359c1d364f8cd8c4db2510d3cc | [
"Apache-2.0"
] | permissive | fpvandoorn/lean-perfectoid-spaces | 569b4006fdfe491ca8b58dd817bb56138ada761f | 06cec51438b168837fc6e9268945735037fd1db6 | refs/heads/master | 1,590,154,571,918 | 1,557,685,392,000 | 1,557,685,392,000 | 186,363,547 | 0 | 0 | Apache-2.0 | 1,557,730,933,000 | 1,557,730,933,000 | null | UTF-8 | Lean | false | false | 1,523 | lean | import order.filter.basic
open filter set
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-
f
α → β
g ↓ ↓ h
γ → δ
i
-/
variables {f : α → β} {g : α → γ} {h : β → δ} {i : γ → δ} (H : h ∘ f = i ∘ g)
include H
lemma filter.map_comm (F : filter α) : map h (map f F) = map i (map g F) :=
by rw [filter.map_map, H, ← filter.map_map]
lemma filter.comap_comm (G : filter δ) : comap f (comap h G) = comap g (comap i G) :=
by rw [filter.comap_comap_comp, H, ← filter.comap_comap_comp]
omit H
variables (φ : α → β)
lemma tendsto_pure (F : filter α) (b : β) : tendsto φ F (pure b) ↔ φ ⁻¹' {b} ∈ F :=
tendsto_principal
variables {G : filter β} {s : set α} {t : set β} {φ}
lemma mem_comap_sets_of_inj (h : ∀ a a', φ a = φ a' → a = a') :
s ∈ comap φ G ↔ ∃ t ∈ G, s = φ ⁻¹' t :=
begin
rw mem_comap_sets,
split ; rintros ⟨t, ht, hts⟩,
{ use t ∪ φ '' s,
split,
{ simp [mem_sets_of_superset ht] },
{ rw [preimage_union, preimage_image_eq _ h],
exact (union_eq_self_of_subset_left hts).symm } },
{ use [t, ht],
rwa hts }
end
lemma filter.inf_eq_bot_iff {α : Type*} (f g : filter α) : f ⊓ g = ⊥ ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ :=
by { rw [← empty_in_sets_eq_bot, mem_inf_sets], simp [subset_empty_iff] }
lemma filter.ne_bot_of_map {α : Type*} {β : Type*} {f : α → β} {F : filter α} (h : map f F ≠ ⊥) : F ≠ ⊥ :=
λ H, (H ▸ h : map f ⊥ ≠ ⊥) map_bot
|
b8a490d1b869c008518d8b9c209649010902ecea | 7056dcccc8ffc1e6f9f533f3fed8ef16ff9fcc1e | /src/Init/Lean/Compiler/IR/EmitC.lean | f0219f91201ee178def9846704f0ed46d8bc899b | [
"Apache-2.0"
] | permissive | graydon/lean4 | d73f60d0aa60e64e8d15674538bb5921aad5a4d1 | ec9f4b579dc6b4a20407d2735f8ad91de29bfdb5 | refs/heads/master | 1,650,641,753,817 | 1,587,651,832,000 | 1,587,733,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,464 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Control.Conditional
import Init.Lean.Runtime
import Init.Lean.Compiler.NameMangling
import Init.Lean.Compiler.ExportAttr
import Init.Lean.Compiler.InitAttr
import Init.Lean.Compiler.IR.CompilerM
import Init.Lean.Compiler.IR.EmitUtil
import Init.Lean.Compiler.IR.NormIds
import Init.Lean.Compiler.IR.SimpCase
import Init.Lean.Compiler.IR.Boxing
namespace Lean
namespace IR
open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName)
namespace EmitC
def leanMainFn := "_lean_main"
structure Context :=
(env : Environment)
(modName : Name)
(jpMap : JPParamsMap := {})
(mainFn : FunId := arbitrary _)
(mainParams : Array Param := #[])
abbrev M := ReaderT Context (EStateM String String)
def getEnv : M Environment := Context.env <$> read
def getModName : M Name := Context.modName <$> read
def getDecl (n : Name) : M Decl := do
env ← getEnv;
match findEnvDecl env n with
| some d => pure d
| none => throw ("unknown declaration '" ++ toString n ++ "'")
@[inline] def emit {α : Type} [HasToString α] (a : α) : M Unit :=
modify (fun out => out ++ toString a)
@[inline] def emitLn {α : Type} [HasToString α] (a : α) : M Unit :=
emit a *> emit "\n"
def emitLns {α : Type} [HasToString α] (as : List α) : M Unit :=
as.forM $ fun a => emitLn a
def argToCString (x : Arg) : String :=
match x with
| Arg.var x => toString x
| _ => "lean_box(0)"
def emitArg (x : Arg) : M Unit :=
emit (argToCString x)
def toCType : IRType → String
| IRType.float => "double"
| IRType.uint8 => "uint8_t"
| IRType.uint16 => "uint16_t"
| IRType.uint32 => "uint32_t"
| IRType.uint64 => "uint64_t"
| IRType.usize => "size_t"
| IRType.object => "lean_object*"
| IRType.tobject => "lean_object*"
| IRType.irrelevant => "lean_object*"
| IRType.struct _ _ => panic! "not implemented yet"
| IRType.union _ _ => panic! "not implemented yet"
def throwInvalidExportName {α : Type} (n : Name) : M α :=
throw ("invalid export name '" ++ toString n ++ "'")
def toCName (n : Name) : M String := do
env ← getEnv;
-- TODO: we should support simple export names only
match getExportNameFor env n with
| some (Name.str Name.anonymous s _) => pure s
| some _ => throwInvalidExportName n
| none => if n == `main then pure leanMainFn else pure n.mangle
def emitCName (n : Name) : M Unit :=
toCName n >>= emit
def toCInitName (n : Name) : M String := do
env ← getEnv;
-- TODO: we should support simple export names only
match getExportNameFor env n with
| some (Name.str Name.anonymous s _) => pure $ "_init_" ++ s
| some _ => throwInvalidExportName n
| none => pure ("_init_" ++ n.mangle)
def emitCInitName (n : Name) : M Unit :=
toCInitName n >>= emit
def emitFnDeclAux (decl : Decl) (cppBaseName : String) (addExternForConsts : Bool) : M Unit := do
let ps := decl.params;
env ← getEnv;
when (ps.isEmpty && addExternForConsts) (emit "extern ");
emit (toCType decl.resultType ++ " " ++ cppBaseName);
unless (ps.isEmpty) $ do {
emit "(";
-- We omit irrelevant parameters for extern constants
let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps;
if ps.size > closureMaxArgs && isBoxedName decl.name then
emit "lean_object**"
else
ps.size.forM $ fun i => do {
when (i > 0) (emit ", ");
emit (toCType (ps.get! i).ty)
};
emit ")"
};
emitLn ";"
def emitFnDecl (decl : Decl) (addExternForConsts : Bool) : M Unit := do
cppBaseName ← toCName decl.name;
emitFnDeclAux decl cppBaseName addExternForConsts
def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do
let cName := mkNameSimple cNameStr;
env ← getEnv;
let extC := isExternC env decl.name;
emitFnDeclAux decl cNameStr (!extC)
def emitFnDecls : M Unit := do
env ← getEnv;
let decls := getDecls env;
let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {};
let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {};
let usedDecls := usedDecls.toList;
usedDecls.forM $ fun n => do
decl ← getDecl n;
match getExternNameFor env `c decl.name with
| some cName => emitExternDeclAux decl cName
| none => emitFnDecl decl (!modDecls.contains n)
def emitMainFn : M Unit := do
d ← getDecl `main;
match d with
| Decl.fdecl f xs t b => do
unless (xs.size == 2 || xs.size == 1) (throw "invalid main function, incorrect arity when generating code");
env ← getEnv;
let usesLeanAPI := usesModuleFrom env `Init.Lean;
if usesLeanAPI then
emitLn "void lean_initialize();"
else
emitLn "void lean_initialize_runtime_module();";
emitLn "int main(int argc, char ** argv) {\nlean_object* in; lean_object* res;";
if usesLeanAPI then
emitLn "lean_initialize();"
else
emitLn "lean_initialize_runtime_module();";
modName ← getModName;
emitLn ("res = initialize_" ++ (modName.mangle "") ++ "(lean_io_mk_world());");
emitLns ["lean_io_mark_end_initialization();",
"if (lean_io_result_is_ok(res)) {",
"lean_dec_ref(res);",
"lean_init_task_manager();"];
if xs.size == 2 then do {
emitLns ["in = lean_box(0);",
"int i = argc;",
"while (i > 1) {",
" lean_object* n;",
" i--;",
" n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);",
" in = n;",
"}"];
emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());")
} else do {
emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());")
};
emitLn "}";
emitLns ["if (lean_io_result_is_ok(res)) {",
" int ret = lean_unbox(lean_io_result_get_value(res));",
" lean_dec_ref(res);",
" return ret;",
"} else {",
" lean_io_result_show_error(res);",
" lean_dec_ref(res);",
" return 1;",
"}"];
emitLn "}"
| other => throw "function declaration expected"
def hasMainFn : M Bool := do
env ← getEnv;
let decls := getDecls env;
pure $ decls.any (fun d => d.name == `main)
def emitMainFnIfNeeded : M Unit :=
whenM hasMainFn emitMainFn
def emitFileHeader : M Unit := do
env ← getEnv;
modName ← getModName;
emitLn "// Lean compiler output";
emitLn ("// Module: " ++ toString modName);
emit "// Imports:";
env.imports.forM $ fun m => emit (" " ++ toString m);
emitLn "";
emitLn "#include \"runtime/lean.h\"";
emitLns [
"#if defined(__clang__)",
"#pragma clang diagnostic ignored \"-Wunused-parameter\"",
"#pragma clang diagnostic ignored \"-Wunused-label\"",
"#elif defined(__GNUC__) && !defined(__CLANG__)",
"#pragma GCC diagnostic ignored \"-Wunused-parameter\"",
"#pragma GCC diagnostic ignored \"-Wunused-label\"",
"#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"",
"#endif",
"#ifdef __cplusplus",
"extern \"C\" {",
"#endif"
]
def emitFileFooter : M Unit :=
emitLns [
"#ifdef __cplusplus",
"}",
"#endif"
]
def throwUnknownVar {α : Type} (x : VarId) : M α :=
throw ("unknown variable '" ++ toString x ++ "'")
def getJPParams (j : JoinPointId) : M (Array Param) := do
ctx ← read;
match ctx.jpMap.find? j with
| some ps => pure ps
| none => throw "unknown join point"
def declareVar (x : VarId) (t : IRType) : M Unit := do
emit (toCType t); emit " "; emit x; emit "; "
def declareParams (ps : Array Param) : M Unit :=
ps.forM $ fun p => declareVar p.x p.ty
partial def declareVars : FnBody → Bool → M Bool
| e@(FnBody.vdecl x t _ b), d => do
ctx ← read;
if isTailCallTo ctx.mainFn e then
pure d
else
declareVar x t *> declareVars b true
| FnBody.jdecl j xs _ b, d => declareParams xs *> declareVars b (d || xs.size > 0)
| e, d => if e.isTerminal then pure d else declareVars e.body d
def emitTag (x : VarId) (xType : IRType) : M Unit := do
if xType.isObj then do
emit "lean_obj_tag("; emit x; emit ")"
else
emit x
def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) :=
if alts.size != 2 then none
else match alts.get! 0 with
| Alt.ctor c b => some (c.cidx, b, (alts.get! 1).body)
| _ => none
def emitIf (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do
emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")";
emitBody t;
emitLn "else";
emitBody e
def emitCase (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit :=
match isIf alts with
| some (tag, t, e) => emitIf emitBody x xType tag t e
| _ => do
emit "switch ("; emitTag x xType; emitLn ") {";
let alts := ensureHasDefault alts;
alts.forM $ fun alt => match alt with
| Alt.ctor c b => emit "case " *> emit c.cidx *> emitLn ":" *> emitBody b
| Alt.default b => emitLn "default: " *> emitBody b;
emitLn "}"
def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do
emit $
if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n")
else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n");
emit "(" *> emit x;
when (n != 1) (emit ", " *> emit n);
emitLn ");"
def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do
emit (if checkRef then "lean_dec" else "lean_dec_ref");
emit "("; emit x;
when (n != 1) (do emit ", "; emit n);
emitLn ");"
def emitDel (x : VarId) : M Unit := do
emit "lean_free_object("; emit x; emitLn ");"
def emitSetTag (x : VarId) (i : Nat) : M Unit := do
emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");"
def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do
emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");"
def emitOffset (n : Nat) (offset : Nat) : M Unit :=
if n > 0 then do
emit "sizeof(void*)*"; emit n;
when (offset > 0) (emit " + " *> emit offset)
else
emit offset
def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do
emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");"
def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do
match t with
| IRType.float => emit "lean_ctor_set_float"
| IRType.uint8 => emit "lean_ctor_set_uint8"
| IRType.uint16 => emit "lean_ctor_set_uint16"
| IRType.uint32 => emit "lean_ctor_set_uint32"
| IRType.uint64 => emit "lean_ctor_set_uint64"
| _ => throw "invalid instruction";
emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");"
def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do
ps ← getJPParams j;
unless (xs.size == ps.size) (throw "invalid goto");
xs.size.forM $ fun i => do {
let p := ps.get! i;
let x := xs.get! i;
emit p.x; emit " = "; emitArg x; emitLn ";"
};
emit "goto "; emit j; emitLn ";"
def emitLhs (z : VarId) : M Unit := do
emit z; emit " = "
def emitArgs (ys : Array Arg) : M Unit :=
ys.size.forM $ fun i => do
when (i > 0) (emit ", ");
emitArg (ys.get! i)
def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit :=
if usize == 0 then emit ssize
else if ssize == 0 then emit "sizeof(size_t)*" *> emit usize
else emit "sizeof(size_t)*" *> emit usize *> emit " + " *> emit ssize
def emitAllocCtor (c : CtorInfo) : M Unit := do
emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", ";
emitCtorScalarSize c.usize c.ssize; emitLn ");"
def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit :=
ys.size.forM $ fun i => do
emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg (ys.get! i); emitLn ");"
def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do
emitLhs z;
if c.size == 0 && c.usize == 0 && c.ssize == 0 then do
emit "lean_box("; emit c.cidx; emitLn ");"
else do
emitAllocCtor c; emitCtorSetArgs z ys
def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do
emit "if (lean_is_exclusive("; emit x; emitLn ")) {";
n.forM $ fun i => do {
emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");"
};
emit " "; emitLhs z; emit x; emitLn ";";
emitLn "} else {";
emit " lean_dec_ref("; emit x; emitLn ");";
emit " "; emitLhs z; emitLn "lean_box(0);";
emitLn "}"
def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do
emit "if (lean_is_scalar("; emit x; emitLn ")) {";
emit " "; emitLhs z; emitAllocCtor c;
emitLn "} else {";
emit " "; emitLhs z; emit x; emitLn ";";
when updtHeader (do emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");");
emitLn "}";
emitCtorSetArgs z ys
def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do
emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");"
def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do
emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");"
def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do
emitLhs z;
match t with
| IRType.float => emit "lean_ctor_get_float"
| IRType.uint8 => emit "lean_ctor_get_uint8"
| IRType.uint16 => emit "lean_ctor_get_uint16"
| IRType.uint32 => emit "lean_ctor_get_uint32"
| IRType.uint64 => emit "lean_ctor_get_uint64"
| _ => throw "invalid instruction";
emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");"
def toStringArgs (ys : Array Arg) : List String :=
ys.toList.map argToCString
def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do
emit f; emit "(";
-- We must remove irrelevant arguments to extern calls.
_ ← ys.size.foldM
(fun i (first : Bool) =>
if (ps.get! i).ty.isIrrelevant then
pure first
else do
unless first (emit ", ");
emitArg (ys.get! i);
pure false)
true;
emitLn ");";
pure ()
def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit :=
match getExternEntryFor extData `c with
| some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys
| some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";"
| some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys
| _ => throw ("failed to emit extern application '" ++ toString f ++ "'")
def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do
emitLhs z;
decl ← getDecl f;
match decl with
| Decl.extern _ ps _ extData => emitExternCall f ps extData ys
| _ => do emitCName f; when (ys.size > 0) (do emit "("; emitArgs ys; emit ")"); emitLn ";"
def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do
decl ← getDecl f;
let arity := decl.params.size;
emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");";
ys.size.forM $ fun i => do {
let y := ys.get! i;
emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");"
}
def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit :=
if ys.size > closureMaxArgs then do
emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};";
emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }"
else do
emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");"
def emitBoxFn (xType : IRType) : M Unit :=
match xType with
| IRType.usize => emit "lean_box_usize"
| IRType.uint32 => emit "lean_box_uint32"
| IRType.uint64 => emit "lean_box_uint64"
| IRType.float => emit "lean_box_float"
| other => emit "lean_box"
def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do
emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");"
def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do
emitLhs z;
match t with
| IRType.usize => emit "lean_unbox_usize"
| IRType.uint32 => emit "lean_unbox_uint32"
| IRType.uint64 => emit "lean_unbox_uint64"
| IRType.float => emit "lean_unbox_float"
| other => emit "lean_unbox";
emit "("; emit x; emitLn ");"
def emitIsShared (z : VarId) (x : VarId) : M Unit := do
emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");"
def emitIsTaggedPtr (z : VarId) (x : VarId) : M Unit := do
emitLhs z; emit "!lean_is_scalar("; emit x; emitLn ");"
def toHexDigit (c : Nat) : String :=
String.singleton c.digitChar
def quoteString (s : String) : String :=
let q := "\"";
let q := s.foldl
(fun q c => q ++
if c == '\n' then "\\n"
else if c == '\n' then "\\t"
else if c == '\\' then "\\\\"
else if c == '\"' then "\\\""
else if c.toNat <= 31 then
"\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16)
-- TODO(Leo): we should use `\unnnn` for escaping unicode characters.
else String.singleton c)
q;
q ++ "\""
def emitNumLit (t : IRType) (v : Nat) : M Unit :=
if t.isObj then do
if v < uint32Sz then
emit "lean_unsigned_to_nat(" *> emit v *> emit "u)"
else
emit "lean_cstr_to_nat(\"" *> emit v *> emit "\")"
else
emit v
def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit :=
emitLhs z *>
match v with
| LitVal.num v => emitNumLit t v *> emitLn ";"
| LitVal.str v => do emit "lean_mk_string("; emit (quoteString v); emitLn ");"
def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit :=
match v with
| Expr.ctor c ys => emitCtor z c ys
| Expr.reset n x => emitReset z n x
| Expr.reuse x c u ys => emitReuse z x c u ys
| Expr.proj i x => emitProj z i x
| Expr.uproj i x => emitUProj z i x
| Expr.sproj n o x => emitSProj z t n o x
| Expr.fap c ys => emitFullApp z c ys
| Expr.pap c ys => emitPartialApp z c ys
| Expr.ap x ys => emitApp z x ys
| Expr.box t x => emitBox z x t
| Expr.unbox x => emitUnbox z t x
| Expr.isShared x => emitIsShared z x
| Expr.isTaggedPtr x => emitIsTaggedPtr z x
| Expr.lit v => emitLit z t v
def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do
ctx ← read;
match v, b with
| Expr.fap f _, FnBody.ret (Arg.var y) => pure $ f == ctx.mainFn && x == y
| _, _ => pure false
def paramEqArg (p : Param) (x : Arg) : Bool :=
match x with
| Arg.var x => p.x == x
| _ => false
/-
Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments
```
p_0 := y_0,
...
p_{n-1} := y_{n-1}
```
Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`.
That is, we have
```
p_i := y_i,
...
p_j := p_i, -- p_i was overwritten above
```
-/
def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool :=
let n := ps.size;
n.any $ fun i =>
let p := ps.get! i;
(i+1, n).anyI $ fun j => paramEqArg p (ys.get! j)
def emitTailCall (v : Expr) : M Unit :=
match v with
| Expr.fap _ ys => do
ctx ← read;
let ps := ctx.mainParams;
unless (ps.size == ys.size) (throw "invalid tail call");
if overwriteParam ps ys then do {
emitLn "{";
ps.size.forM $ fun i => do {
let p := ps.get! i;
let y := ys.get! i;
unless (paramEqArg p y) $ do {
emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";"
}
};
ps.size.forM $ fun i => do {
let p := ps.get! i;
let y := ys.get! i;
unless (paramEqArg p y) (do emit p.x; emit " = _tmp_"; emit i; emitLn ";")
};
emitLn "}"
} else do {
ys.size.forM $ fun i => do {
let p := ps.get! i;
let y := ys.get! i;
unless (paramEqArg p y) (do emit p.x; emit " = "; emitArg y; emitLn ";")
}
};
emitLn "goto _start;"
| _ => throw "bug at emitTailCall"
partial def emitBlock (emitBody : FnBody → M Unit) : FnBody → M Unit
| FnBody.jdecl j xs v b => emitBlock b
| d@(FnBody.vdecl x t v b) =>
do ctx ← read; if isTailCallTo ctx.mainFn d then emitTailCall v else emitVDecl x t v *> emitBlock b
| FnBody.inc x n c p b => unless p (emitInc x n c) *> emitBlock b
| FnBody.dec x n c p b => unless p (emitDec x n c) *> emitBlock b
| FnBody.del x b => emitDel x *> emitBlock b
| FnBody.setTag x i b => emitSetTag x i *> emitBlock b
| FnBody.set x i y b => emitSet x i y *> emitBlock b
| FnBody.uset x i y b => emitUSet x i y *> emitBlock b
| FnBody.sset x i o y t b => emitSSet x i o y t *> emitBlock b
| FnBody.mdata _ b => emitBlock b
| FnBody.ret x => emit "return " *> emitArg x *> emitLn ";"
| FnBody.case _ x xType alts => emitCase emitBody x xType alts
| FnBody.jmp j xs => emitJmp j xs
| FnBody.unreachable => emitLn "lean_panic_unreachable();"
partial def emitJPs (emitBody : FnBody → M Unit) : FnBody → M Unit
| FnBody.jdecl j xs v b => do emit j; emitLn ":"; emitBody v; emitJPs b
| e => unless e.isTerminal (emitJPs e.body)
partial def emitFnBody : FnBody → M Unit
| b => do
emitLn "{";
declared ← declareVars b false;
when declared (emitLn "");
emitBlock emitFnBody b;
emitJPs emitFnBody b;
emitLn "}"
def emitDeclAux (d : Decl) : M Unit := do
env ← getEnv;
let (vMap, jpMap) := mkVarJPMaps d;
adaptReader (fun (ctx : Context) => { jpMap := jpMap, .. ctx }) $ do
unless (hasInitAttr env d.name) $
match d with
| Decl.fdecl f xs t b => do
baseName ← toCName f;
emit (toCType t); emit " ";
if xs.size > 0 then do {
emit baseName;
emit "(";
if xs.size > closureMaxArgs && isBoxedName d.name then
emit "lean_object** _args"
else
xs.size.forM $ fun i => do {
when (i > 0) (emit ", ");
let x := xs.get! i;
emit (toCType x.ty); emit " "; emit x.x
};
emit ")"
} else do {
emit ("_init_" ++ baseName ++ "()")
};
emitLn " {";
when (xs.size > closureMaxArgs && isBoxedName d.name) $
xs.size.forM $ fun i => do {
let x := xs.get! i;
emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];"
};
emitLn "_start:";
adaptReader (fun (ctx : Context) => { mainFn := f, mainParams := xs, .. ctx }) (emitFnBody b);
emitLn "}"
| _ => pure ()
def emitDecl (d : Decl) : M Unit :=
let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices
catch
(emitDeclAux d)
(fun err => throw (err ++ "\ncompiling:\n" ++ toString d))
def emitFns : M Unit := do
env ← getEnv;
let decls := getDecls env;
decls.reverse.forM emitDecl
def emitMarkPersistent (d : Decl) (n : Name) : M Unit :=
when d.resultType.isObj $ do {
emit "lean_mark_persistent("; emitCName n; emitLn ");"
}
def emitDeclInit (d : Decl) : M Unit := do
env ← getEnv;
let n := d.name;
if isIOUnitInitFn env n then do {
emit "res = "; emitCName n; emitLn "(lean_io_mk_world());";
emitLn "if (lean_io_result_is_error(res)) return res;";
emitLn "lean_dec_ref(res);"
} else when (d.params.size == 0) $
match getInitFnNameFor env d.name with
| some initFn => do {
emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());";
emitLn "if (lean_io_result_is_error(res)) return res;";
emitCName n; emitLn " = lean_io_result_get_value(res);";
emitMarkPersistent d n;
emitLn "lean_dec_ref(res);"
}
| _ => do { emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n }
def emitInitFn : M Unit := do
env ← getEnv;
modName ← getModName;
env.imports.forM $ fun imp => emitLn ("lean_object* initialize_" ++ imp.module.mangle "" ++ "(lean_object*);");
emitLns [
"static bool _G_initialized = false;",
"lean_object* initialize_" ++ modName.mangle "" ++ "(lean_object* w) {",
"lean_object * res;",
"if (_G_initialized) return lean_mk_io_result(lean_box(0));",
"_G_initialized = true;"
];
env.imports.forM $ fun imp => emitLns [
"res = initialize_" ++ imp.module.mangle "" ++ "(lean_io_mk_world());",
"if (lean_io_result_is_error(res)) return res;",
"lean_dec_ref(res);"];
let decls := getDecls env;
decls.reverse.forM emitDeclInit;
emitLns ["return lean_mk_io_result(lean_box(0));", "}"]
def main : M Unit := do
emitFileHeader;
emitFnDecls;
emitFns;
emitInitFn;
emitMainFnIfNeeded;
emitFileFooter
end EmitC
@[export lean_ir_emit_c]
def emitC (env : Environment) (modName : Name) : Except String String :=
match (EmitC.main { env := env, modName := modName }).run "" with
| EStateM.Result.ok _ s => Except.ok s
| EStateM.Result.error err _ => Except.error err
end IR
end Lean
|
590d37541b2762578d5a97f870b19d51f4dd070a | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/measure_theory/integral/mean_inequalities.lean | 00ad1844ab031d09825a006d77713caf2b646f28 | [
"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 | 19,810 | lean | /-
Copyright (c) 2020 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import measure_theory.integral.lebesgue
import analysis.mean_inequalities
import measure_theory.function.special_functions
/-!
# Mean value inequalities for integrals
In this file we prove several inequalities on integrals, notably the Hölder inequality and
the Minkowski inequality. The versions for finite sums are in `analysis.mean_inequalities`.
## Main results
Hölder's inequality for the Lebesgue integral of `ℝ≥0∞` and `ℝ≥0` functions: we prove
`∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents
and `α→(e)nnreal` functions in two cases,
* `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions,
* `nnreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0 functions.
Minkowski's inequality for the Lebesgue integral of measurable functions with `ℝ≥0∞` values:
we prove `(∫ (f + g)^p ∂μ) ^ (1/p) ≤ (∫ f^p ∂μ) ^ (1/p) + (∫ g^p ∂μ) ^ (1/p)` for `1 ≤ p`.
-/
section lintegral
/-!
### Hölder's inequality for the Lebesgue integral of ℝ≥0∞ and nnreal functions
We prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q`
conjugate real exponents and `α→(e)nnreal` functions in several cases, the first two being useful
only to prove the more general results:
* `ennreal.lintegral_mul_le_one_of_lintegral_rpow_eq_one` : ℝ≥0∞ functions for which the
integrals on the right are equal to 1,
* `ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top` : ℝ≥0∞ functions for which the
integrals on the right are neither ⊤ nor 0,
* `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions,
* `nnreal.lintegral_mul_le_Lp_mul_Lq` : nnreal functions.
-/
noncomputable theory
open_locale classical big_operators nnreal ennreal
open measure_theory
variables {α : Type*} [measurable_space α] {μ : measure α}
namespace ennreal
lemma lintegral_mul_le_one_of_lintegral_rpow_eq_one {p q : ℝ} (hpq : p.is_conjugate_exponent q)
{f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ)
(hf_norm : ∫⁻ a, (f a)^p ∂μ = 1) (hg_norm : ∫⁻ a, (g a)^q ∂μ = 1) :
∫⁻ a, (f * g) a ∂μ ≤ 1 :=
begin
calc ∫⁻ (a : α), ((f * g) a) ∂μ
≤ ∫⁻ (a : α), ((f a)^p / ennreal.of_real p + (g a)^q / ennreal.of_real q) ∂μ :
lintegral_mono (λ a, young_inequality (f a) (g a) hpq)
... = 1 :
begin
simp only [div_eq_mul_inv],
rw lintegral_add',
{ rw [lintegral_mul_const'' _ (hf.pow_const p), lintegral_mul_const'' _ (hg.pow_const q),
hf_norm, hg_norm, ← div_eq_mul_inv, ← div_eq_mul_inv, hpq.inv_add_inv_conj_ennreal], },
{ exact (hf.pow_const _).mul_const _, },
{ exact (hg.pow_const _).mul_const _, },
end
end
/-- Function multiplied by the inverse of its p-seminorm `(∫⁻ f^p ∂μ) ^ 1/p`-/
def fun_mul_inv_snorm (f : α → ℝ≥0∞) (p : ℝ) (μ : measure α) : α → ℝ≥0∞ :=
λ a, (f a) * ((∫⁻ c, (f c) ^ p ∂μ) ^ (1 / p))⁻¹
lemma fun_eq_fun_mul_inv_snorm_mul_snorm {p : ℝ} (f : α → ℝ≥0∞)
(hf_nonzero : ∫⁻ a, (f a) ^ p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) {a : α} :
f a = (fun_mul_inv_snorm f p μ a) * (∫⁻ c, (f c)^p ∂μ)^(1/p) :=
by simp [fun_mul_inv_snorm, mul_assoc, inv_mul_cancel, hf_nonzero, hf_top]
lemma fun_mul_inv_snorm_rpow {p : ℝ} (hp0 : 0 < p) {f : α → ℝ≥0∞} {a : α} :
(fun_mul_inv_snorm f p μ a) ^ p = (f a)^p * (∫⁻ c, (f c) ^ p ∂μ)⁻¹ :=
begin
rw [fun_mul_inv_snorm, mul_rpow_of_nonneg _ _ (le_of_lt hp0)],
suffices h_inv_rpow : ((∫⁻ (c : α), f c ^ p ∂μ) ^ (1 / p))⁻¹ ^ p = (∫⁻ (c : α), f c ^ p ∂μ)⁻¹,
by rw h_inv_rpow,
rw [inv_rpow, ← rpow_mul, one_div_mul_cancel hp0.ne', rpow_one]
end
lemma lintegral_rpow_fun_mul_inv_snorm_eq_one {p : ℝ} (hp0_lt : 0 < p) {f : α → ℝ≥0∞}
(hf : ae_measurable f μ) (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) :
∫⁻ c, (fun_mul_inv_snorm f p μ c)^p ∂μ = 1 :=
begin
simp_rw fun_mul_inv_snorm_rpow hp0_lt,
rw [lintegral_mul_const'' _ (hf.pow_const p), mul_inv_cancel hf_nonzero hf_top],
end
/-- Hölder's inequality in case of finite non-zero integrals -/
lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top {p q : ℝ} (hpq : p.is_conjugate_exponent q)
{f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ)
(hf_nontop : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) (hg_nontop : ∫⁻ a, (g a)^q ∂μ ≠ ⊤)
(hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) :
∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) :=
begin
let npf := (∫⁻ (c : α), (f c) ^ p ∂μ) ^ (1/p),
let nqg := (∫⁻ (c : α), (g c) ^ q ∂μ) ^ (1/q),
calc ∫⁻ (a : α), (f * g) a ∂μ
= ∫⁻ (a : α), ((fun_mul_inv_snorm f p μ * fun_mul_inv_snorm g q μ) a)
* (npf * nqg) ∂μ :
begin
refine lintegral_congr (λ a, _),
rw [pi.mul_apply, fun_eq_fun_mul_inv_snorm_mul_snorm f hf_nonzero hf_nontop,
fun_eq_fun_mul_inv_snorm_mul_snorm g hg_nonzero hg_nontop, pi.mul_apply],
ring,
end
... ≤ npf * nqg :
begin
rw lintegral_mul_const' (npf * nqg) _ (by simp [hf_nontop, hg_nontop, hf_nonzero, hg_nonzero]),
nth_rewrite 1 ←one_mul (npf * nqg),
refine mul_le_mul _ (le_refl (npf * nqg)),
have hf1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.pos hf hf_nonzero hf_nontop,
have hg1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.symm.pos hg hg_nonzero hg_nontop,
exact lintegral_mul_le_one_of_lintegral_rpow_eq_one hpq (hf.mul_const _)
(hg.mul_const _) hf1 hg1,
end
end
lemma ae_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0_lt : 0 < p) {f : α → ℝ≥0∞}
(hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) :
f =ᵐ[μ] 0 :=
begin
rw lintegral_eq_zero_iff' (hf.pow_const p) at hf_zero,
refine filter.eventually.mp hf_zero (filter.eventually_of_forall (λ x, _)),
dsimp only,
rw [pi.zero_apply, rpow_eq_zero_iff],
intro hx,
cases hx,
{ exact hx.left, },
{ exfalso,
linarith, },
end
lemma lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0_lt : 0 < p)
{f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) :
∫⁻ a, (f * g) a ∂μ = 0 :=
begin
rw ←@lintegral_zero_fun α _ μ,
refine lintegral_congr_ae _,
suffices h_mul_zero : f * g =ᵐ[μ] 0 * g , by rwa zero_mul at h_mul_zero,
have hf_eq_zero : f =ᵐ[μ] 0, from ae_eq_zero_of_lintegral_rpow_eq_zero hp0_lt hf hf_zero,
exact filter.eventually_eq.mul hf_eq_zero (ae_eq_refl g),
end
lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top {p q : ℝ} (hp0_lt : 0 < p) (hq0 : 0 ≤ q)
{f g : α → ℝ≥0∞} (hf_top : ∫⁻ a, (f a)^p ∂μ = ⊤) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) :
∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) :=
begin
refine le_trans le_top (le_of_eq _),
have hp0_inv_lt : 0 < 1/p, by simp [hp0_lt],
rw [hf_top, ennreal.top_rpow_of_pos hp0_inv_lt],
simp [hq0, hg_nonzero],
end
/-- Hölder's inequality for functions `α → ℝ≥0∞`. The integral of the product of two functions
is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate
exponents. -/
theorem lintegral_mul_le_Lp_mul_Lq (μ : measure α) {p q : ℝ} (hpq : p.is_conjugate_exponent q)
{f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) :
∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) :=
begin
by_cases hf_zero : ∫⁻ a, (f a) ^ p ∂μ = 0,
{ refine le_trans (le_of_eq _) (zero_le _),
exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.pos hf hf_zero, },
by_cases hg_zero : ∫⁻ a, (g a) ^ q ∂μ = 0,
{ refine le_trans (le_of_eq _) (zero_le _),
rw mul_comm,
exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.symm.pos hg hg_zero, },
by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤,
{ exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.pos hpq.symm.nonneg hf_top hg_zero, },
by_cases hg_top : ∫⁻ a, (g a) ^ q ∂μ = ⊤,
{ rw [mul_comm, mul_comm ((∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p))],
exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.symm.pos hpq.nonneg hg_top hf_zero, },
-- non-⊤ non-zero case
exact ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top hpq hf hg hf_top hg_top hf_zero
hg_zero,
end
lemma lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top {p : ℝ}
{f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ < ⊤)
(hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ < ⊤) (hp1 : 1 ≤ p) :
∫⁻ a, ((f + g) a) ^ p ∂μ < ⊤ :=
begin
have hp0_lt : 0 < p, from lt_of_lt_of_le zero_lt_one hp1,
have hp0 : 0 ≤ p, from le_of_lt hp0_lt,
calc ∫⁻ (a : α), (f a + g a) ^ p ∂μ
≤ ∫⁻ a, ((2:ℝ≥0∞)^(p-1) * (f a) ^ p + (2:ℝ≥0∞)^(p-1) * (g a) ^ p) ∂ μ :
begin
refine lintegral_mono (λ a, _),
dsimp only,
have h_zero_lt_half_rpow : (0 : ℝ≥0∞) < (1 / 2) ^ p,
{ rw [←ennreal.zero_rpow_of_pos hp0_lt],
exact ennreal.rpow_lt_rpow (by simp [zero_lt_one]) hp0_lt, },
have h_rw : (1 / 2) ^ p * (2:ℝ≥0∞) ^ (p - 1) = 1 / 2,
{ rw [sub_eq_add_neg, ennreal.rpow_add _ _ ennreal.two_ne_zero ennreal.coe_ne_top,
←mul_assoc, ←ennreal.mul_rpow_of_nonneg _ _ hp0, one_div,
ennreal.inv_mul_cancel ennreal.two_ne_zero ennreal.coe_ne_top, ennreal.one_rpow,
one_mul, ennreal.rpow_neg_one], },
rw ←ennreal.mul_le_mul_left (ne_of_lt h_zero_lt_half_rpow).symm _,
{ rw [mul_add, ← mul_assoc, ← mul_assoc, h_rw, ←ennreal.mul_rpow_of_nonneg _ _ hp0, mul_add],
refine ennreal.rpow_arith_mean_le_arith_mean2_rpow (1/2 : ℝ≥0∞) (1/2 : ℝ≥0∞)
(f a) (g a) _ hp1,
rw [ennreal.div_add_div_same, one_add_one_eq_two,
ennreal.div_self ennreal.two_ne_zero ennreal.coe_ne_top], },
{ rw ←ennreal.lt_top_iff_ne_top,
refine ennreal.rpow_lt_top_of_nonneg hp0 _,
rw [one_div, ennreal.inv_ne_top],
exact ennreal.two_ne_zero, },
end
... < ⊤ :
begin
rw [lintegral_add', lintegral_const_mul'' _ (hf.pow_const p),
lintegral_const_mul'' _ (hg.pow_const p), ennreal.add_lt_top],
{ have h_two : (2 : ℝ≥0∞) ^ (p - 1) < ⊤,
from ennreal.rpow_lt_top_of_nonneg (by simp [hp1]) ennreal.coe_ne_top,
repeat {rw ennreal.mul_lt_top_iff},
simp [hf_top, hg_top, h_two], },
{ exact (hf.pow_const _).const_mul _ },
{ exact (hg.pow_const _).const_mul _ },
end
end
lemma lintegral_Lp_mul_le_Lq_mul_Lr {α} [measurable_space α] {p q r : ℝ} (hp0_lt : 0 < p)
(hpq : p < q) (hpqr : 1/p = 1/q + 1/r) (μ : measure α) {f g : α → ℝ≥0∞}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) :
(∫⁻ a, ((f * g) a)^p ∂μ) ^ (1/p) ≤ (∫⁻ a, (f a)^q ∂μ) ^ (1/q) * (∫⁻ a, (g a)^r ∂μ) ^ (1/r) :=
begin
have hp0_ne : p ≠ 0, from (ne_of_lt hp0_lt).symm,
have hp0 : 0 ≤ p, from le_of_lt hp0_lt,
have hq0_lt : 0 < q, from lt_of_le_of_lt hp0 hpq,
have hq0_ne : q ≠ 0, from (ne_of_lt hq0_lt).symm,
have h_one_div_r : 1/r = 1/p - 1/q, by simp [hpqr],
have hr0_ne : r ≠ 0,
{ have hr_inv_pos : 0 < 1/r,
by rwa [h_one_div_r, sub_pos, one_div_lt_one_div hq0_lt hp0_lt],
rw [one_div, _root_.inv_pos] at hr_inv_pos,
exact (ne_of_lt hr_inv_pos).symm, },
let p2 := q/p,
let q2 := p2.conjugate_exponent,
have hp2q2 : p2.is_conjugate_exponent q2,
from real.is_conjugate_exponent_conjugate_exponent (by simp [lt_div_iff, hpq, hp0_lt]),
calc (∫⁻ (a : α), ((f * g) a) ^ p ∂μ) ^ (1 / p)
= (∫⁻ (a : α), (f a)^p * (g a)^p ∂μ) ^ (1 / p) :
by simp_rw [pi.mul_apply, ennreal.mul_rpow_of_nonneg _ _ hp0]
... ≤ ((∫⁻ a, (f a)^(p * p2) ∂ μ)^(1/p2) * (∫⁻ a, (g a)^(p * q2) ∂ μ)^(1/q2)) ^ (1/p) :
begin
refine ennreal.rpow_le_rpow _ (by simp [hp0]),
simp_rw ennreal.rpow_mul,
exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hp2q2 (hf.pow_const _) (hg.pow_const _)
end
... = (∫⁻ (a : α), (f a) ^ q ∂μ) ^ (1 / q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1 / r) :
begin
rw [@ennreal.mul_rpow_of_nonneg _ _ (1/p) (by simp [hp0]), ←ennreal.rpow_mul,
←ennreal.rpow_mul],
have hpp2 : p * p2 = q,
{ symmetry, rw [mul_comm, ←div_eq_iff hp0_ne], },
have hpq2 : p * q2 = r,
{ rw [← inv_inv' r, ← one_div, ← one_div, h_one_div_r],
field_simp [q2, real.conjugate_exponent, p2, hp0_ne, hq0_ne] },
simp_rw [div_mul_div, mul_one, mul_comm p2, mul_comm q2, hpp2, hpq2],
end
end
lemma lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow {p q : ℝ}
(hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) :
∫⁻ a, (f a) * (g a) ^ (p - 1) ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^p ∂μ) ^ (1/q) :=
begin
refine le_trans (ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf (hg.pow_const _)) _,
by_cases hf_zero_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) = 0,
{ rw [hf_zero_rpow, zero_mul],
exact zero_le _, },
have hf_top_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) ≠ ⊤,
{ by_contra h,
push_neg at h,
refine hf_top _,
have hp_not_neg : ¬ p < 0, by simp [hpq.nonneg],
simpa [hpq.pos, hp_not_neg] using h, },
refine (ennreal.mul_le_mul_left hf_zero_rpow hf_top_rpow).mpr (le_of_eq _),
congr,
ext1 a,
rw [←ennreal.rpow_mul, hpq.sub_one_mul_conj],
end
lemma lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add {p q : ℝ}
(hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ)
(hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) :
∫⁻ a, ((f + g) a)^p ∂ μ
≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p))
* (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) :=
begin
calc ∫⁻ a, ((f+g) a) ^ p ∂μ ≤ ∫⁻ a, ((f + g) a) * ((f + g) a) ^ (p - 1) ∂μ :
begin
refine lintegral_mono (λ a, _),
dsimp only,
by_cases h_zero : (f + g) a = 0,
{ rw [h_zero, ennreal.zero_rpow_of_pos hpq.pos],
exact zero_le _, },
by_cases h_top : (f + g) a = ⊤,
{ rw [h_top, ennreal.top_rpow_of_pos hpq.sub_one_pos, ennreal.top_mul_top],
exact le_top, },
refine le_of_eq _,
nth_rewrite 1 ←ennreal.rpow_one ((f + g) a),
rw [←ennreal.rpow_add _ _ h_zero h_top, add_sub_cancel'_right],
end
... = ∫⁻ (a : α), f a * (f + g) a ^ (p - 1) ∂μ + ∫⁻ (a : α), g a * (f + g) a ^ (p - 1) ∂μ :
begin
have h_add_m : ae_measurable (λ (a : α), ((f + g) a) ^ (p-1)) μ,
from (hf.add hg).pow_const _,
have h_add_apply : ∫⁻ (a : α), (f + g) a * (f + g) a ^ (p - 1) ∂μ
= ∫⁻ (a : α), (f a + g a) * (f + g) a ^ (p - 1) ∂μ,
from rfl,
simp_rw [h_add_apply, add_mul],
rw lintegral_add' (hf.mul h_add_m) (hg.mul h_add_m),
end
... ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p))
* (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) :
begin
rw add_mul,
exact add_le_add
(lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hf (hf.add hg) hf_top)
(lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hg (hf.add hg) hg_top),
end
end
private lemma lintegral_Lp_add_le_aux {p q : ℝ}
(hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ)
(hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤)
(h_add_zero : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ 0) (h_add_top : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤) :
(∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) :=
begin
have hp_not_nonpos : ¬ p ≤ 0, by simp [hpq.pos],
have htop_rpow : (∫⁻ a, ((f+g) a) ^ p ∂μ)^(1/p) ≠ ⊤,
{ by_contra h,
push_neg at h,
exact h_add_top (@ennreal.rpow_eq_top_of_nonneg _ (1/p) (by simp [hpq.nonneg]) h), },
have h0_rpow : (∫⁻ a, ((f+g) a) ^ p ∂ μ) ^ (1/p) ≠ 0,
by simp [h_add_zero, h_add_top, hpq.nonneg, hp_not_nonpos, -pi.add_apply],
suffices h : 1 ≤ (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ -(1/p)
* ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)),
by rwa [←mul_le_mul_left h0_rpow htop_rpow, ←mul_assoc, ←rpow_add _ _ h_add_zero h_add_top,
←sub_eq_add_neg, _root_.sub_self, rpow_zero, one_mul, mul_one] at h,
have h : ∫⁻ (a : α), ((f+g) a)^p ∂μ
≤ ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p))
* (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ (1/q),
from lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add hpq hf hf_top hg hg_top,
have h_one_div_q : 1/q = 1 - 1/p, by { nth_rewrite 1 ←hpq.inv_add_inv_conj, ring, },
simp_rw [h_one_div_q, sub_eq_add_neg 1 (1/p), ennreal.rpow_add _ _ h_add_zero h_add_top,
rpow_one] at h,
nth_rewrite 1 mul_comm at h,
nth_rewrite 0 ←one_mul (∫⁻ (a : α), ((f+g) a) ^ p ∂μ) at h,
rwa [←mul_assoc, ennreal.mul_le_mul_right h_add_zero h_add_top, mul_comm] at h,
end
/-- Minkowski's inequality for functions `α → ℝ≥0∞`: the `ℒp` seminorm of the sum of two
functions is bounded by the sum of their `ℒp` seminorms. -/
theorem lintegral_Lp_add_le {p : ℝ} {f g : α → ℝ≥0∞}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) :
(∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) :=
begin
have hp_pos : 0 < p, from lt_of_lt_of_le zero_lt_one hp1,
by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤,
{ simp [hf_top, hp_pos], },
by_cases hg_top : ∫⁻ a, (g a) ^ p ∂μ = ⊤,
{ simp [hg_top, hp_pos], },
by_cases h1 : p = 1,
{ refine le_of_eq _,
simp_rw [h1, one_div_one, ennreal.rpow_one],
exact lintegral_add' hf hg, },
have hp1_lt : 1 < p, by { refine lt_of_le_of_ne hp1 _, symmetry, exact h1, },
have hpq := real.is_conjugate_exponent_conjugate_exponent hp1_lt,
by_cases h0 : ∫⁻ a, ((f+g) a) ^ p ∂ μ = 0,
{ rw [h0, @ennreal.zero_rpow_of_pos (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1])],
exact zero_le _, },
have htop : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤,
{ rw ←ne.def at hf_top hg_top,
rw ←ennreal.lt_top_iff_ne_top at hf_top hg_top ⊢,
exact lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top hf hf_top hg hg_top hp1, },
exact lintegral_Lp_add_le_aux hpq hf hf_top hg hg_top h0 htop,
end
end ennreal
/-- Hölder's inequality for functions `α → ℝ≥0`. The integral of the product of two functions
is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate
exponents. -/
theorem nnreal.lintegral_mul_le_Lp_mul_Lq {p q : ℝ} (hpq : p.is_conjugate_exponent q)
{f g : α → ℝ≥0} (hf : ae_measurable f μ) (hg : ae_measurable g μ) :
∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) :=
begin
simp_rw [pi.mul_apply, ennreal.coe_mul],
exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf.coe_nnreal_ennreal hg.coe_nnreal_ennreal,
end
end lintegral
|
42b6b8cd71ff88171954a30ffae6841853308081 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/leanpkg/a/A.lean | 7ee5f376002da78e37192e9e4ebe5988c08197ad | [
"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 | 20 | lean | def name := "world"
|
f3f611ea52988a0ef512cefe4be1be12e4c6754d | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/finsupp/basic.lean | 665c651c2fd7650c19711fc7f2087dcb9e1ad65b | [
"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 | 63,440 | 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.big_operators.finsupp
import data.finset.preimage
import data.list.alist
/-!
# Miscellaneous definitions, lemmas, and constructions using finsupp
## Main declarations
* `finsupp.graph`: the finset of input and output pairs with non-zero outputs.
* `alist.lookup_finsupp`: converts an association list into a finitely supported function
via `alist.lookup`, sending absent keys to zero.
* `finsupp.map_range.equiv`: `finsupp.map_range` as an equiv.
* `finsupp.map_domain`: maps the domain of a `finsupp` by a function and by summing.
* `finsupp.comap_domain`: postcomposition of a `finsupp` with a function injective on the preimage
of its support.
* `finsupp.some`: restrict a finitely supported function on `option α` to a finitely supported
function on `α`.
* `finsupp.filter`: `filter p f` is the finitely supported function that is `f a` if `p a` is true
and 0 otherwise.
* `finsupp.frange`: the image of a finitely supported function on its support.
* `finsupp.subtype_domain`: the restriction of a finitely supported function `f` to a subtype.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
## TODO
* This file is currently ~1600 lines long and is quite a miscellany of definitions and lemmas,
so it should be divided into smaller pieces.
* Expand the list of definitions and important lemmas to the module docstring.
-/
noncomputable theory
open finset function
open_locale classical big_operators
variables {α β γ ι M M' N P G H R S : Type*}
namespace finsupp
/-! ### Declarations about `graph` -/
section graph
variable [has_zero M]
/-- The graph of a finitely supported function over its support, i.e. the finset of input and output
pairs with non-zero outputs. -/
def graph (f : α →₀ M) : finset (α × M) :=
f.support.map ⟨λ a, prod.mk a (f a), λ x y h, (prod.mk.inj h).1⟩
lemma mk_mem_graph_iff {a : α} {m : M} {f : α →₀ M} : (a, m) ∈ f.graph ↔ f a = m ∧ m ≠ 0 :=
begin
simp_rw [graph, mem_map, mem_support_iff],
split,
{ rintro ⟨b, ha, rfl, -⟩,
exact ⟨rfl, ha⟩ },
{ rintro ⟨rfl, ha⟩,
exact ⟨a, ha, rfl⟩ }
end
@[simp] lemma mem_graph_iff {c : α × M} {f : α →₀ M} : c ∈ f.graph ↔ f c.1 = c.2 ∧ c.2 ≠ 0 :=
by { cases c, exact mk_mem_graph_iff }
lemma mk_mem_graph (f : α →₀ M) {a : α} (ha : a ∈ f.support) : (a, f a) ∈ f.graph :=
mk_mem_graph_iff.2 ⟨rfl, mem_support_iff.1 ha⟩
lemma apply_eq_of_mem_graph {a : α} {m : M} {f : α →₀ M} (h : (a, m) ∈ f.graph) : f a = m :=
(mem_graph_iff.1 h).1
@[simp] lemma not_mem_graph_snd_zero (a : α) (f : α →₀ M) : (a, (0 : M)) ∉ f.graph :=
λ h, (mem_graph_iff.1 h).2.irrefl
@[simp] lemma image_fst_graph (f : α →₀ M) : f.graph.image prod.fst = f.support :=
by simp only [graph, map_eq_image, image_image, embedding.coe_fn_mk, (∘), image_id']
lemma graph_injective (α M) [has_zero M] : injective (@graph α M _) :=
begin
intros f g h,
have hsup : f.support = g.support, by rw [← image_fst_graph, h, image_fst_graph],
refine ext_iff'.2 ⟨hsup, λ x hx, apply_eq_of_mem_graph $ h.symm ▸ _⟩,
exact mk_mem_graph _ (hsup ▸ hx)
end
@[simp] lemma graph_inj {f g : α →₀ M} : f.graph = g.graph ↔ f = g :=
(graph_injective α M).eq_iff
@[simp] lemma graph_zero : graph (0 : α →₀ M) = ∅ := by simp [graph]
@[simp] lemma graph_eq_empty {f : α →₀ M} : f.graph = ∅ ↔ f = 0 :=
(graph_injective α M).eq_iff' graph_zero
/-- Produce an association list for the finsupp over its support using choice. -/
@[simps] def to_alist (f : α →₀ M) : alist (λ x : α, M) :=
⟨f.graph.to_list.map prod.to_sigma, begin
rw [list.nodupkeys, list.keys, list.map_map, prod.fst_comp_to_sigma, list.nodup_map_iff_inj_on],
{ rintros ⟨b, m⟩ hb ⟨c, n⟩ hc (rfl : b = c),
rw [mem_to_list, finsupp.mem_graph_iff] at hb hc,
dsimp at hb hc,
rw [←hc.1, hb.1] },
{ apply nodup_to_list }
end⟩
@[simp] lemma to_alist_keys_to_finset (f : α →₀ M) : f.to_alist.keys.to_finset = f.support :=
by { ext, simp [to_alist, alist.mem_keys, alist.keys, list.keys] }
@[simp] lemma mem_to_alist {f : α →₀ M} {x : α} : x ∈ f.to_alist ↔ f x ≠ 0 :=
by rw [alist.mem_keys, ←list.mem_to_finset, to_alist_keys_to_finset, mem_support_iff]
end graph
end finsupp
/-! ### Declarations about `alist.lookup_finsupp` -/
section lookup_finsupp
variable [has_zero M]
namespace alist
open list
/-- Converts an association list into a finitely supported function via `alist.lookup`, sending
absent keys to zero. -/
@[simps] def lookup_finsupp (l : alist (λ x : α, M)) : α →₀ M :=
{ support := (l.1.filter $ λ x, sigma.snd x ≠ 0).keys.to_finset,
to_fun := λ a, (l.lookup a).get_or_else 0,
mem_support_to_fun := λ a, begin
simp_rw [mem_to_finset, list.mem_keys, list.mem_filter, ←mem_lookup_iff],
cases lookup a l;
simp
end }
alias lookup_finsupp_to_fun ← lookup_finsupp_apply
lemma lookup_finsupp_eq_iff_of_ne_zero {l : alist (λ x : α, M)} {a : α} {x : M} (hx : x ≠ 0) :
l.lookup_finsupp a = x ↔ x ∈ l.lookup a :=
by { rw lookup_finsupp_to_fun, cases lookup a l with m; simp [hx.symm] }
lemma lookup_finsupp_eq_zero_iff {l : alist (λ x : α, M)} {a : α} :
l.lookup_finsupp a = 0 ↔ a ∉ l ∨ (0 : M) ∈ l.lookup a :=
by { rw [lookup_finsupp_to_fun, ←lookup_eq_none], cases lookup a l with m; simp }
@[simp] lemma empty_lookup_finsupp : lookup_finsupp (∅ : alist (λ x : α, M)) = 0 :=
by { ext, simp }
@[simp] lemma insert_lookup_finsupp (l : alist (λ x : α, M)) (a : α) (m : M) :
(l.insert a m).lookup_finsupp = l.lookup_finsupp.update a m :=
by { ext b, by_cases h : b = a; simp [h] }
@[simp] lemma singleton_lookup_finsupp (a : α) (m : M) :
(singleton a m).lookup_finsupp = finsupp.single a m :=
by simp [←alist.insert_empty]
@[simp] lemma _root_.finsupp.to_alist_lookup_finsupp (f : α →₀ M) : f.to_alist.lookup_finsupp = f :=
begin
ext,
by_cases h : f a = 0,
{ suffices : f.to_alist.lookup a = none,
{ simp [h, this] },
{ simp [lookup_eq_none, h] } },
{ suffices : f.to_alist.lookup a = some (f a),
{ simp [h, this] },
{ apply mem_lookup_iff.2,
simpa using h } }
end
lemma lookup_finsupp_surjective : surjective (@lookup_finsupp α M _) :=
λ f, ⟨_, finsupp.to_alist_lookup_finsupp f⟩
end alist
end lookup_finsupp
/-! ### Declarations about `map_range` -/
section map_range
namespace finsupp
section equiv
variables [has_zero M] [has_zero N] [has_zero P]
/-- `finsupp.map_range` as an equiv. -/
@[simps apply]
def map_range.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) :=
{ to_fun := (map_range f hf : (α →₀ M) → (α →₀ N)),
inv_fun := (map_range f.symm hf' : (α →₀ N) → (α →₀ M)),
left_inv := λ x, begin
rw ←map_range_comp _ _ _ _; simp_rw equiv.symm_comp_self,
{ exact map_range_id _ },
{ refl },
end,
right_inv := λ x, begin
rw ←map_range_comp _ _ _ _; simp_rw equiv.self_comp_symm,
{ exact map_range_id _ },
{ refl },
end }
@[simp]
lemma map_range.equiv_refl :
map_range.equiv (equiv.refl M) rfl rfl = equiv.refl (α →₀ M) :=
equiv.ext map_range_id
lemma map_range.equiv_trans
(f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') :
(map_range.equiv (f.trans f₂) (by rw [equiv.trans_apply, hf, hf₂])
(by rw [equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) =
(map_range.equiv f hf hf').trans (map_range.equiv f₂ hf₂ hf₂') :=
equiv.ext $ map_range_comp _ _ _ _ _
@[simp] lemma map_range.equiv_symm (f : M ≃ N) (hf hf') :
((map_range.equiv f hf hf').symm : (α →₀ _) ≃ _) = map_range.equiv f.symm hf' hf :=
equiv.ext $ λ x, rfl
end equiv
section zero_hom
variables [has_zero M] [has_zero N] [has_zero P]
/-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism
on functions. -/
@[simps]
def map_range.zero_hom (f : zero_hom M N) : zero_hom (α →₀ M) (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
map_zero' := map_range_zero }
@[simp]
lemma map_range.zero_hom_id :
map_range.zero_hom (zero_hom.id M) = zero_hom.id (α →₀ M) := zero_hom.ext map_range_id
lemma map_range.zero_hom_comp (f : zero_hom N P) (f₂ : zero_hom M N) :
(map_range.zero_hom (f.comp f₂) : zero_hom (α →₀ _) _) =
(map_range.zero_hom f).comp (map_range.zero_hom f₂) :=
zero_hom.ext $ map_range_comp _ _ _ _ _
end zero_hom
section add_monoid_hom
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
/--
Composition with a fixed additive homomorphism is itself an additive homomorphism on functions.
-/
@[simps]
def map_range.add_monoid_hom (f : M →+ N) : (α →₀ M) →+ (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
map_zero' := map_range_zero,
map_add' := λ a b, map_range_add f.map_add _ _ }
@[simp]
lemma map_range.add_monoid_hom_id :
map_range.add_monoid_hom (add_monoid_hom.id M) = add_monoid_hom.id (α →₀ M) :=
add_monoid_hom.ext map_range_id
lemma map_range.add_monoid_hom_comp (f : N →+ P) (f₂ : M →+ N) :
(map_range.add_monoid_hom (f.comp f₂) : (α →₀ _) →+ _) =
(map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) :=
add_monoid_hom.ext $ map_range_comp _ _ _ _ _
@[simp]
lemma map_range.add_monoid_hom_to_zero_hom (f : M →+ N) :
(map_range.add_monoid_hom f).to_zero_hom =
(map_range.zero_hom f.to_zero_hom : zero_hom (α →₀ _) _) :=
zero_hom.ext $ λ _, rfl
lemma map_range_multiset_sum (f : M →+ N) (m : multiset (α →₀ M)) :
map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum :=
(map_range.add_monoid_hom f : (α →₀ _) →+ _).map_multiset_sum _
lemma map_range_finset_sum (f : M →+ N) (s : finset ι) (g : ι → (α →₀ M)) :
map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) :=
(map_range.add_monoid_hom f : (α →₀ _) →+ _).map_sum _ _
/-- `finsupp.map_range.add_monoid_hom` as an equiv. -/
@[simps apply]
def map_range.add_equiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
inv_fun := (map_range f.symm f.symm.map_zero : (α →₀ N) → (α →₀ M)),
left_inv := λ x, begin
rw ←map_range_comp _ _ _ _; simp_rw add_equiv.symm_comp_self,
{ exact map_range_id _ },
{ refl },
end,
right_inv := λ x, begin
rw ←map_range_comp _ _ _ _; simp_rw add_equiv.self_comp_symm,
{ exact map_range_id _ },
{ refl },
end,
..(map_range.add_monoid_hom f.to_add_monoid_hom) }
@[simp]
lemma map_range.add_equiv_refl :
map_range.add_equiv (add_equiv.refl M) = add_equiv.refl (α →₀ M) :=
add_equiv.ext map_range_id
lemma map_range.add_equiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) :
(map_range.add_equiv (f.trans f₂) : (α →₀ _) ≃+ _) =
(map_range.add_equiv f).trans (map_range.add_equiv f₂) :=
add_equiv.ext $ map_range_comp _ _ _ _ _
@[simp] lemma map_range.add_equiv_symm (f : M ≃+ N) :
((map_range.add_equiv f).symm : (α →₀ _) ≃+ _) = map_range.add_equiv f.symm :=
add_equiv.ext $ λ x, rfl
@[simp]
lemma map_range.add_equiv_to_add_monoid_hom (f : M ≃+ N) :
(map_range.add_equiv f : (α →₀ _) ≃+ _).to_add_monoid_hom =
(map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ _) →+ _) :=
add_monoid_hom.ext $ λ _, rfl
@[simp]
lemma map_range.add_equiv_to_equiv (f : M ≃+ N) :
(map_range.add_equiv f).to_equiv =
(map_range.equiv f.to_equiv f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) :=
equiv.ext $ λ _, rfl
end add_monoid_hom
end finsupp
end map_range
/-! ### Declarations about `equiv_congr_left` -/
section equiv_congr_left
variable [has_zero M]
namespace finsupp
/-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equiv_map_domain f l : β →₀ M` (computably)
by mapping the support forwards and the function backwards. -/
def equiv_map_domain (f : α ≃ β) (l : α →₀ M) : β →₀ M :=
{ support := l.support.map f.to_embedding,
to_fun := λ a, l (f.symm a),
mem_support_to_fun := λ a, by simp only [finset.mem_map_equiv, mem_support_to_fun]; refl }
@[simp] lemma equiv_map_domain_apply (f : α ≃ β) (l : α →₀ M) (b : β) :
equiv_map_domain f l b = l (f.symm b) := rfl
lemma equiv_map_domain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) :
equiv_map_domain f.symm l a = l (f a) := rfl
@[simp] lemma equiv_map_domain_refl (l : α →₀ M) : equiv_map_domain (equiv.refl _) l = l :=
by ext x; refl
lemma equiv_map_domain_refl' : equiv_map_domain (equiv.refl _) = @id (α →₀ M) :=
by ext x; refl
lemma equiv_map_domain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) :
equiv_map_domain (f.trans g) l = equiv_map_domain g (equiv_map_domain f l) := by ext x; refl
lemma equiv_map_domain_trans' (f : α ≃ β) (g : β ≃ γ) :
@equiv_map_domain _ _ M _ (f.trans g) = equiv_map_domain g ∘ equiv_map_domain f := by ext x; refl
@[simp] lemma equiv_map_domain_single (f : α ≃ β) (a : α) (b : M) :
equiv_map_domain f (single a b) = single (f a) b :=
by ext x; simp only [single_apply, equiv.apply_eq_iff_eq_symm_apply, equiv_map_domain_apply]; congr
@[simp] lemma equiv_map_domain_zero {f : α ≃ β} : equiv_map_domain f (0 : α →₀ M) = (0 : β →₀ M) :=
by ext x; simp only [equiv_map_domain_apply, coe_zero, pi.zero_apply]
/-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection:
`(α →₀ M) ≃ (β →₀ M)`.
This is the finitely-supported version of `equiv.Pi_congr_left`. -/
def equiv_congr_left (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) :=
by refine ⟨equiv_map_domain f, equiv_map_domain f.symm, λ f, _, λ f, _⟩;
ext x; simp only [equiv_map_domain_apply, equiv.symm_symm,
equiv.symm_apply_apply, equiv.apply_symm_apply]
@[simp] lemma equiv_congr_left_apply (f : α ≃ β) (l : α →₀ M) :
equiv_congr_left f l = equiv_map_domain f l := rfl
@[simp] lemma equiv_congr_left_symm (f : α ≃ β) :
(@equiv_congr_left _ _ M _ f).symm = equiv_congr_left f.symm := rfl
end finsupp
end equiv_congr_left
section cast_finsupp
variables [has_zero M] (f : α →₀ M)
namespace nat
@[simp, norm_cast] lemma cast_finsupp_prod [comm_semiring R] (g : α → M → ℕ) :
(↑(f.prod g) : R) = f.prod (λ a b, ↑(g a b)) :=
nat.cast_prod _ _
@[simp, norm_cast] lemma cast_finsupp_sum [comm_semiring R] (g : α → M → ℕ) :
(↑(f.sum g) : R) = f.sum (λ a b, ↑(g a b)) :=
nat.cast_sum _ _
end nat
namespace int
@[simp, norm_cast] lemma cast_finsupp_prod [comm_ring R] (g : α → M → ℤ) :
(↑(f.prod g) : R) = f.prod (λ a b, ↑(g a b)) :=
int.cast_prod _ _
@[simp, norm_cast] lemma cast_finsupp_sum [comm_ring R] (g : α → M → ℤ) :
(↑(f.sum g) : R) = f.sum (λ a b, ↑(g a b)) :=
int.cast_sum _ _
end int
namespace rat
@[simp, norm_cast] lemma cast_finsupp_sum [division_ring R] [char_zero R] (g : α → M → ℚ) :
(↑(f.sum g) : R) = f.sum (λ a b, g a b) :=
cast_sum _ _
@[simp, norm_cast] lemma cast_finsupp_prod [field R] [char_zero R] (g : α → M → ℚ) :
(↑(f.prod g) : R) = f.prod (λ a b, g a b) :=
cast_prod _ _
end rat
end cast_finsupp
/-! ### Declarations about `map_domain` -/
namespace finsupp
section map_domain
variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M}
/-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M`
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 : α →₀ M) : β →₀ M :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (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) },
{ assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] }
end
lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (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
@[simp]
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,
{ intro, exact single_zero _ },
{ intro, exact single_add _ },
refine sum_congr (λ _ _, sum_single_index _),
{ exact single_zero _ }
end
@[simp]
lemma map_domain_single {f : α → β} {a : α} {b : M} : 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 : α →₀ M) = (0 : β →₀ M) :=
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 _)
@[simp] lemma map_domain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) :
map_domain f x a = x (f.symm a) :=
begin
conv_lhs { rw ←f.apply_symm_apply a },
exact map_domain_apply f.injective _ _,
end
/-- `finsupp.map_domain` is an `add_monoid_hom`. -/
@[simps]
def map_domain.add_monoid_hom (f : α → β) : (α →₀ M) →+ (β →₀ M) :=
{ to_fun := map_domain f,
map_zero' := map_domain_zero,
map_add' := λ _ _, map_domain_add}
@[simp]
lemma map_domain.add_monoid_hom_id : map_domain.add_monoid_hom id = add_monoid_hom.id (α →₀ M) :=
add_monoid_hom.ext $ λ _, map_domain_id
lemma map_domain.add_monoid_hom_comp (f : β → γ) (g : α → β) :
(map_domain.add_monoid_hom (f ∘ g) : (α →₀ M) →+ (γ →₀ M)) =
(map_domain.add_monoid_hom f).comp (map_domain.add_monoid_hom g) :=
add_monoid_hom.ext $ λ _, map_domain_comp
lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} :
map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) :=
(map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_sum _ _
lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
(map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _
lemma map_domain_support [decidable_eq β] {f : α → β} {s : α →₀ M} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $
by rw [finset.bUnion_singleton]; exact subset.refl _
lemma map_domain_apply' (S : set α) {f : α → β} (x : α →₀ M)
(hS : (x.support : set α) ⊆ S) (hf : set.inj_on f S) {a : α} (ha : a ∈ S) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum],
simp_rw single_apply,
have : ∀ (b : α) (ha1 : b ∈ x.support),
(if f b = f a then x b else 0) = if f b = f a then x a else 0,
{ intros b hb,
refine if_ctx_congr iff.rfl (λ hh, _) (λ _, rfl),
rw hf (hS hb) ha hh, },
conv in (ite _ _ _)
{ rw [this _ H], },
by_cases ha : a ∈ x.support,
{ rw [← finset.add_sum_erase _ _ ha, if_pos rfl],
convert add_zero _,
have : ∀ i ∈ x.support.erase a, f i ≠ f a,
{ intros i hi,
exact (finset.ne_of_mem_erase hi) ∘ (hf (hS $ finset.mem_of_mem_erase hi) (hS ha)), },
conv in (ite _ _ _)
{ rw if_neg (this x H), },
exact finset.sum_const_zero, },
{ rw [mem_support_iff, not_not] at ha,
simp [ha], }
end
lemma map_domain_support_of_inj_on [decidable_eq β] {f : α → β} (s : α →₀ M)
(hf : set.inj_on f s.support) : (map_domain f s).support = finset.image f s.support :=
finset.subset.antisymm map_domain_support $ begin
intros x hx,
simp only [mem_image, exists_prop, mem_support_iff, ne.def] at hx,
rcases hx with ⟨hx_w, hx_h_left, rfl⟩,
simp only [mem_support_iff, ne.def],
rw map_domain_apply' (↑s.support : set _) _ _ hf,
{ exact hx_h_left, },
{ simp only [mem_coe, mem_support_iff, ne.def],
exact hx_h_left, },
{ exact subset.refl _, },
end
lemma map_domain_support_of_injective [decidable_eq β] {f : α → β} (hf : function.injective f)
(s : α →₀ M) : (map_domain f s).support = finset.image f s.support :=
map_domain_support_of_inj_on s (hf.inj_on _)
@[to_additive]
lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M}
{h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) :
(map_domain f s).prod h = s.prod (λa m, h (f a) m) :=
(prod_sum_index h_zero h_add).trans $ prod_congr $ λ _ _, prod_single_index (h_zero _)
/--
A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`,
rather than separate linearity hypotheses.
-/
-- Note that in `prod_map_domain_index`, `M` is still an additive monoid,
-- so there is no analogous version in terms of `monoid_hom`.
@[simp]
lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β}
{s : α →₀ M} (h : β → M →+ N) :
(map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) :=
@sum_map_domain_index _ _ _ _ _ _ _ _
(λ b m, h b m)
(λ b, (h b).map_zero)
(λ b m₁ m₂, (h b).map_add _ _)
lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) :
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
@[to_additive]
lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M}
{h : β → M → N} (hf : function.injective f) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain]
lemma map_domain_injective {f : α → β} (hf : function.injective f) :
function.injective (map_domain f : (α →₀ M) → (β →₀ M)) :=
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
/-- When `f` is an embedding we have an embedding `(α →₀ ℕ) ↪ (β →₀ ℕ)` given by `map_domain`. -/
@[simps] def map_domain_embedding {α β : Type*} (f : α ↪ β) : (α →₀ ℕ) ↪ β →₀ ℕ :=
⟨finsupp.map_domain f, finsupp.map_domain_injective f.injective⟩
lemma map_domain.add_monoid_hom_comp_map_range [add_comm_monoid N] (f : α → β) (g : M →+ N) :
(map_domain.add_monoid_hom f).comp (map_range.add_monoid_hom g) =
(map_range.add_monoid_hom g).comp (map_domain.add_monoid_hom f) :=
by { ext, simp }
/-- When `g` preserves addition, `map_range` and `map_domain` commute. -/
lemma map_domain_map_range [add_comm_monoid N] (f : α → β) (v : α →₀ M) (g : M → N)
(h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) :
map_domain f (map_range g h0 v) = map_range g h0 (map_domain f v) :=
let g' : M →+ N := { to_fun := g, map_zero' := h0, map_add' := hadd} in
add_monoid_hom.congr_fun (map_domain.add_monoid_hom_comp_map_range f g') v
lemma sum_update_add [add_comm_monoid α] [add_comm_monoid β]
(f : ι →₀ α) (i : ι) (a : α) (g : ι → α → β) (hg : ∀ i, g i 0 = 0)
(hgg : ∀ (j : ι) (a₁ a₂ : α), g j (a₁ + a₂) = g j a₁ + g j a₂) :
(f.update i a).sum g + g i (f i) = f.sum g + g i a :=
begin
rw [update_eq_erase_add_single, sum_add_index' hg hgg],
conv_rhs { rw ← finsupp.update_self f i },
rw [update_eq_erase_add_single, sum_add_index' hg hgg, add_assoc, add_assoc],
congr' 1,
rw [add_comm, sum_single_index (hg _), sum_single_index (hg _)],
end
lemma map_domain_inj_on (S : set α) {f : α → β}
(hf : set.inj_on f S) :
set.inj_on (map_domain f : (α →₀ M) → (β →₀ M)) {w | (w.support : set α) ⊆ S} :=
begin
intros v₁ hv₁ v₂ hv₂ eq,
ext a,
by_cases h : a ∈ v₁.support ∪ v₂.support,
{ rw [← map_domain_apply' S _ hv₁ hf _, ← map_domain_apply' S _ hv₂ hf _, eq];
{ apply set.union_subset hv₁ hv₂,
exact_mod_cast h, }, },
{ simp only [decidable.not_or_iff_and_not, mem_union, not_not, mem_support_iff] at h,
simp [h], },
end
lemma equiv_map_domain_eq_map_domain {M} [add_comm_monoid M] (f : α ≃ β) (l : α →₀ M) :
equiv_map_domain f l = map_domain f l := by ext x; simp [map_domain_equiv_apply]
end map_domain
/-! ### Declarations about `comap_domain` -/
section comap_domain
/-- Given `f : α → β`, `l : β →₀ M` 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 `M` given by composing `l` with `f`. -/
@[simps support]
def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) :
α →₀ M :=
{ support := l.support.preimage f 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 [has_zero M] (f : α → β) (l : β →₀ M)
(hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) :
comap_domain f l hf a = l (f a) :=
rfl
lemma sum_comap_domain [has_zero M] [add_comm_monoid N]
(f : α → β) (l : β →₀ M) (g : β → M → N)
(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 only [sum, comap_domain_apply, (∘)],
simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))],
end
lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M]
(f : α → β) (l : β →₀ M) (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
section f_injective
section has_zero
variables [has_zero M]
/-- Note the `hif` argument is needed for this to work in `rw`. -/
@[simp] lemma comap_domain_zero (f : α → β)
(hif : set.inj_on f (f ⁻¹' ↑((0 : β →₀ M).support)) := set.inj_on_empty _) :
comap_domain f (0 : β →₀ M) hif = (0 : α →₀ M) :=
by { ext, refl }
@[simp] lemma comap_domain_single (f : α → β) (a : α) (m : M)
(hif : set.inj_on f (f ⁻¹' (single (f a) m).support)) :
comap_domain f (finsupp.single (f a) m) hif = finsupp.single a m :=
begin
rcases eq_or_ne m 0 with rfl | hm,
{ simp only [single_zero, comap_domain_zero] },
{ rw [eq_single_iff, comap_domain_apply, comap_domain_support, ← finset.coe_subset, coe_preimage,
support_single_ne_zero _ hm, coe_singleton, coe_singleton, single_eq_same],
rw [support_single_ne_zero _ hm, coe_singleton] at hif,
exact ⟨λ x hx, hif hx rfl hx, rfl⟩ }
end
end has_zero
section add_zero_class
variables [add_zero_class M] {f : α → β}
lemma comap_domain_add (v₁ v₂ : β →₀ M)
(hv₁ : set.inj_on f (f ⁻¹' ↑(v₁.support))) (hv₂ : set.inj_on f (f ⁻¹' ↑(v₂.support)))
(hv₁₂ : set.inj_on f (f ⁻¹' ↑((v₁ + v₂).support))) :
comap_domain f (v₁ + v₂) hv₁₂ = comap_domain f v₁ hv₁ + comap_domain f v₂ hv₂ :=
by { ext, simp only [comap_domain_apply, coe_add, pi.add_apply] }
/-- A version of `finsupp.comap_domain_add` that's easier to use. -/
lemma comap_domain_add_of_injective (hf : function.injective f) (v₁ v₂ : β →₀ M) :
comap_domain f (v₁ + v₂) (hf.inj_on _)
= comap_domain f v₁ (hf.inj_on _) + comap_domain f v₂ (hf.inj_on _) :=
comap_domain_add _ _ _ _ _
/-- `finsupp.comap_domain` is an `add_monoid_hom`. -/
@[simps]
def comap_domain.add_monoid_hom (hf : function.injective f) : (β →₀ M) →+ (α →₀ M) :=
{ to_fun := λ x, comap_domain f x (hf.inj_on _),
map_zero' := comap_domain_zero f,
map_add' := comap_domain_add_of_injective hf }
end add_zero_class
variables [add_comm_monoid M] (f : α → β)
lemma map_domain_comap_domain
(hf : function.injective f) (l : β →₀ M) (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 f_injective
end comap_domain
/-! ### Declarations about finitely supported functions whose support is an `option` type -/
section option
/-- Restrict a finitely supported function on `option α` to a finitely supported function on `α`. -/
def some [has_zero M] (f : option α →₀ M) : α →₀ M :=
f.comap_domain option.some (λ _, by simp)
@[simp] lemma some_apply [has_zero M] (f : option α →₀ M) (a : α) :
f.some a = f (option.some a) := rfl
@[simp] lemma some_zero [has_zero M] : (0 : option α →₀ M).some = 0 :=
by { ext, simp, }
@[simp] lemma some_add [add_comm_monoid M] (f g : option α →₀ M) : (f + g).some = f.some + g.some :=
by { ext, simp, }
@[simp] lemma some_single_none [has_zero M] (m : M) : (single none m : option α →₀ M).some = 0 :=
by { ext, simp, }
@[simp] lemma some_single_some [has_zero M] (a : α) (m : M) :
(single (option.some a) m : option α →₀ M).some = single a m :=
by { ext b, simp [single_apply], }
@[to_additive]
lemma prod_option_index [add_comm_monoid M] [comm_monoid N]
(f : option α →₀ M) (b : option α → M → N) (h_zero : ∀ o, b o 0 = 1)
(h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) :
f.prod b = b none (f none) * f.some.prod (λ a, b (option.some a)) :=
begin
apply induction_linear f,
{ simp [h_zero], },
{ intros f₁ f₂ h₁ h₂,
rw [finsupp.prod_add_index, h₁, h₂, some_add, finsupp.prod_add_index],
simp only [h_add, pi.add_apply, finsupp.coe_add],
rw mul_mul_mul_comm,
all_goals { simp [h_zero, h_add], }, },
{ rintros (_|a) m; simp [h_zero, h_add], }
end
lemma sum_option_index_smul [semiring R] [add_comm_monoid M] [module R M]
(f : option α →₀ R) (b : option α → M) :
f.sum (λ o r, r • b o) =
f none • b none + f.some.sum (λ a r, r • b (option.some a)) :=
f.sum_option_index _ (λ _, zero_smul _ _) (λ _ _ _, add_smul _ _ _)
end option
/-! ### Declarations about `filter` -/
section filter
section has_zero
variables [has_zero M] (p : α → Prop) (f : α →₀ M)
/--
`filter p f` is the finitely supported function that is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) (f : α →₀ M) : α →₀ M :=
{ to_fun := λ a, if p a then f a else 0,
support := f.support.filter (λ a, p a),
mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } }
lemma filter_apply (a : α) [D : decidable (p a)] : f.filter p a = if p a then f a else 0 :=
by rw subsingleton.elim D; refl
lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl
lemma filter_eq_zero_iff : f.filter p = 0 ↔ ∀ x, p x → f x = 0 :=
by simp only [fun_like.ext_iff, filter_eq_indicator, zero_apply, set.indicator_apply_eq_zero,
set.mem_set_of_eq]
lemma filter_eq_self_iff : f.filter p = f ↔ ∀ x, f x ≠ 0 → p x :=
by simp only [fun_like.ext_iff, filter_eq_indicator, set.indicator_apply_eq_self, set.mem_set_of_eq,
not_imp_comm]
@[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 [D : decidable_pred p] : (f.filter p).support = f.support.filter p :=
by rw subsingleton.elim D; refl
lemma filter_zero : (0 : α →₀ M).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos {a : α} {b : M} (h : p a) :
(single a b).filter p = single a b :=
(filter_eq_self_iff _ _).2 $ λ x hx, (single_apply_ne_zero.1 hx).1.symm ▸ h
@[simp] lemma filter_single_of_neg {a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 :=
(filter_eq_zero_iff _ _).2 $ λ x hpx, single_apply_eq_zero.2 $ λ hxa, absurd hpx (hxa.symm ▸ h)
@[to_additive] lemma prod_filter_index [comm_monoid N] (g : α → M → N) :
(f.filter p).prod g = ∏ x in (f.filter p).support, g x (f x) :=
begin
refine finset.prod_congr rfl (λ x hx, _),
rw [support_filter, finset.mem_filter] at hx,
rw [filter_apply_pos _ _ hx.2]
end
@[simp, to_additive] lemma prod_filter_mul_prod_filter_not [comm_monoid N] (g : α → M → N) :
(f.filter p).prod g * (f.filter (λ a, ¬ p a)).prod g = f.prod g :=
by simp_rw [prod_filter_index, support_filter, prod_filter_mul_prod_filter_not, finsupp.prod]
@[simp, to_additive] lemma prod_div_prod_filter [comm_group G] (g : α → M → G) :
f.prod g / (f.filter p).prod g = (f.filter (λ a, ¬p a)).prod g :=
div_eq_of_eq_mul' (prod_filter_mul_prod_filter_not _ _ _).symm
end has_zero
lemma filter_pos_add_filter_neg [add_zero_class M] (f : α →₀ M) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
coe_fn_injective $ set.indicator_self_add_compl {x | p x} f
end filter
/-! ### Declarations about `frange` -/
section frange
variables [has_zero M]
/-- `frange f` is the image of `f` on the support of `f`. -/
def frange (f : α →₀ M) : finset M := finset.image f f.support
theorem mem_frange {f : α →₀ M} {y : M} :
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 : α →₀ M} : (0:M) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : M} : 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
section zero
variables [has_zero M] {p : α → Prop}
/--
`subtype_domain p f` is the restriction of the finitely supported function `f` to subtype `p`. -/
def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) :=
⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain [D : decidable_pred p] {f : α →₀ M} :
(subtype_domain p f).support = f.support.subtype p :=
by rw subsingleton.elim D; refl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 :=
rfl
lemma subtype_domain_eq_zero_iff' {f : α →₀ M} :
f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 :=
by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff]
lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) :
f.subtype_domain p = 0 ↔ f = 0 :=
subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x,
if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩
@[to_additive]
lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M}
{h : α → M → N} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a 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 add_zero_class
variables [add_zero_class M] {p : α → Prop} {v v' : α →₀ M}
@[simp] lemma subtype_domain_add {v v' : α →₀ M} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
/-- `subtype_domain` but as an `add_monoid_hom`. -/
def subtype_domain_add_monoid_hom : (α →₀ M) →+ subtype p →₀ M :=
{ to_fun := subtype_domain p,
map_zero' := subtype_domain_zero,
map_add' := λ _ _, subtype_domain_add }
/-- `finsupp.filter` as an `add_monoid_hom`. -/
def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) :=
{ to_fun := filter p,
map_zero' := filter_zero p,
map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g }
@[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p :=
(filter_add_hom p).map_add v v'
end add_zero_class
section comm_monoid
variables [add_comm_monoid M] {p : α → Prop}
lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} :
(∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p :=
(subtype_domain_add_monoid_hom : _ →+ subtype p →₀ M).map_sum _ s
lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} :
(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 : ι → α →₀ M) :
(∑ a in s, f a).filter p = ∑ a in s, filter p (f a) :=
(filter_add_hom p : (α →₀ M) →+ _).map_sum f s
lemma filter_eq_sum (p : α → Prop) [D : decidable_pred p] (f : α →₀ M) :
f.filter p = ∑ i in f.support.filter p, single i (f i) :=
(f.filter p).sum_single.symm.trans $ finset.sum_congr (by rw subsingleton.elim D; refl) $
λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2]
end comm_monoid
section group
variables [add_group G] {p : α → Prop} {v v' : α →₀ G}
@[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma single_neg (a : α) (b : G) : single a (-b) = -single a b :=
(single_add_hom a : G →+ _).map_neg b
@[simp] lemma single_sub (a : α) (b₁ b₂ : G) : single a (b₁ - b₂) = single a b₁ - single a b₂ :=
(single_add_hom a : G →+ _).map_sub b₁ b₂
@[simp] lemma erase_neg (a : α) (f : α →₀ G) : erase a (-f) = -erase a f :=
(erase_add_hom a : (_ →₀ G) →+ _).map_neg f
@[simp] lemma erase_sub (a : α) (f₁ f₂ : α →₀ G) : erase a (f₁ - f₂) = erase a f₁ - erase a f₂ :=
(erase_add_hom a : (_ →₀ G) →+ _).map_sub f₁ f₂
@[simp] lemma filter_neg (p : α → Prop) (f : α →₀ G) : filter p (-f) = -filter p f :=
(filter_add_hom p : (_ →₀ G) →+ _).map_neg f
@[simp] lemma filter_sub (p : α → Prop) (f₁ f₂ : α →₀ G) :
filter p (f₁ - f₂) = filter p f₁ - filter p f₂ :=
(filter_add_hom p : (_ →₀ G) →+ _).map_sub f₁ f₂
end group
end subtype_domain
lemma mem_support_multiset_sum [add_comm_monoid M]
{s : multiset (α →₀ M)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).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 M]
{s : finset ι} {h : ι → α →₀ M} (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⟩
/-! ### Declarations about `curry` and `uncurry` -/
section curry_uncurry
variables [add_comm_monoid M] [add_comm_monoid N]
/-- 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 (f : (α × β) →₀ M) : α →₀ (β →₀ M) :=
f.sum $ λp c, single p.1 (single p.2 c)
@[simp] lemma curry_apply (f : (α × β) →₀ M) (x : α) (y : β) :
f.curry x y = f (x, y) :=
begin
have : ∀ (b : α × β), single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0,
{ rintros ⟨b₁, b₂⟩,
simp [single_apply, ite_apply, prod.ext_iff, ite_and],
split_ifs; simp [single_apply, *] },
rw [finsupp.curry, sum_apply, sum_apply, finsupp.sum, finset.sum_eq_single, this, if_pos rfl],
{ intros b hb b_ne, rw [this b, if_neg b_ne] },
{ intros hxy, rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] }
end
lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N)
(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 `M`,
`uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/
protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
/-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by
currying and uncurrying. -/
def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) :=
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 (f : α × β →₀ M) (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, 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 [decidable_eq α] (f : α × β →₀ M) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bUnion_singleton,
refine finset.subset.trans support_sum _,
refine finset.bUnion_mono (assume a _, support_single_subset)
end
end curry_uncurry
/-! ### Declarations about finitely supported functions whose support is a `sum` type -/
section sum
/-- `finsupp.sum_elim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/
def sum_elim {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ :=
on_finset
((f.support.map ⟨_, sum.inl_injective⟩) ∪ g.support.map ⟨_, sum.inr_injective⟩)
(sum.elim f g)
(λ ab h, by { cases ab with a b; simp only [sum.elim_inl, sum.elim_inr] at h; simpa })
@[simp] lemma coe_sum_elim {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) : ⇑(sum_elim f g) = sum.elim f g := rfl
lemma sum_elim_apply {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sum_elim f g x = sum.elim f g x := rfl
lemma sum_elim_inl {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) (x : α) : sum_elim f g (sum.inl x) = f x := rfl
lemma sum_elim_inr {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) (x : β) : sum_elim f g (sum.inr x) = g x := rfl
/-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`.
This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/
@[simps apply symm_apply]
def sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] :
((α ⊕ β) →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) :=
{ to_fun := λ f,
⟨f.comap_domain sum.inl (sum.inl_injective.inj_on _),
f.comap_domain sum.inr (sum.inr_injective.inj_on _)⟩,
inv_fun := λ fg, sum_elim fg.1 fg.2,
left_inv := λ f, by { ext ab, cases ab with a b; simp },
right_inv := λ fg, by { ext; simp } }
lemma fst_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ]
(f : (α ⊕ β) →₀ γ) (x : α) :
(sum_finsupp_equiv_prod_finsupp f).1 x = f (sum.inl x) :=
rfl
lemma snd_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ]
(f : (α ⊕ β) →₀ γ) (y : β) :
(sum_finsupp_equiv_prod_finsupp f).2 y = f (sum.inr y) :=
rfl
lemma sum_finsupp_equiv_prod_finsupp_symm_inl {α β γ : Type*} [has_zero γ]
(fg : (α →₀ γ) × (β →₀ γ)) (x : α) :
(sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x :=
rfl
lemma sum_finsupp_equiv_prod_finsupp_symm_inr {α β γ : Type*} [has_zero γ]
(fg : (α →₀ γ) × (β →₀ γ)) (y : β) :
(sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y :=
rfl
variables [add_monoid M]
/-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`.
This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/
@[simps apply symm_apply] def sum_finsupp_add_equiv_prod_finsupp {α β : Type*} :
((α ⊕ β) →₀ M) ≃+ (α →₀ M) × (β →₀ M) :=
{ map_add' :=
by { intros, ext;
simp only [equiv.to_fun_as_coe, prod.fst_add, prod.snd_add, add_apply,
snd_sum_finsupp_equiv_prod_finsupp, fst_sum_finsupp_equiv_prod_finsupp] },
.. sum_finsupp_equiv_prod_finsupp }
lemma fst_sum_finsupp_add_equiv_prod_finsupp {α β : Type*}
(f : (α ⊕ β) →₀ M) (x : α) :
(sum_finsupp_add_equiv_prod_finsupp f).1 x = f (sum.inl x) :=
rfl
lemma snd_sum_finsupp_add_equiv_prod_finsupp {α β : Type*}
(f : (α ⊕ β) →₀ M) (y : β) :
(sum_finsupp_add_equiv_prod_finsupp f).2 y = f (sum.inr y) :=
rfl
lemma sum_finsupp_add_equiv_prod_finsupp_symm_inl {α β : Type*}
(fg : (α →₀ M) × (β →₀ M)) (x : α) :
(sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x :=
rfl
lemma sum_finsupp_add_equiv_prod_finsupp_symm_inr {α β : Type*}
(fg : (α →₀ M) × (β →₀ M)) (y : β) :
(sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y :=
rfl
end sum
/-! ### Declarations about scalar multiplication -/
section
variables [has_zero M] [monoid_with_zero R] [mul_action_with_zero R M]
@[simp] lemma single_smul (a b : α) (f : α → M) (r : R) :
(single a r b) • (f a) = single a (r • f b) b :=
by by_cases a = b; simp [h]
end
section
variables [monoid G] [mul_action G α] [add_comm_monoid M]
/-- Scalar multiplication acting on the domain.
This is not an instance as it would conflict with the action on the range.
See the `instance_diamonds` test for examples of such conflicts. -/
def comap_has_smul : has_smul G (α →₀ M) :=
{ smul := λ g, map_domain ((•) g) }
local attribute [instance] comap_has_smul
lemma comap_smul_def (g : G) (f : α →₀ M) : g • f = map_domain ((•) g) f := rfl
@[simp] lemma comap_smul_single (g : G) (a : α) (b : M) :
g • single a b = single (g • a) b :=
map_domain_single
/-- `finsupp.comap_has_smul` is multiplicative -/
def comap_mul_action : mul_action G (α →₀ M) :=
{ one_smul := λ f, by rw [comap_smul_def, one_smul_eq_id, map_domain_id],
mul_smul := λ g g' f, by rw [comap_smul_def, comap_smul_def, comap_smul_def, ←comp_smul_left,
map_domain_comp], }
local attribute [instance] comap_mul_action
/-- `finsupp.comap_has_smul` is distributive -/
def comap_distrib_mul_action :
distrib_mul_action G (α →₀ M) :=
{ smul_zero := λ g, by { ext, dsimp [(•)], simp, },
smul_add := λ g f f', by { ext, dsimp [(•)], simp [map_domain_add], }, }
end
section
variables [group G] [mul_action G α] [add_comm_monoid M]
local attribute [instance] comap_has_smul comap_mul_action comap_distrib_mul_action
/-- When `G` is a group, `finsupp.comap_has_smul` acts by precomposition with the action of `g⁻¹`.
-/
@[simp] lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) :
(g • f) a = f (g⁻¹ • a) :=
begin
conv_lhs { rw ←smul_inv_smul g a },
exact map_domain_apply (mul_action.injective g) _ (g⁻¹ • a),
end
end
section
instance [monoid R] [add_monoid M] [distrib_mul_action R M] : has_smul R (α →₀ M) :=
⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
/-!
Throughout this section, some `monoid` and `semiring` arguments are specified with `{}` instead of
`[]`. See note [implicit instance arguments].
-/
@[simp] lemma coe_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
(b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl
lemma smul_apply {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
(b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl
lemma _root_.is_smul_regular.finsupp {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {k : R}
(hk : is_smul_regular M k) : is_smul_regular (α →₀ M) k :=
λ _ _ h, ext $ λ i, hk (congr_fun h i)
instance [monoid R] [nonempty α] [add_monoid M] [distrib_mul_action R M] [has_faithful_smul R M] :
has_faithful_smul R (α →₀ M) :=
{ eq_of_smul_eq_smul := λ r₁ r₂ h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ m : M,
by simpa using congr_fun (h (single a m)) a }
variables (α M)
instance [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (α →₀ M) :=
{ smul := (•),
smul_add := λ a x y, ext $ λ _, smul_add _ _ _,
one_smul := λ x, ext $ λ _, one_smul _ _,
mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _,
smul_zero := λ x, ext $ λ _, smul_zero _ }
instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M]
[has_smul R S] [is_scalar_tower R S M] :
is_scalar_tower R S (α →₀ M) :=
{ smul_assoc := λ r s a, ext $ λ _, smul_assoc _ _ _ }
instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M]
[smul_comm_class R S M] :
smul_comm_class R S (α →₀ M) :=
{ smul_comm := λ r s a, ext $ λ _, smul_comm _ _ _ }
instance [monoid R] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action Rᵐᵒᵖ M]
[is_central_scalar R M] : is_central_scalar R (α →₀ M) :=
{ op_smul_eq_smul := λ r a, ext $ λ _, op_smul_eq_smul _ _ }
instance [semiring R] [add_comm_monoid M] [module R M] : module R (α →₀ M) :=
{ smul := (•),
zero_smul := λ x, ext $ λ _, zero_smul _ _,
add_smul := λ a x y, ext $ λ _, add_smul _ _ _,
.. finsupp.distrib_mul_action α M }
variables {α M} {R}
lemma support_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {g : α →₀ M} :
(b • g).support ⊆ g.support :=
λ a, by { simp only [smul_apply, mem_support_iff, ne.def], exact mt (λ h, h.symm ▸ smul_zero _) }
@[simp]
lemma support_smul_eq [semiring R] [add_comm_monoid M] [module R M]
[no_zero_smul_divisors R M] {b : R} (hb : b ≠ 0) {g : α →₀ M} :
(b • g).support = g.support :=
finset.ext (λ a, by simp [finsupp.smul_apply, hb])
section
variables {p : α → Prop}
@[simp] lemma filter_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
{b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p :=
coe_fn_injective $ set.indicator_const_smul {x | p x} b v
end
lemma map_domain_smul {_ : monoid R} [add_comm_monoid M] [distrib_mul_action R M]
{f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v :=
map_domain_map_range _ _ _ _ (smul_add b)
@[simp] lemma smul_single {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
(c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) :=
map_range_single
@[simp] lemma smul_single' {_ : semiring R}
(c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) :=
smul_single _ _ _
lemma map_range_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
[add_monoid N] [distrib_mul_action R N]
{f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) :
map_range f hf (c • v) = c • map_range f hf v :=
begin
erw ←map_range_comp,
have : (f ∘ (•) c) = ((•) c ∘ f) := funext hsmul,
simp_rw this,
apply map_range_comp,
rw [function.comp_apply, smul_zero, hf],
end
lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b :=
by rw [smul_single, smul_eq_mul, mul_one]
lemma comap_domain_smul [add_monoid M] [monoid R] [distrib_mul_action R M]
{f : α → β} (r : R) (v : β →₀ M)
(hfv : set.inj_on f (f ⁻¹' ↑(v.support)))
(hfrv : set.inj_on f (f ⁻¹' ↑((r • v).support)) :=
hfv.mono $ set.preimage_mono $ finset.coe_subset.mpr support_smul):
comap_domain f (r • v) hfrv = r • comap_domain f v hfv :=
by { ext, refl }
/-- A version of `finsupp.comap_domain_smul` that's easier to use. -/
lemma comap_domain_smul_of_injective [add_monoid M] [monoid R] [distrib_mul_action R M]
{f : α → β} (hf : function.injective f) (r : R) (v : β →₀ M) :
comap_domain f (r • v) (hf.inj_on _) = r • comap_domain f v (hf.inj_on _) :=
comap_domain_smul _ _ _ _
end
lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M}
(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' [monoid R] [add_monoid M] [distrib_mul_action R M] [add_comm_monoid N]
{g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) :
(b • g).sum h = g.sum (λi c, h i (b • c)) :=
finsupp.sum_map_range_index h0
/-- A version of `finsupp.sum_smul_index'` for bundled additive maps. -/
lemma sum_smul_index_add_monoid_hom
[monoid R] [add_monoid M] [add_comm_monoid N] [distrib_mul_action R M]
{g : α →₀ M} {b : R} {h : α → M →+ N} :
(b • g).sum (λ a, h a) = g.sum (λ i c, h i (b • c)) :=
sum_map_range_index (λ i, (h i).map_zero)
instance [semiring R] [add_comm_monoid M] [module R M] {ι : Type*}
[no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) :=
⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext
(λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩
section distrib_mul_action_hom
variables [semiring R]
variables [add_comm_monoid M] [add_comm_monoid N] [distrib_mul_action R M] [distrib_mul_action R N]
/-- `finsupp.single` as a `distrib_mul_action_hom`.
See also `finsupp.lsingle` for the version as a linear map. -/
def distrib_mul_action_hom.single (a : α) : M →+[R] (α →₀ M) :=
{ map_smul' :=
λ k m, by simp only [add_monoid_hom.to_fun_eq_coe, single_add_hom_apply, smul_single],
.. single_add_hom a }
lemma distrib_mul_action_hom_ext {f g : (α →₀ M) →+[R] N}
(h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) :
f = g :=
distrib_mul_action_hom.to_add_monoid_hom_injective $ add_hom_ext h
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma distrib_mul_action_hom_ext' {f g : (α →₀ M) →+[R] N}
(h : ∀ (a : α), f.comp (distrib_mul_action_hom.single a) =
g.comp (distrib_mul_action_hom.single a)) :
f = g :=
distrib_mul_action_hom_ext $ λ a, distrib_mul_action_hom.congr_fun (h a)
end distrib_mul_action_hom
section
variables [has_zero R]
/-- The `finsupp` version of `pi.unique`. -/
instance unique_of_right [subsingleton R] : unique (α →₀ R) := fun_like.coe_injective.unique
/-- The `finsupp` version of `pi.unique_of_is_empty`. -/
instance unique_of_left [is_empty α] : unique (α →₀ R) := fun_like.coe_injective.unique
end
/-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` 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 α) (M : Type*) [add_comm_monoid M] :
{f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) :=
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 M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between
`α →₀ M` and `β →₀ M`.
This is `finsupp.equiv_congr_left` as an `add_equiv`. -/
@[simps apply]
protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) :=
{ to_fun := equiv_map_domain e,
inv_fun := equiv_map_domain e.symm,
left_inv := λ v, begin
simp only [← equiv_map_domain_trans, equiv.self_trans_symm],
exact equiv_map_domain_refl _
end,
right_inv := begin
assume v,
simp only [← equiv_map_domain_trans, equiv.symm_trans_self],
exact equiv_map_domain_refl _
end,
map_add' := λ a b, by simp only [equiv_map_domain_eq_map_domain]; exact map_domain_add }
@[simp] lemma dom_congr_refl [add_comm_monoid M] :
finsupp.dom_congr (equiv.refl α) = add_equiv.refl (α →₀ M) :=
add_equiv.ext $ λ _, equiv_map_domain_refl _
@[simp] lemma dom_congr_symm [add_comm_monoid M] (e : α ≃ β) :
(finsupp.dom_congr e).symm = (finsupp.dom_congr e.symm : (β →₀ M) ≃+ (α →₀ M)):=
add_equiv.ext $ λ _, rfl
@[simp] lemma dom_congr_trans [add_comm_monoid M] (e : α ≃ β) (f : β ≃ γ) :
(finsupp.dom_congr e).trans (finsupp.dom_congr f) =
(finsupp.dom_congr (e.trans f) : (α →₀ M) ≃+ _) :=
add_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm
end finsupp
namespace finsupp
/-! ### Declarations about sigma types -/
section sigma
variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M)
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and
an index element `i : ι`, `split l i` is the `i`th component of `l`,
a finitely supported function from `as i` to `M`.
This is the `finsupp` version of `sigma.curry`.
-/
def split (i : ι) : αs i →₀ M :=
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 N] (g : Π i, (αs i →₀ M) → N)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N :=
{ 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 N] (f : (Σ (i : ι), αs i) → M → N) :
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]
variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α]
/-- On a `fintype η`, `finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α`
and `Π j, (ιs j →₀ α)`.
This is the `finsupp` version of `equiv.Pi_curry`. -/
noncomputable def sigma_finsupp_equiv_pi_finsupp :
((Σ j, ιs j) →₀ α) ≃ Π j, (ιs j →₀ α) :=
{ to_fun := split,
inv_fun := λ f, on_finset
(finset.univ.sigma (λ j, (f j).support))
(λ ji, f ji.1 ji.2)
(λ g hg, finset.mem_sigma.mpr ⟨finset.mem_univ _, mem_support_iff.mpr hg⟩),
left_inv := λ f, by { ext, simp [split] },
right_inv := λ f, by { ext, simp [split] } }
@[simp] lemma sigma_finsupp_equiv_pi_finsupp_apply
(f : (Σ j, ιs j) →₀ α) (j i) :
sigma_finsupp_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl
/-- On a `fintype η`, `finsupp.split` is an additive equivalence between
`(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`.
This is the `add_equiv` version of `finsupp.sigma_finsupp_equiv_pi_finsupp`.
-/
noncomputable def sigma_finsupp_add_equiv_pi_finsupp
{α : Type*} {ιs : η → Type*} [add_monoid α] :
((Σ j, ιs j) →₀ α) ≃+ Π j, (ιs j →₀ α) :=
{ map_add' := λ f g, by { ext, simp },
.. sigma_finsupp_equiv_pi_finsupp }
@[simp] lemma sigma_finsupp_add_equiv_pi_finsupp_apply
{α : Type*} {ιs : η → Type*} [add_monoid α] (f : (Σ j, ιs j) →₀ α) (j i) :
sigma_finsupp_add_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl
end sigma
end finsupp
|
1a55d2d4b9f732494cf4528bdb34d29fef11e6c5 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/finset/sort.lean | 77366d111010399bc5d5d224d4b963a9bb50c305 | [] | 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 | 9,768 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.finset.lattice
import Mathlib.data.multiset.sort
import Mathlib.data.list.nodup_equiv_fin
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Construct a sorted list from a finset.
-/
namespace finset
/-! ### sort -/
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : finset α) : List α :=
multiset.sort r (val s)
@[simp] theorem sort_sorted {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : finset α) : list.sorted r (sort r s) :=
multiset.sort_sorted r (val s)
@[simp] theorem sort_eq {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : finset α) : ↑(sort r s) = val s :=
multiset.sort_eq r (val s)
@[simp] theorem sort_nodup {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : finset α) : list.nodup (sort r s) :=
eq.mpr (id (Eq._oldrec (Eq.refl (multiset.nodup ↑(sort r s))) (sort_eq r s))) (nodup s)
@[simp] theorem sort_to_finset {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] [DecidableEq α] (s : finset α) : list.to_finset (sort r s) = s :=
list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s)
@[simp] theorem mem_sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
multiset.mem_sort r
@[simp] theorem length_sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] {s : finset α} : list.length (sort r s) = card s :=
multiset.length_sort r
theorem sort_sorted_lt {α : Type u_1} [linear_order α] (s : finset α) : list.sorted Less (sort LessEq s) :=
list.pairwise.imp₂ lt_of_le_of_ne (sort_sorted LessEq s) (sort_nodup LessEq s)
theorem sorted_zero_eq_min'_aux {α : Type u_1} [linear_order α] (s : finset α) (h : 0 < list.length (sort LessEq s)) (H : finset.nonempty s) : list.nth_le (sort LessEq s) 0 h = min' s H := sorry
theorem sorted_zero_eq_min' {α : Type u_1} [linear_order α] {s : finset α} {h : 0 < list.length (sort LessEq s)} : list.nth_le (sort LessEq s) 0 h =
min' s (iff.mp card_pos (eq.mp (Eq._oldrec (Eq.refl (0 < list.length (sort LessEq s))) (length_sort LessEq)) h)) :=
sorted_zero_eq_min'_aux s h
(iff.mp card_pos (eq.mp (Eq._oldrec (Eq.refl (0 < list.length (sort LessEq s))) (length_sort LessEq)) h))
theorem min'_eq_sorted_zero {α : Type u_1} [linear_order α] {s : finset α} {h : finset.nonempty s} : min' s h =
list.nth_le (sort LessEq s) 0
(eq.mpr (id (Eq._oldrec (Eq.refl (0 < list.length (sort LessEq s))) (length_sort LessEq))) (iff.mpr card_pos h)) :=
Eq.symm
(sorted_zero_eq_min'_aux s
(eq.mpr (id (Eq._oldrec (Eq.refl (0 < list.length (sort LessEq s))) (length_sort LessEq))) (iff.mpr card_pos h)) h)
theorem sorted_last_eq_max'_aux {α : Type u_1} [linear_order α] (s : finset α) (h : list.length (sort LessEq s) - 1 < list.length (sort LessEq s)) (H : finset.nonempty s) : list.nth_le (sort LessEq s) (list.length (sort LessEq s) - 1) h = max' s H := sorry
theorem sorted_last_eq_max' {α : Type u_1} [linear_order α] {s : finset α} {h : list.length (sort LessEq s) - 1 < list.length (sort LessEq s)} : list.nth_le (sort LessEq s) (list.length (sort LessEq s) - 1) h =
max' s
(iff.mp card_pos
(lt_of_le_of_lt bot_le
(eq.mp
(Eq._oldrec (Eq.refl (list.length (sort LessEq s) - 1 < list.length (sort LessEq s))) (length_sort LessEq))
h))) := sorry
theorem max'_eq_sorted_last {α : Type u_1} [linear_order α] {s : finset α} {h : finset.nonempty s} : max' s h =
list.nth_le (sort LessEq s) (list.length (sort LessEq s) - 1)
(eq.mpr
(id
((fun (ᾰ ᾰ_1 : ℕ) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℕ) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg Less e_2) e_3)
(list.length (sort LessEq s) - 1) (card s - 1)
((fun (ᾰ ᾰ_1 : ℕ) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℕ) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg Sub.sub e_2) e_3)
(list.length (sort LessEq s)) (card s) (length_sort LessEq) 1 1 (Eq.refl 1))
(list.length (sort LessEq s)) (card s) (length_sort LessEq)))
(eq.mp (Eq.refl (card s - 1 < card s)) (nat.sub_lt (iff.mpr card_pos h) zero_lt_one))) := sorry
/-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_iso_of_fin s h`
is the increasing bijection between `fin k` and `s` as an `order_iso`. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of an iso `fin s.card ≃o s` to avoid
casting issues in further uses of this function. -/
def order_iso_of_fin {α : Type u_1} [linear_order α] (s : finset α) {k : ℕ} (h : card s = k) : fin k ≃o ↥↑s :=
order_iso.trans (fin.cast sorry)
(order_iso.trans (list.sorted.nth_le_iso (sort LessEq s) (sort_sorted_lt s))
(order_iso.set_congr (fun (x : α) => list.mem x (sort LessEq s)) ↑s sorry))
/-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_emb_of_fin s h` is
the increasing bijection between `fin k` and `s` as an order embedding into `α`. Here, `h` is a
proof that the cardinality of `s` is `k`. We use this instead of an embedding `fin s.card ↪o α` to
avoid casting issues in further uses of this function. -/
def order_emb_of_fin {α : Type u_1} [linear_order α] (s : finset α) {k : ℕ} (h : card s = k) : fin k ↪o α :=
rel_embedding.trans (order_iso.to_order_embedding (order_iso_of_fin s h))
(order_embedding.subtype fun (x : α) => x ∈ ↑s)
@[simp] theorem coe_order_iso_of_fin_apply {α : Type u_1} [linear_order α] (s : finset α) {k : ℕ} (h : card s = k) (i : fin k) : ↑(coe_fn (order_iso_of_fin s h) i) = coe_fn (order_emb_of_fin s h) i :=
rfl
theorem order_iso_of_fin_symm_apply {α : Type u_1} [linear_order α] (s : finset α) {k : ℕ} (h : card s = k) (x : ↥↑s) : ↑(coe_fn (order_iso.symm (order_iso_of_fin s h)) x) = list.index_of (↑x) (sort LessEq s) :=
rfl
theorem order_emb_of_fin_apply {α : Type u_1} [linear_order α] (s : finset α) {k : ℕ} (h : card s = k) (i : fin k) : coe_fn (order_emb_of_fin s h) i =
list.nth_le (sort LessEq s) (↑i)
(eq.mpr (id (Eq._oldrec (Eq.refl (↑i < list.length (sort LessEq s))) (length_sort LessEq)))
(eq.mpr (id (Eq._oldrec (Eq.refl (↑i < card s)) h)) (subtype.property i))) :=
rfl
@[simp] theorem order_emb_of_fin_mem {α : Type u_1} [linear_order α] (s : finset α) {k : ℕ} (h : card s = k) (i : fin k) : coe_fn (order_emb_of_fin s h) i ∈ s :=
subtype.property (coe_fn (order_iso_of_fin s h) i)
@[simp] theorem range_order_emb_of_fin {α : Type u_1} [linear_order α] (s : finset α) {k : ℕ} (h : card s = k) : set.range ⇑(order_emb_of_fin s h) = ↑s := sorry
/-- The bijection `order_emb_of_fin s h` sends `0` to the minimum of `s`. -/
theorem order_emb_of_fin_zero {α : Type u_1} [linear_order α] {s : finset α} {k : ℕ} (h : card s = k) (hz : 0 < k) : coe_fn (order_emb_of_fin s h) { val := 0, property := hz } = min' s (iff.mp card_pos (Eq.symm h ▸ hz)) := sorry
/-- The bijection `order_emb_of_fin s h` sends `k-1` to the maximum of `s`. -/
theorem order_emb_of_fin_last {α : Type u_1} [linear_order α] {s : finset α} {k : ℕ} (h : card s = k) (hz : 0 < k) : coe_fn (order_emb_of_fin s h) { val := k - 1, property := buffer.lt_aux_2 hz } =
max' s (iff.mp card_pos (Eq.symm h ▸ hz)) := sorry
/-- `order_emb_of_fin {a} h` sends any argument to `a`. -/
@[simp] theorem order_emb_of_fin_singleton {α : Type u_1} [linear_order α] (a : α) (i : fin 1) : coe_fn (order_emb_of_fin (singleton a) (card_singleton a)) i = a := sorry
/-- Any increasing map `f` from `fin k` to a finset of cardinality `k` has to coincide with
the increasing bijection `order_emb_of_fin s h`. -/
theorem order_emb_of_fin_unique {α : Type u_1} [linear_order α] {s : finset α} {k : ℕ} (h : card s = k) {f : fin k → α} (hfs : ∀ (x : fin k), f x ∈ s) (hmono : strict_mono f) : f = ⇑(order_emb_of_fin s h) := sorry
/-- An order embedding `f` from `fin k` to a finset of cardinality `k` has to coincide with
the increasing bijection `order_emb_of_fin s h`. -/
theorem order_emb_of_fin_unique' {α : Type u_1} [linear_order α] {s : finset α} {k : ℕ} (h : card s = k) {f : fin k ↪o α} (hfs : ∀ (x : fin k), coe_fn f x ∈ s) : f = order_emb_of_fin s h :=
rel_embedding.ext (iff.mp function.funext_iff (order_emb_of_fin_unique h hfs (order_embedding.strict_mono f)))
/-- Two parametrizations `order_emb_of_fin` of the same set take the same value on `i` and `j` if
and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l`
(although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/
@[simp] theorem order_emb_of_fin_eq_order_emb_of_fin_iff {α : Type u_1} [linear_order α] {k : ℕ} {l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : card s = k} {h' : card s = l} : coe_fn (order_emb_of_fin s h) i = coe_fn (order_emb_of_fin s h') j ↔ ↑i = ↑j := sorry
protected instance has_repr {α : Type u_1} [has_repr α] : has_repr (finset α) :=
has_repr.mk fun (s : finset α) => repr (val s)
|
2b6f9f66fa79b48dd6a80f666896da7a3f4b58fc | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/category_theory/category/default.lean | ac354f8090ac853de4a1465340bd968db3ebbe0f | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 7,586 | 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, Johannes Hölzl, Reid Barton
-/
import tactic.basic
/-!
# Categories
Defines a category, as a type class parametrised by the type of objects.
## Notations
Introduces notations
* `X ⟶ Y` for the morphism spaces,
* `f ≫ g` for composition in the 'arrows' convention.
Users may like to add `f ⊚ g` for composition in the standard convention, using
```lean
local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo
```
-/
-- The order in this declaration matters: v often needs to be explicitly specified while u often
-- can be omitted
universes v u
namespace category_theory
class has_hom (obj : Type u) : Type (max u (v+1)) :=
(hom : obj → obj → Type v)
infixr ` ⟶ `:10 := has_hom.hom -- type as \h
section prio
set_option default_priority 100 -- see Note [default priority]
class category_struct (obj : Type u)
extends has_hom.{v} obj : Type (max u (v+1)) :=
(id : Π X : obj, hom X X)
(comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z))
notation `𝟙` := category_struct.id -- type as \b1
infixr ` ≫ `:80 := category_struct.comp -- type as \gg
/--
The typeclass `category C` describes morphisms associated to objects of type `C`.
The universe levels of the objects and morphisms are unconstrained, and will often need to be
specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.)
-/
class category (obj : Type u)
extends category_struct.{v} obj : Type (max u (v+1)) :=
(id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously)
(comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously)
(assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z),
(f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously)
end prio
-- `restate_axiom` is a command that creates a lemma from a structure field,
-- discarding any auto_param wrappers from the type.
-- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".)
restate_axiom category.id_comp'
restate_axiom category.comp_id'
restate_axiom category.assoc'
attribute [simp] category.id_comp category.comp_id category.assoc
attribute [trans] category_struct.comp
/--
A `large_category` has objects in one universe level higher than the universe level of
the morphisms. It is useful for examples such as the category of types, or the category
of groups, etc.
-/
abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C
/--
A `small_category` has objects and morphisms in the same universe level.
-/
abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C
section
variables {C : Type u} [category.{v} C] {X Y Z : C}
/-- postcompose an equation between morphisms by another morphism -/
lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h :=
by rw w
/-- precompose an equation between morphisms by another morphism -/
lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h :=
by rw w
infixr ` =≫ `:80 := eq_whisker
infixr ` ≫= `:80 := whisker_eq
lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g :=
by { convert w (𝟙 Y), tidy }
lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g :=
by { convert w (𝟙 Y), tidy }
lemma eq_of_comp_left_eq' (f g : X ⟶ Y)
(w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g :=
eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h)
lemma eq_of_comp_right_eq' (f g : Y ⟶ Z)
(w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g :=
eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h)
lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X :=
by { convert w (𝟙 X), tidy }
lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X :=
by { convert w (𝟙 X), tidy }
lemma comp_dite {P : Prop} [decidable P]
{X Y Z : C} (f : X ⟶ Y) (g : P → (Y ⟶ Z)) (g' : ¬P → (Y ⟶ Z)) :
(f ≫ if h : P then g h else g' h) = (if h : P then f ≫ g h else f ≫ g' h) :=
by { split_ifs; refl }
lemma dite_comp {P : Prop} [decidable P]
{X Y Z : C} (f : P → (X ⟶ Y)) (f' : ¬P → (X ⟶ Y)) (g : Y ⟶ Z) :
(if h : P then f h else f' h) ≫ g = (if h : P then f h ≫ g else f' h ≫ g) :=
by { split_ifs; refl }
class epi (f : X ⟶ Y) : Prop :=
(left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h)
class mono (f : X ⟶ Y) : Prop :=
(right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h)
instance (X : C) : epi (𝟙 X) :=
⟨λ Z g h w, by simpa using w⟩
instance (X : C) : mono (𝟙 X) :=
⟨λ Z g h w, by simpa using w⟩
lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h :=
⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩
lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h :=
⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩
lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y :=
by { convert cancel_epi f, simp, }
lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X :=
by { convert cancel_mono f, simp, }
lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) :=
begin
split, intros Z a b w,
apply (cancel_epi g).1,
apply (cancel_epi f).1,
simpa using w,
end
lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) :=
begin
split, intros Z a b w,
apply (cancel_mono f).1,
apply (cancel_mono g).1,
simpa using w,
end
lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f :=
begin
split, intros Z a b w,
replace w := congr_arg (λ k, k ≫ g) w,
dsimp at w,
rw [category.assoc, category.assoc] at w,
exact (cancel_mono _).1 w,
end
lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) :
mono f :=
by { substI h, exact mono_of_mono f g, }
lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g :=
begin
split, intros Z a b w,
replace w := congr_arg (λ k, f ≫ k) w,
dsimp at w,
rw [←category.assoc, ←category.assoc] at w,
exact (cancel_epi _).1 w,
end
lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) :
epi g :=
by substI h; exact epi_of_epi f g
end
section
variable (C : Type u)
variable [category.{v} C]
universe u'
instance ulift_category : category.{v} (ulift.{u'} C) :=
{ hom := λ X Y, (X.down ⟶ Y.down),
id := λ X, 𝟙 X.down,
comp := λ _ _ _ f g, f ≫ g }
-- We verify that this previous instance can lift small categories to large categories.
example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance
end
end category_theory
open category_theory
namespace preorder
variables (α : Type u)
@[priority 100] -- see Note [lower instance priority]
instance small_category [preorder α] : small_category α :=
{ hom := λ U V, ulift (plift (U ≤ V)),
id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩,
comp := λ X Y Z f g, ⟨ ⟨ le_trans _ _ _ f.down.down g.down.down ⟩ ⟩ }
end preorder
|
37c9324188243f5ccf263d4379b8351cd35302aa | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/algebra/group/hom.lean | cd69b364f41dec958bfc64c84489532fc6305a19 | [
"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 | 8,762 | 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 algebra.group.to_additive algebra.group.basic
/-!
# 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.
## 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
-/
variables {M : Type*} {N : Type*} {P : Type*} -- monoids
{G : Type*} {H : Type*} -- groups
/-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/
structure add_monoid_hom (M : Type*) (N : Type*) [add_monoid M] [add_monoid N] :=
(to_fun : M → N)
(map_zero' : to_fun 0 = 0)
(map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y)
infixr ` →+ `:25 := add_monoid_hom
/-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/
@[to_additive add_monoid_hom]
structure monoid_hom (M : Type*) (N : Type*) [monoid M] [monoid N] :=
(to_fun : M → N)
(map_one' : to_fun 1 = 1)
(map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y)
infixr ` →* `:25 := monoid_hom
@[to_additive]
instance {M : Type*} {N : Type*} {mM : monoid M} {mN : monoid N} : has_coe_to_fun (M →* N) :=
⟨_, monoid_hom.to_fun⟩
namespace monoid_hom
variables {mM : monoid M} {mN : monoid N} {mP : monoid P}
variables [group G] [comm_group H]
include mM mN
@[simp, to_additive]
lemma coe_mk (f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl
@[to_additive]
lemma coe_inj ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext, to_additive]
lemma ext ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g :=
coe_inj (funext h)
attribute [ext] _root_.add_monoid_hom.ext
@[to_additive]
lemma ext_iff {f g : M →* N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
/-- If f is a monoid homomorphism then f 1 = 1. -/
@[simp, to_additive]
lemma map_one (f : M →* N) : f 1 = 1 := f.map_one'
/-- If f is a monoid homomorphism then f (a * b) = f a * f b. -/
@[simp, to_additive]
lemma map_mul (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
omit mN mM
/-- The identity map from a monoid to itself. -/
@[to_additive]
def id (M : Type*) [monoid M] : M →* M :=
{ to_fun := id,
map_one' := rfl,
map_mul' := λ _ _, rfl }
include mM mN mP
/-- Composition of monoid morphisms is a monoid morphism. -/
@[to_additive]
def comp (hnp : N →* P) (hmn : M →* N) : M →* P :=
{ to_fun := hnp ∘ hmn,
map_one' := by simp,
map_mul' := by simp }
@[simp, to_additive] lemma comp_apply (g : N →* P) (f : M →* N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of monoid homomorphisms is associative. -/
@[to_additive] lemma comp_assoc {Q : Type*} [monoid Q] (f : M →* N) (g : N →* P) (h : P →* Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
/-- Given a monoid homomorphism `f : M →* N` and a set `S ⊆ M` such that `f` maps elements of
`S` to invertible elements of `N`, any monoid homomorphism `g : N →* P` maps elements of
`f(S)` to invertible elements of `P`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and a set `S ⊆ M` such that `f` maps elements of `S` to invertible elements of `N`, any add_monoid homomorphism `g : N →+ P` maps elements of `f(S)` to invertible elements of `P`."]
lemma exists_inv_of_comp_exists_inv {S : set M} {f : M →* N}
(hf : ∀ s ∈ S, ∃ b, f s * b = 1) (g : N →* P) (s ∈ S) :
∃ x : P, g.comp f s * x = 1 :=
let ⟨c, hc⟩ := hf s H in ⟨g c, show g _ * _ = _, by rw [←g.map_mul, hc, g.map_one]⟩
@[to_additive]
lemma cancel_right {g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩
@[to_additive]
lemma cancel_left {g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩
omit mP
variables [mM] [mN]
@[to_additive]
protected def one : M →* N :=
{ to_fun := λ _, 1,
map_one' := rfl,
map_mul' := λ _ _, (one_mul 1).symm }
@[to_additive]
instance : has_one (M →* N) := ⟨monoid_hom.one⟩
@[to_additive]
instance : inhabited (M →* N) := ⟨1⟩
omit mM mN
/-- The product of two monoid morphisms is a monoid morphism if the target is commutative. -/
@[to_additive]
protected def mul {M N} {mM : monoid M} [comm_monoid N] (f g : M →* N) : M →* N :=
{ to_fun := λ m, f m * g m,
map_one' := show f 1 * g 1 = 1, by simp,
map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y),
rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }
@[to_additive]
instance {M N} {mM : monoid M} [comm_monoid N] : has_mul (M →* N) := ⟨monoid_hom.mul⟩
/-- (M →* N) is a comm_monoid if N is commutative. -/
@[to_additive add_comm_monoid]
instance {M N} [monoid M] [comm_monoid N] : comm_monoid (M →* N) :=
{ mul := (*),
mul_assoc := by intros; ext; apply mul_assoc,
one := 1,
one_mul := by intros; ext; apply one_mul,
mul_one := by intros; ext; apply mul_one,
mul_comm := by intros; ext; apply mul_comm }
/-- Group homomorphisms preserve inverse. -/
@[simp, to_additive]
theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ :=
eq_inv_of_mul_eq_one $ by rw [←f.map_mul, inv_mul_self, f.map_one]
/-- Group homomorphisms preserve division. -/
@[simp, to_additive]
theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) :
f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv]
/-- A group homomorphism is injective iff its kernel is trivial. -/
@[to_additive]
lemma injective_iff {G H} [group G] [group H] (f : G →* H) :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h _, by rw ← f.map_one; exact @h _ _,
λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← f.map_inv,
← f.map_mul] at hxy;
simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩
include mM
/-- Makes a group homomomorphism from a proof that the map preserves multiplication. -/
@[to_additive]
def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G :=
{ to_fun := f,
map_mul' := map_mul,
map_one' := mul_self_iff_eq_one.1 $ by rw [←map_mul, mul_one] }
omit mM
/-- The inverse of a monoid homomorphism is a monoid homomorphism if the target is
a commutative group.-/
@[to_additive]
protected def inv {M G} {mM : monoid M} [comm_group G] (f : M →* G) : M →* G :=
mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]
@[to_additive]
instance {M G} [monoid M] [comm_group G] : has_inv (M →* G) := ⟨monoid_hom.inv⟩
/-- (M →* G) is a comm_group if G is a comm_group -/
@[to_additive add_comm_group]
instance {M G} [monoid M] [comm_group G] : comm_group (M →* G) :=
{ inv := has_inv.inv,
mul_left_inv := by intros; ext; apply mul_left_inv,
..monoid_hom.comm_monoid }
end monoid_hom
/-- Additive group homomorphisms preserve subtraction. -/
@[simp] theorem add_monoid_hom.map_sub {G H} [add_group G] [add_group H] (f : G →+ H) (g h : G) :
f (g - h) = (f g) - (f h) := f.map_add_neg g h
|
834043b28ec262a46f458577e5d105eba127ca43 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/big_operators/multiset.lean | c5f6340148181dba0d0a490ef2e562d1b1fc4602 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 16,569 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.group_with_zero.power
import data.list.big_operators
import data.multiset.basic
/-!
# Sums and products over multisets
In this file we define products and sums indexed by multisets. This is later used to define products
and sums indexed by finite sets.
## Main declarations
* `multiset.prod`: `s.prod f` is the product of `f i` over all `i ∈ s`. Not to be mistaken with
the cartesian product `multiset.product`.
* `multiset.sum`: `s.sum f` is the sum of `f i` over all `i ∈ s`.
-/
variables {ι α β γ : Type*}
namespace multiset
section comm_monoid
variables [comm_monoid α] {s t : multiset α} {a : α} {m : multiset ι} {f g : ι → α}
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive "Sum of a multiset given a commutative additive monoid structure on `α`.
`sum {a, b, c} = a + b + c`"]
def prod : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
lemma prod_eq_foldr (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s :=
rfl
@[to_additive]
lemma prod_eq_foldl (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, norm_cast, to_additive] lemma coe_prod (l : list α) : prod ↑l = l.prod := prod_eq_foldl _
@[simp, to_additive]
lemma prod_to_list (s : multiset α) : s.to_list.prod = s.prod :=
begin
conv_rhs { rw ←coe_to_list s },
rw coe_prod,
end
@[simp, to_additive] lemma prod_zero : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
lemma prod_cons (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _
@[simp, to_additive]
lemma prod_erase [decidable_eq α] (h : a ∈ s) : a * (s.erase a).prod = s.prod :=
by rw [← s.coe_to_list, coe_erase, coe_prod, coe_prod, list.prod_erase (mem_to_list.2 h)]
@[simp, to_additive]
lemma prod_map_erase [decidable_eq ι] {a : ι} (h : a ∈ m) :
f a * ((m.erase a).map f).prod = (m.map f).prod :=
by rw [← m.coe_to_list, coe_erase, coe_map, coe_map, coe_prod, coe_prod,
list.prod_map_erase f (mem_to_list.2 h)]
@[simp, to_additive]
lemma prod_singleton (a : α) : prod {a} = a :=
by simp only [mul_one, prod_cons, ←cons_zero, eq_self_iff_true, prod_zero]
@[to_additive]
lemma prod_pair (a b : α) : ({a, b} : multiset α).prod = a * b :=
by rw [insert_eq_cons, prod_cons, prod_singleton]
@[simp, to_additive]
lemma prod_add (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
lemma prod_nsmul (m : multiset α) : ∀ (n : ℕ), (n • m).prod = m.prod ^ n
| 0 := by { rw [zero_nsmul, pow_zero], refl }
| (n + 1) :=
by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_nsmul n]
@[simp, to_additive] lemma prod_repeat (a : α) (n : ℕ) : (repeat a n).prod = a ^ n :=
by simp [repeat, list.prod_repeat]
@[to_additive]
lemma prod_map_eq_pow_single [decidable_eq ι] (i : ι) (hf : ∀ i' ≠ i, i' ∈ m → f i' = 1) :
(m.map f).prod = f i ^ m.count i :=
begin
induction m using quotient.induction_on with l,
simp [list.prod_map_eq_pow_single i f hf],
end
@[to_additive]
lemma prod_eq_pow_single [decidable_eq α] (a : α) (h : ∀ a' ≠ a, a' ∈ s → a' = 1) :
s.prod = a ^ (s.count a) :=
begin
induction s using quotient.induction_on with l,
simp [list.prod_eq_pow_single a h],
end
@[to_additive]
lemma pow_count [decidable_eq α] (a : α) : a ^ s.count a = (s.filter (eq a)).prod :=
by rw [filter_eq, prod_repeat]
@[to_additive]
lemma prod_hom [comm_monoid β] (s : multiset α) {F : Type*} [monoid_hom_class F α β] (f : F) :
(s.map f).prod = f s.prod :=
quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
lemma prod_hom' [comm_monoid β] (s : multiset ι) {F : Type*} [monoid_hom_class F α β] (f : F)
(g : ι → α) : (s.map $ λ i, f $ g i).prod = f (s.map g).prod :=
by { convert (s.map g).prod_hom f, exact (map_map _ _ _).symm }
@[to_additive]
lemma prod_hom₂ [comm_monoid β] [comm_monoid γ] (s : multiset ι) (f : α → β → γ)
(hf : ∀ a b c d, f (a * b) (c * d) = f a c * f b d) (hf' : f 1 1 = 1) (f₁ : ι → α) (f₂ : ι → β) :
(s.map $ λ i, f (f₁ i) (f₂ i)).prod = f (s.map f₁).prod (s.map f₂).prod :=
quotient.induction_on s $ λ l,
by simp only [l.prod_hom₂ f hf hf', quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
lemma prod_hom_rel [comm_monoid β] (s : multiset ι) {r : α → β → Prop} {f : ι → α} {g : ι → β}
(h₁ : r 1 1) (h₂ : ∀ ⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (s.map f).prod (s.map g).prod :=
quotient.induction_on s $ λ l,
by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
lemma prod_map_one : prod (m.map (λ i, (1 : α))) = 1 := by rw [map_const, prod_repeat, one_pow]
@[simp, to_additive]
lemma prod_map_mul : (m.map $ λ i, f i * g i).prod = (m.map f).prod * (m.map g).prod :=
m.prod_hom₂ (*) mul_mul_mul_comm (mul_one _) _ _
@[simp]
lemma prod_map_neg [has_distrib_neg α] (s : multiset α) :
(s.map has_neg.neg).prod = (-1) ^ s.card * s.prod :=
by { refine quotient.ind _ s, simp }
@[to_additive]
lemma prod_map_pow {n : ℕ} : (m.map $ λ i, f i ^ n).prod = (m.map f).prod ^ n :=
m.prod_hom' (pow_monoid_hom n : α →* α) f
@[to_additive]
lemma prod_map_prod_map (m : multiset β) (n : multiset γ) {f : β → γ → α} :
prod (m.map $ λ a, prod $ n.map $ λ b, f a b) = prod (n.map $ λ b, prod $ m.map $ λ a, f a b) :=
multiset.induction_on m (by simp) (λ a m ih, by simp [ih])
@[to_additive]
lemma prod_induction (p : α → Prop) (s : multiset α) (p_mul : ∀ a b, p a → p b → p (a * b))
(p_one : p 1) (p_s : ∀ a ∈ s, p a) :
p s.prod :=
begin
rw prod_eq_foldr,
exact foldr_induction (*) (λ x y z, by simp [mul_left_comm]) 1 p s p_mul p_one p_s,
end
@[to_additive]
lemma prod_induction_nonempty (p : α → Prop) (p_mul : ∀ a b, p a → p b → p (a * b))
(hs : s ≠ ∅) (p_s : ∀ a ∈ s, p a) :
p s.prod :=
begin
revert s,
refine multiset.induction _ _,
{ intro h,
exfalso,
simpa using h },
intros a s hs hsa hpsa,
rw prod_cons,
by_cases hs_empty : s = ∅,
{ simp [hs_empty, hpsa a] },
have hps : ∀ x, x ∈ s → p x, from λ x hxs, hpsa x (mem_cons_of_mem hxs),
exact p_mul a s.prod (hpsa a (mem_cons_self a s)) (hs hs_empty hps),
end
lemma dvd_prod : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
lemma prod_dvd_prod_of_le (h : s ≤ t) : s.prod ∣ t.prod :=
by { obtain ⟨z, rfl⟩ := exists_add_of_le h, simp only [prod_add, dvd_mul_right] }
end comm_monoid
lemma prod_dvd_prod_of_dvd [comm_monoid β] {S : multiset α} (g1 g2 : α → β)
(h : ∀ a ∈ S, g1 a ∣ g2 a) :
(multiset.map g1 S).prod ∣ (multiset.map g2 S).prod :=
begin
apply multiset.induction_on' S, { simp },
intros a T haS _ IH,
simp [mul_dvd_mul (h a haS) IH]
end
section add_comm_monoid
variables [add_comm_monoid α]
/-- `multiset.sum`, the sum of the elements of a multiset, promoted to a morphism of
`add_comm_monoid`s. -/
def sum_add_monoid_hom : multiset α →+ α :=
{ to_fun := sum,
map_zero' := sum_zero,
map_add' := sum_add }
@[simp] lemma coe_sum_add_monoid_hom : (sum_add_monoid_hom : multiset α → α) = sum := rfl
end add_comm_monoid
section comm_monoid_with_zero
variables [comm_monoid_with_zero α]
lemma prod_eq_zero {s : multiset α} (h : (0 : α) ∈ s) : s.prod = 0 :=
begin
rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩,
simp [hs', multiset.prod_cons]
end
variables [no_zero_divisors α] [nontrivial α] {s : multiset α}
lemma prod_eq_zero_iff : s.prod = 0 ↔ (0 : α) ∈ s :=
quotient.induction_on s $ λ l, by { rw [quot_mk_to_coe, coe_prod], exact list.prod_eq_zero_iff }
lemma prod_ne_zero (h : (0 : α) ∉ s) : s.prod ≠ 0 := mt prod_eq_zero_iff.1 h
end comm_monoid_with_zero
section division_comm_monoid
variables [division_comm_monoid α] {m : multiset ι} {f g : ι → α}
@[to_additive] lemma prod_map_inv' (m : multiset α) : (m.map has_inv.inv).prod = m.prod⁻¹ :=
m.prod_hom (inv_monoid_hom : α →* α)
@[simp, to_additive] lemma prod_map_inv : (m.map $ λ i, (f i)⁻¹).prod = (m.map f).prod ⁻¹ :=
by { convert (m.map f).prod_map_inv', rw map_map }
@[simp, to_additive]
lemma prod_map_div : (m.map $ λ i, f i / g i).prod = (m.map f).prod / (m.map g).prod :=
m.prod_hom₂ (/) mul_div_mul_comm (div_one _) _ _
@[to_additive]
lemma prod_map_zpow {n : ℤ} : (m.map $ λ i, f i ^ n).prod = (m.map f).prod ^ n :=
by { convert (m.map f).prod_hom (zpow_group_hom _ : α →* α), rw map_map, refl }
end division_comm_monoid
section non_unital_non_assoc_semiring
variables [non_unital_non_assoc_semiring α] {a : α} {s : multiset ι} {f : ι → α}
lemma _root_.commute.multiset_sum_right (s : multiset α) (a : α) (h : ∀ b ∈ s, commute a b) :
commute a s.sum :=
begin
induction s using quotient.induction_on,
rw [quot_mk_to_coe, coe_sum],
exact commute.list_sum_right _ _ h,
end
lemma _root_.commute.multiset_sum_left (s : multiset α) (b : α) (h : ∀ a ∈ s, commute a b) :
commute s.sum b :=
(commute.multiset_sum_right _ _ $ λ a ha, (h _ ha).symm).symm
lemma sum_map_mul_left : sum (s.map (λ i, a * f i)) = a * sum (s.map f) :=
multiset.induction_on s (by simp) (λ i s ih, by simp [ih, mul_add])
lemma sum_map_mul_right : sum (s.map (λ i, f i * a)) = sum (s.map f) * a :=
multiset.induction_on s (by simp) (λ a s ih, by simp [ih, add_mul])
end non_unital_non_assoc_semiring
section semiring
variables [semiring α]
lemma dvd_sum {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum :=
multiset.induction_on s (λ _, dvd_zero _)
(λ x s ih h, by { rw sum_cons, exact dvd_add
(h _ (mem_cons_self _ _)) (ih $ λ y hy, h _ $ mem_cons.2 $ or.inr hy) })
end semiring
/-! ### Order -/
section ordered_comm_monoid
variables [ordered_comm_monoid α] {s t : multiset α} {a : α}
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le : (∀ x ∈ s, (1 : α) ≤ x) → 1 ≤ s.prod :=
quotient.induction_on s $ λ l hl, by simpa using list.one_le_prod_of_one_le hl
@[to_additive]
lemma single_le_prod : (∀ x ∈ s, (1 : α) ≤ x) → ∀ x ∈ s, x ≤ s.prod :=
quotient.induction_on s $ λ l hl x hx, by simpa using list.single_le_prod hl x hx
@[to_additive sum_le_card_nsmul]
lemma prod_le_pow_card (s : multiset α) (n : α) (h : ∀ x ∈ s, x ≤ n) : s.prod ≤ n ^ s.card :=
begin
induction s using quotient.induction_on,
simpa using list.prod_le_pow_card _ _ h,
end
@[to_additive all_zero_of_le_zero_le_of_sum_eq_zero]
lemma all_one_of_le_one_le_of_prod_eq_one :
(∀ x ∈ s, (1 : α) ≤ x) → s.prod = 1 → ∀ x ∈ s, x = (1 : α) :=
begin
apply quotient.induction_on s,
simp only [quot_mk_to_coe, coe_prod, mem_coe],
exact λ l, list.all_one_of_le_one_le_of_prod_eq_one,
end
@[to_additive]
lemma prod_le_prod_of_rel_le (h : s.rel (≤) t) : s.prod ≤ t.prod :=
begin
induction h with _ _ _ _ rh _ rt,
{ refl },
{ rw [prod_cons, prod_cons],
exact mul_le_mul' rh rt }
end
@[to_additive]
lemma prod_map_le_prod_map {s : multiset ι} (f : ι → α) (g : ι → α) (h : ∀ i, i ∈ s → f i ≤ g i) :
(s.map f).prod ≤ (s.map g).prod :=
prod_le_prod_of_rel_le $ rel_map.2 $ rel_refl_of_refl_on h
@[to_additive]
lemma prod_map_le_prod (f : α → α) (h : ∀ x, x ∈ s → f x ≤ x) : (s.map f).prod ≤ s.prod :=
prod_le_prod_of_rel_le $ rel_map_left.2 $ rel_refl_of_refl_on h
@[to_additive]
lemma prod_le_prod_map (f : α → α) (h : ∀ x, x ∈ s → x ≤ f x) : s.prod ≤ (s.map f).prod :=
@prod_map_le_prod αᵒᵈ _ _ f h
@[to_additive card_nsmul_le_sum]
lemma pow_card_le_prod (h : ∀ x ∈ s, a ≤ x) : a ^ s.card ≤ s.prod :=
by { rw [←multiset.prod_repeat, ←multiset.map_const], exact prod_map_le_prod _ h }
end ordered_comm_monoid
lemma prod_nonneg [ordered_comm_semiring α] {m : multiset α} (h : ∀ a ∈ m, (0 : α) ≤ a) :
0 ≤ m.prod :=
begin
revert h,
refine m.induction_on _ _,
{ rintro -, rw prod_zero, exact zero_le_one },
intros a s hs ih,
rw prod_cons,
exact mul_nonneg (ih _ $ mem_cons_self _ _) (hs $ λ a ha, ih _ $ mem_cons_of_mem ha),
end
@[to_additive]
lemma prod_eq_one_iff [canonically_ordered_monoid α] {m : multiset α} :
m.prod = 1 ↔ ∀ x ∈ m, x = (1 : α) :=
quotient.induction_on m $ λ l, by simpa using list.prod_eq_one_iff l
/-- Slightly more general version of `multiset.prod_eq_one_iff` for a non-ordered `monoid` -/
@[to_additive "Slightly more general version of `multiset.sum_eq_zero_iff`
for a non-ordered `add_monoid`"]
lemma prod_eq_one [comm_monoid α] {m : multiset α} (h : ∀ x ∈ m, x = (1 : α)) : m.prod = 1 :=
begin
induction m using quotient.induction_on with l,
simp [list.prod_eq_one h],
end
@[to_additive]
lemma le_prod_of_mem [canonically_ordered_monoid α] {m : multiset α} {a : α} (h : a ∈ m) :
a ≤ m.prod :=
begin
obtain ⟨m', rfl⟩ := exists_cons_of_mem h,
rw [prod_cons],
exact _root_.le_mul_right (le_refl a),
end
@[to_additive le_sum_of_subadditive_on_pred]
lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (p : α → Prop) (h_one : f 1 = 1) (hp_one : p 1)
(h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b)
(hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hps : ∀ a, a ∈ s → p a) :
f s.prod ≤ (s.map f).prod :=
begin
revert s,
refine multiset.induction _ _,
{ simp [le_of_eq h_one] },
intros a s hs hpsa,
have hps : ∀ x, x ∈ s → p x, from λ x hx, hpsa x (mem_cons_of_mem hx),
have hp_prod : p s.prod, from prod_induction p s hp_mul hp_one hps,
rw [prod_cons, map_cons, prod_cons],
exact (h_mul a s.prod (hpsa a (mem_cons_self a s)) hp_prod).trans (mul_le_mul_left' (hs hps) _),
end
@[to_additive le_sum_of_subadditive]
lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_one : f 1 = 1) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) :
f s.prod ≤ (s.map f).prod :=
le_prod_of_submultiplicative_on_pred f (λ i, true) h_one trivial (λ x y _ _ , h_mul x y) (by simp)
s (by simp)
@[to_additive le_sum_nonempty_of_subadditive_on_pred]
lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (p : α → Prop) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b)
(hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hs_nonempty : s ≠ ∅)
(hs : ∀ a, a ∈ s → p a) :
f s.prod ≤ (s.map f).prod :=
begin
revert s,
refine multiset.induction _ _,
{ intro h,
exfalso,
exact h rfl },
rintros a s hs hsa_nonempty hsa_prop,
rw [prod_cons, map_cons, prod_cons],
by_cases hs_empty : s = ∅,
{ simp [hs_empty] },
have hsa_restrict : (∀ x, x ∈ s → p x), from λ x hx, hsa_prop x (mem_cons_of_mem hx),
have hp_sup : p s.prod,
from prod_induction_nonempty p hp_mul hs_empty hsa_restrict,
have hp_a : p a, from hsa_prop a (mem_cons_self a s),
exact (h_mul a _ hp_a hp_sup).trans (mul_le_mul_left' (hs hs_empty hsa_restrict) _),
end
@[to_additive le_sum_nonempty_of_subadditive]
lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) (hs_nonempty : s ≠ ∅) :
f s.prod ≤ (s.map f).prod :=
le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) s
hs_nonempty (by simp)
@[simp] lemma sum_map_singleton (s : multiset α) : (s.map (λ a, ({a} : multiset α))).sum = s :=
multiset.induction_on s (by simp) (by simp)
lemma abs_sum_le_sum_abs [linear_ordered_add_comm_group α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
end multiset
@[to_additive]
lemma map_multiset_prod [comm_monoid α] [comm_monoid β] {F : Type*} [monoid_hom_class F α β]
(f : F) (s : multiset α) : f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
@[to_additive]
protected lemma monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β)
(s : multiset α) : f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
|
7356c51df54d5cc87898aee2a65246578859a1eb | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/algebra/category/Mon/colimits.lean | f851db288530a60278e10337f07cf2b2b37511b2 | [
"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 | 7,762 | 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.Mon.basic
import category_theory.limits.limits
/-!
# The category of monoids has all colimits.
We do this construction knowing nothing about monoids.
In particular, I want to claim that this file could be produced by a python script
that just looks at the output of `#print monoid`:
-- structure monoid : Type u → Type u
-- fields:
-- monoid.mul : Π {α : Type u} [c : monoid α], α → α → α
-- monoid.mul_assoc : ∀ {α : Type u} [c : monoid α] (a b c_1 : α), a * b * c_1 = a * (b * c_1)
-- monoid.one : Π (α : Type u) [c : monoid α], α
-- monoid.one_mul : ∀ {α : Type u} [c : monoid α] (a : α), 1 * a = a
-- monoid.mul_one : ∀ {α : Type u} [c : monoid α] (a : α), a * 1 = a
and if we'd fed it the output of `#print comm_ring`, this file would instead build
colimits of commutative rings.
A slightly bolder claim is that we could do this with tactics, as well.
-/
universes v
open category_theory
open category_theory.limits
namespace Mon.colimits
/-!
We build the colimit of a diagram in `Mon` by constructing the
free monoid on the disjoint union of all the monoids in the diagram,
then taking the quotient by the monoid laws within each monoid,
and the identifications given by the morphisms in the diagram.
-/
variables {J : Type v} [small_category J] (F : J ⥤ Mon.{v})
/--
An inductive type representing all monoid 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
| one {} : prequotient
| mul : prequotient → prequotient → prequotient
instance : inhabited (prequotient F) := ⟨prequotient.one⟩
open prequotient
/--
The relation on `prequotient` saying when two expressions are equal
because of the monoid 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`
| mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y))
| one : Π (j), relation (of j 1) one
-- Then one relation per argument of each operation
| mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y)
| mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y')
-- And one relation per axiom
| mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z))
| one_mul : Π (x), relation (mul one x) x
| mul_one : Π (x), relation (mul x one) x
/--
The setoid corresponding to monoid expressions modulo monoid 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 `Mon`.
-/
@[derive inhabited]
def colimit_type : Type v := quotient (colimit_setoid F)
instance monoid_colimit_type : monoid (colimit_type F) :=
{ mul :=
begin
fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)),
{ intro x,
fapply @quot.lift,
{ intro y,
exact quot.mk _ (mul x y) },
{ intros y y' r,
apply quot.sound,
exact relation.mul_2 _ _ _ r } },
{ intros x x' r,
funext y,
induction y,
dsimp,
apply quot.sound,
{ exact relation.mul_1 _ _ _ r },
{ refl } },
end,
one :=
begin
exact quot.mk _ one
end,
mul_assoc := λ x y z,
begin
induction x,
induction y,
induction z,
dsimp,
apply quot.sound,
apply relation.mul_assoc,
refl,
refl,
refl,
end,
one_mul := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.one_mul,
refl,
end,
mul_one := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.mul_one,
refl,
end }
@[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl
@[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl
/-- The bundled monoid giving the colimit of a diagram. -/
def colimit : Mon := ⟨colimit_type F, by apply_instance⟩
/-- The function from a given monoid in the diagram to the colimit monoid. -/
def cocone_fun (j : J) (x : F.obj j) : colimit_type F :=
quot.mk _ (of j x)
/-- The monoid homomorphism from a given monoid in the diagram to the colimit monoid. -/
def cocone_morphism (j : J) : F.obj j ⟶ colimit F :=
{ to_fun := cocone_fun F j,
map_one' := quot.sound (relation.one _ _),
map_mul' := λ x y, quot.sound (relation.mul _ _ _) }
@[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 monoid. -/
def colimit_cocone : cocone F :=
{ X := colimit F,
ι :=
{ app := cocone_morphism F, } }.
/-- The function from the free monoid 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
| one := 1
| (mul x y) := desc_fun_lift x * desc_fun_lift y
/-- The function from the colimit monoid 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
{ rw cocone.naturality_concrete, },
-- mul
{ rw monoid_hom.map_mul ((s.ι).app r_j) },
-- one
{ erw monoid_hom.map_one ((s.ι).app r), refl },
-- mul_1
{ rw r_ih, },
-- mul_2
{ rw r_ih, },
-- mul_assoc
{ rw mul_assoc, },
-- one_mul
{ rw one_mul, },
-- mul_one
{ rw mul_one, } }
end
/-- The monoid homomorphism from the colimit monoid to the cone point of any other cocone. -/
@[simps]
def desc_morphism (s : cocone F) : colimit F ⟶ s.X :=
{ to_fun := desc_fun F s,
map_one' := rfl,
map_mul' := λ x y, by { induction x; induction y; refl }, }
/-- Evidence that the proposed colimit is the colimit. -/
def colimit_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 only [desc_morphism, quot_one],
erw monoid_hom.map_one m,
refl, },
{ simp only [desc_morphism, quot_mul],
erw monoid_hom.map_mul m,
rw [x_ih_a, x_ih_a_1],
refl, },
refl
end }.
instance has_colimits_Mon : has_colimits.{v} Mon.{v} :=
{ has_colimits_of_shape := λ J 𝒥,
{ has_colimit := λ F, by exactI
{ cocone := colimit_cocone F,
is_colimit := colimit_is_colimit F } } }
end Mon.colimits
|
1a706c20d7ff639c030995ec2fadd31b13b543df | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/opposite.lean | ee9b41888985db0ecbe7fcc0e48bd7772c769dbc | [
"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 | 4,644 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Reid Barton, Simon Hudon, Kenny Lau
-/
import data.equiv.basic
/-!
# Opposites
In this file we define a type synonym `opposite α := α`, denoted by `αᵒᵖ` and two synonyms for the
identity map, `op : α → αᵒᵖ` and `unop : αᵒᵖ → α`. The type tag `αᵒᵖ` is used with two different
meanings:
- if `α` is a category, then `αᵒᵖ` is the opposite category, with all arrows reversed;
- if `α` is a monoid (group, etc), then `αᵒᵖ` is the opposite monoid (group, etc) with
`op (x * y) = op x * op y`.
-/
universes v u -- morphism levels before object levels. See note [category_theory universes].
variable (α : Sort u)
/-- The type of objects of the opposite of `α`; used to define the opposite category or group.
In order to avoid confusion between `α` and its opposite type, we
set up the type of objects `opposite α` using the following pattern,
which will be repeated later for the morphisms.
1. Define `opposite α := α`.
2. Define the isomorphisms `op : α → opposite α`, `unop : opposite α → α`.
3. Make the definition `opposite` irreducible.
This has the following consequences.
* `opposite α` and `α` are distinct types in the elaborator, so you
must use `op` and `unop` explicitly to convert between them.
* Both `unop (op X) = X` and `op (unop X) = X` are definitional
equalities. Notably, every object of the opposite category is
definitionally of the form `op X`, which greatly simplifies the
definition of the structure of the opposite category, for example.
(If Lean supported definitional eta equality for records, we could
achieve the same goals using a structure with one field.)
-/
def opposite : Sort u := α
-- Use a high right binding power (like that of postfix ⁻¹) so that, for example,
-- `presheaf Cᵒᵖ` parses as `presheaf (Cᵒᵖ)` and not `(presheaf C)ᵒᵖ`.
notation α `ᵒᵖ`:std.prec.max_plus := opposite α
namespace opposite
variables {α}
/-- The canonical map `α → αᵒᵖ`. -/
@[pp_nodot]
def op : α → αᵒᵖ := id
/-- The canonical map `αᵒᵖ → α`. -/
@[pp_nodot]
def unop : αᵒᵖ → α := id
lemma op_injective : function.injective (op : α → αᵒᵖ) := λ _ _, id
lemma unop_injective : function.injective (unop : αᵒᵖ → α) := λ _ _, id
@[simp] lemma op_inj_iff (x y : α) : op x = op y ↔ x = y := iff.rfl
@[simp] lemma unop_inj_iff (x y : αᵒᵖ) : unop x = unop y ↔ x = y := iff.rfl
@[simp] lemma op_unop (x : αᵒᵖ) : op (unop x) = x := rfl
@[simp] lemma unop_op (x : α) : unop (op x) = x := rfl
attribute [irreducible] opposite
/-- The type-level equivalence between a type and its opposite. -/
def equiv_to_opposite : α ≃ αᵒᵖ :=
{ to_fun := op,
inv_fun := unop,
left_inv := unop_op,
right_inv := op_unop }
@[simp]
lemma equiv_to_opposite_coe : (equiv_to_opposite : α → αᵒᵖ) = op := rfl
@[simp]
lemma equiv_to_opposite_symm_coe : (equiv_to_opposite.symm : αᵒᵖ → α) = unop := rfl
lemma op_eq_iff_eq_unop {x : α} {y} : op x = y ↔ x = unop y :=
equiv_to_opposite.apply_eq_iff_eq_symm_apply
lemma unop_eq_iff_eq_op {x} {y : α} : unop x = y ↔ x = op y :=
equiv_to_opposite.symm.apply_eq_iff_eq_symm_apply
instance [inhabited α] : inhabited αᵒᵖ := ⟨op (default _)⟩
/-- A recursor for `opposite`. Use as `induction x using opposite.rec`. -/
@[simp]
protected def rec {F : Π (X : αᵒᵖ), Sort v} (h : Π X, F (op X)) : Π X, F X :=
λ X, h (unop X)
end opposite
namespace tactic
open opposite
namespace op_induction
/-- Test if `e : expr` is of type `opposite α` for some `α`. -/
meta def is_opposite (e : expr) : tactic bool :=
do t ← infer_type e,
`(opposite _) ← whnf t | return ff,
return tt
/-- Find the first hypothesis of type `opposite _`. Fail if no such hypothesis exist in the local
context. -/
meta def find_opposite_hyp : tactic name :=
do lc ← local_context,
h :: _ ← lc.mfilter $ is_opposite | fail "No hypotheses of the form Xᵒᵖ",
return h.local_pp_name
end op_induction
open op_induction
/-- A version of `induction x using opposite.rec` which finds the appropriate hypothesis
automatically, for use with `local attribute [tidy] op_induction'`. This is necessary because
`induction x` is not able to deduce that `opposite.rec` should be used. -/
meta def op_induction' : tactic unit :=
do h ← find_opposite_hyp,
h' ← tactic.get_local h,
tactic.induction' h' [] `opposite.rec
end tactic
|
dbeaf17153d737b4cfe13adefbe329aeda3fb260 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/lie/base_change.lean | 11c0631716dbd191818ff1be7d91f851df409d4d | [
"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 | 5,849 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.algebra.restrict_scalars
import algebra.lie.tensor_product
/-!
# Extension and restriction of scalars for Lie algebras
Lie algebras have a well-behaved theory of extension and restriction of scalars.
## Main definitions
* `lie_algebra.extend_scalars.lie_algebra`
* `lie_algebra.restrict_scalars.lie_algebra`
## Tags
lie ring, lie algebra, extension of scalars, restriction of scalars, base change
-/
universes u v w w₁ w₂ w₃
open_locale tensor_product
variables (R : Type u) (A : Type w) (L : Type v)
namespace lie_algebra
namespace extend_scalars
variables [comm_ring R] [comm_ring A] [algebra R A] [lie_ring L] [lie_algebra R L]
/-- The Lie bracket on the extension of a Lie algebra `L` over `R` by an algebra `A` over `R`.
In fact this bracket is fully `A`-bilinear but without a significant upgrade to our mixed-scalar
support in the tensor product library, it is far easier to bootstrap like this, starting with the
definition below. -/
private def bracket' : (A ⊗[R] L) →ₗ[R] (A ⊗[R] L) →ₗ[R] A ⊗[R] L :=
tensor_product.curry $
(tensor_product.map (linear_map.mul' R _) (lie_module.to_module_hom R L L : L ⊗[R] L →ₗ[R] L))
∘ₗ ↑(tensor_product.tensor_tensor_tensor_comm R A L A L)
@[simp] private lemma bracket'_tmul (s t : A) (x y : L) :
bracket' R A L (s ⊗ₜ[R] x) (t ⊗ₜ[R] y) = (s*t) ⊗ₜ ⁅x, y⁆ :=
by simp [bracket']
instance : has_bracket (A ⊗[R] L) (A ⊗[R] L) := { bracket := λ x y, bracket' R A L x y, }
private lemma bracket_def (x y : A ⊗[R] L) : ⁅x, y⁆ = bracket' R A L x y := rfl
@[simp] lemma bracket_tmul (s t : A) (x y : L) : ⁅s ⊗ₜ[R] x, t ⊗ₜ[R] y⁆ = (s*t) ⊗ₜ ⁅x, y⁆ :=
by rw [bracket_def, bracket'_tmul]
private lemma bracket_lie_self (x : A ⊗[R] L) : ⁅x, x⁆ = 0 :=
begin
simp only [bracket_def],
apply x.induction_on,
{ simp only [linear_map.map_zero, eq_self_iff_true, linear_map.zero_apply], },
{ intros a l,
simp only [bracket'_tmul, tensor_product.tmul_zero, eq_self_iff_true, lie_self], },
{ intros z₁ z₂ h₁ h₂,
suffices : bracket' R A L z₁ z₂ + bracket' R A L z₂ z₁ = 0,
{ rw [linear_map.map_add, linear_map.map_add, linear_map.add_apply, linear_map.add_apply,
h₁, h₂, zero_add, add_zero, add_comm, this], },
apply z₁.induction_on,
{ simp only [linear_map.map_zero, add_zero, linear_map.zero_apply], },
{ intros a₁ l₁, apply z₂.induction_on,
{ simp only [linear_map.map_zero, add_zero, linear_map.zero_apply], },
{ intros a₂ l₂,
simp only [← lie_skew l₂ l₁, mul_comm a₁ a₂, tensor_product.tmul_neg, bracket'_tmul,
add_right_neg], },
{ intros y₁ y₂ hy₁ hy₂,
simp only [hy₁, hy₂, add_add_add_comm, add_zero, linear_map.add_apply,
linear_map.map_add], }, },
{ intros y₁ y₂ hy₁ hy₂,
simp only [add_add_add_comm, hy₁, hy₂, add_zero, linear_map.add_apply,
linear_map.map_add], }, },
end
private lemma bracket_leibniz_lie (x y z : A ⊗[R] L) : ⁅x, ⁅y, z⁆⁆ = ⁅⁅x, y⁆, z⁆ + ⁅y, ⁅x, z⁆⁆ :=
begin
simp only [bracket_def],
apply x.induction_on,
{ simp only [linear_map.map_zero, add_zero, eq_self_iff_true, linear_map.zero_apply], },
{ intros a₁ l₁,
apply y.induction_on,
{ simp only [linear_map.map_zero, add_zero, eq_self_iff_true, linear_map.zero_apply], },
{ intros a₂ l₂,
apply z.induction_on,
{ simp only [linear_map.map_zero, add_zero], },
{ intros a₃ l₃, simp only [bracket'_tmul],
rw [mul_left_comm a₂ a₁ a₃, mul_assoc, leibniz_lie, tensor_product.tmul_add], },
{ intros u₁ u₂ h₁ h₂,
simp only [add_add_add_comm, h₁, h₂, linear_map.map_add], }, },
{ intros u₁ u₂ h₁ h₂,
simp only [add_add_add_comm, h₁, h₂, linear_map.add_apply, linear_map.map_add], }, },
{ intros u₁ u₂ h₁ h₂,
simp only [add_add_add_comm, h₁, h₂, linear_map.add_apply, linear_map.map_add], },
end
instance : lie_ring (A ⊗[R] L) :=
{ add_lie := λ x y z, by simp only [bracket_def, linear_map.add_apply, linear_map.map_add],
lie_add := λ x y z, by simp only [bracket_def, linear_map.map_add],
lie_self := bracket_lie_self R A L,
leibniz_lie := bracket_leibniz_lie R A L, }
private lemma bracket_lie_smul (a : A) (x y : A ⊗[R] L) : ⁅x, a • y⁆ = a • ⁅x, y⁆ :=
begin
apply x.induction_on,
{ simp only [zero_lie, smul_zero], },
{ intros a₁ l₁, apply y.induction_on,
{ simp only [lie_zero, smul_zero], },
{ intros a₂ l₂,
simp only [bracket_def, bracket', tensor_product.smul_tmul', mul_left_comm a₁ a a₂,
tensor_product.curry_apply, linear_map.mul'_apply, algebra.id.smul_eq_mul,
function.comp_app, linear_equiv.coe_coe, linear_map.coe_comp, tensor_product.map_tmul,
tensor_product.tensor_tensor_tensor_comm_tmul], },
{ intros z₁ z₂ h₁ h₂,
simp only [h₁, h₂, smul_add, lie_add], }, },
{ intros z₁ z₂ h₁ h₂,
simp only [h₁, h₂, smul_add, add_lie], },
end
instance lie_algebra : lie_algebra A (A ⊗[R] L) :=
{ lie_smul := bracket_lie_smul R A L, }
end extend_scalars
namespace restrict_scalars
open restrict_scalars
variables [h : lie_ring L]
include h
instance : lie_ring (restrict_scalars R A L) := h
variables [comm_ring A] [lie_algebra A L]
instance lie_algebra [comm_ring R] [algebra R A] : lie_algebra R (restrict_scalars R A L) :=
{ lie_smul := λ t x y, (lie_smul (algebra_map R A t)
(restrict_scalars.add_equiv R A L x) (restrict_scalars.add_equiv R A L y) : _) }
end restrict_scalars
end lie_algebra
|
c9c4eda250d6076765461b42a8ba6a2be42a056f | 567aff36164621444bd9b795b12b12c75da86592 | /src/blank.lean | 76a498c3862baf005c938786244fe96237505fc9 | [] | no_license | kl-i/learning-type-theory | f8f2abed84b8b4577229242208973a1d9b666c6f | 0931a3a5cab90296a58d73466f91c5d785af5a62 | refs/heads/master | 1,666,935,945,903 | 1,592,390,170,000 | 1,592,390,170,000 | 272,946,300 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,093 | lean | import data.rat
universe u
#check Prop
#check Type
constants T U : Type 1
#check λ x : T, λ x : T, x
#check λ x : T, λ t : T, x
#check λ t : T, λ x : T, t
def test : T → T → T :=
λ x : T, λ x : T, x
constants t₁ t₂ : T
#reduce test t₁ t₂
constant t : T
-- #reduce (λ x : T, (λ y : x, U)) for some reason doesn't work
-- def tee : T := t what does this have to do with computability
variable x : T
#check x = x
#check ℕ
#check ℤ
#check ℚ
variables (i : ℕ) (j : ℤ) (k : ℚ)
#check j + i
#check k + i
#check k + (j + i)
universes u v
constants (A : Type u) (B : Type v)
#check A → B
#check B → A
constant P : Prop
#check P → A
#check A → P
mutual inductive TREE, FOREST
with TREE : Type
| node : FOREST → TREE
with FOREST : Type
| emptyf : FOREST
| makef : TREE → FOREST → FOREST
#check TREE
inductive days : Type
| saturday : days
| sunday : days
#check @days.rec
def days_number : days → ℕ :=
@days.rec (λ d : days, ℕ) 0 1
inductive LIST : Type → Type
| emptylist : Π A : Type, LIST A
| append : Π A : Type, LIST A → A → LIST A
#check @LIST.rec
def length_of : Π A : Type, LIST A → ℕ :=
@LIST.rec (λ X : Type, λ x : LIST X, ℕ)
(λ X : Type, 0)
(λ B : Type, λ L : LIST B, λ b : B, λ n : ℕ, n + 1)
#reduce length_of ℕ (LIST.append ℕ (LIST.emptylist ℕ) 2)
#check LIST
constant c : Type
mutual inductive list1, list2 (A : Type) (B : Type)
with list1 : Type → Type
| nil : list1 A
| cons : A → list1 A → list1 A
with list2 : Type → Type
| nil : list2 B
| cons : B → list2 B → list2 B
#check λ x : T, λ x : U, x
#check λ y : T, λ x : U, y
#check ℕ
#print list
-- inductive LISTu : Sort u → Sort u
-- | emptylist : Π A : Sort u, LISTu A
-- | append : Π A : Sort u, Π a : A, Π l : LISTu A, LISTu A
#check false.rec
#check @true.rec
#check @nat.rec
#check @list.rec
inductive NAT : Sort 0
| zero : NAT
| succ : Π n : NAT, NAT
#check @NAT.rec
inductive myeq (α : Sort u) : Π a : α, Π b : α, Sort 0
| refl : Π a : α, myeq a a
#check @myeq.rec |
5473ba4cec67c49b06a82fb5b790b3ed62591c74 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/witt_vector/defs.lean | 5c207bd8b29d208fc8fd0d36e194034de1a8bd81 | [] | 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 | 11,453 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.ring_theory.witt_vector.structure_polynomial
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Witt vectors
In this file we define the type of `p`-typical Witt vectors and ring operations on it.
The ring axioms are verified in `ring_theory/witt_vector/basic.lean`.
For a fixed commutative ring `R` and prime `p`,
a Witt vector `x : 𝕎 R` is an infinite sequence `ℕ → R` of elements of `R`.
However, the ring operations `+` and `*` are not defined in the obvious component-wise way.
Instead, these operations are defined via certain polynomials
using the machinery in `structure_polynomial.lean`.
The `n`th value of the sum of two Witt vectors can depend on the `0`-th through `n`th values
of the summands. This effectively simulates a “carrying” operation.
## Main definitions
* `witt_vector p R`: the type of `p`-typical Witt vectors with coefficients in `R`.
* `witt_vector.coeff x n`: projects the `n`th value of the Witt vector `x`.
## Notation
We use notation `𝕎 R`, entered `\bbW`, for the Witt vectors over `R`.
-/
/-- `witt_vector p R` is the ring of `p`-typical Witt vectors over the commutative ring `R`,
where `p` is a prime number.
If `p` is invertible in `R`, this ring is isomorphic to `ℕ → R` (the product of `ℕ` copies of `R`).
If `R` is a ring of characteristic `p`, then `witt_vector p R` is a ring of characteristic `0`.
The canonical example is `witt_vector p (zmod p)`,
which is isomorphic to the `p`-adic integers `ℤ_[p]`. -/
def witt_vector (p : ℕ) (R : Type u_1) :=
ℕ → R
/- We cannot make this `localized` notation, because the `p` on the RHS doesn't occur on the left
Hiding the `p` in the notation is very convenient, so we opt for repeating the `local notation`
in other files that use Witt vectors. -/
namespace witt_vector
/-- Construct a Witt vector `mk p x : 𝕎 R` from a sequence `x` of elements of `R`. -/
def mk (p : ℕ) {R : Type u_1} (x : ℕ → R) : witt_vector p R :=
x
protected instance inhabited {p : ℕ} {R : Type u_1} [Inhabited R] : Inhabited (witt_vector p R) :=
{ default := mk p fun (_x : ℕ) => Inhabited.default }
/--
`x.coeff n` is the `n`th coefficient of the Witt vector `x`.
This concept does not have a standard name in the literature.
-/
def coeff {p : ℕ} {R : Type u_1} (x : witt_vector p R) (n : ℕ) : R :=
x n
theorem ext {p : ℕ} {R : Type u_1} {x : witt_vector p R} {y : witt_vector p R} (h : ∀ (n : ℕ), coeff x n = coeff y n) : x = y :=
funext fun (n : ℕ) => h n
theorem ext_iff {p : ℕ} {R : Type u_1} {x : witt_vector p R} {y : witt_vector p R} : x = y ↔ ∀ (n : ℕ), coeff x n = coeff y n :=
{ mp := fun (h : x = y) (n : ℕ) => eq.mpr (id (Eq._oldrec (Eq.refl (coeff x n = coeff y n)) h)) (Eq.refl (coeff y n)),
mpr := ext }
@[simp] theorem coeff_mk (p : ℕ) {R : Type u_1} (x : ℕ → R) : coeff (mk p x) = x :=
rfl
/- These instances are not needed for the rest of the development,
but it is interesting to establish early on that `witt_vector p` is a lawful functor. -/
protected instance functor (p : ℕ) : Functor (witt_vector p) :=
{ map := fun (α β : Type u_1) (f : α → β) (v : witt_vector p α) => f ∘ v,
mapConst := fun (α β : Type u_1) (a : α) (v : witt_vector p β) (_x : ℕ) => a }
protected instance is_lawful_functor (p : ℕ) : is_lawful_functor (witt_vector p) :=
is_lawful_functor.mk (fun (α : Type u_1) (v : witt_vector p α) => rfl)
fun (α β γ : Type u_1) (f : α → β) (g : β → γ) (v : witt_vector p α) => rfl
/-- The polynomials used for defining the element `0` of the ring of Witt vectors. -/
def witt_zero (p : ℕ) [hp : fact (nat.prime p)] : ℕ → mv_polynomial (fin 0 × ℕ) ℤ :=
witt_structure_int p 0
/-- The polynomials used for defining the element `1` of the ring of Witt vectors. -/
def witt_one (p : ℕ) [hp : fact (nat.prime p)] : ℕ → mv_polynomial (fin 0 × ℕ) ℤ :=
witt_structure_int p 1
/-- The polynomials used for defining the addition of the ring of Witt vectors. -/
def witt_add (p : ℕ) [hp : fact (nat.prime p)] : ℕ → mv_polynomial (fin (bit0 1) × ℕ) ℤ :=
witt_structure_int p (mv_polynomial.X 0 + mv_polynomial.X 1)
/-- The polynomials used for describing the subtraction of the ring of Witt vectors. -/
def witt_sub (p : ℕ) [hp : fact (nat.prime p)] : ℕ → mv_polynomial (fin (bit0 1) × ℕ) ℤ :=
witt_structure_int p (mv_polynomial.X 0 - mv_polynomial.X 1)
/-- The polynomials used for defining the multiplication of the ring of Witt vectors. -/
def witt_mul (p : ℕ) [hp : fact (nat.prime p)] : ℕ → mv_polynomial (fin (bit0 1) × ℕ) ℤ :=
witt_structure_int p (mv_polynomial.X 0 * mv_polynomial.X 1)
/-- The polynomials used for defining the negation of the ring of Witt vectors. -/
def witt_neg (p : ℕ) [hp : fact (nat.prime p)] : ℕ → mv_polynomial (fin 1 × ℕ) ℤ :=
witt_structure_int p (-mv_polynomial.X 0)
/-- An auxiliary definition used in `witt_vector.eval`.
Evaluates a polynomial whose variables come from the disjoint union of `k` copies of `ℕ`,
with a curried evaluation `x`.
This can be defined more generally but we use only a specific instance here. -/
def peval {R : Type u_1} [comm_ring R] {k : ℕ} (φ : mv_polynomial (fin k × ℕ) ℤ) (x : fin k → ℕ → R) : R :=
coe_fn (mv_polynomial.aeval (function.uncurry x)) φ
/--
Let `φ` be a family of polynomials, indexed by natural numbers, whose variables come from the
disjoint union of `k` copies of `ℕ`, and let `xᵢ` be a Witt vector for `0 ≤ i < k`.
`eval φ x` evaluates `φ` mapping the variable `X_(i, n)` to the `n`th coefficient of `xᵢ`.
Instantiating `φ` with certain polynomials defined in `structure_polynomial.lean` establishes the
ring operations on `𝕎 R`. For example, `witt_vector.witt_add` is such a `φ` with `k = 2`;
evaluating this at `(x₀, x₁)` gives us the sum of two Witt vectors `x₀ + x₁`.
-/
def eval {p : ℕ} {R : Type u_1} [comm_ring R] {k : ℕ} (φ : ℕ → mv_polynomial (fin k × ℕ) ℤ) (x : fin k → witt_vector p R) : witt_vector p R :=
mk p fun (n : ℕ) => peval (φ n) fun (i : fin k) => coeff (x i)
protected instance has_zero {p : ℕ} (R : Type u_1) [comm_ring R] [fact (nat.prime p)] : HasZero (witt_vector p R) :=
{ zero := eval (witt_zero p) matrix.vec_empty }
protected instance has_one {p : ℕ} (R : Type u_1) [comm_ring R] [fact (nat.prime p)] : HasOne (witt_vector p R) :=
{ one := eval (witt_one p) matrix.vec_empty }
protected instance has_add {p : ℕ} (R : Type u_1) [comm_ring R] [fact (nat.prime p)] : Add (witt_vector p R) :=
{ add := fun (x y : witt_vector p R) => eval (witt_add p) (matrix.vec_cons x (matrix.vec_cons y matrix.vec_empty)) }
protected instance has_sub {p : ℕ} (R : Type u_1) [comm_ring R] [fact (nat.prime p)] : Sub (witt_vector p R) :=
{ sub := fun (x y : witt_vector p R) => eval (witt_sub p) (matrix.vec_cons x (matrix.vec_cons y matrix.vec_empty)) }
protected instance has_mul {p : ℕ} (R : Type u_1) [comm_ring R] [fact (nat.prime p)] : Mul (witt_vector p R) :=
{ mul := fun (x y : witt_vector p R) => eval (witt_mul p) (matrix.vec_cons x (matrix.vec_cons y matrix.vec_empty)) }
protected instance has_neg {p : ℕ} (R : Type u_1) [comm_ring R] [fact (nat.prime p)] : Neg (witt_vector p R) :=
{ neg := fun (x : witt_vector p R) => eval (witt_neg p) (matrix.vec_cons x matrix.vec_empty) }
@[simp] theorem witt_zero_eq_zero (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : witt_zero p n = 0 := sorry
@[simp] theorem witt_one_zero_eq_one (p : ℕ) [hp : fact (nat.prime p)] : witt_one p 0 = 1 := sorry
@[simp] theorem witt_one_pos_eq_zero (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (hn : 0 < n) : witt_one p n = 0 := sorry
@[simp] theorem witt_add_zero (p : ℕ) [hp : fact (nat.prime p)] : witt_add p 0 = mv_polynomial.X (0, 0) + mv_polynomial.X (1, 0) := sorry
@[simp] theorem witt_sub_zero (p : ℕ) [hp : fact (nat.prime p)] : witt_sub p 0 = mv_polynomial.X (0, 0) - mv_polynomial.X (1, 0) := sorry
@[simp] theorem witt_mul_zero (p : ℕ) [hp : fact (nat.prime p)] : witt_mul p 0 = mv_polynomial.X (0, 0) * mv_polynomial.X (1, 0) := sorry
@[simp] theorem witt_neg_zero (p : ℕ) [hp : fact (nat.prime p)] : witt_neg p 0 = -mv_polynomial.X (0, 0) := sorry
@[simp] theorem constant_coeff_witt_add (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_add p n) = 0 := sorry
@[simp] theorem constant_coeff_witt_sub (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_sub p n) = 0 := sorry
@[simp] theorem constant_coeff_witt_mul (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_mul p n) = 0 := sorry
@[simp] theorem constant_coeff_witt_neg (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_neg p n) = 0 := sorry
@[simp] theorem zero_coeff (p : ℕ) (R : Type u_1) [hp : fact (nat.prime p)] [comm_ring R] (n : ℕ) : coeff 0 n = 0 := sorry
@[simp] theorem one_coeff_zero (p : ℕ) (R : Type u_1) [hp : fact (nat.prime p)] [comm_ring R] : coeff 1 0 = 1 := sorry
@[simp] theorem one_coeff_eq_of_pos (p : ℕ) (R : Type u_1) [hp : fact (nat.prime p)] [comm_ring R] (n : ℕ) (hn : 0 < n) : coeff 1 n = 0 := sorry
theorem add_coeff {p : ℕ} {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] (x : witt_vector p R) (y : witt_vector p R) (n : ℕ) : coeff (x + y) n = peval (witt_add p n) (matrix.vec_cons (coeff x) (matrix.vec_cons (coeff y) matrix.vec_empty)) :=
rfl
theorem sub_coeff {p : ℕ} {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] (x : witt_vector p R) (y : witt_vector p R) (n : ℕ) : coeff (x - y) n = peval (witt_sub p n) (matrix.vec_cons (coeff x) (matrix.vec_cons (coeff y) matrix.vec_empty)) :=
rfl
theorem mul_coeff {p : ℕ} {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] (x : witt_vector p R) (y : witt_vector p R) (n : ℕ) : coeff (x * y) n = peval (witt_mul p n) (matrix.vec_cons (coeff x) (matrix.vec_cons (coeff y) matrix.vec_empty)) :=
rfl
theorem neg_coeff {p : ℕ} {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] (x : witt_vector p R) (n : ℕ) : coeff (-x) n = peval (witt_neg p n) (matrix.vec_cons (coeff x) matrix.vec_empty) :=
rfl
theorem witt_add_vars (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : mv_polynomial.vars (witt_add p n) ⊆ finset.product finset.univ (finset.range (n + 1)) :=
witt_structure_int_vars p (mv_polynomial.X 0 + mv_polynomial.X 1) n
theorem witt_sub_vars (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : mv_polynomial.vars (witt_sub p n) ⊆ finset.product finset.univ (finset.range (n + 1)) :=
witt_structure_int_vars p (mv_polynomial.X 0 - mv_polynomial.X 1) n
theorem witt_mul_vars (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : mv_polynomial.vars (witt_mul p n) ⊆ finset.product finset.univ (finset.range (n + 1)) :=
witt_structure_int_vars p (mv_polynomial.X 0 * mv_polynomial.X 1) n
theorem witt_neg_vars (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : mv_polynomial.vars (witt_neg p n) ⊆ finset.product finset.univ (finset.range (n + 1)) :=
witt_structure_int_vars p (-mv_polynomial.X 0) n
|
6c798a780deb87c89860314e9285af73dc6b5980 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /analysis/limits.lean | 92f08328dc5f99f74880cfc7e0af4ff102f45acb | [
"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 | 11,716 | 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
A collection of limit properties.
-/
import algebra.big_operators algebra.group_power tactic.norm_num
analysis.ennreal analysis.topology.infinite_sum
noncomputable theory
open classical finset function filter
local attribute [instance] prop_decidable
section real
lemma has_sum_of_absolute_convergence {f : ℕ → ℝ}
(hf : ∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (nhds r)) : has_sum f :=
let f' := λs:finset ℕ, s.sum (λi, abs (f i)) in
suffices cauchy (map (λs:finset ℕ, s.sum f) at_top),
from complete_space.complete this,
cauchy_iff.mpr $ and.intro (map_ne_bot at_top_ne_bot) $
assume s hs,
let ⟨ε, hε, hsε⟩ := mem_uniformity_dist.mp hs, ⟨r, hr⟩ := hf in
have hε' : {p : ℝ × ℝ | dist p.1 p.2 < ε / 2} ∈ (@uniformity ℝ _).sets,
from mem_uniformity_dist.mpr ⟨ε / 2, div_pos_of_pos_of_pos hε two_pos, assume a b h, h⟩,
have cauchy (at_top.map $ λn, f' (range n)),
from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hr,
have ∃n, ∀{n'}, n ≤ n' → dist (f' (range n)) (f' (range n')) < ε / 2,
by simp [cauchy_iff, mem_at_top_sets] at this;
from let ⟨t, ⟨u, hu⟩, ht⟩ := this _ hε' in
⟨u, assume n' hn, ht $ set.prod_mk_mem_set_prod_eq.mpr ⟨hu _ (le_refl _), hu _ hn⟩⟩,
let ⟨n, hn⟩ := this in
have ∀{s}, range n ⊆ s → abs ((s \ range n).sum f) < ε / 2,
from assume s hs,
let ⟨n', hn'⟩ := @exists_nat_subset_range s in
have range n ⊆ range n', from finset.subset.trans hs hn',
have f'_nn : 0 ≤ f' (range n' \ range n), from zero_le_sum $ assume _ _, abs_nonneg _,
calc abs ((s \ range n).sum f) ≤ f' (s \ range n) : abs_sum_le_sum_abs
... ≤ f' (range n' \ range n) : sum_le_sum_of_subset_of_nonneg
(finset.sdiff_subset_sdiff hn' (finset.subset.refl _))
(assume _ _ _, abs_nonneg _)
... = abs (f' (range n' \ range n)) : (abs_of_nonneg f'_nn).symm
... = abs (f' (range n') - f' (range n)) :
by simp [f', (sum_sdiff ‹range n ⊆ range n'›).symm]
... = abs (f' (range n) - f' (range n')) : abs_sub _ _
... < ε / 2 : hn $ range_subset.mp this,
have ∀{s t}, range n ⊆ s → range n ⊆ t → dist (s.sum f) (t.sum f) < ε,
from assume s t hs ht,
calc abs (s.sum f - t.sum f) = abs ((s \ range n).sum f + - (t \ range n).sum f) :
by rw [←sum_sdiff hs, ←sum_sdiff ht]; simp
... ≤ abs ((s \ range n).sum f) + abs ((t \ range n).sum f) :
le_trans (abs_add_le_abs_add_abs _ _) $ by rw [abs_neg]; exact le_refl _
... < ε / 2 + ε / 2 : add_lt_add (this hs) (this ht)
... = ε : by rw [←add_div, add_self_div_two],
⟨(λs:finset ℕ, s.sum f) '' {s | range n ⊆ s}, image_mem_map $ mem_at_top (range n),
assume ⟨a, b⟩ ⟨⟨t, ht, ha⟩, ⟨s, hs, hb⟩⟩, by simp at ha hb; exact ha ▸ hb ▸ hsε (this ht hs)⟩
lemma is_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} {r : ℝ} (hf : ∀n, 0 ≤ f n) :
is_sum f r ↔ tendsto (λn, (range n).sum f) at_top (nhds r) :=
⟨tendsto_sum_nat_of_is_sum,
assume hr,
have tendsto (λn, (range n).sum (λn, abs (f n))) at_top (nhds r),
by simp [(λi, abs_of_nonneg (hf i)), hr],
let ⟨p, h⟩ := has_sum_of_absolute_convergence ⟨r, this⟩ in
have hp : tendsto (λn, (range n).sum f) at_top (nhds p), from tendsto_sum_nat_of_is_sum h,
have p = r, from tendsto_nhds_unique at_top_ne_bot hp hr,
this ▸ h⟩
end real
lemma mul_add_one_le_pow {r : ℝ} (hr : 0 ≤ r) : ∀{n:ℕ}, (n:ℝ) * r + 1 ≤ (r + 1) ^ n
| 0 := by simp; exact le_refl 1
| (n + 1) :=
let h : (n:ℝ) ≥ 0 := nat.cast_nonneg n in
calc ↑(n + 1) * r + 1 ≤ ((n + 1) * r + 1) + r * r * n :
le_add_of_le_of_nonneg (le_refl _) (mul_nonneg (mul_nonneg hr hr) h)
... = (r + 1) * (n * r + 1) : by simp [mul_add, add_mul, mul_comm, mul_assoc]
... ≤ (r + 1) * (r + 1) ^ n : mul_le_mul (le_refl _) mul_add_one_le_pow
(add_nonneg (mul_nonneg h hr) zero_le_one) (add_nonneg hr zero_le_one)
lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : r > 1) : tendsto (λn:ℕ, r ^ n) at_top at_top :=
tendsto_infi.2 $ assume p, tendsto_principal.2 $
let ⟨n, hn⟩ := exists_nat_gt (p / (r - 1)) in
have hn_nn : (0:ℝ) ≤ n, from nat.cast_nonneg n,
have r - 1 > 0, from sub_lt_iff_lt_add.mp $ by simp; assumption,
have p ≤ r ^ n,
from calc p = (p / (r - 1)) * (r - 1) : (div_mul_cancel _ $ ne_of_gt this).symm
... ≤ n * (r - 1) : mul_le_mul (le_of_lt hn) (le_refl _) (le_of_lt this) hn_nn
... ≤ n * (r - 1) + 1 : le_add_of_le_of_nonneg (le_refl _) zero_le_one
... ≤ ((r - 1) + 1) ^ n : mul_add_one_le_pow $ le_of_lt this
... ≤ r ^ n : by simp; exact le_refl _,
show {n | p ≤ r ^ n} ∈ at_top.sets,
from mem_at_top_sets.mpr ⟨n, assume m hnm, le_trans this (pow_le_pow (le_of_lt h) hnm)⟩
lemma tendsto_inverse_at_top_nhds_0 : tendsto (λr:ℝ, r⁻¹) at_top (nhds 0) :=
tendsto_orderable_unbounded (no_top 0) (no_bot 0) $ assume l u hl hu,
mem_at_top_sets.mpr ⟨u⁻¹ + 1, assume b hb,
have u⁻¹ < b, from lt_of_lt_of_le (lt_add_of_pos_right _ zero_lt_one) hb,
⟨lt_trans hl $ inv_pos $ lt_trans (inv_pos hu) this,
lt_of_one_div_lt_one_div hu $
begin
rw [inv_eq_one_div],
simp [-one_div_eq_inv, div_div_eq_mul_div, div_one],
simp [this]
end⟩⟩
lemma map_succ_at_top_eq : map nat.succ at_top = at_top :=
le_antisymm
(assume s hs,
let ⟨b, hb⟩ := mem_at_top_sets.mp hs in
mem_at_top_sets.mpr ⟨b, assume c hc, hb (c + 1) $ le_trans hc $ nat.le_succ _⟩)
(assume s hs,
let ⟨b, hb⟩ := mem_at_top_sets.mp hs in
mem_at_top_sets.mpr ⟨b + 1, assume c,
match c with
| 0 := assume h,
have 0 > 0, from lt_of_lt_of_le (lt_add_of_le_of_pos (nat.zero_le _) zero_lt_one) h,
(lt_irrefl 0 this).elim
| (c+1) := assume h, hb _ (nat.le_of_succ_le_succ h)
end⟩)
lemma tendsto_comp_succ_at_top_iff {α : Type*} {f : ℕ → α} {x : filter α} :
tendsto (λn, f (nat.succ n)) at_top x ↔ tendsto f at_top x :=
calc tendsto (f ∘ nat.succ) at_top x ↔ tendsto f (map nat.succ at_top) x : by simp [tendsto, filter.map_map]
... ↔ _ : by rw [map_succ_at_top_eq]
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (nhds 0) :=
by_cases
(assume : r = 0, tendsto_comp_succ_at_top_iff.mp $ by simp [pow_succ, this, tendsto_const_nhds])
(assume : r ≠ 0,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (nhds 0),
from (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂).comp
tendsto_inverse_at_top_nhds_0,
tendsto_cong this $ univ_mem_sets' $ by simp *)
lemma tendsto_coe_iff {f : ℕ → ℕ} : tendsto (λ n, (f n : ℝ)) at_top at_top ↔ tendsto f at_top at_top :=
⟨ λ h, tendsto_infi.2 $ λ i, tendsto_principal.2
(have _, from tendsto_infi.1 h i, by simpa using tendsto_principal.1 this),
λ h, tendsto.comp h tendsto_of_nat_at_top_at_top ⟩
lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : 1 < k) : tendsto (λn:ℕ, k ^ n) at_top at_top :=
tendsto_coe_iff.1 $
have hr : 1 < (k : ℝ), by rw [← nat.cast_one, nat.cast_lt]; exact h,
by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (nhds 0) :=
tendsto.comp (tendsto_coe_iff.2 tendsto_id) tendsto_inverse_at_top_nhds_0
lemma tendsto_one_div_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1/(n : ℝ)) at_top (nhds 0) :=
by simpa only [inv_eq_one_div] using tendsto_inverse_at_top_nhds_0_nat
lemma sum_geometric' {r : ℝ} (h : r ≠ 0) :
∀{n}, (finset.range n).sum (λi, (r + 1) ^ i) = ((r + 1) ^ n - 1) / r
| 0 := by simp [zero_div]
| (n+1) :=
by simp [@sum_geometric' n, h, pow_succ, add_div_eq_mul_add_div, add_mul, mul_comm, mul_assoc]
lemma sum_geometric {r : ℝ} {n : ℕ} (h : r ≠ 1) :
(range n).sum (λi, r ^ i) = (r ^ n - 1) / (r - 1) :=
calc (range n).sum (λi, r ^ i) = (range n).sum (λi, ((r - 1) + 1) ^ i) :
by simp
... = (((r - 1) + 1) ^ n - 1) / (r - 1) :
sum_geometric' $ by simp [sub_eq_iff_eq_add, -sub_eq_add_neg, h]
... = (r ^ n - 1) / (r - 1) :
by simp
lemma is_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
is_sum (λn:ℕ, r ^ n) (1 / (1 - r)) :=
have r ≠ 1, from ne_of_lt h₂,
have r + -1 ≠ 0,
by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption,
have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (nhds ((0 - 1) * (r - 1)⁻¹)),
from tendsto_mul
(tendsto_sub (tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂) tendsto_const_nhds) tendsto_const_nhds,
(is_sum_iff_tendsto_nat_of_nonneg $ pow_nonneg h₁).mpr $
by simp [neg_inv, sum_geometric, div_eq_mul_inv, *] at *
lemma is_sum_geometric_two (a : ℝ) : is_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert is_sum_mul_left (a / 2) (is_sum_geometric
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp,
rw ← pow_inv; [refl, exact two_ne_zero] },
{ norm_num, rw div_mul_cancel _ two_ne_zero }
end
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, is_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : is_sum f ε := is_sum_geometric_two _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
let g : ℕ → ℝ := λ n, option.cases_on (encodable.decode2 ι n) 0 (f ∘ encodable.encode),
have : ∀ n, g n = 0 ∨ g n = f n,
{ intro n, dsimp [g], cases e : encodable.decode2 ι n with a,
{ exact or.inl rfl },
{ simp [encodable.mem_decode2.1 e] } },
cases has_sum_of_has_sum_of_sub ⟨_, hf⟩ this with c hg,
have cε : c ≤ ε,
{ refine is_sum_le (λ n, _) hg hf,
cases this n; rw h, exact le_of_lt (f0 _) },
have hs : ∀ n, g n ≠ 0 → (encodable.decode2 ι n).is_some,
{ intros n h, dsimp [g] at h,
cases encodable.decode2 ι n,
exact (h rfl).elim, exact rfl },
refine ⟨c, _, cε⟩,
refine is_sum_of_is_sum_ne_zero
(λ n h, option.get (hs n h)) (λ n _, ne_of_gt (f0 _))
(λ i _, encodable.encode i) (λ n h, ne_of_gt _)
(λ n h, _) (λ i _, _) (λ i _, _) hg,
{ dsimp [g], rw encodable.encodek2, exact f0 _ },
{ exact encodable.mem_decode2.1 (option.get_mem _) },
{ exact option.get_of_mem _ (encodable.encodek2 _) },
{ dsimp [g], rw encodable.encodek2 }
end
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, is_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := dense hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, (nnreal.coe_lt _ _).2 $ hε' i,
⟨c, is_sum_le (assume i, le_of_lt $ hε' i) is_sum_zero hc ⟩, nnreal.is_sum_coe.1 hc,
lt_of_le_of_lt ((nnreal.coe_le _ _).1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑ i, (ε' i : ennreal)) < ε :=
begin
rcases dense hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal |
484282772d9f7a26b885aea7cfba7e81715123a8 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/measure_theory/function/strongly_measurable/lp.lean | d6cea24301e9ec3b22425490c03822d08be29614 | [
"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,707 | lean | /-
Copyright (c) 2022 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import measure_theory.function.simple_func_dense_lp
import measure_theory.function.strongly_measurable.basic
/-!
# Finitely strongly measurable functions in `Lp`
Functions in `Lp` for `0 < p < ∞` are finitely strongly measurable.
## Main statements
* `mem_ℒp.ae_fin_strongly_measurable`: if `mem_ℒp f p μ` with `0 < p < ∞`, then
`ae_fin_strongly_measurable f μ`.
* `Lp.fin_strongly_measurable`: for `0 < p < ∞`, `Lp` functions are finitely strongly measurable.
## References
* Hytönen, Tuomas, Jan Van Neerven, Mark Veraar, and Lutz Weis. Analysis in Banach spaces.
Springer, 2016.
-/
open measure_theory filter topological_space function
open_locale ennreal topology measure_theory
namespace measure_theory
local infixr ` →ₛ `:25 := simple_func
variables {α G : Type*} {p : ℝ≥0∞} {m m0 : measurable_space α} {μ : measure α}
[normed_add_comm_group G]
{f : α → G}
lemma mem_ℒp.fin_strongly_measurable_of_strongly_measurable
(hf : mem_ℒp f p μ) (hf_meas : strongly_measurable f) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) :
fin_strongly_measurable f μ :=
begin
borelize G,
haveI : separable_space (set.range f ∪ {0} : set G) :=
hf_meas.separable_space_range_union_singleton,
let fs := simple_func.approx_on f hf_meas.measurable (set.range f ∪ {0}) 0 (by simp),
refine ⟨fs, _, _⟩,
{ have h_fs_Lp : ∀ n, mem_ℒp (fs n) p μ,
from simple_func.mem_ℒp_approx_on_range hf_meas.measurable hf,
exact λ n, (fs n).measure_support_lt_top_of_mem_ℒp (h_fs_Lp n) hp_ne_zero hp_ne_top },
{ assume x,
apply simple_func.tendsto_approx_on,
apply subset_closure,
simp },
end
lemma mem_ℒp.ae_fin_strongly_measurable (hf : mem_ℒp f p μ) (hp_ne_zero : p ≠ 0)
(hp_ne_top : p ≠ ∞) :
ae_fin_strongly_measurable f μ :=
⟨hf.ae_strongly_measurable.mk f, ((mem_ℒp_congr_ae hf.ae_strongly_measurable.ae_eq_mk).mp hf)
.fin_strongly_measurable_of_strongly_measurable
hf.ae_strongly_measurable.strongly_measurable_mk hp_ne_zero hp_ne_top,
hf.ae_strongly_measurable.ae_eq_mk⟩
lemma integrable.ae_fin_strongly_measurable (hf : integrable f μ) :
ae_fin_strongly_measurable f μ :=
(mem_ℒp_one_iff_integrable.mpr hf).ae_fin_strongly_measurable one_ne_zero ennreal.coe_ne_top
lemma Lp.fin_strongly_measurable (f : Lp G p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) :
fin_strongly_measurable f μ :=
(Lp.mem_ℒp f).fin_strongly_measurable_of_strongly_measurable
(Lp.strongly_measurable f) hp_ne_zero hp_ne_top
end measure_theory
|
39f54865e75cfc26dcba67dfbc5d8ce2f18d5ba4 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/logic/nontrivial.lean | 51c379e9f79ec83e2a111bd06b511f34e3c1efe9 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,961 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import data.pi
import data.prod
import data.subtype
import logic.unique
import logic.function.basic
/-!
# Nontrivial types
A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings
(where it is equivalent to the fact that zero is different from one) and for vector spaces
(where it is equivalent to the fact that the dimension is positive).
We introduce a typeclass `nontrivial` formalizing this property.
-/
variables {α : Type*} {β : Type*}
open_locale classical
/-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings,
this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/
class nontrivial (α : Type*) : Prop :=
(exists_pair_ne : ∃ (x y : α), x ≠ y)
lemma nontrivial_iff : nontrivial α ↔ ∃ (x y : α), x ≠ y :=
⟨λ h, h.exists_pair_ne, λ h, ⟨h⟩⟩
lemma exists_pair_ne (α : Type*) [nontrivial α] : ∃ (x y : α), x ≠ y :=
nontrivial.exists_pair_ne
lemma exists_ne [nontrivial α] (x : α) : ∃ y, y ≠ x :=
begin
rcases exists_pair_ne α with ⟨y, y', h⟩,
by_cases hx : x = y,
{ rw ← hx at h,
exact ⟨y', h.symm⟩ },
{ exact ⟨y, ne.symm hx⟩ }
end
-- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`.
lemma nontrivial_of_ne (x y : α) (h : x ≠ y) : nontrivial α :=
⟨⟨x, y, h⟩⟩
-- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`.
lemma nontrivial_of_lt [preorder α] (x y : α) (h : x < y) : nontrivial α :=
⟨⟨x, y, ne_of_lt h⟩⟩
lemma nontrivial_iff_exists_ne (x : α) : nontrivial α ↔ ∃ y, y ≠ x :=
⟨λ h, @exists_ne α h x, λ ⟨y, hy⟩, nontrivial_of_ne _ _ hy⟩
lemma subtype.nontrivial_iff_exists_ne (p : α → Prop) (x : subtype p) :
nontrivial (subtype p) ↔ ∃ (y : α) (hy : p y), y ≠ x :=
by simp only [nontrivial_iff_exists_ne x, subtype.exists, ne.def, subtype.ext_iff, subtype.coe_mk]
@[priority 100] -- see Note [lower instance priority]
instance nontrivial.to_nonempty [nontrivial α] : nonempty α :=
let ⟨x, _⟩ := exists_pair_ne α in ⟨x⟩
/-- An inhabited type is either nontrivial, or has a unique element. -/
noncomputable def nontrivial_psum_unique (α : Type*) [inhabited α] :
psum (nontrivial α) (unique α) :=
if h : nontrivial α then psum.inl h else psum.inr
{ default := default α,
uniq := λ (x : α),
begin
change x = default α,
contrapose! h,
use [x, default α]
end }
lemma subsingleton_iff : subsingleton α ↔ ∀ (x y : α), x = y :=
⟨by { introsI h, exact subsingleton.elim }, λ h, ⟨h⟩⟩
lemma not_nontrivial_iff_subsingleton : ¬(nontrivial α) ↔ subsingleton α :=
by { rw [nontrivial_iff, subsingleton_iff], push_neg, refl }
lemma not_subsingleton (α) [h : nontrivial α] : ¬subsingleton α :=
let ⟨⟨x, y, hxy⟩⟩ := h in λ ⟨h'⟩, hxy $ h' x y
/-- A type is either a subsingleton or nontrivial. -/
lemma subsingleton_or_nontrivial (α : Type*) : subsingleton α ∨ nontrivial α :=
by { rw [← not_nontrivial_iff_subsingleton, or_comm], exact classical.em _ }
lemma false_of_nontrivial_of_subsingleton (α : Type*) [nontrivial α] [subsingleton α] : false :=
let ⟨x, y, h⟩ := exists_pair_ne α in h $ subsingleton.elim x y
instance option.nontrivial [nonempty α] : nontrivial (option α) :=
by { inhabit α, use [none, some (default α)] }
/-- Pushforward a `nontrivial` instance along an injective function. -/
protected lemma function.injective.nontrivial [nontrivial α]
{f : α → β} (hf : function.injective f) : nontrivial β :=
let ⟨x, y, h⟩ := exists_pair_ne α in ⟨⟨f x, f y, hf.ne h⟩⟩
/-- Pullback a `nontrivial` instance along a surjective function. -/
protected lemma function.surjective.nontrivial [nontrivial β]
{f : α → β} (hf : function.surjective f) : nontrivial α :=
begin
rcases exists_pair_ne β with ⟨x, y, h⟩,
rcases hf x with ⟨x', hx'⟩,
rcases hf y with ⟨y', hy'⟩,
have : x' ≠ y', by { contrapose! h, rw [← hx', ← hy', h] },
exact ⟨⟨x', y', this⟩⟩
end
/-- An injective function from a nontrivial type has an argument at
which it does not take a given value. -/
protected lemma function.injective.exists_ne [nontrivial α] {f : α → β}
(hf : function.injective f) (y : β) : ∃ x, f x ≠ y :=
begin
rcases exists_pair_ne α with ⟨x₁, x₂, hx⟩,
by_cases h : f x₂ = y,
{ exact ⟨x₁, (hf.ne_iff' h).2 hx⟩ },
{ exact ⟨x₂, h⟩ }
end
instance nontrivial_prod_right [nonempty α] [nontrivial β] : nontrivial (α × β) :=
prod.snd_surjective.nontrivial
instance nontrivial_prod_left [nontrivial α] [nonempty β] : nontrivial (α × β) :=
prod.fst_surjective.nontrivial
namespace pi
variables {I : Type*} {f : I → Type*}
/-- A pi type is nontrivial if it's nonempty everywhere and nontrivial somewhere. -/
lemma nontrivial_at (i' : I) [inst : Π i, nonempty (f i)] [nontrivial (f i')] :
nontrivial (Π i : I, f i) :=
by classical; exact
(function.update_injective (λ i, classical.choice (inst i)) i').nontrivial
/--
As a convenience, provide an instance automatically if `(f (default I))` is nontrivial.
If a different index has the non-trivial type, then use `haveI := nontrivial_at that_index`.
-/
instance nontrivial [inhabited I] [inst : Π i, nonempty (f i)] [nontrivial (f (default I))] :
nontrivial (Π i : I, f i) :=
nontrivial_at (default I)
end pi
instance function.nontrivial [h : nonempty α] [nontrivial β] : nontrivial (α → β) :=
h.elim $ λ a, pi.nontrivial_at a
mk_simp_attribute nontriviality "Simp lemmas for `nontriviality` tactic"
protected lemma subsingleton.le [preorder α] [subsingleton α] (x y : α) : x ≤ y :=
le_of_eq (subsingleton.elim x y)
attribute [nontriviality] eq_iff_true_of_subsingleton subsingleton.le
namespace tactic
/--
Tries to generate a `nontrivial α` instance by performing case analysis on
`subsingleton_or_nontrivial α`,
attempting to discharge the subsingleton branch using lemmas with `@[nontriviality]` attribute,
including `subsingleton.le` and `eq_iff_true_of_subsingleton`.
-/
meta def nontriviality_by_elim (α : expr) (lems : interactive.parse simp_arg_list) : tactic unit :=
do
alternative ← to_expr ``(subsingleton_or_nontrivial %%α),
n ← get_unused_name "_inst",
tactic.cases alternative [n, n],
(solve1 $ do
reset_instance_cache,
apply_instance <|>
interactive.simp none none ff lems [`nontriviality] (interactive.loc.ns [none])) <|>
fail format!"Could not prove goal assuming `subsingleton {α}`",
reset_instance_cache
/--
Tries to generate a `nontrivial α` instance using `nontrivial_of_ne` or `nontrivial_of_lt`
and local hypotheses.
-/
meta def nontriviality_by_assumption (α : expr) : tactic unit :=
do
n ← get_unused_name "_inst",
to_expr ``(nontrivial %%α) >>= assert n,
apply_instance <|> `[solve_by_elim [nontrivial_of_ne, nontrivial_of_lt]],
reset_instance_cache
end tactic
namespace tactic.interactive
open tactic
setup_tactic_parser
/--
Attempts to generate a `nontrivial α` hypothesis.
The tactic first looks for an instance using `apply_instance`.
If the goal is an (in)equality, the type `α` is inferred from the goal.
Otherwise, the type needs to be specified in the tactic invocation, as `nontriviality α`.
The `nontriviality` tactic will first look for strict inequalities amongst the hypotheses,
and use these to derive the `nontrivial` instance directly.
Otherwise, it will perform a case split on `subsingleton α ∨ nontrivial α`, and attempt to discharge
the `subsingleton` goal using `simp [lemmas] with nontriviality`, where `[lemmas]` is a list of
additional `simp` lemmas that can be passed to `nontriviality` using the syntax
`nontriviality α using [lemmas]`.
```
example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : 0 < a :=
begin
nontriviality, -- There is now a `nontrivial R` hypothesis available.
assumption,
end
```
```
example {R : Type} [comm_ring R] {r s : R} : r * s = s * r :=
begin
nontriviality, -- There is now a `nontrivial R` hypothesis available.
apply mul_comm,
end
```
```
example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : (2 : ℕ) ∣ 4 :=
begin
nontriviality R, -- there is now a `nontrivial R` hypothesis available.
dec_trivial
end
```
```
def myeq {α : Type} (a b : α) : Prop := a = b
example {α : Type} (a b : α) (h : a = b) : myeq a b :=
begin
success_if_fail { nontriviality α }, -- Fails
nontriviality α using [myeq], -- There is now a `nontrivial α` hypothesis available
assumption
end
```
-/
meta def nontriviality (t : parse texpr?)
(lems : parse (tk "using" *> simp_arg_list <|> pure [])) :
tactic unit :=
do
α ← match t with
| some α := to_expr α
| none :=
(do t ← mk_mvar, e ← to_expr ``(@eq %%t _ _), target >>= unify e, return t) <|>
(do t ← mk_mvar, e ← to_expr ``(@has_le.le %%t _ _ _), target >>= unify e, return t) <|>
(do t ← mk_mvar, e ← to_expr ``(@ne %%t _ _), target >>= unify e, return t) <|>
(do t ← mk_mvar, e ← to_expr ``(@has_lt.lt %%t _ _ _), target >>= unify e, return t) <|>
fail "The goal is not an (in)equality, so you'll need to specify the desired `nontrivial α`
instance by invoking `nontriviality α`."
end,
nontriviality_by_assumption α <|> nontriviality_by_elim α lems
add_tactic_doc
{ name := "nontriviality",
category := doc_category.tactic,
decl_names := [`tactic.interactive.nontriviality],
tags := ["logic", "type class"] }
end tactic.interactive
namespace bool
instance : nontrivial bool := ⟨⟨tt,ff, tt_eq_ff_eq_false⟩⟩
end bool
|
2615fb8b7edaee604f45b990b7b68288ea25b275 | 38ee9024fb5974f555fb578fcf5a5a7b71e669b5 | /Mathlib/Mathport/Attributes.lean | 2977a1b1025497a38d9052f3b037528e5ea729d4 | [
"Apache-2.0"
] | permissive | denayd/mathlib4 | 750e0dcd106554640a1ac701e51517501a574715 | 7f40a5c514066801ab3c6d431e9f405baa9b9c58 | refs/heads/master | 1,693,743,991,894 | 1,636,618,048,000 | 1,636,618,048,000 | 373,926,241 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 800 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Lean.Attributes
namespace Lean.Attr
initialize reflAttr : TagAttribute ← registerTagAttribute `refl "reflexive relation"
initialize symmAttr : TagAttribute ← registerTagAttribute `symm "symmetric relation"
initialize transAttr : TagAttribute ← registerTagAttribute `trans "transitive relation"
initialize substAttr : TagAttribute ← registerTagAttribute `subst "substitution"
initialize linterAttr : TagAttribute ←
registerTagAttribute `linter "Use this declaration as a linting test in #lint"
initialize hintTacticAttr : TagAttribute ←
registerTagAttribute `hintTactic "A tactic that should be tried by `hint`."
|
497a9e3680a80c007ae18118c70f32c77061a4b0 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/finite_type.lean | b862b84dff4d23ecd46655ffa9cafe9bd00e1bcd | [
"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 | 23,804 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import group_theory.finiteness
import ring_theory.adjoin.tower
import ring_theory.finiteness
import ring_theory.noetherian
/-!
# Finiteness conditions in commutative algebra
In this file we define a notion of finiteness that is common in commutative algebra.
## Main declarations
- `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type`
all of these express that some object is finitely generated *as algebra* over some base ring.
-/
open function (surjective)
open_locale big_operators polynomial
section module_and_algebra
variables (R A B M N : Type*)
/-- An algebra over a commutative semiring is of `finite_type` if it is finitely generated
over the base ring as algebra. -/
class algebra.finite_type [comm_semiring R] [semiring A] [algebra R A] : Prop :=
(out : (⊤ : subalgebra R A).fg)
namespace module
variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N]
namespace finite
open _root_.submodule set
variables {R M N}
section algebra
@[priority 100] -- see Note [lower instance priority]
instance finite_type {R : Type*} (A : Type*) [comm_semiring R] [semiring A]
[algebra R A] [hRA : finite R A] : algebra.finite_type R A :=
⟨subalgebra.fg_of_submodule_fg hRA.1⟩
end algebra
end finite
end module
namespace algebra
variables [comm_ring R] [comm_ring A] [algebra R A] [comm_ring B] [algebra R B]
variables [add_comm_group M] [module R M]
variables [add_comm_group N] [module R N]
namespace finite_type
lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩
protected lemma polynomial : finite_type R R[X] :=
⟨⟨{polynomial.X}, by { rw finset.coe_singleton, exact polynomial.adjoin_X }⟩⟩
open_locale classical
protected lemma mv_polynomial (ι : Type*) [finite ι] : finite_type R (mv_polynomial ι R) :=
by casesI nonempty_fintype ι; exact ⟨⟨finset.univ.image mv_polynomial.X,
by {rw [finset.coe_image, finset.coe_univ, set.image_univ], exact mv_polynomial.adjoin_range_X}⟩⟩
lemma of_restrict_scalars_finite_type [algebra A B] [is_scalar_tower R A B] [hB : finite_type R B] :
finite_type A B :=
begin
obtain ⟨S, hS⟩ := hB.out,
refine ⟨⟨S, eq_top_iff.2 (λ b, _)⟩⟩,
have le : adjoin R (S : set B) ≤ subalgebra.restrict_scalars R (adjoin A S),
{ apply (algebra.adjoin_le _ : _ ≤ (subalgebra.restrict_scalars R (adjoin A ↑S))),
simp only [subalgebra.coe_restrict_scalars],
exact algebra.subset_adjoin, },
exact le (eq_top_iff.1 hS b),
end
variables {R A B}
lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) :
finite_type R B :=
⟨begin
convert hRA.1.map f,
simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf
end⟩
lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B :=
hRA.of_surjective e e.surjective
lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) :
finite_type R B :=
⟨fg_trans' hRA.1 hAB.1⟩
/-- An algebra is finitely generated if and only if it is a quotient
of a polynomial ring whose variables are indexed by a finset. -/
lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A)
(f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rintro ⟨s, hs⟩,
use [s, mv_polynomial.aeval coe],
intro x,
have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl,
rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs],
exact set.mem_univ x },
{ rintro ⟨s, ⟨f, hsur⟩⟩,
exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur }
end
/-- An algebra is finitely generated if and only if it is a quotient
of a polynomial ring whose variables are indexed by a fintype. -/
lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) (_ : fintype ι)
(f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rw iff_quotient_mv_polynomial,
rintro ⟨s, ⟨f, hsur⟩⟩,
use [{x // x ∈ s}, by apply_instance, f, hsur] },
{ rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩,
letI : fintype ι := hfintype,
exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur }
end
/-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n`
variables. -/
lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ)
(f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rw iff_quotient_mv_polynomial',
rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩,
resetI,
have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι),
exact ⟨fintype.card ι, alg_hom.comp f equiv.symm, function.surjective.comp hsur
(alg_equiv.symm equiv).surjective⟩ },
{ rintro ⟨n, ⟨f, hsur⟩⟩,
exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur }
end
instance prod [hA : finite_type R A] [hB : finite_type R B] : finite_type R (A × B) :=
⟨begin
rw ← subalgebra.prod_top,
exact hA.1.prod hB.1
end⟩
lemma is_noetherian_ring (R S : Type*) [comm_ring R] [comm_ring S] [algebra R S]
[h : algebra.finite_type R S] [is_noetherian_ring R] : is_noetherian_ring S :=
begin
obtain ⟨s, hs⟩ := h.1,
apply is_noetherian_ring_of_surjective
(mv_polynomial s R) S (mv_polynomial.aeval coe : mv_polynomial s R →ₐ[R] S),
rw [← set.range_iff_surjective, alg_hom.coe_to_ring_hom, ← alg_hom.coe_range,
← algebra.adjoin_range_eq_range_aeval, subtype.range_coe_subtype, finset.set_of_mem, hs],
refl
end
lemma _root_.subalgebra.fg_iff_finite_type {R A : Type*} [comm_semiring R] [semiring A]
[algebra R A] (S : subalgebra R A) : S.fg ↔ algebra.finite_type R S :=
S.fg_top.symm.trans ⟨λ h, ⟨h⟩, λ h, h.out⟩
end finite_type
end algebra
end module_and_algebra
namespace ring_hom
variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C]
/-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/
def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra
namespace finite
variables {A}
lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f :=
@module.finite.finite_type _ _ _ _ f.to_algebra hf
end finite
namespace finite_type
variables (A)
lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A
variables {A}
lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) :
(g.comp f).finite_type :=
@algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf
{ to_fun := g, commutes' := λ a, rfl, .. g } hg
lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type :=
by { rw ← f.comp_id, exact (id A).comp_surjective hf }
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) :
(g.comp f).finite_type :=
@algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
begin
fconstructor,
intros a b c,
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end
hf hg
lemma of_finite {f : A →+* B} (hf : f.finite) : f.finite_type :=
@module.finite.finite_type _ _ _ _ f.to_algebra hf
alias of_finite ← _root_.ring_hom.finite.to_finite_type
lemma of_comp_finite_type {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite_type) :
g.finite_type :=
begin
letI := f.to_algebra,
letI := g.to_algebra,
letI := (g.comp f).to_algebra,
letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C,
letI : algebra.finite_type A C := h,
exact algebra.finite_type.of_restrict_scalars_finite_type A B C
end
end finite_type
end ring_hom
namespace alg_hom
variables {R A B C : Type*} [comm_ring R]
variables [comm_ring A] [comm_ring B] [comm_ring C]
variables [algebra R A] [algebra R B] [algebra R C]
/-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism.
In other words, if `B` is finitely generated as `A`-algebra. -/
def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type
namespace finite
variables {R A}
lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f :=
ring_hom.finite.finite_type hf
end finite
namespace finite_type
variables (R A)
lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) :
(g.comp f).finite_type :=
ring_hom.finite_type.comp hg hf
lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) :
(g.comp f).finite_type :=
ring_hom.finite_type.comp_surjective hf hg
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type :=
ring_hom.finite_type.of_surjective f hf
lemma of_comp_finite_type {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite_type) :
g.finite_type :=
ring_hom.finite_type.of_comp_finite_type h
end finite_type
end alg_hom
section monoid_algebra
variables {R : Type*} {M : Type*}
namespace add_monoid_algebra
open algebra add_submonoid submodule
section span
section semiring
variables [comm_semiring R] [add_monoid M]
/-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_adjoin_support (f : add_monoid_algebra R M) : f ∈ adjoin R (of' R M '' f.support) :=
begin
suffices : span R (of' R M '' f.support) ≤ (adjoin R (of' R M '' f.support)).to_submodule,
{ exact this (mem_span_support f) },
rw submodule.span_le,
exact subset_adjoin
end
/-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the set of supports of
elements of `S` generates `add_monoid_algebra R M`. -/
lemma support_gen_of_gen {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (⋃ f ∈ S, (of' R M '' (f.support : set M))) = ⊤ :=
begin
refine le_antisymm le_top _,
rw [← hS, adjoin_le_iff],
intros f hf,
have hincl : of' R M '' f.support ⊆
⋃ (g : add_monoid_algebra R M) (H : g ∈ S), of' R M '' g.support,
{ intros s hs,
exact set.mem_Union₂.2 ⟨f, ⟨hf, hs⟩⟩ },
exact adjoin_mono hincl (mem_adjoin_support f)
end
/-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the image of the union of
the supports of elements of `S` generates `add_monoid_algebra R M`. -/
lemma support_gen_of_gen' {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (of' R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ :=
begin
suffices : of' R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of' R M '' (f.support : set M)),
{ rw this,
exact support_gen_of_gen hS },
simp only [set.image_Union]
end
end semiring
section ring
variables [comm_ring R] [add_comm_monoid M]
/-- If `add_monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its
image generates, as algera, `add_monoid_algebra R M`. -/
lemma exists_finset_adjoin_eq_top [h : finite_type R (add_monoid_algebra R M)] :
∃ G : finset M, algebra.adjoin R (of' R M '' G) = ⊤ :=
begin
unfreezingI { obtain ⟨S, hS⟩ := h },
letI : decidable_eq M := classical.dec_eq M,
use finset.bUnion S (λ f, f.support),
have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M),
{ simp only [finset.set_bUnion_coe, finset.coe_bUnion] },
rw [this],
exact support_gen_of_gen' hS
end
/-- The image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by
`S : set M` if and only if `m ∈ S`. -/
lemma of'_mem_span [nontrivial R] {m : M} {S : set M} :
of' R M m ∈ span R (of' R M '' S) ↔ m ∈ S :=
begin
refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩,
rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported,
finsupp.support_single_ne_zero _ (one_ne_zero' R)] at h,
simpa using h
end
/--If the image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by
the closure of some `S : set M` then `m ∈ closure S`. -/
lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M}
(h : of' R M m ∈ span R (submonoid.closure (of' R M '' S) : set (add_monoid_algebra R M))) :
m ∈ closure S :=
begin
suffices : multiplicative.of_add m ∈ submonoid.closure (multiplicative.to_add ⁻¹' S),
{ simpa [← to_submonoid_closure] },
let S' := @submonoid.closure M multiplicative.mul_one_class S,
have h' : submonoid.map (of R M) S' = submonoid.closure ((λ (x : M), (of R M) x) '' S) :=
monoid_hom.map_mclosure _ _,
rw [set.image_congr' (show ∀ x, of' R M x = of R M x, from λ x, of'_eq_of x), ← h'] at h,
simpa using of'_mem_span.1 h
end
end ring
end span
variables [add_comm_monoid M]
/-- If a set `S` generates an additive monoid `M`, then the image of `M` generates, as algebra,
`add_monoid_algebra R M`. -/
lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M}
(hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval
(λ (s : S), of' R M ↑s) : mv_polynomial S R → add_monoid_algebra R M) :=
begin
refine λ f, induction_on f (λ m, _) _ _,
{ have : m ∈ closure S := hS.symm ▸ mem_top _,
refine closure_induction this (λ m hm, _) _ _,
{ exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ },
{ exact ⟨1, alg_hom.map_one _⟩ },
{ rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩,
exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply,
single_mul_single, one_mul]; refl⟩ } },
{ rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩,
exact ⟨P + Q, alg_hom.map_add _ _ _⟩ },
{ rintro r f ⟨P, rfl⟩,
exact ⟨r • P, alg_hom.map_smul _ _ _⟩ }
end
variables (R M)
/-- If an additive monoid `M` is finitely generated then `add_monoid_algebra R M` is of finite
type. -/
instance finite_type_of_fg [comm_ring R] [h : add_monoid.fg M] :
finite_type R (add_monoid_algebra R M) :=
begin
obtain ⟨S, hS⟩ := h.out,
exact (finite_type.mv_polynomial R (S : set M)).of_surjective (mv_polynomial.aeval
(λ (s : (S : set M)), of' R M ↑s)) (mv_polynomial_aeval_of_surjective_of_closure hS)
end
variables {R M}
/-- An additive monoid `M` is finitely generated if and only if `add_monoid_algebra R M` is of
finite type. -/
lemma finite_type_iff_fg [comm_ring R] [nontrivial R] :
finite_type R (add_monoid_algebra R M) ↔ add_monoid.fg M :=
begin
refine ⟨λ h, _, λ h, @add_monoid_algebra.finite_type_of_fg _ _ _ _ h⟩,
obtain ⟨S, hS⟩ := @exists_finset_adjoin_eq_top R M _ _ h,
refine add_monoid.fg_def.2 ⟨S, (eq_top_iff' _).2 (λ m, _)⟩,
have hm : of' R M m ∈ (adjoin R (of' R M '' ↑S)).to_submodule,
{ simp only [hS, top_to_submodule, submodule.mem_top], },
rw [adjoin_eq_span] at hm,
exact mem_closure_of_mem_span_closure hm
end
/-- If `add_monoid_algebra R M` is of finite type then `M` is finitely generated. -/
lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (add_monoid_algebra R M)] :
add_monoid.fg M :=
finite_type_iff_fg.1 h
/-- An additive group `G` is finitely generated if and only if `add_monoid_algebra R G` is of
finite type. -/
lemma finite_type_iff_group_fg {G : Type*} [add_comm_group G] [comm_ring R] [nontrivial R] :
finite_type R (add_monoid_algebra R G) ↔ add_group.fg G :=
by simpa [add_group.fg_iff_add_monoid.fg] using finite_type_iff_fg
end add_monoid_algebra
namespace monoid_algebra
open algebra submonoid submodule
section span
section semiring
variables [comm_semiring R] [monoid M]
/-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_adjoin_support (f : monoid_algebra R M) : f ∈ adjoin R (of R M '' f.support) :=
begin
suffices : span R (of R M '' f.support) ≤ (adjoin R (of R M '' f.support)).to_submodule,
{ exact this (mem_span_support f) },
rw submodule.span_le,
exact subset_adjoin
end
/-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the set of supports of elements
of `S` generates `monoid_algebra R M`. -/
lemma support_gen_of_gen {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (⋃ f ∈ S, (of R M '' (f.support : set M))) = ⊤ :=
begin
refine le_antisymm le_top _,
rw [← hS, adjoin_le_iff],
intros f hf,
have hincl : (of R M) '' f.support ⊆
⋃ (g : monoid_algebra R M) (H : g ∈ S), of R M '' g.support,
{ intros s hs,
exact set.mem_Union₂.2 ⟨f, ⟨hf, hs⟩⟩ },
exact adjoin_mono hincl (mem_adjoin_support f)
end
/-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the image of the union of the
supports of elements of `S` generates `monoid_algebra R M`. -/
lemma support_gen_of_gen' {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (of R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ :=
begin
suffices : of R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of R M '' (f.support : set M)),
{ rw this,
exact support_gen_of_gen hS },
simp only [set.image_Union]
end
end semiring
section ring
variables [comm_ring R] [comm_monoid M]
/-- If `monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image
generates, as algera, `monoid_algebra R M`. -/
lemma exists_finset_adjoin_eq_top [h :finite_type R (monoid_algebra R M)] :
∃ G : finset M, algebra.adjoin R (of R M '' G) = ⊤ :=
begin
unfreezingI { obtain ⟨S, hS⟩ := h },
letI : decidable_eq M := classical.dec_eq M,
use finset.bUnion S (λ f, f.support),
have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M),
{ simp only [finset.set_bUnion_coe, finset.coe_bUnion] },
rw [this],
exact support_gen_of_gen' hS
end
/-- The image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by
`S : set M` if and only if `m ∈ S`. -/
lemma of_mem_span_of_iff [nontrivial R] {m : M} {S : set M} :
of R M m ∈ span R (of R M '' S) ↔ m ∈ S :=
begin
refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩,
rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported,
finsupp.support_single_ne_zero _ (one_ne_zero' R)] at h,
simpa using h
end
/--If the image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by the
closure of some `S : set M` then `m ∈ closure S`. -/
lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M}
(h : of R M m ∈ span R (submonoid.closure (of R M '' S) : set (monoid_algebra R M))) :
m ∈ closure S :=
begin
rw ← monoid_hom.map_mclosure at h,
simpa using of_mem_span_of_iff.1 h
end
end ring
end span
variables [comm_monoid M]
/-- If a set `S` generates a monoid `M`, then the image of `M` generates, as algebra,
`monoid_algebra R M`. -/
lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M}
(hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval
(λ (s : S), of R M ↑s) : mv_polynomial S R → monoid_algebra R M) :=
begin
refine λ f, induction_on f (λ m, _) _ _,
{ have : m ∈ closure S := hS.symm ▸ mem_top _,
refine closure_induction this (λ m hm, _) _ _,
{ exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ },
{ exact ⟨1, alg_hom.map_one _⟩ },
{ rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩,
exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply,
single_mul_single, one_mul]⟩ } },
{ rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩,
exact ⟨P + Q, alg_hom.map_add _ _ _⟩ },
{ rintro r f ⟨P, rfl⟩,
exact ⟨r • P, alg_hom.map_smul _ _ _⟩ }
end
/-- If a monoid `M` is finitely generated then `monoid_algebra R M` is of finite type. -/
instance finite_type_of_fg [comm_ring R] [monoid.fg M] : finite_type R (monoid_algebra R M) :=
(add_monoid_algebra.finite_type_of_fg R (additive M)).equiv (to_additive_alg_equiv R M).symm
/-- A monoid `M` is finitely generated if and only if `monoid_algebra R M` is of finite type. -/
lemma finite_type_iff_fg [comm_ring R] [nontrivial R] :
finite_type R (monoid_algebra R M) ↔ monoid.fg M :=
⟨λ h, monoid.fg_iff_add_fg.2 $ add_monoid_algebra.finite_type_iff_fg.1 $ h.equiv $
to_additive_alg_equiv R M, λ h, @monoid_algebra.finite_type_of_fg _ _ _ _ h⟩
/-- If `monoid_algebra R M` is of finite type then `M` is finitely generated. -/
lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (monoid_algebra R M)] :
monoid.fg M :=
finite_type_iff_fg.1 h
/-- A group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/
lemma finite_type_iff_group_fg {G : Type*} [comm_group G] [comm_ring R] [nontrivial R] :
finite_type R (monoid_algebra R G) ↔ group.fg G :=
by simpa [group.fg_iff_monoid.fg] using finite_type_iff_fg
end monoid_algebra
end monoid_algebra
section vasconcelos
variables {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (f : M →ₗ[R] M)
noncomputable theory
/-- The structure of a module `M` over a ring `R` as a module over `R[X]` when given a
choice of how `X` acts by choosing a linear map `f : M →ₗ[R] M` -/
def module_polynomial_of_endo : module R[X] M :=
module.comp_hom M (polynomial.aeval f).to_ring_hom
lemma module_polynomial_of_endo_smul_def (n : R[X]) (a : M) :
@@has_smul.smul (module_polynomial_of_endo f).to_has_smul n a = polynomial.aeval f n a := rfl
local attribute [simp] module_polynomial_of_endo_smul_def
include f
lemma module_polynomial_of_endo.is_scalar_tower : @is_scalar_tower R R[X] M _
(by { letI := module_polynomial_of_endo f, apply_instance }) _ :=
begin
letI := module_polynomial_of_endo f,
constructor,
intros x y z,
simp,
end
open polynomial module
/-- A theorem/proof by Vasconcelos, given a finite module `M` over a commutative ring, any
surjective endomorphism of `M` is also injective. Based on,
https://math.stackexchange.com/a/239419/31917,
https://www.ams.org/journals/tran/1969-138-00/S0002-9947-1969-0238839-5/.
This is similar to `is_noetherian.injective_of_surjective_endomorphism` but only applies in the
commutative case, but does not use a Noetherian hypothesis. -/
theorem module.finite.injective_of_surjective_endomorphism [hfg : finite R M]
(f_surj : function.surjective f) : function.injective f :=
begin
letI := module_polynomial_of_endo f,
haveI : is_scalar_tower R R[X] M := module_polynomial_of_endo.is_scalar_tower f,
have hfgpoly : finite R[X] M, from finite.of_restrict_scalars_finite R _ _,
have X_mul : ∀ o, (X : R[X]) • o = f o,
{ intro,
simp, },
have : (⊤ : submodule R[X] M) ≤ ideal.span {X} • ⊤,
{ intros a ha,
obtain ⟨y, rfl⟩ := f_surj a,
rw [← X_mul y],
exact submodule.smul_mem_smul (ideal.mem_span_singleton.mpr (dvd_refl _)) trivial, },
obtain ⟨F, hFa, hFb⟩ := submodule.exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul _
(⊤ : submodule R[X] M) (finite_def.mp hfgpoly) this,
rw [← linear_map.ker_eq_bot, linear_map.ker_eq_bot'],
intros m hm,
rw ideal.mem_span_singleton' at hFa,
obtain ⟨G, hG⟩ := hFa,
suffices : (F - 1) • m = 0,
{ have Fmzero := hFb m (by simp),
rwa [← sub_add_cancel F 1, add_smul, one_smul, this, zero_add] at Fmzero, },
rw [← hG, mul_smul, X_mul m, hm, smul_zero],
end
end vasconcelos
|
641562c1b13570b29c9f6e61fcee49f956dd3227 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/uniform_space/uniform_convergence.lean | 1ee5495cedb4626858f45d35e2bdc17695c05bb3 | [
"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 | 49,856 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.separation
import topology.uniform_space.basic
import topology.uniform_space.cauchy
/-!
# Uniform convergence
A sequence of functions `Fₙ` (with values in a metric space) converges uniformly on a set `s` to a
function `f` if, for all `ε > 0`, for all large enough `n`, one has for all `y ∈ s` the inequality
`dist (f y, Fₙ y) < ε`. Under uniform convergence, many properties of the `Fₙ` pass to the limit,
most notably continuity. We prove this in the file, defining the notion of uniform convergence
in the more general setting of uniform spaces, and with respect to an arbitrary indexing set
endowed with a filter (instead of just `ℕ` with `at_top`).
## Main results
Let `α` be a topological space, `β` a uniform space, `Fₙ` and `f` be functions from `α`to `β`
(where the index `n` belongs to an indexing type `ι` endowed with a filter `p`).
* `tendsto_uniformly_on F f p s`: the fact that `Fₙ` converges uniformly to `f` on `s`. This means
that, for any entourage `u` of the diagonal, for large enough `n` (with respect to `p`), one has
`(f y, Fₙ y) ∈ u` for all `y ∈ s`.
* `tendsto_uniformly F f p`: same notion with `s = univ`.
* `tendsto_uniformly_on.continuous_on`: a uniform limit on a set of functions which are continuous
on this set is itself continuous on this set.
* `tendsto_uniformly.continuous`: a uniform limit of continuous functions is continuous.
* `tendsto_uniformly_on.tendsto_comp`: If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends
to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`.
* `tendsto_uniformly.tendsto_comp`: If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then
`Fₙ gₙ` tends to `f x`.
We also define notions where the convergence is locally uniform, called
`tendsto_locally_uniformly_on F f p s` and `tendsto_locally_uniformly F f p`. The previous theorems
all have corresponding versions under locally uniform convergence.
Finally, we introduce the notion of a uniform Cauchy sequence, which is to uniform
convergence what a Cauchy sequence is to the usual notion of convergence.
## Implementation notes
We derive most of our initial results from an auxiliary definition `tendsto_uniformly_on_filter`.
This definition in and of itself can sometimes be useful, e.g., when studying the local behavior
of the `Fₙ` near a point, which would typically look like `tendsto_uniformly_on_filter F f p (𝓝 x)`.
Still, while this may be the "correct" definition (see
`tendsto_uniformly_on_iff_tendsto_uniformly_on_filter`), it is somewhat unwieldy to work with in
practice. Thus, we provide the more traditional definition in `tendsto_uniformly_on`.
Most results hold under weaker assumptions of locally uniform approximation. In a first section,
we prove the results under these weaker assumptions. Then, we derive the results on uniform
convergence from them.
## Tags
Uniform limit, uniform convergence, tends uniformly to
-/
noncomputable theory
open_locale topological_space classical uniformity filter
open set filter
universes u v w
variables {α β γ ι : Type*} [uniform_space β]
variables {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {p' : filter α}
{g : ι → α}
/-!
### Different notions of uniform convergence
We define uniform convergence and locally uniform convergence, on a set or in the whole space.
-/
/-- A sequence of functions `Fₙ` converges uniformly on a filter `p'` to a limiting function `f`
with respect to the filter `p` if, for any entourage of the diagonal `u`, one has
`p ×ᶠ p'`-eventually `(f x, Fₙ x) ∈ u`. -/
def tendsto_uniformly_on_filter (F : ι → α → β) (f : α → β) (p : filter ι) (p' : filter α) :=
∀ u ∈ 𝓤 β, ∀ᶠ (n : ι × α) in (p ×ᶠ p'), (f n.snd, F n.fst n.snd) ∈ u
/--
A sequence of functions `Fₙ` converges uniformly on a filter `p'` to a limiting function `f` w.r.t.
filter `p` iff the function `(n, x) ↦ (f x, Fₙ x)` converges along `p ×ᶠ p'` to the uniformity.
In other words: one knows nothing about the behavior of `x` in this limit besides it being in `p'`.
-/
lemma tendsto_uniformly_on_filter_iff_tendsto :
tendsto_uniformly_on_filter F f p p' ↔
tendsto (λ q : ι × α, (f q.2, F q.1 q.2)) (p ×ᶠ p') (𝓤 β) :=
forall₂_congr $ λ u u_in, by simp [mem_map, filter.eventually, mem_prod_iff, preimage]
/-- A sequence of functions `Fₙ` converges uniformly on a set `s` to a limiting function `f` with
respect to the filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually
`(f x, Fₙ x) ∈ u` for all `x ∈ s`. -/
def tendsto_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) :=
∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ (x : α), x ∈ s → (f x, F n x) ∈ u
lemma tendsto_uniformly_on_iff_tendsto_uniformly_on_filter :
tendsto_uniformly_on F f p s ↔ tendsto_uniformly_on_filter F f p (𝓟 s) :=
begin
simp only [tendsto_uniformly_on, tendsto_uniformly_on_filter],
apply forall₂_congr,
simp_rw [eventually_prod_principal_iff],
simp,
end
alias tendsto_uniformly_on_iff_tendsto_uniformly_on_filter ↔
tendsto_uniformly_on.tendsto_uniformly_on_filter tendsto_uniformly_on_filter.tendsto_uniformly_on
/--
A sequence of functions `Fₙ` converges uniformly on a set `s` to a limiting function `f` w.r.t.
filter `p` iff the function `(n, x) ↦ (f x, Fₙ x)` converges along `p ×ᶠ 𝓟 s` to the uniformity.
In other words: one knows nothing about the behavior of `x` in this limit besides it being in `s`.
-/
lemma tendsto_uniformly_on_iff_tendsto {F : ι → α → β} {f : α → β} {p : filter ι} {s : set α} :
tendsto_uniformly_on F f p s ↔ tendsto (λ q : ι × α, (f q.2, F q.1 q.2)) (p ×ᶠ 𝓟 s) (𝓤 β) :=
by simp [tendsto_uniformly_on_iff_tendsto_uniformly_on_filter,
tendsto_uniformly_on_filter_iff_tendsto]
/-- A sequence of functions `Fₙ` converges uniformly to a limiting function `f` with respect to a
filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually
`(f x, Fₙ x) ∈ u` for all `x`. -/
def tendsto_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) :=
∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ (x : α), (f x, F n x) ∈ u
lemma tendsto_uniformly_iff_tendsto_uniformly_on_filter :
tendsto_uniformly F f p ↔ tendsto_uniformly_on_filter F f p ⊤ :=
begin
simp only [tendsto_uniformly, tendsto_uniformly_on_filter],
apply forall₂_congr,
simp_rw [← principal_univ, eventually_prod_principal_iff],
simp,
end
lemma tendsto_uniformly.tendsto_uniformly_on_filter
(h : tendsto_uniformly F f p) : tendsto_uniformly_on_filter F f p ⊤ :=
by rwa ← tendsto_uniformly_iff_tendsto_uniformly_on_filter
lemma tendsto_uniformly_on_iff_tendsto_uniformly_comp_coe :
tendsto_uniformly_on F f p s ↔ tendsto_uniformly (λ i (x : s), F i x) (f ∘ coe) p :=
begin
apply forall₂_congr,
intros u hu,
simp,
end
/--
A sequence of functions `Fₙ` converges uniformly to a limiting function `f` w.r.t.
filter `p` iff the function `(n, x) ↦ (f x, Fₙ x)` converges along `p ×ᶠ ⊤` to the uniformity.
In other words: one knows nothing about the behavior of `x` in this limit.
-/
lemma tendsto_uniformly_iff_tendsto {F : ι → α → β} {f : α → β} {p : filter ι} :
tendsto_uniformly F f p ↔ tendsto (λ q : ι × α, (f q.2, F q.1 q.2)) (p ×ᶠ ⊤) (𝓤 β) :=
by simp [tendsto_uniformly_iff_tendsto_uniformly_on_filter, tendsto_uniformly_on_filter_iff_tendsto]
/-- Uniform converence implies pointwise convergence. -/
lemma tendsto_uniformly_on_filter.tendsto_at (h : tendsto_uniformly_on_filter F f p p')
(hx : 𝓟 {x} ≤ p') : tendsto (λ n, F n x) p $ 𝓝 (f x) :=
begin
refine uniform.tendsto_nhds_right.mpr (λ u hu, mem_map.mpr _),
filter_upwards [(h u hu).curry],
intros i h,
simpa using (h.filter_mono hx),
end
/-- Uniform converence implies pointwise convergence. -/
lemma tendsto_uniformly_on.tendsto_at (h : tendsto_uniformly_on F f p s) {x : α} (hx : x ∈ s) :
tendsto (λ n, F n x) p $ 𝓝 (f x) :=
h.tendsto_uniformly_on_filter.tendsto_at
(le_principal_iff.mpr $ mem_principal.mpr $ singleton_subset_iff.mpr $ hx)
/-- Uniform converence implies pointwise convergence. -/
lemma tendsto_uniformly.tendsto_at (h : tendsto_uniformly F f p) (x : α) :
tendsto (λ n, F n x) p $ 𝓝 (f x) :=
h.tendsto_uniformly_on_filter.tendsto_at le_top
lemma tendsto_uniformly_on_univ :
tendsto_uniformly_on F f p univ ↔ tendsto_uniformly F f p :=
by simp [tendsto_uniformly_on, tendsto_uniformly]
lemma tendsto_uniformly_on_filter.mono_left {p'' : filter ι}
(h : tendsto_uniformly_on_filter F f p p') (hp : p'' ≤ p) :
tendsto_uniformly_on_filter F f p'' p' :=
λ u hu, (h u hu).filter_mono (p'.prod_mono_left hp)
lemma tendsto_uniformly_on_filter.mono_right {p'' : filter α}
(h : tendsto_uniformly_on_filter F f p p') (hp : p'' ≤ p') :
tendsto_uniformly_on_filter F f p p'' :=
λ u hu, (h u hu).filter_mono (p.prod_mono_right hp)
lemma tendsto_uniformly_on.mono {s' : set α}
(h : tendsto_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_uniformly_on F f p s' :=
tendsto_uniformly_on_iff_tendsto_uniformly_on_filter.mpr
(h.tendsto_uniformly_on_filter.mono_right (le_principal_iff.mpr $ mem_principal.mpr h'))
lemma tendsto_uniformly_on_filter.congr {F' : ι → α → β}
(hf : tendsto_uniformly_on_filter F f p p')
(hff' : ∀ᶠ (n : ι × α) in (p ×ᶠ p'), F n.fst n.snd = F' n.fst n.snd) :
tendsto_uniformly_on_filter F' f p p' :=
begin
refine (λ u hu, ((hf u hu).and hff').mono (λ n h, _)),
rw ← h.right,
exact h.left,
end
lemma tendsto_uniformly_on.congr {F' : ι → α → β}
(hf : tendsto_uniformly_on F f p s) (hff' : ∀ᶠ n in p, set.eq_on (F n) (F' n) s) :
tendsto_uniformly_on F' f p s :=
begin
rw tendsto_uniformly_on_iff_tendsto_uniformly_on_filter at hf ⊢,
refine hf.congr _,
rw eventually_iff at hff' ⊢,
simp only [set.eq_on] at hff',
simp only [mem_prod_principal, hff', mem_set_of_eq],
end
lemma tendsto_uniformly_on.congr_right {g : α → β}
(hf : tendsto_uniformly_on F f p s) (hfg : eq_on f g s) :
tendsto_uniformly_on F g p s :=
λ u hu, by filter_upwards [hf u hu] with i hi a ha using hfg ha ▸ hi a ha
protected lemma tendsto_uniformly.tendsto_uniformly_on
(h : tendsto_uniformly F f p) : tendsto_uniformly_on F f p s :=
(tendsto_uniformly_on_univ.2 h).mono (subset_univ s)
/-- Composing on the right by a function preserves uniform convergence on a filter -/
lemma tendsto_uniformly_on_filter.comp (h : tendsto_uniformly_on_filter F f p p') (g : γ → α) :
tendsto_uniformly_on_filter (λ n, F n ∘ g) (f ∘ g) p (p'.comap g) :=
begin
intros u hu,
obtain ⟨pa, hpa, pb, hpb, hpapb⟩ := eventually_prod_iff.mp (h u hu),
rw eventually_prod_iff,
simp_rw eventually_comap,
exact ⟨pa, hpa, pb ∘ g, ⟨hpb.mono (λ x hx y hy, by simp only [hx, hy, function.comp_app]),
λ x hx y hy, hpapb hx hy⟩⟩,
end
/-- Composing on the right by a function preserves uniform convergence on a set -/
lemma tendsto_uniformly_on.comp (h : tendsto_uniformly_on F f p s) (g : γ → α) :
tendsto_uniformly_on (λ n, F n ∘ g) (f ∘ g) p (g ⁻¹' s) :=
begin
rw tendsto_uniformly_on_iff_tendsto_uniformly_on_filter at h ⊢,
simpa [tendsto_uniformly_on, comap_principal] using (tendsto_uniformly_on_filter.comp h g),
end
/-- Composing on the right by a function preserves uniform convergence -/
lemma tendsto_uniformly.comp (h : tendsto_uniformly F f p) (g : γ → α) :
tendsto_uniformly (λ n, F n ∘ g) (f ∘ g) p :=
begin
rw tendsto_uniformly_iff_tendsto_uniformly_on_filter at h ⊢,
simpa [principal_univ, comap_principal] using (h.comp g),
end
/-- Composing on the left by a uniformly continuous function preserves
uniform convergence on a filter -/
lemma uniform_continuous.comp_tendsto_uniformly_on_filter [uniform_space γ] {g : β → γ}
(hg : uniform_continuous g) (h : tendsto_uniformly_on_filter F f p p') :
tendsto_uniformly_on_filter (λ i, g ∘ (F i)) (g ∘ f) p p' :=
λ u hu, h _ (hg hu)
/-- Composing on the left by a uniformly continuous function preserves
uniform convergence on a set -/
lemma uniform_continuous.comp_tendsto_uniformly_on [uniform_space γ] {g : β → γ}
(hg : uniform_continuous g) (h : tendsto_uniformly_on F f p s) :
tendsto_uniformly_on (λ i, g ∘ (F i)) (g ∘ f) p s :=
λ u hu, h _ (hg hu)
/-- Composing on the left by a uniformly continuous function preserves uniform convergence -/
lemma uniform_continuous.comp_tendsto_uniformly [uniform_space γ] {g : β → γ}
(hg : uniform_continuous g) (h : tendsto_uniformly F f p) :
tendsto_uniformly (λ i, g ∘ (F i)) (g ∘ f) p :=
λ u hu, h _ (hg hu)
lemma tendsto_uniformly_on_filter.prod_map {ι' α' β' : Type*} [uniform_space β']
{F' : ι' → α' → β'} {f' : α' → β'} {q : filter ι'} {q' : filter α'}
(h : tendsto_uniformly_on_filter F f p p') (h' : tendsto_uniformly_on_filter F' f' q q') :
tendsto_uniformly_on_filter (λ (i : ι × ι'), prod.map (F i.1) (F' i.2))
(prod.map f f') (p.prod q) (p'.prod q') :=
begin
intros u hu,
rw [uniformity_prod_eq_prod, mem_map, mem_prod_iff] at hu,
obtain ⟨v, hv, w, hw, hvw⟩ := hu,
apply (tendsto_swap4_prod.eventually ((h v hv).prod_mk (h' w hw))).mono,
simp only [prod_map, and_imp, prod.forall],
intros n n' x hxv hxw,
have hout : ((f x.fst, F n x.fst), (f' x.snd, F' n' x.snd)) ∈
{x : (β × β) × β' × β' | ((x.fst.fst, x.snd.fst), x.fst.snd, x.snd.snd) ∈ u},
{ exact mem_of_mem_of_subset (set.mem_prod.mpr ⟨hxv, hxw⟩) hvw, },
exact hout,
end
lemma tendsto_uniformly_on.prod_map {ι' α' β' : Type*} [uniform_space β']
{F' : ι' → α' → β'} {f' : α' → β'} {p' : filter ι'} {s' : set α'}
(h : tendsto_uniformly_on F f p s) (h' : tendsto_uniformly_on F' f' p' s') :
tendsto_uniformly_on (λ (i : ι × ι'), prod.map (F i.1) (F' i.2))
(prod.map f f') (p.prod p') (s ×ˢ s') :=
begin
rw tendsto_uniformly_on_iff_tendsto_uniformly_on_filter at h h' ⊢,
simpa only [prod_principal_principal] using (h.prod_map h'),
end
lemma tendsto_uniformly.prod_map {ι' α' β' : Type*} [uniform_space β'] {F' : ι' → α' → β'}
{f' : α' → β'} {p' : filter ι'} (h : tendsto_uniformly F f p) (h' : tendsto_uniformly F' f' p') :
tendsto_uniformly (λ (i : ι × ι'), prod.map (F i.1) (F' i.2)) (prod.map f f') (p.prod p') :=
begin
rw [←tendsto_uniformly_on_univ, ←univ_prod_univ] at *,
exact h.prod_map h',
end
lemma tendsto_uniformly_on_filter.prod {ι' β' : Type*} [uniform_space β']
{F' : ι' → α → β'} {f' : α → β'} {q : filter ι'}
(h : tendsto_uniformly_on_filter F f p p') (h' : tendsto_uniformly_on_filter F' f' q p') :
tendsto_uniformly_on_filter (λ (i : ι × ι') a, (F i.1 a, F' i.2 a))
(λ a, (f a, f' a)) (p.prod q) p' :=
λ u hu, ((h.prod_map h') u hu).diag_of_prod_right
lemma tendsto_uniformly_on.prod {ι' β' : Type*} [uniform_space β'] {F' : ι' → α → β'} {f' : α → β'}
{p' : filter ι'} (h : tendsto_uniformly_on F f p s) (h' : tendsto_uniformly_on F' f' p' s) :
tendsto_uniformly_on (λ (i : ι × ι') a, (F i.1 a, F' i.2 a)) (λ a, (f a, f' a)) (p.prod p') s :=
(congr_arg _ s.inter_self).mp ((h.prod_map h').comp (λ a, (a, a)))
lemma tendsto_uniformly.prod {ι' β' : Type*} [uniform_space β'] {F' : ι' → α → β'} {f' : α → β'}
{p' : filter ι'} (h : tendsto_uniformly F f p) (h' : tendsto_uniformly F' f' p') :
tendsto_uniformly (λ (i : ι × ι') a, (F i.1 a, F' i.2 a)) (λ a, (f a, f' a)) (p.prod p') :=
(h.prod_map h').comp (λ a, (a, a))
/-- Uniform convergence on a filter `p'` to a constant function is equivalent to convergence in
`p ×ᶠ p'`. -/
lemma tendsto_prod_filter_iff {c : β} :
tendsto ↿F (p ×ᶠ p') (𝓝 c) ↔ tendsto_uniformly_on_filter F (λ _, c) p p' :=
begin
simp_rw [tendsto, nhds_eq_comap_uniformity, map_le_iff_le_comap.symm, map_map, le_def, mem_map],
exact forall₂_congr (λ u hu, by simpa [eventually_iff]),
end
/-- Uniform convergence on a set `s` to a constant function is equivalent to convergence in
`p ×ᶠ 𝓟 s`. -/
lemma tendsto_prod_principal_iff {c : β} :
tendsto ↿F (p ×ᶠ 𝓟 s) (𝓝 c) ↔ tendsto_uniformly_on F (λ _, c) p s :=
begin
rw tendsto_uniformly_on_iff_tendsto_uniformly_on_filter,
exact tendsto_prod_filter_iff,
end
/-- Uniform convergence to a constant function is equivalent to convergence in `p ×ᶠ ⊤`. -/
lemma tendsto_prod_top_iff {c : β} : tendsto ↿F (p ×ᶠ ⊤) (𝓝 c) ↔ tendsto_uniformly F (λ _, c) p :=
begin
rw tendsto_uniformly_iff_tendsto_uniformly_on_filter,
exact tendsto_prod_filter_iff,
end
/-- Uniform convergence on the empty set is vacuously true -/
lemma tendsto_uniformly_on_empty :
tendsto_uniformly_on F f p ∅ :=
λ u hu, by simp
/-- Uniform convergence on a singleton is equivalent to regular convergence -/
lemma tendsto_uniformly_on_singleton_iff_tendsto :
tendsto_uniformly_on F f p {x} ↔ tendsto (λ n : ι, F n x) p (𝓝 (f x)) :=
begin
simp_rw [tendsto_uniformly_on_iff_tendsto, uniform.tendsto_nhds_right, tendsto_def],
exact forall₂_congr (λ u hu, by simp [mem_prod_principal, preimage]),
end
/-- If a sequence `g` converges to some `b`, then the sequence of constant functions
`λ n, λ a, g n` converges to the constant function `λ a, b` on any set `s` -/
lemma filter.tendsto.tendsto_uniformly_on_filter_const
{g : ι → β} {b : β} (hg : tendsto g p (𝓝 b)) (p' : filter α) :
tendsto_uniformly_on_filter (λ n : ι, λ a : α, g n) (λ a : α, b) p p' :=
begin
rw tendsto_uniformly_on_filter_iff_tendsto,
rw uniform.tendsto_nhds_right at hg,
exact (hg.comp (tendsto_fst.comp ((@tendsto_id ι p).prod_map (@tendsto_id α p')))).congr
(λ x, by simp),
end
/-- If a sequence `g` converges to some `b`, then the sequence of constant functions
`λ n, λ a, g n` converges to the constant function `λ a, b` on any set `s` -/
lemma filter.tendsto.tendsto_uniformly_on_const
{g : ι → β} {b : β} (hg : tendsto g p (𝓝 b)) (s : set α) :
tendsto_uniformly_on (λ n : ι, λ a : α, g n) (λ a : α, b) p s :=
tendsto_uniformly_on_iff_tendsto_uniformly_on_filter.mpr
(hg.tendsto_uniformly_on_filter_const (𝓟 s))
lemma uniform_continuous_on.tendsto_uniformly [uniform_space α] [uniform_space γ]
{x : α} {U : set α} (hU : U ∈ 𝓝 x)
{F : α → β → γ} (hF : uniform_continuous_on ↿F (U ×ˢ (univ : set β))) :
tendsto_uniformly F (F x) (𝓝 x) :=
begin
let φ := (λ q : α × β, ((x, q.2), q)),
rw [tendsto_uniformly_iff_tendsto,
show (λ q : α × β, (F x q.2, F q.1 q.2)) = prod.map ↿F ↿F ∘ φ, by { ext ; simpa }],
apply hF.comp (tendsto_inf.mpr ⟨_, _⟩),
{ rw [uniformity_prod, tendsto_inf, tendsto_comap_iff, tendsto_comap_iff,
show (λp : (α × β) × α × β, (p.1.1, p.2.1)) ∘ φ = (λa, (x, a)) ∘ prod.fst, by { ext, simp },
show (λp : (α × β) × α × β, (p.1.2, p.2.2)) ∘ φ = (λb, (b, b)) ∘ prod.snd, by { ext, simp }],
exact ⟨tendsto_left_nhds_uniformity.comp tendsto_fst,
(tendsto_diag_uniformity id ⊤).comp tendsto_top⟩ },
{ rw tendsto_principal,
apply mem_of_superset (prod_mem_prod hU (mem_top.mpr rfl)) (λ q h, _),
simp [h.1, mem_of_mem_nhds hU] }
end
lemma uniform_continuous₂.tendsto_uniformly [uniform_space α] [uniform_space γ]
{f : α → β → γ} (h : uniform_continuous₂ f) {x : α} : tendsto_uniformly f (f x) (𝓝 x) :=
uniform_continuous_on.tendsto_uniformly univ_mem $
by rwa [univ_prod_univ, uniform_continuous_on_univ]
/-- A sequence is uniformly Cauchy if eventually all of its pairwise differences are
uniformly bounded -/
def uniform_cauchy_seq_on_filter
(F : ι → α → β) (p : filter ι) (p' : filter α) : Prop :=
∀ u : set (β × β), u ∈ 𝓤 β → ∀ᶠ (m : (ι × ι) × α) in ((p ×ᶠ p) ×ᶠ p'),
(F m.fst.fst m.snd, F m.fst.snd m.snd) ∈ u
/-- A sequence is uniformly Cauchy if eventually all of its pairwise differences are
uniformly bounded -/
def uniform_cauchy_seq_on
(F : ι → α → β) (p : filter ι) (s : set α) : Prop :=
∀ u : set (β × β), u ∈ 𝓤 β → ∀ᶠ (m : ι × ι) in (p ×ᶠ p), ∀ (x : α), x ∈ s →
(F m.fst x, F m.snd x) ∈ u
lemma uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter :
uniform_cauchy_seq_on F p s ↔ uniform_cauchy_seq_on_filter F p (𝓟 s) :=
begin
simp only [uniform_cauchy_seq_on, uniform_cauchy_seq_on_filter],
refine forall₂_congr (λ u hu, _),
rw eventually_prod_principal_iff,
end
lemma uniform_cauchy_seq_on.uniform_cauchy_seq_on_filter (hF : uniform_cauchy_seq_on F p s) :
uniform_cauchy_seq_on_filter F p (𝓟 s) :=
by rwa ←uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter
/-- A sequence that converges uniformly is also uniformly Cauchy -/
lemma tendsto_uniformly_on_filter.uniform_cauchy_seq_on_filter
(hF : tendsto_uniformly_on_filter F f p p') :
uniform_cauchy_seq_on_filter F p p' :=
begin
intros u hu,
rcases comp_symm_of_uniformity hu with ⟨t, ht, htsymm, htmem⟩,
have := tendsto_swap4_prod.eventually ((hF t ht).prod_mk (hF t ht)),
apply this.diag_of_prod_right.mono,
simp only [and_imp, prod.forall],
intros n1 n2 x hl hr,
exact set.mem_of_mem_of_subset (prod_mk_mem_comp_rel (htsymm hl) hr) htmem,
end
/-- A sequence that converges uniformly is also uniformly Cauchy -/
lemma tendsto_uniformly_on.uniform_cauchy_seq_on (hF : tendsto_uniformly_on F f p s) :
uniform_cauchy_seq_on F p s :=
uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter.mpr
hF.tendsto_uniformly_on_filter.uniform_cauchy_seq_on_filter
/-- A uniformly Cauchy sequence converges uniformly to its limit -/
lemma uniform_cauchy_seq_on_filter.tendsto_uniformly_on_filter_of_tendsto [ne_bot p]
(hF : uniform_cauchy_seq_on_filter F p p')
(hF' : ∀ᶠ (x : α) in p', tendsto (λ n, F n x) p (𝓝 (f x))) :
tendsto_uniformly_on_filter F f p p' :=
begin
-- Proof idea: |f_n(x) - f(x)| ≤ |f_n(x) - f_m(x)| + |f_m(x) - f(x)|. We choose `n`
-- so that |f_n(x) - f_m(x)| is uniformly small across `s` whenever `m ≥ n`. Then for
-- a fixed `x`, we choose `m` sufficiently large such that |f_m(x) - f(x)| is small.
intros u hu,
rcases comp_symm_of_uniformity hu with ⟨t, ht, htsymm, htmem⟩,
-- We will choose n, x, and m simultaneously. n and x come from hF. m comes from hF'
-- But we need to promote hF' to the full product filter to use it
have hmc : ∀ᶠ (x : (ι × ι) × α) in p ×ᶠ p ×ᶠ p', tendsto (λ (n : ι), F n x.snd) p (𝓝 (f x.snd)),
{ rw eventually_prod_iff,
refine ⟨(λ x, true), by simp, _, hF', by simp⟩, },
-- To apply filter operations we'll need to do some order manipulation
rw filter.eventually_swap_iff,
have := tendsto_prod_assoc.eventually (tendsto_prod_swap.eventually ((hF t ht).and hmc)),
apply this.curry.mono,
simp only [equiv.prod_assoc_apply, eventually_and, eventually_const, prod.snd_swap,
prod.fst_swap, and_imp, prod.forall],
-- Complete the proof
intros x n hx hm',
refine set.mem_of_mem_of_subset (mem_comp_rel.mpr _) htmem,
rw uniform.tendsto_nhds_right at hm',
have := hx.and (hm' ht),
obtain ⟨m, hm⟩ := this.exists,
exact ⟨F m x, ⟨hm.2, htsymm hm.1⟩⟩,
end
/-- A uniformly Cauchy sequence converges uniformly to its limit -/
lemma uniform_cauchy_seq_on.tendsto_uniformly_on_of_tendsto [ne_bot p]
(hF : uniform_cauchy_seq_on F p s) (hF' : ∀ x : α, x ∈ s → tendsto (λ n, F n x) p (𝓝 (f x))) :
tendsto_uniformly_on F f p s :=
tendsto_uniformly_on_iff_tendsto_uniformly_on_filter.mpr
(hF.uniform_cauchy_seq_on_filter.tendsto_uniformly_on_filter_of_tendsto hF')
lemma uniform_cauchy_seq_on_filter.mono_left {p'' : filter ι}
(hf : uniform_cauchy_seq_on_filter F p p') (hp : p'' ≤ p) :
uniform_cauchy_seq_on_filter F p'' p' :=
begin
intros u hu,
have := (hf u hu).filter_mono (p'.prod_mono_left (filter.prod_mono hp hp)),
exact this.mono (by simp),
end
lemma uniform_cauchy_seq_on_filter.mono_right {p'' : filter α}
(hf : uniform_cauchy_seq_on_filter F p p') (hp : p'' ≤ p') :
uniform_cauchy_seq_on_filter F p p'' :=
begin
intros u hu,
have := (hf u hu).filter_mono ((p ×ᶠ p).prod_mono_right hp),
exact this.mono (by simp),
end
lemma uniform_cauchy_seq_on.mono {s' : set α} (hf : uniform_cauchy_seq_on F p s) (hss' : s' ⊆ s) :
uniform_cauchy_seq_on F p s' :=
begin
rw uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter at hf ⊢,
exact hf.mono_right (le_principal_iff.mpr $mem_principal.mpr hss'),
end
/-- Composing on the right by a function preserves uniform Cauchy sequences -/
lemma uniform_cauchy_seq_on_filter.comp {γ : Type*} (hf : uniform_cauchy_seq_on_filter F p p')
(g : γ → α) :
uniform_cauchy_seq_on_filter (λ n, F n ∘ g) p (p'.comap g) :=
begin
intros u hu,
obtain ⟨pa, hpa, pb, hpb, hpapb⟩ := eventually_prod_iff.mp (hf u hu),
rw eventually_prod_iff,
refine ⟨pa, hpa, pb ∘ g, _, λ x hx y hy, hpapb hx hy⟩,
exact eventually_comap.mpr (hpb.mono (λ x hx y hy, by simp only [hx, hy, function.comp_app])),
end
/-- Composing on the right by a function preserves uniform Cauchy sequences -/
lemma uniform_cauchy_seq_on.comp {γ : Type*} (hf : uniform_cauchy_seq_on F p s) (g : γ → α) :
uniform_cauchy_seq_on (λ n, F n ∘ g) p (g ⁻¹' s) :=
begin
rw uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter at hf ⊢,
simpa only [uniform_cauchy_seq_on, comap_principal] using (hf.comp g),
end
/-- Composing on the left by a uniformly continuous function preserves
uniform Cauchy sequences -/
lemma uniform_continuous.comp_uniform_cauchy_seq_on [uniform_space γ] {g : β → γ}
(hg : uniform_continuous g) (hf : uniform_cauchy_seq_on F p s) :
uniform_cauchy_seq_on (λ n, g ∘ (F n)) p s :=
λ u hu, hf _ (hg hu)
lemma uniform_cauchy_seq_on.prod_map {ι' α' β' : Type*} [uniform_space β']
{F' : ι' → α' → β'} {p' : filter ι'} {s' : set α'}
(h : uniform_cauchy_seq_on F p s) (h' : uniform_cauchy_seq_on F' p' s') :
uniform_cauchy_seq_on (λ (i : ι × ι'), prod.map (F i.1) (F' i.2))
(p.prod p') (s ×ˢ s') :=
begin
intros u hu,
rw [uniformity_prod_eq_prod, mem_map, mem_prod_iff] at hu,
obtain ⟨v, hv, w, hw, hvw⟩ := hu,
simp_rw [mem_prod, prod_map, and_imp, prod.forall],
rw [← set.image_subset_iff] at hvw,
apply (tendsto_swap4_prod.eventually ((h v hv).prod_mk (h' w hw))).mono,
intros x hx a b ha hb,
refine hvw ⟨_, mk_mem_prod (hx.1 a ha) (hx.2 b hb), rfl⟩,
end
lemma uniform_cauchy_seq_on.prod {ι' β' : Type*} [uniform_space β'] {F' : ι' → α → β'}
{p' : filter ι'}
(h : uniform_cauchy_seq_on F p s) (h' : uniform_cauchy_seq_on F' p' s) :
uniform_cauchy_seq_on (λ (i : ι × ι') a, (F i.fst a, F' i.snd a)) (p ×ᶠ p') s :=
(congr_arg _ s.inter_self).mp ((h.prod_map h').comp (λ a, (a, a)))
lemma uniform_cauchy_seq_on.prod' {β' : Type*} [uniform_space β'] {F' : ι → α → β'}
(h : uniform_cauchy_seq_on F p s) (h' : uniform_cauchy_seq_on F' p s) :
uniform_cauchy_seq_on (λ (i : ι) a, (F i a, F' i a)) p s :=
begin
intros u hu,
have hh : tendsto (λ x : ι, (x, x)) p (p ×ᶠ p), { exact tendsto_diag, },
exact (hh.prod_map hh).eventually ((h.prod h') u hu),
end
/-- If a sequence of functions is uniformly Cauchy on a set, then the values at each point form
a Cauchy sequence. -/
lemma uniform_cauchy_seq_on.cauchy_map [hp : ne_bot p]
(hf : uniform_cauchy_seq_on F p s) (hx : x ∈ s) :
cauchy (map (λ i, F i x) p) :=
begin
simp only [cauchy_map_iff, hp, true_and],
assume u hu,
rw mem_map,
filter_upwards [hf u hu] with p hp using hp x hx,
end
section seq_tendsto
lemma tendsto_uniformly_on_of_seq_tendsto_uniformly_on {l : filter ι} [l.is_countably_generated]
(h : ∀ u : ℕ → ι, tendsto u at_top l → tendsto_uniformly_on (λ n, F (u n)) f at_top s) :
tendsto_uniformly_on F f l s :=
begin
rw [tendsto_uniformly_on_iff_tendsto, tendsto_iff_seq_tendsto],
intros u hu,
rw tendsto_prod_iff' at hu,
specialize h (λ n, (u n).fst) hu.1,
rw tendsto_uniformly_on_iff_tendsto at h,
have : ((λ (q : ι × α), (f q.snd, F q.fst q.snd)) ∘ u)
= (λ (q : ℕ × α), (f q.snd, F ((λ (n : ℕ), (u n).fst) q.fst) q.snd)) ∘ (λ n, (n, (u n).snd)),
{ ext1 n, simp, },
rw this,
refine tendsto.comp h _,
rw tendsto_prod_iff',
exact ⟨tendsto_id, hu.2⟩,
end
lemma tendsto_uniformly_on.seq_tendsto_uniformly_on {l : filter ι}
(h : tendsto_uniformly_on F f l s) (u : ℕ → ι) (hu : tendsto u at_top l) :
tendsto_uniformly_on (λ n, F (u n)) f at_top s :=
begin
rw tendsto_uniformly_on_iff_tendsto at h ⊢,
have : (λ (q : ℕ × α), (f q.snd, F (u q.fst) q.snd))
= (λ (q : ι × α), (f q.snd, F q.fst q.snd)) ∘ (λ p : ℕ × α, (u p.fst, p.snd)),
{ ext1 x, simp, },
rw this,
refine h.comp _,
rw tendsto_prod_iff',
exact ⟨hu.comp tendsto_fst, tendsto_snd⟩,
end
lemma tendsto_uniformly_on_iff_seq_tendsto_uniformly_on {l : filter ι} [l.is_countably_generated] :
tendsto_uniformly_on F f l s
↔ ∀ u : ℕ → ι, tendsto u at_top l → tendsto_uniformly_on (λ n, F (u n)) f at_top s :=
⟨tendsto_uniformly_on.seq_tendsto_uniformly_on, tendsto_uniformly_on_of_seq_tendsto_uniformly_on⟩
lemma tendsto_uniformly_iff_seq_tendsto_uniformly {l : filter ι} [l.is_countably_generated] :
tendsto_uniformly F f l
↔ ∀ u : ℕ → ι, tendsto u at_top l → tendsto_uniformly (λ n, F (u n)) f at_top :=
begin
simp_rw ← tendsto_uniformly_on_univ,
exact tendsto_uniformly_on_iff_seq_tendsto_uniformly_on,
end
end seq_tendsto
variable [topological_space α]
/-- A sequence of functions `Fₙ` converges locally uniformly on a set `s` to a limiting function
`f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x ∈ s`, one
has `p`-eventually `(f y, Fₙ y) ∈ u` for all `y` in a neighborhood of `x` in `s`. -/
def tendsto_locally_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) :=
∀ u ∈ 𝓤 β, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u
/-- A sequence of functions `Fₙ` converges locally uniformly to a limiting function `f` with respect
to a filter `p` if, for any entourage of the diagonal `u`, for any `x`, one has `p`-eventually
`(f y, Fₙ y) ∈ u` for all `y` in a neighborhood of `x`. -/
def tendsto_locally_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) :=
∀ u ∈ 𝓤 β, ∀ (x : α), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u
lemma tendsto_locally_uniformly_on_iff_tendsto_locally_uniformly_comp_coe :
tendsto_locally_uniformly_on F f p s ↔
tendsto_locally_uniformly (λ i (x : s), F i x) (f ∘ coe) p :=
begin
refine forall₂_congr (λ V hV, _),
simp only [exists_prop, function.comp_app, set_coe.forall, subtype.coe_mk],
refine forall₂_congr (λ x hx, ⟨_, _⟩),
{ rintro ⟨t, ht₁, ht₂⟩,
obtain ⟨u, hu₁, hu₂⟩ := mem_nhds_within_iff_exists_mem_nhds_inter.mp ht₁,
exact ⟨coe⁻¹' u,
(mem_nhds_subtype _ _ _).mpr ⟨u, hu₁, rfl.subset⟩,
ht₂.mono (λ i hi y hy₁ hy₂, hi y (hu₂ ⟨hy₂, hy₁⟩))⟩, },
{ rintro ⟨t, ht₁, ht₂⟩,
obtain ⟨u, hu₁, hu₂⟩ := (mem_nhds_subtype _ _ _).mp ht₁,
exact ⟨u ∩ s,
mem_nhds_within_iff_exists_mem_nhds_inter.mpr ⟨u, hu₁, rfl.subset⟩,
ht₂.mono (λ i hi y hy, hi y hy.2 (hu₂ (by simp [hy.1])))⟩, },
end
lemma tendsto_locally_uniformly_iff_forall_tendsto :
tendsto_locally_uniformly F f p ↔
∀ x, tendsto (λ (y : ι × α), (f y.2, F y.1 y.2)) (p ×ᶠ (𝓝 x)) (𝓤 β) :=
begin
simp only [tendsto_locally_uniformly, filter.forall_in_swap, tendsto_def, mem_prod_iff,
set.prod_subset_iff],
refine forall₃_congr (λ x u hu, ⟨_, _⟩),
{ rintros ⟨n, hn, hp⟩,
exact ⟨_, hp, n, hn, λ i hi a ha, hi a ha⟩, },
{ rintros ⟨I, hI, n, hn, hu⟩,
exact ⟨n, hn, by filter_upwards [hI] using hu⟩, },
end
protected lemma tendsto_uniformly_on.tendsto_locally_uniformly_on
(h : tendsto_uniformly_on F f p s) : tendsto_locally_uniformly_on F f p s :=
λ u hu x hx,⟨s, self_mem_nhds_within, by simpa using (h u hu)⟩
protected lemma tendsto_uniformly.tendsto_locally_uniformly
(h : tendsto_uniformly F f p) : tendsto_locally_uniformly F f p :=
λ u hu x, ⟨univ, univ_mem, by simpa using (h u hu)⟩
lemma tendsto_locally_uniformly_on.mono (h : tendsto_locally_uniformly_on F f p s) (h' : s' ⊆ s) :
tendsto_locally_uniformly_on F f p s' :=
begin
assume u hu x hx,
rcases h u hu x (h' hx) with ⟨t, ht, H⟩,
exact ⟨t, nhds_within_mono x h' ht, H.mono (λ n, id)⟩
end
lemma tendsto_locally_uniformly_on_Union {S : γ → set α} (hS : ∀ i, is_open (S i))
(h : ∀ i, tendsto_locally_uniformly_on F f p (S i)) :
tendsto_locally_uniformly_on F f p (⋃ i, S i) :=
begin
rintro v hv x ⟨_, ⟨i, rfl⟩, hi : x ∈ S i⟩,
obtain ⟨t, ht, ht'⟩ := h i v hv x hi,
refine ⟨t, _, ht'⟩,
rw (hS _).nhds_within_eq hi at ht,
exact mem_nhds_within_of_mem_nhds ht,
end
lemma tendsto_locally_uniformly_on_bUnion {s : set γ} {S : γ → set α}
(hS : ∀ i ∈ s, is_open (S i)) (h : ∀ i ∈ s, tendsto_locally_uniformly_on F f p (S i)) :
tendsto_locally_uniformly_on F f p (⋃ i ∈ s, S i) :=
by { rw bUnion_eq_Union, exact tendsto_locally_uniformly_on_Union (λ i, hS _ i.2) (λ i, h _ i.2) }
lemma tendsto_locally_uniformly_on_sUnion (S : set (set α)) (hS : ∀ s ∈ S, is_open s)
(h : ∀ s ∈ S, tendsto_locally_uniformly_on F f p s) :
tendsto_locally_uniformly_on F f p (⋃₀ S) :=
by { rw sUnion_eq_bUnion, exact tendsto_locally_uniformly_on_bUnion hS h }
lemma tendsto_locally_uniformly_on.union {s₁ s₂ : set α} (hs₁ : is_open s₁) (hs₂ : is_open s₂)
(h₁ : tendsto_locally_uniformly_on F f p s₁) (h₂ : tendsto_locally_uniformly_on F f p s₂) :
tendsto_locally_uniformly_on F f p (s₁ ∪ s₂) :=
by { rw ←sUnion_pair, refine tendsto_locally_uniformly_on_sUnion _ _ _; simp [*] }
lemma tendsto_locally_uniformly_on_univ :
tendsto_locally_uniformly_on F f p univ ↔ tendsto_locally_uniformly F f p :=
by simp [tendsto_locally_uniformly_on, tendsto_locally_uniformly, nhds_within_univ]
protected lemma tendsto_locally_uniformly.tendsto_locally_uniformly_on
(h : tendsto_locally_uniformly F f p) : tendsto_locally_uniformly_on F f p s :=
(tendsto_locally_uniformly_on_univ.mpr h).mono (subset_univ _)
/-- On a compact space, locally uniform convergence is just uniform convergence. -/
lemma tendsto_locally_uniformly_iff_tendsto_uniformly_of_compact_space [compact_space α] :
tendsto_locally_uniformly F f p ↔ tendsto_uniformly F f p :=
begin
refine ⟨λ h V hV, _, tendsto_uniformly.tendsto_locally_uniformly⟩,
choose U hU using h V hV,
obtain ⟨t, ht⟩ := is_compact_univ.elim_nhds_subcover' (λ k hk, U k) (λ k hk, (hU k).1),
replace hU := λ (x : t), (hU x).2,
rw ← eventually_all at hU,
refine hU.mono (λ i hi x, _),
specialize ht (mem_univ x),
simp only [exists_prop, mem_Union, set_coe.exists, exists_and_distrib_right,subtype.coe_mk] at ht,
obtain ⟨y, ⟨hy₁, hy₂⟩, hy₃⟩ := ht,
exact hi ⟨⟨y, hy₁⟩, hy₂⟩ x hy₃,
end
/-- For a compact set `s`, locally uniform convergence on `s` is just uniform convergence on `s`. -/
lemma tendsto_locally_uniformly_on_iff_tendsto_uniformly_on_of_compact (hs : is_compact s) :
tendsto_locally_uniformly_on F f p s ↔ tendsto_uniformly_on F f p s :=
begin
haveI : compact_space s := is_compact_iff_compact_space.mp hs,
refine ⟨λ h, _, tendsto_uniformly_on.tendsto_locally_uniformly_on⟩,
rwa [tendsto_locally_uniformly_on_iff_tendsto_locally_uniformly_comp_coe,
tendsto_locally_uniformly_iff_tendsto_uniformly_of_compact_space,
← tendsto_uniformly_on_iff_tendsto_uniformly_comp_coe] at h,
end
lemma tendsto_locally_uniformly_on.comp [topological_space γ] {t : set γ}
(h : tendsto_locally_uniformly_on F f p s)
(g : γ → α) (hg : maps_to g t s) (cg : continuous_on g t) :
tendsto_locally_uniformly_on (λ n, (F n) ∘ g) (f ∘ g) p t :=
begin
assume u hu x hx,
rcases h u hu (g x) (hg hx) with ⟨a, ha, H⟩,
have : g⁻¹' a ∈ 𝓝[t] x :=
((cg x hx).preimage_mem_nhds_within' (nhds_within_mono (g x) hg.image_subset ha)),
exact ⟨g ⁻¹' a, this, H.mono (λ n hn y hy, hn _ hy)⟩
end
lemma tendsto_locally_uniformly.comp [topological_space γ]
(h : tendsto_locally_uniformly F f p) (g : γ → α) (cg : continuous g) :
tendsto_locally_uniformly (λ n, (F n) ∘ g) (f ∘ g) p :=
begin
rw ← tendsto_locally_uniformly_on_univ at h ⊢,
rw continuous_iff_continuous_on_univ at cg,
exact h.comp _ (maps_to_univ _ _) cg
end
lemma tendsto_locally_uniformly_on_tfae [locally_compact_space α]
(G : ι → α → β) (g : α → β) (p : filter ι) (hs : is_open s) :
tfae [(tendsto_locally_uniformly_on G g p s),
(∀ K ⊆ s, is_compact K → tendsto_uniformly_on G g p K),
(∀ x ∈ s, ∃ v ∈ 𝓝[s] x, tendsto_uniformly_on G g p v)] :=
begin
tfae_have : 1 → 2,
{ rintro h K hK1 hK2,
exact (tendsto_locally_uniformly_on_iff_tendsto_uniformly_on_of_compact hK2).mp (h.mono hK1) },
tfae_have : 2 → 3,
{ rintro h x hx,
obtain ⟨K, ⟨hK1, hK2⟩, hK3⟩ := (compact_basis_nhds x).mem_iff.mp (hs.mem_nhds hx),
refine ⟨K, nhds_within_le_nhds hK1, h K hK3 hK2⟩ },
tfae_have : 3 → 1,
{ rintro h u hu x hx,
obtain ⟨v, hv1, hv2⟩ := h x hx,
exact ⟨v, hv1, hv2 u hu⟩ },
tfae_finish
end
lemma tendsto_locally_uniformly_on_iff_forall_is_compact [locally_compact_space α]
(hs : is_open s) :
tendsto_locally_uniformly_on F f p s ↔
∀ K ⊆ s, is_compact K → tendsto_uniformly_on F f p K :=
(tendsto_locally_uniformly_on_tfae F f p hs).out 0 1
lemma tendsto_locally_uniformly_on_iff_filter :
tendsto_locally_uniformly_on F f p s ↔
∀ x ∈ s, tendsto_uniformly_on_filter F f p (𝓝[s] x) :=
begin
simp only [tendsto_uniformly_on_filter, eventually_prod_iff],
split,
{ rintro h x hx u hu,
obtain ⟨s, hs1, hs2⟩ := h u hu x hx,
exact ⟨_, hs2, _, eventually_of_mem hs1 (λ x, id), λ i hi y hy, hi y hy⟩ },
{ rintro h u hu x hx,
obtain ⟨pa, hpa, pb, hpb, h⟩ := h x hx u hu,
refine ⟨pb, hpb, eventually_of_mem hpa (λ i hi y hy, h hi hy)⟩ }
end
lemma tendsto_locally_uniformly_iff_filter :
tendsto_locally_uniformly F f p ↔
∀ x, tendsto_uniformly_on_filter F f p (𝓝 x) :=
by simpa [← tendsto_locally_uniformly_on_univ, ← nhds_within_univ] using
@tendsto_locally_uniformly_on_iff_filter _ _ _ _ F f univ p _
lemma tendsto_locally_uniformly_on.tendsto_at (hf : tendsto_locally_uniformly_on F f p s)
{a : α} (ha : a ∈ s) :
tendsto (λ i, F i a) p (𝓝 (f a)) :=
begin
refine ((tendsto_locally_uniformly_on_iff_filter.mp hf) a ha).tendsto_at _,
simpa only [filter.principal_singleton] using pure_le_nhds_within ha
end
lemma tendsto_locally_uniformly_on.unique [p.ne_bot] [t2_space β] {g : α → β}
(hf : tendsto_locally_uniformly_on F f p s) (hg : tendsto_locally_uniformly_on F g p s) :
s.eq_on f g :=
λ a ha, tendsto_nhds_unique (hf.tendsto_at ha) (hg.tendsto_at ha)
lemma tendsto_locally_uniformly_on.congr {G : ι → α → β}
(hf : tendsto_locally_uniformly_on F f p s) (hg : ∀ n, s.eq_on (F n) (G n)) :
tendsto_locally_uniformly_on G f p s :=
begin
rintro u hu x hx,
obtain ⟨t, ht, h⟩ := hf u hu x hx,
refine ⟨s ∩ t, inter_mem self_mem_nhds_within ht, _⟩,
filter_upwards [h] with i hi y hy using hg i hy.1 ▸ hi y hy.2
end
lemma tendsto_locally_uniformly_on.congr_right {g : α → β}
(hf : tendsto_locally_uniformly_on F f p s) (hg : s.eq_on f g) :
tendsto_locally_uniformly_on F g p s :=
begin
rintro u hu x hx,
obtain ⟨t, ht, h⟩ := hf u hu x hx,
refine ⟨s ∩ t, inter_mem self_mem_nhds_within ht, _⟩,
filter_upwards [h] with i hi y hy using hg hy.1 ▸ hi y hy.2
end
/-!
### Uniform approximation
In this section, we give lemmas ensuring that a function is continuous if it can be approximated
uniformly by continuous functions. We give various versions, within a set or the whole space, at
a single point or at all points, with locally uniform approximation or uniform approximation. All
the statements are derived from a statement about locally uniform approximation within a set at
a point, called `continuous_within_at_of_locally_uniform_approx_of_continuous_within_at`. -/
/-- A function which can be locally uniformly approximated by functions which are continuous
within a set at a point is continuous within this set at this point. -/
lemma continuous_within_at_of_locally_uniform_approx_of_continuous_within_at
(hx : x ∈ s) (L : ∀ u ∈ 𝓤 β, ∃ (t ∈ 𝓝[s] x) (F : α → β), continuous_within_at F s x ∧
∀ y ∈ t, (f y, F y) ∈ u) : continuous_within_at f s x :=
begin
apply uniform.continuous_within_at_iff'_left.2 (λ u₀ hu₀, _),
obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ :=
comp_mem_uniformity_sets hu₀,
obtain ⟨u₂, h₂, hsymm, u₂₁⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β),
(∀{a b}, (a, b) ∈ u → (b, a) ∈ u) ∧ comp_rel u u ⊆ u₁ := comp_symm_of_uniformity h₁,
rcases L u₂ h₂ with ⟨t, tx, F, hFc, hF⟩,
have A : ∀ᶠ y in 𝓝[s] x, (f y, F y) ∈ u₂ := eventually.mono tx hF,
have B : ∀ᶠ y in 𝓝[s] x, (F y, F x) ∈ u₂ :=
uniform.continuous_within_at_iff'_left.1 hFc h₂,
have C : ∀ᶠ y in 𝓝[s] x, (f y, F x) ∈ u₁ :=
(A.and B).mono (λ y hy, u₂₁ (prod_mk_mem_comp_rel hy.1 hy.2)),
have : (F x, f x) ∈ u₁ :=
u₂₁ (prod_mk_mem_comp_rel (refl_mem_uniformity h₂) (hsymm (A.self_of_nhds_within hx))),
exact C.mono (λ y hy, u₁₀ (prod_mk_mem_comp_rel hy this))
end
/-- A function which can be locally uniformly approximated by functions which are continuous at
a point is continuous at this point. -/
lemma continuous_at_of_locally_uniform_approx_of_continuous_at
(L : ∀ u ∈ 𝓤 β, ∃ (t ∈ 𝓝 x) F, continuous_at F x ∧ ∀ y ∈ t, (f y, F y) ∈ u) :
continuous_at f x :=
begin
rw ← continuous_within_at_univ,
apply continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (mem_univ _) _,
simpa only [exists_prop, nhds_within_univ, continuous_within_at_univ] using L
end
/-- A function which can be locally uniformly approximated by functions which are continuous
on a set is continuous on this set. -/
lemma continuous_on_of_locally_uniform_approx_of_continuous_within_at
(L : ∀ (x ∈ s) (u ∈ 𝓤 β), ∃ (t ∈ 𝓝[s] x) F,
continuous_within_at F s x ∧ ∀ y ∈ t, (f y, F y) ∈ u) : continuous_on f s :=
λ x hx, continuous_within_at_of_locally_uniform_approx_of_continuous_within_at hx (L x hx)
/-- A function which can be uniformly approximated by functions which are continuous on a set
is continuous on this set. -/
lemma continuous_on_of_uniform_approx_of_continuous_on
(L : ∀ u ∈ 𝓤 β, ∃ F, continuous_on F s ∧ ∀ y ∈ s, (f y, F y) ∈ u) : continuous_on f s :=
continuous_on_of_locally_uniform_approx_of_continuous_within_at $
λ x hx u hu, ⟨s, self_mem_nhds_within, (L u hu).imp $
λ F hF, ⟨hF.1.continuous_within_at hx, hF.2⟩⟩
/-- A function which can be locally uniformly approximated by continuous functions is continuous. -/
lemma continuous_of_locally_uniform_approx_of_continuous_at
(L : ∀ (x : α), ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ F, continuous_at F x ∧ ∀ y ∈ t, (f y, F y) ∈ u) :
continuous f :=
continuous_iff_continuous_at.2 $ λ x, continuous_at_of_locally_uniform_approx_of_continuous_at (L x)
/-- A function which can be uniformly approximated by continuous functions is continuous. -/
lemma continuous_of_uniform_approx_of_continuous
(L : ∀ u ∈ 𝓤 β, ∃ F, continuous F ∧ ∀ y, (f y, F y) ∈ u) : continuous f :=
continuous_iff_continuous_on_univ.mpr $ continuous_on_of_uniform_approx_of_continuous_on $
by simpa [continuous_iff_continuous_on_univ] using L
/-!
### Uniform limits
From the previous statements on uniform approximation, we deduce continuity results for uniform
limits.
-/
/-- A locally uniform limit on a set of functions which are continuous on this set is itself
continuous on this set. -/
protected lemma tendsto_locally_uniformly_on.continuous_on
(h : tendsto_locally_uniformly_on F f p s) (hc : ∀ᶠ n in p, continuous_on (F n) s) [ne_bot p] :
continuous_on f s :=
begin
apply continuous_on_of_locally_uniform_approx_of_continuous_within_at (λ x hx u hu, _),
rcases h u hu x hx with ⟨t, ht, H⟩,
rcases (hc.and H).exists with ⟨n, hFc, hF⟩,
exact ⟨t, ht, ⟨F n, hFc.continuous_within_at hx, hF⟩⟩
end
/-- A uniform limit on a set of functions which are continuous on this set is itself continuous
on this set. -/
protected lemma tendsto_uniformly_on.continuous_on (h : tendsto_uniformly_on F f p s)
(hc : ∀ᶠ n in p, continuous_on (F n) s) [ne_bot p] : continuous_on f s :=
h.tendsto_locally_uniformly_on.continuous_on hc
/-- A locally uniform limit of continuous functions is continuous. -/
protected lemma tendsto_locally_uniformly.continuous (h : tendsto_locally_uniformly F f p)
(hc : ∀ᶠ n in p, continuous (F n)) [ne_bot p] : continuous f :=
continuous_iff_continuous_on_univ.mpr $ h.tendsto_locally_uniformly_on.continuous_on $
hc.mono $ λ n hn, hn.continuous_on
/-- A uniform limit of continuous functions is continuous. -/
protected lemma tendsto_uniformly.continuous (h : tendsto_uniformly F f p)
(hc : ∀ᶠ n in p, continuous (F n)) [ne_bot p] : continuous f :=
h.tendsto_locally_uniformly.continuous hc
/-!
### Composing limits under uniform convergence
In general, if `Fₙ` converges pointwise to a function `f`, and `gₙ` tends to `x`, it is not true
that `Fₙ gₙ` tends to `f x`. It is true however if the convergence of `Fₙ` to `f` is uniform. In
this paragraph, we prove variations around this statement.
-/
/-- If `Fₙ` converges locally uniformly on a neighborhood of `x` within a set `s` to a function `f`
which is continuous at `x` within `s `, and `gₙ` tends to `x` within `s`, then `Fₙ (gₙ)` tends
to `f x`. -/
lemma tendsto_comp_of_locally_uniform_limit_within
(h : continuous_within_at f s x) (hg : tendsto g p (𝓝[s] x))
(hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) :
tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
begin
apply uniform.tendsto_nhds_right.2 (λ u₀ hu₀, _),
obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ :=
comp_mem_uniformity_sets hu₀,
rcases hunif u₁ h₁ with ⟨s, sx, hs⟩,
have A : ∀ᶠ n in p, g n ∈ s := hg sx,
have B : ∀ᶠ n in p, (f x, f (g n)) ∈ u₁ := hg (uniform.continuous_within_at_iff'_right.1 h h₁),
refine ((hs.and A).and B).mono (λ y hy, _),
rcases hy with ⟨⟨H1, H2⟩, H3⟩,
exact u₁₀ (prod_mk_mem_comp_rel H3 (H1 _ H2))
end
/-- If `Fₙ` converges locally uniformly on a neighborhood of `x` to a function `f` which is
continuous at `x`, and `gₙ` tends to `x`, then `Fₙ (gₙ)` tends to `f x`. -/
lemma tendsto_comp_of_locally_uniform_limit (h : continuous_at f x) (hg : tendsto g p (𝓝 x))
(hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) :
tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
begin
rw ← continuous_within_at_univ at h,
rw ← nhds_within_univ at hunif hg,
exact tendsto_comp_of_locally_uniform_limit_within h hg hunif
end
/-- If `Fₙ` tends locally uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then
`Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s` and `x ∈ s`. -/
lemma tendsto_locally_uniformly_on.tendsto_comp (h : tendsto_locally_uniformly_on F f p s)
(hf : continuous_within_at f s x) (hx : x ∈ s) (hg : tendsto g p (𝓝[s] x)) :
tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, h u hu x hx)
/-- If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ`
tends to `f x` if `f` is continuous at `x` within `s`. -/
lemma tendsto_uniformly_on.tendsto_comp (h : tendsto_uniformly_on F f p s)
(hf : continuous_within_at f s x) (hg : tendsto g p (𝓝[s] x)) :
tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu,
⟨s, self_mem_nhds_within, h u hu⟩)
/-- If `Fₙ` tends locally uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/
lemma tendsto_locally_uniformly.tendsto_comp (h : tendsto_locally_uniformly F f p)
(hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
tendsto_comp_of_locally_uniform_limit hf hg (λ u hu, h u hu x)
/-- If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/
lemma tendsto_uniformly.tendsto_comp (h : tendsto_uniformly F f p)
(hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
h.tendsto_locally_uniformly.tendsto_comp hf hg
|
fae81aa5341d762ac5878cba25ffa6191ccae0b4 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/data/multiset.lean | bc7f66a7cd96647360ba7c5f4685cbc32195d58d | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 134,572 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Multisets.
-/
import data.list.sort
import data.list.intervals
import data.list.antidiagonal
import data.string.basic
import algebra.group_power
import control.traversable.lemmas
import control.traversable.instances
open list subtype nat
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale add_monoid
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.is_setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/- empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
@[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl
theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] :=
iff.trans coe_eq_coe perm_nil
/- cons -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound (p.cons a))
notation a :: b := cons a b
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a::s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a::l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a::s = b::s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t :=
by rintros ⟨l₁⟩ ⟨l₂⟩; simp
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s :=
by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
h.rec_heq
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)}
{C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s :=
mem_cons.2 (or.inl rfl)
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl
theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s :=
⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
@[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m :=
assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this
@[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm
lemma cons_eq_cons {a b : α} {as bs : multiset α} :
a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) :=
begin
haveI : decidable_eq α := classical.dec_eq α,
split,
{ assume eq,
by_cases a = b,
{ subst h, simp * at * },
{ have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _,
have : a ∈ bs, by simpa [h],
rcases exists_cons_of_mem this with ⟨cs, hcs⟩,
simp [h, hcs],
have : a :: as = b :: a :: cs, by simp [eq, hcs],
have : a :: as = a :: b :: cs, by rwa [cons_swap],
simpa using this } },
{ assume h,
rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ simp * },
{ simp [*, cons_swap a b] } }
end
end mem
/- subset -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
end subset
/- multiset order -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := by rintros ⟨l⟩; exact subperm.refl _,
le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _,
le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, (nil_sublist l).subperm
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨(sublist_cons _ _).subperm,
λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $
((sublist_or_mem_of_sublist s).resolve_right m₁).subperm)
end
/- cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card (s : multiset α) : ℕ :=
quot.lift_on s length $ λ l₁ l₂, perm.length_eq
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
@[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
theorem strong_induction_eq {p : multiset α → Sort*}
(s : multiset α) (H) : @strong_induction_on _ p s H =
H s (λ t h, @strong_induction_on _ p t H) :=
by rw [strong_induction_on]
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/- singleton -/
@[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp
theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _
theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _
@[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 :=
⟨quot.induction_on s $ λ l h,
(list.length_eq_one.1 h).imp $ λ a, congr_arg coe,
λ ⟨a, e⟩, e.symm ▸ rfl⟩
/- add -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_add_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $
by simpa [multiset.add_comm] using h,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) :=
by rw [add_comm, cons_add, add_comm]
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
@[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
quotient.induction_on₂ s t length_append
lemma card_smul (s : multiset α) (n : ℕ) :
(n • s).card = n * s.card :=
by induction n; simp [succ_smul, *, nat.succ_mul]; cc
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩,
λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩
instance : canonically_ordered_add_monoid (multiset α) :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _,
le_iff_exists_add := @le_iff_exists_add _,
bot := 0,
bot_le := multiset.zero_le,
..multiset.ordered_cancel_add_comm_monoid }
/- repeat -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl
@[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat]
@[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩
/- range -/
/-- `range n` is the multiset lifted from the list `range n`,
that is, the set `{0, 1, ..., n-1}`. -/
def range (n : ℕ) : multiset ℕ := range n
@[simp] theorem range_zero : range 0 = 0 := rfl
@[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n :=
by rw [range, range_concat, ← coe_add, add_comm]; refl
@[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self
/- erase -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (p.erase a))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp, priority 990]
theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp, priority 980]
theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) :
(s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) :
a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) :
(s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, (erase_sublist a l).subperm
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} :
a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s :=
λ h, card_lt_of_lt (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s :=
card_le_of_le (erase_le a s)
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/- map -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (p.map f))
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s :=
quot.induction_on s $ λ l, rfl
lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
instance (f : α → β) : is_add_monoid_hom (map f) :=
{ map_add := map_add _, map_zero := map_zero _ }
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
@[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 :=
by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero]
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_inj H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _
theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
/- fold -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, p.foldl_eq H b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, p.foldr_eq H b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive]
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, to_additive]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
@[simp, to_additive]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s :=
foldr_cons _ _ _ _ _
@[to_additive]
theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp
@[simp, to_additive]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) :=
{ map_add := sum_add, map_zero := sum_zero }
lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) :
∀n, (add_monoid.smul n m).prod = m.prod ^ n
| 0 := rfl
| (n + 1) :=
by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.pow_one, prod_add, prod_smul n]
@[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a :=
@prod_repeat (multiplicative α) _
attribute [to_additive] prod_repeat
lemma prod_map_one [comm_monoid γ] {m : multiset α} :
prod (m.map (λa, (1 : γ))) = (1 : γ) :=
by simp
lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} :
sum (m.map (λa, (0 : γ))) = (0 : γ) :=
by simp
attribute [to_additive] prod_map_one
@[simp, to_additive]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} :
prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih])
lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ},
sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) :=
@prod_map_prod_map _ _ (multiplicative γ) _
attribute [to_additive] prod_map_prod_map
lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, b * f a)) = b * sum (s.map f) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add])
lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, f a * b)) = sum (s.map f) * b :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul])
@[to_additive]
lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α → β) [is_monoid_hom f] :
(s.map f).prod = f s.prod :=
quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (s.map f).prod (s.map g).prod :=
quotient.induction_on s $ λ l,
by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod]
lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) :
f s.sum ≤ (s.map f).sum :=
multiset.induction_on s (le_of_eq h_zero) $
assume a s ih, by rw [sum_cons, map_cons, sum_cons];
from le_trans (h_add a s.sum) (add_le_add_left' ih)
lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum :=
multiset.induction_on s (λ _, dvd_zero _)
(λ x s ih h, by rw sum_cons; exact dvd_add
(h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy)))))
/- join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/- bind -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 :=
by simp [bind, join]
@[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) :
bind s (λa, f a + g a) = bind s f + bind s g :=
by simp [bind, join]
@[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) :
bind s (λa, f a :: g a) = map f s + bind s g :=
multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt})
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λa, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λa, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/- product -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a :: s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp; cc
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
(a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp; cc
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/- map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ pp.pmap f
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a::m, p b), pmap f (a :: m) h =
f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_exists
variables {m : multiset α}
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
def decidable_exists_multiset {p : α → Prop} [decidable_pred p] :
decidable (∃ x ∈ m, p x) :=
quotient.rec_on_subsingleton m list.decidable_exists_mem
instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∃a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩)
(λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩))
end decidable_pi_exists
/- subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that
`count a (s - t) = count a s - count a t` for all `a`. -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.diff p₂
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) }
@[simp] theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t :=
begin
revert t,
refine multiset.induction_on s (by simp) (λ a s IH t h, _),
have := cons_erase (mem_of_le h (mem_cons_self _ _)),
rw [cons_add, sub_cons, IH, this],
exact (cons_le_cons_iff a).1 (this.symm ▸ h)
end
theorem sub_add' : s - (t + u) = s - t - u :=
quotient.induction_on₃ s t u $
λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _
theorem sub_add_cancel (h : t ≤ s) : s - t + t = s :=
by rw [add_comm, add_sub_of_le h]
@[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t :=
multiset.induction_on s (by simp)
(λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH])
@[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s :=
by rw [add_comm, add_sub_cancel_left]
theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u :=
by revert s t h; exact
multiset.induction_on u (by simp {contextual := tt})
(λ a u IH s t h, by simp [IH, erase_le_erase a h])
theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s :=
le_induction_on h $ λ l₁ l₂ h, begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u,
{ refl },
{ rw [← cons_coe, sub_cons],
exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) },
{ rw [← cons_coe, sub_cons, ← cons_coe, sub_cons],
exact IH _ }
end
theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp)
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
theorem le_sub_add (s t : multiset α) : s ≤ s - t + t :=
sub_le_iff_le_add.1 (le_refl _)
theorem sub_le_self (s t : multiset α) : s - t ≤ s :=
sub_le_iff_le_add.2 (le_add_right _ _)
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm
/- union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (sub_le_sub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
@[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
congr_arg coe (by rw [list.map_append f, list.map_diff finj])
/- inter -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.bag_inter p₂
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a :: s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
(bag_inter_sublist_left _ _).subperm
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t,
by rw [add_comm t, sub_add', add_sub_cancel]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) :=
by simpa using add_union_distrib (a::0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $
by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)]
end
/- filter -/
section
variables {p : α → Prop} [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ h.filter p)
@[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p]
(l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
{s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h
@[simp] theorem filter_add (s t : multiset α) :
filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, (filter_sublist _).subperm
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter h).subperm
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter $ inter_le_left _ _)
(filter_le_filter $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _) (filter_le _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) :
filter p (filter q s) = filter (λ a, p a ∧ q a) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter l
theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) :
filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s :=
multiset.induction_on s rfl $ λ a s IH,
by by_cases p a; by_cases q a; simp *
theorem filter_add_not (s : multiset α) :
filter p s + filter (λ a, ¬ p a) s = s :=
by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em]
/- filter_map -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $ h.filter_map f)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) :
filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a :: s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a :: s) = b :: filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm
/- powerset -/
def powerset_aux (l : list α) : list (multiset α) :=
0 :: sublists_aux l (λ x y, x :: y)
theorem powerset_aux_eq_map_coe {l : list α} :
powerset_aux l = (sublists l).map coe :=
by simp [powerset_aux, sublists];
rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) =
sublists_aux l (λ x, list.cons ↑x),
from sublists_aux₁_eq_sublists_aux _ _,
sublists_aux_cons_eq_sublists_aux₁,
← bind_ret_eq_map, sublists_aux₁_bind]; refl
@[simp] theorem mem_powerset_aux {l : list α} {s} :
s ∈ powerset_aux l ↔ s ≤ ↑l :=
quotient.induction_on s $
by simp [powerset_aux_eq_map_coe, subperm, and.comm]
def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe
theorem powerset_aux_perm_powerset_aux' {l : list α} :
powerset_aux l ~ powerset_aux' l :=
by rw powerset_aux_eq_map_coe; exact (sublists_perm_sublists' _).map _
@[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl
@[simp] theorem powerset_aux'_cons (a : α) (l : list α) :
powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) :=
by simp [powerset_aux']; refl
theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux' l₁ ~ powerset_aux' l₂ :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact IH.append (IH.map _) },
{ simp, apply perm.append_left,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_append_comm.append_right _ },
{ exact IH₁.trans IH₂ }
end
theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux l₁ ~ powerset_aux l₂ :=
powerset_aux_perm_powerset_aux'.trans $
(powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm
def powerset (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_aux l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_aux_perm h))
theorem powerset_coe (l : list α) :
@powerset α l = ((sublists l).map coe : list (multiset α)) :=
congr_arg coe powerset_aux_eq_map_coe
@[simp] theorem powerset_coe' (l : list α) :
@powerset α l = ((sublists' l).map coe : list (multiset α)) :=
quot.sound powerset_aux_perm_powerset_aux'
@[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl
@[simp] theorem powerset_cons (a : α) (s) :
powerset (a::s) = powerset s + map (cons a) (powerset s) :=
quotient.induction_on s $ λ l, by simp; refl
@[simp] theorem mem_powerset {s t : multiset α} :
s ∈ powerset t ↔ s ≤ t :=
quotient.induction_on₂ s t $ by simp [subperm, and.comm]
theorem map_single_le_powerset (s : multiset α) :
s.map (λ a, a::0) ≤ powerset s :=
quotient.induction_on s $ λ l, begin
simp [powerset_coe],
show l.map (coe ∘ list.ret) <+~ (sublists l).map coe,
rw ← list.map_map,
exact ((map_ret_sublist_sublists _).map _).subperm
end
@[simp] theorem card_powerset (s : multiset α) :
card (powerset s) = 2 ^ card s :=
quotient.induction_on s $ by simp
/- antidiagonal -/
theorem revzip_powerset_aux {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists _ _ _ h)
end
theorem revzip_powerset_aux' {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists' _ _ _ h)
end
theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α)
{l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) :
revzip l' = l'.map (λ x, (x, ↑l - x)) :=
begin
have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s))
(revzip l') ((revzip l').map prod.fst),
{ rw forall₂_map_right_iff,
apply forall₂_same, rintro ⟨s, t⟩ h,
dsimp, rw [← H h, add_sub_cancel_left] },
rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa
end
theorem revzip_powerset_aux_perm_aux' {l : list α} :
revzip (powerset_aux l) ~ revzip (powerset_aux' l) :=
begin
haveI := classical.dec_eq α,
rw [revzip_powerset_aux_lemma l revzip_powerset_aux,
revzip_powerset_aux_lemma l revzip_powerset_aux'],
exact powerset_aux_perm_powerset_aux'.map _
end
theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) :=
begin
haveI := classical.dec_eq α,
simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p],
exact (powerset_aux_perm p).map _
end
/-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)`
such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/
def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) :=
quot.lift_on s
(λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α)))
(λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h))
theorem antidiagonal_coe (l : list α) :
@antidiagonal α l = revzip (powerset_aux l) := rfl
@[simp] theorem antidiagonal_coe' (l : list α) :
@antidiagonal α l = revzip (powerset_aux' l) :=
quot.sound revzip_powerset_aux_perm_aux'
/-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s`
if and only if `t₁ + t₂ = s`. -/
@[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} :
x ∈ antidiagonal s ↔ x.1 + x.2 = s :=
quotient.induction_on s $ λ l, begin
simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩,
haveI := classical.dec_eq α,
simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm],
cases x with x₁ x₂,
exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩
end
@[simp] theorem antidiagonal_map_fst (s : multiset α) :
(antidiagonal s).map prod.fst = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_map_snd (s : multiset α) :
(antidiagonal s).map prod.snd = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0)::0 := rfl
@[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a::s) =
map (prod.map id (cons a)) (antidiagonal s) +
map (prod.map (cons a) id) (antidiagonal s) :=
quotient.induction_on s $ λ l, begin
simp only [revzip, reverse_append, quot_mk_to_coe, coe_eq_coe, powerset_aux'_cons, cons_coe,
coe_map, antidiagonal_coe', coe_add],
rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)],
{congr; simp}, {simp}
end
@[simp] theorem card_antidiagonal (s : multiset α) :
card (antidiagonal s) = 2 ^ card s :=
by have := card_powerset s;
rwa [← antidiagonal_map_fst, card_map] at this
lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} :
prod (s.map (λa, f a + g a)) =
sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) :=
begin
refine s.induction_on _ _,
{ simp },
{ assume a s ih,
simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm],
cc },
end
/- powerset_len -/
def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) :=
sublists_len_aux n l coe []
theorem powerset_len_aux_eq_map_coe {n} {l : list α} :
powerset_len_aux n l = (sublists_len n l).map coe :=
by rw [powerset_len_aux, sublists_len_aux_eq, append_nil]
@[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} :
s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n :=
quotient.induction_on s $
by simp [powerset_len_aux_eq_map_coe, subperm]; exact
λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩,
λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩
@[simp] theorem powerset_len_aux_zero (l : list α) :
powerset_len_aux 0 l = [0] :=
by simp [powerset_len_aux_eq_map_coe]
@[simp] theorem powerset_len_aux_nil (n : ℕ) :
powerset_len_aux (n+1) (@nil α) = [] := rfl
@[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) :
powerset_len_aux (n+1) (a::l) =
powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) :=
by simp [powerset_len_aux_eq_map_coe]; refl
theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_len_aux n l₁ ~ powerset_len_aux n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl},
{ simp, exact IH.append ((IHn p).map _) },
{ simp, apply perm.append_left,
cases n, {simp, apply perm.swap},
simp,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_append_comm.append_right _ },
{ exact IH₁.trans IH₂ }
end
def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_len_aux n l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h))
theorem powerset_len_coe' (n) (l : list α) :
@powerset_len α n l = powerset_len_aux n l := rfl
theorem powerset_len_coe (n) (l : list α) :
@powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) :=
congr_arg coe powerset_len_aux_eq_map_coe
@[simp] theorem powerset_len_zero_left (s : multiset α) :
powerset_len 0 s = 0::0 :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem powerset_len_zero_right (n : ℕ) :
@powerset_len α (n + 1) 0 = 0 := rfl
@[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) :
powerset_len (n + 1) (a::s) =
powerset_len (n + 1) s + map (cons a) (powerset_len n s) :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} :
s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n :=
quotient.induction_on t $ λ l, by simp [powerset_len_coe']
@[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) :
card (powerset_len n s) = nat.choose (card s) n :=
quotient.induction_on s $ by simp [powerset_len_coe]
theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) :
powerset_len n s ≤ powerset s :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact
((sublists_len_sublist_sublists' _ _).map _).subperm
theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) :
powerset_len n s ≤ powerset_len n t :=
le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact
((sublists_len_sublist_of_sublist _ h).map _).subperm
/- countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 :=
quot.induction_on s countp_cons_of_pos
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s :=
quot.induction_on s countp_cons_of_neg
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) :=
{ map_add := countp_add, map_zero := countp_zero _ }
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h)
@[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) :
countp p (filter q s) = countp (λ a, p a ∧ q a) s :=
by simp [countp_eq_card_filter]
end
/- count -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_singleton (a : α) : count a (a::0) = 1 :=
by simp
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add
instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) :=
countp.is_add_monoid_hom
@[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s :=
by induction n; simp [*, succ_smul', succ_mul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
@[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a::erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp, priority 980]
theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, sub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, sub_add_min],
end
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) (by simp)
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {s : multiset α} (h : p a) : count a (filter p s) = count a s :=
quot.induction_on s $ λ l, count_filter h
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[ext]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
@[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) :=
by ext; simp
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp only [max_min_distrib_left,
multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter],
..multiset.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice }
end
/- relator -/
section rel
/-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/
inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop
| zero : rel 0 0
| cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs)
mk_iff_of_inductive_prop multiset.rel multiset.rel_iff
variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s :=
rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih)
lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
lemma rel_eq_refl {s : multiset α} : rel (=) s s :=
multiset.induction_on s rel.zero (assume a s, rel.cons rfl)
lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t :=
begin
split,
{ assume h, induction h; simp * },
{ assume h, subst h, exact rel_eq_refl }
end
lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) }
end
lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) :=
begin
induction hst,
case rel.zero { simpa using huv },
case rel.cons : a b s t hab hst ih { simpa using ih.cons hab }
end
lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t :=
show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm]
@[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 :=
by rw [rel_iff]; simp
@[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 :=
by rw [rel_iff]; simp
lemma rel_cons_left {a as bs} :
rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') :=
begin
split,
{ generalize hm : a :: as = m,
assume h,
induction h generalizing as,
case rel.zero { simp at hm, contradiction },
case rel.cons : a' b as' bs ha'b h ih {
rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ },
{ rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩,
exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ }
} },
{ exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h }
end
lemma rel_cons_right {as b bs} :
rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') :=
begin
rw [← rel_flip, rel_cons_left],
apply exists_congr, assume a,
apply exists_congr, assume as',
rw [rel_flip, flip]
end
lemma rel_add_left {as₀ as₁} :
∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) :=
multiset.induction_on as₀ (by simp)
begin
assume a s ih bs,
simp only [ih, cons_add, rel_cons_left],
split,
{ assume h,
rcases h with ⟨b, bs', hab, h, rfl⟩,
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩,
exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ },
{ assume h,
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩,
rcases h with ⟨b, bs, hab, h₀, rfl⟩,
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ }
end
lemma rel_add_right {as bs₀ bs₁} :
rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) :=
by rw [← rel_flip, rel_add_left]; simp [rel_flip]
lemma rel_map_left {s : multiset γ} {f : γ → α} :
∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t :=
multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt})
lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} :
rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t :=
by rw [← rel_flip, rel_map_left, ← rel_flip]; refl
lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) :
rel p (s.map f) (t.map g) :=
by rw [rel_map_left, rel_map_right]; exact hst.mono h
lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by apply rel_join; apply rel_map; assumption
lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
card s = card t :=
by induction h; simp [*]
lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b :=
begin
induction h with x y s t hxy hst ih,
{ simp },
{ assume a ha,
cases mem_cons.1 ha with ha ha,
{ exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ },
{ rcases ih ha with ⟨b, hbt, hab⟩,
exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } }
end
end rel
section map
theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} :
s.map f = t.map f ↔ s = t :=
by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff]
theorem injective_map {f : α → β} (hf : function.injective f) :
function.injective (multiset.map f) :=
assume x y, (map_eq_map hf).1
end map
section quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) :
s.map (quot.mk r) = t.map (quot.mk r) :=
rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) :
∃t:multiset α, s = t.map (quot.mk r) :=
multiset.induction_on s ⟨0, rfl⟩ $
assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot
{r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) :
(∀s:multiset α, p (s.map (quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end
end quot
/- disjoint -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp, priority 1100]
theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp, priority 1100]
theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
by rw [disjoint_comm, disjoint_add_left]; tauto
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ (a::0) s t).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t :=
by rw [disjoint_comm, disjoint_cons_left]; tauto
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
begin
simp [disjoint],
split,
from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm,
from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁)
end
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h)
(assume h, ⟨l, rfl, h⟩)
/- nodup -/
/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of
any element is at most 1. -/
def nodup (s : multiset α) : Prop :=
quot.lift_on s nodup (λ s t p, propext p.nodup_iff)
@[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl
@[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil
@[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s :=
quot.induction_on s $ λ l, nodup_cons
theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton
theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s :=
(nodup_cons.1 h).1
theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s :=
le_induction_on h $ λ l₁ l₂, nodup_of_sublist
theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair
theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s :=
quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a,
not_congr (@repeat_le_coe _ a 2 _).symm
theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 :=
quot.induction_on s $ λ l, nodup_iff_count_le_one
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α}
(d : nodup s) (h : a ∈ s) : count a s = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} :
(∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s :=
quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩
lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α}
(hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) :=
let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂
theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=
quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append
theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t :=
(nodup_add.1 d).2.2
theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t :=
by simp [nodup_add, d₁, d₂]
theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s :=
quot.induction_on s $ λ l, nodup_of_nodup_map f
theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) →
nodup s → nodup (map f s) :=
quot.induction_on s $ λ l, nodup_map_on
theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) :=
nodup_map_on (λ x _ y _ h, hf h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) :=
quot.induction_on s $ λ l, nodup_filter p
@[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s :=
quot.induction_on s $ λ l, nodup_attach
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) :=
quot.induction_on s (λ l H, nodup_pmap hf) H
instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) :=
quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s :=
quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp [and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
by rw mem_erase_iff_of_nodup h; simp
theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂]
theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} :
nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) :=
quot.induction_on s $ assume l₁,
begin
choose f hf using assume a, quotient.exists_rep (t a),
rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a),
simpa using nodup_sigma
end
theorem nodup_filter_map (f : α → option β) {s : multiset α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup s → nodup (filter_map f s) :=
quot.induction_on s $ λ l, nodup_filter_map H
theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _
theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) :=
nodup_of_le $ inter_le_left _ _
theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) :=
nodup_of_le $ inter_le_right _ _
@[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t :=
⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩,
λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact
max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩
@[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h),
quotient.induction_on s $ λ l h,
by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact
λ x sx y sy e,
(h.sublist_ext (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1
(quotient.exact e)⟩
theorem nodup_powerset_len {n : ℕ} {s : multiset α}
(h : nodup s) : nodup (powerset_len n s) :=
nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h)
@[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} :
nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) :=
have h₁ : ∀a, ∃l:list β, t a = l, from
assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩,
let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in
have t = λa, t' a, from funext h',
have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm,
quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd]
theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂
theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩
theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n :=
(le_iff_subset (nodup_range _)).trans range_subset
theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h',
by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le];
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩
lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β}
(hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β)
(hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂)
(i_surj : ∀b∈t, ∃a ha, b = i a ha) :
s.map f = t.map g :=
have t = s.attach.map (λ x, i x.1 x.2),
from (nodup_ext ht (nodup_map
(show function.injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy,
subtype.eq (i_inj x.1 y.1 x.2 y.2 hxy))
(nodup_attach.2 hs))).2
(λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach];
exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩),
calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map]
... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach]
... = t.map g : by rw [this, multiset.map_map]; exact map_congr (λ x _, h _ _)
section
variable [decidable_eq α]
/- erase_dup -/
/-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/
def erase_dup (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.erase_dup : multiset α))
(λ s t p, quot.sound p.erase_dup)
@[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl
@[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl
@[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_erase_dup
@[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s →
erase_dup (a::s) = erase_dup s :=
quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s →
erase_dup (a::s) = a :: erase_dup s :=
quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m
theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s :=
quot.induction_on s $ λ l, (erase_dup_sublist _).subperm
theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s :=
subset_of_le $ erase_dup_le _
theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s :=
λ a, mem_erase_dup.2
@[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t :=
⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩
@[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t :=
⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩
@[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) :=
quot.induction_on s nodup_erase_dup
theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s :=
⟨λ e, e ▸ nodup_erase_dup s,
quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩
theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 :=
⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _,
λ h, h.symm ▸ erase_dup_zero⟩
@[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 :=
erase_dup_eq_self.2 $ nodup_singleton _
theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s :=
⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩,
λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩
theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t :=
by simp [nodup_ext]
theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) :
erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext]
/- finset insert -/
/-- `ndinsert a s` is the lift of the list `insert` operation. This operation
does not respect multiplicities, unlike `cons`, but it is suitable as
an insert operation on `finset`. -/
def ndinsert (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.insert a : multiset α))
(λ s t p, quot.sound (p.insert a))
@[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl
@[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl
@[simp, priority 980]
theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h
@[simp, priority 980]
theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h
@[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, mem_insert_iff
@[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s :=
quot.induction_on s $ λ l, (sublist_of_suffix $ suffix_insert _ _).subperm
@[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s :=
mem_ndinsert.2 (or.inl rfl)
theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s :=
mem_ndinsert.2 (or.inr h)
@[simp, priority 980]
theorem length_ndinsert_of_mem {a : α} {s : multiset α} (h : a ∈ s) :
card (ndinsert a s) = card s :=
by simp [h]
@[simp, priority 980]
theorem length_ndinsert_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) :
card (ndinsert a s) = card s + 1 :=
by simp [h]
theorem erase_dup_cons {a : α} {s : multiset α} :
erase_dup (a::s) = ndinsert a (erase_dup s) :=
by by_cases a ∈ s; simp [h]
theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) :=
quot.induction_on s $ λ l, nodup_insert
theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t :=
⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩,
λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else
by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff,
← le_cons_of_not_mem h, cons_erase m]; exact l⟩
lemma attach_ndinsert (a : α) (s : multiset α) :
(s.ndinsert a).attach =
ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) :=
have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s,
(λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from
assume h, funext $ assume p, subtype.eq rfl,
have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩
(s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩),
begin
intros t ht,
by_cases a ∈ s,
{ rw [ndinsert_of_mem h] at ht,
subst ht,
rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] },
{ rw [ndinsert_of_not_mem h] at ht,
subst ht,
simp [attach_cons, h] }
end,
this _ rfl
@[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} :
disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t :=
iff.trans (by simp [disjoint]) disjoint_cons_left
@[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} :
disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t :=
by rw [disjoint_comm, disjoint_ndinsert_left]; tauto
/- finset union -/
/-- `ndunion s t` is the lift of the list `union` operation. This operation
does not respect multiplicities, unlike `s ∪ t`, but it is suitable as
a union operation on `finset`. (`s ∪ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndunion (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.union p₂
@[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl
@[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem cons_ndunion (s t : multiset α) (a : α) :
ndunion (a :: s) t = ndinsert a (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, rfl
@[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union
theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
(sublist_of_suffix $ suffix_union_right _ _).subperm
theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t :=
quotient.induction_on₂ s t $ λ l₁ l₂, (union_sublist_append _ _).subperm
theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u :=
multiset.induction_on s (by simp)
(by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt})
theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t :=
λ a h, mem_ndunion.2 $ or.inl h
theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t :=
(le_iff_subset d).2 $ subset_ndunion_left _ _
theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t :=
ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩
theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _
@[simp, priority 980]
theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t :=
le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _)
theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _
/- finset inter -/
/-- `ndinter s t` is the lift of the list `∩` operation. This operation
does not respect multiplicities, unlike `s ∩ t`, but it is suitable as
an intersection operation on `finset`. (`s ∩ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndinter (s t : multiset α) : multiset α := filter (∈ t) s
@[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl
@[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl
@[simp, priority 980]
theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) :
ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h]
@[simp, priority 980]
theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) :
ndinter (a::s) t = ndinter s t := by simp [ndinter, h]
@[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t :=
mem_filter
@[simp]
theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) :=
nodup_filter _
theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u :=
by simp [ndinter, le_filter, subset_iff]
theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s :=
(le_ndinter.1 (le_refl _)).1
theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t :=
(le_ndinter.1 (le_refl _)).2
theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t :=
(le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _)
theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t :=
le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩
@[simp, priority 980]
theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t :=
le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _)
theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
end
/- fold -/
section fold
variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op]
local notation a * b := op a b
include hc ha
/-- `fold op b s` folds a commutative associative operation `op` over
the multiset `s`. -/
def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc)
theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl
@[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl
theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b :=
(coe_foldr_swap op _ b l).trans $ by simp [hc.comm]
theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s :=
quot.induction_on s $ λ l, coe_fold_l _ _ _
@[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl
@[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α),
(a :: s).fold op b = a * s.fold op b := foldr_cons _ _
theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a :=
by simp [hc.comm]
theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) :=
by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl]
theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) :=
by rw [fold_cons'_right, hc.comm]
theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ :=
multiset.induction_on s₂
(by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op])
(by simp {contextual := tt}; cc)
theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp
theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) :
(s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ :=
multiset.induction_on s (by simp) (by simp {contextual := tt}; cc)
theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op']
{m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) :
(s.map m).fold op' (m b) = m (s.fold op b) :=
multiset.induction_on s (by simp) (by simp [hm] {contextual := tt})
theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) :
(s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ :=
by rw [← fold_add op, union_add_inter, fold_add op]
@[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) :
(erase_dup s).fold op b = s.fold op b :=
multiset.induction_on s (by simp) $ λ a s IH, begin
by_cases a ∈ s; simp [IH, h],
show fold op b s = op a (fold op b s),
rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent],
end
end fold
theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) :
∃ n : ℕ, s ≤ n • erase_dup s :=
⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin
rw count_smul, by_cases a ∈ s,
{ refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h),
have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a));
[simp [le_max_left], simpa [cons_erase h]] },
{ simp [count_eq_zero.2 h, nat.zero_le] }
end⟩
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : multiset α) : α := s.fold (⊔) ⊥
@[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ :=
fold_zero _ _
@[simp] lemma sup_cons (a : α) (s : multiset α) :
(a :: s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp
@[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 (le_refl _) _ h
lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 $ assume b hb, le_sup (h hb)
variables [decidable_eq α]
@[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup :=
fold_erase_dup_idem _ _ _
@[simp] lemma sup_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).sup = a ⊔ s.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp
end sup
section inf
variables [semilattice_inf_top α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : multiset α) : α := s.fold (⊓) ⊤
@[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ :=
fold_zero _ _
@[simp] lemma inf_cons (a : α) (s : multiset α) :
(a :: s).inf = a ⊓ s.inf :=
fold_cons_left _ _ _ _
@[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp
@[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 (le_refl _) _ h
lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 $ assume b hb, inf_le (h hb)
variables [decidable_eq α]
@[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf :=
fold_erase_dup_idem _ _ _
@[simp] lemma inf_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).inf = a ⊓ s.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp
end inf
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the multiset `s`.
(Uses merge sort algorithm.) -/
def sort (s : multiset α) : list α :=
quot.lift_on s (merge_sort r) $ λ a b h,
eq_of_sorted_of_perm
((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm)
(sorted_merge_sort r _)
(sorted_merge_sort r _)
@[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl
@[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) :=
quot.induction_on s $ λ l, sorted_merge_sort r _
@[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s :=
quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _
@[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
by rw [← mem_coe, sort_eq]
@[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card :=
quot.induction_on s $ length_merge_sort _
end sort
instance [has_repr α] : has_repr (multiset α) :=
⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩
section sections
def sections (s : multiset (multiset α)) : multiset (multiset α) :=
multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a))
(assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap])
@[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 :=
rfl
@[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) :
sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) :=
rec_on_cons m s
lemma coe_sections : ∀(l : list (list α)),
sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) =
((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α))
| [] := rfl
| (a :: l) :=
begin
simp,
rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l],
simp [list.sections, (∘), list.bind]
end
@[simp] lemma sections_add (s t : multiset (multiset α)) :
sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm])
lemma mem_sections {s : multiset (multiset α)} :
∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a :=
multiset.induction_on s (by simp)
(assume a s ih a',
by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm])
lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} :
prod (s.map sum) = sum ((sections s).map prod) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right])
end sections
section pi
variables [decidable_eq α] {δ : α → Type*}
open function
def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' :=
λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h
def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) .
lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) :
pi.cons m a b f a h = b :=
dif_pos rfl
lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) :
pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) :=
dif_neg h
lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') :
pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) :=
begin
apply hfunext, { refl }, intros a'' _ h, subst h,
apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h,
by_cases h₁ : a'' = a; by_cases h₂ : a'' = a';
simp [*, pi.cons_same, pi.cons_ne] at *,
{ subst h₁, rw [pi.cons_same, pi.cons_same] },
{ subst h₂, rw [pi.cons_same, pi.cons_same] }
end
/-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/
def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) :=
m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b)
begin
intros a a' m n,
by_cases eq : a = a',
{ subst eq },
{ simp [map_bind, bind_bind (t a') (t a)],
apply bind_hcongr, { rw [cons_swap a a'] },
intros b hb,
apply bind_hcongr, { rw [cons_swap a a'] },
intros b' hb',
apply map_hcongr, { rw [cons_swap a a'] },
intros f hf,
exact pi.cons_swap eq }
end
@[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl
@[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) :
pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) :=
rec_on_cons a m
lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume f₁ f₂ eq, funext $ assume a', funext $ assume h',
have ne : a ≠ a', from assume h, hs $ h.symm ▸ h',
have a' ∈ a :: s, from mem_cons_of_mem h',
calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm]
... = pi.cons s a b f₂ a' this : by rw [eq]
... = f₂ a' h' : by rw [pi.cons_ne this ne.symm]
lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) :
card (pi m t) = prod (m.map $ λa, card (t a)) :=
multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt})
lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} :
nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) :=
multiset.induction_on s (assume _ _, nodup_singleton _)
begin
assume a s ih hs ht,
have has : a ∉ s, by simp at hs; exact hs.1,
have hs : nodup s, by simp at hs; exact hs.2,
simp,
split,
{ assume b hb,
from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') },
{ apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _),
from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq,
have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _),
by rw [eq],
neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) }
end
lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) :
∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) :=
begin
refine multiset.induction_on m (λ f, _) (λ a m ih f, _),
{ simpa using show f = pi.empty δ, by funext a ha; exact ha.elim },
simp, split,
{ rintro ⟨b, hb, f', hf', rfl⟩ a' ha',
rw [ih] at hf',
by_cases a' = a,
{ subst h, rwa [pi.cons_same] },
{ rw [pi.cons_ne _ h], apply hf' } },
{ intro hf,
refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha),
(ih _).2 (λ a' h', hf _ _), _⟩,
funext a' h',
by_cases a' = a,
{ subst h, rw [pi.cons_same] },
{ rw [pi.cons_ne _ h] } }
end
end pi
end multiset
namespace multiset
instance : functor multiset :=
{ map := @map }
instance : is_lawful_functor multiset :=
by refine { .. }; intros; simp
open is_lawful_traversable is_comm_applicative
variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F]
variables {α' β' : Type u_1} (f : α' → F β')
def traverse : multiset α' → F (multiset β') :=
quotient.lift (functor.map coe ∘ traversable.traverse f)
begin
introv p, unfold function.comp,
induction p,
case perm.nil { refl },
case perm.cons {
have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) =
multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂),
{ rw [p_ih] },
simpa with functor_norm },
case perm.swap {
have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x =
(λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y,
{ rw [is_comm_applicative.commutative_map],
congr, funext a b l, simpa [flip] using perm.swap b a l },
simp [(∘), this] with functor_norm },
case perm.trans { simp [*] }
end
instance : monad multiset :=
{ pure := λ α x, x::0,
bind := @bind,
.. multiset.functor }
instance : is_lawful_monad multiset :=
{ bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih,
by rw [bind_cons, map_cons, bind_zero, add_zero],
pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero],
bind_assoc := @bind_assoc }
open functor
open traversable is_lawful_traversable
@[simp]
lemma lift_beta {α β : Type*} (x : list α) (f : list α → β)
(h : ∀ a b : list α, a ≈ b → f a = f b) :
quotient.lift f h (x : multiset α) = f x :=
quotient.lift_beta _ _ _
@[simp]
lemma map_comp_coe {α β} (h : α → β) :
functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) :=
by funext; simp [functor.map]
lemma id_traverse {α : Type*} (x : multiset α) :
traverse id.mk x = x :=
quotient.induction_on x
(by { intro, rw [traverse,quotient.lift_beta,function.comp],
simp, congr })
lemma comp_traverse {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
{α β γ : Type*}
(g : α → G β) (h : β → H γ) (x : multiset α) :
traverse (comp.mk ∘ functor.map h ∘ g) x =
comp.mk (functor.map (traverse h) (traverse g x)) :=
quotient.induction_on x
(by intro;
simp [traverse,comp_traverse] with functor_norm;
simp [(<$>),(∘)] with functor_norm)
lemma map_traverse {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → G β) (h : β → γ)
(x : multiset α) :
functor.map (functor.map h) (traverse g x) =
traverse (functor.map h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse] with functor_norm;
rw [comp_map,map_traverse])
lemma traverse_map {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → β) (h : β → G γ)
(x : multiset α) :
traverse h (map g x) =
traverse (h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse];
rw [← traversable.traverse_map h g];
[ refl, apply_instance ])
lemma naturality {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
(eta : applicative_transformation G H)
{α β : Type*} (f : α → G β) (x : multiset α) :
eta (traverse f x) = traverse (@eta _ ∘ f) x :=
quotient.induction_on x
(by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm)
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } :=
quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin
intros,
funext hp,
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y,
{ apply all_equal },
{ rintros ⟨x, px⟩ ⟨y, py⟩,
rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩,
congr,
calc x = z : z_unique x px
... = y : (z_unique y py).symm }
end
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
/- Ico -/
/-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/
def Ico (n m : ℕ) : multiset ℕ := Ico n m
namespace Ico
theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) :=
congr_arg coe $ list.Ico.map_add _ _ _
theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) :=
congr_arg coe $ list.Ico.map_sub _ _ _ h
theorem zero_bot (n : ℕ) : Ico 0 n = range n :=
congr_arg coe $ list.Ico.zero_bot _
@[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n :=
list.Ico.length _ _
theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _
@[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m :=
list.Ico.mem
theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 :=
congr_arg coe $ list.Ico.eq_nil_of_le h
@[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 :=
eq_zero_of_le $ le_refl n
@[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n :=
iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff
lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) :
Ico n m + Ico m l = Ico n l :=
congr_arg coe $ list.Ico.append_consecutive hnm hml
@[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 :=
congr_arg coe $ list.Ico.bag_inter_consecutive n m l
@[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} :=
congr_arg coe $ list.Ico.succ_singleton
theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m :=
by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl
theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m :=
congr_arg coe $ list.Ico.eq_cons h
@[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} :=
congr_arg coe $ list.Ico.pred_singleton h
@[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m :=
list.Ico.not_mem_top
lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m :=
congr_arg coe $ list.Ico.filter_lt_of_top_le hml
lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ :=
congr_arg coe $ list.Ico.filter_lt_of_le_bot hln
lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l :=
congr_arg coe $ list.Ico.filter_lt_of_ge hlm
@[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) :=
congr_arg coe $ list.Ico.filter_lt n m l
lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m :=
congr_arg coe $ list.Ico.filter_le_of_le_bot hln
lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ :=
congr_arg coe $ list.Ico.filter_le_of_top_le hml
lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m :=
congr_arg coe $ list.Ico.filter_le_of_le hnl
@[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m :=
congr_arg coe $ list.Ico.filter_le n m l
end Ico
variable (α)
def subsingleton_equiv [subsingleton α] : list α ≃ multiset α :=
{ to_fun := coe,
inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b),
list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _,
left_inv := λ l, rfl,
right_inv := λ m, quot.induction_on m $ λ l, rfl }
namespace nat
/-- The antidiagonal of a natural number `n` is
the multiset of pairs `(i,j)` such that `i+j = n`. -/
def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) :=
list.nat.antidiagonal n
/-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal]
/-- The cardinality of the antidiagonal of `n` is `n+1`. -/
@[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 :=
by rw [antidiagonal, coe_card, list.nat.length_antidiagonal]
/-- The antidiagonal of `0` is the list `[(0,0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} :=
by { rw [antidiagonal, list.nat.antidiagonal_zero], refl }
/-- The antidiagonal of `n` does not contain duplicate entries. -/
@[simp] lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) :=
coe_nodup.2 $ list.nat.nodup_antidiagonal n
end nat
end multiset
@[to_additive]
theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) :
f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
|
febf669fd10618e1da9bd42844a8aa3e6776a080 | ca1ad81c8733787aba30f7a8d63f418508e12812 | /clfrags/src/hilbert/wr/and.lean | 826de92ed7c38964d7c4b3516398ad6883eb6957 | [] | no_license | greati/hilbert-classical-fragments | 5cdbe07851e979c8a03c621a5efd4d24bbfa333a | 18a21ac6b2e890060eb4ae65752fc0245394d226 | refs/heads/master | 1,591,973,117,184 | 1,573,822,710,000 | 1,573,822,710,000 | 194,334,439 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 361 | lean | import core.connectives
namespace clfrags
namespace hilbert
namespace wr
namespace and
axiom c₁ : Π {a b : Prop}, a → b → and a b
axiom c₂ : Π {a b : Prop}, and a b → a
axiom c₃ : Π {a b : Prop}, and a b → b
end and
end wr
end hilbert
end clfrags
|
00ab7c56f4153997f09e295ada6435bcefb30181 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/topology/algebra/group.lean | 01e673345d50f2957bdd79738ed8a4e4e3bfa015 | [
"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 | 17,329 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
Theory of topological groups.
-/
import algebra.pointwise order.filter.pointwise
import group_theory.quotient_group
import topology.algebra.monoid topology.homeomorph
open classical set filter topological_space
open_locale classical topological_space
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
section topological_group
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological (additive) group is a group in which the addition and negation operations are
continuous. -/
class topological_add_group (α : Type u) [topological_space α] [add_group α]
extends topological_add_monoid α : Prop :=
(continuous_neg : continuous (λa:α, -a))
/-- A topological group is a group in which the multiplication and inversion operations are
continuous. -/
@[to_additive topological_add_group]
class topological_group (α : Type*) [topological_space α] [group α]
extends topological_monoid α : Prop :=
(continuous_inv : continuous (λa:α, a⁻¹))
end prio
variables [topological_space α] [group α]
@[to_additive]
lemma continuous_inv [topological_group α] : continuous (λx:α, x⁻¹) :=
topological_group.continuous_inv α
@[to_additive]
lemma continuous.inv [topological_group α] [topological_space β] {f : β → α}
(hf : continuous f) : continuous (λx, (f x)⁻¹) :=
continuous_inv.comp hf
@[to_additive]
lemma continuous_on.inv [topological_group α] [topological_space β] {f : β → α} {s : set β}
(hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s :=
continuous_inv.comp_continuous_on hf
/-- If a function converges to a value in a multiplicative topological group, then its inverse
converges to the inverse of this value. For the version in normed fields assuming additionally
that the limit is nonzero, use `tendsto.inv'`. -/
@[to_additive]
lemma filter.tendsto.inv [topological_group α] {f : β → α} {x : filter β} {a : α}
(hf : tendsto f x (𝓝 a)) : tendsto (λx, (f x)⁻¹) x (𝓝 a⁻¹) :=
tendsto.comp (continuous_iff_continuous_at.mp (topological_group.continuous_inv α) a) hf
@[to_additive]
lemma continuous_at.inv [topological_group α] [topological_space β] {f : β → α} {x : β}
(hf : continuous_at f x) : continuous_at (λx, (f x)⁻¹) x :=
hf.inv
@[to_additive]
lemma continuous_within_at.inv [topological_group α] [topological_space β] {f : β → α}
{s : set β} {x : β} (hf : continuous_within_at f s x) :
continuous_within_at (λx, (f x)⁻¹) s x :=
hf.inv
@[to_additive topological_add_group]
instance [topological_group α] [topological_space β] [group β] [topological_group β] :
topological_group (α × β) :=
{ continuous_inv := continuous_fst.inv.prod_mk continuous_snd.inv }
attribute [instance] prod.topological_add_group
@[to_additive]
protected def homeomorph.mul_left [topological_group α] (a : α) : α ≃ₜ α :=
{ continuous_to_fun := continuous_const.mul continuous_id,
continuous_inv_fun := continuous_const.mul continuous_id,
.. equiv.mul_left a }
@[to_additive]
lemma is_open_map_mul_left [topological_group α] (a : α) : is_open_map (λ x, a * x) :=
(homeomorph.mul_left a).is_open_map
@[to_additive]
lemma is_closed_map_mul_left [topological_group α] (a : α) : is_closed_map (λ x, a * x) :=
(homeomorph.mul_left a).is_closed_map
@[to_additive]
protected def homeomorph.mul_right
{α : Type*} [topological_space α] [group α] [topological_group α] (a : α) :
α ≃ₜ α :=
{ continuous_to_fun := continuous_id.mul continuous_const,
continuous_inv_fun := continuous_id.mul continuous_const,
.. equiv.mul_right a }
@[to_additive]
lemma is_open_map_mul_right [topological_group α] (a : α) : is_open_map (λ x, x * a) :=
(homeomorph.mul_right a).is_open_map
@[to_additive]
lemma is_closed_map_mul_right [topological_group α] (a : α) : is_closed_map (λ x, x * a) :=
(homeomorph.mul_right a).is_closed_map
@[to_additive]
protected def homeomorph.inv (α : Type*) [topological_space α] [group α] [topological_group α] :
α ≃ₜ α :=
{ continuous_to_fun := continuous_inv,
continuous_inv_fun := continuous_inv,
.. equiv.inv α }
@[to_additive exists_nhds_half]
lemma exists_nhds_split [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) :
∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w ∈ s :=
begin
have : ((λa:α×α, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : α × α) :=
tendsto_mul (by simpa using hs),
rw nhds_prod_eq at this,
rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩,
exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩
end
@[to_additive exists_nhds_half_neg]
lemma exists_nhds_split_inv [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) :
∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w⁻¹ ∈ s :=
begin
have : tendsto (λa:α×α, a.1 * (a.2)⁻¹) ((𝓝 (1:α)).prod (𝓝 (1:α))) (𝓝 1),
{ simpa using (@tendsto_fst α α (𝓝 1) (𝓝 1)).mul tendsto_snd.inv },
have : ((λa:α×α, a.1 * (a.2)⁻¹) ⁻¹' s) ∈ (𝓝 (1:α)).prod (𝓝 (1:α)) :=
this (by simpa using hs),
rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩,
exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩
end
@[to_additive exists_nhds_quarter]
lemma exists_nhds_split4 [topological_group α] {u : set α} (hu : u ∈ 𝓝 (1 : α)) :
∃ V ∈ 𝓝 (1 : α), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u :=
begin
rcases exists_nhds_split hu with ⟨W, W_nhd, h⟩,
rcases exists_nhds_split W_nhd with ⟨V, V_nhd, h'⟩,
existsi [V, V_nhd],
intros v w s t v_in w_in s_in t_in,
simpa [mul_assoc] using h _ _ (h' v w v_in w_in) (h' s t s_in t_in)
end
section
variable (α)
@[to_additive]
lemma nhds_one_symm [topological_group α] : comap (λr:α, r⁻¹) (𝓝 (1 : α)) = 𝓝 (1 : α) :=
begin
have lim : tendsto (λr:α, r⁻¹) (𝓝 1) (𝓝 1),
{ simpa using (@tendsto_id α (𝓝 1)).inv },
refine comap_eq_of_inverse _ _ lim lim,
{ funext x, simp },
end
end
@[to_additive]
lemma nhds_translation_mul_inv [topological_group α] (x : α) :
comap (λy:α, y * x⁻¹) (𝓝 1) = 𝓝 x :=
begin
refine comap_eq_of_inverse (λy:α, y * x) _ _ _,
{ funext x; simp },
{ suffices : tendsto (λy:α, y * x⁻¹) (𝓝 x) (𝓝 (x * x⁻¹)), { simpa },
exact tendsto_id.mul tendsto_const_nhds },
{ suffices : tendsto (λy:α, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa },
exact tendsto_id.mul tendsto_const_nhds }
end
@[to_additive]
lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G}
(tg : @topological_group G t _) (tg' : @topological_group G t' _)
(h : @nhds G t 1 = @nhds G t' 1) : t = t' :=
eq_of_nhds_eq_nhds $ λ x, by
rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h]
end topological_group
section quotient_topological_group
variables [topological_space α] [group α] [topological_group α] (N : set α) [normal_subgroup N]
@[to_additive]
instance {α : Type u} [group α] [topological_space α] (N : set α) [normal_subgroup N] :
topological_space (quotient_group.quotient N) :=
by dunfold quotient_group.quotient; apply_instance
open quotient_group
@[to_additive quotient_add_group_saturate]
lemma quotient_group_saturate {α : Type u} [group α] (N : set α) [normal_subgroup N] (s : set α) :
(coe : α → quotient N) ⁻¹' ((coe : α → quotient N) '' s) = (⋃ x : N, (λ y, y*x.1) '' s) :=
begin
ext x,
simp only [mem_preimage, mem_image, mem_Union, quotient_group.eq],
split,
{ exact assume ⟨a, a_in, h⟩, ⟨⟨_, h⟩, a, a_in, mul_inv_cancel_left _ _⟩ },
{ exact assume ⟨⟨i, hi⟩, a, ha, eq⟩,
⟨a, ha, by simp only [eq.symm, (mul_assoc _ _ _).symm, inv_mul_cancel_left, hi]⟩ }
end
@[to_additive]
lemma quotient_group.open_coe : is_open_map (coe : α → quotient N) :=
begin
intros s s_op,
change is_open ((coe : α → quotient N) ⁻¹' (coe '' s)),
rw quotient_group_saturate N s,
apply is_open_Union,
rintro ⟨n, _⟩,
exact is_open_map_mul_right n s s_op
end
@[to_additive topological_add_group_quotient]
instance topological_group_quotient : topological_group (quotient N) :=
{ continuous_mul := begin
have cont : continuous ((coe : α → quotient N) ∘ (λ (p : α × α), p.fst * p.snd)) :=
continuous_quot_mk.comp continuous_mul,
have quot : quotient_map (λ p : α × α, ((p.1:quotient N), (p.2:quotient N))),
{ apply is_open_map.to_quotient_map,
{ exact is_open_map.prod (quotient_group.open_coe N) (quotient_group.open_coe N) },
{ exact (continuous_quot_mk.comp continuous_fst).prod_mk
(continuous_quot_mk.comp continuous_snd) },
{ rintro ⟨⟨x⟩, ⟨y⟩⟩,
exact ⟨(x, y), rfl⟩ } },
exact (quotient_map.continuous_iff quot).2 cont,
end,
continuous_inv := begin
apply continuous_quotient_lift,
change continuous ((coe : α → quotient N) ∘ (λ (a : α), a⁻¹)),
exact continuous_quot_mk.comp continuous_inv
end }
attribute [instance] topological_add_group_quotient
end quotient_topological_group
section topological_add_group
variables [topological_space α] [add_group α]
lemma continuous.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λx, f x - g x) :=
by simp [sub_eq_add_neg]; exact hf.add hg.neg
lemma continuous_sub [topological_add_group α] : continuous (λp:α×α, p.1 - p.2) :=
continuous_fst.sub continuous_snd
lemma continuous_on.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} {s : set β}
(hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s :=
continuous_sub.comp_continuous_on (hf.prod hg)
lemma filter.tendsto.sub [topological_add_group α] {f : β → α} {g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x - g x) x (𝓝 (a - b)) :=
by simp [sub_eq_add_neg]; exact hf.add hg.neg
lemma nhds_translation [topological_add_group α] (x : α) : comap (λy:α, y - x) (𝓝 0) = 𝓝 x :=
nhds_translation_add_neg x
end topological_add_group
section prio
set_option default_priority 100 -- see Note [default priority]
/-- additive group with a neighbourhood around 0.
Only used to construct a topology and uniform space.
This is currently only available for commutative groups, but it can be extended to
non-commutative groups too.
-/
class add_group_with_zero_nhd (α : Type u) extends add_comm_group α :=
(Z : filter α)
(zero_Z {} : pure 0 ≤ Z)
(sub_Z {} : tendsto (λp:α×α, p.1 - p.2) (Z.prod Z) Z)
end prio
namespace add_group_with_zero_nhd
variables (α) [add_group_with_zero_nhd α]
local notation `Z` := add_group_with_zero_nhd.Z
@[priority 100] -- see Note [lower instance priority]
instance : topological_space α :=
topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α)
variables {α}
lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) :=
have tendsto (λa, (0:α)) (Z α) (Z α),
by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt},
have tendsto (λa:α, 0 - a) (Z α) (Z α), from
sub_Z.comp (tendsto.prod_mk this tendsto_id),
by simpa
lemma add_Z : tendsto (λp:α×α, p.1 + p.2) ((Z α).prod (Z α)) (Z α) :=
suffices tendsto (λp:α×α, p.1 - -p.2) ((Z α).prod (Z α)) (Z α),
by simpa [sub_eq_add_neg],
sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd))
lemma exists_Z_half {s : set α} (hs : s ∈ Z α) : ∃ V ∈ Z α, ∀ v w ∈ V, v + w ∈ s :=
begin
have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ (Z α).prod (Z α) := add_Z (by simpa using hs),
rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩,
exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩
end
lemma nhds_eq (a : α) : 𝓝 a = map (λx, x + a) (Z α) :=
topological_space.nhds_mk_of_nhds _ _
(assume a, calc pure a = map (λx, x + a) (pure 0) : by simp
... ≤ _ : map_mono zero_Z)
(assume b s hs,
let ⟨t, ht, eqt⟩ := exists_Z_half hs in
have t0 : (0:α) ∈ t, by simpa using zero_Z ht,
begin
refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩,
{ refine set.image_subset_iff.2 (assume b hbt, _),
simpa using eqt 0 b t0 hbt },
{ rintros _ ⟨c, hb, rfl⟩,
refine (Z α).sets_of_superset ht (assume x hxt, _),
simpa using eqt _ _ hxt hb }
end)
lemma nhds_zero_eq_Z : 𝓝 0 = Z α := by simp [nhds_eq]; exact filter.map_id
@[priority 100] -- see Note [lower instance priority]
instance : topological_add_monoid α :=
⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩,
begin
rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq,
tendsto_map'_iff],
suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (filter.prod (Z α) (Z α))
(map (λx:α, (a + b) + x) (Z α)),
{ simpa [(∘), add_comm, add_left_comm] },
exact tendsto_map.comp add_Z
end⟩
@[priority 100] -- see Note [lower instance priority]
instance : topological_add_group α :=
⟨continuous_iff_continuous_at.2 $ assume a,
begin
rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff],
suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)),
{ simpa [(∘), add_comm, sub_eq_add_neg] using this },
exact tendsto_map.comp neg_Z
end⟩
end add_group_with_zero_nhd
section filter_mul
local attribute [instance]
set.pointwise_one set.pointwise_mul set.pointwise_add filter.pointwise_mul filter.pointwise_add
filter.pointwise_one
section
variables [topological_space α] [group α] [topological_group α]
@[to_additive]
lemma is_open_pointwise_mul_left {s t : set α} : is_open t → is_open (s * t) := λ ht,
begin
have : ∀a, is_open ((λ (x : α), a * x) '' t),
assume a, apply is_open_map_mul_left, exact ht,
rw pointwise_mul_eq_Union_mul_left,
exact is_open_Union (λa, is_open_Union $ λha, this _),
end
@[to_additive]
lemma is_open_pointwise_mul_right {s t : set α} : is_open s → is_open (s * t) := λ hs,
begin
have : ∀a, is_open ((λ (x : α), x * a) '' s),
assume a, apply is_open_map_mul_right, exact hs,
rw pointwise_mul_eq_Union_mul_right,
exact is_open_Union (λa, is_open_Union $ λha, this _),
end
variables (α)
lemma topological_group.t1_space (h : @is_closed α _ {1}) : t1_space α :=
⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩
lemma topological_group.regular_space [t1_space α] : regular_space α :=
⟨assume s a hs ha,
let f := λ p : α × α, p.1 * (p.2)⁻¹ in
have hf : continuous f :=
continuous_mul.comp (continuous_fst.prod_mk (continuous_inv.comp continuous_snd)),
-- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s);
-- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s)
let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ :=
is_open_prod_iff.1 (hf _ (is_open_compl_iff.2 hs)) a (1:α) (by simpa [f]) in
begin
use s * t₂,
use is_open_pointwise_mul_left ht₂,
use λ x hx, ⟨x, hx, 1, one_mem_t₂, (mul_one _).symm⟩,
apply inf_principal_eq_bot,
rw mem_nhds_sets_iff,
refine ⟨t₁, _, ht₁, a_mem_t₁⟩,
rintros x hx ⟨y, hy, z, hz, yz⟩,
have : x * z⁻¹ ∈ -s := (prod_subset_iff.1 t_subset) x hx z hz,
have : x * z⁻¹ ∈ s, rw yz, simpa,
contradiction
end⟩
local attribute [instance] topological_group.regular_space
lemma topological_group.t2_space [t1_space α] : t2_space α := regular_space.t2_space α
end
section
variables [topological_space α] [comm_group α] [topological_group α]
@[to_additive]
lemma nhds_pointwise_mul (x y : α) : 𝓝 (x * y) = 𝓝 x * 𝓝 y :=
filter_eq $ set.ext $ assume s,
begin
rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)],
split,
{ rintros ⟨t, ht, ts⟩,
rcases exists_nhds_split ht with ⟨V, V_mem, h⟩,
refine ⟨(λa, a * x⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩,
(λa, a * y⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, _⟩,
rintros a ⟨v, v_mem, w, w_mem, rfl⟩,
apply ts,
simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) (w * y⁻¹) v_mem w_mem },
{ rintros ⟨a, ⟨b, hb, ba⟩, c, ⟨d, hd, dc⟩, ac⟩,
refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩,
simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *,
rintros ⟨vb, vd⟩,
refine ac ⟨v * y⁻¹, _, y, _, _⟩,
{ rw ← mul_assoc _ _ _ at vb, exact ba _ vb },
{ apply dc y, rw mul_right_inv, exact mem_of_nhds hd },
{ simp only [inv_mul_cancel_right] } }
end
@[to_additive]
lemma nhds_is_mul_hom : is_mul_hom (λx:α, 𝓝 x) := ⟨λ_ _, nhds_pointwise_mul _ _⟩
end
end filter_mul
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.