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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bdee55f5bd5bd9d9197b0a91e3113b14f98138c6 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/group_theory/submonoid/basic.lean | 99493198c8db4cc7ea3b7ed46f14b63500df779e | [
"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 | 20,839 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard,
Amelia Livingston, Yury Kudryashov
-/
import group_theory.subsemigroup.basic
/-!
# Submonoids: definition and `complete_lattice` structure
This file defines bundled multiplicative and additive submonoids. We also define
a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid
that includes this set, and prove a few results about extending properties from a dense set (i.e.
a set with `closure s = ⊤`) to the whole monoid, see `submonoid.dense_induction` and
`monoid_hom.of_mdense`.
## Main definitions
* `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in
the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`.
* `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`.
For each of the following definitions in the `submonoid` namespace, there is a corresponding
definition in the `add_submonoid` namespace.
* `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly
not definitionally equal to the carrier of the original `submonoid`.
* `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set.
* `submonoid.gi` : `closure : set M → submonoid M` and coercion `coe : submonoid M → set M`
form a `galois_insertion`;
* `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`;
* `monoid_hom.of_mdense`: if a map `f : M → N` between two monoids satisfies `f 1 = 1` and
`f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism.
E.g., if `f : ℕ → M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive
monoid homomorphism.
## Implementation notes
Submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as
membership of a submonoid's underlying set.
Note that `submonoid M` does not actually require `monoid M`, instead requiring only the weaker
`mul_one_class M`.
This file is designed to have very few dependencies. In particular, it should not use natural
numbers. `submonoid` is implemented by extending `subsemigroup` requiring `one_mem'`.
## Tags
submonoid, submonoids
-/
variables {M : Type*} {N : Type*}
variables {A : Type*}
section non_assoc
variables [mul_one_class M] {s : set M}
variables [add_zero_class A] {t : set A}
/-- `one_mem_class S M` says `S` is a type of subsets `s ≤ M`, such that `1 ∈ s` for all `s`. -/
class one_mem_class (S : Type*) (M : out_param $ Type*) [has_one M] [set_like S M] :=
(one_mem : ∀ (s : S), (1 : M) ∈ s)
export one_mem_class (one_mem)
/-- `zero_mem_class S M` says `S` is a type of subsets `s ≤ M`, such that `0 ∈ s` for all `s`. -/
class zero_mem_class (S : Type*) (M : out_param $ Type*) [has_zero M] [set_like S M] :=
(zero_mem : ∀ (s : S), (0 : M) ∈ s)
export zero_mem_class (zero_mem)
attribute [to_additive] one_mem_class
section
set_option old_structure_cmd true
/-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/
@[ancestor subsemigroup]
structure submonoid (M : Type*) [mul_one_class M] extends subsemigroup M :=
(one_mem' : (1 : M) ∈ carrier)
end
/-- A submonoid of a monoid `M` can be considered as a subsemigroup of that monoid. -/
add_decl_doc submonoid.to_subsemigroup
/-- `submonoid_class S M` says `S` is a type of subsets `s ≤ M` that contain `1`
and are closed under `(*)` -/
class submonoid_class (S : Type*) (M : out_param $ Type*) [mul_one_class M] [set_like S M]
extends mul_mem_class S M :=
(one_mem : ∀ (s : S), (1 : M) ∈ s)
section
set_option old_structure_cmd true
/-- An additive submonoid of an additive monoid `M` is a subset containing 0 and
closed under addition. -/
@[ancestor add_subsemigroup]
structure add_submonoid (M : Type*) [add_zero_class M] extends add_subsemigroup M :=
(zero_mem' : (0 : M) ∈ carrier)
end
/-- An additive submonoid of an additive monoid `M` can be considered as an
additive subsemigroup of that additive monoid. -/
add_decl_doc add_submonoid.to_add_subsemigroup
/-- `add_submonoid_class S M` says `S` is a type of subsets `s ≤ M` that contain `0`
and are closed under `(+)` -/
class add_submonoid_class (S : Type*) (M : out_param $ Type*) [add_zero_class M] [set_like S M]
extends add_mem_class S M :=
(zero_mem : ∀ (s : S), (0 : M) ∈ s)
attribute [to_additive] submonoid submonoid_class
@[to_additive, priority 100] -- See note [lower instance priority]
instance submonoid_class.to_one_mem_class (S : Type*) (M : out_param $ Type*) [mul_one_class M]
[set_like S M] [h : submonoid_class S M] : one_mem_class S M :=
{ ..h }
@[to_additive]
lemma pow_mem {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] {S : A} {x : M}
(hx : x ∈ S) : ∀ (n : ℕ), x ^ n ∈ S
| 0 := by { rw pow_zero, exact one_mem_class.one_mem S }
| (n + 1) := by { rw pow_succ, exact mul_mem_class.mul_mem hx (pow_mem n) }
namespace submonoid
@[to_additive]
instance : set_like (submonoid M) M :=
{ coe := submonoid.carrier,
coe_injective' := λ p q h, by cases p; cases q; congr' }
@[to_additive]
instance : submonoid_class (submonoid M) M :=
{ one_mem := submonoid.one_mem',
mul_mem := submonoid.mul_mem' }
/-- See Note [custom simps projection] -/
@[to_additive " See Note [custom simps projection]"]
def simps.coe (S : submonoid M) : set M := S
initialize_simps_projections submonoid (carrier → coe)
initialize_simps_projections add_submonoid (carrier → coe)
@[simp, to_additive]
lemma mem_carrier {s : submonoid M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
@[simp, to_additive]
lemma mem_mk {s : set M} {x : M} (h_one) (h_mul) : x ∈ mk s h_one h_mul ↔ x ∈ s := iff.rfl
@[simp, to_additive]
lemma coe_set_mk {s : set M} (h_one) (h_mul) : (mk s h_one h_mul : set M) = s := rfl
@[simp, to_additive]
lemma mk_le_mk {s t : set M} (h_one) (h_mul) (h_one') (h_mul') :
mk s h_one h_mul ≤ mk t h_one' h_mul' ↔ s ⊆ t := iff.rfl
/-- Two submonoids are equal if they have the same elements. -/
@[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."]
theorem ext {S T : submonoid M}
(h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/
@[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."]
protected def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M :=
{ carrier := s,
one_mem' := hs.symm ▸ S.one_mem',
mul_mem' := hs.symm ▸ S.mul_mem' }
variable {S : submonoid M}
@[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) :
(S.copy s hs : set M) = s := rfl
@[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S :=
set_like.coe_injective hs
variable (S)
/-- A submonoid contains the monoid's 1. -/
@[to_additive "An `add_submonoid` contains the monoid's 0."]
protected theorem one_mem : (1 : M) ∈ S := one_mem S
/-- A submonoid is closed under multiplication. -/
@[to_additive "An `add_submonoid` is closed under addition."]
protected theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := mul_mem
/-- The submonoid `M` of the monoid `M`. -/
@[to_additive "The additive submonoid `M` of the `add_monoid M`."]
instance : has_top (submonoid M) :=
⟨{ carrier := set.univ,
one_mem' := set.mem_univ 1,
mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩
/-- The trivial submonoid `{1}` of an monoid `M`. -/
@[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."]
instance : has_bot (submonoid M) :=
⟨{ carrier := {1},
one_mem' := set.mem_singleton 1,
mul_mem' := λ a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩
@[to_additive]
instance : inhabited (submonoid M) := ⟨⊥⟩
@[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff
@[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x
@[simp, to_additive] lemma coe_top : ((⊤ : submonoid M) : set M) = set.univ := rfl
@[simp, to_additive] lemma coe_bot : ((⊥ : submonoid M) : set M) = {1} := rfl
/-- The inf of two submonoids is their intersection. -/
@[to_additive "The inf of two `add_submonoid`s is their intersection."]
instance : has_inf (submonoid M) :=
⟨λ S₁ S₂,
{ carrier := S₁ ∩ S₂,
one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩,
mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩,
⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩
@[simp, to_additive]
lemma coe_inf (p p' : submonoid M) : ((p ⊓ p' : submonoid M) : set M) = p ∩ p' := rfl
@[simp, to_additive]
lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[to_additive]
instance : has_Inf (submonoid M) :=
⟨λ s,
{ carrier := ⋂ t ∈ s, ↑t,
one_mem' := set.mem_bInter $ λ i h, i.one_mem,
mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h,
i.mul_mem (by apply set.mem_Inter₂.1 hx i h) (by apply set.mem_Inter₂.1 hy i h) }⟩
@[simp, norm_cast, to_additive]
lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = ⋂ s ∈ S, ↑s := rfl
@[to_additive]
lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂
@[to_additive]
lemma mem_infi {ι : Sort*} {S : ι → submonoid M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp, norm_cast, to_additive]
lemma coe_infi {ι : Sort*} {S : ι → submonoid M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i :=
by simp only [infi, coe_Inf, set.bInter_range]
/-- Submonoids of a monoid form a complete lattice. -/
@[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."]
instance : complete_lattice (submonoid M) :=
{ le := (≤),
lt := (<),
bot := (⊥),
bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem,
top := (⊤),
le_top := λ S x hx, mem_top x,
inf := (⊓),
Inf := has_Inf.Inf,
le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩,
inf_le_left := λ a b x, and.left,
inf_le_right := λ a b x, and.right,
.. complete_lattice_of_Inf (submonoid M) $ λ s,
is_glb.of_image (λ S T,
show (S : set M) ≤ T ↔ S ≤ T, from set_like.coe_subset_coe) is_glb_binfi }
@[simp, to_additive]
lemma subsingleton_iff : subsingleton (submonoid M) ↔ subsingleton M :=
⟨ λ h, by exactI ⟨λ x y,
have ∀ i : M, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : submonoid M) ⊥ ▸ mem_top i,
(this x).trans (this y).symm⟩,
λ h, by exactI ⟨λ x y, submonoid.ext $ λ i, subsingleton.elim 1 i ▸ by simp [submonoid.one_mem]⟩⟩
@[simp, to_additive]
lemma nontrivial_iff : nontrivial (submonoid M) ↔ nontrivial M :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans
not_nontrivial_iff_subsingleton.symm)
@[to_additive]
instance [subsingleton M] : unique (submonoid M) :=
⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mpr ‹_›) a _⟩
@[to_additive]
instance [nontrivial M] : nontrivial (submonoid M) := nontrivial_iff.mpr ‹_›
/-- The `submonoid` generated by a set. -/
@[to_additive "The `add_submonoid` generated by a set"]
def closure (s : set M) : submonoid M := Inf {S | s ⊆ S}
@[to_additive]
lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : submonoid M, s ⊆ S → x ∈ S :=
mem_Inf
/-- The submonoid generated by a set includes the set. -/
@[simp, to_additive "The `add_submonoid` generated by a set includes the set."]
lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
@[to_additive]
lemma not_mem_of_not_mem_closure {P : M} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h)
variable {S}
open set
/-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/
@[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"]
lemma closure_le : closure s ≤ S ↔ s ⊆ S :=
⟨subset.trans subset_closure, λ h, Inf_le h⟩
/-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
@[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`"]
lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ subset.trans h subset_closure
@[to_additive]
lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S :=
le_antisymm (closure_le.2 h₁) h₂
variable (S)
/-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and
is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/
@[elab_as_eliminator, to_additive "An induction principle for additive closure membership. If `p`
holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all
elements of the additive closure of `s`."]
lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, Hmul, H1⟩).2 Hs h
/-- A dependent version of `submonoid.closure_induction`. -/
@[elab_as_eliminator, to_additive "A dependent version of `add_submonoid.closure_induction`. "]
lemma closure_induction' (s : set M) {p : Π x, x ∈ closure s → Prop}
(Hs : ∀ x (h : x ∈ s), p x (subset_closure h))
(H1 : p 1 (one_mem _))
(Hmul : ∀ x hx y hy, p x hx → p y hy → p (x * y) (mul_mem hx hy))
{x} (hx : x ∈ closure s) :
p x hx :=
begin
refine exists.elim _ (λ (hx : x ∈ closure s) (hc : p x hx), hc),
exact closure_induction hx
(λ x hx, ⟨_, Hs x hx⟩) ⟨_, H1⟩ (λ x y ⟨hx', hx⟩ ⟨hy', hy⟩, ⟨_, Hmul _ _ _ _ hx hy⟩),
end
/-- An induction principle for closure membership for predicates with two arguments. -/
@[elab_as_eliminator, to_additive "An induction principle for additive closure membership for
predicates with two arguments."]
lemma closure_induction₂ {p : M → M → Prop} {x} {y : M} (hx : x ∈ closure s) (hy : y ∈ closure s)
(Hs : ∀ (x ∈ s) (y ∈ s), p x y)
(H1_left : ∀ x, p 1 x)
(H1_right : ∀ x, p x 1)
(Hmul_left : ∀ x y z, p x z → p y z → p (x * y) z)
(Hmul_right : ∀ x y z, p z x → p z y → p z (x * y)) : p x y :=
closure_induction hx
(λ x xs, closure_induction hy (Hs x xs) (H1_right x) (λ z y h₁ h₂, Hmul_right z _ _ h₁ h₂))
(H1_left y) (λ x z h₁ h₂, Hmul_left _ _ _ h₁ h₂)
/-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = ⊤`, then in order to prove that
some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 1`,
and verify that `p x` and `p y` imply `p (x * y)`. -/
@[elab_as_eliminator, to_additive "If `s` is a dense set in an additive monoid `M`,
`add_submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M`
it suffices to verify `p x` for `x ∈ s`, verify `p 0`, and verify that `p x` and `p y` imply
`p (x + y)`."]
lemma dense_induction {p : M → Prop} (x : M) {s : set M} (hs : closure s = ⊤)
(Hs : ∀ x ∈ s, p x) (H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
have ∀ x ∈ closure s, p x, from λ x hx, closure_induction hx Hs H1 Hmul,
by simpa [hs] using this x
variable (M)
/-- `closure` forms a Galois insertion with the coercion to set. -/
@[to_additive "`closure` forms a Galois insertion with the coercion to set."]
protected def gi : galois_insertion (@closure M _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {M}
/-- Closure of a submonoid `S` equals `S`. -/
@[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"]
lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S
@[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ :=
(submonoid.gi M).gc.l_bot
@[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ :=
@coe_top M _ ▸ closure_eq ⊤
@[to_additive]
lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t :=
(submonoid.gi M).gc.l_sup
@[to_additive]
lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(submonoid.gi M).gc.l_supr
@[simp, to_additive]
lemma closure_singleton_le_iff_mem (m : M) (p : submonoid M) :
closure {m} ≤ p ↔ m ∈ p :=
by rw [closure_le, singleton_subset_iff, set_like.mem_coe]
@[to_additive]
lemma mem_supr {ι : Sort*} (p : ι → submonoid M) {m : M} :
(m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) :=
begin
rw [← closure_singleton_le_iff_mem, le_supr_iff],
simp only [closure_singleton_le_iff_mem],
end
@[to_additive]
lemma supr_eq_closure {ι : Sort*} (p : ι → submonoid M) :
(⨆ i, p i) = submonoid.closure (⋃ i, (p i : set M)) :=
by simp_rw [submonoid.closure_Union, submonoid.closure_eq]
@[to_additive]
lemma disjoint_def {p₁ p₂ : submonoid M} :
disjoint p₁ p₂ ↔ ∀ {x : M}, x ∈ p₁ → x ∈ p₂ → x = 1 :=
show (∀ x, x ∈ p₁ ∧ x ∈ p₂ → x ∈ ({1} : set M)) ↔ _, by simp
@[to_additive]
lemma disjoint_def' {p₁ p₂ : submonoid M} :
disjoint p₁ p₂ ↔ ∀ {x y : M}, x ∈ p₁ → y ∈ p₂ → x = y → x = 1 :=
disjoint_def.trans ⟨λ h x y hx hy hxy, h hx $ hxy.symm ▸ hy,
λ h x hx hx', h hx hx' rfl⟩
end submonoid
namespace monoid_hom
variables [mul_one_class N]
open submonoid
/-- The submonoid of elements `x : M` such that `f x = g x` -/
@[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"]
def eq_mlocus (f g : M →* N) : submonoid M :=
{ carrier := {x | f x = g x},
one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one],
mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] }
/-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/
@[to_additive "If two monoid homomorphisms are equal on a set, then they are equal on its submonoid
closure."]
lemma eq_on_mclosure {f g : M →* N} {s : set M} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_mlocus g, from closure_le.2 h
@[to_additive]
lemma eq_of_eq_on_mtop {f g : M →* N} (h : set.eq_on f g (⊤ : submonoid M)) :
f = g :=
ext $ λ x, h trivial
@[to_additive]
lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →* N} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h
end monoid_hom
end non_assoc
section assoc
variables [monoid M] [monoid N] {s : set M}
section is_unit
/-- The submonoid consisting of the units of a monoid -/
@[to_additive "The additive submonoid consisting of the additive units of an additive monoid"]
def is_unit.submonoid (M : Type*) [monoid M] : submonoid M :=
{ carrier := set_of is_unit,
one_mem' := by simp only [is_unit_one, set.mem_set_of_eq],
mul_mem' := by { intros a b ha hb, rw set.mem_set_of_eq at *, exact is_unit.mul ha hb } }
@[to_additive]
lemma is_unit.mem_submonoid_iff {M : Type*} [monoid M] (a : M) :
a ∈ is_unit.submonoid M ↔ is_unit a :=
begin
change a ∈ set_of is_unit ↔ is_unit a,
rw set.mem_set_of_eq
end
end is_unit
namespace monoid_hom
open submonoid
/-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid.
Then `monoid_hom.of_mdense` defines a monoid homomorphism from `M` asking for a proof
of `f (x * y) = f x * f y` only for `y ∈ s`. -/
@[to_additive]
def of_mdense {M N} [monoid M] [monoid N] {s : set M} (f : M → N) (hs : closure s = ⊤)
(h1 : f 1 = 1) (hmul : ∀ x (y ∈ s), f (x * y) = f x * f y) :
M →* N :=
{ to_fun := f,
map_one' := h1,
map_mul' := λ x y, dense_induction y hs (λ y hy x, hmul x y hy) (by simp [h1])
(λ y₁ y₂ h₁ h₂ x, by simp only [← mul_assoc, h₁, h₂]) x }
/-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid.
Then `add_monoid_hom.of_mdense` defines an additive monoid homomorphism from `M` asking for a proof
of `f (x + y) = f x + f y` only for `y ∈ s`. -/
add_decl_doc add_monoid_hom.of_mdense
@[simp, norm_cast, to_additive] lemma coe_of_mdense (f : M → N) (hs : closure s = ⊤) (h1 hmul) :
⇑(of_mdense f hs h1 hmul) = f := rfl
end monoid_hom
end assoc
|
bc0bb11e85b2231b25f6b2ee271e88bac489a4ba | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/group_theory/coset.lean | f86831c6852ca6e6abe0211aaaaeb4da2f167c34 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 9,164 | lean | /-
Copyright (c) 2018 Mitchell Rowett. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mitchell Rowett, Scott Morrison
-/
import group_theory.subgroup data.equiv.basic data.quot
open set function
variable {α : Type*}
@[to_additive left_add_coset]
def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s
@[to_additive right_add_coset]
def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s
localized "infix ` *l `:70 := left_coset" in coset
localized "infix ` +l `:70 := left_add_coset" in coset
localized "infix ` *r `:70 := right_coset" in coset
localized "infix ` +r `:70 := right_add_coset" in coset
section coset_mul
variable [has_mul α]
@[to_additive mem_left_add_coset]
lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s :=
mem_image_of_mem (λ b : α, a * b) hxS
@[to_additive mem_right_add_coset]
lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a :=
mem_image_of_mem (λ b : α, b * a) hxS
@[to_additive left_add_coset_equiv]
def left_coset_equiv (s : set α) (a b : α) := a *l s = b *l s
@[to_additive left_add_coset_equiv_rel]
lemma left_coset_equiv_rel (s : set α) : equivalence (left_coset_equiv s) :=
mk_equivalence (left_coset_equiv s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans)
end coset_mul
section coset_semigroup
variable [semigroup α]
@[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s :=
by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc]
attribute [to_additive left_add_coset_assoc] left_coset_assoc
@[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) :=
by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc]
attribute [to_additive right_add_coset_assoc] right_coset_assoc
@[to_additive left_add_coset_right_add_coset]
lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) :=
by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc]
end coset_semigroup
section coset_monoid
variables [monoid α] (s : set α)
@[simp] lemma one_left_coset : 1 *l s = s :=
set.ext $ by simp [left_coset]
attribute [to_additive zero_left_add_coset] one_left_coset
@[simp] lemma right_coset_one : s *r 1 = s :=
set.ext $ by simp [right_coset]
attribute [to_additive right_add_coset_zero] right_coset_one
end coset_monoid
section coset_submonoid
open submonoid
variables [monoid α] (s : submonoid α)
@[to_additive mem_own_left_add_coset]
lemma mem_own_left_coset (a : α) : a ∈ a *l s :=
suffices a * 1 ∈ a *l s, by simpa,
mem_left_coset a (one_mem s)
@[to_additive mem_own_right_add_coset]
lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a :=
suffices 1 * a ∈ (s : set α) *r a, by simpa,
mem_right_coset a (one_mem s)
@[to_additive mem_left_add_coset_left_add_coset]
lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s :=
by rw [←submonoid.mem_coe, ←ha]; exact mem_own_left_coset s a
@[to_additive mem_right_add_coset_right_add_coset]
lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s :=
by rw [←submonoid.mem_coe, ←ha]; exact mem_own_right_coset s a
end coset_submonoid
section coset_group
variables [group α] {s : set α} {x : α}
@[to_additive mem_left_add_coset_iff]
lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s :=
iff.intro
(assume ⟨b, hb, eq⟩, by simp [eq.symm, hb])
(assume h, ⟨a⁻¹ * x, h, by simp⟩)
@[to_additive mem_right_add_coset_iff]
lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s :=
iff.intro
(assume ⟨b, hb, eq⟩, by simp [eq.symm, hb])
(assume h, ⟨x * a⁻¹, h, by simp⟩)
end coset_group
section coset_subgroup
open submonoid
open is_subgroup
variables [group α] (s : set α) [is_subgroup s]
@[to_additive left_add_coset_mem_left_add_coset]
lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s :=
set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_right s (inv_mem ha)]
@[to_additive right_add_coset_mem_right_add_coset]
lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : s *r a = s :=
set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_left s (inv_mem ha)]
@[to_additive normal_of_eq_add_cosets]
theorem normal_of_eq_cosets [normal_subgroup s] (g : α) : g *l s = s *r g :=
set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [mem_norm_comm_iff]
@[to_additive eq_add_cosets_of_normal]
theorem eq_cosets_of_normal (h : ∀ g, g *l s = s *r g) : normal_subgroup s :=
⟨assume a ha g, show g * a * g⁻¹ ∈ s,
by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩
@[to_additive normal_iff_eq_add_cosets]
theorem normal_iff_eq_cosets : normal_subgroup s ↔ ∀ g, g *l s = s *r g :=
⟨@normal_of_eq_cosets _ _ s _, eq_cosets_of_normal s⟩
end coset_subgroup
run_cmd to_additive.map_namespace `quotient_group `quotient_add_group
namespace quotient_group
@[to_additive]
def left_rel [group α] (s : set α) [is_subgroup s] : setoid α :=
⟨λ x y, x⁻¹ * y ∈ s,
assume x, by simp [is_submonoid.one_mem],
assume x y hxy,
have (x⁻¹ * y)⁻¹ ∈ s, from is_subgroup.inv_mem hxy,
by simpa using this,
assume x y z hxy hyz,
have x⁻¹ * y * (y⁻¹ * z) ∈ s, from is_submonoid.mul_mem hxy hyz,
by simpa [mul_assoc] using this⟩
/-- `quotient s` is the quotient type representing the left cosets of `s`.
If `s` is a normal subgroup, `quotient s` is a group -/
@[to_additive]
def quotient [group α] (s : set α) [is_subgroup s] : Type* := quotient (left_rel s)
variables [group α] {s : set α} [is_subgroup s]
@[to_additive]
def mk (a : α) : quotient s :=
quotient.mk' a
@[elab_as_eliminator, to_additive]
lemma induction_on {C : quotient s → Prop} (x : quotient s)
(H : ∀ z, C (quotient_group.mk z)) : C x :=
quotient.induction_on' x H
@[to_additive]
instance : has_coe_t α (quotient s) := ⟨mk⟩ -- note [use has_coe_t]
@[elab_as_eliminator, to_additive]
lemma induction_on' {C : quotient s → Prop} (x : quotient s)
(H : ∀ z : α, C z) : C x :=
quotient.induction_on' x H
@[to_additive]
instance [group α] (s : set α) [is_subgroup s] : inhabited (quotient s) :=
⟨((1 : α) : quotient s)⟩
@[to_additive quotient_add_group.eq]
protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s :=
quotient.eq'
@[to_additive]
lemma eq_class_eq_left_coset [group α] (s : set α) [is_subgroup s] (g : α) :
{x : α | (x : quotient s) = g} = left_coset g s :=
set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq]
end quotient_group
namespace is_subgroup
open quotient_group
variables [group α] {s : set α}
@[to_additive]
def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s :=
⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩,
λ x, ⟨g * x.1, x.1, x.2, rfl⟩,
λ ⟨x, hx⟩, subtype.eq $ by simp,
λ ⟨g, hg⟩, subtype.eq $ by simp⟩
@[to_additive]
noncomputable def group_equiv_quotient_times_subgroup (hs : is_subgroup s) :
α ≃ quotient s × s :=
calc α ≃ Σ L : quotient s, {x : α // (x : quotient s)= L} :
(equiv.sigma_preimage_equiv quotient_group.mk).symm
... ≃ Σ L : quotient s, left_coset (quotient.out' L) s :
equiv.sigma_congr_right (λ L,
begin rw ← eq_class_eq_left_coset,
show {x // quotient.mk' x = L} ≃ {x : α // quotient.mk' x = quotient.mk' _},
simp [-quotient.eq']
end)
... ≃ Σ L : quotient s, s :
equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _)
... ≃ quotient s × s :
equiv.sigma_equiv_prod _ _
end is_subgroup
namespace quotient_group
variables [group α]
noncomputable def preimage_mk_equiv_subgroup_times_set
(s : set α) [is_subgroup s] (t : set (quotient s)) : quotient_group.mk ⁻¹' t ≃ s × t :=
have h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s →
(quotient.mk' (quotient.out' x * a) : quotient s) = quotient.mk' (quotient.out' x) :=
λ x a hx ha, quotient.sound' (show (quotient.out' x * a)⁻¹ * quotient.out' x ∈ s,
from (is_subgroup.inv_mem_iff _).1 $
by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]),
{ to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a,
@quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _)⟩,
⟨quotient.mk' a, ha⟩⟩,
inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t,
by simp [h hx ha, hx]⟩,
left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp,
right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] }
end quotient_group
library_note "use has_coe_t"
"We use the class `has_coe_t` instead of `has_coe` if the first-argument is a variable.
Using `has_coe` would cause looping of type-class inference. See
<https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain>"
|
c95b9db5de19142a643324ddf226f0fb255a08cc | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /category/traversable/instances.lean | f24314bdda6d8891fca079b30410db361fe9f9c7 | [
"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 | 6,078 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
Instances of `traversable` for types from the core library
-/
import category.traversable.basic category.basic category.functor category.applicative
import data.list.basic data.set.lattice
universes u v
instance : traversable id := ⟨λ _ _ _ _, id⟩
instance : is_lawful_traversable id := by refine {..}; intros; refl
section option
open functor
section inst
variables {F : Type u → Type v} [applicative F]
instance : traversable option := ⟨@option.traverse⟩
end inst
variables {F G : Type u → Type u}
variables [applicative F] [applicative G]
variables [is_lawful_applicative F] [is_lawful_applicative G]
lemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x :=
by cases x; refl
lemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) :
option.traverse (comp.mk ∘ (<$>) f ∘ g) x =
comp.mk (option.traverse f <$> option.traverse g x) :=
by cases x; simp! with functor_norm; refl
lemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) :
traverse (id.mk ∘ f) x = id.mk (f <$> x) :=
by cases x; refl
variable (η : applicative_transformation F G)
lemma option.naturality {α β} (f : α → F β) (x : option α) :
η (option.traverse f x) = option.traverse (@η _ ∘ f) x :=
by cases x with x; simp! [*] with functor_norm
end option
instance : is_lawful_traversable option :=
{ id_traverse := @option.id_traverse,
comp_traverse := @option.comp_traverse,
traverse_eq_map_id := @option.traverse_eq_map_id,
naturality := @option.naturality }
namespace list
variables {F G : Type u → Type u}
variables [applicative F] [applicative G]
variables [is_lawful_applicative F] [is_lawful_applicative G]
open applicative functor
open list (cons)
protected lemma id_traverse {α} (xs : list α) :
list.traverse id.mk xs = xs :=
by induction xs; simp! * with functor_norm; refl
protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) :
list.traverse (comp.mk ∘ (<$>) f ∘ g) x =
comp.mk (list.traverse f <$> list.traverse g x) :=
by induction x; simp! * with functor_norm; refl
protected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) :
list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=
by induction x; simp! * with functor_norm; refl
variable (η : applicative_transformation F G)
protected lemma naturality {α β} (f : α → F β) (x : list α) :
η (list.traverse f x) = list.traverse (@η _ ∘ f) x :=
by induction x; simp! * with functor_norm
open nat
instance : traversable list := ⟨@list.traverse⟩
instance : is_lawful_traversable list :=
{ id_traverse := @list.id_traverse,
comp_traverse := @list.comp_traverse,
traverse_eq_map_id := @list.traverse_eq_map_id,
naturality := @list.naturality }
section traverse
variables {α' β' : Type u} (f : α' → F β')
@[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl
@[simp] lemma traverse_cons (a : α') (l : list α') :
traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl
variables [is_lawful_applicative F]
@[simp] lemma traverse_append :
∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs
| [] bs :=
have has_append.append ([] : list β') = id, by funext; refl,
by simp [this] with functor_norm
| (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr
lemma mem_traverse {f : α' → set β'} :
∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l
| [] [] := by simp
| (a::as) [] := by simp; exact assume h, match h with end
| [] (b::bs) := by simp
| (a::as) (b::bs) :=
suffices (b :: bs : list β') ∈ traverse f (a :: as) ↔ b ∈ f a ∧ bs ∈ traverse f as,
by simpa [mem_traverse as bs],
iff.intro
(assume ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩, ⟨hb, hl⟩)
(assume ⟨hb, hl⟩, ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩)
end traverse
end list
namespace sum
section traverse
variables {σ : Type u}
variables {F G : Type u → Type u}
variables [applicative F] [applicative G]
open applicative functor
open list (cons)
protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β)
| (sum.inl x) := pure (sum.inl x)
| (sum.inr x) := sum.inr <$> f x
variables [is_lawful_applicative F] [is_lawful_applicative G]
protected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x :=
by cases x; refl
protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :
sum.traverse (comp.mk ∘ (<$>) f ∘ g) x =
comp.mk (sum.traverse f <$> sum.traverse g x) :=
by cases x; simp! [sum.traverse,map_id] with functor_norm; refl
protected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :
sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=
by induction x; simp! * with functor_norm; refl
protected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :
(<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x :=
by cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl
protected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :
sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=
by cases x; simp [sum.traverse, id_map] with functor_norm; refl
variable (η : applicative_transformation F G)
protected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) :
η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x :=
by cases x; simp! [sum.traverse] with functor_norm
end traverse
instance {σ : Type u} : traversable.{u} (sum σ) := ⟨@sum.traverse _⟩
instance {σ : Type u} : is_lawful_traversable.{u} (sum σ) :=
{ id_traverse := @sum.id_traverse σ,
comp_traverse := @sum.comp_traverse σ,
traverse_eq_map_id := @sum.traverse_eq_map_id σ,
naturality := @sum.naturality σ }
end sum
|
b8f6c45488515a668fe82947fe9198c7b7635836 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/finset/pi_induction.lean | 9cc1013b99ec7f1bdde18f1ad53873c50c1c1dfc | [
"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,092 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import data.fintype.lattice
import data.finset.sigma
/-!
# Induction principles for `Π i, finset (α i)`
In this file we prove a few induction principles for functions `Π i : ι, finset (α i)` defined on a
finite type.
* `finset.induction_on_pi` is a generic lemma that requires only `[finite ι]`, `[decidable_eq ι]`,
and `[Π i, decidable_eq (α i)]`; this version can be seen as a direct generalization of
`finset.induction_on`.
* `finset.induction_on_pi_max` and `finset.induction_on_pi_min`: generalizations of
`finset.induction_on_max`; these versions require `Π i, linear_order (α i)` but assume
`∀ y ∈ g i, y < x` and `∀ y ∈ g i, x < y` respectively in the induction step.
## Tags
finite set, finite type, induction, function
-/
open function
variables {ι : Type*} {α : ι → Type*} [finite ι] [decidable_eq ι] [Π i, decidable_eq (α i)]
namespace finset
/-- General theorem for `finset.induction_on_pi`-style induction principles. -/
lemma induction_on_pi_of_choice (r : Π i, α i → finset (α i) → Prop)
(H_ex : ∀ i (s : finset (α i)) (hs : s.nonempty), ∃ x ∈ s, r i x (s.erase x))
{p : (Π i, finset (α i)) → Prop} (f : Π i, finset (α i)) (h0 : p (λ _, ∅))
(step : ∀ (g : Π i, finset (α i)) (i : ι) (x : α i),
r i x (g i) → p g → p (update g i (insert x (g i)))) :
p f :=
begin
casesI nonempty_fintype ι,
induction hs : univ.sigma f using finset.strong_induction_on with s ihs generalizing f, subst s,
cases eq_empty_or_nonempty (univ.sigma f) with he hne,
{ convert h0, simpa [funext_iff] using he },
{ rcases sigma_nonempty.1 hne with ⟨i, -, hi⟩,
rcases H_ex i (f i) hi with ⟨x, x_mem, hr⟩,
set g := update f i ((f i).erase x) with hg, clear_value g,
have hx' : x ∉ g i, by { rw [hg, update_same], apply not_mem_erase },
obtain rfl : f = update g i (insert x (g i)),
by rw [hg, update_idem, update_same, insert_erase x_mem, update_eq_self],
clear hg, rw [update_same, erase_insert hx'] at hr,
refine step _ _ _ hr (ihs (univ.sigma g) _ _ rfl),
rw ssubset_iff_of_subset (sigma_mono (subset.refl _) _),
exacts [⟨⟨i, x⟩, mem_sigma.2 ⟨mem_univ _, by simp⟩, by simp [hx']⟩,
(@le_update_iff _ _ _ _ g g i _).2 ⟨subset_insert _ _, λ _ _, le_rfl⟩] }
end
/-- Given a predicate on functions `Π i, finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `λ _, ∅` and for any function `g : Π i, finset (α i)`, an index
`i : ι`, and `x ∉ g i`, `p g` implies `p (update g i (insert x (g i)))`.
See also `finset.induction_on_pi_max` and `finset.induction_on_pi_min` for specialized versions
that require `Π i, linear_order (α i)`. -/
lemma induction_on_pi {p : (Π i, finset (α i)) → Prop} (f : Π i, finset (α i)) (h0 : p (λ _, ∅))
(step : ∀ (g : Π i, finset (α i)) (i : ι) (x : α i) (hx : x ∉ g i),
p g → p (update g i (insert x (g i)))) :
p f :=
induction_on_pi_of_choice (λ i x s, x ∉ s) (λ i s ⟨x, hx⟩, ⟨x, hx, not_mem_erase x s⟩) f h0 step
/-- Given a predicate on functions `Π i, finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `λ _, ∅` and for any function `g : Π i, finset (α i)`, an index
`i : ι`, and an element`x : α i` that is strictly greater than all elements of `g i`, `p g` implies
`p (update g i (insert x (g i)))`.
This lemma requires `linear_order` instances on all `α i`. See also `finset.induction_on_pi` for a
version that `x ∉ g i` instead of ` does not need `Π i, linear_order (α i)`. -/
lemma induction_on_pi_max [Π i, linear_order (α i)] {p : (Π i, finset (α i)) → Prop}
(f : Π i, finset (α i)) (h0 : p (λ _, ∅))
(step : ∀ (g : Π i, finset (α i)) (i : ι) (x : α i),
(∀ y ∈ g i, y < x) → p g → p (update g i (insert x (g i)))) :
p f :=
induction_on_pi_of_choice (λ i x s, ∀ y ∈ s, y < x)
(λ i s hs, ⟨s.max' hs, s.max'_mem hs, λ y, s.lt_max'_of_mem_erase_max' _⟩) f h0 step
/-- Given a predicate on functions `Π i, finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `λ _, ∅` and for any function `g : Π i, finset (α i)`, an index
`i : ι`, and an element`x : α i` that is strictly less than all elements of `g i`, `p g` implies
`p (update g i (insert x (g i)))`.
This lemma requires `linear_order` instances on all `α i`. See also `finset.induction_on_pi` for a
version that `x ∉ g i` instead of ` does not need `Π i, linear_order (α i)`. -/
lemma induction_on_pi_min [Π i, linear_order (α i)] {p : (Π i, finset (α i)) → Prop}
(f : Π i, finset (α i)) (h0 : p (λ _, ∅))
(step : ∀ (g : Π i, finset (α i)) (i : ι) (x : α i),
(∀ y ∈ g i, x < y) → p g → p (update g i (insert x (g i)))) :
p f :=
@induction_on_pi_max ι (λ i, (α i)ᵒᵈ) _ _ _ _ _ _ h0 step
end finset
|
370c8e28fbe3088d017ab39af9da00e99d0cd467 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/implicitLambdaLocalWithoutType.lean | 38a0acaea6622d544fd567e9074eb01e554963f1 | [
"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,435 | lean | def foo1mk (_ : ∀ (α : Type) (a : α), a = a) : Nat := 37
def foo2mk (_ : ∀ {α : Type} (a : α), a = a) : Nat := 37 -- implicit binder
example (x) : foo1mk x = foo1mk x := rfl -- works
example (x : ∀ {α : Type} (a : α), a = a) : 37 = foo2mk x := rfl -- works
example (x) : 37 = foo2mk @x := rfl -- works
example (x) : foo1mk x = foo1mk x := rfl -- works
example (x : ∀ {α : Type} (a : α), a = a) : foo2mk x = foo2mk x := rfl -- works
example (x) : foo2mk x = foo2mk x := rfl -- works
example (x) : foo2mk x = 37 := rfl -- works
example (x) : foo2mk x = foo2mk x := rfl -- works
universe u v w
structure ApplicativeTransformation (F : Type u → Type v) [Applicative F] [LawfulApplicative F]
(G : Type u → Type w) [Applicative G] [LawfulApplicative G] : Type max (u + 1) v w where
app : ∀ α : Type u, F α → G α
preserves_pure' : ∀ {α : Type u} (x : α), app _ (pure x) = pure x
preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app _ (x <*> y) = app _ x <*> app _ y
variable (F : Type u → Type v) [Applicative F] [LawfulApplicative F]
variable (G : Type u → Type w) [Applicative G] [LawfulApplicative G]
instance : CoeFun (ApplicativeTransformation F G) fun _ => ∀ {α}, F α → G α :=
⟨ApplicativeTransformation.app⟩
variable {F G}
@[simp]
theorem coe_mk (f : ∀ (α : Type u), F α → G α) (pp ps) :
(ApplicativeTransformation.mk f pp ps) = f :=
rfl
|
4728e499f642dada0a4b32bc63d5e63f9c4e07cc | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/data/support.lean | 743c26362a51db8056aed41ea13331cd010617c9 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 5,287 | 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 order.conditionally_complete_lattice
import algebra.big_operators
import algebra.group.prod
/-!
# Support of a function
In this file we define `function.support f = {x | f x ≠ 0}` and prove its basic properties.
-/
universes u v w x y
open set
open_locale big_operators
namespace function
variables {α : Type u} {β : Type v} {ι : Sort w} {A : Type x} {B : Type y}
/-- `support` of a function is the set of points `x` such that `f x ≠ 0`. -/
def support [has_zero A] (f : α → A) : set α := {x | f x ≠ 0}
lemma nmem_support [has_zero A] {f : α → A} {x : α} :
x ∉ support f ↔ f x = 0 :=
classical.not_not
lemma mem_support [has_zero A] {f : α → A} {x : α} :
x ∈ support f ↔ f x ≠ 0 :=
iff.rfl
lemma support_subset_iff [has_zero A] {f : α → A} {s : set α} :
support f ⊆ s ↔ ∀ x, f x ≠ 0 → x ∈ s :=
iff.rfl
lemma support_subset_iff' [has_zero A] {f : α → A} {s : set α} :
support f ⊆ s ↔ ∀ x ∉ s, f x = 0 :=
forall_congr $ λ x, by classical; exact not_imp_comm
lemma support_binop_subset [has_zero A] (op : A → A → A) (op0 : op 0 0 = 0) (f g : α → A) :
support (λ x, op (f x) (g x)) ⊆ support f ∪ support g :=
λ x hx, classical.by_cases
(λ hf : f x = 0, or.inr $ λ hg, hx $ by simp only [hf, hg, op0])
or.inl
lemma support_add [add_monoid A] (f g : α → A) :
support (λ x, f x + g x) ⊆ support f ∪ support g :=
support_binop_subset (+) (zero_add _) f g
@[simp] lemma support_neg [add_group A] (f : α → A) :
support (λ x, -f x) = support f :=
set.ext $ λ x, not_congr neg_eq_zero
lemma support_sub [add_group A] (f g : α → A) :
support (λ x, f x - g x) ⊆ support f ∪ support g :=
support_binop_subset (has_sub.sub) (sub_self _) f g
@[simp] lemma support_mul [mul_zero_class A] [no_zero_divisors A] (f g : α → A) :
support (λ x, f x * g x) = support f ∩ support g :=
set.ext $ λ x, by simp only [support, ne.def, mul_eq_zero, mem_set_of_eq,
mem_inter_iff, not_or_distrib]
@[simp] lemma support_inv [division_ring A] (f : α → A) :
support (λ x, (f x)⁻¹) = support f :=
set.ext $ λ x, not_congr inv_eq_zero
@[simp] lemma support_div [division_ring A] (f g : α → A) :
support (λ x, f x / g x) = support f ∩ support g :=
by simp [div_eq_mul_inv]
lemma support_sup [has_zero A] [semilattice_sup A] (f g : α → A) :
support (λ x, (f x) ⊔ (g x)) ⊆ support f ∪ support g :=
support_binop_subset (⊔) sup_idem f g
lemma support_inf [has_zero A] [semilattice_inf A] (f g : α → A) :
support (λ x, (f x) ⊓ (g x)) ⊆ support f ∪ support g :=
support_binop_subset (⊓) inf_idem f g
lemma support_max [has_zero A] [decidable_linear_order A] (f g : α → A) :
support (λ x, max (f x) (g x)) ⊆ support f ∪ support g :=
support_sup f g
lemma support_min [has_zero A] [decidable_linear_order A] (f g : α → A) :
support (λ x, min (f x) (g x)) ⊆ support f ∪ support g :=
support_inf f g
lemma support_supr [has_zero A] [conditionally_complete_lattice A] [nonempty ι] (f : ι → α → A) :
support (λ x, ⨆ i, f i x) ⊆ ⋃ i, support (f i) :=
begin
intros x hx,
classical,
contrapose hx,
simp only [mem_Union, not_exists, nmem_support] at hx ⊢,
simp only [hx, csupr_const]
end
lemma support_infi [has_zero A] [conditionally_complete_lattice A] [nonempty ι] (f : ι → α → A) :
support (λ x, ⨅ i, f i x) ⊆ ⋃ i, support (f i) :=
@support_supr _ _ (order_dual A) ⟨(0:A)⟩ _ _ f
lemma support_sum [add_comm_monoid A] (s : finset α) (f : α → β → A) :
support (λ x, ∑ i in s, f i x) ⊆ ⋃ i ∈ s, support (f i) :=
begin
intros x hx,
classical,
contrapose hx,
simp only [mem_Union, not_exists, nmem_support] at hx ⊢,
exact finset.sum_eq_zero hx
end
lemma support_prod_subset [comm_monoid_with_zero A] (s : finset α) (f : α → β → A) :
support (λ x, ∏ i in s, f i x) ⊆ ⋂ i ∈ s, support (f i) :=
λ x hx, mem_bInter_iff.2 $ λ i hi H, hx $ finset.prod_eq_zero hi H
lemma support_prod [comm_monoid_with_zero A] [no_zero_divisors A] [nontrivial A]
(s : finset α) (f : α → β → A) :
support (λ x, ∏ i in s, f i x) = ⋂ i ∈ s, support (f i) :=
set.ext $ λ x, by
simp only [support, ne.def, finset.prod_eq_zero_iff, mem_set_of_eq, set.mem_Inter, not_exists]
lemma support_comp_subset [has_zero A] [has_zero B] {g : A → B} (hg : g 0 = 0) (f : α → A) :
support (g ∘ f) ⊆ support f :=
λ x, mt $ λ h, by simp [(∘), *]
lemma support_subset_comp [has_zero A] [has_zero B] {g : A → B} (hg : ∀ {x}, g x = 0 → x = 0)
(f : α → A) :
support f ⊆ support (g ∘ f) :=
λ x, mt hg
lemma support_comp_eq [has_zero A] [has_zero B] (g : A → B) (hg : ∀ {x}, g x = 0 ↔ x = 0)
(f : α → A) :
support (g ∘ f) = support f :=
set.ext $ λ x, not_congr hg
lemma support_prod_mk [has_zero A] [has_zero B] (f : α → A) (g : α → B) :
support (λ x, (f x, g x)) = support f ∪ support g :=
set.ext $ λ x, by simp only [support, classical.not_and_distrib, mem_union_eq, mem_set_of_eq,
prod.mk_eq_zero, ne.def]
end function
|
d286119d148275ef68fefc21e2fbec19480493cd | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/convex/extreme.lean | 810e6ceec62828e4dcf68b83892b9a59f689ba66 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 11,524 | 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 IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
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
Prove lemmas relating extreme sets and points to the intrinsic frontier.
More not-yet-PRed stuff is available on the branch `sperner_again`.
-/
open function set
open_locale affine classical
variables {𝕜 E F ι : Type*} {π : ι → Type*}
section has_smul
variables (𝕜) [ordered_semiring 𝕜] [add_comm_monoid E] [has_smul 𝕜 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₂⦄, x₂ ∈ A → ∀ ⦃x⦄, 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₂⦄, 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₁ hx₁A x₂ 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
refine ⟨subset.trans hBC.1 hAB.1, λ x₁ hx₁A x₂ hx₂A x hxC hx, _⟩,
obtain ⟨hx₁B, hx₂B⟩ := hAB.2 hx₁A hx₂A (hBC.1 hxC) hx,
exact hBC.2 hx₁B hx₂B 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₁ hx₁A x₂ hx₂A x ⟨hxB, hxC⟩ hx,
obtain ⟨hx₁B, hx₂B⟩ := hAB.2 hx₁A hx₂A hxB hx,
obtain ⟨hx₁C, hx₂C⟩ := hAC.2 hx₁A hx₂A 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₁ hx₁B x₂ hx₂B x hxC hx, hAC.2 (hBA hx₁B) (hBA hx₂B) hxC hx⟩
lemma is_extreme_Inter {ι : Sort*} [nonempty ι] {F : ι → set E}
(hAF : ∀ i : ι, is_extreme 𝕜 A (F i)) :
is_extreme 𝕜 A (⋂ i : ι, F i) :=
begin
obtain i := classical.arbitrary ι,
refine ⟨Inter_subset_of_subset i (hAF i).1, λ x₁ hx₁A x₂ hx₂A x hxF hx, _⟩,
simp_rw mem_Inter at ⊢ hxF,
have h := λ i, (hAF i).2 hx₁A hx₂A (hxF i) hx,
exact ⟨λ i, (h i).1, λ i, (h i).2⟩,
end
lemma is_extreme_bInter {F : set (set E)} (hF : F.nonempty) (hA : ∀ B ∈ F, is_extreme 𝕜 A B) :
is_extreme 𝕜 A (⋂ B ∈ F, B) :=
by { haveI := hF.to_subtype, simpa only [Inter_subtype] using is_extreme_Inter (λ i : F, hA _ i.2) }
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₁ hx₁A x₂ hx₂A x hxF hx, _⟩,
simp_rw mem_sInter at ⊢ hxF,
have h := λ B hB, (hAF B hB).2 hx₁A hx₂A (hxF B hB) hx,
exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩,
end
lemma mem_extreme_points :
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₁ hx₁ x₂ hx₂, hx.2 hx₁ hx₂ rfl⟩⟩,
rintro ⟨hxA, hAx⟩,
use singleton_subset_iff.2 hxA,
rintro x₁ hx₁A x₂ hx₂A y (rfl : y = x),
exact hAx 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₁ hx₁ x₂ 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₁ hx₁ x₂ hx₂ hx, hxA.2 (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_smul
section ordered_semiring
variables [ordered_semiring 𝕜] [add_comm_group E] [add_comm_group F] [Π i, add_comm_group (π i)]
[module 𝕜 E] [module 𝕜 F] [Π i, module 𝕜 (π i)] {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₁ ⟨hx₁A, hx₁B⟩ x₂ ⟨hx₂A, hx₂B⟩ x hx,
⟨hA.open_segment_subset hx₁A hx₂A hx, λ hxB, hx₁B (hAB.2 hx₁A hx₂A hxB hx).1⟩)
@[simp] lemma extreme_points_prod (s : set E) (t : set F) :
(s ×ˢ t).extreme_points 𝕜 = s.extreme_points 𝕜 ×ˢ t.extreme_points 𝕜 :=
begin
ext,
refine (and_congr_right $ λ hx, ⟨λ h, _, λ h, _⟩).trans (and_and_and_comm _ _ _ _),
split,
{ rintro x₁ hx₁ x₂ hx₂ hx_fst,
refine (h (mk_mem_prod hx₁ hx.2) (mk_mem_prod hx₂ hx.2) _).imp
(congr_arg prod.fst) (congr_arg prod.fst),
rw ←prod.image_mk_open_segment_left,
exact ⟨_, hx_fst, prod.mk.eta⟩ },
{ rintro x₁ hx₁ x₂ hx₂ hx_snd,
refine (h (mk_mem_prod hx.1 hx₁) (mk_mem_prod hx.1 hx₂) _).imp
(congr_arg prod.snd) (congr_arg prod.snd),
rw ←prod.image_mk_open_segment_right,
exact ⟨_, hx_snd, prod.mk.eta⟩ },
{ rintro x₁ hx₁ x₂ hx₂ ⟨a, b, ha, hb, hab, hx'⟩,
simp_rw prod.ext_iff,
exact (and_and_and_comm _ _ _ _).1
⟨h.1 hx₁.1 hx₂.1 ⟨a, b, ha, hb, hab, congr_arg prod.fst hx'⟩,
h.2 hx₁.2 hx₂.2 ⟨a, b, ha, hb, hab, congr_arg prod.snd hx'⟩⟩ }
end
@[simp] lemma extreme_points_pi (s : Π i, set (π i)) :
(univ.pi s).extreme_points 𝕜 = univ.pi (λ i, (s i).extreme_points 𝕜) :=
begin
ext,
simp only [mem_extreme_points, mem_pi, mem_univ, true_implies_iff, @forall_and_distrib ι],
refine and_congr_right (λ hx, ⟨λ h i, _, λ h, _⟩),
{ rintro x₁ hx₁ x₂ hx₂ hi,
refine (h (update x i x₁) _ (update x i x₂) _ _).imp (λ h₁, by rw [←h₁, update_same])
(λ h₂, by rw [←h₂, update_same]),
iterate 2
{ rintro j,
obtain rfl | hji := eq_or_ne j i,
{ rwa update_same },
{ rw update_noteq hji,
exact hx _ } },
rw ←pi.image_update_open_segment,
exact ⟨_, hi, update_eq_self _ _⟩ },
{ rintro x₁ hx₁ x₂ hx₂ ⟨a, b, ha, hb, hab, hx'⟩,
simp_rw [funext_iff, ←forall_and_distrib],
exact λ i, h _ _ (hx₁ _) _ (hx₂ _) ⟨a, b, ha, hb, hab, congr_fun hx' _⟩ }
end
end ordered_semiring
section linear_ordered_ring
variables {𝕜} [linear_ordered_ring 𝕜] [add_comm_group E] [module 𝕜 E]
variables [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 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 :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x :=
begin
refine and_congr_right (λ hxA, forall₄_congr $ λ x₁ h₁ x₂ h₂, _),
split,
{ rw ← insert_endpoints_open_segment,
rintro H (rfl|rfl|hx),
exacts [or.inl rfl, or.inr rfl, or.inl $ (H hx).1] },
{ intros H hx,
rcases H (open_segment_subset_segment _ _ _ hx) with rfl | rfl,
exacts [⟨rfl, (left_mem_open_segment_iff.1 hx).symm⟩, ⟨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₁ hx₁ x₂ hx₂ hx, _⟩,
rw convex_iff_segment_subset at hAx,
by_contra' 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,
apply_instance
end
end linear_ordered_ring
|
88cc7305e038119cc3e3c0bacf5de16585fd9f6f | c3de33d4701e6113627153fe1103b255e752ed7d | /topology/uniform_space.lean | d1795e7c6ffa49f148a1f9d1d7da47ebe8dee24a | [] | no_license | jroesch/library_dev | 77d2b246ff47ab05d55cb9706a37d3de97038388 | 4faa0a45c6aa7eee6e661113c2072b8840bff79b | refs/heads/master | 1,611,281,606,352 | 1,495,661,644,000 | 1,495,661,644,000 | 92,340,430 | 0 | 0 | null | 1,495,663,344,000 | 1,495,663,344,000 | null | UTF-8 | Lean | false | false | 52,372 | 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 uniform spaces.
-/
import algebra.lattice.filter .topological_space .continuity
open set lattice filter
set_option eqn_compiler.zeta true
attribute [trans] subset.trans
universes u v w x y
section
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y}
def id_rel {α : Type u} := {p : α × α | p.1 = p.2}
def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) :=
{p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂}
@[simp] lemma swap_id_rel : prod.swap '' id_rel = @id_rel α :=
set.ext $ take ⟨a, b⟩, by simp [image_swap_eq_vimage_swap]; exact eq_comm
lemma monotone_comp_rel [weak_order β] {f g : β → set (α×α)}
(hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) :=
take a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩
lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) :
(a, b) ∈ comp_rel s t :=
⟨c, h₁, h₂⟩
@[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r :=
set.ext $ take ⟨a, b⟩, ⟨take ⟨a', (heq : a = a'), ha'⟩, heq.symm ▸ ha', take ha, ⟨a, rfl, ha⟩⟩
/- uniformity -/
class uniform_space (α : Type u) :=
(uniformity : filter (α × α))
(refl : principal id_rel ≤ uniformity)
(symm : prod.swap <$> uniformity ≤ uniformity)
(comp : uniformity^.lift' (λs, comp_rel s s) ≤ uniformity)
lemma uniform_space_eq {u₁ u₂ : uniform_space α} (h : u₁.uniformity = u₂.uniformity) : u₁ = u₂ :=
begin
cases u₁ with a, cases u₂ with b,
assert h' : a = b, assumption,
clear h,
subst h'
end
section uniform_space
variables [uniform_space α]
def uniformity : filter (α × α) := uniform_space.uniformity α
lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ :=
uniform_space.refl α
lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) :
(x, x) ∈ s :=
refl_le_uniformity h rfl
lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity :=
uniform_space.symm α
lemma comp_le_uniformity :
uniformity^.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity :=
uniform_space.comp α
lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) :
∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s :=
have s ∈ (uniformity^.lift' (λt:set (α×α), comp_rel t t)).sets,
from comp_le_uniformity hs,
(mem_lift'_iff $ monotone_comp_rel monotone_id monotone_id).mp this
lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) :
∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s :=
have vimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs,
⟨s ∩ vimage prod.swap s, inter_mem_sets hs this, take a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩
lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) :
∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s :=
let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in
let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in
⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩
lemma uniformity_le_symm : uniformity ≤ map (@prod.swap α α) uniformity :=
calc uniformity = id <$> uniformity : (functor.id_map _)^.symm
... = (prod.swap.{u u} ∘ prod.swap) <$> uniformity :
congr_arg (λf : (α×α)→(α×α), f <$> uniformity) (by apply funext; intro x; cases x; refl)
... = (map prod.swap ∘ map prod.swap) uniformity :
congr map_compose rfl
... ≤ prod.swap.{u u} <$> uniformity : map_mono symm_le_uniformity
lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity :=
le_antisymm uniformity_le_symm symm_le_uniformity
lemma uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g)
(h : uniformity^.lift (λs, g (vimage prod.swap s)) ≤ f) : uniformity^.lift g ≤ f :=
le_trans
(lift_mono uniformity_le_symm (le_refl _))
(by rw [map_lift_eq2 hg, image_swap_eq_vimage_swap]; exact h)
lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f):
uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f :=
calc uniformity.lift (λs, f (comp_rel s s)) =
(uniformity.lift' (λs:set (α×α), comp_rel s s))^.lift f :
begin
rw [lift_lift'_assoc],
exact monotone_comp_rel monotone_id monotone_id,
exact h
end
... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _)
lemma comp_le_uniformity3 :
uniformity^.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity :=
calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) =
uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) :
begin
rw [lift_lift'_same_eq_lift'],
exact (take x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id),
exact (take x, monotone_comp_rel monotone_id monotone_const),
end
... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) :
lift_mono' $ take s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $
monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal
... = uniformity.lift' (λs:set(α×α), comp_rel s s) :
lift_lift'_same_eq_lift'
(take s, monotone_comp_rel monotone_const monotone_id)
(take s, monotone_comp_rel monotone_id monotone_const)
... ≤ uniformity : comp_le_uniformity
instance uniform_space.to_topological_space : topological_space α :=
{ open' := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (uniformity.sets : set (set (α×α))),
open_univ := by simp; intros; apply univ_mem_sets,
open_inter := take s t hs ht x ⟨xs, xt⟩,
uniformity.upwards_sets (inter_mem_sets (hs x xs) (ht x xt)) $
take p ⟨ps, pt⟩ h, ⟨ps h, pt h⟩,
open_sUnion := take s hs x ⟨t, ts, xt⟩,
uniformity.upwards_sets (hs t ts x xt) $
take p ph h, ⟨t, ts, ph h⟩ }
lemma mem_nhds_uniformity_iff {x : α} {s : set α} :
(s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) :=
⟨ begin
simp [mem_nhds_sets_iff],
exact take ⟨t, ht, ts, xt⟩, uniformity.upwards_sets (ht x xt) $
take ⟨x', y⟩ h eq, ts $ h eq
end,
take hs,
mem_nhds_sets_iff.mpr $ ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets},
take x', assume hx' : {p : α × α | p.fst = x' → p.snd ∈ s} ∈ (@uniformity α _).sets,
refl_mem_uniformity hx' rfl,
take x' hx',
let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in
uniformity.upwards_sets ht $
take ⟨a, b⟩ hp' (eq : a = x'),
have hp : (x', b) ∈ t, from eq ▸ hp',
show {p : α × α | p.fst = b → p.snd ∈ s} ∈ (@uniformity α _).sets,
from uniformity.upwards_sets ht $
take ⟨a, b'⟩ hp' (heq : a = b),
have (b, b') ∈ t, from heq ▸ hp',
have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩,
show b' ∈ s,
from tr this rfl,
hs⟩⟩
lemma nhds_eq_uniformity {x : α} :
nhds x = uniformity^.lift' (λs:set (α×α), {y | (x, y) ∈ s}) :=
filter_eq $ set.ext $ take s,
begin
rw [mem_lift'_iff], tactic.swap, apply monotone_vimage,
simp [mem_nhds_uniformity_iff],
exact ⟨take h, ⟨_, h, take y h, h rfl⟩,
take ⟨t, h₁, h₂⟩,
uniformity.upwards_sets h₁ $
take ⟨x', y⟩ hp (eq : x' = x), h₂ $
show (x, y) ∈ t, from eq ▸ hp⟩
end
lemma mem_nhds_left {x : α} {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) :
{y : α | (x, y) ∈ s} ∈ (nhds x)^.sets :=
have nhds x ≤ principal {y : α | (x, y) ∈ s},
by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h),
by simp at this; assumption
lemma mem_nhds_right {y : α} {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) :
{x : α | (x, y) ∈ s} ∈ (nhds y)^.sets :=
mem_nhds_left (symm_le_uniformity h)
lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) :
(nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) :=
eq.trans
begin
rw [nhds_eq_uniformity],
exact (filter.lift_assoc $ monotone_comp monotone_vimage $ monotone_comp monotone_vimage monotone_principal)
end
(congr_arg _ $ funext $ take s, filter.lift_principal hg)
lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) :
(nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (y, x) ∈ s}) :=
calc (nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg
... = ((@prod.swap α α) <$> uniformity)^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [-uniformity_eq_symm]
... = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) :
map_lift_eq2 $ monotone_comp monotone_vimage hg
... = _ : by simp [image_swap_eq_vimage_swap]
lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} :
filter.prod (nhds a) (nhds b) =
uniformity^.lift (λs:set (α×α), uniformity^.lift' (λt:set (α×α),
set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) :=
show (nhds a)^.lift (λs:set α, (nhds b)^.lift (λt:set α, principal (set.prod s t))) = _,
begin
rw [lift_nhds_right],
apply congr_arg, apply funext, intro s,
rw [lift_nhds_left],
refl,
exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal,
exact (monotone_lift' monotone_const $ monotone_lam $
take x, monotone_prod monotone_id monotone_const)
end
lemma nhds_eq_uniformity_prod {a b : α} :
nhds (a, b) =
uniformity^.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) :=
begin
rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'],
{ intro s, exact monotone_prod monotone_const monotone_vimage },
{ intro t, exact monotone_prod monotone_vimage monotone_const }
end
lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) :
∃(t : set (α×α)), open' t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} :=
let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in
have ∀p ∈ s, ∃t ⊆ cl_d, open' t ∧ p ∈ t, from
take ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $
show cl_d ∈ (nhds (x, y)).sets,
begin
rw [nhds_eq_uniformity_prod, mem_lift'_iff],
exact ⟨d, hd, take ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩,
exact monotone_prod monotone_vimage monotone_vimage
end,
have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)),
∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ open' (t p h) ∧ p ∈ t p h,
by simp [classical.skolem] at this; simp; assumption,
match this with
| ⟨t, ht⟩ :=
⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)),
open_Union $ take (p:α×α), open_Union $ take hp, (ht p hp).right.left,
take ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end,
Union_subset $ take p, Union_subset $ take hp, (ht p hp).left⟩
end
lemma closure_eq_inter_uniformity {t : set (α×α)} :
closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) :=
set.ext $ take ⟨a, b⟩,
calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds]
... ↔ (((@prod.swap α α) <$> uniformity).lift'
(λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) :
by rw [-uniformity_eq_symm, nhds_eq_uniformity_prod]
... ↔ ((map (@prod.swap α α) uniformity).lift'
(λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) :
by refl
... ↔ (uniformity.lift'
(λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) :
begin
rw [map_lift'_eq2],
simp [image_swap_eq_vimage_swap, function.comp],
exact monotone_prod monotone_vimage monotone_vimage
end
... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) :
begin
rw [lift'_inf_principal_eq, lift'_neq_bot_iff],
apply forall_congr, intro s, rw [ne_empty_iff_exists_mem],
exact monotone_inter (monotone_prod monotone_vimage monotone_vimage) monotone_const
end
... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) :
forall_congr $ take s, forall_congr $ take hs,
⟨take ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩,
take ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩
... ↔ _ : by simp
lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure :=
le_antisymm
(le_infi $ take s, le_infi $ take hs, by simp; exact uniformity.upwards_sets hs subset_closure)
(calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) :
lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs)
... ≤ uniformity : comp_le_uniformity3)
lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior :=
le_antisymm
(le_infi $ take d, le_infi $ take hd,
let ⟨s, hs, hs_comp⟩ := (mem_lift'_iff $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in
let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in
have s ⊆ interior d, from
calc s ⊆ t : hst
... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $
take x, suppose x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩,
have interior d ∈ (@uniformity α _).sets,
from (@uniformity α _).upwards_sets hs $ this,
by simp [this])
(take s hs, (uniformity.lift' interior).upwards_sets (mem_lift' hs) interior_subset)
lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) :
interior s ∈ (@uniformity α _).sets :=
by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs
/- uniform continuity -/
definition uniform_continuous [uniform_space β] (f : α → β) :=
filter.map (λx:α×α, (f x.1, f x.2)) uniformity ≤ uniformity
definition uniform_embedding [uniform_space β] (f : α → β) :=
(∀a₁ a₂, f a₁ = f a₂ → a₁ = a₂) ∧
vmap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity
lemma uniform_continuous_of_embedding [uniform_space β] {f : α → β}
(hf : uniform_embedding f) : uniform_continuous f :=
by simp [uniform_continuous, hf.right.symm]; exact take s hs, ⟨s, hs, subset.refl _⟩
lemma continuous_of_uniform [uniform_space β] {f : α → β}
(hf : uniform_continuous f) : continuous f :=
continuous_iff_towards.mpr $ take a,
calc map f (nhds a) ≤
(map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) :
begin
rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2],
exact (lift'_mono' $ take s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩,
⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩),
exact monotone_vimage,
exact monotone_vimage
end
... ≤ nhds (f a) :
by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _)
/- cauchy filters -/
definition cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity
lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g :=
⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩
lemma cauchy_nhds {a : α} : cauchy (nhds a) :=
⟨nhds_neq_bot,
calc filter.prod (nhds a) (nhds a) =
uniformity^.lift (λs:set (α×α), uniformity^.lift' (λt:set(α×α),
set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod
... ≤ uniformity^.lift' (λs:set (α×α), comp_rel s s) :
le_infi $ take s, le_infi $ take hs,
infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $
principal_mono.mpr $
take ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩
... ≤ uniformity : comp_le_uniformity⟩
lemma cauchy_pure {a : α} : cauchy (pure a) :=
cauchy_downwards cauchy_nhds
(show principal {a} ≠ ⊥, by simp)
(return_le_nhds a)
lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f)
(adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x :=
have ∀s∈f.sets, x ∈ closure s,
begin
intros s hs,
simp [closure_eq_nhds, inf_comm],
exact take h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _)
end,
calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) :
le_infi $ take s, le_infi $ take hs,
begin
rw [-forall_sets_neq_empty_iff_neq_bot] at adhs,
simp [this s hs],
exact f.upwards_sets hs subset_closure
end
... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) :
by simp [closure_prod_eq]; exact le_refl _
... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) :
begin
rw [prod_same_eq],
rw [lift'_lift'_assoc],
exact monotone_prod monotone_id monotone_id,
exact monotone_comp (take s t h x h', closure_mono h h') monotone_vimage
end
... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _)
... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) :
begin
rw [lift'_lift'_assoc],
exact take s t h, closure_mono h,
exact monotone_vimage
end
... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) :
by rw [-uniformity_eq_uniformity_closure]
... = nhds x :
by rw [nhds_eq_uniformity]
lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) :
f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ :=
⟨take h, (inf_of_le_left h).symm ▸ hf.left,
le_nhds_of_cauchy_adhp hf⟩
lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β}
(hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) :=
⟨have f ≠ ⊥, from hf.left, by simp; assumption,
calc filter.prod (map m f) (map m f) =
map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq
... ≤ map (λp:α×α, (m p.1, m p.2)) uniformity : map_mono hf.right
... ≤ uniformity : hm⟩
lemma cauchy_vmap [uniform_space β] {f : filter β} {m : α → β}
(hm : vmap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity)
(hf : cauchy f) (hb : vmap m f ≠ ⊥) : cauchy (vmap m f) :=
⟨hb,
calc filter.prod (vmap m f) (vmap m f) =
vmap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_vmap_vmap_eq
... ≤ vmap (λp:α×α, (m p.1, m p.2)) uniformity : vmap_mono hf.right
... ≤ uniformity : hm⟩
/- separated uniformity -/
protected def separation_rel (α : Type u) [uniform_space α] :=
(⋂₀ (@uniformity α _).sets)
lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) :=
⟨take x, take s, refl_mem_uniformity,
take x y, take h (s : set (α×α)) hs,
have vimage prod.swap s ∈ (@uniformity α _).sets,
from symm_le_uniformity hs,
h _ this,
take x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α)
s (hs : s ∈ (@uniformity α _).sets),
let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in
h_ts $ show (x, z) ∈ comp_rel t t,
from ⟨y, hxy t ht, hyz t ht⟩⟩
protected def separation_setoid (α : Type u) [uniform_space α] : setoid α :=
⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩
@[class]
definition separated (α : Type u) [uniform_space α] :=
separation_rel α = id_rel
instance separated_t2 [s : separated α] : t2_space α :=
⟨take x y, assume h : x ≠ y,
have separation_rel α = id_rel,
from s,
have (x, y) ∉ separation_rel α,
by simp [this]; exact h,
let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := classical.bexists_not_of_not_bforall this in
let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in
have {y | (x, y) ∈ d'} ∈ (nhds x).sets,
from mem_nhds_left hd',
let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in
have {x | (x, y) ∈ d'} ∈ (nhds y).sets,
from mem_nhds_right hd',
let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in
have u ∩ v = ∅, from
eq_empty_of_subset_empty $
take z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩,
have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩,
hxy $ hd'd' this,
⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩
/- totally bounded -/
def totally_bounded (s : set α) : Prop :=
∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d})
lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α}
(hs : totally_bounded s) (hf : ultrafilter f) (h : f ≤ principal s) : cauchy f :=
⟨hf.left, take t ht,
let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in
let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in
have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets,
from f.upwards_sets (le_principal_iff.mp h) hs_union,
have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets,
from mem_of_finite_Union_ultrafilter hf hi this,
let ⟨y, hy, hif⟩ := this in
have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t',
from take ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩,
⟨y, h₁, ht'_symm h₂⟩,
(filter.prod f f).upwards_sets (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩
lemma totally_bounded_iff_filter {s : set α} :
totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) :=
⟨suppose totally_bounded s, take f hf hs,
⟨ultrafilter_of f, ultrafilter_of_le,
cauchy_of_totally_bounded_of_ultrafilter this
(ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩,
assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, take d hd,
classical.by_contradiction $ take hs,
have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}),
by simp [not_exists_iff_forall_not, classical.not_and_iff, not_or_iff_implies] at hs;
assumption,
let
f := ⨅t:{t : set α // finite t}, principal (s - (⋃y∈t.val, {x | (x,y) ∈ d})),
⟨a, ha⟩ := @exists_mem_of_ne_empty α s
(take h, hd_cover finite.empty $ h.symm ▸ empty_subset _)
in
have f ≠ ⊥,
from infi_neq_bot_of_directed ⟨a⟩
(take ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩,
principal_mono.mpr $ diff_right_antimono $ Union_subset_Union $
take t, Union_subset_Union_const or.inl,
principal_mono.mpr $ diff_right_antimono $ Union_subset_Union $
take t, Union_subset_Union_const or.inr⟩)
(take ⟨t, ht⟩, by simp [diff_neq_empty]; exact hd_cover ht),
have f ≤ principal s, from infi_le_of_le ⟨∅, finite.empty⟩ $ by simp; exact subset.refl s,
let
⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this,
⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α d c).mp $ hc₂.right hd
in
have c ≤ principal s, from le_trans ‹c ≤ f› this,
have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this,
let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in
let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in
have m ⊆ ys,
from take y' hy', by dsimp; simp; exact @hmd (y', y) ⟨hy', hym⟩,
have c ≤ principal (s - ys),
from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_insert finite.empty⟩ $ le_refl _,
have (s - ys) ∩ (m ∩ s) ∈ c.sets,
from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›,
have ∅ ∈ c.sets,
from c.upwards_sets this $ take x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm,
hc₂.left $ empty_in_sets_eq_bot.mp this⟩
lemma totally_bounded_iff_ultrafilter {s : set α} :
totally_bounded s ↔ (∀f, ultrafilter f → f ≤ principal s → cauchy f) :=
⟨take hs f, cauchy_of_totally_bounded_of_ultrafilter hs,
take h, totally_bounded_iff_filter.mpr $ take f hf hfs,
have cauchy (ultrafilter_of f),
from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs),
⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩
lemma compact_of_totally_bounded_complete {s : set α}
(ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) :
compact s :=
begin
rw [compact_iff_ultrafilter_le_nhds],
rw [totally_bounded_iff_ultrafilter] at ht,
exact take f hf hfs, hc (ht _ hf hfs) hfs
end
/- complete space -/
class complete_space (α : Type u) [uniform_space α] : Prop :=
(complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x)
lemma complete_of_closed [complete_space α] {s : set α} {f : filter α}
(h : closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x :=
let ⟨x, hx⟩ := complete_space.complete hf in
have x ∈ s, from closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $
le_inf hx hfs,
⟨x, this, hx⟩
lemma compact_of_totally_bounded_closed [complete_space α] {s : set α}
(ht : totally_bounded s) (hc : closed s) : compact s :=
@compact_of_totally_bounded_complete α _ s ht $ take f, complete_of_closed hc
lemma complete_space_extension [uniform_space β] {m : β → α}
(hm : uniform_embedding m)
(dense : ∀x, x ∈ closure (m '' univ))
(h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) :
complete_space α :=
⟨take (f : filter α), assume hf : cauchy f,
let
p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s},
g := uniformity.lift (λs, f^.lift' (p s))
in
have mp₀ : monotone p,
from take a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩,
have mp₁ : ∀{s}, monotone (p s),
from take s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩,
have f ≤ g, from
le_infi $ take s, le_infi $ take hs, le_infi $ take t, le_infi $ take ht,
le_principal_iff.mpr $
f.upwards_sets ht $ take x hx, ⟨x, hx, refl_mem_uniformity hs⟩,
have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this,
have vmap m g ≠ ⊥, from vmap_neq_bot $ take t ht,
let ⟨t', ht', ht_mem⟩ := (mem_lift_iff $ monotone_lift' monotone_const mp₀).mp ht in
let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_iff mp₁).mp ht_mem in
let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in
have h₀ : nhds x ⊓ principal (m '' univ) ≠ ⊥,
by simp [closure_eq_nhds] at dense; exact dense x,
have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (m '' univ)).sets,
from @mem_inf_sets_of_left α (nhds x) (principal (m '' univ)) _ $ mem_nhds_left ht',
have h₂ : m '' univ ∈ (nhds x ⊓ principal (m '' univ)).sets,
from @mem_inf_sets_of_right α (nhds x) (principal (m '' univ)) _ $ subset.refl _,
have {y | (x, y) ∈ t'} ∩ m '' univ ∈ (nhds x ⊓ principal (m '' univ)).sets,
from @inter_mem_sets α (nhds x ⊓ principal (m '' univ)) _ _ h₁ h₂,
let ⟨y, xyt', b, _, b_eq⟩ := inhabited_of_mem_sets h₀ this in
⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩,
have cauchy g, from
⟨‹g ≠ ⊥›, take s hs,
let
⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs,
⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁,
⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂)
in
have hg₁ : p (vimage prod.swap s₁) t ∈ g.sets,
from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht,
have hg₂ : p s₂ t ∈ g.sets,
from mem_lift hs₂ $ @mem_lift' α α f _ t ht,
have hg : set.prod (p (vimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets,
from @prod_mem_prod α α _ _ g g hg₁ hg₂,
(filter.prod g g).upwards_sets hg
(take ⟨a, b⟩ ⟨⟨c₁, c₁t, (hc₁ : (a, c₁) ∈ s₁)⟩, ⟨c₂, c₂t, (hc₂ : (c₂, b) ∈ s₂)⟩⟩,
have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩,
comp_s₁ $ prod_mk_mem_comp_rel hc₁ $
comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩,
have cauchy (filter.vmap m g),
from cauchy_vmap (le_of_eq hm.right) ‹cauchy g› (by assumption),
let ⟨x, (hx : map m (filter.vmap m g) ≤ nhds x)⟩ := h _ this in
have map m (filter.vmap m g) ⊓ nhds x ≠ ⊥,
from (le_nhds_iff_adhp_of_cauchy (cauchy_map (uniform_continuous_of_embedding hm) this)).mp hx,
have g ⊓ nhds x ≠ ⊥,
from neq_bot_of_le_neq_bot this (inf_le_inf (take s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)),
⟨x, calc f ≤ g : by assumption
... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩
/- separation space -/
section separation_space
local attribute [instance] separation_setoid
instance : uniform_space (quotient (separation_setoid α)) :=
{ uniform_space .
uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity,
refl := take s hs ⟨a, b⟩ (h : a = b),
have ∀a:α, (a, a) ∈ vimage (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) s,
from take a, refl_mem_uniformity hs,
h ▸ quotient.induction_on a this,
symm :=
have prod.swap ∘ (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) =
(λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ prod.swap,
from funext $ take ⟨a, b⟩, rfl,
calc (map prod.swap ∘ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧))) uniformity =
(map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) ∘ map prod.swap) uniformity : by simp [map_compose, this]
... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono symm_le_uniformity,
comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) =
uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) :
map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id
... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) :
lift'_mono' $ take s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩,
begin
simp at a_eq,
simp at b_eq,
assert h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] },
note h : (a₂, b₁) ∈ separation_rel α := quotient.exact h,
simp [function.comp, set.image, comp_rel],
exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩
end
... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) :
by rw [map_lift'_eq];
exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id)
... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity :
map_mono comp_le_uniformity3 }
lemma uniform_continuous_quotient_mk :
uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) :=
le_refl _
lemma vmap_quotient_le_uniformity : vmap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity ≤ uniformity :=
take t' ht',
let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in
let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in
⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s,
(@uniformity α _).upwards_sets hs $ take x hx, ⟨x, hx, rfl⟩,
take ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩,
have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq,
have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this,
have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht,
have ba₂ : (b₂, a₂) ∈ s, from this.right s hs,
tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁,
ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩
lemma complete_space_separation [h : complete_space α] :
complete_space (quotient (separation_setoid α)) :=
⟨take f, assume hf : cauchy f,
have cauchy (vmap (λx, ⟦x⟧) f), from
cauchy_vmap vmap_quotient_le_uniformity hf $
vmap_neq_bot_of_surj hf.left $ take b, quotient.exists_rep _,
let ⟨x, (hx : vmap (λx, ⟦x⟧) f ≤ nhds x)⟩ := complete_space.complete this in
⟨⟦x⟧, calc f ≤ map (λx, ⟦x⟧) (vmap (λx, ⟦x⟧) f) : le_map_vmap $ take b, quotient.exists_rep _
... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx
... ≤ _ : continuous_iff_towards.mp (continuous_of_uniform uniform_continuous_quotient_mk) _⟩⟩
end separation_space
noncomputable def uniformly_extend [uniform_space γ] [nonempty γ]
(emb : β → α) (f : β → γ) (a : α) : γ :=
classical.epsilon $ λc, map f (vmap emb (nhds a)) ≤ nhds c
section uniform_extension
variables
[uniform_space β]
[uniform_space γ]
{e : β → α}
(h_e : uniform_embedding e)
(h_dense : ∀x, x ∈ closure (e '' univ))
{f : β → γ}
(h_f : uniform_continuous f)
local notation `ψ` := uniformly_extend e f
include h_dense h_e
private lemma vmap_e_neq_empty {a : α} : vmap e (nhds a) ≠ ⊥ :=
forall_sets_neq_empty_iff_neq_bot.mp $
have neq_bot : nhds a ⊓ principal (e '' univ) ≠ ⊥,
by simp [closure_eq_nhds] at h_dense; exact h_dense a,
take s ⟨t, ht, (hs : vimage e t ⊆ s)⟩,
have h₁ : t ∈ (nhds a ⊓ principal (e '' univ)).sets,
from @mem_inf_sets_of_left α (nhds a) (principal (e '' univ)) t ht,
have h₂ : e '' univ ∈ (nhds a ⊓ principal (e '' univ)).sets,
from @mem_inf_sets_of_right α (nhds a) (principal (e '' univ)) _ $ subset.refl _,
have t ∩ e '' univ ∈ (nhds a ⊓ principal (e '' univ)).sets,
from @inter_mem_sets α (nhds a ⊓ principal (e '' univ)) _ _ h₁ h₂,
let ⟨x, ⟨hx₁, y, hy, y_eq⟩⟩ := inhabited_of_mem_sets neq_bot this in
ne_empty_of_mem $ hs $ show e y ∈ t, from y_eq.symm ▸ hx₁
include h_f
lemma uniformly_extend_spec [nonempty γ] [complete_space γ] {a : α} :
map f (vmap e (nhds a)) ≤ nhds (ψ a) :=
have cauchy (nhds a), from cauchy_nhds,
have cauchy (vmap e (nhds a)), from
cauchy_vmap (le_of_eq h_e.right) this $ vmap_e_neq_empty h_e h_dense,
have cauchy (map f (vmap e (nhds a))), from
cauchy_map h_f this,
have ∃c, map f (vmap e (nhds a)) ≤ nhds c,
from complete_space.complete this,
classical.epsilon_spec this
lemma uniformly_extend_unique [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] {a : α} {c : γ}
(h : map f (vmap e (nhds a)) ≤ nhds c) : ψ a = c :=
have map f (vmap e (nhds a)) ≤ nhds (ψ a) ⊓ nhds c,
from le_inf (@uniformly_extend_spec α β γ _ _ _ _ h_e h_dense f h_f _ cγ a) h,
-- why does the elaborator not find cγ?
have nhds (uniformly_extend e f a) ⊓ nhds c ≠ ⊥,
from neq_bot_of_le_neq_bot (by simp [map_eq_bot_iff]; exact vmap_e_neq_empty h_e h_dense) this,
@eq_of_nhds_neq_bot _ _ (@separated_t2 _ _ sγ) _ _ this
lemma uniformly_extend_of_emb [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] {b : β} :
ψ (e b) = f b :=
@uniformly_extend_unique α β γ _ _ _ e h_e h_dense f h_f _ cγ sγ (e b) (f b) $
have vmap e (nhds (e b)) ≤ nhds b,
begin
simp [nhds_eq_uniformity],
rw [vmap_lift'_eq],
simp [vimage, function.comp],
rw [-h_e.right],
rw [vmap_lift'_eq2],
exact le_refl _,
exact monotone_vimage,
exact monotone_vimage
end,
calc map f (vmap e (nhds (e b))) ≤ map f (nhds b) : map_mono this
... ≤ nhds (f b) : continuous_iff_towards.mp (continuous_of_uniform h_f) b
lemma uniform_continuous_uniformly_extend [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] :
uniform_continuous ψ :=
take d hd,
let ⟨s, hs, (hs_comp : comp_rel s (comp_rel s s) ⊆ d)⟩ := (mem_lift'_iff $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in
have vimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets,
from h_f hs,
have vimage (λp:β×β, (f p.1, f p.2)) s ∈ (vmap (λx:β×β, (e x.1, e x.2)) uniformity).sets,
by rw [h_e.right.symm] at this; assumption,
let ⟨t, ht, (ts : ∀p:(β×β), (e p.1, e p.2) ∈ t → (f p.1, f p.2) ∈ s)⟩ := this in
show vimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from
(@uniformity α _).upwards_sets (interior_mem_uniformity ht) $
take ⟨x₁, x₂⟩ hx_t,
have nhds (x₁, x₂) ≤ principal (interior t),
from open_iff_nhds.mp open_interior (x₁, x₂) hx_t,
have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets,
by rw [nhds_prod_eq, le_principal_iff] at this; assumption,
let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in
have nb : ∀{x}, map f (vmap e (nhds x)) ≠ ⊥,
from take x hx, by rw [map_eq_bot_iff] at hx; exact vmap_e_neq_empty h_e h_dense hx,
have (f '' vimage e m₁) ∩ {y | (ψ x₁, y) ∈ s } ∈ (map f (vmap e (nhds x₁))).sets,
from inter_mem_sets (image_mem_map $ vimage_mem_vmap $ hm₁)
(uniformly_extend_spec h_e h_dense h_f $ mem_nhds_left hs),
let ⟨a, ha₁, ha₂⟩ := inhabited_of_mem_sets nb this in
have (f '' vimage e m₂) ∩ {x | (x, ψ x₂) ∈ s } ∈ (map f (vmap e (nhds x₂))).sets,
from inter_mem_sets (image_mem_map $ vimage_mem_vmap $ hm₂)
(uniformly_extend_spec h_e h_dense h_f $ mem_nhds_right hs),
let ⟨b, hb₁, hb₂⟩ := inhabited_of_mem_sets nb this in
have set.prod (vimage e m₁) (vimage e m₂) ⊆ vimage (λp:(β×β), (f p.1, f p.2)) s,
from calc vimage (λp:(β×β), (e p.1, e p.2)) (set.prod m₁ m₂) ⊆ vimage (λp:(β×β), (e p.1, e p.2)) (interior t) :
vimage_mono hm
... ⊆ vimage (λp:(β×β), (e p.1, e p.2)) t : vimage_mono interior_subset
... ⊆ vimage (λp:(β×β), (f p.1, f p.2)) s : ts,
have set.prod (f '' vimage e m₁) (f '' vimage e m₂) ⊆ s,
from calc set.prod (f '' vimage e m₁) (f '' vimage e m₂) =
(λp:(β×β), (f p.1, f p.2)) '' (set.prod (vimage e m₁) (vimage e m₂)) : prod_image_image_eq
... ⊆ (λp:(β×β), (f p.1, f p.2)) '' vimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this
... ⊆ s : image_subset_iff_subset_vimage.mpr $ subset.refl _,
have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩,
hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s),
from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩
end uniform_extension
end uniform_space
end
/-- Space of Cauchy filters
This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters.
This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all
entourages) is necessary for this.
-/
def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f }
namespace Cauchy
section
parameters {α : Type u} [uniform_space α]
def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) :=
{p | s ∈ (filter.prod (p.1^.val) (p.2^.val))^.sets }
lemma monotone_gen : monotone gen :=
monotone_set_of $ take p, @monotone_mem_sets (α×α) (filter.prod (p.1^.val) (p.2^.val))
private lemma symm_gen : map prod.swap (uniformity^.lift' gen) ≤ uniformity^.lift' gen :=
calc map prod.swap (uniformity^.lift' gen) =
uniformity^.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2^.val) (p.1^.val))^.sets }) :
begin
delta gen,
simp [map_lift'_eq, monotone_set_of, monotone_mem_sets,
function.comp, image_swap_eq_vimage_swap]
end
... ≤ uniformity^.lift' gen :
uniformity_lift_le_swap
(monotone_comp (monotone_set_of $ take p,
@monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal)
begin
note h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val),
simp [function.comp, h],
exact le_refl _
end
private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆
(gen (comp_rel s t) : set (Cauchy α × Cauchy α)) :=
take ⟨f, g⟩ ⟨h, h₁, h₂⟩,
let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ :=
mem_prod_iff^.mp h₁ in
let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ :=
mem_prod_iff^.mp h₂ in
have t₂ ∩ t₃ ∈ h.val.sets,
from inter_mem_sets ht₂ ht₃,
let ⟨x, xt₂, xt₃⟩ :=
inhabited_of_mem_sets (h.property.left) this in
(filter.prod f^.val g^.val).upwards_sets
(prod_mem_prod ht₁ ht₄)
(take ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩,
⟨x,
h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩),
h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩)
private lemma comp_gen :
(uniformity^.lift' gen)^.lift' (λs, comp_rel s s) ≤ uniformity^.lift' gen :=
calc (uniformity^.lift' gen)^.lift' (λs, comp_rel s s) =
uniformity^.lift' (λs, comp_rel (gen s) (gen s)) :
begin
rw [lift'_lift'_assoc],
exact monotone_gen,
exact (monotone_comp_rel monotone_id monotone_id)
end
... ≤ uniformity^.lift' (λs, gen $ comp_rel s s) :
lift'_mono' $ take s hs, comp_rel_gen_gen_subset_gen_comp_rel
... = (uniformity^.lift' $ λs:set(α×α), comp_rel s s)^.lift' gen :
begin
rw [lift'_lift'_assoc],
exact (monotone_comp_rel monotone_id monotone_id),
exact monotone_gen
end
... ≤ uniformity^.lift' gen : lift'_mono comp_le_uniformity (le_refl _)
instance completion_space : uniform_space (Cauchy α) :=
{ uniformity := uniformity^.lift' gen,
refl := principal_le_lift' $ take s hs ⟨a, b⟩ (a_eq_b : a = b),
a_eq_b ▸ a^.property^.right hs,
symm := symm_gen,
comp := comp_gen }
def pure_cauchy (a : α) : Cauchy α :=
⟨pure a, cauchy_pure⟩
lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) :=
⟨take a₁ a₂ h,
have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h,
have {a₁} = ({a₂} : set α),
from principal_eq_iff_eq.mp this,
by simp at this; assumption,
have (vimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id,
from funext $ take s, set.ext $ take ⟨a₁, a₂⟩,
by simp [vimage, gen, pure_cauchy, prod_principal_principal],
calc vmap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity^.lift' gen) =
uniformity^.lift' (vimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) :
vmap_lift'_eq monotone_gen
... = uniformity : by simp [this]⟩
lemma pure_cauchy_dense : ∀x, x ∈ closure (pure_cauchy '' univ) :=
take f,
have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from
take s hs,
let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_iff monotone_gen).mp hs in
let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in
have t' ∈ (filter.prod (f.val) (f.val)).sets,
from f.property.right ht'₁,
let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in
let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in
have t'' ∈ (filter.prod f.val (pure x)).sets,
from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'},
take y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end,
take ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩,
ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩,
⟨x, ht''₂ $ by dsimp [gen]; exact this⟩,
begin
simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq],
exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_vimage).mpr
(take s hs,
let ⟨y, hy⟩ := h_ex s hs in
have pure_cauchy y ∈ pure_cauchy '' univ ∩ {y : Cauchy α | (f, y) ∈ s},
from ⟨mem_image_of_mem _ $ mem_univ y, hy⟩,
ne_empty_of_mem this)
end
instance : complete_space (Cauchy α) :=
complete_space_extension
uniform_embedding_pure_cauchy
pure_cauchy_dense $
take f hf,
let f' : Cauchy α := ⟨f, hf⟩ in
have map pure_cauchy f ≤ uniformity.lift' (vimage (prod.mk f')),
from le_lift' $ take s hs,
let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_iff monotone_gen).mp hs in
let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in
have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t },
from take x hx, (filter.prod f (pure x)).upwards_sets (prod_mem_prod ht' $ mem_pure hx) h,
f.upwards_sets ht' $ subset.trans this (vimage_mono ht₂),
⟨f', by simp [nhds_eq_uniformity]; assumption⟩
end
end Cauchy
section constructions
variables {α : Type u} {β : Type v}
instance : weak_order (uniform_space α) :=
{ weak_order .
le := λt s, s^.uniformity ≤ t^.uniformity,
le_antisymm := take t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁,
le_refl := take t, le_refl _,
le_trans := take a b c h₁ h₂, @le_trans _ _ c^.uniformity b^.uniformity a^.uniformity h₂ h₁ }
instance : has_Sup (uniform_space α) :=
⟨take s, {
uniformity := (⨅u∈s, @uniformity α u),
refl := le_infi $ take u, le_infi $ take hu, u.refl,
symm := le_infi $ take u, le_infi $ take hu,
le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm,
comp := le_infi $ take u, le_infi $ take hu,
le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩
private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) :
t ≤ Sup tt :=
show (⨅u∈tt, @uniformity α u) ≤ t.uniformity,
from infi_le_of_le t $ infi_le _ h
private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) :
Sup tt ≤ t :=
show t.uniformity ≤ (⨅u∈tt, @uniformity α u),
from le_infi $ take t', le_infi $ take ht', h t' ht'
instance : has_bot (uniform_space α) :=
⟨{ uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩
instance : has_top (uniform_space α) :=
⟨{ uniformity := principal id_rel,
refl := le_refl _,
symm := by simp; apply subset.refl,
comp :=
begin
rw [lift'_principal],
{ simp, apply subset.refl },
exact monotone_comp_rel monotone_id monotone_id
end}⟩
instance : complete_lattice (uniform_space α) :=
{ uniform_space.weak_order with
sup := λa b, Sup {a, b},
le_sup_left := take a b, le_Sup $ by simp,
le_sup_right := take a b, le_Sup $ by simp,
sup_le := take a b c h₁ h₂, Sup_le $ take t',
begin simp, intro h, cases h with h h, repeat { subst h; assumption } end,
inf := λa b, Sup {x | x ≤ a ∧ x ≤ b},
le_inf := take a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩,
inf_le_left := take a b, Sup_le $ take x ⟨ha, hb⟩, ha,
inf_le_right := take a b, Sup_le $ take x ⟨ha, hb⟩, hb,
top := top,
le_top := take u, u.refl,
bot := bot,
bot_le := take a, show a.uniformity ≤ ⊤, from le_top,
Sup := Sup,
le_Sup := take s u, le_Sup,
Sup_le := take s u, Sup_le,
Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'},
le_Inf := take s a hs, le_Sup hs,
Inf_le := take s a ha, Sup_le $ take u hs, hs _ ha }
instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩
def uniform_space.vmap (f : α → β) (u : uniform_space β) : uniform_space α :=
{ uniformity := u.uniformity.vmap (λp:α×α, (f p.1, f p.2)),
refl := le_trans (by simp; exact take ⟨a, b⟩ (h : a = b), h ▸ rfl) (vmap_mono u.refl),
symm := le_trans
(by simp [map_swap_vmap_swap_eq, vmap_vmap_comp, function.comp]; exact le_refl _)
(vmap_mono u.symm),
comp := le_trans
begin
rw [vmap_lift'_eq, vmap_lift'_eq2],
exact (lift'_mono' $ take s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩),
repeat { exact monotone_comp_rel monotone_id monotone_id }
end
(vmap_mono u.comp) }
lemma uniform_continuous_vmap {f : α → β} {u : uniform_space β} :
@uniform_continuous α β (uniform_space.vmap f u) u f :=
map_vmap_le
lemma to_topological_space_vmap {f : α → β} {u : uniform_space β} :
(uniform_space.vmap f u).to_topological_space = topological_space.induced f u.to_topological_space :=
eq_of_nhds_eq_nhds $ take a,
begin
simp [nhds_induced_eq_vmap, nhds_eq_uniformity, nhds_eq_uniformity],
show vmap f (uniformity.lift' (vimage (λb, (f a, b)))) =
(u.uniformity.vmap (λp:α×α, (f p.1, f p.2))).lift' (vimage (λa', (a, a'))),
by rw [vmap_lift'_eq monotone_vimage, vmap_lift'_eq2 monotone_vimage]; exact rfl
end
instance : uniform_space empty := ⊤
instance : uniform_space unit := ⊤
instance : uniform_space bool := ⊤
instance : uniform_space ℕ := ⊤
instance : uniform_space ℤ := ⊤
instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) :=
uniform_space.vmap subtype.val t
instance [t₁ : uniform_space α] [t₂ : uniform_space β] : uniform_space (α × β) :=
uniform_space.vmap prod.fst t₁ ⊔ uniform_space.vmap prod.snd t₂
/- a similar product space is possible on the function space (uniformity of pointwise convergence),
but we want to have the uniformity of uniform convergence on function spaces -/
lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) :
u₁.to_topological_space ≤ u₂.to_topological_space :=
le_of_nhds_le_nhds $ take a,
by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _)
lemma supr_uniformity {ι : Sort v} {u : ι → uniform_space α} :
(supr u).uniformity = (⨅i, (u i).uniformity) :=
show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from
le_antisymm
(le_infi $ take i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩)
(le_infi $ take a, le_infi $ take ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _)
lemma to_topological_space_top : (⊤ : uniform_space α).to_topological_space = ⊤ :=
top_unique $ take s hs x hx ⟨a₁, a₂⟩ (h₁ : a₁ = a₂) (h₂ : a₁ = x),
h₁ ▸ h₂.symm ▸ hx
lemma to_topological_space_bot : (⊥ : uniform_space α).to_topological_space = ⊥ :=
bot_unique $ take s hs, classical.by_cases
(suppose s = ∅, this.symm ▸ @open_empty _ ⊥)
(suppose s ≠ ∅,
let ⟨x, hx⟩ := exists_mem_of_ne_empty this in
have univ ⊆ _,
from hs x hx,
have s = univ,
from top_unique $ take y hy, @this (x, y) ⟨⟩ rfl,
this.symm ▸ @open_univ _ ⊥)
lemma to_topological_space_supr {ι : Sort v} {u : ι → uniform_space α} :
(supr u).to_topological_space = (⨆i, (u i).to_topological_space) :=
classical.by_cases
(assume h : nonempty ι,
eq_of_nhds_eq_nhds $ take a,
begin
rw [nhds_supr, nhds_eq_uniformity],
show _ = (supr u).uniformity.lift' (vimage $ prod.mk a),
begin
rw [supr_uniformity, lift'_infi],
exact (congr_arg _ $ funext $ take i, @nhds_eq_uniformity α (u i) a),
exact h,
exact take a b, rfl
end
end)
(suppose ¬ nonempty ι,
le_antisymm
(have supr u = bot, from bot_unique $ supr_le $ take i, (this ⟨i⟩).elim,
have (supr u).to_topological_space = bot,
from this.symm ▸ to_topological_space_bot,
this.symm ▸ bot_le)
(supr_le $ take i, to_topological_space_mono $ le_supr _ _))
end constructions
|
80e7c1aa6803b3a72144cee785360b7d5bc45916 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch4/ex0305.lean | 8e349af646bf0d487932d9eb6e6072db2c2f15ba | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 318 | lean | variables (a b c d e : ℕ)
variable h1 : a = b
variable h2 : b = c + 1
variable h3 : c = d
variable h4 : e = 1 + d
include h1 h2 h3 h4
theorem T : a = e :=
by simp [h1, h2, h3, h4, add_comm]
-- lean 3.6 removes simp attributes from add_comm
-- i.e., now it is required to provide that lemma to solve this theorem.
|
a22203c7c9b25da6b20c3b70e79dc2e810ccd761 | ad0c7d243dc1bd563419e2767ed42fb323d7beea | /linear_algebra/quotient_module.lean | aba46fbdd1d5e47668d67fdf3604f9714bb7a250 | [
"Apache-2.0"
] | permissive | sebzim4500/mathlib | e0b5a63b1655f910dee30badf09bd7e191d3cf30 | 6997cafbd3a7325af5cb318561768c316ceb7757 | refs/heads/master | 1,585,549,958,618 | 1,538,221,723,000 | 1,538,221,723,000 | 150,869,076 | 0 | 0 | Apache-2.0 | 1,538,229,323,000 | 1,538,229,323,000 | null | UTF-8 | Lean | false | false | 6,949 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Quotient construction on modules
-/
import linear_algebra.basic
import linear_algebra.prod_module
import linear_algebra.subtype_module
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
variables [ring α] [module α β] [module α γ] (s : set β) [is_submodule s]
include α
open function
namespace is_submodule
def quotient_rel : setoid β :=
⟨λb₁ b₂, b₁ - b₂ ∈ s,
assume b, by simp [zero],
assume b₁ b₂ hb,
have - (b₁ - b₂) ∈ s, from is_submodule.neg hb,
by simpa using this,
assume b₁ b₂ b₃ hb₁₂ hb₂₃,
have (b₁ - b₂) + (b₂ - b₃) ∈ s, from add hb₁₂ hb₂₃,
by simpa using this⟩
end is_submodule
namespace quotient_module
open is_submodule
section
variable (β)
/-- Quotient module. `quotient β s` is the quotient of the module `β` by the submodule `s`. -/
def quotient (s : set β) [is_submodule s] : Type v := quotient (quotient_rel s)
end
local notation ` Q ` := quotient β s
def mk {s : set β} [is_submodule s] : β → quotient β s := quotient.mk'
instance {α} {β} {r : ring α} [module α β] (s : set β) [is_submodule s] : has_coe β (quotient β s) := ⟨mk⟩
protected def eq {s : set β} [is_submodule s] {a b : β} : (a : quotient β s) = b ↔ a - b ∈ s :=
quotient.eq'
instance quotient.has_zero : has_zero Q := ⟨mk 0⟩
instance quotient.has_add : has_add Q :=
⟨λa b, quotient.lift_on₂' a b (λa b, ((a + b : β ) : Q)) $
assume a₁ a₂ b₁ b₂ (h₁ : a₁ - b₁ ∈ s) (h₂ : a₂ - b₂ ∈ s),
quotient.sound' $
have (a₁ - b₁) + (a₂ - b₂) ∈ s, from add h₁ h₂,
show (a₁ + a₂) - (b₁ + b₂) ∈ s, by simpa⟩
instance quotient.has_neg : has_neg Q :=
⟨λa, quotient.lift_on' a (λa, mk (- a)) $ assume a b (h : a - b ∈ s),
quotient.sound' $
have - (a - b) ∈ s, from neg h,
show (-a) - (-b) ∈ s, by simpa⟩
instance quotient.add_comm_group : add_comm_group Q :=
{ zero := 0,
add := (+),
neg := has_neg.neg,
add_assoc := assume a b c, quotient.induction_on₃' a b c $
assume a b c, quotient_module.eq.2 $
by simp [is_submodule.zero],
add_comm := assume a b, quotient.induction_on₂' a b $
assume a b, quotient_module.eq.2 $ by simp [is_submodule.zero],
add_zero := assume a, quotient.induction_on' a $
assume a, quotient_module.eq.2 $ by simp [is_submodule.zero],
zero_add := assume a, quotient.induction_on' a $
assume a, quotient_module.eq.2 $ by simp [is_submodule.zero],
add_left_neg := assume a, quotient.induction_on' a $
assume a, quotient_module.eq.2 $ by simp [is_submodule.zero] }
instance quotient.has_scalar : has_scalar α Q :=
⟨λa b, quotient.lift_on' b (λb, ((a • b : β) : Q)) $ assume b₁ b₂ (h : b₁ - b₂ ∈ s),
quotient.sound' $
have a • (b₁ - b₂) ∈ s, from is_submodule.smul a h,
show a • b₁ - a • b₂ ∈ s, by simpa [smul_add]⟩
instance quotient.module : module α Q :=
{ smul := (•),
one_smul := assume a, quotient.induction_on' a $
assume a, quotient_module.eq.2 $ by simp [is_submodule.zero],
mul_smul := assume a b c, quotient.induction_on' c $
assume c, quotient_module.eq.2 $ by simp [is_submodule.zero, mul_smul],
smul_add := assume a b c, quotient.induction_on₂' b c $
assume b c, quotient_module.eq.2 $ by simp [is_submodule.zero, smul_add],
add_smul := assume a b c, quotient.induction_on' c $
assume c, quotient_module.eq.2 $ by simp [is_submodule.zero, add_smul], }
@[simp] lemma coe_zero : ((0 : β) : Q) = 0 := rfl
@[simp] lemma coe_smul (a : α) (b : β) : ((a • b : β) : Q) = a • b := rfl
@[simp] lemma coe_add (a b : β) : ((a + b : β) : Q) = a + b := rfl
lemma coe_eq_zero (b : β) : (b : quotient β s) = 0 ↔ b ∈ s :=
by rw [← (coe_zero s), quotient_module.eq]; simp
instance quotient.inhabited : inhabited Q := ⟨0⟩
lemma is_linear_map_quotient_mk : @is_linear_map _ _ Q _ _ _ (λb, mk b : β → Q) :=
by refine {..}; intros; refl
def quotient.lift {f : β → γ} (hf : is_linear_map f) (h : ∀x∈s, f x = 0) (b : Q) : γ :=
b.lift_on' f $ assume a b (hab : a - b ∈ s),
have f a - f b = 0, by rw [←hf.sub]; exact h _ hab,
show f a = f b, from eq_of_sub_eq_zero this
@[simp] lemma quotient.lift_mk {f : β → γ} (hf : is_linear_map f) (h : ∀x∈s, f x = 0) (b : β) :
quotient.lift s hf h (b : Q) = f b :=
rfl
lemma is_linear_map_quotient_lift {f : β → γ} {h : ∀x y, x - y ∈ s → f x = f y}
(hf : is_linear_map f) : is_linear_map (λq:Q, quotient.lift_on' q f h) :=
⟨assume b₁ b₂, quotient.induction_on₂' b₁ b₂ $ assume b₁ b₂, hf.add b₁ b₂,
assume a b, quotient.induction_on' b $ assume b, hf.smul a b⟩
lemma quotient.injective_lift [is_submodule s] {f : β → γ} (hf : is_linear_map f)
(hs : s = {x | f x = 0}) : injective (quotient.lift s hf $ le_of_eq hs) :=
assume a b, quotient.induction_on₂' a b $ assume a b (h : f a = f b), quotient.sound' $
have f (a - b) = 0, by rw [hf.sub]; simp [h],
show a - b ∈ s, from hs.symm ▸ this
lemma quotient.exists_rep {s : set β} [is_submodule s] : ∀ q : quotient β s, ∃ b : β, mk b = q :=
@_root_.quotient.exists_rep _ (quotient_rel s)
section vector_space
variables {α' : Type u} {β' : Type v}
variables [field α'] [vector_space α' β'] (s' : set β') [is_submodule s']
omit α
include α'
instance quotient.vector_space : vector_space α' (quotient β' s') := {}
theorem quotient_prod_linear_equiv :
nonempty ((quotient_module.quotient β' s' × s') ≃ₗ β') :=
let ⟨g, H1, H2⟩ := exists_right_inverse_linear_map_of_surjective
(quotient_module.is_linear_map_quotient_mk s')
(quotient_module.quotient.exists_rep) in
have H3 : ∀ b, quotient_module.mk (g b) = b := λ b, congr_fun H2 b,
⟨{ to_fun := λ b, g b.1 + b.2.1,
inv_fun := λ b, (quotient_module.mk b, ⟨b - g (quotient_module.mk b),
(quotient_module.coe_eq_zero _ _).1 $
((quotient_module.is_linear_map_quotient_mk _).sub _ _).trans $
by rw [H3, sub_self]⟩),
left_inv := λ ⟨q, b, h⟩,
have H4 : quotient_module.mk b = 0,
from (quotient_module.coe_eq_zero s' b).2 h,
have H5 : quotient_module.mk (g q + b) = q,
from ((quotient_module.is_linear_map_quotient_mk _).add _ _).trans $
by simp only [H3, H4, add_zero],
prod.ext H5 (subtype.eq $ by simp only [H5, add_sub_cancel']),
right_inv := λ b, add_sub_cancel'_right _ _,
linear_fun := ⟨λ ⟨q1, b1, h1⟩ ⟨q2, b2, h2⟩,
show g (q1 + q2) + (b1 + b2) = (g q1 + b1) + (g q2 + b2),
by rw [H1.add]; simp only [add_left_comm, add_assoc],
λ c ⟨q, b, h⟩, show g (c • q) + (c • b) = c • (g q + b),
by rw [H1.smul, smul_add]⟩ }⟩
end vector_space
end quotient_module
|
3ece99753aad97c7f6b5214dd5f73b461c4d5d34 | 205f0fc16279a69ea36e9fd158e3a97b06834ce2 | /src/12_Sets/01_sets_as_functions.lean | c05c4066305ccf823d718f67a5c1d5346fe29d25 | [] | no_license | kevinsullivan/cs-dm-lean | b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124 | a06a94e98be77170ca1df486c8189338b16cf6c6 | refs/heads/master | 1,585,948,743,595 | 1,544,339,346,000 | 1,544,339,346,000 | 155,570,767 | 1 | 3 | null | 1,541,540,372,000 | 1,540,995,993,000 | Lean | UTF-8 | Lean | false | false | 4,749 | lean |
/-
What are sets?
In many programming languages, sets are unordered
containers of unique items
{3, 1, 2} and {1, 2, 3} are the same set
{1, 1, 2, 3} is not a set
In Lean, to create a set, you need to first specify
what type is contained in the set (in Lean, a set
cannot contain elements of different types)
A set of naturals (set ℕ) is a map from the naturals
to a proposition. The proposition is whether a natural
number is an element of the set
-/
/-
What are functions?
Functions take one or more inputs and provide one or
more outputs. Technically, functions can take zero inputs
(constant functions), and in some contexts, functions can
have no outputs. Multiple outputs can be combined together
as a single output that is a tuple.
Functions have domains (valid input values) and ranges
(valid output values) and map values in the domain into
values in the range
In Lean, a function that takes inputs of type α and β and
returns an outputs of type γ and δ would have the type:
α → β → γ × δ
-/
namespace function_example
variables α β γ δ: Type
variable my_fn: α → β → γ × δ
end function_example
/-
Exercise
What is the domain for your basic (i.e., one that does
not produce imaginary numbers) square root function?
What is the domain for your basic division function?
-/
/-
What are predicates?
Predicates are functions that return a proposition
E.g., α → β → Prop
Alternatively, predicates are propositions with parameters
E.g., fromCharlottesville(p: Person): Prop := …
E.g., onSegment(s: Segment)(p: Point): Prop := …
Note that in Lean, predicates have a return type of
Prop and not bool. In other languages (e.g., PVS), this
distinction is not meaningful.
-/
/-
How sets can represent predicates
There are two ways that sets can represent predicates
1. The set could have the same domain as the predicate.
Membership in the set would indicate a true proposition.
Non-membership in the set represents a false proposition.
2. The set could follow the same convention as for other
functions… (discussed below)
-/
namespace predicate_set_example
variables α β: Type
-- Predicate my_pred
variable my_pred(a: α)(b: β): Prop
-- Set my_set
def my_set: set (α × β) :=
{tuple | my_pred tuple.1 tuple.2}
end predicate_set_example
/-
How sets can represent functions
Consider a function taking a single natural number that is
only valid over the inputs 1, 2, and 3 (its domain) and
that returns a value that is one greater than its input
(so its range is 2, 3, and 4)
We can represent this as this set of tuples:
{(1, 2), (2, 3), (3, 4)}
-/
/-
Exercise
Represent the following functions as sets:
-/
namespace function_set_exercise
def fn1(n: ℕ) := n + 1
def fn2(n: ℕ)(m: ℕ) :=
n / m
#reduce 2 / 0
#reduce fn2 2 0
def fn3(n: ℕ)(m: {a: ℕ // a ≠ 0}) :=
n / m
-- #reduce fn3 2 0
variables n d : ℕ
-- #check fn3 n d
end function_set_exercise
/-
Solution
-/
namespace function_set_solution
def fn1(n: ℕ) := n + 1
def fn2(n: ℕ)(m: ℕ) :=
n / m
def fn3(n: ℕ)(m: {a: ℕ // a ≠ 0}) :=
n / m
def set1: set (ℕ × ℕ) :=
{tuple | tuple.2 = tuple.1 + 1}
def set1': set (ℕ × ℕ) :=
{tuple | tuple.2 = fn1 tuple.1}
example: set1 = set1' := rfl
def my_tuple := (1, 2, 3)
#check my_tuple
#reduce my_tuple.2
def my_tuple' := ((1, 2), 3)
#check my_tuple'
#reduce my_tuple'.1
#reduce my_tuple'.2
def set2: set (ℕ × ℕ × ℕ) :=
{tuple | tuple.2.2 = tuple.1 / tuple.2.1}
def set3: set (ℕ × {a: ℕ // a ≠ 0} × ℕ) :=
{tuple | tuple.2.2 = tuple.1 / tuple.2.1}
end function_set_solution
/-
Exercise
Represent the following functions as a set
-/
namespace function_set_exercise2
variable fn1: ℕ → ℕ
variable fn2: ℕ → ℕ → ℕ
variable fn3: ℕ → ℕ → (ℕ × ℕ)
end function_set_exercise2
/-
Solution
-/
namespace function_set_solution2
variable fn1: ℕ → ℕ
def set1: set (ℕ × ℕ) :=
{tuple | tuple.2 = fn1 tuple.1}
variable fn2: ℕ → ℕ → ℕ
def set2: set (ℕ × ℕ × ℕ) :=
{tuple | tuple.2.2 = fn2 tuple.1 tuple.2.1}
variable fn3: ℕ → ℕ → (ℕ × ℕ)
def set3: set (ℕ × ℕ × (ℕ × ℕ)) :=
{tuple | (tuple.2.2.1, tuple.2.2.2) =
fn3 tuple.1 tuple.2.1}
def set3': set (ℕ × ℕ × ℕ × ℕ) :=
{tuple | (tuple.2.2.1, tuple.2.2.2) =
fn3 tuple.1 tuple.2.1}
example: set3 = set3' := rfl
def tuple3 := (1, 2, 3, 4)
#reduce tuple3.1
#reduce tuple3.2
#reduce tuple3.2.1
#reduce tuple3.2.2
#reduce tuple3.2.2.1
#reduce tuple3.2.2.2
end function_set_solution2 |
4d13511858a93201efeab13e868d4bb3ba48dd85 | bb31430994044506fa42fd667e2d556327e18dfe | /src/group_theory/presented_group.lean | fcd3117a13e301089af44d57a7ec498e9a6db278 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 3,082 | lean | /-
Copyright (c) 2019 Michael Howes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Howes
-/
import group_theory.free_group
import group_theory.quotient_group
/-!
# Defining a group given by generators and relations
Given a subset `rels` of relations of the free group on a type `α`, this file constructs the group
given by generators `x : α` and relations `r ∈ rels`.
## Main definitions
* `presented_group rels`: the quotient group of the free group on a type `α` by a subset `rels` of
relations of the free group on `α`.
* `of`: The canonical map from `α` to a presented group with generators `α`.
* `to_group f`: the canonical group homomorphism `presented_group rels → G`, given a function
`f : α → G` from a type `α` to a group `G` which satisfies the relations `rels`.
## Tags
generators, relations, group presentations
-/
variables {α : Type*}
/-- Given a set of relations, rels, over a type `α`, presented_group constructs the group with
generators `x : α` and relations `rels` as a quotient of free_group `α`.-/
def presented_group (rels : set (free_group α)) :=
free_group α ⧸ subgroup.normal_closure rels
namespace presented_group
instance (rels : set (free_group α)) : group (presented_group (rels)) :=
quotient_group.quotient.group _
/-- `of` is the canonical map from `α` to a presented group with generators `x : α`. The term `x` is
mapped to the equivalence class of the image of `x` in `free_group α`. -/
def of {rels : set (free_group α)} (x : α) : presented_group rels :=
quotient_group.mk (free_group.of x)
section to_group
/-
Presented groups satisfy a universal property. If `G` is a group and `f : α → G` is a map such that
the images of `f` satisfy all the given relations, then `f` extends uniquely to a group homomorphism
from `presented_group rels` to `G`.
-/
variables {G : Type*} [group G] {f : α → G} {rels : set (free_group α)}
local notation `F` := free_group.lift f
variable (h : ∀ r ∈ rels, F r = 1)
lemma closure_rels_subset_ker : subgroup.normal_closure rels ≤ monoid_hom.ker F :=
subgroup.normal_closure_le_normal (λ x w, (monoid_hom.mem_ker _).2 (h x w))
lemma to_group_eq_one_of_mem_closure : ∀ x ∈ subgroup.normal_closure rels, F x = 1 :=
λ x w, (monoid_hom.mem_ker _).1 $ closure_rels_subset_ker h w
/-- The extension of a map `f : α → G` that satisfies the given relations to a group homomorphism
from `presented_group rels → G`. -/
def to_group : presented_group rels →* G :=
quotient_group.lift (subgroup.normal_closure rels) F (to_group_eq_one_of_mem_closure h)
@[simp] lemma to_group.of {x : α} : to_group h (of x) = f x := free_group.lift.of
theorem to_group.unique (g : presented_group rels →* G)
(hg : ∀ x : α, g (of x) = f x) : ∀ {x}, g x = to_group h x :=
λ x, quotient_group.induction_on x
(λ _, free_group.lift.unique (g.comp (quotient_group.mk' _)) hg)
end to_group
instance (rels : set (free_group α)) : inhabited (presented_group rels) := ⟨1⟩
end presented_group
|
30458b3b2031c9770ebc9d6dd0aea20d85b1cb02 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/run/extmacro.lean | 373017c7ee7638cf9637915803b87906a5e80d93 | [
"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 | 498 | lean | new_frontend
macro ext_tactic t:tactic "=>" newT:tactic : command => `(macro_rules | `($t) => `($newT))
syntax "trivial" : tactic
ext_tactic trivial => apply Eq.refl
theorem tst1 (x : Nat) : x = x :=
begin trivial end
-- theorem tst2 (x y : Nat) (h : x = y) : x = y :=
-- begin trivial end -- fail as expected
ext_tactic trivial => assumption
theorem tst1b (x : Nat) : x = x :=
begin trivial end -- still works
theorem tst2 (x y : Nat) (h : x = y) : x = y :=
begin trivial end -- works too
|
b1248525df57dc01970b1609ca387e592a35383f | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/e15.lean | c28f036608166018be4156cb0b7df9a626d01b67 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 534 | lean | prelude
inductive nat : Type
| zero : nat
| succ : nat → nat
namespace nat end nat open nat
inductive list (A : Sort*)
| nil {} : list
| cons : A → list → list
namespace list end list open list
check nil
check nil.{1}
check @nil.{1} nat
check @nil nat
check cons zero nil
inductive vector (A : Sort*) : nat → Sort*
| vnil {} : vector zero
| vcons : forall {n : nat}, A → vector n → vector (succ n)
namespace vector end vector open vector
check vcons zero vnil
constant n : nat
check vcons n vnil
check vector.rec
|
6de2560bd3817e4207334369ab1e5d562270d86c | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/equiv/fin.lean | 791d8d6f2727716a0e8940b7aaac04ddb5bd5cd8 | [
"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 | 10,242 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import data.fin
import data.equiv.basic
/-!
# Equivalences for `fin n`
-/
universe variables u
variables {m n : ℕ}
/-- Equivalence between `fin 0` and `empty`. -/
def fin_zero_equiv : fin 0 ≃ empty :=
⟨fin_zero_elim, empty.elim, assume a, fin_zero_elim a, assume a, empty.elim a⟩
/-- Equivalence between `fin 0` and `pempty`. -/
def fin_zero_equiv' : fin 0 ≃ pempty.{u} :=
equiv.equiv_pempty fin.elim0
/-- Equivalence between `fin 1` and `punit`. -/
def fin_one_equiv : fin 1 ≃ punit :=
⟨λ_, (), λ_, 0, fin.cases rfl (λa, fin_zero_elim a), assume ⟨⟩, rfl⟩
/-- Equivalence between `fin 2` and `bool`. -/
def fin_two_equiv : fin 2 ≃ bool :=
⟨@fin.cases 1 (λ_, bool) ff (λ_, tt),
λb, cond b 1 0,
begin
refine fin.cases _ _, refl,
refine fin.cases _ _, refl,
exact λi, fin_zero_elim i
end,
assume b, match b with tt := rfl | ff := rfl end⟩
/-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/
def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m :=
equiv.subtype_equiv_right (λ x, by subst h)
@[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) :
fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ :=
rfl
@[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) :
(fin_congr h).symm = fin_congr h.symm := rfl
@[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) :
(fin_congr h k : ℕ) = k :=
by { cases k, refl, }
lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) :
((fin_congr h).symm k : ℕ) = k :=
by { cases k, refl, }
/-- An equivalence that removes `i` and maps it to `none`.
This is a version of `fin.pred_above` that produces `option (fin n)` instead of
mapping both `i.cast_succ` and `i.succ` to `i`. -/
def fin_succ_equiv' {n : ℕ} (i : fin n) :
fin (n + 1) ≃ option (fin n) :=
{ to_fun := λ x, if x = i.cast_succ then none else some (i.pred_above x),
inv_fun := λ x, x.cases_on' i.cast_succ (fin.succ_above i.cast_succ),
left_inv := λ x, if h : x = i.cast_succ then by simp [h]
else by simp [h, fin.succ_above_ne],
right_inv := λ x, by { cases x; simp [fin.succ_above_ne] }}
@[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) :
(fin_succ_equiv' i) i.cast_succ = none := by simp [fin_succ_equiv']
lemma fin_succ_equiv'_below {n : ℕ} {i m : fin (n + 1)} (h : m < i) :
(fin_succ_equiv' i) m.cast_succ = some m :=
begin
have : m.cast_succ ≤ i.cast_succ := h.le,
simp [fin_succ_equiv', h.ne, fin.pred_above_below, this]
end
lemma fin_succ_equiv'_above {n : ℕ} {i m : fin (n + 1)} (h : i ≤ m) :
(fin_succ_equiv' i) m.succ = some m :=
begin
have : i.cast_succ < m.succ,
{ refine (lt_of_le_of_lt _ m.cast_succ_lt_succ), exact h },
simp [fin_succ_equiv', this, fin.pred_above_above, ne_of_gt]
end
@[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) :
(fin_succ_equiv' i).symm none = i.cast_succ := rfl
lemma fin_succ_equiv_symm'_some_below {n : ℕ} {i m : fin (n + 1)} (h : m < i) :
(fin_succ_equiv' i).symm (some m) = m.cast_succ :=
by simp [fin_succ_equiv', ne_of_gt h, fin.succ_above, not_le_of_gt h]
lemma fin_succ_equiv_symm'_some_above {n : ℕ} {i m : fin (n + 1)} (h : i ≤ m) :
(fin_succ_equiv' i).symm (some m) = m.succ :=
by simp [fin_succ_equiv', fin.succ_above, h.not_lt]
lemma fin_succ_equiv_symm'_coe_below {n : ℕ} {i m : fin (n + 1)} (h : m < i) :
(fin_succ_equiv' i).symm m = m.cast_succ :=
by { convert fin_succ_equiv_symm'_some_below h; simp }
lemma fin_succ_equiv_symm'_coe_above {n : ℕ} {i m : fin (n + 1)} (h : i ≤ m) :
(fin_succ_equiv' i).symm m = m.succ :=
by { convert fin_succ_equiv_symm'_some_above h; simp }
/-- Equivalence between `fin (n + 1)` and `option (fin n)`.
This is a version of `fin.pred` that produces `option (fin n)` instead of
requiring a proof that the input is not `0`. -/
-- TODO: make the `n = 0` case neater
def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) :=
nat.cases_on n
{ to_fun := λ _, none,
inv_fun := λ _, 0,
left_inv := λ _, by simp,
right_inv := λ x, by { cases x, simp, exact x.elim0 } }
(λ _, fin_succ_equiv' 0)
@[simp] lemma fin_succ_equiv_zero {n : ℕ} :
(fin_succ_equiv n) 0 = none :=
by cases n; refl
@[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n):
(fin_succ_equiv n) m.succ = some m :=
begin
cases n, { exact m.elim0 },
convert fin_succ_equiv'_above m.zero_le
end
@[simp] lemma fin_succ_equiv_symm_none {n : ℕ} :
(fin_succ_equiv n).symm none = 0 :=
by cases n; refl
@[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) :
(fin_succ_equiv n).symm (some m) = m.succ :=
begin
cases n, { exact m.elim0 },
convert fin_succ_equiv_symm'_some_above m.zero_le
end
@[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) :
(fin_succ_equiv n).symm m = m.succ :=
fin_succ_equiv_symm_some m
/-- The equiv version of `fin.pred_above_zero`. -/
lemma fin_succ_equiv'_zero {n : ℕ} :
fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv (n + 1) := rfl
/-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/
def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) :=
{ to_fun := λ x, sum.rec_on x
(λ y, ⟨y.1, nat.lt_of_lt_of_le y.2 $ nat.le_add_right m n⟩)
(λ y, ⟨m + y.1, nat.add_lt_add_left y.2 m⟩),
inv_fun := λ x, if H : x.1 < m
then sum.inl ⟨x.1, H⟩
else sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $
show m + (x.1 - m) < m + n,
from (nat.add_sub_of_le $ le_of_not_gt H).symm ▸ x.2⟩,
left_inv := λ x, begin
cases x with y y,
{ simp [fin.ext_iff, y.is_lt], },
{ have H : ¬m + y.val < m := not_lt_of_ge (nat.le_add_right _ _),
simp [H, nat.add_sub_cancel_left, fin.ext_iff] }
end,
right_inv := λ x, begin
by_cases H : (x:ℕ) < m,
{ dsimp, rw [dif_pos H], simp },
{ dsimp, rw [dif_neg H], simp [fin.ext_iff, nat.add_sub_of_le (le_of_not_gt H)] }
end }
@[simp] lemma fin_sum_fin_equiv_apply_left (x : fin m) :
@fin_sum_fin_equiv m n (sum.inl x) = ⟨x.1, nat.lt_of_lt_of_le x.2 $ nat.le_add_right m n⟩ :=
rfl
@[simp] lemma fin_sum_fin_equiv_apply_right (x : fin n) :
@fin_sum_fin_equiv m n (sum.inr x) = ⟨m + x.1, nat.add_lt_add_left x.2 m⟩ :=
rfl
@[simp] lemma fin_sum_fin_equiv_symm_apply_left (x : fin (m + n)) (h : ↑x < m) :
fin_sum_fin_equiv.symm x = sum.inl ⟨x.1, h⟩ :=
by simp [fin_sum_fin_equiv, dif_pos h]
@[simp] lemma fin_sum_fin_equiv_symm_apply_right (x : fin (m + n)) (h : m ≤ ↑x) :
fin_sum_fin_equiv.symm x = sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $
show m + (x.1 - m) < m + n, from (nat.add_sub_of_le $ h).symm ▸ x.2⟩ :=
by simp [fin_sum_fin_equiv, dif_neg (not_lt.mpr h)]
/-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/
def fin_add_flip : fin (m + n) ≃ fin (n + m) :=
(fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv
@[simp] lemma fin_add_flip_apply_left {k : ℕ} (h : k < m)
(hk : k < m + n := nat.lt_add_right k m n h)
(hnk : n + k < n + m := add_lt_add_left h n) :
fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ :=
begin
dsimp [fin_add_flip, fin_sum_fin_equiv],
rw [dif_pos h],
refl,
end
@[simp] lemma fin_add_flip_apply_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) :
fin_add_flip (⟨k, h₂⟩ : fin (m + n)) =
⟨k - m, lt_of_le_of_lt (nat.sub_le _ _) (by { convert h₂ using 1, simp [add_comm] })⟩ :=
begin
dsimp [fin_add_flip, fin_sum_fin_equiv],
rw [dif_neg (not_lt.mpr h₁)],
refl,
end
/-- Rotate `fin n` one step to the right. -/
def fin_rotate : Π n, fin n ≃ fin n
| 0 := equiv.refl _
| (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _))
@[simp] lemma fin_rotate_of_lt {k : ℕ} (h : k < n) :
fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ :=
begin
dsimp [fin_rotate],
simp [h, add_comm],
end
@[simp] lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ :=
begin
dsimp [fin_rotate],
rw fin_add_flip_apply_right,
simp,
end
@[simp] lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 :=
fin_rotate_last'
lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) :
@fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) :=
begin
ext ⟨i, h⟩,
by_cases h' : i < n,
{ rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'],
refl, },
{ have h'' : n = i,
{ simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, },
subst h'',
rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)],
refl, }
end
/-- Equivalence between `fin m × fin n` and `fin (m * n)` -/
def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) :=
{ to_fun := λ x, ⟨x.2.1 + n * x.1.1,
calc x.2.1 + n * x.1.1 + 1
= x.1.1 * n + x.2.1 + 1 : by ac_refl
... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _
... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _
... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩,
inv_fun := λ x,
have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero x.1 $ by subst H; from x.2,
(⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩,
⟨x.1 % n, nat.mod_lt _ H⟩),
left_inv := λ ⟨x, y⟩,
have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2,
prod.ext
(fin.eq_of_veq $ calc
(y.1 + n * x.1) / n
= y.1 / n + x.1 : nat.add_mul_div_left _ _ H
... = 0 + x.1 : by rw nat.div_eq_of_lt y.2
... = x.1 : nat.zero_add x.1)
(fin.eq_of_veq $ calc
(y.1 + n * x.1) % n
= y.1 % n : nat.add_mul_mod_self_left _ _ _
... = y.1 : nat.mod_eq_of_lt y.2),
right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ }
/-- `fin 0` is a subsingleton. -/
instance subsingleton_fin_zero : subsingleton (fin 0) :=
fin_zero_equiv.subsingleton
/-- `fin 1` is a subsingleton. -/
instance subsingleton_fin_one : subsingleton (fin 1) :=
fin_one_equiv.subsingleton
|
6bf3382b06f7b76311d11c6ea1549f23f78b8dfe | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/concatElim.lean | 2d135a8a7da15f1f7ac68973d1cf3383f7d3e0fe | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 2,502 | lean | universe u
def concat {α} : List α → α → List α
| [], a => [a]
| x::xs, a => x :: concat xs a
def last {α} : (xs : List α) → xs ≠ [] → α
| [], h => by contradiction
| [a], h => a
| _::a::as, h => last (a::as) (fun h => by injection h)
def dropLast {α} : List α → List α
| [] => []
| [a] => []
| a::as => a :: dropLast as
variable {α}
theorem concatEq (xs : List α) (h : xs ≠ []) : concat (dropLast xs) (last xs h) = xs := by
match xs, h with
| [], h => contradiction
| [x], h => rfl
| x₁::x₂::xs, h => simp [concat, last, concatEq (x₂::xs) List.noConfusion]
theorem lengthCons {α} (x : α) (xs : List α) : (x::xs).length = xs.length + 1 :=
rfl
theorem eqNilOfLengthZero {α} : (xs : List α) → xs.length = 0 → xs = []
| [], h => rfl
| x::xs, h => by rw [lengthCons] at h; contradiction
theorem dropLastLen {α} (xs : List α) : (n : Nat) → xs.length = n+1 → (dropLast xs).length = n := by
match xs with
| [] => intros; contradiction
| [a] =>
intro n h
have : 1 = n + 1 := h
have : 0 = n := by injection this; assumption
subst this
rfl
| x₁::x₂::xs =>
intro n h
cases n with
| zero =>
simp [lengthCons] at h
injection h
| succ n =>
have : (x₁ :: x₂ :: xs).length = xs.length + 2 := by simp [lengthCons]
have : xs.length = n := by rw [this] at h; injection h with h; injection h with h; assumption
simp [dropLast, lengthCons, dropLastLen (x₂::xs) xs.length (lengthCons ..), this]
@[inline]
def concatElim {α}
(motive : List α → Sort u)
(base : Unit → motive [])
(ind : (xs : List α) → (a : α) → motive xs → motive (concat xs a))
(xs : List α)
: motive xs :=
let rec @[specialize] aux : (n : Nat) → (xs : List α) → xs.length = n → motive xs
| 0, xs, h => by
have aux := eqNilOfLengthZero _ h
subst aux
apply base ()
| n+1, xs, h => by
have notNil : xs ≠ [] := by intro h1; subst h1; injection h
let ih := aux n (dropLast xs) (dropLastLen _ _ h)
let aux := ind (dropLast xs) (last xs notNil) ih
rw [concatEq] at aux
exact aux
aux xs.length xs rfl
-- The generated code is tail recursive
def test (xs : List Nat) : IO Unit :=
concatElim (motive := fun _ => IO Unit)
(fun _ => pure ())
(fun xs x r => do IO.println s!"step xs: {xs} x: {x}"; r)
xs
#eval test [1, 2, 3, 4]
|
3774624c87e425dd9a0dbd4a72252826b93a11df | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/exit.lean | 553d6d2777efa6df20e34613035d2f44ae226cad | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20 | lean | exit
print "FAILED"
|
b50eb6f5a1939bd8f9c4723e703848cca129b31c | f1d0c3912d57abc8ea280458f07787fa00ecf62a | /src/tpow.lean | e30c13adcdf7e2f9e0b7759f2a365bb6266cf9d3 | [] | no_license | 101damnations/test | 2e426e10dde625657b531c978ba179b1a87b1fed | ade0896c09890e877e8fb0f17c636bc0491b8f2b | refs/heads/master | 1,672,484,804,338 | 1,603,359,314,000 | 1,603,359,314,000 | 276,198,127 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,440 | lean | import algebra.category.Module.monoidal
import linear_algebra.tensor_algebra
import algebra.category.CommRing.basic
open category_theory
variables {C : Type*} [category C] [monoidal_category C]
/-
def tensor_power_aux (X : C) : ℕ → C
| 0 := 𝟙_ C
| (n+1) := tensor_power_aux n ⊗ X
instance wtf {R : Type*} [comm_ring R] : monoidal_category (Module R) :=
Module.Module.monoidal_category
def tensor_power {R : Type*} [comm_ring R] (M : Module R) : ℕ → Module R :=
@tensor_power_aux _ _ huh.wtf M-/
universe u
def tpow_aux (R : Type u) [comm_semiring R] (M : Type u) [add_comm_monoid M] [semimodule R M] :
ℕ → Σ (N : Type*) (h : add_comm_monoid N), @semimodule R N _ h
| 0 := ⟨R, ⟨by apply_instance, by apply_instance⟩⟩
| (n+1) := ⟨@tensor_product R _ (tpow_aux n).1 M (tpow_aux n).2.1 _ (tpow_aux n).2.2 _, ⟨by apply_instance, by apply_instance⟩⟩
def tpow (R : Type u) [comm_semiring R] (M : Type u) [add_comm_monoid M] [semimodule R M] (n : ℕ) :=
(tpow_aux R M n).1
instance tpow_acg (R : Type u) [comm_semiring R] (M : Type u) [add_comm_monoid M] [semimodule R M] (n : ℕ) :
add_comm_monoid (tpow R M n) := (tpow_aux R M n).2.1
instance tpow_semimodule (R : Type u) [comm_semiring R] (M : Type u) [add_comm_monoid M] [semimodule R M] (n : ℕ) :
semimodule R (tpow R M n) := (tpow_aux R M n).2.2
--abbreviation tpow (R : Type u) [comm_ring R] (M : Type u) [add_comm_group M]
-- [module R M] := tensor_power (Module.of R M)
variables {R : Type u} [comm_semiring R] {M : Type u} [add_comm_monoid M] [semimodule R M]
--lemma tpow_zero : tensor_power (Module.of R M) 0 = Module.of R R := rfl
lemma tpow_zero : tpow R M 0 = R := rfl
--def tpow_one : tensor_power (Module.of R M) 1 ≅ Module.of R M :=
--Module.monoidal_category.left_unitor (Module.of R M)
variables (R M)
def tpow_one : linear_equiv R (tpow R M 1) M :=
tensor_product.lid R M
namespace tpow
def algebra_alg_hom (S : Type*) [semiring S] [algebra R S] : R →ₐ[R] S :=
{ commutes' := λ r, rfl,
..algebra_map R S }
local attribute [semireducible] tensor_algebra
def of_scalar :
R →ₗ[R] tensor_algebra R M :=
(((ring_quot.mk_alg_hom R (tensor_algebra.rel R M)).comp
(algebra_alg_hom R (free_algebra R M))) : R →ₐ[R] tensor_algebra R M).to_linear_map
/-def mk : Π (n : ℕ) (f : fin n → M), tpow R M n
| 0 _ := (1 : R)
| (n + 1) f := tensor_product.mk _ _ _ (mk n $ λ y, f y) $ f (n + 1)-/
def mk : Π (n : ℕ) (f : fin n → M), tpow R M n
| 0 _ := (1 : R)
| (n + 1) f := @tensor_product.mk R _ (tpow R M n) M _ _ _ _ (mk n $ λ y, f y) $ f (n + 1)
variables (x : M)
def mk' (n : ℕ) : @multilinear_map R (fin n) (λ _, M) (tpow R M n) _ _ _ _ _ _ :=
{ to_fun := mk R M n,
map_add' := λ f m x y, sorry,
map_smul' := sorry }
variables {R M}
lemma mk'_apply (n : ℕ) (x) : mk' R M n x = mk R M n x := rfl
lemma mk_one_lid (x : tensor_product R R M) :
tensor_product.mk R R M 1 (tensor_product.lid R M x) = x :=
begin
apply tensor_product.induction_on x,
rw linear_equiv.map_zero, convert tensor_product.tmul_zero _ _,
intros y z,
rw tensor_product.lid_tmul, rw map_smul_eq_smul_map,
erw tensor_product.smul_tmul',
rw [algebra.id.smul_eq_mul, mul_one],
intros y z hy hz,
simp only [tensor_product.mk_apply, linear_equiv.map_add] at *,
rw tensor_product.tmul_add, rw hy, rw hz,
end
lemma mk_one_rid (x : tensor_product R M R) :
tensor_product.mk R M R (tensor_product.rid R M x) 1 = x :=
begin
apply tensor_product.induction_on x,
rw linear_equiv.map_zero, convert tensor_product.zero_tmul _ _,
intros y z,
erw tensor_product.lid_tmul,
rw map_smul_eq_smul_map,
rw linear_map.smul_apply,
simp only [],
erw ←tensor_product.tmul_smul,
rw algebra.id.smul_eq_mul, rw mul_one,
intros y z hy hz,
simp only [tensor_product.mk_apply, linear_equiv.map_add] at *,
rw tensor_product.add_tmul, rw hy, rw hz,
end
variables (R M)
def fin0_to_multilinear (f : (fin 0 → M) → R) :
@multilinear_map R (fin 0) (λ _, M) R _ _ _ _ _ _ :=
{ to_fun := f,
map_add' := λ x y a b, fin.elim0 y,
map_smul' := λ x y, fin.elim0 y }
variables {R M}
@[simp] lemma to_span_singleton_apply (x : M) (r : R) :
linear_map.to_span_singleton R M x r = r • x := rfl
lemma eq_smul_one (f : R →ₗ[R] M) (x : R) :
x • f 1 = f x :=
by rw [←f.map_smul, algebra.id.smul_eq_mul, mul_one]
lemma eq_iff_eq_one (f g : R →ₗ[R] M) :
f = g ↔ f 1 = g 1 :=
⟨λ h, h ▸ rfl, λ h, linear_map.ext $ λ x, by
rw [←eq_smul_one, h, eq_smul_one]⟩
/-def lift {M : Type u} [add_comm_group M] [module R M] :
Π (n : ℕ) (P : Type u) {h1 : add_comm_monoid P}, by exactI Π
{h2 : semimodule R P}, by exactI Π
(f : @multilinear_map R (fin n) (λ _, M) P _ _ _ _ _ _),
tpow R M n →ₗ[R] P
| 0 P h1 h2 g := @linear_map.to_span_singleton R P _ h1 h2 $ g (default _)
| (n + 1) P h1 h2 g := @tensor_product.lift _ _ _ _ _ _ _ h1 _ _ h2
$ lift n _ (@multilinear_map.curry_right _ _ _ _ _ _ h1 _ h2 g)-/
variables (R M)
def lift {M : Type u} [add_comm_monoid M] [semimodule R M] :
Π (n : ℕ) (P : Type u) {h1 : add_comm_monoid P}, by exactI Π
{h2 : semimodule R P}, by exactI Π
(f : @multilinear_map R (fin n) (λ _, M) P _ _ _ _ _ _),
tpow R M n →ₗ[R] P
| 0 P h1 h2 g := @linear_map.to_span_singleton R P _ h1 h2 $ g (default (fin 0 → M))
| (n + 1) P h1 h2 g := @tensor_product.lift _ _ _ _ _ _ _ h1 _ _ h2
$ lift n _ (@multilinear_map.curry_right _ _ _ _ _ _ h1 _ h2 g)
variables {R M}
lemma lift_mk {M : Type u} [add_comm_monoid M] [semimodule R M] (n : ℕ) :
∀ {P : Type u} [add_comm_monoid P], by exactI ∀ [semimodule R P],
by exactI ∀
(f : @multilinear_map R (fin n) (λ _, M) P _ _ _ _ _ _),
(lift R n P f).comp_multilinear_map (mk' R M n) = f :=
begin
induction n with n hn,
intros,
ext,
show linear_map.to_span_singleton _ _ _ (1 : R) = _,
rw linear_map.to_span_singleton_one,
congr,
intros,
ext,
show tensor_product.lift _ (tensor_product.mk _ _ _ _ _) = _,
rw tensor_product.mk_apply,
rw tensor_product.lift.tmul,
unfreezingI {erw multilinear_map.ext_iff.1 (hn f.curry_right) (λ y : fin n, x y)},
rw f.curry_right_apply,
congr,
sorry -- annoying fin stuff
end
lemma lift_mk_apply {M : Type u} [add_comm_monoid M] [semimodule R M] (n : ℕ)
{P : Type u} [add_comm_monoid P] [semimodule R P]
(f : @multilinear_map R (fin n) (λ _, M) P _ _ _ _ _ _) (x) :
lift R n P f (mk' R M n x) = f x :=
multilinear_map.ext_iff.1 (lift_mk n f) _
lemma lift_unique {M : Type u} [add_comm_monoid M] [semimodule R M] (n : ℕ) :
∀ {P : Type u} [add_comm_monoid P], by exactI ∀ [semimodule R P],
by exactI ∀
(f : @multilinear_map R (fin n) (λ _, M) P _ _ _ _ _ _)
(g : tpow R M n →ₗ[R] P)
(H : ∀ x : fin n → M, g (mk' R M n x) = f x),
g = lift R n P f :=
begin
induction n with n hn,
intros,
ext,
rw ←eq_smul_one,
erw H (default _),
refl,
intros,
unfold lift,
ext (x : tpow R M n) y,
rw tensor_product.lift.tmul,
unfreezingI { rw ←hn f.curry_right (tensor_product.lcurry _ (tpow R M n) _ _ g)
(λ x, by {ext z,
rw f.curry_right_apply,rw ← H (fin.snoc x z),
rw tensor_product.lcurry_apply,
rw mk'_apply, rw mk'_apply,
unfold mk,
rw tensor_product.mk_apply,
congr,
specialize H (fin.snoc x z),
ext,
sorry, --more stupid fin stuff
sorry, --same
}), },
refl,
end
end tpow |
6aee7620e03e6c4810ae5088356f922ca429225b | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/group_theory/submonoid/operations.lean | b8175c61e89c266df9e062289c968891419fdac3 | [
"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 | 32,528 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard,
Amelia Livingston, Yury Kudryashov
-/
import group_theory.submonoid.basic
import data.equiv.mul_add
import algebra.group.prod
import algebra.group.inj_surj
/-!
# Operations on `submonoid`s
In this file we define various operations on `submonoid`s and `monoid_hom`s.
## Main definitions
### Conversion between multiplicative and additive definitions
* `submonoid.to_add_submonoid`, `submonoid.to_add_submonoid'`, `add_submonoid.to_submonoid`,
`add_submonoid.to_submonoid'`: convert between multiplicative and additive submonoids of `M`,
`multiplicative M`, and `additive M`. These are stated as `order_iso`s.
### (Commutative) monoid structure on a submonoid
* `submonoid.to_monoid`, `submonoid.to_comm_monoid`: a submonoid inherits a (commutative) monoid
structure.
### Group actions by submonoids
* `submonoid.mul_action`, `submonoid.distrib_mul_action`: a submonoid inherits (distributive)
multiplicative actions.
### Operations on submonoids
* `submonoid.comap`: preimage of a submonoid under a monoid homomorphism as a submonoid of the
domain;
* `submonoid.map`: image of a submonoid under a monoid homomorphism as a submonoid of the codomain;
* `submonoid.prod`: product of two submonoids `s : submonoid M` and `t : submonoid N` as a submonoid
of `M × N`;
### Monoid homomorphisms between submonoid
* `submonoid.subtype`: embedding of a submonoid into the ambient monoid.
* `submonoid.inclusion`: given two submonoids `S`, `T` such that `S ≤ T`, `S.inclusion T` is the
inclusion of `S` into `T` as a monoid homomorphism;
* `mul_equiv.submonoid_congr`: converts a proof of `S = T` into a monoid isomorphism between `S`
and `T`.
* `submonoid.prod_equiv`: monoid isomorphism between `s.prod t` and `s × t`;
### Operations on `monoid_hom`s
* `monoid_hom.mrange`: range of a monoid homomorphism as a submonoid of the codomain;
* `monoid_hom.mrestrict`: restrict a monoid homomorphism to a submonoid;
* `monoid_hom.cod_mrestrict`: restrict the codomain of a monoid homomorphism to a submonoid;
* `monoid_hom.mrange_restrict`: restrict a monoid homomorphism to its range;
## Tags
submonoid, range, product, map, comap
-/
variables {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (S : submonoid M)
/-!
### Conversion to/from `additive`/`multiplicative`
-/
section
/-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/
@[simps]
def submonoid.to_add_submonoid : submonoid M ≃o add_submonoid (additive M) :=
{ to_fun := λ S,
{ carrier := additive.to_mul ⁻¹' S,
zero_mem' := S.one_mem',
add_mem' := S.mul_mem' },
inv_fun := λ S,
{ carrier := additive.of_mul ⁻¹' S,
one_mem' := S.zero_mem',
mul_mem' := S.add_mem' },
left_inv := λ x, by cases x; refl,
right_inv := λ x, by cases x; refl,
map_rel_iff' := λ a b, iff.rfl, }
/-- Additive submonoids of an additive monoid `additive M` are isomorphic to submonoids of `M`. -/
abbreviation add_submonoid.to_submonoid' : add_submonoid (additive M) ≃o submonoid M :=
submonoid.to_add_submonoid.symm
lemma submonoid.to_add_submonoid_closure (S : set M) :
(submonoid.closure S).to_add_submonoid = add_submonoid.closure (additive.to_mul ⁻¹' S) :=
le_antisymm
(submonoid.to_add_submonoid.to_galois_connection.l_le $
submonoid.closure_le.2 add_submonoid.subset_closure)
(add_submonoid.closure_le.2 submonoid.subset_closure)
lemma add_submonoid.to_submonoid'_closure (S : set (additive M)) :
(add_submonoid.closure S).to_submonoid' = submonoid.closure (multiplicative.of_add ⁻¹' S) :=
le_antisymm
(add_submonoid.to_submonoid'.to_galois_connection.l_le $
add_submonoid.closure_le.2 submonoid.subset_closure)
(submonoid.closure_le.2 add_submonoid.subset_closure)
end
section
variables {A : Type*} [add_zero_class A]
/-- Additive submonoids of an additive monoid `A` are isomorphic to
multiplicative submonoids of `multiplicative A`. -/
@[simps]
def add_submonoid.to_submonoid : add_submonoid A ≃o submonoid (multiplicative A) :=
{ to_fun := λ S,
{ carrier := multiplicative.to_add ⁻¹' S,
one_mem' := S.zero_mem',
mul_mem' := S.add_mem' },
inv_fun := λ S,
{ carrier := multiplicative.of_add ⁻¹' S,
zero_mem' := S.one_mem',
add_mem' := S.mul_mem' },
left_inv := λ x, by cases x; refl,
right_inv := λ x, by cases x; refl,
map_rel_iff' := λ a b, iff.rfl, }
/-- Submonoids of a monoid `multiplicative A` are isomorphic to additive submonoids of `A`. -/
abbreviation submonoid.to_add_submonoid' : submonoid (multiplicative A) ≃o add_submonoid A :=
add_submonoid.to_submonoid.symm
lemma add_submonoid.to_submonoid_closure (S : set A) :
(add_submonoid.closure S).to_submonoid = submonoid.closure (multiplicative.to_add ⁻¹' S) :=
le_antisymm
(add_submonoid.to_submonoid.to_galois_connection.l_le $
add_submonoid.closure_le.2 submonoid.subset_closure)
(submonoid.closure_le.2 add_submonoid.subset_closure)
lemma submonoid.to_add_submonoid'_closure (S : set (multiplicative A)) :
(submonoid.closure S).to_add_submonoid' = add_submonoid.closure (additive.of_mul ⁻¹' S) :=
le_antisymm
(submonoid.to_add_submonoid'.to_galois_connection.l_le $
submonoid.closure_le.2 add_submonoid.subset_closure)
(add_submonoid.closure_le.2 submonoid.subset_closure)
end
namespace submonoid
open set
/-!
### `comap` and `map`
-/
/-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/
@[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an
`add_submonoid`."]
def comap (f : M →* N) (S : submonoid N) : submonoid M :=
{ carrier := (f ⁻¹' S),
one_mem' := show f 1 ∈ S, by rw f.map_one; exact S.one_mem,
mul_mem' := λ a b ha hb,
show f (a * b) ∈ S, by rw f.map_mul; exact S.mul_mem ha hb }
@[simp, to_additive]
lemma coe_comap (S : submonoid N) (f : M →* N) : (S.comap f : set M) = f ⁻¹' S := rfl
@[simp, to_additive]
lemma mem_comap {S : submonoid N} {f : M →* N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl
@[to_additive]
lemma comap_comap (S : submonoid P) (g : N →* P) (f : M →* N) :
(S.comap g).comap f = S.comap (g.comp f) :=
rfl
@[simp, to_additive]
lemma comap_id (S : submonoid P) : S.comap (monoid_hom.id _) = S :=
ext (by simp)
/-- The image of a submonoid along a monoid homomorphism is a submonoid. -/
@[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is
an `add_submonoid`."]
def map (f : M →* N) (S : submonoid M) : submonoid N :=
{ carrier := (f '' S),
one_mem' := ⟨1, S.one_mem, f.map_one⟩,
mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy,
by rw f.map_mul; refl⟩ end }
@[simp, to_additive]
lemma coe_map (f : M →* N) (S : submonoid M) :
(S.map f : set N) = f '' S := rfl
@[simp, to_additive]
lemma mem_map {f : M →* N} {S : submonoid M} {y : N} :
y ∈ S.map f ↔ ∃ x ∈ S, f x = y :=
mem_image_iff_bex
@[to_additive]
lemma mem_map_of_mem (f : M →* N) {S : submonoid M} {x : M} (hx : x ∈ S) : f x ∈ S.map f :=
mem_image_of_mem f hx
@[to_additive]
lemma apply_coe_mem_map (f : M →* N) (S : submonoid M) (x : S) : f x ∈ S.map f :=
mem_map_of_mem f x.prop
@[to_additive]
lemma map_map (g : N →* P) (f : M →* N) : (S.map f).map g = S.map (g.comp f) :=
set_like.coe_injective $ image_image _ _ _
@[to_additive]
lemma map_le_iff_le_comap {f : M →* N} {S : submonoid M} {T : submonoid N} :
S.map f ≤ T ↔ S ≤ T.comap f :=
image_subset_iff
@[to_additive]
lemma gc_map_comap (f : M →* N) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
@[to_additive]
lemma map_le_of_le_comap {T : submonoid N} {f : M →* N} : S ≤ T.comap f → S.map f ≤ T :=
(gc_map_comap f).l_le
@[to_additive]
lemma le_comap_of_map_le {T : submonoid N} {f : M →* N} : S.map f ≤ T → S ≤ T.comap f :=
(gc_map_comap f).le_u
@[to_additive]
lemma le_comap_map {f : M →* N} : S ≤ (S.map f).comap f :=
(gc_map_comap f).le_u_l _
@[to_additive]
lemma map_comap_le {S : submonoid N} {f : M →* N} : (S.comap f).map f ≤ S :=
(gc_map_comap f).l_u_le _
@[to_additive]
lemma monotone_map {f : M →* N} : monotone (map f) :=
(gc_map_comap f).monotone_l
@[to_additive]
lemma monotone_comap {f : M →* N} : monotone (comap f) :=
(gc_map_comap f).monotone_u
@[simp, to_additive]
lemma map_comap_map {f : M →* N} : ((S.map f).comap f).map f = S.map f :=
congr_fun ((gc_map_comap f).l_u_l_eq_l) _
@[simp, to_additive]
lemma comap_map_comap {S : submonoid N} {f : M →* N} : ((S.comap f).map f).comap f = S.comap f :=
congr_fun ((gc_map_comap f).u_l_u_eq_u) _
@[to_additive]
lemma map_sup (S T : submonoid M) (f : M →* N) : (S ⊔ T).map f = S.map f ⊔ T.map f :=
(gc_map_comap f).l_sup
@[to_additive]
lemma map_supr {ι : Sort*} (f : M →* N) (s : ι → submonoid M) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
@[to_additive]
lemma comap_inf (S T : submonoid N) (f : M →* N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f :=
(gc_map_comap f).u_inf
@[to_additive]
lemma comap_infi {ι : Sort*} (f : M →* N) (s : ι → submonoid N) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp, to_additive] lemma map_bot (f : M →* N) : (⊥ : submonoid M).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp, to_additive] lemma comap_top (f : M →* N) : (⊤ : submonoid N).comap f = ⊤ :=
(gc_map_comap f).u_top
@[simp, to_additive] lemma map_id (S : submonoid M) : S.map (monoid_hom.id M) = S :=
ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩)
section galois_coinsertion
variables {ι : Type*} {f : M →* N} (hf : function.injective f)
include hf
/-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/
def gci_map_comap : galois_coinsertion (map f) (comap f) :=
(gc_map_comap f).to_galois_coinsertion
(λ S x, by simp [mem_comap, mem_map, hf.eq_iff])
lemma comap_map_eq_of_injective (S : submonoid M) : (S.map f).comap f = S :=
(gci_map_comap hf).u_l_eq _
lemma comap_surjective_of_injective : function.surjective (comap f) :=
(gci_map_comap hf).u_surjective
lemma map_injective_of_injective : function.injective (map f) :=
(gci_map_comap hf).l_injective
lemma comap_inf_map_of_injective (S T : submonoid M) : (S.map f ⊓ T.map f).comap f = S ⊓ T :=
(gci_map_comap hf).u_inf_l _ _
lemma comap_infi_map_of_injective (S : ι → submonoid M) : (⨅ i, (S i).map f).comap f = infi S :=
(gci_map_comap hf).u_infi_l _
lemma comap_sup_map_of_injective (S T : submonoid M) : (S.map f ⊔ T.map f).comap f = S ⊔ T :=
(gci_map_comap hf).u_sup_l _ _
lemma comap_supr_map_of_injective (S : ι → submonoid M) : (⨆ i, (S i).map f).comap f = supr S :=
(gci_map_comap hf).u_supr_l _
lemma map_le_map_iff_of_injective {S T : submonoid M} : S.map f ≤ T.map f ↔ S ≤ T :=
(gci_map_comap hf).l_le_l_iff
lemma map_strict_mono_of_injective : strict_mono (map f) :=
(gci_map_comap hf).strict_mono_l
end galois_coinsertion
section galois_insertion
variables {ι : Type*} {f : M →* N} (hf : function.surjective f)
include hf
/-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/
def gi_map_comap : galois_insertion (map f) (comap f) :=
(gc_map_comap f).to_galois_insertion
(λ S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩)
lemma map_comap_eq_of_surjective (S : submonoid N) : (S.comap f).map f = S :=
(gi_map_comap hf).l_u_eq _
lemma map_surjective_of_surjective : function.surjective (map f) :=
(gi_map_comap hf).l_surjective
lemma comap_injective_of_surjective : function.injective (comap f) :=
(gi_map_comap hf).u_injective
lemma map_inf_comap_of_surjective (S T : submonoid N) : (S.comap f ⊓ T.comap f).map f = S ⊓ T :=
(gi_map_comap hf).l_inf_u _ _
lemma map_infi_comap_of_surjective (S : ι → submonoid N) : (⨅ i, (S i).comap f).map f = infi S :=
(gi_map_comap hf).l_infi_u _
lemma map_sup_comap_of_surjective (S T : submonoid N) : (S.comap f ⊔ T.comap f).map f = S ⊔ T :=
(gi_map_comap hf).l_sup_u _ _
lemma map_supr_comap_of_surjective (S : ι → submonoid N) : (⨆ i, (S i).comap f).map f = supr S :=
(gi_map_comap hf).l_supr_u _
lemma comap_le_comap_iff_of_surjective {S T : submonoid N} : S.comap f ≤ T.comap f ↔ S ≤ T :=
(gi_map_comap hf).u_le_u_iff
lemma comap_strict_mono_of_surjective : strict_mono (comap f) :=
(gi_map_comap hf).strict_mono_u
end galois_insertion
/-- A submonoid of a monoid inherits a multiplication. -/
@[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."]
instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩
/-- A submonoid of a monoid inherits a 1. -/
@[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."]
instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩
@[simp, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl
@[simp, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl
attribute [norm_cast] coe_mul coe_one
attribute [norm_cast] add_submonoid.coe_add add_submonoid.coe_zero
/-- A submonoid of a unital magma inherits a unital magma structure. -/
@[to_additive "An `add_submonoid` of an unital additive magma inherits an unital additive magma
structure."]
instance to_mul_one_class {M : Type*} [mul_one_class M] (S : submonoid M) : mul_one_class S :=
subtype.coe_injective.mul_one_class coe rfl (λ _ _, rfl)
/-- A submonoid of a monoid inherits a monoid structure. -/
@[to_additive "An `add_submonoid` of an `add_monoid` inherits an `add_monoid`
structure."]
instance to_monoid {M : Type*} [monoid M] (S : submonoid M) : monoid S :=
subtype.coe_injective.monoid coe rfl (λ _ _, rfl)
/-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `add_comm_monoid` is
an `add_comm_monoid`."]
instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S :=
subtype.coe_injective.comm_monoid coe rfl (λ _ _, rfl)
/-- A submonoid of an `ordered_comm_monoid` is an `ordered_comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `ordered_add_comm_monoid` is
an `ordered_add_comm_monoid`."]
instance to_ordered_comm_monoid {M} [ordered_comm_monoid M] (S : submonoid M) :
ordered_comm_monoid S :=
subtype.coe_injective.ordered_comm_monoid coe rfl (λ _ _, rfl)
/-- A submonoid of a `linear_ordered_comm_monoid` is a `linear_ordered_comm_monoid`. -/
@[to_additive "An `add_submonoid` of a `linear_ordered_add_comm_monoid` is
a `linear_ordered_add_comm_monoid`."]
instance to_linear_ordered_comm_monoid {M} [linear_ordered_comm_monoid M] (S : submonoid M) :
linear_ordered_comm_monoid S :=
subtype.coe_injective.linear_ordered_comm_monoid coe rfl (λ _ _, rfl)
/-- A submonoid of an `ordered_cancel_comm_monoid` is an `ordered_cancel_comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `ordered_cancel_add_comm_monoid` is
an `ordered_cancel_add_comm_monoid`."]
instance to_ordered_cancel_comm_monoid {M} [ordered_cancel_comm_monoid M] (S : submonoid M) :
ordered_cancel_comm_monoid S :=
subtype.coe_injective.ordered_cancel_comm_monoid coe rfl (λ _ _, rfl)
/-- A submonoid of a `linear_ordered_cancel_comm_monoid` is a `linear_ordered_cancel_comm_monoid`.
-/
@[to_additive "An `add_submonoid` of a `linear_ordered_cancel_add_comm_monoid` is
a `linear_ordered_cancel_add_comm_monoid`."]
instance to_linear_ordered_cancel_comm_monoid {M} [linear_ordered_cancel_comm_monoid M]
(S : submonoid M) : linear_ordered_cancel_comm_monoid S :=
subtype.coe_injective.linear_ordered_cancel_comm_monoid coe rfl (λ _ _, rfl)
/-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/
@[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."]
def subtype : S →* M := ⟨coe, rfl, λ _ _, rfl⟩
@[simp, to_additive] theorem coe_subtype : ⇑S.subtype = coe := rfl
/-- A submonoid is isomorphic to its image under an injective function -/
@[to_additive "An additive submonoid is isomorphic to its image under an injective function"]
noncomputable def equiv_map_of_injective
(f : M →* N) (hf : function.injective f) : S ≃* S.map f :=
{ map_mul' := λ _ _, subtype.ext (f.map_mul _ _), ..equiv.set.image f S hf }
@[simp, to_additive] lemma coe_equiv_map_of_injective_apply
(f : M →* N) (hf : function.injective f) (x : S) :
(equiv_map_of_injective S f hf x : N) = f x := rfl
/-- An induction principle on elements of the type `submonoid.closure s`.
If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p`
holds for all elements of the closure of `s`.
The difference with `submonoid.closure_induction` is that this acts on the subtype.
-/
@[to_additive "An induction principle on elements of the type `add_submonoid.closure s`.
If `p` holds for `0` and all elements of `s`, and is preserved under addition, then `p`
holds for all elements of the closure of `s`.
The difference with `add_submonoid.closure_induction` is that this acts on the subtype."]
lemma closure_induction' (s : set M) {p : closure s → Prop}
(Hs : ∀ x (h : x ∈ s), p ⟨x, subset_closure h⟩)
(H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y))
(x : closure s) :
p x :=
subtype.rec_on x $ λ x hx, begin
refine exists.elim _ (λ (hx : x ∈ closure s) (hc : p ⟨x, hx⟩), hc),
exact closure_induction hx
(λ x hx, ⟨subset_closure hx, Hs x hx⟩)
⟨one_mem _, H1⟩
(λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy,
⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩),
end
attribute [elab_as_eliminator] submonoid.closure_induction' add_submonoid.closure_induction'
/-- Given `submonoid`s `s`, `t` of monoids `M`, `N` respectively, `s × t` as a submonoid
of `M × N`. -/
@[to_additive prod "Given `add_submonoid`s `s`, `t` of `add_monoid`s `A`, `B` respectively, `s × t`
as an `add_submonoid` of `A × B`."]
def prod (s : submonoid M) (t : submonoid N) : submonoid (M × N) :=
{ carrier := (s : set M).prod t,
one_mem' := ⟨s.one_mem, t.one_mem⟩,
mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ }
@[to_additive coe_prod]
lemma coe_prod (s : submonoid M) (t : submonoid N) :
(s.prod t : set (M × N)) = (s : set M).prod (t : set N) :=
rfl
@[to_additive mem_prod]
lemma mem_prod {s : submonoid M} {t : submonoid N} {p : M × N} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[to_additive prod_mono]
lemma prod_mono {s₁ s₂ : submonoid M} {t₁ t₂ : submonoid N} (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) :
s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
@[to_additive prod_top]
lemma prod_top (s : submonoid M) :
s.prod (⊤ : submonoid N) = s.comap (monoid_hom.fst M N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
@[to_additive top_prod]
lemma top_prod (s : submonoid N) :
(⊤ : submonoid M).prod s = s.comap (monoid_hom.snd M N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp, to_additive top_prod_top]
lemma top_prod_top : (⊤ : submonoid M).prod (⊤ : submonoid N) = ⊤ :=
(top_prod _).trans $ comap_top _
@[to_additive] lemma bot_prod_bot : (⊥ : submonoid M).prod (⊥ : submonoid N) = ⊥ :=
set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk]
/-- The product of submonoids is isomorphic to their product as monoids. -/
@[to_additive prod_equiv "The product of additive submonoids is isomorphic to their product
as additive monoids"]
def prod_equiv (s : submonoid M) (t : submonoid N) : s.prod t ≃* s × t :=
{ map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
open monoid_hom
@[to_additive]
lemma map_inl (s : submonoid M) : s.map (inl M N) = s.prod ⊥ :=
ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨hx, set.mem_singleton 1⟩,
λ ⟨hps, hp1⟩, ⟨p.1, hps, prod.ext rfl $ (set.eq_of_mem_singleton hp1).symm⟩⟩
@[to_additive]
lemma map_inr (s : submonoid N) : s.map (inr M N) = prod ⊥ s :=
ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨set.mem_singleton 1, hx⟩,
λ ⟨hp1, hps⟩, ⟨p.2, hps, prod.ext (set.eq_of_mem_singleton hp1).symm rfl⟩⟩
@[simp, to_additive prod_bot_sup_bot_prod]
lemma prod_bot_sup_bot_prod (s : submonoid M) (t : submonoid N) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono (le_refl s) bot_le) (prod_mono bot_le (le_refl t))) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem _
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set.mem_singleton 1⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set.mem_singleton 1, hp.2⟩)
@[to_additive]
lemma mem_map_equiv {f : M ≃* N} {K : submonoid M} {x : N} :
x ∈ K.map f.to_monoid_hom ↔ f.symm x ∈ K :=
@set.mem_image_equiv _ _ ↑K f.to_equiv x
@[to_additive]
lemma map_equiv_eq_comap_symm (f : M ≃* N) (K : submonoid M) :
K.map f.to_monoid_hom = K.comap f.symm.to_monoid_hom :=
set_like.coe_injective (f.to_equiv.image_eq_preimage K)
@[to_additive]
lemma comap_equiv_eq_map_symm (f : N ≃* M) (K : submonoid M) :
K.comap f.to_monoid_hom = K.map f.symm.to_monoid_hom :=
(map_equiv_eq_comap_symm f.symm K).symm
end submonoid
namespace monoid_hom
open submonoid
/-- For many categories (monoids, modules, rings, ...) the set-theoretic image of a morphism `f` is
a subobject of the codomain. When this is the case, it is useful to define the range of a morphism
in such a way that the underlying carrier set of the range subobject is definitionally
`set.range f`. In particular this means that the types `↥(set.range f)` and `↥f.range` are
interchangeable without proof obligations.
A convenient candidate definition for range which is mathematically correct is `map ⊤ f`, just as
`set.range` could have been defined as `f '' set.univ`. However, this lacks the desired definitional
convenience, in that it both does not match `set.range`, and that it introduces a redudant `x ∈ ⊤`
term which clutters proofs. In such a case one may resort to the `copy`
pattern. A `copy` function converts the definitional problem for the carrier set of a subobject
into a one-off propositional proof obligation which one discharges while writing the definition of
the definitionally convenient range (the parameter `hs` in the example below).
A good example is the case of a morphism of monoids. A convenient definition for
`monoid_hom.mrange` would be `(⊤ : submonoid M).map f`. However since this lacks the required
definitional convenience, we first define `submonoid.copy` as follows:
```lean
protected def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M :=
{ carrier := s,
one_mem' := hs.symm ▸ S.one_mem',
mul_mem' := hs.symm ▸ S.mul_mem' }
```
and then finally define:
```lean
def mrange (f : M →* N) : submonoid N :=
((⊤ : submonoid M).map f).copy (set.range f) set.image_univ.symm
```
-/
library_note "range copy pattern"
/-- The range of a monoid homomorphism is a submonoid. See Note [range copy pattern]. -/
@[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."]
def mrange (f : M →* N) : submonoid N :=
((⊤ : submonoid M).map f).copy (set.range f) set.image_univ.symm
@[simp, to_additive]
lemma coe_mrange (f : M →* N) :
(f.mrange : set N) = set.range f :=
rfl
@[simp, to_additive] lemma mem_mrange {f : M →* N} {y : N} :
y ∈ f.mrange ↔ ∃ x, f x = y :=
iff.rfl
@[to_additive] lemma mrange_eq_map (f : M →* N) : f.mrange = (⊤ : submonoid M).map f :=
by ext; simp
@[to_additive]
lemma map_mrange (g : N →* P) (f : M →* N) : f.mrange.map g = (g.comp f).mrange :=
by simpa only [mrange_eq_map] using (⊤ : submonoid M).map_map g f
@[to_additive]
lemma mrange_top_iff_surjective {N} [mul_one_class N] {f : M →* N} :
f.mrange = (⊤ : submonoid N) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_mrange, coe_top]) set.range_iff_surjective
/-- The range of a surjective monoid hom is the whole of the codomain. -/
@[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."]
lemma mrange_top_of_surjective {N} [mul_one_class N] (f : M →* N) (hf : function.surjective f) :
f.mrange = (⊤ : submonoid N) :=
mrange_top_iff_surjective.2 hf
@[to_additive]
lemma mclosure_preimage_le (f : M →* N) (s : set N) :
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 monoid hom of the submonoid generated by a set equals the submonoid generated
by the image of the set. -/
@[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals
the `add_submonoid` generated by the image of the set."]
lemma map_mclosure (f : M →* N) (s : set M) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(mclosure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
/-- Restriction of a monoid hom to a submonoid of the domain. -/
@[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."]
def mrestrict {N : Type*} [mul_one_class N] (f : M →* N) (S : submonoid M) : S →* N :=
f.comp S.subtype
@[simp, to_additive]
lemma mrestrict_apply {N : Type*} [mul_one_class N] (f : M →* N) (x : S) : f.mrestrict S x = f x :=
rfl
/-- Restriction of a monoid hom to a submonoid of the codomain. -/
@[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain.", simps]
def cod_mrestrict (f : M →* N) (S : submonoid N) (h : ∀ x, f x ∈ S) : M →* S :=
{ to_fun := λ n, ⟨f n, h n⟩,
map_one' := subtype.eq f.map_one,
map_mul' := λ x y, subtype.eq (f.map_mul x y) }
/-- Restriction of a monoid hom to its range interpreted as a submonoid. -/
@[to_additive "Restriction of an `add_monoid` hom to its range interpreted as a submonoid."]
def mrange_restrict {N} [mul_one_class N] (f : M →* N) : M →* f.mrange :=
f.cod_mrestrict f.mrange $ λ x, ⟨x, rfl⟩
@[simp, to_additive]
lemma coe_mrange_restrict {N} [mul_one_class N] (f : M →* N) (x : M) :
(f.mrange_restrict x : N) = f x :=
rfl
end monoid_hom
namespace submonoid
open monoid_hom
@[to_additive]
lemma mrange_inl : (inl M N).mrange = prod ⊤ ⊥ :=
by simpa only [mrange_eq_map] using map_inl ⊤
@[to_additive]
lemma mrange_inr : (inr M N).mrange = prod ⊥ ⊤ :=
by simpa only [mrange_eq_map] using map_inr ⊤
@[to_additive]
lemma mrange_inl' : (inl M N).mrange = comap (snd M N) ⊥ := mrange_inl.trans (top_prod _)
@[to_additive]
lemma mrange_inr' : (inr M N).mrange = comap (fst M N) ⊥ := mrange_inr.trans (prod_top _)
@[simp, to_additive]
lemma mrange_fst : (fst M N).mrange = ⊤ :=
(fst M N).mrange_top_of_surjective $ @prod.fst_surjective _ _ ⟨1⟩
@[simp, to_additive]
lemma mrange_snd : (snd M N).mrange = ⊤ :=
(snd M N).mrange_top_of_surjective $ @prod.snd_surjective _ _ ⟨1⟩
@[simp, to_additive]
lemma mrange_inl_sup_mrange_inr : (inl M N).mrange ⊔ (inr M N).mrange = ⊤ :=
by simp only [mrange_inl, mrange_inr, prod_bot_sup_bot_prod, top_prod_top]
/-- The monoid hom associated to an inclusion of submonoids. -/
@[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."]
def inclusion {S T : submonoid M} (h : S ≤ T) : S →* T :=
S.subtype.cod_mrestrict _ (λ x, h x.2)
@[simp, to_additive]
lemma range_subtype (s : submonoid M) : s.subtype.mrange = s :=
set_like.coe_injective $ (coe_mrange _).trans $ subtype.range_coe
@[to_additive] lemma eq_top_iff' : S = ⊤ ↔ ∀ x : M, x ∈ S :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
@[to_additive] lemma eq_bot_iff_forall : S = ⊥ ↔ ∀ x ∈ S, x = (1 : M) :=
begin
split,
{ intros h x x_in,
rwa [h, mem_bot] at x_in },
{ intros h,
ext x,
rw mem_bot,
exact ⟨h x, by { rintros rfl, exact S.one_mem }⟩ },
end
@[to_additive] lemma nontrivial_iff_exists_ne_one (S : submonoid M) :
nontrivial S ↔ ∃ x ∈ S, x ≠ (1:M) :=
begin
split,
{ introI h,
rcases exists_ne (1 : S) with ⟨⟨h, h_in⟩, h_ne⟩,
use [h, h_in],
intro hyp,
apply h_ne,
simpa [hyp] },
{ rintros ⟨x, x_in, hx⟩,
apply nontrivial_of_ne (⟨x, x_in⟩ : S) 1,
intro hyp,
apply hx,
simpa [has_one.one] using hyp },
end
/-- A submonoid is either the trivial submonoid or nontrivial. -/
@[to_additive] lemma bot_or_nontrivial (S : submonoid M) : S = ⊥ ∨ nontrivial S :=
begin
classical,
by_cases h : ∀ x ∈ S, x = (1 : M),
{ left,
exact S.eq_bot_iff_forall.mpr h },
{ right,
push_neg at h,
simpa [nontrivial_iff_exists_ne_one] using h },
end
/-- A submonoid is either the trivial submonoid or contains a nonzero element. -/
@[to_additive] lemma bot_or_exists_ne_one (S : submonoid M) : S = ⊥ ∨ ∃ x ∈ S, x ≠ (1:M) :=
begin
convert S.bot_or_nontrivial,
rw nontrivial_iff_exists_ne_one
end
end submonoid
namespace mul_equiv
variables {S} {T : submonoid M}
/-- Makes the identity isomorphism from a proof that two submonoids of a multiplicative
monoid are equal. -/
@[to_additive "Makes the identity additive isomorphism from a proof two
submonoids of an additive monoid are equal."]
def submonoid_congr (h : S = T) : S ≃* T :=
{ map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
-- this name is primed so that the version to `f.range` instead of `f.mrange` can be unprimed.
/-- A monoid homomorphism `f : M →* N` with a left-inverse `g : N → M` defines a multiplicative
equivalence between `M` and `f.mrange`.
This is a bidirectional version of `monoid_hom.mrange_restrict`. -/
@[to_additive /-"
An additive monoid homomorphism `f : M →+ N` with a left-inverse `g : N → M` defines an additive
equivalence between `M` and `f.mrange`.
This is a bidirectional version of `add_monoid_hom.mrange_restrict`. "-/, simps {simp_rhs := tt}]
def of_left_inverse' (f : M →* N) {g : N → M} (h : function.left_inverse g f) : M ≃* f.mrange :=
{ to_fun := f.mrange_restrict,
inv_fun := g ∘ f.mrange.subtype,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := monoid_hom.mem_mrange.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
.. f.mrange_restrict }
end mul_equiv
/-! ### Actions by `submonoid`s
These instances tranfer the action by an element `m : M` of a monoid `M` written as `m • a` onto the
action by an element `s : S` of a submonoid `S : submonoid M` such that `s • a = (s : M) • a`.
These instances work particularly well in conjunction with `monoid.to_mul_action`, enabling
`s • m` as an alias for `↑s * m`.
-/
section actions
namespace submonoid
variables {M' : Type*} {α β : Type*} [monoid M']
/-- The action by a submonoid is the action by the underlying monoid. -/
@[to_additive /-"The additive action by an add_submonoid is the action by the underlying
add_monoid. "-/]
instance [mul_action M' α] (S : submonoid M') : mul_action S α :=
mul_action.comp_hom _ S.subtype
@[to_additive]
lemma smul_def [mul_action M' α] {S : submonoid M'} (g : S) (m : α) : g • m = (g : M') • m := rfl
/-- The action by a submonoid is the action by the underlying monoid. -/
instance [add_monoid α] [distrib_mul_action M' α] (S : submonoid M') : distrib_mul_action S α :=
distrib_mul_action.comp_hom _ S.subtype
@[to_additive]
instance smul_comm_class_left
[mul_action M' β] [has_scalar α β] [smul_comm_class M' α β] (S : submonoid M') :
smul_comm_class S α β :=
⟨λ a, (smul_comm (a : M') : _)⟩
@[to_additive]
instance smul_comm_class_right
[has_scalar α β] [mul_action M' β] [smul_comm_class α M' β] (S : submonoid M') :
smul_comm_class α S β :=
⟨λ a s, (smul_comm a (s : M') : _)⟩
/-- Note that this provides `is_scalar_tower S M' M'` which is needed by `smul_mul_assoc`. -/
instance
[has_scalar α β] [mul_action M' α] [mul_action M' β] [is_scalar_tower M' α β] (S : submonoid M') :
is_scalar_tower S α β :=
⟨λ a, (smul_assoc (a : M') : _)⟩
example {S : submonoid M'} : is_scalar_tower S M' M' := by apply_instance
instance [mul_action M' α] [has_faithful_scalar M' α] (S : submonoid M') :
has_faithful_scalar S α :=
{ eq_of_smul_eq_smul := λ x y h, subtype.ext (eq_of_smul_eq_smul h) }
end submonoid
end actions
|
82edf0c6c07eda1c1c4bf7d35572985714111056 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /hott/algebra/category/constructions/comma.hlean | a10aad4a21d35cb18729069092e5293de5a2fbf2 | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,843 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Comma category
-/
import ..functor ..strict ..category
open eq functor equiv sigma sigma.ops is_trunc iso is_equiv
namespace category
structure comma_object {A B C : Precategory} (S : A ⇒ C) (T : B ⇒ C) :=
(a : A)
(b : B)
(f : S a ⟶ T b)
abbreviation ob1 [unfold 6] := @comma_object.a
abbreviation ob2 [unfold 6] := @comma_object.b
abbreviation mor [unfold 6] := @comma_object.f
variables {A B C : Precategory} (S : A ⇒ C) (T : B ⇒ C)
definition comma_object_sigma_char : (Σ(a : A) (b : B), S a ⟶ T b) ≃ comma_object S T :=
begin
fapply equiv.MK,
{ intro u, exact comma_object.mk u.1 u.2.1 u.2.2},
{ intro x, cases x with a b f, exact ⟨a, b, f⟩},
{ intro x, cases x, reflexivity},
{ intro u, cases u with u1 u2, cases u2, reflexivity},
end
theorem is_trunc_comma_object (n : trunc_index) [HA : is_trunc n A]
[HB : is_trunc n B] [H : Π(s d : C), is_trunc n (hom s d)] : is_trunc n (comma_object S T) :=
by apply is_trunc_equiv_closed;apply comma_object_sigma_char
variables {S T}
definition comma_object_eq' {x y : comma_object S T} (p : ob1 x = ob1 y) (q : ob2 x = ob2 y)
(r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : x = y :=
begin
cases x with a b f, cases y with a' b' f', cases p, cases q,
esimp [ap011,congr,ap,subst] at r,
eapply (idp_rec_on r), reflexivity
end
--TODO: remove. This is a different version where Hq is not in square brackets
axiom eq_comp_inverse_of_comp_eq' {ob : Type} {C : precategory ob} {d c b : ob} {r : hom c d}
{q : hom b c} {x : hom b d} {Hq : is_iso q} (p : r ∘ q = x) : r = x ∘ q⁻¹ʰ
-- := sorry --eq_inverse_comp_of_comp_eq p
definition comma_object_eq {x y : comma_object S T} (p : ob1 x = ob1 y) (q : ob2 x = ob2 y)
(r : T (hom_of_eq q) ∘ mor x ∘ S (inv_of_eq p) = mor y) : x = y :=
begin
cases x with a b f, cases y with a' b' f', cases p, cases q,
have r' : f = f',
begin
rewrite [▸* at r, -r, respect_id, id_left, respect_inv'],
apply eq_comp_inverse_of_comp_eq',
rewrite [respect_id,id_right]
end,
rewrite r'
end
definition ap_ob1_comma_object_eq' (x y : comma_object S T) (p : ob1 x = ob1 y) (q : ob2 x = ob2 y)
(r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y)
: ap ob1 (comma_object_eq' p q r) = p :=
begin
cases x with a b f, cases y with a' b' f', cases p, cases q,
eapply (idp_rec_on r), reflexivity
end
definition ap_ob2_comma_object_eq' (x y : comma_object S T) (p : ob1 x = ob1 y) (q : ob2 x = ob2 y)
(r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y)
: ap ob2 (comma_object_eq' p q r) = q :=
begin
cases x with a b f, cases y with a' b' f', cases p, cases q,
eapply (idp_rec_on r), reflexivity
end
structure comma_morphism (x y : comma_object S T) :=
mk' ::
(g : ob1 x ⟶ ob1 y)
(h : ob2 x ⟶ ob2 y)
(p : T h ∘ mor x = mor y ∘ S g)
(p' : mor y ∘ S g = T h ∘ mor x)
abbreviation mor1 := @comma_morphism.g
abbreviation mor2 := @comma_morphism.h
abbreviation coh := @comma_morphism.p
abbreviation coh' := @comma_morphism.p'
protected definition comma_morphism.mk [constructor] [reducible]
{x y : comma_object S T} (g h p) : comma_morphism x y :=
comma_morphism.mk' g h p p⁻¹
variables (x y z w : comma_object S T)
definition comma_morphism_sigma_char :
(Σ(g : ob1 x ⟶ ob1 y) (h : ob2 x ⟶ ob2 y), T h ∘ mor x = mor y ∘ S g) ≃ comma_morphism x y :=
begin
fapply equiv.MK,
{ intro u, exact (comma_morphism.mk u.1 u.2.1 u.2.2)},
{ intro f, cases f with g h p p', exact ⟨g, h, p⟩},
{ intro f, cases f with g h p p', esimp,
apply ap (comma_morphism.mk' g h p), apply is_hprop.elim},
{ intro u, cases u with u1 u2, cases u2 with u2 u3, reflexivity},
end
theorem is_trunc_comma_morphism (n : trunc_index) [H1 : is_trunc n (ob1 x ⟶ ob1 y)]
[H2 : is_trunc n (ob2 x ⟶ ob2 y)] [Hp : Πm1 m2, is_trunc n (T m2 ∘ mor x = mor y ∘ S m1)]
: is_trunc n (comma_morphism x y) :=
by apply is_trunc_equiv_closed; apply comma_morphism_sigma_char
variables {x y z w}
definition comma_morphism_eq {f f' : comma_morphism x y}
(p : mor1 f = mor1 f') (q : mor2 f = mor2 f') : f = f' :=
begin
cases f with g h p₁ p₁', cases f' with g' h' p₂ p₂', cases p, cases q,
apply ap011 (comma_morphism.mk' g' h'),
apply is_hprop.elim,
apply is_hprop.elim
end
definition comma_compose (g : comma_morphism y z) (f : comma_morphism x y) : comma_morphism x z :=
comma_morphism.mk
(mor1 g ∘ mor1 f)
(mor2 g ∘ mor2 f)
(by rewrite [+respect_comp,-assoc,coh,assoc,coh,-assoc])
local infix `∘∘`:60 := comma_compose
definition comma_id : comma_morphism x x :=
comma_morphism.mk id id (by rewrite [+respect_id,id_left,id_right])
theorem comma_assoc (h : comma_morphism z w) (g : comma_morphism y z) (f : comma_morphism x y) :
h ∘∘ (g ∘∘ f) = (h ∘∘ g) ∘∘ f :=
comma_morphism_eq !assoc !assoc
theorem comma_id_left (f : comma_morphism x y) : comma_id ∘∘ f = f :=
comma_morphism_eq !id_left !id_left
theorem comma_id_right (f : comma_morphism x y) : f ∘∘ comma_id = f :=
comma_morphism_eq !id_right !id_right
variables (S T)
definition comma_category [constructor] : Precategory :=
precategory.MK (comma_object S T)
comma_morphism
(λa b, !is_trunc_comma_morphism)
(@comma_compose _ _ _ _ _)
(@comma_id _ _ _ _ _)
(@comma_assoc _ _ _ _ _)
(@comma_id_left _ _ _ _ _)
(@comma_id_right _ _ _ _ _)
--TODO: this definition doesn't use category structure of A and B
definition strict_precategory_comma [HA : strict_precategory A] [HB : strict_precategory B] :
strict_precategory (comma_object S T) :=
strict_precategory.mk (comma_category S T) !is_trunc_comma_object
/-
--set_option pp.notation false
definition is_univalent_comma (HA : is_univalent A) (HB : is_univalent B)
: is_univalent (comma_category S T) :=
begin
intros c d,
fapply adjointify,
{ intro i, cases i with f s, cases s with g l r, cases f with fA fB fp, cases g with gA gB gp,
esimp at *, fapply comma_object_eq,
{apply iso_of_eq⁻¹ᶠ, exact (iso.MK fA gA (ap mor1 l) (ap mor1 r))},
{apply iso_of_eq⁻¹ᶠ, exact (iso.MK fB gB (ap mor2 l) (ap mor2 r))},
{ apply sorry /-rewrite hom_of_eq_eq_of_iso,-/ }},
{ apply sorry},
{ apply sorry},
end
-/
end category
|
94184d697d00c5d4a4032dc26c3f917a7a2576aa | e94d3f31e48d06d252ee7307fe71efe1d500f274 | /library/theories/measure_theory/sigma_algebra.lean | 008effcd551ba5f964a001de15d18a512ac7965a | [
"Apache-2.0"
] | permissive | GallagherCommaJack/lean | e4471240a069d82f97cb361d2bf1a029de3f4256 | 226f8bafeb9baaa5a2ac58000c83d6beb29991e2 | refs/heads/master | 1,610,725,100,482 | 1,459,194,829,000 | 1,459,195,377,000 | 55,377,224 | 0 | 0 | null | 1,459,731,701,000 | 1,459,731,700,000 | null | UTF-8 | Lean | false | false | 9,323 | lean | /-
Copyright (c) 2016 Jacob Gross. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jacob Gross, Jeremy Avigad
Sigma algebras.
-/
import data.set data.nat theories.topology.basic
open eq.ops set nat
structure sigma_algebra [class] (X : Type) :=
(sets : set (set X))
(univ_mem_sets : univ ∈ sets)
(comp_mem_sets : ∀ {s : set X}, s ∈ sets → (-s ∈ sets))
(cUnion_mem_sets : ∀ {s : ℕ → set X}, (∀ i, s i ∈ sets) → (⋃ i, s i) ∈ sets)
/- Closure properties -/
namespace measure_theory
open sigma_algebra
variables {X : Type} [sigma_algebra X]
definition measurable (t : set X) : Prop := t ∈ sets X
theorem measurable_univ : measurable (@univ X) :=
univ_mem_sets X
theorem measurable_compl {s : set X} (H : measurable s) : measurable (-s) :=
comp_mem_sets H
theorem measurable_of_measurable_compl {s : set X} (H : measurable (-s)) : measurable s :=
!compl_compl ▸ measurable_compl H
theorem measurable_empty : measurable (∅ : set X) :=
compl_univ ▸ measurable_compl measurable_univ
theorem measurable_cUnion {s : ℕ → set X} (H : ∀ i, measurable (s i)) :
measurable (⋃ i, s i) :=
cUnion_mem_sets H
theorem measurable_cInter {s : ℕ → set X} (H : ∀ i, measurable (s i)) :
measurable (⋂ i, s i) :=
have ∀ i, measurable (-(s i)), from take i, measurable_compl (H i),
have measurable (-(⋃ i, -(s i))), from measurable_compl (measurable_cUnion this),
show measurable (⋂ i, s i), by rewrite Inter_eq_comp_Union_comp; apply this
theorem measurable_union {s t : set X} (Hs : measurable s) (Ht : measurable t) :
measurable (s ∪ t) :=
have ∀ i, measurable (bin_ext s t i), by intro i; cases i; exact Hs; exact Ht,
show measurable (s ∪ t), by rewrite -Union_bin_ext; exact measurable_cUnion this
theorem measurable_inter {s t : set X} (Hs : measurable s) (Ht : measurable t) :
measurable (s ∩ t) :=
have ∀ i, measurable (bin_ext s t i), by intro i; cases i; exact Hs; exact Ht,
show measurable (s ∩ t), by rewrite -Inter_bin_ext; exact measurable_cInter this
theorem measurable_diff {s t : set X} (Hs : measurable s) (Ht : measurable t) :
measurable (s \ t) :=
measurable_inter Hs (measurable_compl Ht)
theorem measurable_insert {x : X} {s : set X} (Hx : measurable '{x}) (Hs : measurable s) :
measurable (insert x s) :=
!insert_eq⁻¹ ▸ measurable_union Hx Hs
end measure_theory
/-
-- Properties of sigma algebras
-/
namespace sigma_algebra
open measure_theory
variable {X : Type}
protected theorem eq {M N : sigma_algebra X} (H : @sets X M = @sets X N) :
M = N :=
by cases M; cases N; cases H; apply rfl
/- sigma algebra generated by a set -/
inductive sets_generated_by (G : set (set X)) : set X → Prop :=
| generators_mem : ∀ ⦃s : set X⦄, s ∈ G → sets_generated_by G s
| univ_mem : sets_generated_by G univ
| comp_mem : ∀ ⦃s : set X⦄, sets_generated_by G s → sets_generated_by G (-s)
| cUnion_mem : ∀ ⦃s : ℕ → set X⦄, (∀ i, sets_generated_by G (s i)) →
sets_generated_by G (⋃ i, s i)
protected definition generated_by {X : Type} (G : set (set X)) : sigma_algebra X :=
⦃sigma_algebra,
sets := sets_generated_by G,
univ_mem_sets := sets_generated_by.univ_mem G,
comp_mem_sets := sets_generated_by.comp_mem ,
cUnion_mem_sets := sets_generated_by.cUnion_mem ⦄
theorem sets_generated_by_initial {G : set (set X)} {M : sigma_algebra X} (H : G ⊆ @sets _ M) :
sets_generated_by G ⊆ @sets _ M :=
begin
intro s Hs,
induction Hs with s sG s Hs ssX s Hs sisX,
{exact H sG},
{exact measurable_univ},
{exact measurable_compl ssX},
exact measurable_cUnion sisX
end
theorem measurable_generated_by {G : set (set X)} :
∀₀ s ∈ G, @measurable _ (sigma_algebra.generated_by G) s :=
λ s H, sets_generated_by.generators_mem H
/- The collection of sigma algebras forms a complete lattice. -/
protected definition le (M N : sigma_algebra X) : Prop := @sets _ M ⊆ @sets _ N
definition sigma_algebra_has_le [instance] :
has_le (sigma_algebra X) :=
has_le.mk sigma_algebra.le
protected theorem le_refl (M : sigma_algebra X) : M ≤ M := subset.refl (@sets _ M)
protected theorem le_trans (M N L : sigma_algebra X) : M ≤ N → N ≤ L → M ≤ L :=
assume H1, assume H2,
subset.trans H1 H2
protected theorem le_antisymm (M N : sigma_algebra X) : M ≤ N → N ≤ M → M = N :=
assume H1, assume H2,
sigma_algebra.eq (subset.antisymm H1 H2)
protected theorem generated_by_initial {G : set (set X)} {M : sigma_algebra X} (H : G ⊆ @sets X M) :
sigma_algebra.generated_by G ≤ M :=
sets_generated_by_initial H
protected definition inf (M N : sigma_algebra X) : sigma_algebra X :=
⦃sigma_algebra,
sets := @sets X M ∩ @sets X N,
univ_mem_sets := abstract and.intro (@measurable_univ X M) (@measurable_univ X N) end,
comp_mem_sets := abstract take s, assume Hs, and.intro
(@measurable_compl X M s (and.elim_left Hs))
(@measurable_compl X N s (and.elim_right Hs)) end,
cUnion_mem_sets := abstract take s, assume Hs, and.intro
(@measurable_cUnion X M s (λ i, and.elim_left (Hs i)))
(@measurable_cUnion X N s (λ i, and.elim_right (Hs i))) end⦄
protected theorem inf_le_left (M N : sigma_algebra X) : sigma_algebra.inf M N ≤ M :=
λ s, !inter_subset_left
protected theorem inf_le_right (M N : sigma_algebra X) : sigma_algebra.inf M N ≤ N :=
λ s, !inter_subset_right
protected theorem le_inf (M N L : sigma_algebra X) (H1 : L ≤ M) (H2 : L ≤ N) :
L ≤ sigma_algebra.inf M N :=
λ s H, and.intro (H1 s H) (H2 s H)
protected definition Inf (MS : set (sigma_algebra X)) : sigma_algebra X :=
⦃sigma_algebra,
sets := ⋂ M ∈ MS, @sets _ M,
univ_mem_sets := abstract take M, assume HM, @measurable_univ X M end,
comp_mem_sets := abstract take s, assume Hs, take M, assume HM,
measurable_compl (Hs M HM) end,
cUnion_mem_sets := abstract take s, assume Hs, take M, assume HM,
measurable_cUnion (λ i, Hs i M HM) end
⦄
protected theorem Inf_le {M : sigma_algebra X} {MS : set (sigma_algebra X)} (MMS : M ∈ MS) :
sigma_algebra.Inf MS ≤ M :=
bInter_subset_of_mem MMS
protected theorem le_Inf {M : sigma_algebra X} {MS : set (sigma_algebra X)} (H : ∀₀ N ∈ MS, M ≤ N) :
M ≤ sigma_algebra.Inf MS :=
take s, assume Hs : s ∈ @sets _ M,
take N, assume NMS : N ∈ MS,
show s ∈ @sets _ N, from H NMS s Hs
protected definition sup (M N : sigma_algebra X) : sigma_algebra X :=
sigma_algebra.generated_by (@sets _ M ∪ @sets _ N)
protected theorem le_sup_left (M N : sigma_algebra X) : M ≤ sigma_algebra.sup M N :=
take s, assume Hs : s ∈ @sets _ M,
measurable_generated_by (or.inl Hs)
protected theorem le_sup_right (M N : sigma_algebra X) : N ≤ sigma_algebra.sup M N :=
take s, assume Hs : s ∈ @sets _ N,
measurable_generated_by (or.inr Hs)
protected theorem sup_le {M N L : sigma_algebra X} (H1 : M ≤ L) (H2 : N ≤ L) :
sigma_algebra.sup M N ≤ L :=
have @sets _ M ∪ @sets _ N ⊆ @sets _ L, from union_subset H1 H2,
sets_generated_by_initial this
protected definition Sup (MS : set (sigma_algebra X)) : sigma_algebra X :=
sigma_algebra.generated_by (⋃ M ∈ MS, @sets _ M)
protected theorem le_Sup {M : sigma_algebra X} {MS : set (sigma_algebra X)} (MMS : M ∈ MS) :
M ≤ sigma_algebra.Sup MS :=
take s, assume Hs : s ∈ @sets _ M,
measurable_generated_by (mem_bUnion MMS Hs)
protected theorem Sup_le {N : sigma_algebra X} {MS : set (sigma_algebra X)} (H : ∀₀ M ∈ MS, M ≤ N) :
sigma_algebra.Sup MS ≤ N :=
have (⋃ M ∈ MS, @sets _ M) ⊆ @sets _ N, from bUnion_subset H,
sets_generated_by_initial this
protected definition complete_lattice [trans_instance] :
complete_lattice (sigma_algebra X) :=
⦃complete_lattice,
le := sigma_algebra.le,
le_refl := sigma_algebra.le_refl,
le_trans := sigma_algebra.le_trans,
le_antisymm := sigma_algebra.le_antisymm,
inf := sigma_algebra.inf,
sup := sigma_algebra.sup,
inf_le_left := sigma_algebra.inf_le_left,
inf_le_right := sigma_algebra.inf_le_right,
le_inf := sigma_algebra.le_inf,
le_sup_left := sigma_algebra.le_sup_left,
le_sup_right := sigma_algebra.le_sup_right,
sup_le := @sigma_algebra.sup_le X,
Inf := sigma_algebra.Inf,
Sup := sigma_algebra.Sup,
Inf_le := @sigma_algebra.Inf_le X,
le_Inf := @sigma_algebra.le_Inf X,
le_Sup := @sigma_algebra.le_Sup X,
Sup_le := @sigma_algebra.Sup_le X⦄
end sigma_algebra
/- Borel sets -/
namespace measure_theory
section
open topology
variables (X : Type) [topology X]
definition borel_algebra : sigma_algebra X :=
sigma_algebra.generated_by (opens X)
variable {X}
definition borel (s : set X) : Prop := @measurable _ (borel_algebra X) s
theorem borel_of_open {s : set X} (H : Open s) : borel s :=
sigma_algebra.measurable_generated_by H
theorem borel_of_closed {s : set X} (H : closed s) : borel s :=
have borel (-s), from borel_of_open H,
@measurable_of_measurable_compl _ (borel_algebra X) _ this
end
end measure_theory
|
00d5997ab90280a104710fdaa530d47a7dadc0e4 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/logic/function/iterate.lean | 06fb6d200f5d8839feba052f0de32764bc87b38f | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 5,574 | 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 logic.function.conjugate
/-!
# Iterations of a function
In this file we prove simple properties of `nat.iterate f n` a.k.a. `f^[n]`:
* `iterate_zero`, `iterate_succ`, `iterate_succ'`, `iterate_add`, `iterate_mul`:
formulas for `f^[0]`, `f^[n+1]` (two versions), `f^[n+m]`, and `f^[n*m]`;
* `iterate_id` : `id^[n]=id`;
* `injective.iterate`, `surjective.iterate`, `bijective.iterate` :
iterates of an injective/surjective/bijective function belong to the same class;
* `left_inverse.iterate`, `right_inverse.iterate`, `commute.iterate_left`, `comute.iterate_right`,
`commute.iterate_iterate`:
some properties of pairs of functions survive under iterations
* `iterate_fixed`, `semiconj.iterate_*`, `semiconj₂.iterate`:
if `f` fixes a point (resp., semiconjugates unary/binary operarations), then so does `f^[n]`.
-/
universes u v
variables {α : Type u} {β : Type v}
namespace function
variable (f : α → α)
@[simp] theorem iterate_zero : f^[0] = id := rfl
theorem iterate_zero_apply (x : α) : f^[0] x = x := rfl
@[simp] theorem iterate_succ (n : ℕ) : f^[n.succ] = (f^[n]) ∘ f := rfl
theorem iterate_succ_apply (n : ℕ) (x : α) : f^[n.succ] x = (f^[n]) (f x) := rfl
@[simp] theorem iterate_id (n : ℕ) : (id : α → α)^[n] = id :=
nat.rec_on n rfl $ λ n ihn, by rw [iterate_succ, ihn, comp.left_id]
theorem iterate_add : ∀ (m n : ℕ), f^[m + n] = (f^[m]) ∘ (f^[n])
| m 0 := rfl
| m (nat.succ n) := by rw [iterate_succ, iterate_succ, iterate_add]
theorem iterate_add_apply (m n : ℕ) (x : α) : f^[m + n] x = (f^[m] (f^[n] x)) :=
by rw iterate_add
@[simp] theorem iterate_one : f^[1] = f := funext $ λ a, rfl
lemma iterate_mul (m : ℕ) : ∀ n, f^[m * n] = (f^[m]^[n])
| 0 := by simp only [nat.mul_zero, iterate_zero]
| (n + 1) := by simp only [nat.mul_succ, nat.mul_one, iterate_one, iterate_add, iterate_mul n]
variable {f}
theorem iterate_fixed {x} (h : f x = x) (n : ℕ) : f^[n] x = x :=
nat.rec_on n rfl $ λ n ihn, by rw [iterate_succ_apply, h, ihn]
theorem injective.iterate (Hinj : injective f) (n : ℕ) : injective (f^[n]) :=
nat.rec_on n injective_id $ λ n ihn, ihn.comp Hinj
theorem surjective.iterate (Hsurj : surjective f) (n : ℕ) : surjective (f^[n]) :=
nat.rec_on n surjective_id $ λ n ihn, ihn.comp Hsurj
theorem bijective.iterate (Hbij : bijective f) (n : ℕ) : bijective (f^[n]) :=
⟨Hbij.1.iterate n, Hbij.2.iterate n⟩
namespace semiconj
lemma iterate_right {f : α → β} {ga : α → α} {gb : β → β} (h : semiconj f ga gb) (n : ℕ) :
semiconj f (ga^[n]) (gb^[n]) :=
nat.rec_on n id_right $ λ n ihn, ihn.comp_right h
lemma iterate_left {g : ℕ → α → α} (H : ∀ n, semiconj f (g n) (g $ n + 1)) (n k : ℕ) :
semiconj (f^[n]) (g k) (g $ n + k) :=
begin
induction n with n ihn generalizing k,
{ rw [nat.zero_add], exact id_left },
{ rw [nat.succ_eq_add_one, nat.add_right_comm, nat.add_assoc],
exact (H k).comp_left (ihn (k + 1)) }
end
end semiconj
namespace commute
variable {g : α → α}
lemma iterate_right (h : commute f g) (n : ℕ) : commute f (g^[n]) := h.iterate_right n
lemma iterate_left (h : commute f g) (n : ℕ) : commute (f^[n]) g := (h.symm.iterate_right n).symm
lemma iterate_iterate (h : commute f g) (m n : ℕ) : commute (f^[m]) (g^[n]) :=
(h.iterate_left m).iterate_right n
lemma iterate_eq_of_map_eq (h : commute f g) (n : ℕ) {x} (hx : f x = g x) : f^[n] x = (g^[n]) x :=
nat.rec_on n rfl $ λ n ihn,
by simp only [iterate_succ_apply, hx, (h.iterate_left n).eq, ihn, ((refl g).iterate_right n).eq]
lemma comp_iterate (h : commute f g) (n : ℕ) : (f ∘ g)^[n] = (f^[n]) ∘ (g^[n]) :=
begin
induction n with n ihn, { refl },
funext x,
simp only [ihn, (h.iterate_right n).eq, iterate_succ, comp_app]
end
variable (f)
lemma iterate_self (n : ℕ) : commute (f^[n]) f := (refl f).iterate_left n
lemma self_iterate (n : ℕ) : commute f (f^[n]) := (refl f).iterate_right n
lemma iterate_iterate_self (m n : ℕ) : commute (f^[m]) (f^[n]) := (refl f).iterate_iterate m n
end commute
lemma semiconj₂.iterate {f : α → α} {op : α → α → α} (hf : semiconj₂ f op op) (n : ℕ) :
semiconj₂ (f^[n]) op op :=
nat.rec_on n (semiconj₂.id_left op) (λ n ihn, ihn.comp hf)
variable (f)
theorem iterate_succ' (n : ℕ) : f^[n.succ] = f ∘ (f^[n]) :=
by rw [iterate_succ, (commute.self_iterate f n).comp_eq]
theorem iterate_succ_apply' (n : ℕ) (x : α) : f^[n.succ] x = f (f^[n] x) :=
by rw [iterate_succ']
theorem iterate_pred_comp_of_pos {n : ℕ} (hn : 0 < n) : f^[n.pred] ∘ f = (f^[n]) :=
by rw [← iterate_succ, nat.succ_pred_eq_of_pos hn]
theorem comp_iterate_pred_of_pos {n : ℕ} (hn : 0 < n) : f ∘ (f^[n.pred]) = (f^[n]) :=
by rw [← iterate_succ', nat.succ_pred_eq_of_pos hn]
variable {f}
theorem left_inverse.iterate {g : α → α} (hg : left_inverse g f) (n : ℕ) :
left_inverse (g^[n]) (f^[n]) :=
nat.rec_on n (λ _, rfl) $ λ n ihn, by { rw [iterate_succ', iterate_succ], exact ihn.comp hg }
theorem right_inverse.iterate {g : α → α} (hg : right_inverse g f) (n : ℕ) :
right_inverse (g^[n]) (f^[n]) :=
hg.iterate n
lemma iterate_comm (f : α → α) (m n : ℕ) : f^[n]^[m] = (f^[m]^[n]) :=
(iterate_mul _ _ _).symm.trans (eq.trans (by rw nat.mul_comm) (iterate_mul _ _ _))
lemma iterate_commute (m n : ℕ) : commute (λ f : α → α, f^[m]) (λ f, f^[n]) :=
λ f, iterate_comm f m n
end function
|
4dfa3ba5195c4c5002454bb7e7eafcb29e88bce7 | ad0c7d243dc1bd563419e2767ed42fb323d7beea | /data/nat/choose.lean | 67cc53c63472dd398e6d2e80e3bd443749bc8772 | [
"Apache-2.0"
] | permissive | sebzim4500/mathlib | e0b5a63b1655f910dee30badf09bd7e191d3cf30 | 6997cafbd3a7325af5cb318561768c316ceb7757 | refs/heads/master | 1,585,549,958,618 | 1,538,221,723,000 | 1,538,221,723,000 | 150,869,076 | 0 | 0 | Apache-2.0 | 1,538,229,323,000 | 1,538,229,323,000 | null | UTF-8 | Lean | false | false | 3,708 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
Mostly based on Jeremy Avigad's choose file in lean 2
-/
import data.nat.basic
open nat
def choose : ℕ → ℕ → ℕ
| _ 0 := 1
| 0 (k + 1) := 0
| (n + 1) (k + 1) := choose n k + choose n (succ k)
@[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl
@[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl
lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl
lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0
| _ 0 hk := absurd hk dec_trivial
| 0 (k + 1) hk := choose_zero_succ _
| (n + 1) (k + 1) hk :=
have hnk : n < k, from lt_of_succ_lt_succ hk,
have hnk1 : n < k + 1, from lt_of_succ_lt hk,
by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1]
@[simp] lemma choose_self (n : ℕ) : choose n n = 1 :=
by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)]
@[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 :=
choose_eq_zero_of_lt (lt_succ_self _)
@[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n :=
by induction n; simp [*, choose]
lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k
| 0 _ hk := by rw [eq_zero_of_le_zero hk]; exact dec_trivial
| (n + 1) 0 hk := by simp; exact dec_trivial
| (n + 1) (k + 1) hk := by rw choose_succ_succ;
exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (zero_le _)
lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k
| 0 0 := dec_trivial
| 0 (k + 1) := by simp [choose]
| (n + 1) 0 := by simp
| (n + 1) (k + 1) :=
by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ,
←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul]
lemma choose_mul_fact_mul_fact : ∀ {n k}, k ≤ n → choose n k * fact k * fact (n - k) = fact n
| 0 _ hk := by simp [eq_zero_of_le_zero hk]
| (n + 1) 0 hk := by simp
| (n + 1) (succ k) hk :=
begin
cases lt_or_eq_of_le hk with hk₁ hk₁,
{ have h : choose n k * fact (succ k) * fact (n - k) = succ k * fact n :=
by rw ← choose_mul_fact_mul_fact (le_of_succ_le_succ hk);
simp [fact_succ, mul_comm, mul_left_comm],
have h₁ : fact (n - k) = (n - k) * fact (n - succ k) :=
by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), fact_succ],
have h₂ : choose n (succ k) * fact (succ k) * ((n - k) * fact (n - succ k)) = (n - k) * fact n :=
by rw ← choose_mul_fact_mul_fact (le_of_lt_succ hk₁);
simp [fact_succ, mul_comm, mul_left_comm, mul_assoc],
have h₃ : k * fact n ≤ n * fact n := mul_le_mul_right _ (le_of_succ_le_succ hk),
rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, ← add_one, add_mul, nat.mul_sub_right_distrib,
fact_succ, ← nat.add_sub_assoc h₃, add_assoc, ← add_mul, nat.add_sub_cancel_left, add_comm] },
{ simp [hk₁, mul_comm, choose, nat.sub_self] }
end
theorem choose_eq_fact_div_fact {n k : ℕ} (hk : k ≤ n) : choose n k = fact n / (fact k * fact (n - k)) :=
begin
have : fact n = choose n k * (fact k * fact (n - k)) :=
by rw ← mul_assoc; exact (choose_mul_fact_mul_fact hk).symm,
exact (nat.div_eq_of_eq_mul_left (mul_pos (fact_pos _) (fact_pos _)) this).symm
end
theorem fact_mul_fact_dvd_fact {n k : ℕ} (hk : k ≤ n) : fact k * fact (n - k) ∣ fact n :=
by rw [←choose_mul_fact_mul_fact hk, mul_assoc]; exact dvd_mul_left _ _
|
e18534eb99f078413d50f77e24d90924e7aae347 | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/normed_group/pseudo_normed_group.lean | 27292f631023e04040cb372810446d0cd10f8b5a | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,140 | lean | import pseudo_normed_group.basic
import analysis.normed_space.basic
/-!
# A seminormed group is pseudo-normed
This file contains the construction of a pseudo-normed group from a seminormed group.
-/
open_locale nnreal
namespace semi_normed_group
instance (V : Type*) [semi_normed_group V] : pseudo_normed_group V :=
{ filtration := λ c, {v | ∥v∥₊ ≤ c},
filtration_mono := λ c₁ c₂ h v (hv : ∥v∥ ≤ c₁), le_trans hv h,
zero_mem_filtration := λ c, by simp only [set.mem_set_of_eq, nnnorm_zero, zero_le],
neg_mem_filtration := λ c v hv, by simpa only [set.mem_set_of_eq, nnnorm_neg] using hv,
add_mem_filtration := λ c₁ c₂ v₁ v₂ hv₁ hv₂,
calc ∥v₁ + v₂∥
≤ ∥v₁∥ + ∥v₂∥ : norm_add_le _ _
... ≤ c₁ + c₂ : add_le_add hv₁ hv₂ }
variables {V : Type*} [semi_normed_group V]
open pseudo_normed_group
lemma mem_filtration_nnnorm (v : V) : v ∈ filtration V (∥v∥₊) :=
show ∥v∥₊ ≤ ∥v∥₊, from le_rfl
@[simp] lemma mem_filtration_iff (v : V) (c : ℝ≥0) :
v ∈ filtration V c ↔ ∥v∥₊ ≤ c := iff.rfl
end semi_normed_group
|
6c0aeaecdac12a35a72caf40100c4189690f1b8f | dd24e6c3b8dc14dc504f8a906fc04c51e4312e6b | /src/mywork/lectures/lecture_1a.lean | 7ca199629accd59e74e2f46be9ba043c316fe4ed | [] | no_license | njeyasingh/CS-2120 | dd781a90dd0645b74e61cee1813483fb7cb4a111 | b3356f665a246f295b3f1e6d61901bfca331810d | refs/heads/main | 1,693,294,711,274 | 1,635,188,659,000 | 1,635,188,659,000 | 399,945,420 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,068 | lean | -- import definitions of real and rational numbers from mathlib
import data.real.basic
namespace cs2120
/-
The first part of this lesson is in the file, lecture_1.md.
Please start there then return here when you're done with
that document.
-/
/-
NUMBER SYSTEMS
-/
/-
Mathematicians think about operations on many kinds of objects.
In early mathematics, the objects are numbers. In later maths,
they can be polynomials, matrices, functions, symmetries, or any
manner of other "mathematical thingies". As we're going to see
here, they can even be propositions and proofs.
But let's start with something really simple. The number, 1. Ok,
it's actually not that simple, because 1 can be interpreted as
denoting a natural number, integer, real number, rational number,
identity matrix, identity function, identity element of a group,
or any manner (again) of "mathematical thingy". If Lean sees a
bare numeral, 1, it interprets it as the natural number, 1. It
is possible to force many other interpretations however, as the
following examples show.
As you read the code, remember the following.
ℕ: Natural numbers. The non-negative whole numbers. {0, 1, 2, ...}
ℤ: Integers: The negative and non-negative whole numbers.
ℚ: Rationals: Ratios of an integer and a non-zero natural number.
ℝ: Reals: Equivalence classes of convergent sequence of rationals.
Irrational numbers: Real numbers not "isomorphic" to any rationals.
Examples:
Natural numbers: 0, 3, 11, 29
Integers: -29, 0, 3, 11
Rationals: 1/2, -3/4, 23/7
Reals: 0.000..., .333..., 3.1415...
Irrationals: 3.1415..., e, sqrt 2
-/
def m := 1 -- 1 inferred to be a natural number (built into Lean)
def n : ℕ := 1 -- 1 specified to be a natural number (non-negative whole number)
def z : ℤ := 1 -- 1 as an integer (negative or non-negative whole number)
def r : ℝ := 1.0 -- 1 as a real number (infinite decimal sequence)
def q : ℚ := 1/1 -- 1 as a rational number (fraction)
/-
Each proceeding line of code has the following elements
- def: a keyword, binds the given identifer to the given value
- n, m, z, r, q: identifiers, a.k.a., variables or variable names
- : T, where T is ℕ, ℤ, ℝ, or ℚ: specifies the *type* of the value
- := 1.0: specifies the value, 1.0, to be bound to the identifier
-/
/-
The same definitions could be written as follows, allowing Lean
to fill in type information that it can infer from the way in
which the values are given.
-/
def m' := 1 -- Lean assumes 1 is a natural number (built into Lean)
def n' := (1 : ℕ) -- 1 as a natural number (non-negative whole number)
def z' := (1 : ℤ) -- 1 as an integer (negative or non-negative whole number)
def r' := (1.0 : ℝ) -- 1 as a real number (infinite decimal sequence)
def q' := 1/1 -- Here Lean infers 1/1 is rational number (fraction)
/-
AXIOMS, PROPOSITIONS, PROOFS
-/
/-
Let's again talk about propositions and
proofs involving "equality" propositions,
such as the proposition that 1 = 1. We
all *know* intuitively that 1 = 1, but
how would you prove it, given that it's
not an axiom of ordinary predicate logic?
Without getting into the weeds, suffice
it to say that the standard Lean Prover
libraries define equality pretty much as
we've discussed here: with an axiom in
the form of a universal generaliztion:
∀ {T : Type} (t : T), t = t.
In English, this says, "if you give me
*any* Type, T, and any object, t, of that
type, I will return you (and therefore
there must be) a proof of the proposition,
t = t; and the existence of this proof,
in turn, justifies the *judgment* that
the proposition, 1 = 1, is *true*.
Let's take another look at the axiom that
let's us *deduce* the *theorem* that 1 = 1.
Here it is: ∀ {T : Type} (t : T), t = t.
What that means is that if I choose any
type, T, say T = ℕ, and any value of that
type, say t = (1 : ℕ), then I should be
able to apply the axiom to the argument
values, ℕ and 1, to get back a *proof* of
the proposition, 1 = 1.
Indeed, that's just how it works, as the
follow example shows formally (in Lean).
-/
example : 1 = 1 :=
eq.refl 1 -- Lean inferns T = ℕ from 1
/-
Yay! We just constructed a formal proof: a
mathematical object that certifies that 1=1.
It might not be super-impressive that Lean
rejects "eq.refl 2" as a suitable proof (try
it, and don't fail to read the entire error
message when you hover your cursor over the
red squiggle!); but the principle extends to
commplex proofs of profound propositions.
Nice: you've not only constructed a formal
proof object but you have a "high assurance"
check that the proof itself is correct, in
that Lean actually accepts that it's correct.
*That* is what Lean is really for: not just
for formalizing mathematics and logic, but
for checking that proofs *truly* prove what
they claim to prove.
-/
/-
Of course, if formal proofs came without
costs, we'd all be using them. The benefit
of a *natural language* "proof description"
(written in, say, English, but in a highly
mathematical style) is that it's easier for
people to follow, often because details can
be elided on the assumption that the reader
will know from context what is meant.
In this case at hand, you could give a proof,
of the proposition, 1 = 1, as follows:
Proof: By the reflexive property of equality
(applied to the particular value, 1). QED."
If you and your audience both understand that
you're *applying* the universal generalization
given as an axiom to suitable values, then you
can just leave out the parenthetical expression.
How much detail to put in a proof description
is a matter of style and of a willingness to
make your readers fill in the missing details.
The QED, by the way, is short for quod est
demonstratum, Latin for "it is shown." It is
a kind of traditional punctuation for natural
language proof descriptions that signals that
the proof is complete.
The downside of using natural language proof
descriptions in lieu of formal proof objects
is that when things get complex, it can be
nearly impossible to tell whether a proof in
natural language is correct or not. In hard
cases, it can require years of work by world
experts to decide whether a proof is correct
or faulty.
In this class, we will insist, because all
mathematicians do, that your propositions
be fully formal, i.e., syntactically correct
by the grammatical rules of predicate logic,
as enforced by Lean. We will expose you to
formal proofs to the extent that we believe
that doing so will help you to understand
how to write quasi-formal proof descriptions.
Quasi-formal proofs are what most people use
today, including instructors for follow-on CS
courses. But there are now thriving communities
in both mathematics and computer science that
are aggressively pursuing the formalization,
and the *computerization* of logic and proof.
The community around Lean is most interested
in formalizing mathematics for mathematicians.
Other critically important applications of
Lean and similar "proof assistants" arise in
relation to the definition of programming
languages, and in the formal (mathematical)
specification and trustworthy and automated
correctness checking of computer programs.
-/
/-
If you're getting the feeling that we are
pointing you a little bit to a computational
understand of what it means to construct or
to use proofs, you're right. To make the point
clearer, let's write our own proof-returning
function@ We'll call it gimme_a_proof. It
will take two arguments, a type, T, and a
value, t, of that type; and it will return
a proof of t = t, on the basis of which we
can render the judgment that t = t is *true*.
-/
def gimme_a_proof -- function name
(T : Type) -- first argument
(t : T) -- second argument
: t = t -- return type
:= eq.refl t -- implementation
/-
Let's decode that. We're defining a function
called gimme_a_proof that takes T and t as
its arguments and promises to return a value
of type t = t (a proof of this proposition).
The way that it upholds this promise is by
*applying* eq.refl to t, whatever it is, to
construct a proof of t = t. That proof is the
result and return value of this function.
-/
/-
Now that we've got this function defined,
we can apply *it* to arguments to have it
construct values that constitute proofs of
t = t. If you hover over #reduce in the
following Lean commands, Lean will report
to you the results of applying the function
to arguments of various numerical types.
Remember when reading the outputs that
"eq.refl x" *is* an object that serves
as a proof of x = x
-/
#reduce gimme_a_proof ℕ 9
#reduce gimme_a_proof bool tt
#reduce gimme_a_proof ℚ 1
#reduce gimme_a_proof ℤ (-3)
/-
That wraps up this review (and extension)
of our last lecture. Now for the quiz.
-/
/-++++++++++
EXERCISES #1.
Give a quasi-formal English language "proof"
of the proposition that 2 = 2.
Theorem: 2 = 2.
Proof: By the reflexive property of equality.
-/
/-++++++++++
EXERCISE #2.
Give, below, a formal statement and proof of
the proposition, 2 = 2. (See above for a good
example to follow!)
-/
-- answer here:
example : 2 = 2 :=@ eg.refl N 2
/-
EXERCISE #3.
Identify what form of reasoning is being used
in each of the following made-up stories. Just
give a one-word answer for each.
A. Every time the bell has rung, I've gotten a
nugget. The bell just rung, so I'm gonna get a
nugget! (Dogs usually say "gonna," by the way).
answer:
B. The "clone repo into container" command did
nothing. That was clearly wrong. I search around
on the World Wide Web and notice someone saying
something about that VSCode command needed to
have git installed. Ah ha, I thought. That could
be it. I'll do the obvious experiment and install
git and see if it works. (It did, by the way.)
answer:
C. It's true that it's raining, and it's true
that the streets are wet, so it must be true
that "it's raining *and* the streets are wet."
answer:
-/
end cs2120 |
3ad64350df33a0a7a2ba876411b5fa04f145c443 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/logic/equiv/functor.lean | 3ecd01ad4c5de44700ec7bccbc351065adca79bb | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 2,302 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Simon Hudon, Scott Morrison
-/
import control.bifunctor
import logic.equiv.basic
/-!
# Functor and bifunctors can be applied to `equiv`s.
We define
```lean
def functor.map_equiv (f : Type u → Type v) [functor f] [is_lawful_functor f] :
α ≃ β → f α ≃ f β
```
and
```lean
def bifunctor.map_equiv (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F] :
α ≃ β → α' ≃ β' → F α α' ≃ F β β'
```
-/
universes u v w
variables {α β : Type u}
open equiv
namespace functor
variables (f : Type u → Type v) [functor f] [is_lawful_functor f]
/-- Apply a functor to an `equiv`. -/
def map_equiv (h : α ≃ β) : f α ≃ f β :=
{ to_fun := map h,
inv_fun := map h.symm,
left_inv := λ x, by simp [map_map],
right_inv := λ x, by simp [map_map] }
@[simp]
lemma map_equiv_apply (h : α ≃ β) (x : f α) :
(map_equiv f h : f α ≃ f β) x = map h x := rfl
@[simp]
lemma map_equiv_symm_apply (h : α ≃ β) (y : f β) :
(map_equiv f h : f α ≃ f β).symm y = map h.symm y := rfl
@[simp]
lemma map_equiv_refl : map_equiv f (equiv.refl α) = equiv.refl (f α) :=
begin
ext x,
simp only [map_equiv_apply, refl_apply],
exact is_lawful_functor.id_map x,
end
end functor
namespace bifunctor
variables {α' β' : Type v} (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F]
/-- Apply a bifunctor to a pair of `equiv`s. -/
def map_equiv (h : α ≃ β) (h' : α' ≃ β') : F α α' ≃ F β β' :=
{ to_fun := bimap h h',
inv_fun := bimap h.symm h'.symm,
left_inv := λ x, by simp [bimap_bimap, id_bimap],
right_inv := λ x, by simp [bimap_bimap, id_bimap] }
@[simp]
lemma map_equiv_apply (h : α ≃ β) (h' : α' ≃ β') (x : F α α') :
(map_equiv F h h' : F α α' ≃ F β β') x = bimap h h' x := rfl
@[simp]
lemma map_equiv_symm_apply (h : α ≃ β) (h' : α' ≃ β') (y : F β β') :
(map_equiv F h h' : F α α' ≃ F β β').symm y = bimap h.symm h'.symm y := rfl
@[simp]
lemma map_equiv_refl_refl : map_equiv F (equiv.refl α) (equiv.refl α') = equiv.refl (F α α') :=
begin
ext x,
simp [id_bimap]
end
end bifunctor
|
52bb6f14ab63eedc95a79933f33bcd9cdeb8e3ea | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/constProp.lean | 06181a8ccafdede7a9562d1acdff2118816f910d | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 20,529 | lean | abbrev Var := String
inductive Val where
| int (i : Int)
| bool (b : Bool)
deriving DecidableEq, Repr
instance : Coe Bool Val where
coe b := .bool b
instance : Coe Int Val where
coe i := .int i
instance : OfNat Val n where
ofNat := .int n
#check (true : Val)
#check (0 : Val)
inductive BinOp where
| eq | and | lt | add | sub
deriving Repr
inductive UnaryOp where
| not
deriving Repr
inductive Expr where
| val (v : Val)
| var (x : Var)
| bin (lhs : Expr) (op : BinOp) (rhs : Expr)
| una (op : UnaryOp) (arg : Expr)
deriving Repr
instance : Coe Val Expr where
coe v := .val v
instance : Coe Var Expr where
coe x := .var x
instance : OfNat Expr n where
ofNat := .val n
@[simp] def BinOp.eval : BinOp → Val → Val → Option Val
| .eq, v₁, v₂ => some (.bool (v₁ = v₂))
| .and, .bool b₁, .bool b₂ => some (.bool (b₁ && b₂))
| .lt, .int i₁, .int i₂ => some (.bool (i₁ < i₂))
| .add, .int i₁, .int i₂ => some (.int (i₁ + i₂))
| .sub, .int i₁, .int i₂ => some (.int (i₁ - i₂))
| _, _, _ => none
@[simp] def UnaryOp.eval : UnaryOp → Val → Option Val
| .not, .bool b => some (.bool !b)
| _, _ => none
inductive Stmt where
| skip
| assign (x : Var) (e : Expr)
| seq (s₁ s₂ : Stmt)
| ite (c : Expr) (e t : Stmt)
| while (c : Expr) (b : Stmt)
deriving Repr
infix:150 " ::= " => Stmt.assign
infixr:130 ";; " => Stmt.seq
syntax "`[Expr|" term "]" : term
macro_rules
| `(`[Expr|true]) => `((true : Expr))
| `(`[Expr|false]) => `((false : Expr))
| `(`[Expr|$n:num]) => `(($n : Expr))
| `(`[Expr|$x:ident]) => `(($(Lean.quote x.getId.toString) : Expr))
| `(`[Expr|$x = $y]) => `(Expr.bin `[Expr|$x] BinOp.eq `[Expr|$y])
| `(`[Expr|$x && $y]) => `(Expr.bin `[Expr|$x] BinOp.and `[Expr|$y])
| `(`[Expr|$x < $y]) => `(Expr.bin `[Expr|$x] BinOp.lt `[Expr|$y])
| `(`[Expr|$x + $y]) => `(Expr.bin `[Expr|$x] BinOp.add `[Expr|$y])
| `(`[Expr|$x - $y]) => `(Expr.bin `[Expr|$x] BinOp.sub `[Expr|$y])
| `(`[Expr|!$x]) => `(Expr.una UnaryOp.not `[Expr|$x])
| `(`[Expr|($x)]) => `(`[Expr|$x])
declare_syntax_cat stmt
syntax ident " := " term ";": stmt
syntax "if " "(" term ")" " {\n" stmt* "\n}" (" else " "{\n" stmt* "\n}")? : stmt
syntax "while " "(" term ")" "{\n" stmt* "\n}" : stmt
syntax "`[Stmt|" stmt* "]" : term
macro_rules
| `(`[Stmt| ]) => `(Stmt.skip)
| `(`[Stmt| $x:ident := $e:term;]) => `(Stmt.assign $(Lean.quote x.getId.toString) `[Expr| $e:term])
| `(`[Stmt| if ($c) { $ts* } else { $es* }]) => `(Stmt.ite `[Expr| $c] `[Stmt| $ts*] `[Stmt| $es*])
| `(`[Stmt| if ($c) { $ts* }]) => `(Stmt.ite `[Expr| $c] `[Stmt| $ts*] Stmt.skip)
| `(`[Stmt| while ($c) { $b* }]) => `(Stmt.while `[Expr|$c] `[Stmt|$b*])
| `(`[Stmt| $s $ss*]) => `(Stmt.seq `[Stmt|$s] `[Stmt|$ss*])
def example1 := `[Stmt|
x := 8;
y := 10;
if (x < y) {
x := x + 1;
} else {
y := y + 3;
}
]
#reduce example1
def example2 := `[Stmt|
x := 8;
if (x < y) {
x := x + 1;
} else {
y := y + 3;
x := 9;
}
y := x;]
#eval example2
abbrev State := List (Var × Val)
@[simp] def State.update (σ : State) (x : Var) (v : Val) : State :=
match σ with
| [] => [(x, v)]
| (y, w)::σ => if x = y then (x, v)::σ else (y, w) :: update σ x v
@[simp] def State.find? (σ : State) (x : Var) : Option Val :=
match σ with
| [] => none
| (y, v) :: σ => if x = y then some v else find? σ x
def State.get (σ : State) (x : Var) : Val :=
σ.find? x |>.getD (.int 0)
@[simp] def State.erase (σ : State) (x : Var) : State :=
match σ with
| [] => []
| (y, v) :: σ => if x = y then erase σ x else (y, v) :: erase σ x
@[simp] theorem State.find?_update_self (σ : State) (x : Var) (v : Val) : (σ.update x v).find? x = some v := by
match σ with -- TODO: automate this proof
| [] => simp
| (y, w) :: s =>
simp
split <;> simp [*]
apply find?_update_self
@[simp] theorem State.find?_update (σ : State) (v : Val) (h : x ≠ z) : (σ.update x v).find? z = σ.find? z := by
match σ with -- TODO: automate this proof
| [] => simp [h.symm]
| (y, w) :: σ =>
simp
split <;> simp [*]
next hc => split <;> simp_all
next =>
split
next => rfl
next => exact find?_update σ v h
-- TODO: remove after we add better automation
@[simp] theorem State.find?_update' (σ : State) (v : Val) (h : z ≠ x) : (σ.update x v).find? z = σ.find? z :=
State.find?_update σ v h.symm
theorem State.get_of_find? {σ : State} (h : σ.find? x = some v) : σ.get x = v := by
simp [State.get, h, Option.getD]
@[simp] theorem State.find?_erase_self (σ : State) (x : Var) : (σ.erase x).find? x = none := by
match σ with
| [] => simp
| (y, w) :: σ =>
simp
split <;> simp [*]
next => exact find?_erase_self σ y
next => exact find?_erase_self σ x
@[simp] theorem State.find?_erase (σ : State) (h : x ≠ z) : (σ.erase x).find? z = σ.find? z := by
match σ with
| [] => simp
| (y, w) :: σ =>
simp
split <;> simp [*]
next hxy => rw [hxy] at h; simp [h.symm]; exact find?_erase σ h
next =>
split
next => rfl
next => exact find?_erase σ h
-- TODO: remove after we add better automation
@[simp] theorem State.find?_erase' (σ : State) (h : z ≠ x) : (σ.erase x).find? z = σ.find? z :=
State.find?_erase σ h.symm
syntax ident " ↦ " term : term
macro_rules
| `($id:ident ↦ $v:term) => `(($(Lean.quote id.getId.toString), $v:term))
example : State.get [x ↦ .int 10, y ↦ .int 20] "x" = .int 10 := rfl
example : State.get [x ↦ 10, y ↦ 20] "x" = 10 := rfl
example : State.get [x ↦ 10, y ↦ true] "y" = true := rfl
@[simp] def Expr.eval (σ : State) : Expr → Option Val
| val v => some v
| var x => σ.get x
| bin lhs op rhs => match lhs.eval σ, rhs.eval σ with
| some v₁, some v₂ => op.eval v₁ v₂ -- BinOp.eval : BinOp → Val → Val → Option Val
| _, _ => none
| una op arg => match arg.eval σ with
| some v => op.eval v
| _ => none
@[simp] def evalTrue (c : Expr) (σ : State) : Prop := c.eval σ = some (Val.bool true)
@[simp] def evalFalse (c : Expr) (σ : State) : Prop := c.eval σ = some (Val.bool false)
section
set_option hygiene false -- HACK: allow forward reference in notation
local notation:60 "(" σ ", " s ")" " ⇓ " σ':60 => Bigstep σ s σ'
inductive Bigstep : State → Stmt → State → Prop where
| skip : (σ, .skip) ⇓ σ
| assign : e.eval σ = some v → (σ, x ::= e) ⇓ σ.update x v
| seq : (σ₁, s₁) ⇓ σ₂ → (σ₂, s₂) ⇓ σ₃ → (σ₁, s₁ ;; s₂) ⇓ σ₃
| ifTrue : evalTrue c σ₁ → (σ₁, t) ⇓ σ₂ → (σ₁, .ite c t e) ⇓ σ₂
| ifFalse : evalFalse c σ₁ → (σ₁, e) ⇓ σ₂ → (σ₁, .ite c t e) ⇓ σ₂
| whileTrue : evalTrue c σ₁ → (σ₁, b) ⇓ σ₂ → (σ₂, .while c b) ⇓ σ₃ → (σ₁, .while c b) ⇓ σ₃
| whileFalse : evalFalse c σ → (σ, .while c b) ⇓ σ
end
notation:60 "(" σ ", " s ")" " ⇓ " σ':60 => Bigstep σ s σ'
/- This proof can be automated using forward reasoning. -/
theorem Bigstem.det (h₁ : (σ, s) ⇓ σ₁) (h₂ : (σ, s) ⇓ σ₂) : σ₁ = σ₂ := by
induction h₁ generalizing σ₂ <;> cases h₂ <;> simp_all
-- The rest of this proof should be automatic with congruence closure and a bit of forward reasoning
case seq ih₁ ih₂ h₁ h₂ =>
simp [ih₁ h₁] at ih₂
simp [ih₂ h₂]
case ifTrue ih h =>
simp [ih h]
case ifFalse ih h =>
simp [ih h]
case whileTrue ih₁ ih₂ h₁ h₂ =>
simp [ih₁ h₁] at ih₂
simp [ih₂ h₂]
abbrev EvalM := ExceptT String (StateM State)
def evalExpr (e : Expr) : EvalM Val := do
match e.eval (← get) with
| some v => return v
| none => throw "failed to evaluate"
@[simp] def Stmt.eval (stmt : Stmt) (fuel : Nat := 100) : EvalM Unit := do
match fuel with
| 0 => throw "out of fuel"
| fuel+1 =>
match stmt with
| skip => return ()
| assign x e => let v ← evalExpr e; modify fun s => s.update x v
| seq s₁ s₂ => s₁.eval fuel; s₂.eval fuel
| ite c e t =>
match (← evalExpr c) with
| .bool true => e.eval fuel
| .bool false => t.eval fuel
| _ => throw "Boolean expected"
| .while c b =>
match (← evalExpr c) with
| .bool true => b.eval fuel; stmt.eval fuel
| .bool false => return ()
| _ => throw "Boolean expected"
#eval `[Stmt| x := 3; y := 5; x := x + y;].eval |>.run {}
#eval `[Stmt| x := 0; while (true) { x := x + 1; }].eval |>.run {}
instance : Repr State where
reprPrec a n :=
match a, n with
| [], _ => "[]"
| as, _ =>
let fs := as.map fun
| (x, .int v) => f!"{x} ↦ {v}"
| (x, .bool v) => f!"{x} ↦ {v}"
Std.Format.bracket "[" (Std.Format.joinSep fs ("," ++ Std.Format.line)) "]"
#eval `[Stmt| x := 3; y := 5; x := x + y; ].eval |>.run {}
@[simp] def BinOp.simplify : BinOp → Expr → Expr → Expr
| .eq, .val v₁, .val v₂ => .val (.bool (v₁ = v₂))
| .and, .val (.bool a), .val (.bool b) => .val (.bool (a && b))
| .lt, .val (.int a), .val (.int b) => .val (.bool (a < b))
| .add, .val (.int a), .val (.int b) => .val (.int (a + b))
| .sub, .val (.int a), .val (.int b) => .val (.int (a - b))
| op, a, b => .bin a op b
@[simp] def UnaryOp.simplify : UnaryOp → Expr → Expr
| .not, .val (.bool b) => .val (.bool !b)
| op, a => .una op a
@[simp] def Expr.simplify : Expr → Expr
| bin lhs op rhs => op.simplify lhs.simplify rhs.simplify
| una op arg => op.simplify arg.simplify
| e => e
@[simp] theorem Expr.eval_simplify (e : Expr) : e.simplify.eval σ = e.eval σ := by
induction e with simp
| bin lhs op rhs ih_lhs ih_rhs =>
simp [← ih_lhs, ← ih_rhs]
split <;> simp [*]
| una op arg ih_arg =>
simp [← ih_arg]
split <;> simp [*]
@[simp] def Stmt.simplify : Stmt → Stmt
| skip => skip
| assign x e => assign x e.simplify
| seq s₁ s₂ => seq s₁.simplify s₂.simplify
| ite c e t =>
match c.simplify with
| .val (.bool true) => e.simplify
| .val (.bool false) => t.simplify
| c' => ite c' e.simplify t.simplify
| .while c b =>
match c.simplify with
| .val (.bool false) => skip
| c' => .while c' b.simplify
def example3 := `[Stmt|
if (1 < 2 + 3) {
x := 3 + 1;
y := y + x;
} else {
y := y + 3;
}
]
#eval example3.simplify
theorem Stmt.simplify_correct (h : (σ, s) ⇓ σ') : (σ, s.simplify) ⇓ σ' := by
induction h with simp_all
| skip => exact Bigstep.skip
| seq h₁ h₂ ih₁ ih₂ => exact Bigstep.seq ih₁ ih₂
| assign => apply Bigstep.assign; simp [*]
| whileTrue heq h₁ h₂ ih₁ ih₂ =>
rw [← Expr.eval_simplify] at heq
split
next h => rw [h] at heq; simp at heq
next hnp => simp [hnp] at ih₂; apply Bigstep.whileTrue heq ih₁ ih₂
| whileFalse heq =>
split
next => exact Bigstep.skip
next => apply Bigstep.whileFalse; simp [heq]
| ifFalse heq h ih =>
rw [← Expr.eval_simplify] at heq
split <;> simp_all
rw [← Expr.eval_simplify] at heq
apply Bigstep.ifFalse heq ih
| ifTrue heq h ih =>
rw [← Expr.eval_simplify] at heq
split <;> simp_all
rw [← Expr.eval_simplify] at heq
apply Bigstep.ifTrue heq ih
@[simp] def Expr.constProp (e : Expr) (σ : State) : Expr :=
match e with
| val v => v
| var x => match σ.find? x with
| some v => val v
| none => var x
| bin lhs op rhs => bin (lhs.constProp σ) op (rhs.constProp σ)
| una op arg => una op (arg.constProp σ)
@[simp] theorem Expr.constProp_nil (e : Expr) : e.constProp [] = e := by
induction e <;> simp [*]
def State.length_erase_le (σ : State) (x : Var) : (σ.erase x).length ≤ σ.length := by
match σ with
| [] => simp
| (y, v) :: σ =>
by_cases hxy : x = y <;> simp [hxy]
next => exact Nat.le_trans (length_erase_le σ y) (by simp_arith)
next => simp_arith [length_erase_le σ x]
def State.length_erase_lt (σ : State) (x : Var) : (σ.erase x).length < σ.length.succ :=
Nat.lt_of_le_of_lt (length_erase_le ..) (by simp_arith)
@[simp] def State.join (σ₁ σ₂ : State) : State :=
match σ₁ with
| [] => []
| (x, v) :: σ₁ =>
let σ₁' := erase σ₁ x -- Must remove duplicates. Alternative design: carry invariant that input state at constProp has no duplicates
have : (erase σ₁ x).length < σ₁.length.succ := length_erase_lt ..
match σ₂.find? x with
| some w => if v = w then (x, v) :: join σ₁' σ₂ else join σ₁' σ₂
| none => join σ₁' σ₂
termination_by _ σ₁ _ => σ₁.length
local notation "⊥" => []
@[simp] def Stmt.constProp (s : Stmt) (σ : State) : Stmt × State :=
match s with
| skip => (skip, σ)
| assign x e => match (e.constProp σ).simplify with
| (.val v) => (assign x (.val v), σ.update x v)
| e' => (assign x e', σ.erase x)
| seq s₁ s₂ => match s₁.constProp σ with
| (s₁', σ₁) => match s₂.constProp σ₁ with
| (s₂', σ₂) => (seq s₁' s₂', σ₂)
| ite c s₁ s₂ =>
match s₁.constProp σ, s₂.constProp σ with
| (s₁', σ₁), (s₂', σ₂) => (ite (c.constProp σ) s₁' s₂', σ₁.join σ₂)
| .while c b => (.while (c.constProp ⊥) (b.constProp ⊥).1, ⊥)
def State.le (σ₁ σ₂ : State) : Prop :=
∀ ⦃x : Var⦄ ⦃v : Val⦄, σ₁.find? x = some v → σ₂.find? x = some v
infix:50 " ≼ " => State.le
theorem State.le_refl (σ : State) : σ ≼ σ :=
fun _ _ h => h
theorem State.le_trans : σ₁ ≼ σ₂ → σ₂ ≼ σ₃ → σ₁ ≼ σ₃ :=
fun h₁ h₂ x v h => h₂ (h₁ h)
theorem State.bot_le (σ : State) : ⊥ ≼ σ :=
fun _ _ h => by contradiction
theorem State.erase_le_cons (h : σ' ≼ σ) : σ'.erase x ≼ ((x, v) :: σ) := by
intro y w hf'
by_cases hyx : y = x <;> simp [*] at hf' |-
exact h hf'
theorem State.cons_le_cons (h : σ' ≼ σ) : (x, v) :: σ' ≼ (x, v) :: σ := by
intro y w hf'
by_cases hyx : y = x <;> simp [*] at hf' |-
next => assumption
next => exact h hf'
theorem State.cons_le_of_eq (h₁ : σ' ≼ σ) (h₂ : σ.find? x = some v) : (x, v) :: σ' ≼ σ := by
intro y w hf'
by_cases hyx : y = x <;> simp [*] at hf' |-
next => assumption
next => exact h₁ hf'
theorem State.erase_le (σ : State) : σ.erase x ≼ σ := by
match σ with
| [] => simp; apply le_refl
| (y, v) :: σ =>
simp
split <;> simp [*]
next => apply erase_le_cons; apply le_refl
next => apply cons_le_cons; apply erase_le
theorem State.join_le_left (σ₁ σ₂ : State) : σ₁.join σ₂ ≼ σ₁ := by
match σ₁ with
| [] => simp; apply le_refl
| (x, v) :: σ₁ =>
simp
have : (erase σ₁ x).length < σ₁.length.succ := length_erase_lt ..
have ih := join_le_left (State.erase σ₁ x) σ₂
split
next y w h =>
split
next => apply cons_le_cons; apply le_trans ih (erase_le _)
next => apply le_trans ih (erase_le_cons (le_refl _))
next h => apply le_trans ih (erase_le_cons (le_refl _))
termination_by _ σ₁ _ => σ₁.length
theorem State.join_le_left_of (h : σ₁ ≼ σ₂) (σ₃ : State) : σ₁.join σ₃ ≼ σ₂ :=
le_trans (join_le_left σ₁ σ₃) h
theorem State.join_le_right (σ₁ σ₂ : State) : σ₁.join σ₂ ≼ σ₂ := by
match σ₁ with
| [] => simp; apply bot_le
| (x, v) :: σ₁ =>
simp
have : (erase σ₁ x).length < σ₁.length.succ := length_erase_lt ..
have ih := join_le_right (erase σ₁ x) σ₂
split
next y w h =>
split <;> simp [*]
next => apply cons_le_of_eq ih h
next h => assumption
termination_by _ σ₁ _ => σ₁.length
theorem State.join_le_right_of (h : σ₁ ≼ σ₂) (σ₃ : State) : σ₃.join σ₁ ≼ σ₂ :=
le_trans (join_le_right σ₃ σ₁) h
theorem State.eq_bot (h : σ ≼ ⊥) : σ = ⊥ := by
match σ with
| [] => simp
| (y, v) :: σ =>
have : State.find? ((y, v) :: σ) y = some v := by simp
have := h this
contradiction
theorem State.erase_le_of_le_cons (h : σ' ≼ (x, v) :: σ) : σ'.erase x ≼ σ := by
intro y w hf'
by_cases hxy : x = y <;> simp [*] at hf'
have hf := h hf'
simp [hxy, Ne.symm hxy] at hf
assumption
theorem State.erase_le_update (h : σ' ≼ σ) : σ'.erase x ≼ σ.update x v := by
intro y w hf'
by_cases hxy : x = y <;> simp [*] at hf' |-
exact h hf'
theorem State.update_le_update (h : σ' ≼ σ) : σ'.update x v ≼ σ.update x v := by
intro y w hf
induction σ generalizing σ' hf with
| nil => rw [eq_bot h] at hf; assumption
| cons zw' σ ih =>
have (z, w') := zw'; simp
have : σ'.erase z ≼ σ := erase_le_of_le_cons h
have ih := ih this
revert ih hf
split <;> simp [*] <;> by_cases hyz : y = z <;> simp (config := { contextual := true }) [*]
next =>
intro he'
have he := h he'
simp [*] at he
assumption
next =>
by_cases hxy : x = y <;> simp [*]
next => intros; assumption
next =>
intro he' ih
exact ih he'
theorem Expr.eval_constProp_of_sub (e : Expr) (h : σ' ≼ σ) : (e.constProp σ').eval σ = e.eval σ := by
induction e with simp [*]
| var x =>
split <;> simp
next he => rw [State.get_of_find? (h he)]
theorem Expr.eval_constProp_of_eq_of_sub {e : Expr} (h₁ : e.eval σ = v) (h₂ : σ' ≼ σ) : (e.constProp σ').eval σ = v := by
have := eval_constProp_of_sub e h₂
simp [h₁] at this
assumption
theorem Stmt.constProp_sub (h₁ : (σ₁, s) ⇓ σ₂) (h₂ : σ₁' ≼ σ₁) : (s.constProp σ₁').2 ≼ σ₂ := by
induction h₁ generalizing σ₁' with simp
| skip => assumption
| assign heq =>
split <;> simp
next h =>
have heq' := Expr.eval_constProp_of_eq_of_sub heq h₂
rw [← Expr.eval_simplify, h] at heq'
simp at heq'
rw [heq']
apply State.update_le_update h₂
next h _ _ =>
exact State.erase_le_update h₂
| whileTrue heq h₃ h₄ ih₃ ih₄ =>
have ih₃ := ih₃ h₂
have ih₄ := ih₄ ih₃
simp [heq] at ih₄
exact ih₄
| whileFalse heq => apply State.bot_le
| ifTrue heq h ih =>
have ih := ih h₂
apply State.join_le_left_of ih
| ifFalse heq h ih =>
have ih := ih h₂
apply State.join_le_right_of ih
| seq h₃ h₄ ih₃ ih₄ => exact ih₄ (ih₃ h₂)
theorem Stmt.constProp_correct (h₁ : (σ₁, s) ⇓ σ₂) (h₂ : σ₁' ≼ σ₁) : (σ₁, (s.constProp σ₁').1) ⇓ σ₂ := by
induction h₁ generalizing σ₁' with simp_all
| skip => exact Bigstep.skip
| assign heq =>
split <;> simp
next h =>
have heq' := Expr.eval_constProp_of_eq_of_sub heq h₂
rw [← Expr.eval_simplify, h] at heq'
simp at heq'
apply Bigstep.assign; simp [*]
next =>
have heq' := Expr.eval_constProp_of_eq_of_sub heq h₂
rw [← Expr.eval_simplify] at heq'
apply Bigstep.assign heq'
| seq h₁ h₂ ih₁ ih₂ =>
apply Bigstep.seq (ih₁ h₂) (ih₂ (constProp_sub h₁ h₂))
| whileTrue heq h₁ h₂ ih₁ ih₂ =>
have ih₁ := ih₁ (State.bot_le _)
have ih₂ := ih₂ (State.bot_le _)
exact Bigstep.whileTrue heq ih₁ ih₂
| whileFalse heq =>
exact Bigstep.whileFalse heq
| ifTrue heq h ih =>
exact Bigstep.ifTrue (Expr.eval_constProp_of_eq_of_sub heq h₂) (ih h₂)
| ifFalse heq h ih =>
exact Bigstep.ifFalse (Expr.eval_constProp_of_eq_of_sub heq h₂) (ih h₂)
def Stmt.constPropagation (s : Stmt) : Stmt :=
(s.constProp ⊥).1
theorem Stmt.constPropagation_correct (h : (σ, s) ⇓ σ') : (σ, s.constPropagation) ⇓ σ' :=
constProp_correct h (State.bot_le _)
def example4 := `[Stmt|
x := 2;
if (x < 3) {
x := x + 1;
y := y + x;
} else {
y := y + 3;
}
]
#eval example4.constPropagation.simplify
#exit
-- TODO: add simp theorems for monadic code
theorem Stmt.eval_correct {s : Stmt} (h : (s.eval fuel).run σ = (.ok unit, σ')) : (σ, s) ⇓ σ' := by
induction fuel generalizing s σ σ' with simp at h
| zero => injection h; contradiction
| succ fuel ih =>
split at h
next => injection h with _ h; rw [h]; exact Bigstep.skip
next => done
|
4ee68ecd282fb35dcd320fc7fd86d56238096467 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/measure_theory/content.lean | c8b10ba736532b5f7993319991fa96e9f759052f | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,630 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.measure_space
import measure_theory.borel_space
import topology.opens
import topology.compacts
/-!
# Contents
In this file we work with *contents*. A content `λ` is a function from a certain class of subsets
(such as the the compact subsets) to `ℝ≥0∞` (or `ℝ≥0`) that is
* additive: If `K₁` and `K₂` are disjoint sets in the domain of `λ`,
then `λ(K₁ ∪ K₂) = λ(K₁) + λ(K₂)`;
* subadditive: If `K₁` and `K₂` are in the domain of `λ`, then `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)`;
* monotone: If `K₁ ⊆ K₂` are in the domain of `λ`, then `λ(K₁) ≤ λ(K₂)`.
We show that:
* Given a content `λ` on compact sets, we get a countably subadditive map that vanishes at `∅`.
In Halmos (1950) this is called the *inner content* `λ*` of `λ`.
* Given an inner content, we define an outer measure.
We don't explicitly define the type of contents.
In this file we only work on contents on compact sets, and inner contents on open sets, and both
contents and inner contents map into the extended nonnegative reals. However, in other applications
other choices can be made, and it is not a priori clear what the best interface should be.
## Main definitions
* `measure_theory.inner_content`: define an inner content from an content
* `measure_theory.outer_measure.of_content`: construct an outer measure from a content
## References
* Paul Halmos (1950), Measure Theory, §53
* https://en.wikipedia.org/wiki/Content_(measure_theory)
-/
universe variables u v w
noncomputable theory
open set topological_space
open_locale nnreal ennreal
namespace measure_theory
variables {G : Type w} [topological_space G]
/-- Constructing the inner content of a content. From a content defined on the compact sets, we
obtain a function defined on all open sets, by taking the supremum of the content of all compact
subsets. -/
def inner_content (μ : compacts G → ℝ≥0∞) (U : opens G) : ℝ≥0∞ :=
⨆ (K : compacts G) (h : K.1 ⊆ U), μ K
lemma le_inner_content {μ : compacts G → ℝ≥0∞} (K : compacts G) (U : opens G)
(h2 : K.1 ⊆ U) : μ K ≤ inner_content μ U :=
le_supr_of_le K $ le_supr _ h2
lemma inner_content_le {μ : compacts G → ℝ≥0∞}
(h : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → μ K₁ ≤ μ K₂)
(U : opens G) (K : compacts G)
(h2 : (U : set G) ⊆ K.1) : inner_content μ U ≤ μ K :=
bsupr_le $ λ K' hK', h _ _ (subset.trans hK' h2)
lemma inner_content_of_is_compact {μ : compacts G → ℝ≥0∞}
(h : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → μ K₁ ≤ μ K₂) {K : set G} (h1K : is_compact K)
(h2K : is_open K) : inner_content μ ⟨K, h2K⟩ = μ ⟨K, h1K⟩ :=
le_antisymm (bsupr_le $ λ K' hK', h _ ⟨K, h1K⟩ hK')
(le_inner_content _ _ subset.rfl)
lemma inner_content_empty {μ : compacts G → ℝ≥0∞} (h : μ ⊥ = 0) :
inner_content μ ∅ = 0 :=
begin
refine le_antisymm _ (zero_le _), rw ←h,
refine bsupr_le (λ K hK, _),
have : K = ⊥, { ext1, rw [subset_empty_iff.mp hK, compacts.bot_val] }, rw this, refl'
end
/-- This is "unbundled", because that it required for the API of `induced_outer_measure`. -/
lemma inner_content_mono {μ : compacts G → ℝ≥0∞} ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V)
(h2 : U ⊆ V) : inner_content μ ⟨U, hU⟩ ≤ inner_content μ ⟨V, hV⟩ :=
supr_le_supr $ λ K, supr_le_supr_const $ λ hK, subset.trans hK h2
lemma inner_content_exists_compact {μ : compacts G → ℝ≥0∞} {U : opens G}
(hU : inner_content μ U < ∞) {ε : ℝ≥0} (hε : 0 < ε) :
∃ K : compacts G, K.1 ⊆ U ∧ inner_content μ U ≤ μ K + ε :=
begin
have h'ε := ennreal.zero_lt_coe_iff.2 hε,
cases le_or_lt (inner_content μ U) ε,
{ exact ⟨⊥, empty_subset _, le_trans h (le_add_of_nonneg_left (zero_le _))⟩ },
have := ennreal.sub_lt_self (ne_of_lt hU) (ne_of_gt $ lt_trans h'ε h) h'ε,
conv at this {to_rhs, rw inner_content }, simp only [lt_supr_iff] at this,
rcases this with ⟨U, h1U, h2U⟩, refine ⟨U, h1U, _⟩,
rw [← ennreal.sub_le_iff_le_add], exact le_of_lt h2U
end
/-- The inner content of a supremum of opens is at most the sum of the individual inner
contents. -/
lemma inner_content_Sup_nat [t2_space G] {μ : compacts G → ℝ≥0∞}
(h1 : μ ⊥ = 0)
(h2 : ∀ (K₁ K₂ : compacts G), μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂) (U : ℕ → opens G) :
inner_content μ (⨆ (i : ℕ), U i) ≤ ∑' (i : ℕ), inner_content μ (U i) :=
begin
have h3 : ∀ (t : finset ℕ) (K : ℕ → compacts G), μ (t.sup K) ≤ t.sum (λ i, μ (K i)),
{ intros t K, refine finset.induction_on t _ _,
{ simp only [h1, nonpos_iff_eq_zero, finset.sum_empty, finset.sup_empty] },
{ intros n s hn ih, rw [finset.sup_insert, finset.sum_insert hn],
exact le_trans (h2 _ _) (add_le_add_left ih _) }},
refine bsupr_le (λ K hK, _),
rcases is_compact.elim_finite_subcover K.2 _ (λ i, (U i).prop) _ with ⟨t, ht⟩, swap,
{ convert hK, rw [opens.supr_def, subtype.coe_mk] },
rcases K.2.finite_compact_cover t (coe ∘ U) (λ i _, (U _).prop) (by simp only [ht])
with ⟨K', h1K', h2K', h3K'⟩,
let L : ℕ → compacts G := λ n, ⟨K' n, h1K' n⟩,
convert le_trans (h3 t L) _,
{ ext1, rw [h3K', compacts.finset_sup_val, finset.sup_eq_supr] },
refine le_trans (finset.sum_le_sum _) (ennreal.sum_le_tsum t),
intros i hi, refine le_trans _ (le_supr _ (L i)),
refine le_trans _ (le_supr _ (h2K' i)), refl'
end
/-- The inner content of a union of sets is at most the sum of the individual inner contents.
This is the "unbundled" version of `inner_content_Sup_nat`.
It required for the API of `induced_outer_measure`. -/
lemma inner_content_Union_nat [t2_space G] {μ : compacts G → ℝ≥0∞}
(h1 : μ ⊥ = 0)
(h2 : ∀ (K₁ K₂ : compacts G), μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂)
⦃U : ℕ → set G⦄ (hU : ∀ (i : ℕ), is_open (U i)) :
inner_content μ ⟨⋃ (i : ℕ), U i, is_open_Union hU⟩ ≤ ∑' (i : ℕ), inner_content μ ⟨U i, hU i⟩ :=
by { have := inner_content_Sup_nat h1 h2 (λ i, ⟨U i, hU i⟩), rwa [opens.supr_def] at this }
lemma inner_content_comap {μ : compacts G → ℝ≥0∞} (f : G ≃ₜ G)
(h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (U : opens G) :
inner_content μ (U.comap f.continuous) = inner_content μ U :=
begin
refine supr_congr _ ((compacts.equiv f).surjective) _,
intro K, refine supr_congr_Prop image_subset_iff _,
intro hK, simp only [equiv.coe_fn_mk, subtype.mk_eq_mk, ennreal.coe_eq_coe, compacts.equiv],
apply h,
end
@[to_additive]
lemma is_mul_left_invariant_inner_content [group G] [topological_group G] {μ : compacts G → ℝ≥0∞}
(h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G)
(U : opens G) : inner_content μ (U.comap $ continuous_mul_left g) = inner_content μ U :=
by convert inner_content_comap (homeomorph.mul_left g) (λ K, h g) U
-- @[to_additive] (fails for now)
lemma inner_content_pos_of_is_mul_left_invariant [t2_space G] [group G] [topological_group G]
{μ : compacts G → ℝ≥0∞}
(h1 : μ ⊥ = 0)
(h2 : ∀ (K₁ K₂ : compacts G), μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂)
(h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K)
(K : compacts G) (hK : 0 < μ K) (U : opens G) (hU : (U : set G).nonempty) :
0 < inner_content μ U :=
begin
have : (interior (U : set G)).nonempty, rwa [U.prop.interior_eq],
rcases compact_covered_by_mul_left_translates K.2 this with ⟨s, hs⟩,
suffices : μ K ≤ s.card * inner_content μ U,
{ exact (ennreal.mul_pos.mp $ lt_of_lt_of_le hK this).2 },
have : K.1 ⊆ ↑⨆ (g ∈ s), U.comap $ continuous_mul_left g,
{ simpa only [opens.supr_def, opens.coe_comap, subtype.coe_mk] },
refine (le_inner_content _ _ this).trans _,
refine (rel_supr_sum (inner_content μ) (inner_content_empty h1) (≤)
(inner_content_Sup_nat h1 h2) _ _).trans _,
simp only [is_mul_left_invariant_inner_content h3, finset.sum_const, nsmul_eq_mul, le_refl]
end
lemma inner_content_mono' {μ : compacts G → ℝ≥0∞} ⦃U V : set G⦄
(hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) :
inner_content μ ⟨U, hU⟩ ≤ inner_content μ ⟨V, hV⟩ :=
supr_le_supr $ λ K, supr_le_supr_const $ λ hK, subset.trans hK h2
namespace outer_measure
/-- Extending a content on compact sets to an outer measure on all sets. -/
def of_content [t2_space G] (μ : compacts G → ℝ≥0∞) (h1 : μ ⊥ = 0) : outer_measure G :=
induced_outer_measure (λ U hU, inner_content μ ⟨U, hU⟩) is_open_empty (inner_content_empty h1)
variables [t2_space G] {μ : compacts G → ℝ≥0∞} {h1 : μ ⊥ = 0}
(h2 : ∀ (K₁ K₂ : compacts G), μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂)
include h2
lemma of_content_opens (U : opens G) : of_content μ h1 U = inner_content μ U :=
induced_outer_measure_eq' (λ _, is_open_Union) (inner_content_Union_nat h1 h2)
inner_content_mono U.2
lemma of_content_le (h : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → μ K₁ ≤ μ K₂)
(U : opens G) (K : compacts G) (hUK : (U : set G) ⊆ K.1) : of_content μ h1 U ≤ μ K :=
(of_content_opens h2 U).le.trans $ inner_content_le h U K hUK
lemma le_of_content_compacts (K : compacts G) : μ K ≤ of_content μ h1 K.1 :=
begin
rw [of_content, induced_outer_measure_eq_infi],
{ exact le_infi (λ U, le_infi $ λ hU, le_infi $ le_inner_content K ⟨U, hU⟩) },
{ exact inner_content_Union_nat h1 h2 },
{ exact inner_content_mono }
end
lemma of_content_eq_infi (A : set G) :
of_content μ h1 A = ⨅ (U : set G) (hU : is_open U) (h : A ⊆ U), inner_content μ ⟨U, hU⟩ :=
induced_outer_measure_eq_infi _ (inner_content_Union_nat h1 h2) inner_content_mono A
lemma of_content_interior_compacts (h3 : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → μ K₁ ≤ μ K₂)
(K : compacts G) : of_content μ h1 (interior K.1) ≤ μ K :=
le_trans (le_of_eq $ of_content_opens h2 (opens.interior K.1))
(inner_content_le h3 _ _ interior_subset)
lemma of_content_exists_compact {U : opens G} (hU : of_content μ h1 U < ∞) {ε : ℝ≥0}
(hε : 0 < ε) : ∃ K : compacts G, K.1 ⊆ U ∧ of_content μ h1 U ≤ of_content μ h1 K.1 + ε :=
begin
rw [of_content_opens h2] at hU ⊢,
rcases inner_content_exists_compact hU hε with ⟨K, h1K, h2K⟩,
exact ⟨K, h1K, le_trans h2K $ add_le_add_right (le_of_content_compacts h2 K) _⟩,
end
lemma of_content_exists_open {A : set G} (hA : of_content μ h1 A < ∞) {ε : ℝ≥0} (hε : 0 < ε) :
∃ U : opens G, A ⊆ U ∧ of_content μ h1 U ≤ of_content μ h1 A + ε :=
begin
rcases induced_outer_measure_exists_set _ _ inner_content_mono hA hε with ⟨U, hU, h2U, h3U⟩,
exact ⟨⟨U, hU⟩, h2U, h3U⟩, swap, exact inner_content_Union_nat h1 h2
end
lemma of_content_preimage (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K)
(A : set G) : of_content μ h1 (f ⁻¹' A) = of_content μ h1 A :=
begin
refine induced_outer_measure_preimage _ (inner_content_Union_nat h1 h2) inner_content_mono _
(λ s, f.is_open_preimage) _,
intros s hs, convert inner_content_comap f h ⟨s, hs⟩
end
@[to_additive]
lemma is_mul_left_invariant_of_content [group G] [topological_group G]
(h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G)
(A : set G) : of_content μ h1 ((λ h, g * h) ⁻¹' A) = of_content μ h1 A :=
by convert of_content_preimage h2 (homeomorph.mul_left g) (λ K, h g) A
lemma of_content_caratheodory (A : set G) :
(of_content μ h1).caratheodory.measurable_set' A ↔ ∀ (U : opens G),
of_content μ h1 (U ∩ A) + of_content μ h1 (U \ A) ≤ of_content μ h1 U :=
begin
dsimp [opens], rw subtype.forall,
apply induced_outer_measure_caratheodory,
apply inner_content_Union_nat h1 h2,
apply inner_content_mono'
end
-- @[to_additive] (fails for now)
lemma of_content_pos_of_is_mul_left_invariant [group G] [topological_group G]
(h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K)
(K : compacts G) (hK : 0 < μ K) {U : set G} (h1U : is_open U) (h2U : U.nonempty) :
0 < of_content μ h1 U :=
by { convert inner_content_pos_of_is_mul_left_invariant h1 h2 h3 K hK ⟨U, h1U⟩ h2U,
exact of_content_opens h2 ⟨U, h1U⟩ }
end outer_measure
end measure_theory
|
1e6344e43d5d2a229280d2fc0ac4b5d80455490d | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/measure_theory/lp_space.lean | ae92e8f4da675499526caa5e6f2cd53f8d116b3d | [
"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 | 79,174 | 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, Sébastien Gouëzel
-/
import measure_theory.ess_sup
import measure_theory.ae_eq_fun
import analysis.mean_inequalities
import topology.continuous_function.compact
/-!
# ℒp space and Lp space
This file describes properties of almost everywhere measurable functions with finite seminorm,
denoted by `snorm f p μ` and defined for `p:ℝ≥0∞` as `0` if `p=0`, `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for
`0 < p < ∞` and `ess_sup ∥f∥ μ` for `p=∞`.
The Prop-valued `mem_ℒp f p μ` states that a function `f : α → E` has finite seminorm.
The space `Lp E p μ` is the subtype of elements of `α →ₘ[μ] E` (see ae_eq_fun) such that
`snorm f p μ` is finite. For `1 ≤ p`, `snorm` defines a norm and `Lp` is a complete metric space.
## Main definitions
* `snorm' f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F` and `p : ℝ`, where `α` is a measurable
space and `F` is a normed group.
* `snorm_ess_sup f μ` : seminorm in `ℒ∞`, equal to the essential supremum `ess_sup ∥f∥ μ`.
* `snorm f p μ` : for `p : ℝ≥0∞`, seminorm in `ℒp`, equal to `0` for `p=0`, to `snorm' f p μ`
for `0 < p < ∞` and to `snorm_ess_sup f μ` for `p = ∞`.
* `mem_ℒp f p μ` : property that the function `f` is almost everywhere measurable and has finite
p-seminorm for measure `μ` (`snorm f p μ < ∞`)
* `Lp E p μ` : elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. Defined
as an `add_subgroup` of `α →ₘ[μ] E`.
Lipschitz functions vanishing at zero act by composition on `Lp`. We define this action, and prove
that it is continuous. In particular,
* `continuous_linear_map.comp_Lp` defines the action on `Lp` of a continuous linear map.
* `Lp.pos_part` is the positive part of an `Lp` function.
* `Lp.neg_part` is the negative part of an `Lp` function.
When `α` is a topological space equipped with a finite Borel measure, there is a bounded linear map
from the normed space of bounded continuous functions (`α →ᵇ E`) to `Lp E p μ`. We construct this
as `bounded_continuous_function.to_Lp`.
## Notations
* `α →₁[μ] E` : the type `Lp E 1 μ`.
* `α →₂[μ] E` : the type `Lp E 2 μ`.
## Implementation
Since `Lp` is defined as an `add_subgroup`, dot notation does not work. Use `Lp.measurable f` to
say that the coercion of `f` to a genuine function is measurable, instead of the non-working
`f.measurable`.
To prove that two `Lp` elements are equal, it suffices to show that their coercions to functions
coincide almost everywhere (this is registered as an `ext` rule). This can often be done using
`filter_upwards`. For instance, a proof from first principles that `f + (g + h) = (f + g) + h`
could read (in the `Lp` namespace)
```
example (f g h : Lp E p μ) : (f + g) + h = f + (g + h) :=
begin
ext1,
filter_upwards [coe_fn_add (f + g) h, coe_fn_add f g, coe_fn_add f (g + h), coe_fn_add g h],
assume a ha1 ha2 ha3 ha4,
simp only [ha1, ha2, ha3, ha4, add_assoc],
end
```
The lemma `coe_fn_add` states that the coercion of `f + g` coincides almost everywhere with the sum
of the coercions of `f` and `g`. All such lemmas use `coe_fn` in their name, to distinguish the
function coercion from the coercion to almost everywhere defined functions.
-/
noncomputable theory
open topological_space measure_theory filter
open_locale nnreal ennreal big_operators topological_space
lemma fact_one_le_one_ennreal : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_refl _⟩
lemma fact_one_le_two_ennreal : fact ((1 : ℝ≥0∞) ≤ 2) :=
⟨ennreal.coe_le_coe.2 (show (1 : ℝ≥0) ≤ 2, by norm_num)⟩
lemma fact_one_le_top_ennreal : fact ((1 : ℝ≥0∞) ≤ ∞) := ⟨le_top⟩
local attribute [instance] fact_one_le_one_ennreal fact_one_le_two_ennreal fact_one_le_top_ennreal
variables {α E F G : Type*} [measurable_space α] {p : ℝ≥0∞} {q : ℝ} {μ : measure α}
[measurable_space E] [normed_group E]
[normed_group F] [normed_group G]
namespace measure_theory
section ℒp
/-!
### ℒp seminorm
We define the ℒp seminorm, denoted by `snorm f p μ`. For real `p`, it is given by an integral
formula (for which we use the notation `snorm' f p μ`), and for `p = ∞` it is the essential
supremum (for which we use the notation `snorm_ess_sup f μ`).
We also define a predicate `mem_ℒp f p μ`, requesting that a function is almost everywhere
measurable and has finite `snorm f p μ`.
This paragraph is devoted to the basic properties of these definitions. It is constructed as
follows: for a given property, we prove it for `snorm'` and `snorm_ess_sup` when it makes sense,
deduce it for `snorm`, and translate it in terms of `mem_ℒp`.
-/
section ℒp_space_definition
/-- `(∫ ∥f a∥^q ∂μ) ^ (1/q)`, which is a seminorm on the space of measurable functions for which
this quantity is finite -/
def snorm' (f : α → F) (q : ℝ) (μ : measure α) : ℝ≥0∞ := (∫⁻ a, (nnnorm (f a))^q ∂μ) ^ (1/q)
/-- seminorm for `ℒ∞`, equal to the essential supremum of `∥f∥`. -/
def snorm_ess_sup (f : α → F) (μ : measure α) := ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) μ
/-- `ℒp` seminorm, equal to `0` for `p=0`, to `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and to
`ess_sup ∥f∥ μ` for `p = ∞`. -/
def snorm (f : α → F) (p : ℝ≥0∞) (μ : measure α) : ℝ≥0∞ :=
if p = 0 then 0 else (if p = ∞ then snorm_ess_sup f μ else snorm' f (ennreal.to_real p) μ)
lemma snorm_eq_snorm' (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} :
snorm f p μ = snorm' f (ennreal.to_real p) μ :=
by simp [snorm, hp_ne_zero, hp_ne_top]
@[simp] lemma snorm_exponent_top {f : α → F} : snorm f ∞ μ = snorm_ess_sup f μ := by simp [snorm]
/-- The property that `f:α→E` is ae_measurable and `(∫ ∥f a∥^p ∂μ)^(1/p)` is finite if `p < ∞`, or
`ess_sup f < ∞` if `p = ∞`. -/
def mem_ℒp (f : α → E) (p : ℝ≥0∞) (μ : measure α) : Prop :=
ae_measurable f μ ∧ snorm f p μ < ∞
lemma mem_ℒp.ae_measurable {f : α → E} {p : ℝ≥0∞} {μ : measure α} (h : mem_ℒp f p μ) :
ae_measurable f μ := h.1
lemma lintegral_rpow_nnnorm_eq_rpow_snorm' {f : α → F} (hq0_lt : 0 < q) :
∫⁻ a, (nnnorm (f a)) ^ q ∂μ = (snorm' f q μ) ^ q :=
begin
rw [snorm', ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one],
exact (ne_of_lt hq0_lt).symm,
end
end ℒp_space_definition
section top
lemma mem_ℒp.snorm_lt_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ < ∞ := hfp.2
lemma mem_ℒp.snorm_ne_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ ≠ ∞ := ne_of_lt (hfp.2)
lemma lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top {f : α → F} (hq0_lt : 0 < q)
(hfq : snorm' f q μ < ∞) :
∫⁻ a, (nnnorm (f a)) ^ q ∂μ < ∞ :=
begin
rw lintegral_rpow_nnnorm_eq_rpow_snorm' hq0_lt,
exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hq0_lt) (ne_of_lt hfq),
end
end top
section zero
@[simp] lemma snorm'_exponent_zero {f : α → F} : snorm' f 0 μ = 1 :=
by rw [snorm', div_zero, ennreal.rpow_zero]
@[simp] lemma snorm_exponent_zero {f : α → F} : snorm f 0 μ = 0 :=
by simp [snorm]
lemma mem_ℒp_zero_iff_ae_measurable {f : α → E} : mem_ℒp f 0 μ ↔ ae_measurable f μ :=
by simp [mem_ℒp, snorm_exponent_zero]
@[simp] lemma snorm'_zero (hp0_lt : 0 < q) : snorm' (0 : α → F) q μ = 0 :=
by simp [snorm', hp0_lt]
@[simp] lemma snorm'_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) : snorm' (0 : α → F) q μ = 0 :=
begin
cases le_or_lt 0 q with hq0 hq_neg,
{ exact snorm'_zero (lt_of_le_of_ne hq0 hq0_ne.symm), },
{ simp [snorm', ennreal.rpow_eq_zero_iff, hμ, hq_neg], },
end
@[simp] lemma snorm_ess_sup_zero : snorm_ess_sup (0 : α → F) μ = 0 :=
begin
simp_rw [snorm_ess_sup, pi.zero_apply, nnnorm_zero, ennreal.coe_zero, ←ennreal.bot_eq_zero],
exact ess_sup_const_bot,
end
@[simp] lemma snorm_zero : snorm (0 : α → F) p μ = 0 :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp only [h_top, snorm_exponent_top, snorm_ess_sup_zero], },
rw ←ne.def at h0,
simp [snorm_eq_snorm' h0 h_top,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
lemma zero_mem_ℒp : mem_ℒp (0 : α → E) p μ :=
⟨measurable_zero.ae_measurable, by { rw snorm_zero, exact ennreal.coe_lt_top, } ⟩
lemma snorm'_measure_zero_of_pos {f : α → F} (hq_pos : 0 < q) : snorm' f q 0 = 0 :=
by simp [snorm', hq_pos]
lemma snorm'_measure_zero_of_exponent_zero {f : α → F} : snorm' f 0 0 = 1 := by simp [snorm']
lemma snorm'_measure_zero_of_neg {f : α → F} (hq_neg : q < 0) : snorm' f q 0 = ∞ :=
by simp [snorm', hq_neg]
@[simp] lemma snorm_ess_sup_measure_zero {f : α → F} : snorm_ess_sup f 0 = 0 :=
by simp [snorm_ess_sup]
@[simp] lemma snorm_measure_zero {f : α → F} : snorm f p 0 = 0 :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top], },
rw ←ne.def at h0,
simp [snorm_eq_snorm' h0 h_top, snorm',
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
end zero
section const
lemma snorm'_const (c : F) (hq_pos : 0 < q) :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) :=
begin
rw [snorm', lintegral_const, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [hq_pos.le])],
congr,
rw ←ennreal.rpow_mul,
suffices hq_cancel : q * (1/q) = 1, by rw [hq_cancel, ennreal.rpow_one],
rw [one_div, mul_inv_cancel (ne_of_lt hq_pos).symm],
end
lemma snorm'_const' [finite_measure μ] (c : F) (hc_ne_zero : c ≠ 0) (hq_ne_zero : q ≠ 0) :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) :=
begin
rw [snorm', lintegral_const, ennreal.mul_rpow_of_ne_top _ (measure_ne_top μ set.univ)],
{ congr,
rw ←ennreal.rpow_mul,
suffices hp_cancel : q * (1/q) = 1, by rw [hp_cancel, ennreal.rpow_one],
rw [one_div, mul_inv_cancel hq_ne_zero], },
{ rw [ne.def, ennreal.rpow_eq_top_iff, auto.not_or_eq, auto.not_and_eq, auto.not_and_eq],
split,
{ left,
rwa [ennreal.coe_eq_zero, nnnorm_eq_zero], },
{ exact or.inl ennreal.coe_ne_top, }, },
end
lemma snorm_ess_sup_const (c : F) (hμ : μ ≠ 0) :
snorm_ess_sup (λ x : α, c) μ = (nnnorm c : ℝ≥0∞) :=
by rw [snorm_ess_sup, ess_sup_const _ hμ]
lemma snorm'_const_of_probability_measure (c : F) (hq_pos : 0 < q) [probability_measure μ] :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) :=
by simp [snorm'_const c hq_pos, measure_univ]
lemma snorm_const (c : F) (h0 : p ≠ 0) (hμ : μ ≠ 0) :
snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) :=
begin
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup_const c hμ], },
simp [snorm_eq_snorm' h0 h_top, snorm'_const,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
lemma snorm_const' (c : F) (h0 : p ≠ 0) (h_top: p ≠ ∞) :
snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) :=
begin
simp [snorm_eq_snorm' h0 h_top, snorm'_const,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
lemma mem_ℒp_const (c : E) [finite_measure μ] : mem_ℒp (λ a:α, c) p μ :=
begin
refine ⟨measurable_const.ae_measurable, _⟩,
by_cases h0 : p = 0,
{ simp [h0], },
by_cases hμ : μ = 0,
{ simp [hμ], },
rw snorm_const c h0 hμ,
refine ennreal.mul_lt_top ennreal.coe_lt_top _,
refine ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ),
simp,
end
end const
lemma snorm'_mono_ae {f : α → F} {g : α → G} (hq : 0 ≤ q) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) :
snorm' f q μ ≤ snorm' g q μ :=
begin
rw [snorm'],
refine ennreal.rpow_le_rpow _ (one_div_nonneg.2 hq),
refine lintegral_mono_ae (h.mono $ λ x hx, _),
exact ennreal.rpow_le_rpow (ennreal.coe_le_coe.2 hx) hq
end
lemma snorm'_congr_norm_ae {f g : α → F} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) :
snorm' f q μ = snorm' g q μ :=
begin
have : (λ x, (nnnorm (f x) ^ q : ℝ≥0∞)) =ᵐ[μ] (λ x, nnnorm (g x) ^ q),
from hfg.mono (λ x hx, by { simp only [← coe_nnnorm, nnreal.coe_eq] at hx, simp [hx] }),
simp only [snorm', lintegral_congr_ae this]
end
lemma snorm'_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm' f q μ = snorm' g q μ :=
snorm'_congr_norm_ae (hfg.fun_comp _)
lemma snorm_ess_sup_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) :
snorm_ess_sup f μ = snorm_ess_sup g μ :=
ess_sup_congr_ae (hfg.fun_comp (coe ∘ nnnorm))
lemma snorm_mono_ae {f : α → F} {g : α → G} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) :
snorm f p μ ≤ snorm g p μ :=
begin
simp only [snorm],
split_ifs,
{ exact le_rfl },
{ refine ess_sup_mono_ae (h.mono $ λ x hx, _),
exact_mod_cast hx },
{ exact snorm'_mono_ae ennreal.to_real_nonneg h }
end
lemma snorm_le_of_ae_bound {f : α → F} {C : ℝ} (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
snorm f p μ ≤ ((μ set.univ) ^ p.to_real⁻¹) * (ennreal.of_real C) :=
begin
by_cases hμ : μ = 0,
{ simp [hμ] },
haveI : μ.ae.ne_bot := ae_ne_bot.mpr hμ,
by_cases hp : p = 0,
{ simp [hp] },
have hC : 0 ≤ C, from le_trans (norm_nonneg _) hfC.exists.some_spec,
have hC' : ∥C∥ = C := by rw [real.norm_eq_abs, abs_eq_self.mpr hC],
have : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥(λ _, C) x∥, from hfC.mono (λ x hx, hx.trans (le_of_eq hC'.symm)),
convert snorm_mono_ae this,
rw [snorm_const _ hp hμ, mul_comm, ← of_real_norm_eq_coe_nnnorm, hC', one_div]
end
lemma snorm_congr_norm_ae {f : α → F} {g : α → G} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) :
snorm f p μ = snorm g p μ :=
le_antisymm (snorm_mono_ae $ eventually_eq.le hfg)
(snorm_mono_ae $ (eventually_eq.symm hfg).le)
@[simp] lemma snorm'_norm {f : α → F} : snorm' (λ a, ∥f a∥) q μ = snorm' f q μ :=
by simp [snorm']
@[simp] lemma snorm_norm (f : α → F) : snorm (λ x, ∥f x∥) p μ = snorm f p μ :=
snorm_congr_norm_ae $ eventually_of_forall $ λ x, norm_norm _
lemma snorm'_norm_rpow (f : α → F) (p q : ℝ) (hq_pos : 0 < q) :
snorm' (λ x, ∥f x∥ ^ q) p μ = (snorm' f (p * q) μ) ^ q :=
begin
simp_rw snorm',
rw [← ennreal.rpow_mul, ←one_div_mul_one_div],
simp_rw one_div,
rw [mul_assoc, inv_mul_cancel hq_pos.ne.symm, mul_one],
congr,
ext1 x,
simp_rw ← of_real_norm_eq_coe_nnnorm,
rw [real.norm_eq_abs, abs_eq_self.mpr (real.rpow_nonneg_of_nonneg (norm_nonneg _) _),
mul_comm, ← ennreal.of_real_rpow_of_nonneg (norm_nonneg _) hq_pos.le, ennreal.rpow_mul],
end
lemma snorm_norm_rpow (f : α → F) (hq_pos : 0 < q) :
snorm (λ x, ∥f x∥ ^ q) p μ = (snorm f (p * ennreal.of_real q) μ) ^ q :=
begin
by_cases h0 : p = 0,
{ simp [h0, ennreal.zero_rpow_of_pos hq_pos], },
by_cases hp_top : p = ∞,
{ simp only [hp_top, snorm_exponent_top, ennreal.top_mul, hq_pos.not_le, ennreal.of_real_eq_zero,
if_false, snorm_exponent_top, snorm_ess_sup],
have h_rpow : ess_sup (λ (x : α), (nnnorm (∥f x∥ ^ q) : ℝ≥0∞)) μ
= ess_sup (λ (x : α), (↑(nnnorm (f x))) ^ q) μ,
{ congr,
ext1 x,
nth_rewrite 1 ← nnnorm_norm,
rw [ennreal.coe_rpow_of_nonneg _ hq_pos.le, ennreal.coe_eq_coe],
ext,
push_cast,
rw real.norm_rpow_of_nonneg (norm_nonneg _), },
rw h_rpow,
have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hq_pos,
have h_rpow_surj := (ennreal.rpow_left_bijective hq_pos.ne.symm).2,
let iso := h_rpow_mono.order_iso_of_surjective _ h_rpow_surj,
exact (iso.ess_sup_apply (λ x, ((nnnorm (f x)) : ℝ≥0∞)) μ).symm, },
rw [snorm_eq_snorm' h0 hp_top, snorm_eq_snorm' _ _],
swap, { refine mul_ne_zero h0 _, rwa [ne.def, ennreal.of_real_eq_zero, not_le], },
swap, { exact ennreal.mul_ne_top hp_top ennreal.of_real_ne_top, },
rw [ennreal.to_real_mul, ennreal.to_real_of_real hq_pos.le],
exact snorm'_norm_rpow f p.to_real q hq_pos,
end
lemma snorm_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm f p μ = snorm g p μ :=
snorm_congr_norm_ae $ hfg.mono (λ x hx, hx ▸ rfl)
lemma mem_ℒp_congr_ae {f g : α → E} (hfg : f =ᵐ[μ] g) : mem_ℒp f p μ ↔ mem_ℒp g p μ :=
by simp only [mem_ℒp, snorm_congr_ae hfg, ae_measurable_congr hfg]
lemma mem_ℒp.ae_eq {f g : α → E} (hfg : f =ᵐ[μ] g) (hf_Lp : mem_ℒp f p μ) : mem_ℒp g p μ :=
(mem_ℒp_congr_ae hfg).1 hf_Lp
lemma mem_ℒp.of_le [measurable_space F] {f : α → E} {g : α → F}
(hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : mem_ℒp f p μ :=
⟨hf, (snorm_mono_ae hfg).trans_lt hg.snorm_lt_top⟩
lemma mem_ℒp.of_bound [finite_measure μ] {f : α → E} (hf : ae_measurable f μ)
(C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
mem_ℒp f p μ :=
(mem_ℒp_const C).of_le hf (hfC.mono (λ x hx, le_trans hx (le_abs_self _)))
section opens_measurable_space
variable [opens_measurable_space E]
lemma mem_ℒp.norm {f : α → E} (h : mem_ℒp f p μ) : mem_ℒp (λ x, ∥f x∥) p μ :=
h.of_le h.ae_measurable.norm (eventually_of_forall (λ x, by simp))
lemma snorm'_eq_zero_of_ae_zero {f : α → F} (hq0_lt : 0 < q) (hf_zero : f =ᵐ[μ] 0) :
snorm' f q μ = 0 :=
by rw [snorm'_congr_ae hf_zero, snorm'_zero hq0_lt]
lemma snorm'_eq_zero_of_ae_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) {f : α → F} (hf_zero : f =ᵐ[μ] 0) :
snorm' f q μ = 0 :=
by rw [snorm'_congr_ae hf_zero, snorm'_zero' hq0_ne hμ]
lemma ae_eq_zero_of_snorm'_eq_zero {f : α → E} (hq0 : 0 ≤ q) (hf : ae_measurable f μ)
(h : snorm' f q μ = 0) : f =ᵐ[μ] 0 :=
begin
rw [snorm', ennreal.rpow_eq_zero_iff] at h,
cases h,
{ rw lintegral_eq_zero_iff' (hf.ennnorm.pow_const q) at h,
refine h.left.mono (λ x hx, _),
rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx,
cases hx,
{ cases hx with hx _,
rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, },
{ exact absurd hx.left ennreal.coe_ne_top, }, },
{ exfalso,
rw [one_div, inv_lt_zero] at h,
exact hq0.not_lt h.right },
end
lemma snorm'_eq_zero_iff (hq0_lt : 0 < q) {f : α → E} (hf : ae_measurable f μ) :
snorm' f q μ = 0 ↔ f =ᵐ[μ] 0 :=
⟨ae_eq_zero_of_snorm'_eq_zero (le_of_lt hq0_lt) hf, snorm'_eq_zero_of_ae_zero hq0_lt⟩
lemma coe_nnnorm_ae_le_snorm_ess_sup (f : α → F) (μ : measure α) :
∀ᵐ x ∂μ, (nnnorm (f x) : ℝ≥0∞) ≤ snorm_ess_sup f μ :=
ennreal.ae_le_ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞))
@[simp] lemma snorm_ess_sup_eq_zero_iff {f : α → F} : snorm_ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 :=
by simp [eventually_eq, snorm_ess_sup]
lemma snorm_eq_zero_iff {f : α → E} (hf : ae_measurable f μ) (h0 : p ≠ 0) :
snorm f p μ = 0 ↔ f =ᵐ[μ] 0 :=
begin
by_cases h_top : p = ∞,
{ rw [h_top, snorm_exponent_top, snorm_ess_sup_eq_zero_iff], },
rw snorm_eq_snorm' h0 h_top,
exact snorm'_eq_zero_iff
(ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩) hf,
end
end opens_measurable_space
@[simp] lemma snorm'_neg {f : α → F} : snorm' (-f) q μ = snorm' f q μ := by simp [snorm']
@[simp] lemma snorm_neg {f : α → F} : snorm (-f) p μ = snorm f p μ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup], },
simp [snorm_eq_snorm' h0 h_top],
end
section borel_space
variable [borel_space E]
lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (-f) p μ :=
⟨ae_measurable.neg hf.1, by simp [hf.right]⟩
lemma snorm'_le_snorm'_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q)
{f : α → E} (hf : ae_measurable f μ) :
snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) :=
begin
have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq,
by_cases hpq_eq : p = q,
{ rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one],
exact le_refl _, },
have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq,
let g := λ a : α, (1 : ℝ≥0∞),
have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ,
from lintegral_congr (λ a, by simp),
repeat {rw snorm'},
rw h_rw,
let r := p * q / (q - p),
have hpqr : 1/p = 1/q + 1/r,
{ field_simp [(ne_of_lt hp0_lt).symm,
(ne_of_lt hq0_lt).symm],
ring, },
calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p)
≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) :
ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.ennnorm
ae_measurable_const
... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) :
by simp [hpqr],
end
lemma snorm'_le_snorm_ess_sup_mul_rpow_measure_univ (hq_pos : 0 < q) {f : α → F} :
snorm' f q μ ≤ snorm_ess_sup f μ * (μ set.univ) ^ (1/q) :=
begin
have h_le : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ ≤ ∫⁻ (a : α), (snorm_ess_sup f μ) ^ q ∂μ,
{ refine lintegral_mono_ae _,
have h_nnnorm_le_snorm_ess_sup := coe_nnnorm_ae_le_snorm_ess_sup f μ,
refine h_nnnorm_le_snorm_ess_sup.mono (λ x hx, ennreal.rpow_le_rpow hx (le_of_lt hq_pos)), },
rw [snorm', ←ennreal.rpow_one (snorm_ess_sup f μ)],
nth_rewrite 1 ←mul_inv_cancel (ne_of_lt hq_pos).symm,
rw [ennreal.rpow_mul, one_div,
←@ennreal.mul_rpow_of_nonneg _ _ q⁻¹ (by simp [hq_pos.le])],
refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le]),
rwa lintegral_const at h_le,
end
lemma snorm'_le_snorm'_of_exponent_le {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α)
[probability_measure μ] {f : α → E} (hf : ae_measurable f μ) :
snorm' f p μ ≤ snorm' f q μ :=
begin
have h_le_μ := snorm'_le_snorm'_mul_rpow_measure_univ hp0_lt hpq hf,
rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ,
end
lemma snorm'_le_snorm_ess_sup (hq_pos : 0 < q) {f : α → F} [probability_measure μ] :
snorm' f q μ ≤ snorm_ess_sup f μ :=
le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hq_pos) (le_of_eq (by simp [measure_univ]))
lemma snorm_le_snorm_of_exponent_le {p q : ℝ≥0∞} (hpq : p ≤ q) [probability_measure μ]
{f : α → E} (hf : ae_measurable f μ) :
snorm f p μ ≤ snorm f q μ :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
rw ←ne.def at hp0,
by_cases hq_top : q = ∞,
{ by_cases hp_top : p = ∞,
{ rw [hq_top, hp_top],
exact le_refl _, },
{ have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
rw [snorm_eq_snorm' hp0 hp_top, hq_top, snorm_exponent_top],
refine le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) (le_of_eq _),
simp [measure_univ], }, },
{ have hp_top : p ≠ ∞,
{ by_contra hp_eq_top,
push_neg at hp_eq_top,
refine hq_top _,
rwa [hp_eq_top, top_le_iff] at hpq, },
have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
have hq0 : q ≠ 0,
{ by_contra hq_eq_zero,
push_neg at hq_eq_zero,
have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _),
rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos,
exact (lt_irrefl _) hp_pos, },
have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top,
rw [snorm_eq_snorm' hp0 hp_top, snorm_eq_snorm' hq0 hq_top],
exact snorm'_le_snorm'_of_exponent_le hp_pos hpq_real _ hf, },
end
lemma snorm'_lt_top_of_snorm'_lt_top_of_exponent_le {p q : ℝ} [finite_measure μ] {f : α → E}
(hf : ae_measurable f μ) (hfq_lt_top : snorm' f q μ < ∞) (hp_nonneg : 0 ≤ p) (hpq : p ≤ q) :
snorm' f p μ < ∞ :=
begin
cases le_or_lt p 0 with hp_nonpos hp_pos,
{ rw le_antisymm hp_nonpos hp_nonneg,
simp, },
have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq,
calc snorm' f p μ
≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) :
snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq hf
... < ∞ :
begin
rw ennreal.mul_lt_top_iff,
refine or.inl ⟨hfq_lt_top, ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)⟩,
rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos],
end
end
lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ℝ≥0∞} [finite_measure μ] {f : α → E}
(hfq : mem_ℒp f q μ) (hpq : p ≤ q) :
mem_ℒp f p μ :=
begin
cases hfq with hfq_m hfq_lt_top,
by_cases hp0 : p = 0,
{ rwa [hp0, mem_ℒp_zero_iff_ae_measurable], },
rw ←ne.def at hp0,
refine ⟨hfq_m, _⟩,
by_cases hp_top : p = ∞,
{ have hq_top : q = ∞,
by rwa [hp_top, top_le_iff] at hpq,
rw [hp_top],
rwa hq_top at hfq_lt_top, },
have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
by_cases hq_top : q = ∞,
{ rw snorm_eq_snorm' hp0 hp_top,
rw [hq_top, snorm_exponent_top] at hfq_lt_top,
refine lt_of_le_of_lt (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) _,
refine ennreal.mul_lt_top hfq_lt_top _,
exact ennreal.rpow_lt_top_of_nonneg (by simp [le_of_lt hp_pos]) (measure_ne_top μ set.univ), },
have hq0 : q ≠ 0,
{ by_contra hq_eq_zero,
push_neg at hq_eq_zero,
have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _),
rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos,
exact (lt_irrefl _) hp_pos, },
have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top,
rw snorm_eq_snorm' hp0 hp_top,
rw snorm_eq_snorm' hq0 hq_top at hfq_lt_top,
exact snorm'_lt_top_of_snorm'_lt_top_of_exponent_le hfq_m hfq_lt_top (le_of_lt hp_pos) hpq_real,
end
lemma snorm'_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hq1 : 1 ≤ q) :
snorm' (f + g) q μ ≤ snorm' f q μ + snorm' g q μ :=
calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q)
≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞))
+ (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) :
begin
refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [le_trans zero_le_one hq1]),
refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hq1)),
simp [←ennreal.coe_add, nnnorm_add_le],
end
... ≤ snorm' f q μ + snorm' g q μ :
ennreal.lintegral_Lp_add_le hf.ennnorm hg.ennnorm hq1
lemma snorm_ess_sup_add_le {f g : α → F} :
snorm_ess_sup (f + g) μ ≤ snorm_ess_sup f μ + snorm_ess_sup g μ :=
begin
refine le_trans (ess_sup_mono_ae (eventually_of_forall (λ x, _)))
(ennreal.ess_sup_add_le _ _),
simp_rw [pi.add_apply, ←ennreal.coe_add, ennreal.coe_le_coe],
exact nnnorm_add_le _ _,
end
lemma snorm_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) :
snorm (f + g) p μ ≤ snorm f p μ + snorm g p μ :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
by_cases hp_top : p = ∞,
{ simp [hp_top, snorm_ess_sup_add_le], },
have hp1_real : 1 ≤ p.to_real,
by rwa [← ennreal.one_to_real, ennreal.to_real_le_to_real ennreal.one_ne_top hp_top],
repeat { rw snorm_eq_snorm' hp0 hp_top, },
exact snorm'_add_le hf hg hp1_real,
end
lemma snorm'_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι}
(hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hq1 : 1 ≤ q) :
snorm' (∑ i in s, f i) q μ ≤ ∑ i in s, snorm' (f i) q μ :=
finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm' f q μ)
(λ f, ae_measurable f μ) (snorm'_zero (zero_lt_one.trans_le hq1))
(λ f g hf hg, snorm'_add_le hf hg hq1) (λ x y, ae_measurable.add) _ hfs
lemma snorm_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι}
(hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hp1 : 1 ≤ p) :
snorm (∑ i in s, f i) p μ ≤ ∑ i in s, snorm (f i) p μ :=
finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm f p μ)
(λ f, ae_measurable f μ) snorm_zero (λ f g hf hg, snorm_add_le hf hg hp1)
(λ x y, ae_measurable.add) _ hfs
lemma snorm_add_lt_top_of_one_le {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ)
(hq1 : 1 ≤ p) : snorm (f + g) p μ < ∞ :=
lt_of_le_of_lt (snorm_add_le hf.1 hg.1 hq1) (ennreal.add_lt_top.mpr ⟨hf.2, hg.2⟩)
lemma snorm'_add_lt_top_of_le_one {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ)
(hf_snorm : snorm' f q μ < ∞) (hg_snorm : snorm' g q μ < ∞) (hq_pos : 0 < q) (hq1 : q ≤ 1) :
snorm' (f + g) q μ < ∞ :=
calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q)
≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞))
+ (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) :
begin
refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [hq_pos.le]),
refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ hq_pos.le),
simp [←ennreal.coe_add, nnnorm_add_le],
end
... ≤ (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q + (nnnorm (g a) : ℝ≥0∞) ^ q ∂μ) ^ (1 / q) :
begin
refine @ennreal.rpow_le_rpow _ _ (1/q) (lintegral_mono (λ a, _)) (by simp [hq_pos.le]),
exact ennreal.rpow_add_le_add_rpow _ _ hq_pos hq1,
end
... < ∞ :
begin
refine @ennreal.rpow_lt_top_of_nonneg _ (1/q) (by simp [hq_pos.le]) _,
rw [lintegral_add' (hf.ennnorm.pow_const q)
(hg.ennnorm.pow_const q), ennreal.add_ne_top, ←lt_top_iff_ne_top,
←lt_top_iff_ne_top],
exact ⟨lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hf_snorm,
lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hg_snorm⟩,
end
lemma snorm_add_lt_top {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
snorm (f + g) p μ < ∞ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
rw ←ne.def at h0,
cases le_total 1 p with hp1 hp1,
{ exact snorm_add_lt_top_of_one_le hf hg hp1, },
have hp_top : p ≠ ∞, from (lt_of_le_of_lt hp1 ennreal.coe_lt_top).ne,
have hp_pos : 0 < p.to_real,
{ rw [← ennreal.zero_to_real, @ennreal.to_real_lt_to_real 0 p ennreal.coe_ne_top hp_top],
exact ((zero_le p).lt_of_ne h0.symm), },
have hp1_real : p.to_real ≤ 1,
{ rwa [← ennreal.one_to_real, @ennreal.to_real_le_to_real p 1 hp_top ennreal.coe_ne_top], },
rw snorm_eq_snorm' h0 hp_top,
rw [mem_ℒp, snorm_eq_snorm' h0 hp_top] at hf hg,
exact snorm'_add_lt_top_of_le_one hf.1 hg.1 hf.2 hg.2 hp_pos hp1_real,
end
section second_countable_topology
variable [second_countable_topology E]
lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f + g) p μ :=
⟨ae_measurable.add hf.1 hg.1, snorm_add_lt_top hf hg⟩
lemma mem_ℒp.sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f - g) p μ :=
by { rw sub_eq_add_neg, exact hf.add hg.neg }
end second_countable_topology
end borel_space
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F]
lemma snorm'_const_smul {f : α → F} (c : 𝕜) (hq0_lt : 0 < q) :
snorm' (c • f) q μ = (nnnorm c : ℝ≥0∞) * snorm' f q μ :=
begin
rw snorm',
simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul,
ennreal.mul_rpow_of_nonneg _ _ (le_of_lt hq0_lt)],
suffices h_integral : ∫⁻ a, ↑(nnnorm c) ^ q * ↑(nnnorm (f a)) ^ q ∂μ
= (nnnorm c : ℝ≥0∞)^q * ∫⁻ a, (nnnorm (f a)) ^ q ∂μ,
{ apply_fun (λ x, x ^ (1/q)) at h_integral,
rw [h_integral, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [le_of_lt hq0_lt])],
congr,
simp_rw [←ennreal.rpow_mul, one_div, mul_inv_cancel (ne_of_lt hq0_lt).symm,
ennreal.rpow_one], },
rw lintegral_const_mul',
rw ennreal.coe_rpow_of_nonneg _ hq0_lt.le,
exact ennreal.coe_ne_top,
end
lemma snorm_ess_sup_const_smul {f : α → F} (c : 𝕜) :
snorm_ess_sup (c • f) μ = (nnnorm c : ℝ≥0∞) * snorm_ess_sup f μ :=
by simp_rw [snorm_ess_sup, pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.ess_sup_const_mul]
lemma snorm_const_smul {f : α → F} (c : 𝕜) :
snorm (c • f) p μ = (nnnorm c : ℝ≥0∞) * snorm f p μ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup_const_smul], },
repeat { rw snorm_eq_snorm' h0 h_top, },
rw ←ne.def at h0,
exact snorm'_const_smul c
(ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩),
end
lemma mem_ℒp.const_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] [borel_space E] {f : α → E}
(hf : mem_ℒp f p μ) (c : 𝕜) :
mem_ℒp (c • f) p μ :=
⟨ae_measurable.const_smul hf.1 c,
lt_of_le_of_lt (le_of_eq (snorm_const_smul c)) (ennreal.mul_lt_top ennreal.coe_lt_top hf.2)⟩
lemma mem_ℒp.const_mul [measurable_space 𝕜] [borel_space 𝕜]
{f : α → 𝕜} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (λ x, c * f x) p μ :=
hf.const_smul c
lemma snorm'_smul_le_mul_snorm' [opens_measurable_space E] [measurable_space 𝕜]
[opens_measurable_space 𝕜] {p q r : ℝ}
{f : α → E} (hf : ae_measurable f μ) {φ : α → 𝕜} (hφ : ae_measurable φ μ)
(hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) :
snorm' (φ • f) p μ ≤ snorm' φ q μ * snorm' f r μ :=
begin
simp_rw [snorm', pi.smul_apply', nnnorm_smul, ennreal.coe_mul],
exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.ennnorm
hf.ennnorm,
end
end normed_space
section monotonicity
lemma snorm_le_mul_snorm_aux_of_nonneg {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : 0 ≤ c) (p : ℝ≥0∞) :
snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ :=
begin
lift c to ℝ≥0 using hc,
rw [ennreal.of_real_coe_nnreal, ← c.nnnorm_eq, ← snorm_norm g, ← snorm_const_smul (c : ℝ)],
swap, apply_instance,
refine snorm_mono_ae _,
simpa
end
lemma snorm_le_mul_snorm_aux_of_neg {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : c < 0) (p : ℝ≥0∞) :
snorm f p μ = 0 ∧ snorm g p μ = 0 :=
begin
suffices : f =ᵐ[μ] 0 ∧ g =ᵐ[μ] 0,
by simp [snorm_congr_ae this.1, snorm_congr_ae this.2],
refine ⟨h.mono $ λ x hx, _, h.mono $ λ x hx, _⟩,
{ refine norm_le_zero_iff.1 (hx.trans _),
exact mul_nonpos_of_nonpos_of_nonneg hc.le (norm_nonneg _) },
{ refine norm_le_zero_iff.1 (nonpos_of_mul_nonneg_right _ hc),
exact (norm_nonneg _).trans hx }
end
lemma snorm_le_mul_snorm_of_ae_le_mul {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (p : ℝ≥0∞) :
snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ :=
begin
cases le_or_lt 0 c with hc hc,
{ exact snorm_le_mul_snorm_aux_of_nonneg h hc p },
{ simp [snorm_le_mul_snorm_aux_of_neg h hc p] }
end
lemma mem_ℒp.of_le_mul [measurable_space F] {f : α → E} {g : α → F} {c : ℝ}
(hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) :
mem_ℒp f p μ :=
begin
simp only [mem_ℒp, hf, true_and],
apply lt_of_le_of_lt (snorm_le_mul_snorm_of_ae_le_mul hfg p),
simp [lt_top_iff_ne_top, hg.snorm_ne_top],
end
end monotonicity
end ℒp
/-!
### Lp space
The space of equivalence classes of measurable functions for which `snorm f p μ < ∞`.
-/
@[simp] lemma snorm_ae_eq_fun {α E : Type*} [measurable_space α] {μ : measure α}
[measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hf : ae_measurable f μ) :
snorm (ae_eq_fun.mk f hf) p μ = snorm f p μ :=
snorm_congr_ae (ae_eq_fun.coe_fn_mk _ _)
lemma mem_ℒp.snorm_mk_lt_top {α E : Type*} [measurable_space α] {μ : measure α}
[measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hfp : mem_ℒp f p μ) :
snorm (ae_eq_fun.mk f hfp.1) p μ < ∞ :=
by simp [hfp.2]
/-- Lp space -/
def Lp {α} (E : Type*) [measurable_space α] [measurable_space E] [normed_group E]
[borel_space E] [second_countable_topology E]
(p : ℝ≥0∞) (μ : measure α) : add_subgroup (α →ₘ[μ] E) :=
{ carrier := {f | snorm f p μ < ∞},
zero_mem' := by simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero],
add_mem' := λ f g hf hg, by simp [snorm_congr_ae (ae_eq_fun.coe_fn_add _ _),
snorm_add_lt_top ⟨f.ae_measurable, hf⟩ ⟨g.ae_measurable, hg⟩],
neg_mem' := λ f hf,
by rwa [set.mem_set_of_eq, snorm_congr_ae (ae_eq_fun.coe_fn_neg _), snorm_neg] }
localized "notation α ` →₁[`:25 μ `] ` E := measure_theory.Lp E 1 μ" in measure_theory
localized "notation α ` →₂[`:25 μ `] ` E := measure_theory.Lp E 2 μ" in measure_theory
namespace mem_ℒp
variables [borel_space E] [second_countable_topology E]
/-- make an element of Lp from a function verifying `mem_ℒp` -/
def to_Lp (f : α → E) (h_mem_ℒp : mem_ℒp f p μ) : Lp E p μ :=
⟨ae_eq_fun.mk f h_mem_ℒp.1, h_mem_ℒp.snorm_mk_lt_top⟩
lemma coe_fn_to_Lp {f : α → E} (hf : mem_ℒp f p μ) : hf.to_Lp f =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk _ _
@[simp] lemma to_Lp_eq_to_Lp_iff {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
hf.to_Lp f = hg.to_Lp g ↔ f =ᵐ[μ] g :=
by simp [to_Lp]
@[simp] lemma to_Lp_zero (h : mem_ℒp (0 : α → E) p μ ) : h.to_Lp 0 = 0 := rfl
lemma to_Lp_add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
(hf.add hg).to_Lp (f + g) = hf.to_Lp f + hg.to_Lp g := rfl
lemma to_Lp_neg {f : α → E} (hf : mem_ℒp f p μ) : hf.neg.to_Lp (-f) = - hf.to_Lp f := rfl
lemma to_Lp_sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
(hf.sub hg).to_Lp (f - g) = hf.to_Lp f - hg.to_Lp g := rfl
end mem_ℒp
namespace Lp
variables [borel_space E] [second_countable_topology E]
instance : has_coe_to_fun (Lp E p μ) := ⟨λ _, α → E, λ f, ((f : α →ₘ[μ] E) : α → E)⟩
@[ext] lemma ext {f g : Lp E p μ} (h : f =ᵐ[μ] g) : f = g :=
begin
cases f,
cases g,
simp only [subtype.mk_eq_mk],
exact ae_eq_fun.ext h
end
lemma ext_iff {f g : Lp E p μ} : f = g ↔ f =ᵐ[μ] g :=
⟨λ h, by rw h, λ h, ext h⟩
lemma mem_Lp_iff_snorm_lt_top {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ snorm f p μ < ∞ := iff.refl _
lemma mem_Lp_iff_mem_ℒp {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ mem_ℒp f p μ :=
by simp [mem_Lp_iff_snorm_lt_top, mem_ℒp, f.measurable.ae_measurable]
lemma antimono [finite_measure μ] {p q : ℝ≥0∞} (hpq : p ≤ q) : Lp E q μ ≤ Lp E p μ :=
λ f hf, (mem_ℒp.mem_ℒp_of_exponent_le ⟨f.ae_measurable, hf⟩ hpq).2
@[simp] lemma coe_fn_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) :
((⟨f, hf⟩ : Lp E p μ) : α → E) = f := rfl
@[simp] lemma coe_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) :
((⟨f, hf⟩ : Lp E p μ) : α →ₘ[μ] E) = f := rfl
@[simp] lemma to_Lp_coe_fn (f : Lp E p μ) (hf : mem_ℒp f p μ) : hf.to_Lp f = f :=
by { cases f, simp [mem_ℒp.to_Lp] }
lemma snorm_lt_top (f : Lp E p μ) : snorm f p μ < ∞ := f.prop
lemma snorm_ne_top (f : Lp E p μ) : snorm f p μ ≠ ∞ := (snorm_lt_top f).ne
protected lemma measurable (f : Lp E p μ) : measurable f := f.val.measurable
protected lemma ae_measurable (f : Lp E p μ) : ae_measurable f μ := f.val.ae_measurable
protected lemma mem_ℒp (f : Lp E p μ) : mem_ℒp f p μ := ⟨Lp.ae_measurable f, f.prop⟩
variables (E p μ)
lemma coe_fn_zero : ⇑(0 : Lp E p μ) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero
variables {E p μ}
lemma coe_fn_neg (f : Lp E p μ) : ⇑(-f) =ᵐ[μ] -f := ae_eq_fun.coe_fn_neg _
lemma coe_fn_add (f g : Lp E p μ) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _
lemma coe_fn_sub (f g : Lp E p μ) : ⇑(f - g) =ᵐ[μ] f - g := ae_eq_fun.coe_fn_sub _ _
lemma mem_Lp_const (α) [measurable_space α] (μ : measure α) (c : E) [finite_measure μ] :
@ae_eq_fun.const α _ _ μ _ c ∈ Lp E p μ :=
(mem_ℒp_const c).snorm_mk_lt_top
instance : has_norm (Lp E p μ) := { norm := λ f, ennreal.to_real (snorm f p μ) }
instance : has_dist (Lp E p μ) := { dist := λ f g, ∥f - g∥}
instance : has_edist (Lp E p μ) := { edist := λ f g, ennreal.of_real (dist f g) }
lemma norm_def (f : Lp E p μ) : ∥f∥ = ennreal.to_real (snorm f p μ) := rfl
@[simp] lemma norm_to_Lp (f : α → E) (hf : mem_ℒp f p μ) :
∥hf.to_Lp f∥ = ennreal.to_real (snorm f p μ) :=
by rw [norm_def, snorm_congr_ae (mem_ℒp.coe_fn_to_Lp hf)]
lemma dist_def (f g : Lp E p μ) : dist f g = (snorm (f - g) p μ).to_real :=
begin
simp_rw [dist, norm_def],
congr' 1,
apply snorm_congr_ae (coe_fn_sub _ _),
end
lemma edist_def (f g : Lp E p μ) : edist f g = snorm (f - g) p μ :=
begin
simp_rw [edist, dist, norm_def, ennreal.of_real_to_real (snorm_ne_top _)],
exact snorm_congr_ae (coe_fn_sub _ _)
end
@[simp] lemma edist_to_Lp_to_Lp (f g : α → E) (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
edist (hf.to_Lp f) (hg.to_Lp g) = snorm (f - g) p μ :=
by { rw edist_def, exact snorm_congr_ae (hf.coe_fn_to_Lp.sub hg.coe_fn_to_Lp) }
@[simp] lemma edist_to_Lp_zero (f : α → E) (hf : mem_ℒp f p μ) :
edist (hf.to_Lp f) 0 = snorm f p μ :=
by { convert edist_to_Lp_to_Lp f 0 hf zero_mem_ℒp, simp }
@[simp] lemma norm_zero : ∥(0 : Lp E p μ)∥ = 0 :=
begin
change (snorm ⇑(0 : α →ₘ[μ] E) p μ).to_real = 0,
simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero]
end
lemma norm_eq_zero_iff {f : Lp E p μ} (hp : 0 < p) : ∥f∥ = 0 ↔ f = 0 :=
begin
refine ⟨λ hf, _, λ hf, by simp [hf]⟩,
rw [norm_def, ennreal.to_real_eq_zero_iff] at hf,
cases hf,
{ rw snorm_eq_zero_iff (Lp.ae_measurable f) hp.ne.symm at hf,
exact subtype.eq (ae_eq_fun.ext (hf.trans ae_eq_fun.coe_fn_zero.symm)), },
{ exact absurd hf (snorm_ne_top f), },
end
lemma eq_zero_iff_ae_eq_zero {f : Lp E p μ} : f = 0 ↔ f =ᵐ[μ] 0 :=
begin
split,
{ assume h,
rw h,
exact ae_eq_fun.coe_fn_const _ _ },
{ assume h,
ext1,
filter_upwards [h, ae_eq_fun.coe_fn_const α (0 : E)],
assume a ha h'a,
rw ha,
exact h'a.symm }
end
@[simp] lemma norm_neg {f : Lp E p μ} : ∥-f∥ = ∥f∥ :=
by rw [norm_def, norm_def, snorm_congr_ae (coe_fn_neg _), snorm_neg]
lemma norm_le_mul_norm_of_ae_le_mul
[second_countable_topology F] [measurable_space F] [borel_space F]
{c : ℝ} {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : ∥f∥ ≤ c * ∥g∥ :=
begin
by_cases pzero : p = 0,
{ simp [pzero, norm_def] },
cases le_or_lt 0 c with hc hc,
{ have := snorm_le_mul_snorm_aux_of_nonneg h hc p,
rw [← ennreal.to_real_le_to_real, ennreal.to_real_mul, ennreal.to_real_of_real hc] at this,
{ exact this },
{ exact (Lp.mem_ℒp _).snorm_ne_top },
{ simp [(Lp.mem_ℒp _).snorm_ne_top] } },
{ have := snorm_le_mul_snorm_aux_of_neg h hc p,
simp only [snorm_eq_zero_iff (Lp.ae_measurable _) pzero, ← eq_zero_iff_ae_eq_zero] at this,
simp [this] }
end
lemma norm_le_norm_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F]
{f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : ∥f∥ ≤ ∥g∥ :=
begin
rw [norm_def, norm_def, ennreal.to_real_le_to_real (snorm_ne_top _) (snorm_ne_top _)],
exact snorm_mono_ae h
end
lemma mem_Lp_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F]
{c : ℝ} {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : f ∈ Lp E p μ :=
mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le_mul (Lp.mem_ℒp g) f.ae_measurable h
lemma mem_Lp_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F]
{f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : f ∈ Lp E p μ :=
mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le (Lp.mem_ℒp g) f.ae_measurable h
lemma mem_Lp_of_ae_bound [finite_measure μ] {f : α →ₘ[μ] E} (C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
f ∈ Lp E p μ :=
mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_bound f.ae_measurable _ hfC
lemma norm_le_of_ae_bound [finite_measure μ] {f : Lp E p μ} {C : ℝ} (hC : 0 ≤ C)
(hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
∥f∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * C :=
begin
by_cases hμ : μ = 0,
{ by_cases hp : p.to_real⁻¹ = 0,
{ simpa [hp, hμ, norm_def] using hC },
{ simp [hμ, norm_def, real.zero_rpow hp] } },
let A : ℝ≥0 := (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * ⟨C, hC⟩,
suffices : snorm f p μ ≤ A,
{ exact ennreal.to_real_le_coe_of_le_coe this },
convert snorm_le_of_ae_bound hfC,
rw [← coe_measure_univ_nnreal μ, ennreal.coe_rpow_of_ne_zero (measure_univ_nnreal_pos hμ).ne',
ennreal.coe_mul],
congr,
rw max_eq_left hC
end
instance [hp : fact (1 ≤ p)] : normed_group (Lp E p μ) :=
normed_group.of_core _
{ norm_eq_zero_iff := λ f, norm_eq_zero_iff (ennreal.zero_lt_one.trans_le hp.1),
triangle := begin
assume f g,
simp only [norm_def],
rw ← ennreal.to_real_add (snorm_ne_top f) (snorm_ne_top g),
suffices h_snorm : snorm ⇑(f + g) p μ ≤ snorm ⇑f p μ + snorm ⇑g p μ,
{ rwa ennreal.to_real_le_to_real (snorm_ne_top (f + g)),
exact ennreal.add_ne_top.mpr ⟨snorm_ne_top f, snorm_ne_top g⟩, },
rw [snorm_congr_ae (coe_fn_add _ _)],
exact snorm_add_le (Lp.ae_measurable f) (Lp.ae_measurable g) hp.1,
end,
norm_neg := by simp }
instance normed_group_L1 : normed_group (Lp E 1 μ) := by apply_instance
instance normed_group_L2 : normed_group (Lp E 2 μ) := by apply_instance
instance normed_group_Ltop : normed_group (Lp E ∞ μ) := by apply_instance
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
lemma mem_Lp_const_smul (c : 𝕜) (f : Lp E p μ) : c • ↑f ∈ Lp E p μ :=
begin
rw [mem_Lp_iff_snorm_lt_top, snorm_congr_ae (ae_eq_fun.coe_fn_smul _ _), snorm_const_smul,
ennreal.mul_lt_top_iff],
exact or.inl ⟨ennreal.coe_lt_top, f.prop⟩,
end
variables (E p μ 𝕜)
/-- The `𝕜`-submodule of elements of `α →ₘ[μ] E` whose `Lp` norm is finite. This is `Lp E p μ`,
with extra structure. -/
def Lp_submodule : submodule 𝕜 (α →ₘ[μ] E) :=
{ smul_mem' := λ c f hf, by simpa using mem_Lp_const_smul c ⟨f, hf⟩,
.. Lp E p μ }
variables {E p μ 𝕜}
lemma coe_Lp_submodule : (Lp_submodule E p μ 𝕜).to_add_subgroup = Lp E p μ := rfl
instance : semimodule 𝕜 (Lp E p μ) :=
{ .. (Lp_submodule E p μ 𝕜).semimodule }
lemma coe_fn_smul (c : 𝕜) (f : Lp E p μ) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _
lemma norm_const_smul (c : 𝕜) (f : Lp E p μ) : ∥c • f∥ = ∥c∥ * ∥f∥ :=
by rw [norm_def, snorm_congr_ae (coe_fn_smul _ _), snorm_const_smul c,
ennreal.to_real_mul, ennreal.coe_to_real, coe_nnnorm, norm_def]
instance [fact (1 ≤ p)] : normed_space 𝕜 (Lp E p μ) :=
{ norm_smul_le := λ _ _, by simp [norm_const_smul] }
instance normed_space_L1 : normed_space 𝕜 (Lp E 1 μ) := by apply_instance
instance normed_space_L2 : normed_space 𝕜 (Lp E 2 μ) := by apply_instance
instance normed_space_Ltop : normed_space 𝕜 (Lp E ∞ μ) := by apply_instance
end normed_space
end Lp
namespace mem_ℒp
variables
[borel_space E] [second_countable_topology E]
{𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜]
lemma to_Lp_const_smul {f : α → E} (c : 𝕜) (hf : mem_ℒp f p μ) :
(hf.const_smul c).to_Lp (c • f) = c • hf.to_Lp f := rfl
end mem_ℒp
end measure_theory
open measure_theory
/-!
### Composition on `L^p`
We show that Lipschitz functions vanishing at zero act by composition on `L^p`, and specialize
this to the composition with continuous linear maps, and to the definition of the positive
part of an `L^p` function.
-/
section composition
variables [second_countable_topology E] [borel_space E]
[second_countable_topology F] [measurable_space F] [borel_space F]
{g : E → F} {c : ℝ≥0}
namespace lipschitz_with
lemma mem_ℒp_comp_iff_of_antilipschitz {α E F} {K K'} [measurable_space α] {μ : measure α}
[measurable_space E] [measurable_space F] [normed_group E] [normed_group F] [borel_space E]
[borel_space F] [complete_space E]
{f : α → E} {g : E → F} (hg : lipschitz_with K g) (hg' : antilipschitz_with K' g) (g0 : g 0 = 0) :
mem_ℒp (g ∘ f) p μ ↔ mem_ℒp f p μ :=
begin
have := ae_measurable_comp_iff_of_closed_embedding g (hg'.closed_embedding hg.uniform_continuous),
split,
{ assume H,
have A : ∀ᵐ x ∂μ, ∥f x∥ ≤ K' * ∥g (f x)∥,
{ apply filter.eventually_of_forall (λ x, _),
rw [← dist_zero_right, ← dist_zero_right, ← g0],
apply hg'.le_mul_dist },
exact H.of_le_mul (this.1 H.ae_measurable) A },
{ assume H,
have A : ∀ᵐ x ∂μ, ∥g (f x)∥ ≤ K * ∥f x∥,
{ apply filter.eventually_of_forall (λ x, _),
rw [← dist_zero_right, ← dist_zero_right, ← g0],
apply hg.dist_le_mul },
exact H.of_le_mul (this.2 H.ae_measurable) A }
end
/-- When `g` is a Lipschitz function sending `0` to `0` and `f` is in `Lp`, then `g ∘ f` is well
defined as an element of `Lp`. -/
def comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : Lp F p μ :=
⟨ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E),
begin
suffices : ∀ᵐ x ∂μ, ∥ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E) x∥ ≤ c * ∥f x∥,
{ exact Lp.mem_Lp_of_ae_le_mul this },
filter_upwards [ae_eq_fun.coe_fn_comp g hg.continuous.measurable (f : α →ₘ[μ] E)],
assume a ha,
simp only [ha],
rw [← dist_zero_right, ← dist_zero_right, ← g0],
exact hg.dist_le_mul (f a) 0,
end⟩
lemma coe_fn_comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) :
hg.comp_Lp g0 f =ᵐ[μ] g ∘ f :=
ae_eq_fun.coe_fn_comp _ _ _
@[simp] lemma comp_Lp_zero (hg : lipschitz_with c g) (g0 : g 0 = 0) :
hg.comp_Lp g0 (0 : Lp E p μ) = 0 :=
begin
rw Lp.eq_zero_iff_ae_eq_zero,
apply (coe_fn_comp_Lp _ _ _).trans,
filter_upwards [Lp.coe_fn_zero E p μ],
assume a ha,
simp [ha, g0]
end
lemma norm_comp_Lp_sub_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f f' : Lp E p μ) :
∥hg.comp_Lp g0 f - hg.comp_Lp g0 f'∥ ≤ c * ∥f - f'∥ :=
begin
apply Lp.norm_le_mul_norm_of_ae_le_mul,
filter_upwards [hg.coe_fn_comp_Lp g0 f, hg.coe_fn_comp_Lp g0 f',
Lp.coe_fn_sub (hg.comp_Lp g0 f) (hg.comp_Lp g0 f'), Lp.coe_fn_sub f f'],
assume a ha1 ha2 ha3 ha4,
simp [ha1, ha2, ha3, ha4, ← dist_eq_norm],
exact hg.dist_le_mul (f a) (f' a)
end
lemma norm_comp_Lp_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) :
∥hg.comp_Lp g0 f∥ ≤ c * ∥f∥ :=
by simpa using hg.norm_comp_Lp_sub_le g0 f 0
lemma lipschitz_with_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) :
lipschitz_with c (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) :=
lipschitz_with.of_dist_le_mul $ λ f g, by simp [dist_eq_norm, norm_comp_Lp_sub_le]
lemma continuous_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) :
continuous (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) :=
(lipschitz_with_comp_Lp hg g0).continuous
end lipschitz_with
namespace continuous_linear_map
variables [normed_space ℝ E] [normed_space ℝ F]
/-- Composing `f : Lp ` with `L : E →L[ℝ] F`. -/
def comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) : Lp F p μ :=
L.lipschitz.comp_Lp (map_zero L) f
lemma coe_fn_comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) :
∀ᵐ a ∂μ, (L.comp_Lp f) a = L (f a) :=
lipschitz_with.coe_fn_comp_Lp _ _ _
variables (μ p)
/-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `Lp E p μ`. -/
def comp_Lpₗ (L : E →L[ℝ] F) : (Lp E p μ) →ₗ[ℝ] (Lp F p μ) :=
{ to_fun := λ f, L.comp_Lp f,
map_add' := begin
intros f g,
ext1,
filter_upwards [Lp.coe_fn_add f g, coe_fn_comp_Lp L (f + g), coe_fn_comp_Lp L f,
coe_fn_comp_Lp L g, Lp.coe_fn_add (L.comp_Lp f) (L.comp_Lp g)],
assume a ha1 ha2 ha3 ha4 ha5,
simp only [ha1, ha2, ha3, ha4, ha5, map_add, pi.add_apply],
end,
map_smul' := begin
intros c f,
ext1,
filter_upwards [Lp.coe_fn_smul c f, coe_fn_comp_Lp L (c • f), Lp.coe_fn_smul c (L.comp_Lp f),
coe_fn_comp_Lp L f],
assume a ha1 ha2 ha3 ha4,
simp only [ha1, ha2, ha3, ha4, map_smul, pi.smul_apply],
end }
variables {μ p}
lemma norm_comp_Lp_le (L : E →L[ℝ] F) (f : Lp E p μ) : ∥L.comp_Lp f∥ ≤ ∥L∥ * ∥f∥ :=
lipschitz_with.norm_comp_Lp_le _ _ _
variables (μ p)
/-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on
`Lp E p μ`. -/
def comp_LpL [fact (1 ≤ p)] (L : E →L[ℝ] F) : (Lp E p μ) →L[ℝ] (Lp F p μ) :=
linear_map.mk_continuous (L.comp_Lpₗ p μ) ∥L∥ L.norm_comp_Lp_le
lemma norm_compLpL_le [fact (1 ≤ p)] (L : E →L[ℝ] F) :
∥L.comp_LpL p μ∥ ≤ ∥L∥ :=
linear_map.mk_continuous_norm_le _ (norm_nonneg _) _
end continuous_linear_map
namespace measure_theory
namespace Lp
section pos_part
lemma lipschitz_with_pos_part : lipschitz_with 1 (λ (x : ℝ), max x 0) :=
lipschitz_with.of_dist_le_mul $ λ x y, by simp [dist, abs_max_sub_max_le_abs]
/-- Positive part of a function in `L^p`. -/
def pos_part (f : Lp ℝ p μ) : Lp ℝ p μ :=
lipschitz_with_pos_part.comp_Lp (max_eq_right (le_refl _)) f
/-- Negative part of a function in `L^p`. -/
def neg_part (f : Lp ℝ p μ) : Lp ℝ p μ := pos_part (-f)
@[norm_cast]
lemma coe_pos_part (f : Lp ℝ p μ) : (pos_part f : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl
lemma coe_fn_pos_part (f : Lp ℝ p μ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 :=
ae_eq_fun.coe_fn_pos_part _
lemma coe_fn_neg_part_eq_max (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 :=
begin
rw neg_part,
filter_upwards [coe_fn_pos_part (-f), coe_fn_neg f],
assume a h₁ h₂,
rw [h₁, h₂, pi.neg_apply]
end
lemma coe_fn_neg_part (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 :=
(coe_fn_neg_part_eq_max f).mono $ assume a h,
by rw [h, ← max_neg_neg, neg_zero]
lemma continuous_pos_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, pos_part f) :=
lipschitz_with.continuous_comp_Lp _ _
lemma continuous_neg_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, neg_part f) :=
have eq : (λf : Lp ℝ p μ, neg_part f) = (λf : Lp ℝ p μ, pos_part (-f)) := rfl,
by { rw eq, exact continuous_pos_part.comp continuous_neg }
end pos_part
end Lp
end measure_theory
end composition
/-!
## `L^p` is a complete space
We show that `L^p` is a complete space for `1 ≤ p`.
-/
section complete_space
variables [borel_space E] [second_countable_topology E]
namespace measure_theory
namespace Lp
lemma snorm'_lim_eq_lintegral_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G} {p : ℝ}
(hp_nonneg : 0 ≤ p) {f_lim : α → G}
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm' f_lim p μ = (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ) ^ (1/p) :=
begin
suffices h_no_pow : (∫⁻ a, (nnnorm (f_lim a)) ^ p ∂μ)
= (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ),
{ rw [snorm', h_no_pow], },
refine lintegral_congr_ae (h_lim.mono (λ a ha, _)),
rw tendsto.liminf_eq,
simp_rw [ennreal.coe_rpow_of_nonneg _ hp_nonneg, ennreal.tendsto_coe],
refine ((nnreal.continuous_rpow_const hp_nonneg).tendsto (nnnorm (f_lim a))).comp _,
exact (continuous_nnnorm.tendsto (f_lim a)).comp ha,
end
lemma snorm'_lim_le_liminf_snorm' {E} [measurable_space E]
[normed_group E] [borel_space E] {f : ℕ → α → E} {p : ℝ} (hp_pos : 0 < p)
(hf : ∀ n, ae_measurable (f n) μ) {f_lim : α → E}
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm' f_lim p μ ≤ at_top.liminf (λ n, snorm' (f n) p μ) :=
begin
rw snorm'_lim_eq_lintegral_liminf hp_pos.le h_lim,
rw [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div],
refine (lintegral_liminf_le' (λ m, ((hf m).ennnorm.pow_const _))).trans_eq _,
have h_pow_liminf : at_top.liminf (λ n, snorm' (f n) p μ) ^ p
= at_top.liminf (λ n, (snorm' (f n) p μ) ^ p),
{ have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hp_pos,
have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2,
refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _,
all_goals { is_bounded_default }, },
rw h_pow_liminf,
simp_rw [snorm', ← ennreal.rpow_mul, one_div, inv_mul_cancel hp_pos.ne.symm, ennreal.rpow_one],
end
lemma snorm_exponent_top_lim_eq_ess_sup_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G}
{f_lim : α → G}
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm f_lim ∞ μ = ess_sup (λ x, at_top.liminf (λ m, (nnnorm (f m x) : ℝ≥0∞))) μ :=
begin
rw [snorm_exponent_top, snorm_ess_sup],
refine ess_sup_congr_ae (h_lim.mono (λ x hx, _)),
rw tendsto.liminf_eq,
rw ennreal.tendsto_coe,
exact (continuous_nnnorm.tendsto (f_lim x)).comp hx,
end
lemma snorm_exponent_top_lim_le_liminf_snorm_exponent_top {ι} [nonempty ι] [encodable ι]
[linear_order ι] {f : ι → α → F} {f_lim : α → F}
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm f_lim ∞ μ ≤ at_top.liminf (λ n, snorm (f n) ∞ μ) :=
begin
rw snorm_exponent_top_lim_eq_ess_sup_liminf h_lim,
simp_rw [snorm_exponent_top, snorm_ess_sup],
exact ennreal.ess_sup_liminf_le (λ n, (λ x, (nnnorm (f n x) : ℝ≥0∞))),
end
lemma snorm_lim_le_liminf_snorm {E} [measurable_space E] [normed_group E] [borel_space E]
{f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (f_lim : α → E)
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm f_lim p μ ≤ at_top.liminf (λ n, snorm (f n) p μ) :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
rw ← ne.def at hp0,
by_cases hp_top : p = ∞,
{ simp_rw [hp_top],
exact snorm_exponent_top_lim_le_liminf_snorm_exponent_top h_lim, },
simp_rw snorm_eq_snorm' hp0 hp_top,
have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
exact snorm'_lim_le_liminf_snorm' hp_pos hf h_lim,
end
/-! ### `Lp` is complete iff Cauchy sequences of `ℒp` have limits in `ℒp` -/
lemma tendsto_Lp_of_tendsto_ℒp {ι} [linear_order ι] [hp : fact (1 ≤ p)]
{f : ι → Lp E p μ} (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ)
(h_tendsto : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) :
at_top.tendsto f (𝓝 (f_lim_ℒp.to_Lp f_lim)) :=
begin
by_cases hι : nonempty ι,
swap, { exact tendsto_of_not_nonempty hι, },
haveI : nonempty ι := hι,
rw ennreal.tendsto_at_top_zero at h_tendsto,
simp_rw metric.tendsto_at_top,
intros ε hε,
have hε_pos : 0 < ennreal.of_real ε, from ennreal.of_real_pos.mpr hε,
have hε2_pos : 0 < ennreal.of_real ε / 2,
by { rw ennreal.div_pos_iff, exact ⟨hε_pos.ne.symm, ennreal.two_ne_top⟩, },
cases (h_tendsto (ennreal.of_real ε / 2) hε2_pos) with N h_tendsto,
refine ⟨N, λ n hn, _⟩,
specialize h_tendsto n hn,
have hp_pos : 0 < p, from ennreal.zero_lt_one.trans_le hp.elim,
rw [dist_def, ←@ennreal.to_real_of_real ε (le_of_lt hε),
ennreal.to_real_lt_to_real _ ennreal.of_real_ne_top],
swap, { rw snorm_congr_ae (coe_fn_sub _ _).symm, exact snorm_ne_top _, },
have h_coe : ⇑(f n) - f_lim =ᵐ[μ] ⇑(f n) - ⇑(mem_ℒp.to_Lp f_lim f_lim_ℒp),
{ have h_coe' : f_lim =ᵐ[μ] ⇑(mem_ℒp.to_Lp f_lim f_lim_ℒp), from (mem_ℒp.coe_fn_to_Lp _).symm,
refine h_coe'.mono (λ x hx, _),
rw [pi.sub_apply, pi.sub_apply, hx], },
rw snorm_congr_ae h_coe.symm,
exact lt_of_le_of_lt h_tendsto (ennreal.half_lt_self hε_pos.ne.symm ennreal.of_real_ne_top),
end
lemma complete_space_Lp_of_cauchy_complete_ℒp [hp : fact (1 ≤ p)]
(H : ∀ (f : ℕ → α → E) (hf : ∀ n, mem_ℒp (f n) p μ) (B : ℕ → ℝ≥0∞) (hB : ∑' i, B i < ∞)
(h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N),
∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ),
at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) :
complete_space (Lp E p μ) :=
begin
let B := λ n : ℕ, ((1:ℝ) / 2) ^ n,
have hB_pos : ∀ n, 0 < B n, from λ n, pow_pos (div_pos zero_lt_one zero_lt_two) n,
refine metric.complete_of_convergent_controlled_sequences B hB_pos (λ f hf, _),
suffices h_limit : ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ),
at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0),
{ rcases h_limit with ⟨f_lim, hf_lim_meas, h_tendsto⟩,
exact ⟨hf_lim_meas.to_Lp f_lim, tendsto_Lp_of_tendsto_ℒp f_lim hf_lim_meas h_tendsto⟩, },
have hB : summable B, from summable_geometric_two,
cases hB with M hB,
let B1 := λ n, ennreal.of_real (B n),
have hB1_has : has_sum B1 (ennreal.of_real M),
{ have h_tsum_B1 : ∑' i, B1 i = (ennreal.of_real M),
{ change (∑' (n : ℕ), ennreal.of_real (B n)) = ennreal.of_real M,
rw ←hB.tsum_eq,
exact (ennreal.of_real_tsum_of_nonneg (λ n, le_of_lt (hB_pos n)) hB.summable).symm, },
have h_sum := (@ennreal.summable _ B1).has_sum,
rwa h_tsum_B1 at h_sum, },
have hB1 : ∑' i, B1 i < ∞, by {rw hB1_has.tsum_eq, exact ennreal.of_real_lt_top, },
let f1 : ℕ → α → E := λ n, f n,
refine H f1 (λ n, Lp.mem_ℒp (f n)) B1 hB1 (λ N n m hn hm, _),
specialize hf N n m hn hm,
rw dist_def at hf,
simp_rw [f1, B1],
rwa ennreal.lt_of_real_iff_to_real_lt,
rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm,
exact Lp.snorm_ne_top _,
end
/-! ### Prove that controlled Cauchy sequences of `ℒp` have limits in `ℒp` -/
private lemma snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' {f : ℕ → α → E}
(hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p)
{B : ℕ → ℝ≥0∞} (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) (n : ℕ) :
snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i :=
begin
let f_norm_diff := λ i x, norm (f (i + 1) x - f i x),
have hgf_norm_diff : ∀ n, (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x))
= ∑ i in finset.range (n + 1), f_norm_diff i,
from λ n, funext (λ x, by simp [f_norm_diff]),
rw hgf_norm_diff,
refine (snorm'_sum_le (λ i _, ((hf (i+1)).sub (hf i)).norm) hp1).trans _,
simp_rw [←pi.sub_apply, snorm'_norm],
refine (finset.sum_le_sum _).trans (sum_le_tsum _ (λ m _, zero_le _) ennreal.summable),
exact λ m _, (h_cau m (m + 1) m (nat.le_succ m) (le_refl m)).le,
end
private lemma lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum {f : ℕ → α → E}
(hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (n : ℕ)
(hn : snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i) :
∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ
≤ (∑' i, B i) ^ p :=
begin
have hp_pos : 0 < p := zero_lt_one.trans_le hp1,
rw [←one_div_one_div p, @ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]),
one_div_one_div p],
simp_rw snorm' at hn,
have h_nnnorm_nonneg :
(λ a, (nnnorm (∑ i in finset.range (n + 1), ∥f (i + 1) a - f i a∥) : ℝ≥0∞) ^ p)
= λ a, (∑ i in finset.range (n + 1), (nnnorm(f (i + 1) a - f i a) : ℝ≥0∞)) ^ p,
{ ext1 a,
congr,
simp_rw ←of_real_norm_eq_coe_nnnorm,
rw ←ennreal.of_real_sum_of_nonneg,
{ rw real.norm_of_nonneg _,
exact finset.sum_nonneg (λ x hx, norm_nonneg _), },
{ exact λ x hx, norm_nonneg _, }, },
change (∫⁻ a, (λ x, ↑(nnnorm (∑ i in finset.range (n + 1), ∥f (i+1) x - f i x∥))^p) a ∂μ)^(1/p)
≤ ∑' i, B i at hn,
rwa h_nnnorm_nonneg at hn,
end
private lemma lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum {f : ℕ → α → E}
(hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞}
(h : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ
≤ (∑' i, B i) ^ p) :
(∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i :=
begin
have hp_pos : 0 < p := zero_lt_one.trans_le hp1,
suffices h_pow : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p,
by rwa [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div],
have h_tsum_1 : ∀ g : ℕ → ℝ≥0∞,
∑' i, g i = at_top.liminf (λ n, ∑ i in finset.range (n + 1), g i),
by { intro g, rw [ennreal.tsum_eq_liminf_sum_nat, ← liminf_nat_add _ 1], },
simp_rw h_tsum_1 _,
rw ← h_tsum_1,
have h_liminf_pow : ∫⁻ a, at_top.liminf (λ n, ∑ i in finset.range (n + 1),
(nnnorm (f (i + 1) a - f i a)))^p ∂μ
= ∫⁻ a, at_top.liminf (λ n, (∑ i in finset.range (n + 1), (nnnorm (f (i + 1) a - f i a)))^p) ∂μ,
{ refine lintegral_congr (λ x, _),
have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos (zero_lt_one.trans_le hp1),
have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2,
refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _,
all_goals { is_bounded_default }, },
rw h_liminf_pow,
refine (lintegral_liminf_le' _).trans _,
{ exact λ n, (finset.ae_measurable_sum (finset.range (n+1))
(λ i _, ((hf (i+1)).sub (hf i)).ennnorm)).pow_const _, },
{ exact liminf_le_of_frequently_le' (frequently_of_forall h), },
end
private lemma tsum_nnnorm_sub_ae_lt_top
{f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞}
(hB : ∑' i, B i < ∞)
(h : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i) :
∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞ :=
begin
have hp_pos : 0 < p := zero_lt_one.trans_le hp1,
have h_integral : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ < ∞,
{ have h_tsum_lt_top : (∑' i, B i) ^ p < ∞,
from ennreal.rpow_lt_top_of_nonneg hp_pos.le (lt_top_iff_ne_top.mp hB),
refine lt_of_le_of_lt _ h_tsum_lt_top,
rwa [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div] at h, },
have rpow_ae_lt_top : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞)^p < ∞,
{ refine ae_lt_top' (ae_measurable.pow_const _ _) h_integral,
exact ae_measurable.ennreal_tsum (λ n, ((hf (n+1)).sub (hf n)).ennnorm), },
refine rpow_ae_lt_top.mono (λ x hx, _),
rwa [←ennreal.lt_rpow_one_div_iff hp_pos,
@ennreal.top_rpow_of_pos (1/p) (by simp [hp_pos])] at hx,
end
lemma ae_tendsto_of_cauchy_snorm' [complete_space E] {f : ℕ → α → E} {p : ℝ}
(hf : ∀ n, ae_measurable (f n) μ) (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞)
(h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) :
∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) :=
begin
have h_summable : ∀ᵐ x ∂μ, summable (λ (i : ℕ), f (i + 1) x - f i x),
{ have h1 : ∀ n, snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ
≤ ∑' i, B i,
from snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' hf hp1 h_cau,
have h2 : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ
≤ (∑' i, B i) ^ p,
from λ n, lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum hf hp1 n (h1 n),
have h3 : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i,
from lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum hf hp1 h2,
have h4 : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞,
from tsum_nnnorm_sub_ae_lt_top hf hp1 hB h3,
exact h4.mono (λ x hx, summable_of_summable_nnnorm
(ennreal.tsum_coe_ne_top_iff_summable.mp (lt_top_iff_ne_top.mp hx))), },
have h : ∀ᵐ x ∂μ, ∃ l : E,
at_top.tendsto (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) (𝓝 l),
{ refine h_summable.mono (λ x hx, _),
let hx_sum := (summable.has_sum_iff_tendsto_nat hx).mp hx.has_sum,
exact ⟨∑' i, (f (i + 1) x - f i x), hx_sum⟩, },
refine h.mono (λ x hx, _),
cases hx with l hx,
have h_rw_sum : (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) = λ n, f n x - f 0 x,
{ ext1 n,
change ∑ (i : ℕ) in finset.range n, ((λ m, f m x) (i + 1) - (λ m, f m x) i) = f n x - f 0 x,
rw finset.sum_range_sub, },
rw h_rw_sum at hx,
have hf_rw : (λ n, f n x) = λ n, f n x - f 0 x + f 0 x, by { ext1 n, abel, },
rw hf_rw,
exact ⟨l + f 0 x, tendsto.add_const _ hx⟩,
end
lemma ae_tendsto_of_cauchy_snorm [complete_space E] {f : ℕ → α → E}
(hf : ∀ n, ae_measurable (f n) μ) (hp : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞)
(h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) :
∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) :=
begin
by_cases hp_top : p = ∞,
{ simp_rw [hp_top] at *,
have h_cau_ae : ∀ᵐ x ∂μ, ∀ N n m, N ≤ n → N ≤ m → (nnnorm ((f n - f m) x) : ℝ≥0∞) < B N,
{ simp_rw [ae_all_iff, ae_imp_iff],
exact λ N n m hnN hmN, ae_lt_of_ess_sup_lt (h_cau N n m hnN hmN), },
simp_rw [snorm_exponent_top, snorm_ess_sup] at h_cau,
refine h_cau_ae.mono (λ x hx, cauchy_seq_tendsto_of_complete _),
refine cauchy_seq_of_le_tendsto_0 (λ n, (B n).to_real) _ _,
{ intros n m N hnN hmN,
specialize hx N n m hnN hmN,
rw [dist_eq_norm, ←ennreal.to_real_of_real (norm_nonneg _),
ennreal.to_real_le_to_real ennreal.of_real_ne_top
((ennreal.ne_top_of_tsum_ne_top (lt_top_iff_ne_top.mp hB)) N)],
rw ←of_real_norm_eq_coe_nnnorm at hx,
exact hx.le, },
{ rw ← ennreal.zero_to_real,
exact tendsto.comp (ennreal.tendsto_to_real ennreal.zero_ne_top)
(ennreal.tendsto_at_top_zero_of_tsum_lt_top hB), }, },
have hp1 : 1 ≤ p.to_real,
{ rw [← ennreal.of_real_le_iff_le_to_real hp_top, ennreal.of_real_one],
exact hp, },
have h_cau' : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) (p.to_real) μ < B N,
{ intros N n m hn hm,
specialize h_cau N n m hn hm,
rwa snorm_eq_snorm' (ennreal.zero_lt_one.trans_le hp).ne.symm hp_top at h_cau, },
exact ae_tendsto_of_cauchy_snorm' hf hp1 hB h_cau',
end
lemma cauchy_tendsto_of_tendsto {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ)
(f_lim : α → E) {B : ℕ → ℝ≥0∞}
(hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N)
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) :=
begin
rw ennreal.tendsto_at_top_zero,
intros ε hε,
have h_B : ∃ (N : ℕ), B N ≤ ε,
{ suffices h_tendsto_zero : ∃ (N : ℕ), ∀ n : ℕ, N ≤ n → B n ≤ ε,
from ⟨h_tendsto_zero.some, h_tendsto_zero.some_spec _ (le_refl _)⟩,
exact (ennreal.tendsto_at_top_zero.mp (ennreal.tendsto_at_top_zero_of_tsum_lt_top hB))
ε hε, },
cases h_B with N h_B,
refine ⟨N, λ n hn, _⟩,
have h_sub : snorm (f n - f_lim) p μ ≤ at_top.liminf (λ m, snorm (f n - f m) p μ),
{ refine snorm_lim_le_liminf_snorm (λ m, (hf n).sub (hf m)) (f n - f_lim) _,
refine h_lim.mono (λ x hx, _),
simp_rw sub_eq_add_neg,
exact tendsto.add tendsto_const_nhds (tendsto.neg hx), },
refine h_sub.trans _,
refine liminf_le_of_frequently_le' (frequently_at_top.mpr _),
refine λ N1, ⟨max N N1, le_max_right _ _, _⟩,
exact (h_cau N n (max N N1) hn (le_max_left _ _)).le.trans h_B,
end
lemma mem_ℒp_of_cauchy_tendsto (hp : 1 ≤ p) {f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ)
(f_lim : α → E) (h_lim_meas : ae_measurable f_lim μ)
(h_tendsto : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) :
mem_ℒp f_lim p μ :=
begin
refine ⟨h_lim_meas, _⟩,
rw ennreal.tendsto_at_top_zero at h_tendsto,
cases (h_tendsto 1 ennreal.zero_lt_one) with N h_tendsto_1,
specialize h_tendsto_1 N (le_refl N),
have h_add : f_lim = f_lim - f N + f N, by abel,
rw h_add,
refine lt_of_le_of_lt (snorm_add_le (h_lim_meas.sub (hf N).1) (hf N).1 hp) _,
rw ennreal.add_lt_top,
split,
{ refine lt_of_le_of_lt _ ennreal.one_lt_top,
have h_neg : f_lim - f N = -(f N - f_lim), by simp,
rwa [h_neg, snorm_neg], },
{ exact (hf N).2, },
end
lemma cauchy_complete_ℒp [complete_space E] (hp : 1 ≤ p)
{f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞)
(h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) :
∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ),
at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) :=
begin
obtain ⟨f_lim, h_f_lim_meas, h_lim⟩ : ∃ (f_lim : α → E) (hf_lim_meas : measurable f_lim),
∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (nhds (f_lim x)),
from measurable_limit_of_tendsto_metric_ae (λ n, (hf n).1)
(ae_tendsto_of_cauchy_snorm (λ n, (hf n).1) hp hB h_cau),
have h_tendsto' : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0),
from cauchy_tendsto_of_tendsto (λ m, (hf m).1) f_lim hB h_cau h_lim,
have h_ℒp_lim : mem_ℒp f_lim p μ,
from mem_ℒp_of_cauchy_tendsto hp hf f_lim h_f_lim_meas.ae_measurable h_tendsto',
exact ⟨f_lim, h_ℒp_lim, h_tendsto'⟩,
end
/-! ### `Lp` is complete for `1 ≤ p` -/
instance [complete_space E] [hp : fact (1 ≤ p)] : complete_space (Lp E p μ) :=
complete_space_Lp_of_cauchy_complete_ℒp (λ f hf B hB h_cau, cauchy_complete_ℒp hp.elim hf hB h_cau)
end Lp
end measure_theory
end complete_space
namespace bounded_continuous_function
open_locale bounded_continuous_function
variables [borel_space E] [second_countable_topology E]
variables [topological_space α] [borel_space α]
variables [finite_measure μ]
/-- A bounded continuous function is in `Lp`. -/
lemma mem_Lp (f : α →ᵇ E) :
f.to_continuous_map.to_ae_eq_fun μ ∈ Lp E p μ :=
begin
refine Lp.mem_Lp_of_ae_bound (∥f∥) _,
filter_upwards [f.to_continuous_map.coe_fn_to_ae_eq_fun μ],
intros x hx,
convert f.norm_coe_le_norm x
end
/-- The `Lp`-norm of a bounded continuous function is at most a constant (depending on the measure
of the whole space) times its sup-norm. -/
lemma Lp_norm_le (f : α →ᵇ E) :
∥(⟨f.to_continuous_map.to_ae_eq_fun μ, mem_Lp f⟩ : Lp E p μ)∥
≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * ∥f∥ :=
begin
apply Lp.norm_le_of_ae_bound (norm_nonneg f),
{ refine (f.to_continuous_map.coe_fn_to_ae_eq_fun μ).mono _,
intros x hx,
convert f.norm_coe_le_norm x },
{ apply_instance }
end
variables (E p μ)
/-- The normed group homomorphism of considering a bounded continuous function on a finite-measure
space as an element of `Lp`. -/
def to_Lp_hom [fact (1 ≤ p)] : normed_group_hom (α →ᵇ E) (Lp E p μ) :=
{ bound' := ⟨_, Lp_norm_le⟩,
.. add_monoid_hom.cod_restrict
((continuous_map.to_ae_eq_fun_add_hom μ).comp (forget_boundedness_add_hom α E))
(Lp E p μ)
mem_Lp }
variables (𝕜 : Type*) [measurable_space 𝕜]
/-- The bounded linear map of considering a bounded continuous function on a finite-measure space
as an element of `Lp`. -/
def to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] :
(α →ᵇ E) →L[𝕜] (Lp E p μ) :=
linear_map.mk_continuous
(linear_map.cod_restrict
(Lp.Lp_submodule E p μ 𝕜)
((continuous_map.to_ae_eq_fun_linear_map μ).comp (forget_boundedness_linear_map α E))
mem_Lp)
_
Lp_norm_le
variables {E p 𝕜}
lemma to_Lp_norm_le [nondiscrete_normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E]
[fact (1 ≤ p)] :
∥to_Lp E p μ 𝕜∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ :=
linear_map.mk_continuous_norm_le _ ((measure_univ_nnreal μ) ^ (p.to_real)⁻¹).coe_nonneg _
end bounded_continuous_function
namespace continuous_map
open_locale bounded_continuous_function
variables [borel_space E] [second_countable_topology E]
variables [topological_space α] [compact_space α] [borel_space α]
variables [finite_measure μ]
variables (𝕜 : Type*) [measurable_space 𝕜] (E p μ) [fact (1 ≤ p)]
/-- The bounded linear map of considering a continuous function on a compact finite-measure
space `α` as an element of `Lp`. By definition, the norm on `C(α, E)` is the sup-norm, transferred
from the space `α →ᵇ E` of bounded continuous functions, so this construction is just a matter of
transferring the structure from `bounded_continuous_function.to_Lp` along the isometry. -/
def to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] :
C(α, E) →L[𝕜] (Lp E p μ) :=
(bounded_continuous_function.to_Lp E p μ 𝕜).comp
(linear_isometry_bounded_of_compact α E 𝕜).to_linear_isometry.to_continuous_linear_map
variables {E p 𝕜}
lemma to_Lp_def [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : C(α, E)) :
to_Lp E p μ 𝕜 f
= bounded_continuous_function.to_Lp E p μ 𝕜 (linear_isometry_bounded_of_compact α E 𝕜 f) :=
rfl
@[simp] lemma to_Lp_comp_forget_boundedness [normed_field 𝕜] [opens_measurable_space 𝕜]
[normed_space 𝕜 E] (f : α →ᵇ E) :
to_Lp E p μ 𝕜 (bounded_continuous_function.forget_boundedness α E f)
= bounded_continuous_function.to_Lp E p μ 𝕜 f :=
rfl
@[simp] lemma coe_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E]
(f : C(α, E)) :
(to_Lp E p μ 𝕜 f : α →ₘ[μ] E) = f.to_ae_eq_fun μ :=
rfl
variables [nondiscrete_normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E]
lemma to_Lp_norm_eq_to_Lp_norm_coe :
∥to_Lp E p μ 𝕜∥ = ∥bounded_continuous_function.to_Lp E p μ 𝕜∥ :=
(bounded_continuous_function.to_Lp E p μ 𝕜).op_norm_comp_linear_isometry_equiv _
/-- Bound for the operator norm of `continuous_map.to_Lp`. -/
lemma to_Lp_norm_le : ∥to_Lp E p μ 𝕜∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ :=
by { rw to_Lp_norm_eq_to_Lp_norm_coe, exact bounded_continuous_function.to_Lp_norm_le μ }
end continuous_map
|
81de743f0598508bc2b39e7f7612749a778f421c | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/have2.lean | 1f55029bf817eac1e53dd8edcaeea5007345fa93 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 176 | lean | definition Prop : Type.{1} := Type.{0}
constants a b c : Prop
axiom Ha : a
axiom Hb : b
axiom Hc : c
check have H1 [visible] : a, from Ha,
have H2 : a, from H1,
H2
|
671924a771eab9b76970105ee5c85b3ad9f3b414 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/sites/sheaf_of_types.lean | eeabe1b286a2c1dbf456349f97947da8e4ea0787 | [
"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 | 35,553 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.sites.pretopology
import category_theory.limits.shapes.types
import category_theory.full_subcategory
/-!
# Sheaves of types on a Grothendieck topology
Defines the notion of a sheaf of types (usually called a sheaf of sets by mathematicians)
on a category equipped with a Grothendieck topology, as well as a range of equivalent
conditions useful in different situations.
First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular
presieve `R` on `X`:
* A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in
`R`. See `family_of_elements`.
* The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`,
and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of
`x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`.
See `family_of_elements.compatible`.
* An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in
`R`, the restriction of `t` on `f` is `x_f`.
See `family_of_elements.is_amalgamation`.
We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation,
and it is a *sheaf* for `R` if every compatible family has a unique amalgamation.
See `is_separated_for` and `is_sheaf_for`.
In the special case where `R` is a sieve, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of
`x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`).
See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`.
In the special case where `C` has pullbacks, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`,
the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g`
along `π₂ : pullback f g ⟶ Z`.
See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`.
Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the
topology. See `is_sheaf`.
In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for
every sieve in the pretopology. See `is_sheaf_pretopology`.
We also provide equivalent conditions to satisfy alternate definitions given in the literature.
* Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be
equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with
`is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.)
The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the
statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries
the same information as the unique existence.)
* Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf`
are equivalent. There are also alternate definitions given:
- Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in
`yoneda_condition_iff_sheaf_condition`.
- Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence
in `equalizer.sieve.sheaf_condition`.
- Matching family for presieves with pullback: `pullback_compatible_iff`.
- Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous.
- Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition`
combined with the previous.
## Implementation
The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u v)`.
This doesn't seem to make a big difference, other than making a couple of definitions noncomputable,
but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements,
which can be convenient.
## References
* [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk:
Chapter III, Section 4.
* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1.
* https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site)
* https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology)
-/
universes v u
namespace category_theory
open opposite category_theory category limits sieve classical
namespace presieve
variables {C : Type u} [category.{v} C]
variables {P : Cᵒᵖ ⥤ Type v}
variables {X Y : C} {S : sieve X} {R : presieve X}
variables (J J₂ : grothendieck_topology C)
/--
A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X`
consists of an element of `P Y` for every `f : Y ⟶ X` in `R`.
A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one
(resp, at most one) amalgamation.
This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete
version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is
more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant].
-/
def family_of_elements (P : Cᵒᵖ ⥤ Type v) (R : presieve X) :=
Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y)
instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩
/--
A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve
`R₁`.
-/
def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) :
family_of_elements P R₂ → family_of_elements P R₁ :=
λ x Y f hf, x f (h _ hf)
/--
A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and
`f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂`
commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and
restricting the element of `P Y₂` along `g₂` are the same.
In special cases, this condition can be simplified, see `pullback_compatible_iff` and
`compatible_iff_sieve_compatible`.
This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab:
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents
-/
def family_of_elements.compatible (x : family_of_elements P R) : Prop :=
∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄
(h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂)
/--
If the category `C` has pullbacks, this is an alternative condition for a family of elements to be
compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the
given elements for `f` and `g` to the pullback agree.
This is equivalent to being compatible (provided `C` has pullbacks), shown in
`pullback_compatible_iff`.
This is the definition for a "matching" family given in [MM92], Chapter III, Section 4,
Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in
https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`,
using the notation defined there.
-/
def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop :=
∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂),
P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂)
lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] :
x.compatible ↔ x.pullback_compatible :=
begin
split,
{ intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂,
apply t,
apply pullback.condition },
{ intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm,
rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂,
←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] }
end
/-- The restriction of a compatible family is compatible. -/
lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
{x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible :=
λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm
/--
Extend a family of elements to the sieve generated by an arrow set.
This is the construction described as "easy" in Lemma C2.1.3 of [Elephant].
-/
noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) :
family_of_elements P (generate R) :=
λ Z f hf, P.map (some (some_spec hf)).op (x _ (some_spec (some_spec (some_spec hf))).1)
/-- The extension of a compatible family to the generated sieve is compatible. -/
lemma family_of_elements.compatible.sieve_extend (x : family_of_elements P R) (hx : x.compatible) :
x.sieve_extend.compatible :=
begin
intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm,
rw [←(some_spec (some_spec (some_spec h₁))).2, ←(some_spec (some_spec (some_spec h₂))).2,
←assoc, ←assoc] at comm,
dsimp [family_of_elements.sieve_extend],
rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply],
apply hx _ _ _ _ comm,
end
/-- The extension of a family agrees with the original family. -/
lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) :
x.sieve_extend f ⟨_, 𝟙 _, f, hf, id_comp _⟩ = x f hf :=
begin
have h : (generate R) f := ⟨_, _, _, hf, id_comp _⟩,
change P.map (some (some_spec h)).op (x _ _) = x f hf,
rw t (some (some_spec h)) (𝟙 _) _ hf _,
{ simp },
simp_rw [id_comp],
apply (some_spec (some_spec (some_spec h))).2,
end
/-- The restriction of an extension is the original. -/
@[simp]
lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) :
x.sieve_extend.restrict (le_generate R) = x :=
begin
ext Y f hf,
exact extend_agrees t hf,
end
/--
If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the
consistency condition can be simplified.
This is an equivalent condition, see `compatible_iff_sieve_compatible`.
This is the notion of "matching" given for families on sieves given in [MM92], Chapter III,
Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family.
See also the discussion before Lemma C2.1.4 of [Elephant].
-/
def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop :=
∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf)
lemma compatible_iff_sieve_compatible (x : family_of_elements P S) :
x.compatible ↔ x.sieve_compatible :=
begin
split,
{ intros h Y Z f g hf,
simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) },
{ intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k,
simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] }
end
lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S}
(t : x.compatible) : x.sieve_compatible :=
(compatible_iff_sieve_compatible x).1 t
/--
Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are
equal when restricted to `R`.
-/
lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)}
(t₁ : x₁.compatible) (t₂ : x₂.compatible) :
x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ :=
begin
intro h,
ext Z f ⟨Y, f, g, hg, rfl⟩,
rw compatible_iff_sieve_compatible at t₁ t₂,
erw [t₁ g f ⟨_, _, g, hg, id_comp _⟩, t₂ g f ⟨_, _, g, hg, id_comp _⟩],
congr' 1,
apply congr_fun (congr_fun (congr_fun h _) g) hg,
end
/--
Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted
to `R` and then extended back up to `S`, the resulting extension equals `x`.
-/
@[simp]
lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) :
(x.restrict (le_generate R)).sieve_extend = x :=
begin
apply restrict_inj,
{ exact (t.restrict (le_generate R)).sieve_extend _ },
{ exact t },
rw restrict_extend,
exact t.restrict (le_generate R),
end
/--
The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every
restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`.
This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents,
and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4,
equation (2).
-/
def family_of_elements.is_amalgamation (x : family_of_elements P R)
(t : P.obj (op X)) : Prop :=
∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h
lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R)
(h : ∃ t, x.is_amalgamation t) : x.compatible :=
begin
cases h with t ht,
intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm,
rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm],
simp,
end
lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
(x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
(x.restrict h).is_amalgamation t :=
λ Y f hf, ht f (h Y hf)
lemma is_amalgamation_sieve_extend {R : presieve X}
(x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
x.sieve_extend.is_amalgamation t :=
begin
intros Y f hf,
dsimp [family_of_elements.sieve_extend],
rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, (some_spec (some_spec (some_spec hf))).2],
end
/-- A presheaf is separated for a presieve if there is at most one amalgamation. -/
def is_separated_for (P : Cᵒᵖ ⥤ Type v) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R) (t₁ t₂),
x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂
lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R)
{t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) :
t₁ = t₂ :=
hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl)
lemma is_separated_for_iff_generate :
is_separated_for P R ↔ is_separated_for P (generate R) :=
begin
split,
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.restrict (le_generate R)) t₁ t₂ _ _,
{ exact is_amalgamation_restrict _ x t₁ ht₁ },
{ exact is_amalgamation_restrict _ x t₂ ht₂ } },
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.sieve_extend),
{ exact is_amalgamation_sieve_extend x t₁ ht₁ },
{ exact is_amalgamation_sieve_extend x t₂ ht₂ } }
end
lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type v) : is_separated_for P (⊤ : presieve X) :=
λ x t₁ t₂ h₁ h₂,
begin
have q₁ := h₁ (𝟙 X) (by simp),
have q₂ := h₂ (𝟙 X) (by simp),
simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂,
rw [q₁, q₂],
end
/--
We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique
amalgamation.
This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents.
Using `compatible_iff_sieve_compatible`,
this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4.
-/
def is_sheaf_for (P : Cᵒᵖ ⥤ Type v) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t
/--
This is an equivalent condition to be a sheaf, which is useful for the abstraction to local
operators on elementary toposes. However this definition is defined only for sieves, not presieves.
The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`.
This version is also useful to establish that being a sheaf is preserved under isomorphism of
presheaves.
See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of
[Elephant]. This is also a direct reformulation of https://stacks.math.columbia.edu/tag/00Z8.
-/
def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v) (S : sieve X) : Prop :=
∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f
/--
(Implementation). This is a (primarily internal) equivalence between natural transformations
and compatible families.
Cf the discussion after Lemma 7.47.10 in https://stacks.math.columbia.edu/tag/00YW. See also
the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4.
-/
def nat_trans_equiv_compatible_family :
(S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} :=
{ to_fun := λ α,
begin
refine ⟨λ Y f hf, _, _⟩,
{ apply α.app (op Y) ⟨_, hf⟩ },
{ rw compatible_iff_sieve_compatible,
intros Y Z f g hf,
dsimp,
rw ← functor_to_types.naturality _ _ α g.op,
refl }
end,
inv_fun := λ t,
{ app := λ Y f, t.1 _ f.2,
naturality' := λ Y Z g,
begin
ext ⟨f, hf⟩,
apply t.2.to_sieve_compatible _,
end },
left_inv := λ α,
begin
ext X ⟨_, _⟩,
refl
end,
right_inv :=
begin
rintro ⟨x, hx⟩,
refl,
end }
/-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/
lemma extension_iff_amalgamation (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) :
S.functor_inclusion ≫ g = x ↔
(nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) :=
begin
change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩,
split,
{ rintro rfl Y f hf,
rw yoneda_equiv_naturality,
dsimp,
simp }, -- See note [dsimp, simp].
{ intro h,
ext Y ⟨f, hf⟩,
have : _ = x.app Y _ := h f hf,
rw yoneda_equiv_naturality at this,
rw ← this,
dsimp,
simp }, -- See note [dsimp, simp].
end
/--
The yoneda version of the sheaf condition is equivalent to the sheaf condition.
C2.1.4 of [Elephant].
-/
lemma is_sheaf_for_iff_yoneda_sheaf_condition :
is_sheaf_for P S ↔ yoneda_sheaf_condition P S :=
begin
rw [is_sheaf_for, yoneda_sheaf_condition],
simp_rw [extension_iff_amalgamation],
rw equiv.forall_congr_left' nat_trans_equiv_compatible_family,
rw subtype.forall,
apply ball_congr,
intros x hx,
rw equiv.exists_unique_congr_left _,
simp,
end
/--
If `P` is a sheaf for the sieve `S` on `X`, a natural transformation from `S` (viewed as a functor)
to `P` can be (uniquely) extended to all of `yoneda.obj X`.
f
S → P
↓ ↗
yX
-/
noncomputable def is_sheaf_for.extend (h : is_sheaf_for P S) (f : S.functor ⟶ P) :
yoneda.obj X ⟶ P :=
classical.some (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists
/--
Show that the extension of `f : S.functor ⟶ P` to all of `yoneda.obj X` is in fact an extension, ie
that the triangle below commutes, provided `P` is a sheaf for `S`
f
S → P
↓ ↗
yX
-/
@[simp, reassoc]
lemma is_sheaf_for.functor_inclusion_comp_extend (h : is_sheaf_for P S) (f : S.functor ⟶ P) :
S.functor_inclusion ≫ h.extend f = f :=
classical.some_spec (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists
/-- The extension of `f` to `yoneda.obj X` is unique. -/
lemma is_sheaf_for.unique_extend (h : is_sheaf_for P S) {f : S.functor ⟶ P} (t : yoneda.obj X ⟶ P)
(ht : S.functor_inclusion ≫ t = f) :
t = h.extend f :=
((is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).unique ht (h.functor_inclusion_comp_extend f))
/--
If `P` is a sheaf for the sieve `S` on `X`, then if two natural transformations from `yoneda.obj X`
to `P` agree when restricted to the subfunctor given by `S`, they are equal.
-/
lemma is_sheaf_for.hom_ext (h : is_sheaf_for P S) (t₁ t₂ : yoneda.obj X ⟶ P)
(ht : S.functor_inclusion ≫ t₁ = S.functor_inclusion ≫ t₂) :
t₁ = t₂ :=
(h.unique_extend t₁ ht).trans (h.unique_extend t₂ rfl).symm
/-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/
lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for :
is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔
is_sheaf_for P R :=
begin
rw [is_separated_for, ←forall_and_distrib],
apply forall_congr,
intro x,
split,
{ intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 },
{ intros h,
refine ⟨_, (exists_of_exists_unique ∘ h)⟩,
intros t₁ t₂ ht₁ ht₂,
apply (h _).unique ht₁ ht₂,
exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ }
end
/--
If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`.
-/
lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) :
(∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) →
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
exact and.intro t,
end
/-- If `P` is a sheaf for `R`, it is separated for `R`. -/
lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R :=
λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1
/-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/
noncomputable def is_sheaf_for.amalgamate
(t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) :
P.obj (op X) :=
classical.some (t x hx).exists
lemma is_sheaf_for.is_amalgamation
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) :
x.is_amalgamation (t.amalgamate x hx) :=
classical.some_spec (t x hx).exists
@[simp]
lemma is_sheaf_for.valid_glue
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) :
P.map f.op (t.amalgamate x hx) = x f Hf :=
t.is_amalgamation hx f Hf
/-- C2.1.3 in [Elephant] -/
lemma is_sheaf_for_iff_generate (R : presieve X) :
is_sheaf_for P R ↔ is_sheaf_for P (generate R) :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_iff_generate,
apply and_congr (iff.refl _),
split,
{ intros q x hx,
apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))),
intros t ht,
simpa [hx] using is_amalgamation_sieve_extend _ _ ht },
{ intros q x hx,
apply exists_imp_exists _ (q _ (hx.sieve_extend _)),
intros t ht,
simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht },
end
/--
Every presheaf is a sheaf for the family {𝟙 X}.
[Elephant] C2.1.5(i)
-/
lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type v) :
is_sheaf_for P (presieve.singleton (𝟙 X)) :=
begin
intros x hx,
refine ⟨x _ (presieve.singleton_self _), _, _⟩,
{ rintro _ _ ⟨rfl, rfl⟩,
simp },
{ intros t ht,
simpa using ht _ (presieve.singleton_self _) }
end
/--
Every presheaf is a sheaf for the maximal sieve.
[Elephant] C2.1.5(ii)
-/
lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type v) :
is_sheaf_for P ((⊤ : sieve X) : presieve X) :=
begin
rw ← generate_of_singleton_split_epi (𝟙 X),
rw ← is_sheaf_for_iff_generate,
apply is_sheaf_for_singleton_iso,
end
/--
If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that
"being a sheaf for a presieve" is a mathematical or hygenic property.
-/
lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type v} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R :=
begin
rw [is_sheaf_for_iff_generate R, is_sheaf_for_iff_generate R],
intro h,
rw [is_sheaf_for_iff_yoneda_sheaf_condition],
intro f,
refine ⟨h.extend (f ≫ i.inv) ≫ i.hom, by simp, _⟩,
intros g' hg',
rw [← i.comp_inv_eq, h.unique_extend (g' ≫ i.inv) (by rw reassoc_of hg')],
end
/--
If a presieve `R` on `X` has a subsieve `S` such that:
* `P` is a sheaf for `S`.
* For every `f` in `R`, `P` is separated for the pullback of `S` along `f`,
then `P` is a sheaf for `R`.
This is closely related to [Elephant] C2.1.6(i).
-/
lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type v) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(hS : is_sheaf_for P S)
(trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) :
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
split,
{ intros x t₁ t₂ ht₁ ht₂,
exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁)
(is_amalgamation_restrict h x t₂ ht₂) },
{ intros x hx,
use hS.amalgamate _ (hx.restrict h),
intros W j hj,
apply (trans hj).ext,
intros Y f hf,
rw [←functor_to_types.map_comp_apply, ←op_comp,
hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict,
←hx (𝟙 _) f _ _ (id_comp _)],
simp },
end
/--
If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which
contains `S`.
This is closely related to [Elephant] C2.1.6.
-/
lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type v) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) :
is_sheaf_for P R :=
is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for)
/-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/
def is_separated (P : Cᵒᵖ ⥤ Type v) : Prop :=
∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S
/--
A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology.
If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to
check the sheaf condition at presieves in the pretopology.
-/
def is_sheaf (P : Cᵒᵖ ⥤ Type v) : Prop :=
∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S
lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type v} (hp : is_sheaf J P)
(R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R :=
(is_sheaf_for_iff_generate R).2 $ hp _ hr
lemma is_sheaf_of_le (P : Cᵒᵖ ⥤ Type v) {J₁ J₂ : grothendieck_topology C} :
J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P :=
λ h t X S hS, t S (h _ hS)
lemma is_separated_of_is_sheaf (P : Cᵒᵖ ⥤ Type v) (h : is_sheaf J P) : is_separated J P :=
λ X S hS, (h S hS).is_separated_for
/-- The property of being a sheaf is preserved by isomorphism. -/
lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type v} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' :=
λ X S hS, is_sheaf_for_iso i (h S hS)
lemma is_sheaf_of_yoneda (h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) :
is_sheaf J P :=
λ X S hS, is_sheaf_for_iff_yoneda_sheaf_condition.2 (h _ hS)
/--
For a topology generated by a basis, it suffices to check the sheaf condition on the basis
presieves only.
-/
lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) :
is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) :=
begin
split,
{ intros PJ X R hR,
rw is_sheaf_for_iff_generate,
apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ },
{ rintro PK X S ⟨R, hR, RS⟩,
have gRS : ⇑(generate R) ≤ S,
{ apply gi_generate.gc.monotone_u,
rwa sets_iff_generate },
apply is_sheaf_for_subsieve P gRS _,
intros Y f,
rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate],
exact PK (pullback_arrows f R) (K.pullbacks f R hR) }
end
/-- Any presheaf is a sheaf for the bottom (trivial) grothendieck topology. -/
lemma is_sheaf_bot : is_sheaf (⊥ : grothendieck_topology C) P :=
λ X, by simp [is_sheaf_for_top_sieve]
end presieve
namespace equalizer
variables {C : Type v} [small_category C] (P : Cᵒᵖ ⥤ Type v) {X : C} (R : presieve X) (S : sieve X)
noncomputable theory
/--
The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of https://stacks.math.columbia.edu/tag/00VM.
-/
def first_obj : Type v :=
∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1))
/-- Show that `first_obj` is isomorphic to `family_of_elements`. -/
@[simps]
def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P :=
{ hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t,
inv := pi.lift (λ f x, x _ f.2.2),
hom_inv_id' :=
begin
ext ⟨Y, f, hf⟩ p,
simpa,
end,
inv_hom_id' :=
begin
ext x Y f hf,
apply limits.types.limit.lift_π_apply,
end }
instance : inhabited (first_obj P (⊥ : presieve X)) :=
((first_obj_eq_family P _).to_equiv).inhabited
/--
The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of https://stacks.math.columbia.edu/tag/00VM.
-/
def fork_map : P.obj (op X) ⟶ first_obj P R :=
pi.lift (λ f, P.map f.2.1.op)
/-!
This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and
the definition of `is_sheaf_for`.
-/
namespace sieve
/--
The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used
to check a family is compatible.
-/
def second_obj : Type v :=
∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1))
/-- The map `p` of Equations (3,4) [MM92]. -/
def first_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f}))
instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ (default _)⟩
/-- The map `a` of Equations (3,4) [MM92]. -/
def second_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op)
lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S :=
begin
apply limit.hom_ext,
rintro ⟨Y, Z, g, f, hf⟩,
simp [first_map, second_map, fork_map],
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P S) :
((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x :=
begin
rw presieve.compatible_iff_sieve_compatible,
split,
{ intro t,
ext ⟨Y, Z, g, f, hf⟩,
simpa [first_map, second_map] using t _ g hf },
{ intros t Y Z f g hf,
rw types.limit_ext_iff at t,
simpa [first_map, second_map] using t ⟨Y, Z, g, f, hf⟩ }
end
/-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/
lemma equalizer_sheaf_condition :
presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) :=
begin
rw [types.type_equalizer_iff_unique,
← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm],
simp_rw ← compatible_iff,
simp only [inv_hom_id_apply, iso.to_equiv_symm_fun],
apply ball_congr,
intros x tx,
apply exists_unique_congr,
intro t,
rw ← iso.to_equiv_symm_fun,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [first_obj_eq_family, fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [first_obj_eq_family, fork_map] }
end
end sieve
/-!
This section establishes the equivalence between the sheaf condition of
https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`.
-/
namespace presieve
variables [has_pullbacks C]
/--
The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which
contains the data used to check a family of elements for a presieve is compatible.
-/
def second_obj : Type v :=
∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})),
P.obj (op (pullback fg.1.2.1 fg.2.2.1)))
/-- The map `pr₀*` of https://stacks.math.columbia.edu/tag/00VL. -/
def first_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op)
instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ (default _)⟩
/-- The map `pr₁*` of https://stacks.math.columbia.edu/tag/00VL. -/
def second_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op)
lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R :=
begin
apply limit.hom_ext,
rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩,
simp only [first_map, second_map, fork_map],
simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk,
subtype.val_eq_coe],
rw [← P.map_comp, ← op_comp, pullback.condition],
simp,
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P R) :
((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x :=
begin
rw presieve.pullback_compatible_iff,
split,
{ intro t,
ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩,
simpa [first_map, second_map] using t hf hg },
{ intros t Y Z f g hf hg,
rw types.limit_ext_iff at t,
simpa [first_map, second_map] using t ⟨⟨Y, f, hf⟩, Z, g, hg⟩ }
end
/--
`P` is a sheaf for `R`, iff the fork given by `w` is an equalizer.
See https://stacks.math.columbia.edu/tag/00VM.
-/
lemma sheaf_condition :
R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) :=
begin
rw types.type_equalizer_iff_unique,
erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm,
simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply],
apply ball_congr,
intros x hx,
apply exists_unique_congr,
intros t,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [fork_map] }
end
end presieve
end equalizer
variables {C : Type u} [category.{v} C]
variables (J : grothendieck_topology C)
/-- The category of sheaves on a grothendieck topology. -/
@[derive category]
def SheafOfTypes (J : grothendieck_topology C) : Type (max u (v+1)) :=
{P : Cᵒᵖ ⥤ Type v // presieve.is_sheaf J P}
/-- The inclusion functor from sheaves to presheaves. -/
@[simps {rhs_md := semireducible}, derive [full, faithful]]
def SheafOfTypes_to_presheaf : SheafOfTypes J ⥤ (Cᵒᵖ ⥤ Type v) :=
full_subcategory_inclusion (presieve.is_sheaf J)
/--
The category of sheaves on the bottom (trivial) grothendieck topology is equivalent to the category
of presheaves.
-/
@[simps]
def SheafOfTypes_bot_equiv : SheafOfTypes (⊥ : grothendieck_topology C) ≌ (Cᵒᵖ ⥤ Type v) :=
{ functor := SheafOfTypes_to_presheaf _,
inverse :=
{ obj := λ P, ⟨P, presieve.is_sheaf_bot⟩,
map := λ P₁ P₂ f, (SheafOfTypes_to_presheaf _).preimage f },
unit_iso :=
{ hom := { app := λ _, 𝟙 _ },
inv := { app := λ _, 𝟙 _ } },
counit_iso := iso.refl _ }
instance : inhabited (SheafOfTypes (⊥ : grothendieck_topology C)) :=
⟨SheafOfTypes_bot_equiv.inverse.obj ((functor.const _).obj punit)⟩
end category_theory
|
595240349671e92b484d86158c89fb5fb96d8a3a | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/secnot.lean | e2af2e6f80daa5a560f9a658417dd3d87162e453 | [
"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 | 416 | lean | import data.num
section
variable {A : Type}
definition f (a b : A) := a
infixl `◀`:65 := f
variables a b : A
check a ◀ b
end
inductive list (T : Type) : Type :=
| nil {} : list T
| cons : T → list T → list T
namespace list
section
variable {T : Type}
notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l
check [(10:num), 20, 30]
end
end list
open list
check [(10:num), 20, 40]
check (10:num) ◀ 20
|
19f05083da5c4c12da8c26cf826804e07bf4d571 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/model_theory/semantics.lean | 724ef54eebf9957b917f605d265359d60353b520 | [
"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 | 38,886 | lean | /-
Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn
-/
import data.finset.basic
import model_theory.syntax
/-!
# Basics on First-Order Semantics
This file defines the interpretations of first-order terms, formulas, sentences, and theories
in a style inspired by the [Flypitch project](https://flypitch.github.io/).
## Main Definitions
* `first_order.language.term.realize` is defined so that `t.realize v` is the term `t` evaluated at
variables `v`.
* `first_order.language.bounded_formula.realize` is defined so that `φ.realize v xs` is the bounded
formula `φ` evaluated at tuples of variables `v` and `xs`.
* `first_order.language.formula.realize` is defined so that `φ.realize v` is the formula `φ`
evaluated at variables `v`.
* `first_order.language.sentence.realize` is defined so that `φ.realize M` is the sentence `φ`
evaluated in the structure `M`. Also denoted `M ⊨ φ`.
* `first_order.language.Theory.model` is defined so that `T.model M` is true if and only if every
sentence of `T` is realized in `M`. Also denoted `T ⊨ φ`.
## Main Results
* `first_order.language.bounded_formula.realize_to_prenex` shows that the prenex normal form of a
formula has the same realization as the original formula.
* Several results in this file show that syntactic constructions such as `relabel`, `cast_le`,
`lift_at`, `subst`, and the actions of language maps commute with realization of terms, formulas,
sentences, and theories.
## Implementation Notes
* Formulas use a modified version of de Bruijn variables. Specifically, a `L.bounded_formula α n`
is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some
indexed by `fin n`, which can. For any `φ : L.bounded_formula α (n + 1)`, we define the formula
`∀' φ : L.bounded_formula α n` by universally quantifying over the variable indexed by
`n : fin (n + 1)`.
## References
For the Flypitch project:
- [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*]
[flypitch_cpp]
- [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of
the continuum hypothesis*][flypitch_itp]
-/
universes u v w u' v'
namespace first_order
namespace language
variables {L : language.{u v}} {L' : language}
variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P]
variables {α : Type u'} {β : Type v'}
open_locale first_order cardinal
open Structure cardinal fin
namespace term
/-- A term `t` with variables indexed by `α` can be evaluated by giving a value to each variable. -/
@[simp] def realize (v : α → M) :
∀ (t : L.term α), M
| (var k) := v k
| (func f ts) := fun_map f (λ i, (ts i).realize)
@[simp] lemma realize_relabel {t : L.term α} {g : α → β} {v : β → M} :
(t.relabel g).realize v = t.realize (v ∘ g) :=
begin
induction t with _ n f ts ih,
{ refl, },
{ simp [ih] }
end
@[simp] lemma realize_lift_at {n n' m : ℕ} {t : L.term (α ⊕ fin n)}
{v : α ⊕ fin (n + n') → M} :
(t.lift_at n' m).realize v = t.realize (v ∘
(sum.map id (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i))) :=
realize_relabel
@[simp] lemma realize_constants {c : L.constants} {v : α → M} :
c.term.realize v = c :=
fun_map_eq_coe_constants
@[simp] lemma realize_functions_apply₁ {f : L.functions 1} {t : L.term α} {v : α → M} :
(f.apply₁ t).realize v = fun_map f ![t.realize v] :=
begin
rw [functions.apply₁, term.realize],
refine congr rfl (funext (λ i, _)),
simp only [matrix.cons_val_fin_one],
end
@[simp] lemma realize_functions_apply₂ {f : L.functions 2} {t₁ t₂ : L.term α} {v : α → M} :
(f.apply₂ t₁ t₂).realize v = fun_map f ![t₁.realize v, t₂.realize v] :=
begin
rw [functions.apply₂, term.realize],
refine congr rfl (funext (fin.cases _ _)),
{ simp only [matrix.cons_val_zero], },
{ simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] }
end
lemma realize_con {A : set M} {a : A} {v : α → M} :
(L.con a).term.realize v = a := rfl
@[simp] lemma realize_subst {t : L.term α} {tf : α → L.term β} {v : β → M} :
(t.subst tf).realize v = t.realize (λ a, (tf a).realize v) :=
begin
induction t with _ _ _ _ ih,
{ refl },
{ simp [ih] }
end
@[simp] lemma realize_restrict_var [decidable_eq α] {t : L.term α} {s : set α}
(h : ↑t.var_finset ⊆ s) {v : α → M} :
(t.restrict_var (set.inclusion h)).realize (v ∘ coe) = t.realize v :=
begin
induction t with _ _ _ _ ih,
{ refl },
{ simp_rw [var_finset, finset.coe_bUnion, set.Union_subset_iff] at h,
exact congr rfl (funext (λ i, ih i (h i (finset.mem_univ i)))) },
end
@[simp] lemma realize_restrict_var_left [decidable_eq α] {γ : Type*}
{t : L.term (α ⊕ γ)} {s : set α}
(h : ↑t.var_finset_left ⊆ s) {v : α → M} {xs : γ → M} :
(t.restrict_var_left (set.inclusion h)).realize (sum.elim (v ∘ coe) xs) =
t.realize (sum.elim v xs) :=
begin
induction t with a _ _ _ ih,
{ cases a;
refl },
{ simp_rw [var_finset_left, finset.coe_bUnion, set.Union_subset_iff] at h,
exact congr rfl (funext (λ i, ih i (h i (finset.mem_univ i)))) },
end
@[simp] lemma realize_constants_to_vars [L[[α]].Structure M]
[(Lhom_with_constants L α).is_expansion_on M]
{t : L[[α]].term β} {v : β → M} :
t.constants_to_vars.realize (sum.elim (λ a, ↑(L.con a)) v) = t.realize v :=
begin
induction t with _ n f _ ih,
{ simp },
{ cases n,
{ cases f,
{ simp [ih], },
{ simp only [realize, constants_to_vars, sum.elim_inl, fun_map_eq_coe_constants],
refl } },
{ cases f,
{ simp [ih] },
{ exact is_empty_elim f } } }
end
@[simp] lemma realize_vars_to_constants [L[[α]].Structure M]
[(Lhom_with_constants L α).is_expansion_on M]
{t : L.term (α ⊕ β)} {v : β → M} :
t.vars_to_constants.realize v = t.realize (sum.elim (λ a, ↑(L.con a)) v) :=
begin
induction t with ab n f ts ih,
{ cases ab;
simp [language.con], },
{ simp [ih], }
end
lemma realize_constants_vars_equiv_left [L[[α]].Structure M]
[(Lhom_with_constants L α).is_expansion_on M]
{n} {t : L[[α]].term (β ⊕ fin n)} {v : β → M} {xs : fin n → M} :
(constants_vars_equiv_left t).realize (sum.elim (sum.elim (λ a, ↑(L.con a)) v) xs) =
t.realize (sum.elim v xs) :=
begin
simp only [constants_vars_equiv_left, realize_relabel, equiv.coe_trans, function.comp_app,
constants_vars_equiv_apply, relabel_equiv_symm_apply],
refine trans _ (realize_constants_to_vars),
rcongr,
rcases x with (a | (b | i));
simp,
end
end term
namespace Lhom
@[simp] lemma realize_on_term [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(t : L.term α) (v : α → M) :
(φ.on_term t).realize v = t.realize v :=
begin
induction t with _ n f ts ih,
{ refl },
{ simp only [term.realize, Lhom.on_term, Lhom.map_on_function, ih] }
end
end Lhom
@[simp] lemma hom.realize_term (g : M →[L] N) {t : L.term α} {v : α → M} :
t.realize (g ∘ v) = g (t.realize v) :=
begin
induction t,
{ refl },
{ rw [term.realize, term.realize, g.map_fun],
refine congr rfl _,
ext x,
simp [t_ih x], },
end
@[simp] lemma embedding.realize_term {v : α → M}
(t : L.term α) (g : M ↪[L] N) :
t.realize (g ∘ v) = g (t.realize v) :=
g.to_hom.realize_term
@[simp] lemma equiv.realize_term {v : α → M}
(t : L.term α) (g : M ≃[L] N) :
t.realize (g ∘ v) = g (t.realize v) :=
g.to_hom.realize_term
variables {L} {α} {n : ℕ}
namespace bounded_formula
open term
/-- A bounded formula can be evaluated as true or false by giving values to each free variable. -/
def realize :
∀ {l} (f : L.bounded_formula α l) (v : α → M) (xs : fin l → M), Prop
| _ falsum v xs := false
| _ (bounded_formula.equal t₁ t₂) v xs := t₁.realize (sum.elim v xs) = t₂.realize (sum.elim v xs)
| _ (bounded_formula.rel R ts) v xs := rel_map R (λ i, (ts i).realize (sum.elim v xs))
| _ (bounded_formula.imp f₁ f₂) v xs := realize f₁ v xs → realize f₂ v xs
| _ (bounded_formula.all f) v xs := ∀(x : M), realize f v (snoc xs x)
variables {l : ℕ} {φ ψ : L.bounded_formula α l} {θ : L.bounded_formula α l.succ}
variables {v : α → M} {xs : fin l → M}
@[simp] lemma realize_bot :
(⊥ : L.bounded_formula α l).realize v xs ↔ false :=
iff.rfl
@[simp] lemma realize_not :
φ.not.realize v xs ↔ ¬ φ.realize v xs :=
iff.rfl
@[simp] lemma realize_bd_equal (t₁ t₂ : L.term (α ⊕ fin l)) :
(t₁.bd_equal t₂).realize v xs ↔
(t₁.realize (sum.elim v xs) = t₂.realize (sum.elim v xs)) :=
iff.rfl
@[simp] lemma realize_top :
(⊤ : L.bounded_formula α l).realize v xs ↔ true :=
by simp [has_top.top]
@[simp] lemma realize_inf : (φ ⊓ ψ).realize v xs ↔ (φ.realize v xs ∧ ψ.realize v xs) :=
by simp [has_inf.inf, realize]
@[simp] lemma realize_foldr_inf (l : list (L.bounded_formula α n))
(v : α → M) (xs : fin n → M) :
(l.foldr (⊓) ⊤).realize v xs ↔ ∀ φ ∈ l, bounded_formula.realize φ v xs :=
begin
induction l with φ l ih,
{ simp },
{ simp [ih] }
end
@[simp] lemma realize_imp : (φ.imp ψ).realize v xs ↔ (φ.realize v xs → ψ.realize v xs) :=
by simp only [realize]
@[simp] lemma realize_rel {k : ℕ} {R : L.relations k} {ts : fin k → L.term _} :
(R.bounded_formula ts).realize v xs ↔ rel_map R (λ i, (ts i).realize (sum.elim v xs)) :=
iff.rfl
@[simp] lemma realize_rel₁ {R : L.relations 1} {t : L.term _} :
(R.bounded_formula₁ t).realize v xs ↔ rel_map R ![t.realize (sum.elim v xs)] :=
begin
rw [relations.bounded_formula₁, realize_rel, iff_eq_eq],
refine congr rfl (funext (λ _, _)),
simp only [matrix.cons_val_fin_one],
end
@[simp] lemma realize_rel₂ {R : L.relations 2} {t₁ t₂ : L.term _} :
(R.bounded_formula₂ t₁ t₂).realize v xs ↔
rel_map R ![t₁.realize (sum.elim v xs), t₂.realize (sum.elim v xs)] :=
begin
rw [relations.bounded_formula₂, realize_rel, iff_eq_eq],
refine congr rfl (funext (fin.cases _ _)),
{ simp only [matrix.cons_val_zero]},
{ simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] }
end
@[simp] lemma realize_sup : (φ ⊔ ψ).realize v xs ↔ (φ.realize v xs ∨ ψ.realize v xs) :=
begin
simp only [realize, has_sup.sup, realize_not, eq_iff_iff],
tauto,
end
@[simp] lemma realize_foldr_sup (l : list (L.bounded_formula α n))
(v : α → M) (xs : fin n → M) :
(l.foldr (⊔) ⊥).realize v xs ↔ ∃ φ ∈ l, bounded_formula.realize φ v xs :=
begin
induction l with φ l ih,
{ simp },
{ simp_rw [list.foldr_cons, realize_sup, ih, exists_prop, list.mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left] }
end
@[simp] lemma realize_all : (all θ).realize v xs ↔ ∀ (a : M), (θ.realize v (fin.snoc xs a)) :=
iff.rfl
@[simp] lemma realize_ex : θ.ex.realize v xs ↔ ∃ (a : M), (θ.realize v (fin.snoc xs a)) :=
begin
rw [bounded_formula.ex, realize_not, realize_all, not_forall],
simp_rw [realize_not, not_not],
end
@[simp] lemma realize_iff : (φ.iff ψ).realize v xs ↔ (φ.realize v xs ↔ ψ.realize v xs) :=
by simp only [bounded_formula.iff, realize_inf, realize_imp, and_imp, ← iff_def]
lemma realize_cast_le_of_eq {m n : ℕ} (h : m = n) {h' : m ≤ n} {φ : L.bounded_formula α m}
{v : α → M} {xs : fin n → M} :
(φ.cast_le h').realize v xs ↔ φ.realize v (xs ∘ fin.cast h) :=
begin
subst h,
simp only [cast_le_rfl, cast_refl, order_iso.coe_refl, function.comp.right_id],
end
lemma realize_map_term_rel_id [L'.Structure M]
{ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin n)}
{fr : ∀ n, L.relations n → L'.relations n}
{n} {φ : L.bounded_formula α n} {v : α → M} {v' : β → M} {xs : fin n → M}
(h1 : ∀ n (t : L.term (α ⊕ fin n)) (xs : fin n → M),
(ft n t).realize (sum.elim v' xs) = t.realize (sum.elim v xs))
(h2 : ∀ n (R : L.relations n) (x : fin n → M), rel_map (fr n R) x = rel_map R x) :
(φ.map_term_rel ft fr (λ _, id)).realize v' xs ↔ φ.realize v xs :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih,
{ refl },
{ simp [map_term_rel, realize, h1] },
{ simp [map_term_rel, realize, h1, h2] },
{ simp [map_term_rel, realize, ih1, ih2], },
{ simp only [map_term_rel, realize, ih, id.def] },
end
lemma realize_map_term_rel_add_cast_le [L'.Structure M]
{k : ℕ}
{ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin (k + n))}
{fr : ∀ n, L.relations n → L'.relations n}
{n} {φ : L.bounded_formula α n} (v : ∀ {n}, (fin (k + n) → M) → α → M) {v' : β → M}
(xs : fin (k + n) → M)
(h1 : ∀ n (t : L.term (α ⊕ fin n)) (xs' : fin (k + n) → M),
(ft n t).realize (sum.elim v' xs') =
t.realize (sum.elim (v xs') (xs' ∘ fin.nat_add _)))
(h2 : ∀ n (R : L.relations n) (x : fin n → M), rel_map (fr n R) x = rel_map R x)
(hv : ∀ n (xs : fin (k + n) → M) (x : M), @v (n+1) (snoc xs x : fin _ → M) = v xs):
(φ.map_term_rel ft fr (λ n, cast_le (add_assoc _ _ _).symm.le)).realize v' xs ↔
φ.realize (v xs) (xs ∘ fin.nat_add _) :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih,
{ refl },
{ simp [map_term_rel, realize, h1] },
{ simp [map_term_rel, realize, h1, h2] },
{ simp [map_term_rel, realize, ih1, ih2], },
{ simp [map_term_rel, realize, ih, hv] },
end
lemma realize_relabel {m n : ℕ}
{φ : L.bounded_formula α n} {g : α → β ⊕ fin m} {v : β → M} {xs : fin (m + n) → M} :
(φ.relabel g).realize v xs ↔
φ.realize (sum.elim v (xs ∘ fin.cast_add n) ∘ g) (xs ∘ fin.nat_add m) :=
by rw [relabel, realize_map_term_rel_add_cast_le]; intros; simp
lemma realize_lift_at {n n' m : ℕ} {φ : L.bounded_formula α n}
{v : α → M} {xs : fin (n + n') → M} (hmn : m + n' ≤ n + 1) :
(φ.lift_at n' m).realize v xs ↔ φ.realize v (xs ∘
(λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i)) :=
begin
rw lift_at,
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 k _ ih3,
{ simp [realize, map_term_rel], },
{ simp [realize, map_term_rel, realize_rel, realize_lift_at, sum.elim_comp_map], },
{ simp [realize, map_term_rel, realize_rel, realize_lift_at, sum.elim_comp_map], },
{ simp only [map_term_rel, realize, ih1 hmn, ih2 hmn] },
{ have h : k + 1 + n' = k + n'+ 1,
{ rw [add_assoc, add_comm 1 n', ← add_assoc], },
simp only [map_term_rel, realize, realize_cast_le_of_eq h, ih3 (hmn.trans k.succ.le_succ)],
refine forall_congr (λ x, iff_eq_eq.mpr (congr rfl (funext (fin.last_cases _ (λ i, _))))),
{ simp only [function.comp_app, coe_last, snoc_last],
by_cases (k < m),
{ rw if_pos h,
refine (congr rfl (ext _)).trans (snoc_last _ _),
simp only [coe_cast, coe_cast_add, coe_last, self_eq_add_right],
refine le_antisymm (le_of_add_le_add_left ((hmn.trans (nat.succ_le_of_lt h)).trans _))
n'.zero_le,
rw add_zero },
{ rw if_neg h,
refine (congr rfl (ext _)).trans (snoc_last _ _),
simp } },
{ simp only [function.comp_app, fin.snoc_cast_succ],
refine (congr rfl (ext _)).trans (snoc_cast_succ _ _ _),
simp only [cast_refl, coe_cast_succ, order_iso.coe_refl, id.def],
split_ifs;
simp } }
end
lemma realize_lift_at_one {n m : ℕ} {φ : L.bounded_formula α n}
{v : α → M} {xs : fin (n + 1) → M} (hmn : m ≤ n) :
(φ.lift_at 1 m).realize v xs ↔ φ.realize v (xs ∘
(λ i, if ↑i < m then cast_succ i else i.succ)) :=
by simp_rw [realize_lift_at (add_le_add_right hmn 1), cast_succ, add_nat_one]
@[simp] lemma realize_lift_at_one_self {n : ℕ} {φ : L.bounded_formula α n}
{v : α → M} {xs : fin (n + 1) → M} :
(φ.lift_at 1 n).realize v xs ↔ φ.realize v (xs ∘ cast_succ) :=
begin
rw [realize_lift_at_one (refl n), iff_eq_eq],
refine congr rfl (congr rfl (funext (λ i, _))),
rw [if_pos i.is_lt],
end
lemma realize_subst {φ : L.bounded_formula α n} {tf : α → L.term β} {v : β → M} {xs : fin n → M} :
(φ.subst tf).realize v xs ↔ φ.realize (λ a, (tf a).realize v) xs :=
realize_map_term_rel_id (λ n t x, begin
rw term.realize_subst,
rcongr a,
{ cases a,
{ simp only [sum.elim_inl, term.realize_relabel, sum.elim_comp_inl] },
{ refl } }
end) (by simp)
@[simp] lemma realize_restrict_free_var [decidable_eq α] {n : ℕ} {φ : L.bounded_formula α n}
{s : set α} (h : ↑φ.free_var_finset ⊆ s) {v : α → M} {xs : fin n → M} :
(φ.restrict_free_var (set.inclusion h)).realize (v ∘ coe) xs ↔
φ.realize v xs :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3,
{ refl },
{ simp [restrict_free_var, realize] },
{ simp [restrict_free_var, realize] },
{ simp [restrict_free_var, realize, ih1, ih2] },
{ simp [restrict_free_var, realize, ih3] },
end
lemma realize_constants_vars_equiv [L[[α]].Structure M]
[(Lhom_with_constants L α).is_expansion_on M]
{n} {φ : L[[α]].bounded_formula β n} {v : β → M} {xs : fin n → M} :
(constants_vars_equiv φ).realize (sum.elim (λ a, ↑(L.con a)) v) xs ↔ φ.realize v xs :=
begin
refine realize_map_term_rel_id (λ n t xs, realize_constants_vars_equiv_left) (λ n R xs, _),
rw ← (Lhom_with_constants L α).map_on_relation (equiv.sum_empty (L.relations n)
((constants_on α).relations n) R) xs,
rcongr,
cases R,
{ simp, },
{ exact is_empty_elim R }
end
@[simp] lemma realize_relabel_equiv {g : α ≃ β} {k} {φ : L.bounded_formula α k}
{v : β → M} {xs : fin k → M} :
(relabel_equiv g φ).realize v xs ↔ φ.realize (v ∘ g) xs :=
begin
simp only [relabel_equiv, map_term_rel_equiv_apply, equiv.coe_refl],
refine realize_map_term_rel_id (λ n t xs, _) (λ _ _ _, rfl),
simp only [relabel_equiv_apply, term.realize_relabel],
refine congr (congr rfl _) rfl,
ext (i | i);
refl,
end
variables [nonempty M]
lemma realize_all_lift_at_one_self {n : ℕ} {φ : L.bounded_formula α n}
{v : α → M} {xs : fin n → M} :
(φ.lift_at 1 n).all.realize v xs ↔ φ.realize v xs :=
begin
inhabit M,
simp only [realize_all, realize_lift_at_one_self],
refine ⟨λ h, _, λ h a, _⟩,
{ refine (congr rfl (funext (λ i, _))).mp (h default),
simp, },
{ refine (congr rfl (funext (λ i, _))).mp h,
simp }
end
lemma realize_to_prenex_imp_right {φ ψ : L.bounded_formula α n}
(hφ : is_qf φ) (hψ : is_prenex ψ) {v : α → M} {xs : fin n → M} :
(φ.to_prenex_imp_right ψ).realize v xs ↔ (φ.imp ψ).realize v xs :=
begin
revert φ,
induction hψ with _ _ hψ _ _ hψ ih _ _ hψ ih; intros φ hφ,
{ rw hψ.to_prenex_imp_right },
{ refine trans (forall_congr (λ _, ih hφ.lift_at)) _,
simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_all],
exact ⟨λ h1 a h2, h1 h2 a, λ h1 h2 a, h1 a h2⟩, },
{ rw [to_prenex_imp_right, realize_ex],
refine trans (exists_congr (λ _, ih hφ.lift_at)) _,
simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_ex],
refine ⟨_, λ h', _⟩,
{ rintro ⟨a, ha⟩ h,
exact ⟨a, ha h⟩ },
{ by_cases φ.realize v xs,
{ obtain ⟨a, ha⟩ := h' h,
exact ⟨a, λ _, ha⟩ },
{ inhabit M,
exact ⟨default, λ h'', (h h'').elim⟩ } } }
end
lemma realize_to_prenex_imp {φ ψ : L.bounded_formula α n}
(hφ : is_prenex φ) (hψ : is_prenex ψ) {v : α → M} {xs : fin n → M} :
(φ.to_prenex_imp ψ).realize v xs ↔ (φ.imp ψ).realize v xs :=
begin
revert ψ,
induction hφ with _ _ hφ _ _ hφ ih _ _ hφ ih; intros ψ hψ,
{ rw [hφ.to_prenex_imp],
exact realize_to_prenex_imp_right hφ hψ, },
{ rw [to_prenex_imp, realize_ex],
refine trans (exists_congr (λ _, ih hψ.lift_at)) _,
simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_all],
refine ⟨_, λ h', _⟩,
{ rintro ⟨a, ha⟩ h,
exact ha (h a) },
{ by_cases ψ.realize v xs,
{ inhabit M,
exact ⟨default, λ h'', h⟩ },
{ obtain ⟨a, ha⟩ := not_forall.1 (h ∘ h'),
exact ⟨a, λ h, (ha h).elim⟩ } } },
{ refine trans (forall_congr (λ _, ih hψ.lift_at)) _,
simp, },
end
@[simp] lemma realize_to_prenex (φ : L.bounded_formula α n) {v : α → M} :
∀ {xs : fin n → M}, φ.to_prenex.realize v xs ↔ φ.realize v xs :=
begin
refine bounded_formula.rec_on φ
(λ _ _, iff.rfl)
(λ _ _ _ _, iff.rfl)
(λ _ _ _ _ _, iff.rfl)
(λ _ f1 f2 h1 h2 _, _)
(λ _ f h xs, _),
{ rw [to_prenex, realize_to_prenex_imp f1.to_prenex_is_prenex f2.to_prenex_is_prenex,
realize_imp, realize_imp, h1, h2],
apply_instance },
{ rw [realize_all, to_prenex, realize_all],
exact forall_congr (λ a, h) },
end
end bounded_formula
attribute [protected] bounded_formula.falsum bounded_formula.equal bounded_formula.rel
attribute [protected] bounded_formula.imp bounded_formula.all
namespace Lhom
open bounded_formula
@[simp] lemma realize_on_bounded_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
{n : ℕ} (ψ : L.bounded_formula α n) {v : α → M} {xs : fin n → M} :
(φ.on_bounded_formula ψ).realize v xs ↔ ψ.realize v xs :=
begin
induction ψ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3,
{ refl },
{ simp only [on_bounded_formula, realize_bd_equal, realize_on_term],
refl, },
{ simp only [on_bounded_formula, realize_rel, realize_on_term, Lhom.map_on_relation],
refl, },
{ simp only [on_bounded_formula, ih1, ih2, realize_imp], },
{ simp only [on_bounded_formula, ih3, realize_all], },
end
end Lhom
attribute [protected] bounded_formula.falsum bounded_formula.equal bounded_formula.rel
attribute [protected] bounded_formula.imp bounded_formula.all
namespace formula
/-- A formula can be evaluated as true or false by giving values to each free variable. -/
def realize (φ : L.formula α) (v : α → M) : Prop :=
φ.realize v default
variables {M} {φ ψ : L.formula α} {v : α → M}
@[simp] lemma realize_not :
(φ.not).realize v ↔ ¬ φ.realize v :=
iff.rfl
@[simp] lemma realize_bot :
(⊥ : L.formula α).realize v ↔ false :=
iff.rfl
@[simp] lemma realize_top :
(⊤ : L.formula α).realize v ↔ true :=
bounded_formula.realize_top
@[simp] lemma realize_inf : (φ ⊓ ψ).realize v ↔ (φ.realize v ∧ ψ.realize v) :=
bounded_formula.realize_inf
@[simp] lemma realize_imp : (φ.imp ψ).realize v ↔ (φ.realize v → ψ.realize v) :=
bounded_formula.realize_imp
@[simp] lemma realize_rel {k : ℕ} {R : L.relations k} {ts : fin k → L.term α} :
(R.formula ts).realize v ↔ rel_map R (λ i, (ts i).realize v) :=
bounded_formula.realize_rel.trans (by simp)
@[simp] lemma realize_rel₁ {R : L.relations 1} {t : L.term _} :
(R.formula₁ t).realize v ↔ rel_map R ![t.realize v] :=
begin
rw [relations.formula₁, realize_rel, iff_eq_eq],
refine congr rfl (funext (λ _, _)),
simp only [matrix.cons_val_fin_one],
end
@[simp] lemma realize_rel₂ {R : L.relations 2} {t₁ t₂ : L.term _} :
(R.formula₂ t₁ t₂).realize v ↔
rel_map R ![t₁.realize v, t₂.realize v] :=
begin
rw [relations.formula₂, realize_rel, iff_eq_eq],
refine congr rfl (funext (fin.cases _ _)),
{ simp only [matrix.cons_val_zero]},
{ simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] }
end
@[simp] lemma realize_sup : (φ ⊔ ψ).realize v ↔ (φ.realize v ∨ ψ.realize v) :=
bounded_formula.realize_sup
@[simp] lemma realize_iff : (φ.iff ψ).realize v ↔ (φ.realize v ↔ ψ.realize v) :=
bounded_formula.realize_iff
@[simp] lemma realize_relabel {φ : L.formula α} {g : α → β} {v : β → M} :
(φ.relabel g).realize v ↔ φ.realize (v ∘ g) :=
begin
rw [realize, realize, relabel, bounded_formula.realize_relabel,
iff_eq_eq, fin.cast_add_zero],
exact congr rfl (funext fin_zero_elim),
end
lemma realize_relabel_sum_inr (φ : L.formula (fin n)) {v : empty → M} {x : fin n → M} :
(bounded_formula.relabel sum.inr φ).realize v x ↔ φ.realize x :=
by rw [bounded_formula.realize_relabel, formula.realize, sum.elim_comp_inr, fin.cast_add_zero,
cast_refl, order_iso.coe_refl, function.comp.right_id,
subsingleton.elim (x ∘ (nat_add n : fin 0 → fin n)) default]
@[simp]
lemma realize_equal {t₁ t₂ : L.term α} {x : α → M} :
(t₁.equal t₂).realize x ↔ t₁.realize x = t₂.realize x :=
by simp [term.equal, realize]
@[simp]
lemma realize_graph {f : L.functions n} {x : fin n → M} {y : M} :
(formula.graph f).realize (fin.cons y x : _ → M) ↔ fun_map f x = y :=
begin
simp only [formula.graph, term.realize, realize_equal, fin.cons_zero, fin.cons_succ],
rw eq_comm,
end
end formula
@[simp] lemma Lhom.realize_on_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(ψ : L.formula α) {v : α → M} :
(φ.on_formula ψ).realize v ↔ ψ.realize v :=
φ.realize_on_bounded_formula ψ
@[simp] lemma Lhom.set_of_realize_on_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(ψ : L.formula α) :
(set_of (φ.on_formula ψ).realize : set (α → M)) = set_of ψ.realize :=
by { ext, simp }
variable (M)
/-- A sentence can be evaluated as true or false in a structure. -/
def sentence.realize (φ : L.sentence) : Prop :=
φ.realize (default : _ → M)
-- input using \|= or \vDash, but not using \models
infix (name := sentence.realize) ` ⊨ `:51 := sentence.realize
@[simp] lemma sentence.realize_not {φ : L.sentence} :
M ⊨ φ.not ↔ ¬ M ⊨ φ :=
iff.rfl
namespace formula
@[simp] lemma realize_equiv_sentence_symm_con
[L[[α]].Structure M] [(L.Lhom_with_constants α).is_expansion_on M]
(φ : L[[α]].sentence) :
(equiv_sentence.symm φ).realize (λ a, (L.con a : M)) ↔ φ.realize M :=
begin
simp only [equiv_sentence, equiv.symm_symm, equiv.coe_trans, realize,
bounded_formula.realize_relabel_equiv],
refine trans _ bounded_formula.realize_constants_vars_equiv,
congr' with (i | i),
{ refl },
{ exact i.elim }
end
@[simp] lemma realize_equiv_sentence
[L[[α]].Structure M] [(L.Lhom_with_constants α).is_expansion_on M]
(φ : L.formula α) :
(equiv_sentence φ).realize M ↔ φ.realize (λ a, (L.con a : M)) :=
by rw [← realize_equiv_sentence_symm_con M (equiv_sentence φ),
_root_.equiv.symm_apply_apply]
lemma realize_equiv_sentence_symm (φ : L[[α]].sentence) (v : α → M) :
(equiv_sentence.symm φ).realize v ↔ @sentence.realize _ M
(@language.with_constants_Structure L M _ α (constants_on.Structure v)) φ :=
begin
letI := constants_on.Structure v,
exact realize_equiv_sentence_symm_con M φ,
end
end formula
@[simp] lemma Lhom.realize_on_sentence [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(ψ : L.sentence) :
M ⊨ φ.on_sentence ψ ↔ M ⊨ ψ :=
φ.realize_on_formula ψ
variables (L)
/-- The complete theory of a structure `M` is the set of all sentences `M` satisfies. -/
def complete_theory : L.Theory := { φ | M ⊨ φ }
variable (N)
/-- Two structures are elementarily equivalent when they satisfy the same sentences. -/
def elementarily_equivalent : Prop := L.complete_theory M = L.complete_theory N
localized "notation (name := elementarily_equivalent) A ` ≅[`:25 L `] ` B:50 :=
first_order.language.elementarily_equivalent L A B" in first_order
variables {L} {M} {N}
@[simp] lemma mem_complete_theory {φ : sentence L} : φ ∈ L.complete_theory M ↔ M ⊨ φ := iff.rfl
lemma elementarily_equivalent_iff : M ≅[L] N ↔ ∀ φ : L.sentence, M ⊨ φ ↔ N ⊨ φ :=
by simp only [elementarily_equivalent, set.ext_iff, complete_theory, set.mem_set_of_eq]
variables (M)
/-- A model of a theory is a structure in which every sentence is realized as true. -/
class Theory.model (T : L.Theory) : Prop :=
(realize_of_mem : ∀ φ ∈ T, M ⊨ φ)
-- input using \|= or \vDash, but not using \models
infix (name := Theory.model) ` ⊨ `:51 := Theory.model
variables {M} (T : L.Theory)
@[simp] lemma Theory.model_iff : M ⊨ T ↔ ∀ φ ∈ T, M ⊨ φ := ⟨λ h, h.realize_of_mem, λ h, ⟨h⟩⟩
lemma Theory.realize_sentence_of_mem [M ⊨ T] {φ : L.sentence} (h : φ ∈ T) :
M ⊨ φ :=
Theory.model.realize_of_mem φ h
@[simp] lemma Lhom.on_Theory_model [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M]
(T : L.Theory) :
M ⊨ φ.on_Theory T ↔ M ⊨ T :=
by simp [Theory.model_iff, Lhom.on_Theory]
variables {M} {T}
instance model_empty : M ⊨ (∅ : L.Theory) := ⟨λ φ hφ, (set.not_mem_empty φ hφ).elim⟩
namespace Theory
lemma model.mono {T' : L.Theory} (h : M ⊨ T') (hs : T ⊆ T') :
M ⊨ T :=
⟨λ φ hφ, T'.realize_sentence_of_mem (hs hφ)⟩
lemma model.union {T' : L.Theory} (h : M ⊨ T) (h' : M ⊨ T') :
M ⊨ T ∪ T' :=
begin
simp only [model_iff, set.mem_union] at *,
exact λ φ hφ, hφ.elim (h _) (h' _),
end
@[simp] lemma model_union_iff {T' : L.Theory} :
M ⊨ T ∪ T' ↔ M ⊨ T ∧ M ⊨ T' :=
⟨λ h, ⟨h.mono (T.subset_union_left T'), h.mono (T.subset_union_right T')⟩, λ h, h.1.union h.2⟩
lemma model_singleton_iff {φ : L.sentence} :
M ⊨ ({φ} : L.Theory) ↔ M ⊨ φ :=
by simp
theorem model_iff_subset_complete_theory :
M ⊨ T ↔ T ⊆ L.complete_theory M :=
T.model_iff
theorem complete_theory.subset [MT : M ⊨ T] : T ⊆ L.complete_theory M :=
model_iff_subset_complete_theory.1 MT
end Theory
instance model_complete_theory : M ⊨ L.complete_theory M :=
Theory.model_iff_subset_complete_theory.2 (subset_refl _)
variables (M N)
theorem realize_iff_of_model_complete_theory [N ⊨ L.complete_theory M] (φ : L.sentence) :
N ⊨ φ ↔ M ⊨ φ :=
begin
refine ⟨λ h, _, (L.complete_theory M).realize_sentence_of_mem⟩,
contrapose! h,
rw [← sentence.realize_not] at *,
exact (L.complete_theory M).realize_sentence_of_mem (mem_complete_theory.2 h)
end
variables {M N}
namespace bounded_formula
@[simp] lemma realize_alls {φ : L.bounded_formula α n} {v : α → M} :
φ.alls.realize v ↔
∀ (xs : fin n → M), (φ.realize v xs) :=
begin
induction n with n ih,
{ exact unique.forall_iff.symm },
{ simp only [alls, ih, realize],
exact ⟨λ h xs, (fin.snoc_init_self xs) ▸ h _ _, λ h xs x, h (fin.snoc xs x)⟩ }
end
@[simp] lemma realize_exs {φ : L.bounded_formula α n} {v : α → M} :
φ.exs.realize v ↔ ∃ (xs : fin n → M), (φ.realize v xs) :=
begin
induction n with n ih,
{ exact unique.exists_iff.symm },
{ simp only [bounded_formula.exs, ih, realize_ex],
split,
{ rintros ⟨xs, x, h⟩,
exact ⟨_, h⟩ },
{ rintros ⟨xs, h⟩,
rw ← fin.snoc_init_self xs at h,
exact ⟨_, _, h⟩ } }
end
@[simp] lemma realize_to_formula (φ : L.bounded_formula α n) (v : α ⊕ fin n → M) :
φ.to_formula.realize v ↔ φ.realize (v ∘ sum.inl) (v ∘ sum.inr) :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3 a8 a9 a0,
{ refl },
{ simp [bounded_formula.realize] },
{ simp [bounded_formula.realize] },
{ rw [to_formula, formula.realize, realize_imp, ← formula.realize, ih1, ← formula.realize, ih2,
realize_imp], },
{ rw [to_formula, formula.realize, realize_all, realize_all],
refine forall_congr (λ a, _),
have h := ih3 (sum.elim (v ∘ sum.inl) (snoc (v ∘ sum.inr) a)),
simp only [sum.elim_comp_inl, sum.elim_comp_inr] at h,
rw [← h, realize_relabel, formula.realize],
rcongr,
{ cases x,
{ simp },
{ refine fin.last_cases _ (λ i, _) x,
{ rw [sum.elim_inr, snoc_last, function.comp_app, sum.elim_inr, function.comp_app,
fin_sum_fin_equiv_symm_last, sum.map_inr, sum.elim_inr, function.comp_app],
exact (congr rfl (subsingleton.elim _ _)).trans (snoc_last _ _) },
{ simp only [cast_succ, function.comp_app, sum.elim_inr,
fin_sum_fin_equiv_symm_apply_cast_add, sum.map_inl, sum.elim_inl],
rw [← cast_succ, snoc_cast_succ] } } },
{ exact subsingleton.elim _ _ } }
end
end bounded_formula
namespace equiv
@[simp] lemma realize_bounded_formula (g : M ≃[L] N) (φ : L.bounded_formula α n)
{v : α → M} {xs : fin n → M} :
φ.realize (g ∘ v) (g ∘ xs) ↔ φ.realize v xs :=
begin
induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3,
{ refl },
{ simp only [bounded_formula.realize, ← sum.comp_elim, equiv.realize_term, g.injective.eq_iff] },
{ simp only [bounded_formula.realize, ← sum.comp_elim, equiv.realize_term, g.map_rel], },
{ rw [bounded_formula.realize, ih1, ih2, bounded_formula.realize] },
{ rw [bounded_formula.realize, bounded_formula.realize],
split,
{ intros h a,
have h' := h (g a),
rw [← fin.comp_snoc, ih3] at h',
exact h' },
{ intros h a,
have h' := h (g.symm a),
rw [← ih3, fin.comp_snoc, g.apply_symm_apply] at h',
exact h' }}
end
@[simp] lemma realize_formula (g : M ≃[L] N) (φ : L.formula α) {v : α → M} :
φ.realize (g ∘ v) ↔ φ.realize v :=
by rw [formula.realize, formula.realize, ← g.realize_bounded_formula φ,
iff_eq_eq, unique.eq_default (g ∘ default)]
lemma realize_sentence (g : M ≃[L] N) (φ : L.sentence) :
M ⊨ φ ↔ N ⊨ φ :=
by rw [sentence.realize, sentence.realize, ← g.realize_formula, unique.eq_default (g ∘ default)]
lemma Theory_model (g : M ≃[L] N) [M ⊨ T] : N ⊨ T :=
⟨λ φ hφ, (g.realize_sentence φ).1 (Theory.realize_sentence_of_mem T hφ)⟩
lemma elementarily_equivalent (g : M ≃[L] N) : M ≅[L] N :=
elementarily_equivalent_iff.2 g.realize_sentence
end equiv
namespace relations
open bounded_formula
variable {r : L.relations 2}
@[simp]
lemma realize_reflexive :
M ⊨ r.reflexive ↔ reflexive (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, realize_rel₂)
@[simp]
lemma realize_irreflexive :
M ⊨ r.irreflexive ↔ irreflexive (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, not_congr realize_rel₂)
@[simp]
lemma realize_symmetric :
M ⊨ r.symmetric ↔ symmetric (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, forall_congr (λ _, imp_congr realize_rel₂ realize_rel₂))
@[simp]
lemma realize_antisymmetric :
M ⊨ r.antisymmetric ↔ anti_symmetric (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, forall_congr (λ _, imp_congr realize_rel₂ (imp_congr realize_rel₂ iff.rfl)))
@[simp]
lemma realize_transitive :
M ⊨ r.transitive ↔ transitive (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, forall_congr (λ _, forall_congr
(λ _, imp_congr realize_rel₂ (imp_congr realize_rel₂ realize_rel₂))))
@[simp]
lemma realize_total :
M ⊨ r.total ↔ total (λ (x y : M), rel_map r ![x,y]) :=
forall_congr (λ _, forall_congr (λ _, realize_sup.trans (or_congr realize_rel₂ realize_rel₂)))
end relations
section cardinality
variable (L)
@[simp] lemma sentence.realize_card_ge (n) : M ⊨ (sentence.card_ge L n) ↔ ↑n ≤ (# M) :=
begin
rw [← lift_mk_fin, ← lift_le, lift_lift, lift_mk_le, sentence.card_ge, sentence.realize,
bounded_formula.realize_exs],
simp_rw [bounded_formula.realize_foldr_inf],
simp only [function.comp_app, list.mem_map, prod.exists, ne.def, list.mem_product,
list.mem_fin_range, forall_exists_index, and_imp, list.mem_filter, true_and],
refine ⟨_, λ xs, ⟨xs.some, _⟩⟩,
{ rintro ⟨xs, h⟩,
refine ⟨⟨xs, λ i j ij, _⟩⟩,
contrapose! ij,
have hij := h _ i j ij rfl,
simp only [bounded_formula.realize_not, term.realize, bounded_formula.realize_bd_equal,
sum.elim_inr] at hij,
exact hij },
{ rintro _ i j ij rfl,
simp [ij] }
end
@[simp] lemma model_infinite_theory_iff : M ⊨ L.infinite_theory ↔ infinite M :=
by simp [infinite_theory, infinite_iff, aleph_0_le]
instance model_infinite_theory [h : infinite M] :
M ⊨ L.infinite_theory :=
L.model_infinite_theory_iff.2 h
@[simp] lemma model_nonempty_theory_iff :
M ⊨ L.nonempty_theory ↔ nonempty M :=
by simp only [nonempty_theory, Theory.model_iff, set.mem_singleton_iff, forall_eq,
sentence.realize_card_ge, nat.cast_one, one_le_iff_ne_zero, mk_ne_zero_iff]
instance model_nonempty [h : nonempty M] :
M ⊨ L.nonempty_theory :=
L.model_nonempty_theory_iff.2 h
lemma model_distinct_constants_theory {M : Type w} [L[[α]].Structure M] (s : set α) :
M ⊨ L.distinct_constants_theory s ↔ set.inj_on (λ (i : α), (L.con i : M)) s :=
begin
simp only [distinct_constants_theory, Theory.model_iff, set.mem_image,
set.mem_inter, set.mem_prod, set.mem_compl, prod.exists, forall_exists_index, and_imp],
refine ⟨λ h a as b bs ab, _, _⟩,
{ contrapose! ab,
have h' := h _ a b ⟨⟨as, bs⟩, ab⟩ rfl,
simp only [sentence.realize, formula.realize_not, formula.realize_equal,
term.realize_constants] at h',
exact h', },
{ rintros h φ a b ⟨⟨as, bs⟩, ab⟩ rfl,
simp only [sentence.realize, formula.realize_not, formula.realize_equal,
term.realize_constants],
exact λ contra, ab (h as bs contra) }
end
lemma card_le_of_model_distinct_constants_theory (s : set α) (M : Type w) [L[[α]].Structure M]
[h : M ⊨ L.distinct_constants_theory s] :
cardinal.lift.{w} (# s) ≤ cardinal.lift.{u'} (# M) :=
lift_mk_le'.2 ⟨⟨_, set.inj_on_iff_injective.1 ((L.model_distinct_constants_theory s).1 h)⟩⟩
end cardinality
namespace elementarily_equivalent
@[symm] lemma symm (h : M ≅[L] N) : N ≅[L] M := h.symm
@[trans] lemma trans (MN : M ≅[L] N) (NP : N ≅[L] P) : M ≅[L] P := MN.trans NP
lemma complete_theory_eq (h : M ≅[L] N) : L.complete_theory M = L.complete_theory N := h
lemma realize_sentence (h : M ≅[L] N) (φ : L.sentence) : M ⊨ φ ↔ N ⊨ φ :=
(elementarily_equivalent_iff.1 h) φ
lemma Theory_model_iff (h : M ≅[L] N) : M ⊨ T ↔ N ⊨ T :=
by rw [Theory.model_iff_subset_complete_theory, Theory.model_iff_subset_complete_theory,
h.complete_theory_eq]
lemma Theory_model [MT : M ⊨ T] (h : M ≅[L] N) : N ⊨ T :=
h.Theory_model_iff.1 MT
lemma nonempty_iff (h : M ≅[L] N) : nonempty M ↔ nonempty N :=
(model_nonempty_theory_iff L).symm.trans (h.Theory_model_iff.trans (model_nonempty_theory_iff L))
lemma nonempty [Mn : nonempty M] (h : M ≅[L] N) : nonempty N := h.nonempty_iff.1 Mn
lemma infinite_iff (h : M ≅[L] N) : infinite M ↔ infinite N :=
(model_infinite_theory_iff L).symm.trans (h.Theory_model_iff.trans (model_infinite_theory_iff L))
lemma infinite [Mi : infinite M] (h : M ≅[L] N) : infinite N := h.infinite_iff.1 Mi
end elementarily_equivalent
end language
end first_order
|
19ea9d7de903fe583eb45dfe6e417c3bf9ddc551 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /library/standard/nat.lean | c6fcd3df24149a1f3bfab9e9e75bc04fa2f08e8c | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 50,117 | lean | ----------------------------------------------------------------------------------------------------
-- Copyright (c) 2014 Floris van Doorn. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Floris van Doorn
----------------------------------------------------------------------------------------------------
import logic num tactic decidable binary
using tactic num binary eq_proofs
using decidable (hiding induction_on rec_on)
namespace nat
inductive nat : Type :=
| zero : nat
| succ : nat → nat
notation `ℕ`:max := nat
abbreviation plus (x y : ℕ) : ℕ
:= nat_rec x (λ n r, succ r) y
definition to_nat [coercion] [inline] (n : num) : ℕ
:= num_rec zero (λ n, pos_num_rec (succ zero) (λ n r, plus r (plus r (succ zero))) (λ n r, plus r r) n) n
namespace helper_tactics
definition apply_refl := apply @refl
tactic_hint apply_refl
end
using helper_tactics
theorem nat_rec_zero {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) : nat_rec x f 0 = x
theorem nat_rec_succ {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) (n : ℕ) : nat_rec x f (succ n) = f n (nat_rec x f n)
theorem induction_on {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : ∀ (n : ℕ) (IH : P n), P (succ n)) : P a
:= nat_rec H1 H2 a
definition rec_on {P : ℕ → Type} (n : ℕ) (H1 : P 0) (H2 : ∀m, P m → P (succ m)) : P n
:= nat_rec H1 H2 n
-------------------------------------------------- succ pred
theorem succ_ne_zero (n : ℕ) : succ n ≠ 0
:= assume H : succ n = 0,
have H2 : true = false, from
let f [inline] := (nat_rec false (fun a b, true)) in
calc true = f (succ n) : _
... = f 0 : {H}
... = false : _,
absurd H2 true_ne_false
definition pred (n : ℕ) := nat_rec 0 (fun m x, m) n
theorem pred_zero : pred 0 = 0
theorem pred_succ (n : ℕ) : pred (succ n) = n
theorem zero_or_succ (n : ℕ) : n = 0 ∨ n = succ (pred n)
:= induction_on n
(or_inl (refl 0))
(take m IH, or_inr
(show succ m = succ (pred (succ m)), from congr2 succ (pred_succ m⁻¹)))
theorem zero_or_succ2 (n : ℕ) : n = 0 ∨ ∃k, n = succ k
:= or_imp_or (zero_or_succ n) (assume H, H) (assume H : n = succ (pred n), exists_intro (pred n) H)
theorem case {P : ℕ → Prop} (n : ℕ) (H1: P 0) (H2 : ∀m, P (succ m)) : P n
:= induction_on n H1 (take m IH, H2 m)
theorem discriminate {B : Prop} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B
:= or_elim (zero_or_succ n)
(take H3 : n = 0, H1 H3)
(take H3 : n = succ (pred n), H2 (pred n) H3)
theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m
:= calc
n = pred (succ n) : pred_succ n⁻¹
... = pred (succ m) : {H}
... = m : pred_succ m
theorem succ_ne_self (n : ℕ) : succ n ≠ n
:= induction_on n
(take H : 1 = 0,
have ne : 1 ≠ 0, from succ_ne_zero 0,
absurd H ne)
(take k IH H, IH (succ_inj H))
theorem decidable_eq [instance] (n m : ℕ) : decidable (n = m)
:= have general : ∀n, decidable (n = m), from
rec_on m
(take n,
rec_on n
(inl (refl 0))
(λ m iH, inr (succ_ne_zero m)))
(λ (m' : ℕ) (iH1 : ∀n, decidable (n = m')),
take n, rec_on n
(inr (ne_symm (succ_ne_zero m')))
(λ (n' : ℕ) (iH2 : decidable (n' = succ m')),
have d1 : decidable (n' = m'), from iH1 n',
decidable.rec_on d1
(assume Heq : n' = m', inl (congr2 succ Heq))
(assume Hne : n' ≠ m',
have H1 : succ n' ≠ succ m', from
assume Heq, absurd (succ_inj Heq) Hne,
inr H1))),
general n
theorem two_step_induction_on {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a
:= have stronger : P a ∧ P (succ a), from
induction_on a
(and_intro H1 H2)
(take k IH,
have IH1 : P k, from and_elim_left IH,
have IH2 : P (succ k), from and_elim_right IH,
and_intro IH2 (H3 k IH1 IH2)),
and_elim_left stronger
theorem sub_induction {P : ℕ → ℕ → Prop} (n m : ℕ) (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : P n m
:= have general : ∀m, P n m, from induction_on n
(take m : ℕ, H1 m)
(take k : ℕ,
assume IH : ∀m, P k m,
take m : ℕ,
discriminate
(assume Hm : m = 0,
Hm⁻¹ ▸ (H2 k))
(take l : ℕ,
assume Hm : m = succ l,
Hm⁻¹ ▸ (H3 k l (IH l)))),
general m
-------------------------------------------------- add
definition add (x y : ℕ) : ℕ := plus x y
infixl `+`:65 := add
theorem add_zero_right (n : ℕ) : n + 0 = n
theorem add_succ_right (n m : ℕ) : n + succ m = succ (n + m)
opaque_hint (hiding add)
---------- comm, assoc
theorem add_zero_left (n : ℕ) : 0 + n = n
:= induction_on n
(add_zero_right 0)
(take m IH, show 0 + succ m = succ m, from
calc
0 + succ m = succ (0 + m) : add_succ_right _ _
... = succ m : {IH})
theorem add_succ_left (n m : ℕ) : (succ n) + m = succ (n + m)
:= induction_on m
(calc
succ n + 0 = succ n : add_zero_right (succ n)
... = succ (n + 0) : {symm (add_zero_right n)})
(take k IH,
calc
succ n + succ k = succ (succ n + k) : add_succ_right _ _
... = succ (succ (n + k)) : {IH}
... = succ (n + succ k) : {symm (add_succ_right _ _)})
theorem add_comm (n m : ℕ) : n + m = m + n
:= induction_on m
(trans (add_zero_right _) (symm (add_zero_left _)))
(take k IH,
calc
n + succ k = succ (n+k) : add_succ_right _ _
... = succ (k + n) : {IH}
... = succ k + n : symm (add_succ_left _ _))
theorem add_move_succ (n m : ℕ) : succ n + m = n + succ m
:= calc
succ n + m = succ (n + m) : add_succ_left n m
... = n +succ m : symm (add_succ_right n m)
theorem add_comm_succ (n m : ℕ) : n + succ m = m + succ n
:= calc
n + succ m = succ n + m : symm (add_move_succ n m)
... = m + succ n : add_comm (succ n) m
theorem add_assoc (n m k : ℕ) : (n + m) + k = n + (m + k)
:= induction_on k
(calc
(n + m) + 0 = n + m : add_zero_right _
... = n + (m + 0) : {symm (add_zero_right m)})
(take l IH,
calc
(n + m) + succ l = succ ((n + m) + l) : add_succ_right _ _
... = succ (n + (m + l)) : {IH}
... = n + succ (m + l) : symm (add_succ_right _ _)
... = n + (m + succ l) : {symm (add_succ_right _ _)})
theorem add_left_comm (n m k : ℕ) : n + (m + k) = m + (n + k)
:= left_comm add_comm add_assoc n m k
theorem add_right_comm (n m k : ℕ) : n + m + k = n + k + m
:= right_comm add_comm add_assoc n m k
---------- inversion
theorem add_cancel_left {n m k : ℕ} : n + m = n + k → m = k
:=
induction_on n
(take H : 0 + m = 0 + k,
calc
m = 0 + m : symm (add_zero_left m)
... = 0 + k : H
... = k : add_zero_left k)
(take (n : ℕ) (IH : n + m = n + k → m = k) (H : succ n + m = succ n + k),
have H2 : succ (n + m) = succ (n + k),
from calc
succ (n + m) = succ n + m : symm (add_succ_left n m)
... = succ n + k : H
... = succ (n + k) : add_succ_left n k,
have H3 : n + m = n + k, from succ_inj H2,
IH H3)
--rename to and_cancel_right
theorem add_cancel_right {n m k : ℕ} (H : n + m = k + m) : n = k
:=
have H2 : m + n = m + k,
from calc
m + n = n + m : add_comm m n
... = k + m : H
... = m + k : add_comm k m,
add_cancel_left H2
theorem add_eq_zero_left {n m : ℕ} : n + m = 0 → n = 0
:=
induction_on n
(take (H : 0 + m = 0), refl 0)
(take k IH,
assume (H : succ k + m = 0),
absurd_elim (succ k = 0)
(show succ (k + m) = 0, from
calc
succ (k + m) = succ k + m : symm (add_succ_left k m)
... = 0 : H)
(succ_ne_zero (k + m)))
theorem add_eq_zero_right {n m : ℕ} (H : n + m = 0) : m = 0
:= add_eq_zero_left (trans (add_comm m n) H)
theorem add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0
:= and_intro (add_eq_zero_left H) (add_eq_zero_right H)
-- add_eq_self below
---------- misc
theorem add_one (n:ℕ) : n + 1 = succ n
:=
calc
n + 1 = succ (n + 0) : add_succ_right _ _
... = succ n : {add_zero_right _}
theorem add_one_left (n:ℕ) : 1 + n = succ n
:=
calc
1 + n = succ (0 + n) : add_succ_left _ _
... = succ n : {add_zero_left _}
--the following theorem has a terrible name, but since the name is not a substring or superstring of another name, it is at least easy to globally replace it
theorem induction_plus_one {P : ℕ → Prop} (a : ℕ) (H1 : P 0)
(H2 : ∀ (n : ℕ) (IH : P n), P (n + 1)) : P a
:= nat_rec H1 (take n IH, (add_one n) ▸ (H2 n IH)) a
-------------------------------------------------- mul
definition mul (n m : ℕ) := nat_rec 0 (fun m x, x + n) m
infixl `*`:75 := mul
theorem mul_zero_right (n:ℕ) : n * 0 = 0
theorem mul_succ_right (n m:ℕ) : n * succ m = n * m + n
opaque_hint (hiding mul)
---------- comm, distr, assoc, identity
theorem mul_zero_left (n:ℕ) : 0 * n = 0
:= induction_on n
(mul_zero_right 0)
(take m IH,
calc
0 * succ m = 0 * m + 0 : mul_succ_right _ _
... = 0 * m : add_zero_right _
... = 0 : IH)
theorem mul_succ_left (n m:ℕ) : (succ n) * m = (n * m) + m
:= induction_on m
(calc
succ n * 0 = 0 : mul_zero_right _
... = n * 0 : symm (mul_zero_right _)
... = n * 0 + 0 : symm (add_zero_right _))
(take k IH,
calc
succ n * succ k = (succ n * k) + succ n : mul_succ_right _ _
... = (n * k) + k + succ n : { IH }
... = (n * k) + (k + succ n) : add_assoc _ _ _
... = (n * k) + (n + succ k) : {add_comm_succ _ _}
... = (n * k) + n + succ k : symm (add_assoc _ _ _)
... = (n * succ k) + succ k : {symm (mul_succ_right n k)})
theorem mul_comm (n m:ℕ) : n * m = m * n
:= induction_on m
(trans (mul_zero_right _) (symm (mul_zero_left _)))
(take k IH,
calc
n * succ k = n * k + n : mul_succ_right _ _
... = k * n + n : {IH}
... = (succ k) * n : symm (mul_succ_left _ _))
theorem mul_add_distr_left (n m k : ℕ) : (n + m) * k = n * k + m * k
:= induction_on k
(calc
(n + m) * 0 = 0 : mul_zero_right _
... = 0 + 0 : symm (add_zero_right _)
... = n * 0 + 0 : {symm (mul_zero_right _)}
... = n * 0 + m * 0 : {symm (mul_zero_right _)})
(take l IH, calc
(n + m) * succ l = (n + m) * l + (n + m) : mul_succ_right _ _
... = n * l + m * l + (n + m) : {IH}
... = n * l + m * l + n + m : symm (add_assoc _ _ _)
... = n * l + n + m * l + m : {add_right_comm _ _ _}
... = n * l + n + (m * l + m) : add_assoc _ _ _
... = n * succ l + (m * l + m) : {symm (mul_succ_right _ _)}
... = n * succ l + m * succ l : {symm (mul_succ_right _ _)})
theorem mul_add_distr_right (n m k : ℕ) : n * (m + k) = n * m + n * k
:= calc
n * (m + k) = (m + k) * n : mul_comm _ _
... = m * n + k * n : mul_add_distr_left _ _ _
... = n * m + k * n : {mul_comm _ _}
... = n * m + n * k : {mul_comm _ _}
theorem mul_assoc (n m k:ℕ) : (n * m) * k = n * (m * k)
:= induction_on k
(calc
(n * m) * 0 = 0 : mul_zero_right _
... = n * 0 : symm (mul_zero_right _)
... = n * (m * 0) : {symm (mul_zero_right _)})
(take l IH,
calc
(n * m) * succ l = (n * m) * l + n * m : mul_succ_right _ _
... = n * (m * l) + n * m : {IH}
... = n * (m * l + m) : symm (mul_add_distr_right _ _ _)
... = n * (m * succ l) : {symm (mul_succ_right _ _)})
theorem mul_comm_left (n m k : ℕ) : n * (m * k) = m * (n * k)
:= left_comm mul_comm mul_assoc n m k
theorem mul_comm_right (n m k : ℕ) : n * m * k = n * k * m
:= right_comm mul_comm mul_assoc n m k
theorem mul_one_right (n : ℕ) : n * 1 = n
:= calc
n * 1 = n * 0 + n : mul_succ_right n 0
... = 0 + n : {mul_zero_right n}
... = n : add_zero_left n
theorem mul_one_left (n : ℕ) : 1 * n = n
:= calc
1 * n = n * 1 : mul_comm _ _
... = n : mul_one_right n
---------- inversion
theorem mul_eq_zero {n m : ℕ} (H : n * m = 0) : n = 0 ∨ m = 0
:=
discriminate
(take Hn : n = 0, or_inl Hn)
(take (k : ℕ),
assume (Hk : n = succ k),
discriminate
(take (Hm : m = 0), or_inr Hm)
(take (l : ℕ),
assume (Hl : m = succ l),
have Heq : succ (k * succ l + l) = n * m, from
symm (calc
n * m = n * succ l : { Hl }
... = succ k * succ l : { Hk }
... = k * succ l + succ l : mul_succ_left _ _
... = succ (k * succ l + l) : add_succ_right _ _),
absurd_elim _ (trans Heq H) (succ_ne_zero _)))
-- see more under "positivity" below
-------------------------------------------------- le
definition le (n m:ℕ) : Prop := ∃k, n + k = m
infix `<=`:50 := le
infix `≤`:50 := le
theorem le_intro {n m k : ℕ} (H : n + k = m) : n ≤ m
:= exists_intro k H
theorem le_elim {n m : ℕ} (H : n ≤ m) : ∃ k, n + k = m
:= H
opaque_hint (hiding le)
---------- partial order (totality is part of lt)
theorem le_intro2 (n m : ℕ) : n ≤ n + m
:= le_intro (refl (n + m))
theorem le_refl (n : ℕ) : n ≤ n
:= le_intro (add_zero_right n)
theorem zero_le (n : ℕ) : 0 ≤ n
:= le_intro (add_zero_left n)
theorem le_zero {n : ℕ} (H : n ≤ 0) : n = 0
:=
obtain (k : ℕ) (Hk : n + k = 0), from le_elim H,
add_eq_zero_left Hk
theorem not_succ_zero_le (n : ℕ) : ¬ succ n ≤ 0
:= assume H : succ n ≤ 0,
have H2 : succ n = 0, from le_zero H,
absurd H2 (succ_ne_zero n)
theorem le_zero_inv {n : ℕ} (H : n ≤ 0) : n = 0
:= obtain (k : ℕ) (Hk : n + k = 0), from le_elim H,
add_eq_zero_left Hk
theorem le_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k
:= obtain (l1 : ℕ) (Hl1 : n + l1 = m), from le_elim H1,
obtain (l2 : ℕ) (Hl2 : m + l2 = k), from le_elim H2,
le_intro
(calc
n + (l1 + l2) = n + l1 + l2 : symm (add_assoc n l1 l2)
... = m + l2 : { Hl1 }
... = k : Hl2)
theorem le_antisym {n m : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m
:= obtain (k : ℕ) (Hk : n + k = m), from (le_elim H1),
obtain (l : ℕ) (Hl : m + l = n), from (le_elim H2),
have L1 : k + l = 0, from
add_cancel_left
(calc
n + (k + l) = n + k + l : { symm (add_assoc n k l) }
... = m + l : { Hk }
... = n : Hl
... = n + 0 : symm (add_zero_right n)),
have L2 : k = 0, from add_eq_zero_left L1,
calc
n = n + 0 : symm (add_zero_right n)
... = n + k : { symm L2 }
... = m : Hk
---------- interaction with add
theorem add_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m
:= obtain (l : ℕ) (Hl : n + l = m), from (le_elim H),
le_intro
(calc
k + n + l = k + (n + l) : add_assoc k n l
... = k + m : { Hl })
theorem add_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k
:= (add_comm k m) ▸ (add_comm k n) ▸ (add_le_left H k)
theorem add_le {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n + m ≤ k + l
:= le_trans (add_le_right H1 m) (add_le_left H2 k)
theorem add_le_left_inv {n m k : ℕ} (H : k + n ≤ k + m) : n ≤ m
:=
obtain (l : ℕ) (Hl : k + n + l = k + m), from (le_elim H),
le_intro (add_cancel_left
(calc
k + (n + l) = k + n + l : symm (add_assoc k n l)
... = k + m : Hl))
theorem add_le_right_inv {n m k : ℕ} (H : n + k ≤ m + k) : n ≤ m
:= add_le_left_inv (add_comm m k ▸ add_comm n k ▸ H)
---------- interaction with succ and pred
theorem succ_le {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m
:= add_one m ▸ add_one n ▸ add_le_right H 1
theorem succ_le_cancel {n m : ℕ} (H : succ n ≤ succ m) : n ≤ m
:= add_le_right_inv (add_one m⁻¹ ▸ add_one n⁻¹ ▸ H)
theorem self_le_succ (n : ℕ) : n ≤ succ n
:= le_intro (add_one n)
theorem le_imp_le_succ {n m : ℕ} (H : n ≤ m) : n ≤ succ m
:= le_trans H (self_le_succ m)
theorem succ_le_left_or {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m
:= obtain (k : ℕ) (Hk : n + k = m), from (le_elim H),
discriminate
(assume H3 : k = 0,
have Heq : n = m,
from calc
n = n + 0 : (add_zero_right n)⁻¹
... = n + k : {H3⁻¹}
... = m : Hk,
or_inr Heq)
(take l:ℕ,
assume H3 : k = succ l,
have Hlt : succ n ≤ m, from
(le_intro
(calc
succ n + l = n + succ l : add_move_succ n l
... = n + k : {H3⁻¹}
... = m : Hk)),
or_inl Hlt)
theorem succ_le_left {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m
:= resolve_left (succ_le_left_or H1) H2
theorem succ_le_right_inv {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m
:= or_imp_or (succ_le_left_or H)
(take H2 : succ n ≤ succ m, show n ≤ m, from succ_le_cancel H2)
(take H2 : n = succ m, H2)
theorem succ_le_left_inv {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m
:= obtain (k : ℕ) (H2 : succ n + k = m), from (le_elim H),
and_intro
(have H3 : n + succ k = m,
from calc
n + succ k = succ n + k : symm (add_move_succ n k)
... = m : H2,
show n ≤ m, from le_intro H3)
(assume H3 : n = m,
have H4 : succ n ≤ n, from subst (symm H3) H,
have H5 : succ n = n, from le_antisym H4 (self_le_succ n),
show false, from absurd H5 (succ_ne_self n))
theorem le_pred_self (n : ℕ) : pred n ≤ n
:= case n
(subst (symm pred_zero) (le_refl 0))
(take k : ℕ, subst (symm (pred_succ k)) (self_le_succ k))
theorem pred_le {n m : ℕ} (H : n ≤ m) : pred n ≤ pred m
:= discriminate
(take Hn : n = 0,
have H2 : pred n = 0,
from calc
pred n = pred 0 : {Hn}
... = 0 : pred_zero,
subst (symm H2) (zero_le (pred m)))
(take k : ℕ,
assume Hn : n = succ k,
obtain (l : ℕ) (Hl : n + l = m), from le_elim H,
have H2 : pred n + l = pred m,
from calc
pred n + l = pred (succ k) + l : {Hn}
... = k + l : {pred_succ k}
... = pred (succ (k + l)) : symm (pred_succ (k + l))
... = pred (succ k + l) : {symm (add_succ_left k l)}
... = pred (n + l) : {symm Hn}
... = pred m : {Hl},
le_intro H2)
theorem pred_le_left_inv {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m
:= discriminate
(take Hn : n = 0,
or_inl (subst (symm Hn) (zero_le m)))
(take k : ℕ,
assume Hn : n = succ k,
have H2 : pred n = k,
from calc
pred n = pred (succ k) : {Hn}
... = k : pred_succ k,
have H3 : k ≤ m, from subst H2 H,
have H4 : succ k ≤ m ∨ k = m, from succ_le_left_or H3,
show n ≤ m ∨ n = succ m, from
or_imp_or H4
(take H5 : succ k ≤ m, show n ≤ m, from subst (symm Hn) H5)
(take H5 : k = m, show n = succ m, from subst H5 Hn))
-- ### interaction with successor and predecessor
theorem le_imp_succ_le_or_eq {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m
:=
obtain (k : ℕ) (Hk : n + k = m), from (le_elim H),
discriminate
(assume H3 : k = 0,
have Heq : n = m,
from calc
n = n + 0 : symm (add_zero_right n)
... = n + k : {symm H3}
... = m : Hk,
or_inr Heq)
(take l : nat,
assume H3 : k = succ l,
have Hlt : succ n ≤ m, from
(le_intro
(calc
succ n + l = n + succ l : add_move_succ n l
... = n + k : {symm H3}
... = m : Hk)),
or_inl Hlt)
theorem le_ne_imp_succ_le {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m
:= resolve_left (le_imp_succ_le_or_eq H1) H2
theorem le_succ_imp_le_or_eq {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m
:= imp_or_left (le_imp_succ_le_or_eq H)
(take H2 : succ n ≤ succ m, show n ≤ m, from succ_le_cancel H2)
theorem succ_le_imp_le_and_ne {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m
:=
and_intro
(le_trans (self_le_succ n) H)
(assume H2 : n = m,
have H3 : succ n ≤ n, from subst (symm H2) H,
have H4 : succ n = n, from le_antisym H3 (self_le_succ n),
show false, from absurd H4 (succ_ne_self n))
theorem pred_le_self (n : ℕ) : pred n ≤ n
:=
case n
(subst (symm pred_zero) (le_refl 0))
(take k : nat, subst (symm (pred_succ k)) (self_le_succ k))
theorem pred_le_imp_le_or_eq {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m
:=
discriminate
(take Hn : n = 0,
or_inl (subst (symm Hn) (zero_le m)))
(take k : nat,
assume Hn : n = succ k,
have H2 : pred n = k,
from calc
pred n = pred (succ k) : {Hn}
... = k : pred_succ k,
have H3 : k ≤ m, from subst H2 H,
have H4 : succ k ≤ m ∨ k = m, from le_imp_succ_le_or_eq H3,
show n ≤ m ∨ n = succ m, from
or_imp_or H4
(take H5 : succ k ≤ m, show n ≤ m, from subst (symm Hn) H5)
(take H5 : k = m, show n = succ m, from subst H5 Hn))
---------- interaction with mul
theorem mul_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k * n ≤ k * m
:=
obtain (l : ℕ) (Hl : n + l = m), from (le_elim H),
induction_on k
(have H2 : 0 * n = 0 * m,
from calc
0 * n = 0 : mul_zero_left n
... = 0 * m : symm (mul_zero_left m),
show 0 * n ≤ 0 * m, from subst H2 (le_refl (0 * n)))
(take (l : ℕ),
assume IH : l * n ≤ l * m,
have H2 : l * n + n ≤ l * m + m, from add_le IH H,
have H3 : succ l * n ≤ l * m + m, from subst (symm (mul_succ_left l n)) H2,
show succ l * n ≤ succ l * m, from subst (symm (mul_succ_left l m)) H3)
theorem mul_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n * k ≤ m * k
:= mul_comm k m ▸ mul_comm k n ▸ (mul_le_left H k)
theorem mul_le {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l
:= le_trans (mul_le_right H1 m) (mul_le_left H2 k)
-- mul_le_[left|right]_inv below
-------------------------------------------------- lt
definition lt (n m : ℕ) := succ n ≤ m
infix `<`:50 := lt
theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m
:= le_intro H
theorem lt_elim {n m : ℕ} (H : n < m) : ∃ k, succ n + k = m
:= le_elim H
theorem lt_intro2 (n m : ℕ) : n < n + succ m
:= lt_intro (add_move_succ n m)
-------------------------------------------------- ge, gt
definition ge (n m : ℕ) := m ≤ n
infix `>=`:50 := ge
infix `≥`:50 := ge
definition gt (n m : ℕ) := m < n
infix `>`:50 := gt
---------- basic facts
theorem lt_ne {n m : ℕ} (H : n < m) : n ≠ m
:= and_elim_right (succ_le_left_inv H)
theorem lt_irrefl (n : ℕ) : ¬ n < n
:= assume H : n < n, absurd (refl n) (lt_ne H)
theorem lt_zero (n : ℕ) : 0 < succ n
:= succ_le (zero_le n)
theorem lt_zero_inv (n : ℕ) : ¬ n < 0
:= assume H : n < 0,
have H2 : succ n = 0, from le_zero_inv H,
absurd H2 (succ_ne_zero n)
theorem lt_positive {n m : ℕ} (H : n < m) : ∃k, m = succ k
:= discriminate
(take (Hm : m = 0), absurd_elim _ (subst Hm H) (lt_zero_inv n))
(take (l : ℕ) (Hm : m = succ l), exists_intro l Hm)
---------- interaction with le
theorem lt_imp_le_succ {n m : ℕ} (H : n < m) : succ n ≤ m
:= H
theorem le_succ_imp_lt {n m : ℕ} (H : succ n ≤ m) : n < m
:= H
theorem self_lt_succ (n : ℕ) : n < succ n
:= le_refl (succ n)
theorem lt_imp_le {n m : ℕ} (H : n < m) : n ≤ m
:= and_elim_left (succ_le_imp_le_and_ne H)
theorem le_imp_lt_or_eq {n m : ℕ} (H : n ≤ m) : n < m ∨ n = m
:= le_imp_succ_le_or_eq H
theorem le_ne_imp_lt {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : n < m
:= le_ne_imp_succ_le H1 H2
theorem le_imp_lt_succ {n m : ℕ} (H : n ≤ m) : n < succ m
:= succ_le H
theorem lt_succ_imp_le {n m : ℕ} (H : n < succ m) : n ≤ m
:= succ_le_cancel H
---------- trans, antisym
theorem lt_le_trans {n m k : ℕ} (H1 : n < m) (H2 : m ≤ k) : n < k
:= le_trans H1 H2
theorem le_lt_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m < k) : n < k
:= le_trans (succ_le H1) H2
theorem lt_trans {n m k : ℕ} (H1 : n < m) (H2 : m < k) : n < k
:= lt_le_trans H1 (lt_imp_le H2)
theorem le_imp_not_gt {n m : ℕ} (H : n ≤ m) : ¬ n > m
:= assume H2 : m < n, absurd (le_lt_trans H H2) (lt_irrefl n)
theorem lt_imp_not_ge {n m : ℕ} (H : n < m) : ¬ n ≥ m
:= assume H2 : m ≤ n, absurd (lt_le_trans H H2) (lt_irrefl n)
theorem lt_antisym {n m : ℕ} (H : n < m) : ¬ m < n
:= le_imp_not_gt (lt_imp_le H)
---------- interaction with add
theorem add_lt_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m
:= add_succ_right k n ▸ add_le_left H k
theorem add_lt_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k
:= add_comm k m ▸ add_comm k n ▸ add_lt_left H k
theorem add_le_lt {n m k l : ℕ} (H1 : n ≤ k) (H2 : m < l) : n + m < k + l
:= le_lt_trans (add_le_right H1 m) (add_lt_left H2 k)
theorem add_lt_le {n m k l : ℕ} (H1 : n < k) (H2 : m ≤ l) : n + m < k + l
:= lt_le_trans (add_lt_right H1 m) (add_le_left H2 k)
theorem add_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n + m < k + l
:= add_lt_le H1 (lt_imp_le H2)
theorem add_lt_left_inv {n m k : ℕ} (H : k + n < k + m) : n < m
:= add_le_left_inv (add_succ_right k n⁻¹ ▸ H)
theorem add_lt_right_inv {n m k : ℕ} (H : n + k < m + k) : n < m
:= add_lt_left_inv (add_comm m k ▸ add_comm n k ▸ H)
---------- interaction with succ (see also the interaction with le)
theorem succ_lt {n m : ℕ} (H : n < m) : succ n < succ m
:= add_one m ▸ add_one n ▸ add_lt_right H 1
theorem succ_lt_inv {n m : ℕ} (H : succ n < succ m) : n < m
:= add_lt_right_inv (add_one m⁻¹ ▸ add_one n⁻¹ ▸ H)
theorem lt_self_succ (n : ℕ) : n < succ n
:= le_refl (succ n)
theorem succ_lt_right {n m : ℕ} (H : n < m) : n < succ m
:= lt_trans H (lt_self_succ m)
---------- totality of lt and le
theorem le_or_lt (n m : ℕ) : n ≤ m ∨ m < n
:= induction_on n
(or_inl (zero_le m))
(take (k : ℕ),
assume IH : k ≤ m ∨ m < k,
or_elim IH
(assume H : k ≤ m,
obtain (l : ℕ) (Hl : k + l = m), from le_elim H,
discriminate
(assume H2 : l = 0,
have H3 : m = k,
from calc
m = k + l : symm Hl
... = k + 0 : {H2}
... = k : add_zero_right k,
have H4 : m < succ k, from subst H3 (lt_self_succ m),
or_inr H4)
(take l2 : ℕ,
assume H2 : l = succ l2,
have H3 : succ k + l2 = m,
from calc
succ k + l2 = k + succ l2 : add_move_succ k l2
... = k + l : {symm H2}
... = m : Hl,
or_inl (le_intro H3)))
(assume H : m < k, or_inr (succ_lt_right H)))
theorem trichotomy_alt (n m : ℕ) : (n < m ∨ n = m) ∨ m < n
:= or_imp_or (le_or_lt n m) (assume H : n ≤ m, le_imp_lt_or_eq H) (assume H : m < n, H)
theorem trichotomy (n m : ℕ) : n < m ∨ n = m ∨ m < n
:= iff_elim_left (or_assoc _ _ _) (trichotomy_alt n m)
theorem le_total (n m : ℕ) : n ≤ m ∨ m ≤ n
:= or_imp_or (le_or_lt n m) (assume H : n ≤ m, H) (assume H : m < n, lt_imp_le H)
-- interaction with mul under "positivity"
theorem strong_induction_on {P : ℕ → Prop} (n : ℕ) (IH : ∀n, (∀m, m < n → P m) → P n) : P n
:= have stronger : ∀k, k ≤ n → P k, from
induction_on n
(take (k : ℕ),
assume H : k ≤ 0,
have H2 : k = 0, from le_zero_inv H,
have H3 : ∀m, m < k → P m, from
(take m : ℕ,
assume H4 : m < k,
have H5 : m < 0, from subst H2 H4,
absurd_elim _ H5 (lt_zero_inv m)),
show P k, from IH k H3)
(take l : ℕ,
assume IHl : ∀k, k ≤ l → P k,
take k : ℕ,
assume H : k ≤ succ l,
or_elim (succ_le_right_inv H)
(assume H2 : k ≤ l, show P k, from IHl k H2)
(assume H2 : k = succ l,
have H3 : ∀m, m < k → P m, from
(take m : ℕ,
assume H4 : m < k,
have H5 : m ≤ l, from lt_succ_imp_le (subst H2 H4),
show P m, from IHl m H5),
show P k, from IH k H3)),
stronger n (le_refl n)
theorem case_strong_induction_on {P : ℕ → Prop} (a : ℕ) (H0 : P 0) (Hind : ∀(n : ℕ), (∀m, m ≤ n → P m) → P (succ n)) : P a
:= strong_induction_on a
(take n, case n
(assume H : (∀m, m < 0 → P m), H0)
(take n, assume H : (∀m, m < succ n → P m),
Hind n (take m, assume H1 : m ≤ n, H m (le_imp_lt_succ H1))))
theorem add_eq_self {n m : ℕ} (H : n + m = n) : m = 0
:= discriminate
(take Hm : m = 0, Hm)
(take k : ℕ,
assume Hm : m = succ k,
have H2 : succ n + k = n,
from calc
succ n + k = n + succ k : add_move_succ n k
... = n + m : {symm Hm}
... = n : H,
have H3 : n < n, from lt_intro H2,
have H4 : n ≠ n, from lt_ne H3,
absurd_elim _ (refl n) H4)
-------------------------------------------------- positivity
-- we use " _ > 0" as canonical way of denoting that a number is positive
---------- basic
theorem zero_or_positive (n : ℕ) : n = 0 ∨ n > 0
:= or_imp_or (or_swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H) (take H : n > 0, H)
theorem succ_positive {n m : ℕ} (H : n = succ m) : n > 0
:= subst (symm H) (lt_zero m)
theorem ne_zero_positive {n : ℕ} (H : n ≠ 0) : n > 0
:= or_elim (zero_or_positive n) (take H2 : n = 0, absurd_elim _ H2 H) (take H2 : n > 0, H2)
theorem pos_imp_eq_succ {n : ℕ} (H : n > 0) : ∃l, n = succ l
:= discriminate
(take H2, absurd_elim _ (subst H2 H) (lt_irrefl 0))
(take l Hl, exists_intro l Hl)
theorem add_positive_right (n : ℕ) {k : ℕ} (H : k > 0) : n + k > n
:= obtain (l : ℕ) (Hl : k = succ l), from pos_imp_eq_succ H,
subst (symm Hl) (lt_intro2 n l)
theorem add_positive_left (n : ℕ) {k : ℕ} (H : k > 0) : k + n > n
:= subst (add_comm n k) (add_positive_right n H)
-- Positivity
-- ---------
--
-- Writing "t > 0" is the preferred way to assert that a natural number is positive.
-- ### basic
-- See also succ_pos.
theorem succ_pos (n : ℕ) : 0 < succ n
:= succ_le (zero_le n)
theorem case_zero_pos {P : ℕ → Prop} (y : ℕ) (H0 : P 0) (H1 : ∀y, y > 0 → P y) : P y
:= case y H0 (take y', H1 _ (succ_pos _))
theorem zero_or_pos (n : ℕ) : n = 0 ∨ n > 0
:= imp_or_left (or_swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H)
theorem succ_imp_pos {n m : ℕ} (H : n = succ m) : n > 0
:= subst (symm H) (succ_pos m)
theorem ne_zero_pos {n : ℕ} (H : n ≠ 0) : n > 0
:= or_elim (zero_or_pos n) (take H2 : n = 0, absurd_elim _ H2 H) (take H2 : n > 0, H2)
theorem add_pos_right (n : ℕ) {k : ℕ} (H : k > 0) : n + k > n
:= subst (add_zero_right n) (add_lt_left H n)
theorem add_pos_left (n : ℕ) {k : ℕ} (H : k > 0) : k + n > n
:= subst (add_comm n k) (add_pos_right n H)
---------- mul
theorem mul_positive {n m : ℕ} (Hn : n > 0) (Hm : m > 0) : n * m > 0
:= obtain (k : ℕ) (Hk : n = succ k), from pos_imp_eq_succ Hn,
obtain (l : ℕ) (Hl : m = succ l), from pos_imp_eq_succ Hm,
succ_positive (calc
n * m = succ k * m : {Hk}
... = succ k * succ l : {Hl}
... = succ k * l + succ k : mul_succ_right (succ k) l
... = succ (succ k * l + k) : add_succ_right _ _)
theorem mul_positive_inv_left {n m : ℕ} (H : n * m > 0) : n > 0
:= discriminate
(assume H2 : n = 0,
have H3 : n * m = 0,
from calc
n * m = 0 * m : {H2}
... = 0 : mul_zero_left m,
have H4 : 0 > 0, from subst H3 H,
absurd_elim _ H4 (lt_irrefl 0))
(take l : ℕ,
assume Hl : n = succ l,
subst (symm Hl) (lt_zero l))
theorem mul_positive_inv_right {n m : ℕ} (H : n * m > 0) : m > 0
:= mul_positive_inv_left (subst (mul_comm n m) H)
theorem mul_left_inj {n m k : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k
:=
have general : ∀m, n * m = n * k → m = k, from
induction_on k
(take m:ℕ,
assume H : n * m = n * 0,
have H2 : n * m = 0,
from calc
n * m = n * 0 : H
... = 0 : mul_zero_right n,
have H3 : n = 0 ∨ m = 0, from mul_eq_zero H2,
resolve_right H3 (ne_symm (lt_ne Hn)))
(take (l : ℕ),
assume (IH : ∀ m, n * m = n * l → m = l),
take (m : ℕ),
assume (H : n * m = n * succ l),
have H2 : n * succ l > 0, from mul_positive Hn (lt_zero l),
have H3 : m > 0, from mul_positive_inv_right (subst (symm H) H2),
obtain (l2:ℕ) (Hm : m = succ l2), from pos_imp_eq_succ H3,
have H4 : n * l2 + n = n * l + n,
from calc
n * l2 + n = n * succ l2 : symm (mul_succ_right n l2)
... = n * m : {symm Hm}
... = n * succ l : H
... = n * l + n : mul_succ_right n l,
have H5 : n * l2 = n * l, from add_cancel_right H4,
calc
m = succ l2 : Hm
... = succ l : {IH l2 H5}),
general m H
theorem mul_right_inj {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k
:= mul_left_inj Hm (subst (mul_comm k m) (subst (mul_comm n m) H))
-- mul_eq_one below
---------- interaction of mul with le and lt
theorem mul_lt_left {n m k : ℕ} (Hk : k > 0) (H : n < m) : k * n < k * m
:=
have H2 : k * n < k * n + k, from add_positive_right (k * n) Hk,
have H3 : k * n + k ≤ k * m, from subst (mul_succ_right k n) (mul_le_left H k),
lt_le_trans H2 H3
theorem mul_lt_right {n m k : ℕ} (Hk : k > 0) (H : n < m) : n * k < m * k
:= subst (mul_comm k m) (subst (mul_comm k n) (mul_lt_left Hk H))
theorem mul_le_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l
:= le_lt_trans (mul_le_right H1 m) (mul_lt_left Hk H2)
theorem mul_lt_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l
:= le_lt_trans (mul_le_left H2 n) (mul_lt_right Hl H1)
theorem mul_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l
:=
have H3 : n * m ≤ k * m, from mul_le_right (lt_imp_le H1) m,
have H4 : k * m < k * l, from mul_lt_left (le_lt_trans (zero_le n) H1) H2,
le_lt_trans H3 H4
theorem mul_lt_left_inv {n m k : ℕ} (H : k * n < k * m) : n < m
:=
have general : ∀ m, k * n < k * m → n < m, from
induction_on n
(take m : ℕ,
assume H2 : k * 0 < k * m,
have H3 : 0 < k * m, from mul_zero_right k ▸ H2,
show 0 < m, from mul_positive_inv_right H3)
(take l : ℕ,
assume IH : ∀ m, k * l < k * m → l < m,
take m : ℕ,
assume H2 : k * succ l < k * m,
have H3 : 0 < k * m, from le_lt_trans (zero_le _) H2,
have H4 : 0 < m, from mul_positive_inv_right H3,
obtain (l2 : ℕ) (Hl2 : m = succ l2), from pos_imp_eq_succ H4,
have H5 : k * l + k < k * m, from mul_succ_right k l ▸ H2,
have H6 : k * l + k < k * succ l2, from Hl2 ▸ H5,
have H7 : k * l + k < k * l2 + k, from mul_succ_right k l2 ▸ H6,
have H8 : k * l < k * l2, from add_lt_right_inv H7,
have H9 : l < l2, from IH l2 H8,
have H10 : succ l < succ l2, from succ_lt H9,
show succ l < m, from Hl2⁻¹ ▸ H10),
general m H
theorem mul_lt_right_inv {n m k : ℕ} (H : n * k < m * k) : n < m
:= mul_lt_left_inv (mul_comm m k ▸ mul_comm n k ▸ H)
theorem mul_le_left_inv {n m k : ℕ} (H : succ k * n ≤ succ k * m) : n ≤ m
:=
have H2 : succ k * n < succ k * m + succ k, from le_lt_trans H (lt_intro2 _ _),
have H3 : succ k * n < succ k * succ m, from subst (symm (mul_succ_right (succ k) m)) H2,
have H4 : n < succ m, from mul_lt_left_inv H3,
show n ≤ m, from lt_succ_imp_le H4
theorem mul_le_right_inv {n m k : ℕ} (H : n * succ m ≤ k * succ m) : n ≤ k
:= mul_le_left_inv (subst (mul_comm k (succ m)) (subst (mul_comm n (succ m)) H))
theorem mul_eq_one_left {n m : ℕ} (H : n * m = 1) : n = 1
:=
have H2 : n * m > 0, from subst (symm H) (lt_zero 0),
have H3 : n > 0, from mul_positive_inv_left H2,
have H4 : m > 0, from mul_positive_inv_right H2,
or_elim (le_or_lt n 1)
(assume H5 : n ≤ 1,
show n = 1, from le_antisym H5 H3)
(assume H5 : n > 1,
have H6 : n * m ≥ 2 * 1, from mul_le H5 H4,
have H7 : 1 ≥ 2, from subst (mul_one_right 2) (subst H H6),
absurd_elim _ (self_lt_succ 1) (le_imp_not_gt H7))
theorem mul_eq_one_right {n m : ℕ} (H : n * m = 1) : m = 1
:= mul_eq_one_left (subst (mul_comm n m) H)
theorem mul_eq_one {n m : ℕ} (H : n * m = 1) : n = 1 ∧ m = 1
:= and_intro (mul_eq_one_left H) (mul_eq_one_right H)
opaque_hint (hiding lt)
-------------------------------------------------- sub
definition sub (n m : ℕ) : ℕ := nat_rec n (fun m x, pred x) m
infixl `-`:65 := sub
theorem sub_zero_right (n : ℕ) : n - 0 = n
theorem sub_succ_right (n m : ℕ) : n - succ m = pred (n - m)
opaque_hint (hiding sub)
theorem sub_zero_left (n : ℕ) : 0 - n = 0
:= induction_on n (sub_zero_right 0)
(take k : ℕ,
assume IH : 0 - k = 0,
calc
0 - succ k = pred (0 - k) : sub_succ_right 0 k
... = pred 0 : {IH}
... = 0 : pred_zero)
theorem sub_succ_succ (n m : ℕ) : succ n - succ m = n - m
:= induction_on m
(calc
succ n - 1 = pred (succ n - 0) : sub_succ_right (succ n) 0
... = pred (succ n) : {sub_zero_right (succ n)}
... = n : pred_succ n
... = n - 0 : symm (sub_zero_right n))
(take k : ℕ,
assume IH : succ n - succ k = n - k,
calc
succ n - succ (succ k) = pred (succ n - succ k) : sub_succ_right (succ n) (succ k)
... = pred (n - k) : {IH}
... = n - succ k : symm (sub_succ_right n k))
theorem sub_one (n : ℕ) : n - 1 = pred n
:= calc
n - 1 = pred (n - 0) : sub_succ_right n 0
... = pred n : {sub_zero_right n}
theorem sub_self (n : ℕ) : n - n = 0
:= induction_on n (sub_zero_right 0) (take k IH, trans (sub_succ_succ k k) IH)
theorem sub_add_add_right (n m k : ℕ) : (n + k) - (m + k) = n - m
:= induction_on k
(calc
(n + 0) - (m + 0) = n - (m + 0) : {add_zero_right _}
... = n - m : {add_zero_right _})
(take l : ℕ,
assume IH : (n + l) - (m + l) = n - m,
calc
(n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {add_succ_right _ _}
... = succ (n + l) - succ (m + l) : {add_succ_right _ _}
... = (n + l) - (m + l) : sub_succ_succ _ _
... = n - m : IH)
theorem sub_add_add_left (n m k : ℕ) : (k + n) - (k + m) = n - m
:= subst (add_comm m k) (subst (add_comm n k) (sub_add_add_right n m k))
theorem sub_add_left (n m : ℕ) : n + m - m = n
:= induction_on m
(subst (symm (add_zero_right n)) (sub_zero_right n))
(take k : ℕ,
assume IH : n + k - k = n,
calc
n + succ k - succ k = succ (n + k) - succ k : {add_succ_right n k}
... = n + k - k : sub_succ_succ _ _
... = n : IH)
theorem sub_sub (n m k : ℕ) : n - m - k = n - (m + k)
:= induction_on k
(calc
n - m - 0 = n - m : sub_zero_right _
... = n - (m + 0) : {symm (add_zero_right m)})
(take l : ℕ,
assume IH : n - m - l = n - (m + l),
calc
n - m - succ l = pred (n - m - l) : sub_succ_right (n - m) l
... = pred (n - (m + l)) : {IH}
... = n - succ (m + l) : symm (sub_succ_right n (m + l))
... = n - (m + succ l) : {symm (add_succ_right m l)})
theorem succ_sub_sub (n m k : ℕ) : succ n - m - succ k = n - m - k
:= calc
succ n - m - succ k = succ n - (m + succ k) : sub_sub _ _ _
... = succ n - succ (m + k) : {add_succ_right m k}
... = n - (m + k) : sub_succ_succ _ _
... = n - m - k : symm (sub_sub n m k)
theorem sub_add_right_eq_zero (n m : ℕ) : n - (n + m) = 0
:= calc
n - (n + m) = n - n - m : symm (sub_sub n n m)
... = 0 - m : {sub_self n}
... = 0 : sub_zero_left m
theorem sub_comm (m n k : ℕ) : m - n - k = m - k - n
:= calc
m - n - k = m - (n + k) : sub_sub m n k
... = m - (k + n) : {add_comm n k}
... = m - k - n : symm (sub_sub m k n)
theorem succ_sub_one (n : ℕ) : succ n - 1 = n
:= sub_succ_succ n 0 ⬝ sub_zero_right n
---------- mul
theorem mul_pred_left (n m : ℕ) : pred n * m = n * m - m
:= induction_on n
(calc
pred 0 * m = 0 * m : {pred_zero}
... = 0 : mul_zero_left _
... = 0 - m : symm (sub_zero_left m)
... = 0 * m - m : {symm (mul_zero_left m)})
(take k : ℕ,
assume IH : pred k * m = k * m - m,
calc
pred (succ k) * m = k * m : {pred_succ k}
... = k * m + m - m : symm (sub_add_left _ _)
... = succ k * m - m : {symm (mul_succ_left k m)})
theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n
:= calc n * pred m = pred m * n : mul_comm _ _
... = m * n - n : mul_pred_left m n
... = n * m - n : {mul_comm m n}
theorem mul_sub_distr_left (n m k : ℕ) : (n - m) * k = n * k - m * k
:= induction_on m
(calc
(n - 0) * k = n * k : {sub_zero_right n}
... = n * k - 0 : symm (sub_zero_right _)
... = n * k - 0 * k : {symm (mul_zero_left _)})
(take l : ℕ,
assume IH : (n - l) * k = n * k - l * k,
calc
(n - succ l) * k = pred (n - l) * k : {sub_succ_right n l}
... = (n - l) * k - k : mul_pred_left _ _
... = n * k - l * k - k : {IH}
... = n * k - (l * k + k) : sub_sub _ _ _
... = n * k - (succ l * k) : {symm (mul_succ_left l k)})
theorem mul_sub_distr_right (n m k : ℕ) : n * (m - k) = n * m - n * k
:= calc
n * (m - k) = (m - k) * n : mul_comm _ _
... = m * n - k * n : mul_sub_distr_left _ _ _
... = n * m - k * n : {mul_comm _ _}
... = n * m - n * k : {mul_comm _ _}
-------------------------------------------------- max, min, iteration, maybe: sub, div
theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n)
:= sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
succ k - 0 = succ k : sub_zero_right (succ k)
... = succ (k - 0) : {symm (sub_zero_right k)})
(take k,
assume H : succ k ≤ 0,
absurd_elim _ H (not_succ_zero_le k))
(take k l,
assume IH : k ≤ l → succ l - k = succ (l - k),
take H : succ k ≤ succ l,
calc
succ (succ l) - succ k = succ l - k : sub_succ_succ (succ l) k
... = succ (l - k) : IH (succ_le_cancel H)
... = succ (succ l - succ k) : {symm (sub_succ_succ l k)})
theorem le_imp_sub_eq_zero {n m : ℕ} (H : n ≤ m) : n - m = 0
:= obtain (k : ℕ) (Hk : n + k = m), from le_elim H, subst Hk (sub_add_right_eq_zero n k)
theorem add_sub_le {n m : ℕ} : n ≤ m → n + (m - n) = m
:= sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
0 + (k - 0) = k - 0 : add_zero_left (k - 0)
... = k : sub_zero_right k)
(take k, assume H : succ k ≤ 0, absurd_elim _ H (not_succ_zero_le k))
(take k l,
assume IH : k ≤ l → k + (l - k) = l,
take H : succ k ≤ succ l,
calc
succ k + (succ l - succ k) = succ k + (l - k) : {sub_succ_succ l k}
... = succ (k + (l - k)) : add_succ_left k (l - k)
... = succ l : {IH (succ_le_cancel H)})
theorem add_sub_ge_left {n m : ℕ} : n ≥ m → n - m + m = n
:= subst (add_comm m (n - m)) add_sub_le
theorem add_sub_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n
:= calc
n + (m - n) = n + 0 : {le_imp_sub_eq_zero H}
... = n : add_zero_right n
theorem add_sub_le_left {n m : ℕ} : n ≤ m → n - m + m = m
:= subst (add_comm m (n - m)) add_sub_ge
theorem le_add_sub_left (n m : ℕ) : n ≤ n + (m - n)
:= or_elim (le_total n m)
(assume H : n ≤ m, subst (symm (add_sub_le H)) H)
(assume H : m ≤ n, subst (symm (add_sub_ge H)) (le_refl n))
theorem le_add_sub_right (n m : ℕ) : m ≤ n + (m - n)
:= or_elim (le_total n m)
(assume H : n ≤ m, subst (symm (add_sub_le H)) (le_refl m))
(assume H : m ≤ n, subst (symm (add_sub_ge H)) H)
theorem sub_split {P : ℕ → Prop} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : ∀k, m + k = n -> P k)
: P (n - m)
:= or_elim (le_total n m)
(assume H3 : n ≤ m, subst (symm (le_imp_sub_eq_zero H3)) (H1 H3))
(assume H3 : m ≤ n, H2 (n - m) (add_sub_le H3))
theorem sub_le_self (n m : ℕ) : n - m ≤ n
:=
sub_split
(assume H : n ≤ m, zero_le n)
(take k : ℕ, assume H : m + k = n, le_intro (subst (add_comm m k) H))
theorem le_elim_sub (n m : ℕ) (H : n ≤ m) : ∃k, m - k = n
:=
obtain (k : ℕ) (Hk : n + k = m), from le_elim H,
exists_intro k
(calc
m - k = n + k - k : {symm Hk}
... = n : sub_add_left n k)
theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k)
:= have l1 : k ≤ m → n + m - k = n + (m - k), from
sub_induction k m
(take m : ℕ,
assume H : 0 ≤ m,
calc
n + m - 0 = n + m : sub_zero_right (n + m)
... = n + (m - 0) : {symm (sub_zero_right m)})
(take k : ℕ, assume H : succ k ≤ 0, absurd_elim _ H (not_succ_zero_le k))
(take k m,
assume IH : k ≤ m → n + m - k = n + (m - k),
take H : succ k ≤ succ m,
calc
n + succ m - succ k = succ (n + m) - succ k : {add_succ_right n m}
... = n + m - k : sub_succ_succ (n + m) k
... = n + (m - k) : IH (succ_le_cancel H)
... = n + (succ m - succ k) : {symm (sub_succ_succ m k)}),
l1 H
theorem sub_eq_zero_imp_le {n m : ℕ} : n - m = 0 → n ≤ m
:= sub_split
(assume H1 : n ≤ m, assume H2 : 0 = 0, H1)
(take k : ℕ,
assume H1 : m + k = n,
assume H2 : k = 0,
have H3 : n = m, from subst (add_zero_right m) (subst H2 (symm H1)),
subst H3 (le_refl n))
theorem sub_sub_split {P : ℕ → ℕ → Prop} {n m : ℕ} (H1 : ∀k, n = m + k -> P k 0)
(H2 : ∀k, m = n + k → P 0 k) : P (n - m) (m - n)
:= or_elim (le_total n m)
(assume H3 : n ≤ m,
le_imp_sub_eq_zero H3⁻¹ ▸ (H2 (m - n) (add_sub_le H3⁻¹)))
(assume H3 : m ≤ n,
le_imp_sub_eq_zero H3⁻¹ ▸ (H1 (n - m) (add_sub_le H3⁻¹)))
theorem sub_intro {n m k : ℕ} (H : n + m = k) : k - n = m
:= have H2 : k - n + n = m + n, from
calc
k - n + n = k : add_sub_ge_left (le_intro H)
... = n + m : symm H
... = m + n : add_comm n m,
add_cancel_right H2
theorem sub_lt {x y : ℕ} (xpos : x > 0) (ypos : y > 0) : x - y < x
:= obtain (x' : ℕ) (xeq : x = succ x'), from pos_imp_eq_succ xpos,
obtain (y' : ℕ) (yeq : y = succ y'), from pos_imp_eq_succ ypos,
have xsuby_eq : x - y = x' - y', from
calc
x - y = succ x' - y : {xeq}
... = succ x' - succ y' : {yeq}
... = x' - y' : sub_succ_succ _ _,
have H1 : x' - y' ≤ x', from sub_le_self _ _,
have H2 : x' < succ x', from self_lt_succ _,
show x - y < x, from xeq⁻¹ ▸ xsuby_eq⁻¹ ▸ le_lt_trans H1 H2
-- Max, min, iteration, and absolute difference
-- --------------------------------------------
definition max (n m : ℕ) : ℕ := n + (m - n)
definition min (n m : ℕ) : ℕ := m - (m - n)
theorem max_le {n m : ℕ} (H : n ≤ m) : n + (m - n) = m := add_sub_le H
theorem max_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := add_sub_ge H
theorem left_le_max (n m : ℕ) : n ≤ n + (m - n) := le_add_sub_left n m
theorem right_le_max (n m : ℕ) : m ≤ max n m := le_add_sub_right n m
-- ### absolute difference
-- This section is still incomplete
definition dist (n m : ℕ) := (n - m) + (m - n)
theorem dist_comm (n m : ℕ) : dist n m = dist m n
:= add_comm (n - m) (m - n)
theorem dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m
:=
have H2 : n - m = 0, from add_eq_zero_left H,
have H3 : n ≤ m, from sub_eq_zero_imp_le H2,
have H4 : m - n = 0, from add_eq_zero_right H,
have H5 : m ≤ n, from sub_eq_zero_imp_le H4,
le_antisym H3 H5
theorem dist_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n
:= calc
dist n m = (n - m) + (m - n) : refl _
... = 0 + (m - n) : {le_imp_sub_eq_zero H}
... = m - n : add_zero_left (m - n)
theorem dist_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m
:= subst (dist_comm m n) (dist_le H)
theorem dist_zero_right (n : ℕ) : dist n 0 = n
:= trans (dist_ge (zero_le n)) (sub_zero_right n)
theorem dist_zero_left (n : ℕ) : dist 0 n = n
:= trans (dist_le (zero_le n)) (sub_zero_right n)
theorem dist_intro {n m k : ℕ} (H : n + m = k) : dist k n = m
:= calc
dist k n = k - n : dist_ge (le_intro H)
... = m : sub_intro H
theorem dist_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m
:=
calc
dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : refl _
... = (n - m) + ((m + k) - (n + k)) : {sub_add_add_right _ _ _}
... = (n - m) + (m - n) : {sub_add_add_right _ _ _}
theorem dist_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m
:= subst (add_comm m k) (subst (add_comm n k) (dist_add_right n k m))
theorem dist_ge_add_right {n m : ℕ} (H : n ≥ m) : dist n m + m = n
:= calc
dist n m + m = n - m + m : {dist_ge H}
... = n : add_sub_ge_left H
theorem dist_eq_intro {n m k l : ℕ} (H : n + m = k + l) : dist n k = dist l m
:= calc
dist n k = dist (n + m) (k + m) : symm (dist_add_right n m k)
... = dist (k + l) (k + m) : {H}
... = dist l m : dist_add_left k l m
end --namespace nat
|
ddf83e7e0089365b7ea15b769b019aeea5f121e2 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/sec_notation2.lean | 8a3610a9b043f236f26c8adf7d34f3e7629f3881 | [
"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 | 440 | lean | open nat
namespace foo
section
section
parameter (A : Type)
definition f (a b : A) : A := a
definition add2 (a : nat) : nat := a + 2
postfix `+.2`:100 := add2
local postfix `++2`:100 := add2
eval 3 +.2
example : 3 +.2 = 3 ++2 := rfl
end
eval 3 +.2
example : 3 +.2 = 3 ++2 := rfl -- error
end
eval 3 +.2
end foo
example : 3 +.2 = 5 := -- error
rfl
open foo
example : 3 +.2 = 5 := -- error
rfl
|
9a084a0f18c6b4e2591aaaee0b4a1c34316c2403 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/order/filter/filter_product.lean | 5dc172ea7d23b559ab922c8b8ab64125b71e749b | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 7,237 | lean | /-
Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Abhimanyu Pallavi Sudhir
-/
import order.filter.ultrafilter
import order.filter.germ
/-!
# Ultraproducts
If `φ` is an ultrafilter, then the space of germs of functions `f : α → β` at `φ` is called
the *ultraproduct*. In this file we prove properties of ultraproducts that rely on `φ` being an
ultrafilter. Definitions and properties that work for any filter should go to `order.filter.germ`.
## Tags
ultrafilter, ultraproduct
-/
universes u v
variables {α : Type u} {β : Type v} {φ : filter α}
open_locale classical
namespace filter
local notation `∀*` binders `, ` r:(scoped p, filter.eventually p φ) := r
namespace germ
local notation `β*` := germ φ β
/-- If `φ` is an ultrafilter then the ultraproduct is a division ring.
This cannot be an instance, since it depends on `φ` being an ultrafilter. -/
protected def division_ring [division_ring β] (U : is_ultrafilter φ) : division_ring β* :=
{ mul_inv_cancel := λ f, induction_on f $ λ f hf, coe_eq.2 $ (U.em (λ y, f y = 0)).elim
(λ H, (hf $ coe_eq.2 H).elim) (λ H, H.mono $ λ x, mul_inv_cancel),
inv_mul_cancel := λ f, induction_on f $ λ f hf, coe_eq.2 $ (U.em (λ y, f y = 0)).elim
(λ H, (hf $ coe_eq.2 H).elim) (λ H, H.mono $ λ x, inv_mul_cancel),
inv_zero := coe_eq.2 $ by simp only [(∘), inv_zero],
.. germ.ring, .. germ.has_inv, .. @germ.nontrivial _ _ _ _ U.1 }
/-- If `φ` is an ultrafilter then the ultraproduct is a field.
This cannot be an instance, since it depends on `φ` being an ultrafilter. -/
protected def field [field β] (U : is_ultrafilter φ) : field β* :=
{ .. germ.comm_ring, .. germ.division_ring U }
/-- If `φ` is an ultrafilter then the ultraproduct is a linear order.
This cannot be an instance, since it depends on `φ` being an ultrafilter. -/
protected noncomputable def linear_order [linear_order β] (U : is_ultrafilter φ) :
linear_order β* :=
{ le_total := λ f g, induction_on₂ f g $ λ f g, U.eventually_or.1 $ eventually_of_forall $
λ x, le_total _ _,
decidable_le := by apply_instance,
.. germ.partial_order }
@[simp, norm_cast] lemma const_div [division_ring β] (U : is_ultrafilter φ) (x y : β) :
(↑(x / y) : β*) = @has_div.div _ (@division_ring_has_div _ (germ.division_ring U)) ↑x ↑y :=
rfl
lemma coe_lt [preorder β] (U : is_ultrafilter φ) {f g : α → β} :
(f : β*) < g ↔ ∀* x, f x < g x :=
by simp only [lt_iff_le_not_le, eventually_and, coe_le, U.eventually_not, eventually_le]
lemma coe_pos [preorder β] [has_zero β] (U : is_ultrafilter φ) {f : α → β} :
0 < (f : β*) ↔ ∀* x, 0 < f x :=
coe_lt U
lemma const_lt [preorder β] (U : is_ultrafilter φ) {x y : β} :
(↑x : β*) < ↑y ↔ x < y :=
(coe_lt U).trans $ by haveI := U.1; exact lift_rel_const_iff
lemma lt_def [preorder β] (U : is_ultrafilter φ) :
((<) : β* → β* → Prop) = lift_rel (<) :=
by { ext ⟨f⟩ ⟨g⟩, exact coe_lt U }
lemma le_def [preorder β] :
((≤) : β* → β* → Prop) = lift_rel (≤) :=
by { ext ⟨f⟩ ⟨g⟩, exact coe_le }
/-- If `φ` is an ultrafilter then the ultraproduct is an ordered ring.
This cannot be an instance, since it depends on `φ` being an ultrafilter. -/
protected def ordered_ring [ordered_ring β] (U : is_ultrafilter φ) : ordered_ring β* :=
{ zero_le_one := by { rw le_def, show (∀* i, (0 : β) ≤ 1), simp [zero_le_one] },
mul_pos := λ x y, induction_on₂ x y $ λ f g hf hg, (coe_pos U).2 $
((coe_pos U).1 hg).mp $ ((coe_pos U).1 hf).mono $ λ x, mul_pos,
.. germ.ring, .. germ.ordered_add_comm_group, .. @germ.nontrivial _ _ _ _ U.1 }
/-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered ring.
This cannot be an instance, since it depends on `φ` being an ultrafilter. -/
protected noncomputable def linear_ordered_ring [linear_ordered_ring β] (U : is_ultrafilter φ) :
linear_ordered_ring β* :=
{ .. germ.ordered_ring U,
.. germ.linear_order U,
.. nontrivial_of_lt 0 (1 : β*)
(by { rw lt_def U, show (∀* i, (0 : β) < 1), simp [zero_lt_one] }) }
/-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered field.
This cannot be an instance, since it depends on `φ` being an ultrafilter. -/
protected noncomputable def linear_ordered_field [linear_ordered_field β] (U : is_ultrafilter φ) :
linear_ordered_field β* :=
{ .. germ.linear_ordered_ring U, .. germ.field U }
/-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered commutative ring.
This cannot be an instance, since it depends on `φ` being an ultrafilter. -/
protected noncomputable def linear_ordered_comm_ring [linear_ordered_comm_ring β]
(U : is_ultrafilter φ) :
linear_ordered_comm_ring β* :=
{ .. germ.linear_ordered_ring U, .. germ.comm_monoid }
/-- If `φ` is an ultrafilter then the ultraproduct is a decidable linear ordered commutative group.
This cannot be an instance, since it depends on `φ` being an ultrafilter. -/
protected noncomputable def linear_ordered_add_comm_group
[linear_ordered_add_comm_group β] (U : is_ultrafilter φ) :
linear_ordered_add_comm_group β* :=
{ .. germ.ordered_add_comm_group, .. germ.linear_order U }
lemma max_def [K : linear_order β] (U : is_ultrafilter φ) (x y : β*) :
@max β* (germ.linear_order U) x y = map₂ max x y :=
quotient.induction_on₂' x y $ λ a b, by unfold max;
begin
split_ifs,
exact quotient.sound'(by filter_upwards [h] λ i hi, (max_eq_left hi).symm),
exact quotient.sound'(by filter_upwards [@le_of_not_le _ (germ.linear_order U) _ _ h]
λ i hi, (max_eq_right hi).symm),
end
lemma min_def [K : linear_order β] (U : is_ultrafilter φ) (x y : β*) :
@min β* (germ.linear_order U) x y = map₂ min x y :=
quotient.induction_on₂' x y $ λ a b, by unfold min;
begin
split_ifs,
exact quotient.sound'(by filter_upwards [h] λ i hi, (min_eq_left hi).symm),
exact quotient.sound'(by filter_upwards [@le_of_not_le _ (germ.linear_order U) _ _ h]
λ i hi, (min_eq_right hi).symm),
end
lemma abs_def [linear_ordered_add_comm_group β] (U : is_ultrafilter φ) (x : β*) :
@abs _ (germ.linear_ordered_add_comm_group U) x = map abs x :=
quotient.induction_on' x $ λ a, by unfold abs; rw max_def U;
exact quotient.sound' (show ∀* i, abs _ = _, by simp)
@[simp] lemma const_max [linear_order β] (U : is_ultrafilter φ) (x y : β) :
(↑(max x y : β) : β*) = @max _ (germ.linear_order U) ↑x ↑y :=
begin
haveI := U.1,
unfold max, split_ifs,
{ refl },
{ exact false.elim (h_1 $ const_le h) },
{ exact false.elim (h (const_le_iff.mp h_1)) },
{ refl }
end
@[simp] lemma const_min [linear_order β] (U : is_ultrafilter φ) (x y : β) :
(↑(min x y : β) : β*) = @min _ (germ.linear_order U) ↑x ↑y :=
begin
haveI := U.1,
unfold min, split_ifs; try { refl }; apply false.elim,
{ exact (h_1 $ const_le h) },
{ exact (h $ const_le_iff.mp h_1) },
end
@[simp] lemma const_abs [linear_ordered_add_comm_group β] (U : is_ultrafilter φ) (x : β) :
(↑(abs x) : β*) = @abs _ (germ.linear_ordered_add_comm_group U) ↑x :=
const_max U x (-x)
end germ
end filter
|
71afe72482b60f05d4fc44d239d0cd833eecb0b4 | 87d5955e1100ba73f6b56149b659e85116fa215b | /group_theory/subgroup.lean | 9dcca7f73978d35fddcece213df1f180dbcf6ccc | [
"Apache-2.0"
] | permissive | avigad/leanproved | 4d15a05f8544a67b9f589c5e656358e1485aef3c | 3cf0f5dda3ace82f6b7cdc159528ce3ebaef159f | refs/heads/master | 1,611,368,103,158 | 1,433,589,072,000 | 1,433,589,072,000 | 36,843,899 | 0 | 0 | null | 1,433,385,918,000 | 1,433,385,918,000 | null | UTF-8 | Lean | false | false | 19,062 | lean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Haitao Zhang
-/
import data algebra.group data .extra
open function
-- ⁻¹ in eq.ops conflicts with group ⁻¹
-- open eq.ops
local notation H1 ▸ H2 := eq.subst H1 H2
open set
local attribute set [reducible]
section
open finset
-- overloading problem, use set.subset explicitly for now-example (A : Type) (x : A) (S H : set A) (Pin : x ∈ S) (Psub : S ⊆ H) : x ∈ H := Psub Pin
end
namespace algebra
namespace coset
-- semigroup coset definition
section
variable {A : Type}
variable [s : semigroup A]
include s
definition lmul (a : A) := λ x, a * x
definition rmul (a : A) := λ x, x * a
definition l a (S : set A) := (lmul a) '[S]
definition r a (S : set A) := (rmul a) '[S]
lemma lmul_compose : ∀ (a b : A), (lmul a) ∘ (lmul b) = lmul (a*b) :=
take a, take b,
funext (assume x, by
rewrite [↑function.compose, ↑lmul, mul.assoc])
lemma rmul_compose : ∀ (a b : A), (rmul a) ∘ (rmul b) = rmul (b*a) :=
take a, take b,
funext (assume x, by
rewrite [↑function.compose, ↑rmul, mul.assoc])
lemma lcompose a b (S : set A) : l a (l b S) = l (a*b) S :=
calc (lmul a) '[(lmul b) '[S]] = ((lmul a) ∘ (lmul b)) '[S] : image_compose
... = lmul (a*b) '[S] : lmul_compose
lemma rcompose a b (S : set A) : r a (r b S) = r (b*a) S :=
calc (rmul a) '[(rmul b) '[S]] = ((rmul a) ∘ (rmul b)) '[S] : image_compose
... = rmul (b*a) '[S] : rmul_compose
lemma l_sub a (S H : set A) : S ⊆ H → (l a S) ⊆ (l a H) := image_subset (lmul a)
definition l_same S (a b : A) := l a S = l b S
definition r_same S (a b : A) := r a S = r b S
lemma l_same.refl S (a : A) : l_same S a a := rfl
lemma l_same.symm S (a b : A) : l_same S a b → l_same S b a := eq.symm
lemma l_same.trans S (a b c : A) : l_same S a b → l_same S b c → l_same S a c := eq.trans
example (S : set A) : equivalence (l_same S) := mk_equivalence (l_same S) (l_same.refl S) (l_same.symm S) (l_same.trans S)
end
end coset
section
variable {A : Type}
variable [s : group A]
include s
definition lmul_by (a : A) := λ x, a * x
definition rmul_by (a : A) := λ x, x * a
definition glcoset a (H : set A) : set A := λ x, H (a⁻¹ * x)
definition grcoset H (a : A) : set A := λ x, H (x * a⁻¹)
definition conj_by (g a : A) := g * a * g⁻¹
definition is_conjugate (a b : A) := ∃ x, conj_by x b = a
end
end algebra
namespace group
open algebra
namespace ops
infixr `∘>`:55 := glcoset -- stronger than = (50), weaker than * (70)
infixl `<∘`:55 := grcoset
infixr `∘c`:55 := conj_by
end ops
end group
namespace algebra
open group.ops
section
variable {A : Type}
variable [s : group A]
include s
-- too precious to make it wider scope. group.ops can now be openned without it.
local infixl `~` := is_conjugate
lemma conj_compose (f g a : A) : f ∘c g ∘c a = f*g ∘c a :=
calc f ∘c g ∘c a = f * (g * a * g⁻¹) * f⁻¹ : rfl
... = f * (g * a) * g⁻¹ * f⁻¹ : mul.assoc
... = f * g * a * g⁻¹ * f⁻¹ : mul.assoc
... = f * g * a * (g⁻¹ * f⁻¹) : mul.assoc
... = f * g * a * (f * g)⁻¹ : mul_inv
lemma conj_id (a : A) : 1 ∘c a = a :=
calc 1 * a * 1⁻¹ = a * 1⁻¹ : one_mul
... = a * 1 : one_inv
... = a : mul_one
lemma conj_one (g : A) : g ∘c 1 = 1 :=
calc g * 1 * g⁻¹ = g * g⁻¹ : mul_one
... = 1 : mul.right_inv
lemma conj_inv_cancel (g : A) : ∀ a, g⁻¹ ∘c g ∘c a = a :=
assume a, calc
g⁻¹ ∘c g ∘c a = g⁻¹*g ∘c a : conj_compose
... = 1 ∘c a : mul.left_inv
... = a : conj_id
lemma is_conj.refl (a : A) : a ~ a := exists.intro 1 (conj_id a)
lemma is_conj.symm (a b : A) : a ~ b → b ~ a :=
assume Pab, obtain x (Pconj : x ∘c b = a), from Pab,
assert Pxinv : x⁻¹ ∘c x ∘c b = x⁻¹ ∘c a, from (congr_arg2 conj_by (eq.refl x⁻¹) Pconj),
exists.intro x⁻¹ (eq.symm (conj_inv_cancel x b ▸ Pxinv))
lemma is_conj.trans (a b c : A) : a ~ b → b ~ c → a ~ c :=
assume Pab, assume Pbc,
obtain x (Px : x ∘c b = a), from Pab,
obtain y (Py : y ∘c c = b), from Pbc,
exists.intro (x*y) (calc
x*y ∘c c = x ∘c y ∘c c : conj_compose
... = x ∘c b : Py
... = a : Px)
lemma lmul_inv_on (a : A) (H : set A) : left_inv_on (lmul_by a⁻¹) (lmul_by a) H :=
take x Px, show a⁻¹*(a*x) = x, by rewrite inv_mul_cancel_left
lemma lmul_inj_on (a : A) (H : set A) : inj_on (lmul_by a) H :=
inj_on_of_left_inv_on (lmul_inv_on a H)
lemma glcoset_eq_lcoset a (H : set A) : a ∘> H = coset.l a H :=
setext
begin
intro x,
rewrite [↑glcoset, ↑coset.l, ↑image, ↑set_of, ↑mem, ↑coset.lmul],
apply iff.intro,
intro P1,
apply (exists.intro (a⁻¹ * x)),
apply and.intro,
exact P1,
exact (mul_inv_cancel_left a x),
show (∃ (x_1 : A), H x_1 ∧ a * x_1 = x) → H (a⁻¹ * x), from
assume P2, obtain x_1 P3, from P2,
have P4 : a * x_1 = x, from and.right P3,
have P5 : x_1 = a⁻¹ * x, from eq_inv_mul_of_mul_eq P4,
eq.subst P5 (and.left P3)
end
lemma grcoset_eq_rcoset a (H : set A) : H <∘ a = coset.r a H :=
begin
rewrite [↑grcoset, ↑coset.r, ↑image, ↑coset.rmul, ↑set_of],
apply setext, rewrite ↑mem,
intro x,
apply iff.intro,
show H (x * a⁻¹) → (∃ (x_1 : A), H x_1 ∧ x_1 * a = x), from
assume PH,
exists.intro (x * a⁻¹)
(and.intro PH (inv_mul_cancel_right x a)),
show (∃ (x_1 : A), H x_1 ∧ x_1 * a = x) → H (x * a⁻¹), from
assume Pex,
obtain x_1 Pand, from Pex,
eq.subst (eq_mul_inv_of_mul_eq (and.right Pand)) (and.left Pand)
end
lemma glcoset_sub a (S H : set A) : S ⊆ H → (a ∘> S) ⊆ (a ∘> H) :=
assume Psub,
assert P : _, from coset.l_sub a S H Psub,
eq.symm (glcoset_eq_lcoset a S) ▸ eq.symm (glcoset_eq_lcoset a H) ▸ P
lemma glcoset_compose (a b : A) (H : set A) : a ∘> b ∘> H = a*b ∘> H :=
begin
rewrite [*glcoset_eq_lcoset], exact (coset.lcompose a b H)
end
lemma grcoset_compose (a b : A) (H : set A) : H <∘ a <∘ b = H <∘ a*b :=
begin
rewrite [*grcoset_eq_rcoset], exact (coset.rcompose b a H)
end
lemma glcoset_id (H : set A) : 1 ∘> H = H :=
funext (assume x,
calc (1 ∘> H) x = H (1⁻¹*x) : rfl
... = H (1*x) : {one_inv}
... = H x : {one_mul x})
lemma grcoset_id (H : set A) : H <∘ 1 = H :=
funext (assume x,
calc H (x*1⁻¹) = H (x*1) : {one_inv}
... = H x : {mul_one x})
--lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H :=
-- funext (assume x,
-- calc glcoset a⁻¹ (glcoset a H) x = H x : {mul_inv_cancel_left a⁻¹ x})
lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H :=
calc a⁻¹ ∘> a ∘> H = (a⁻¹*a) ∘> H : glcoset_compose
... = 1 ∘> H : mul.left_inv
... = H : glcoset_id
lemma grcoset_inv H (a : A) : (H <∘ a) <∘ a⁻¹ = H :=
funext (assume x,
calc grcoset (grcoset H a) a⁻¹ x = H x : {inv_mul_cancel_right x a⁻¹})
lemma glcoset_cancel a b (H : set A) : (b*a⁻¹) ∘> a ∘> H = b ∘> H :=
calc (b*a⁻¹) ∘> a ∘> H = b*a⁻¹*a ∘> H : glcoset_compose
... = b ∘> H : {inv_mul_cancel_right b a}
lemma grcoset_cancel a b (H : set A) : H <∘ a <∘ a⁻¹*b = H <∘ b :=
calc H <∘ a <∘ a⁻¹*b = H <∘ a*(a⁻¹*b) : grcoset_compose
... = H <∘ b : {mul_inv_cancel_left a b}
-- test how precedence breaks tie: infixr takes hold since its encountered first
example a b (H : set A) : a ∘> H <∘ b = a ∘> (H <∘ b) := rfl
-- should be true for semigroup as well but irrelevant
lemma lcoset_rcoset_assoc a b (H : set A) : a ∘> H <∘ b = (a ∘> H) <∘ b :=
funext (assume x, begin
esimp [glcoset, grcoset], rewrite mul.assoc
end)
definition mul_closed_on H := ∀ (x y : A), x ∈ H → y ∈ H → x * y ∈ H
lemma closed_lcontract a (H : set A) : mul_closed_on H → a ∈ H → a ∘> H ⊆ H :=
begin
rewrite [↑mul_closed_on, ↑glcoset, ↑subset, ↑mem],
intro Pclosed, intro PHa, intro x, intro PHainvx,
exact (eq.subst (mul_inv_cancel_left a x)
(Pclosed a (a⁻¹*x) PHa PHainvx))
end
lemma closed_rcontract a (H : set A) : mul_closed_on H → a ∈ H → H <∘ a ⊆ H :=
assume P1 : mul_closed_on H,
assume P2 : H a,
begin
rewrite ↑subset,
intro x,
rewrite [↑grcoset, ↑mem],
intro P3,
exact (eq.subst (inv_mul_cancel_right x a) (P1 (x * a⁻¹) a P3 P2))
end
lemma closed_lcontract_set a (H G : set A) : mul_closed_on G → H ⊆ G → a∈G → a∘>H ⊆ G :=
assume Pclosed, assume PHsubG, assume PainG,
assert PaGsubG : a ∘> G ⊆ G, from closed_lcontract a G Pclosed PainG,
assert PaHsubaG : a ∘> H ⊆ a ∘> G, from
eq.symm (glcoset_eq_lcoset a H) ▸ eq.symm (glcoset_eq_lcoset a G) ▸ (coset.l_sub a H G PHsubG),
subset.trans _ _ _ PaHsubaG PaGsubG
definition subgroup.has_inv H := ∀ (a : A), a ∈ H → a⁻¹ ∈ H
-- two ways to define the same equivalence relatiohship for subgroups
definition in_lcoset [reducible] H (a b : A) := a ∈ b ∘> H
definition in_rcoset [reducible] H (a b : A) := a ∈ H <∘ b
definition same_lcoset [reducible] H (a b : A) := a ∘> H = b ∘> H
definition same_rcoset [reducible] H (a b : A) := H <∘ a = H <∘ b
definition same_left_right_coset (N : set A) := ∀ x, x ∘> N = N <∘ x
structure is_subgroup [class] (H : set A) : Type :=
(has_one : H 1)
(mul_closed : mul_closed_on H)
(has_inv : subgroup.has_inv H)
structure is_normal_subgroup [class] (N : set A) extends is_subgroup N :=
(normal : same_left_right_coset N)
end
section subgroup
variable {A : Type}
variable [s : group A]
include s
variable {H : set A}
variable [is_subg : is_subgroup H]
include is_subg
lemma subg_has_one : H (1 : A) := @is_subgroup.has_one A s H is_subg
lemma subg_mul_closed : mul_closed_on H := @is_subgroup.mul_closed A s H is_subg
lemma subg_has_inv : subgroup.has_inv H := @is_subgroup.has_inv A s H is_subg
lemma subgroup_coset_id : ∀ a, a ∈ H → (a ∘> H = H ∧ H <∘ a = H) :=
take a, assume PHa : H a,
assert Pl : a ∘> H ⊆ H, from closed_lcontract a H subg_mul_closed PHa,
assert Pr : H <∘ a ⊆ H, from closed_rcontract a H subg_mul_closed PHa,
assert PHainv : H a⁻¹, from subg_has_inv a PHa,
and.intro
(setext (assume x,
begin
esimp [glcoset, mem],
apply iff.intro,
apply Pl,
intro PHx, exact (subg_mul_closed a⁻¹ x PHainv PHx)
end))
(setext (assume x,
begin
esimp [grcoset, mem],
apply iff.intro,
apply Pr,
intro PHx, exact (subg_mul_closed x a⁻¹ PHx PHainv)
end))
lemma subgroup_lcoset_id : ∀ a, a ∈ H → a ∘> H = H :=
take a, assume PHa : H a,
and.left (subgroup_coset_id a PHa)
lemma subgroup_rcoset_id : ∀ a, a ∈ H → H <∘ a = H :=
take a, assume PHa : H a,
and.right (subgroup_coset_id a PHa)
lemma subg_in_coset_refl (a : A) : a ∈ a ∘> H ∧ a ∈ H <∘ a :=
assert PH1 : H 1, from subg_has_one,
assert PHinvaa : H (a⁻¹*a), from (eq.symm (mul.left_inv a)) ▸ PH1,
assert PHainva : H (a*a⁻¹), from (eq.symm (mul.right_inv a)) ▸ PH1,
and.intro PHinvaa PHainva
lemma subg_in_lcoset_same_lcoset (a b : A) : in_lcoset H a b → same_lcoset H a b :=
assume Pa_in_b : H (b⁻¹*a),
have Pbinva : b⁻¹*a ∘> H = H, from subgroup_lcoset_id (b⁻¹*a) Pa_in_b,
have Pb_binva : b ∘> b⁻¹*a ∘> H = b ∘> H, from Pbinva ▸ rfl,
have Pbbinva : b*(b⁻¹*a)∘>H = b∘>H, from glcoset_compose b (b⁻¹*a) H ▸ Pb_binva,
mul_inv_cancel_left b a ▸ Pbbinva
lemma subg_same_lcoset_in_lcoset (a b : A) : same_lcoset H a b → in_lcoset H a b :=
assume Psame : a∘>H = b∘>H,
assert Pa : a ∈ a∘>H, from and.left (subg_in_coset_refl a),
by exact (Psame ▸ Pa)
lemma subg_lcoset_same (a b : A) : in_lcoset H a b = (a∘>H = b∘>H) :=
propext(iff.intro (subg_in_lcoset_same_lcoset a b) (subg_same_lcoset_in_lcoset a b))
lemma subg_rcoset_same (a b : A) : in_rcoset H a b = (H<∘a = H<∘b) :=
propext(iff.intro
(assume Pa_in_b : H (a*b⁻¹),
have Pabinv : H<∘a*b⁻¹ = H, from subgroup_rcoset_id (a*b⁻¹) Pa_in_b,
have Pabinv_b : H <∘ a*b⁻¹ <∘ b = H <∘ b, from Pabinv ▸ rfl,
have Pabinvb : H <∘ a*b⁻¹*b = H <∘ b, from grcoset_compose (a*b⁻¹) b H ▸ Pabinv_b,
inv_mul_cancel_right a b ▸ Pabinvb)
(assume Psame,
assert Pa : a ∈ H<∘a, from and.right (subg_in_coset_refl a),
by exact (Psame ▸ Pa)))
lemma subg_same_lcoset.refl (a : A) : same_lcoset H a a := rfl
lemma subg_same_rcoset.refl (a : A) : same_rcoset H a a := rfl
lemma subg_same_lcoset.symm (a b : A) : same_lcoset H a b → same_lcoset H b a := eq.symm
lemma subg_same_rcoset.symm (a b : A) : same_rcoset H a b → same_rcoset H b a := eq.symm
lemma subg_same_lcoset.trans (a b c : A) : same_lcoset H a b → same_lcoset H b c → same_lcoset H a c :=
eq.trans
lemma subg_same_rcoset.trans (a b c : A) : same_rcoset H a b → same_rcoset H b c → same_rcoset H a c :=
eq.trans
variable {S : set A}
lemma subg_lcoset_subset_subg (Psub : S ⊆ H) (a : A) : a ∈ H → a ∘> S ⊆ H :=
assume Pin, have P : a ∘> S ⊆ a ∘> H, from glcoset_sub a S H Psub,
subgroup_lcoset_id a Pin ▸ P
end subgroup
section normal_subg
open quot
variable {A : Type}
variable [s : group A]
include s
variable (N : set A)
variable [is_nsubg : is_normal_subgroup N]
include is_nsubg
local notation a `~` b := same_lcoset N a b -- note : does not bind as strong as →
lemma nsubg_normal : same_left_right_coset N := @is_normal_subgroup.normal A s N is_nsubg
lemma nsubg_same_lcoset_product : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ((a1*a2) ~ (b1*b2)) :=
take a1, take a2, take b1, take b2,
assume Psame1 : a1 ∘> N = b1 ∘> N,
assume Psame2 : a2 ∘> N = b2 ∘> N,
calc
a1*a2 ∘> N = a1 ∘> a2 ∘> N : glcoset_compose
... = a1 ∘> b2 ∘> N : by rewrite Psame2
... = a1 ∘> (N <∘ b2) : by rewrite (nsubg_normal N)
... = (a1 ∘> N) <∘ b2 : by rewrite lcoset_rcoset_assoc
... = (b1 ∘> N) <∘ b2 : by rewrite Psame1
... = N <∘ b1 <∘ b2 : by rewrite (nsubg_normal N)
... = N <∘ (b1*b2) : by rewrite grcoset_compose
... = (b1*b2) ∘> N : by rewrite (nsubg_normal N)
example (a b : A) : (a⁻¹ ~ b⁻¹) = (a⁻¹ ∘> N = b⁻¹ ∘> N) := rfl
lemma nsubg_same_lcoset_inv : ∀ a b, (a ~ b) → (a⁻¹ ~ b⁻¹) :=
take a b, assume Psame : a ∘> N = b ∘> N, calc
a⁻¹ ∘> N = a⁻¹*b*b⁻¹ ∘> N : by rewrite mul_inv_cancel_right
... = a⁻¹*b ∘> b⁻¹ ∘> N : by rewrite glcoset_compose
... = a⁻¹*b ∘> (N <∘ b⁻¹) : by rewrite nsubg_normal
... = (a⁻¹*b ∘> N) <∘ b⁻¹ : by rewrite lcoset_rcoset_assoc
... = (a⁻¹ ∘> b ∘> N) <∘ b⁻¹ : by rewrite glcoset_compose
... = (a⁻¹ ∘> a ∘> N) <∘ b⁻¹ : by rewrite Psame
... = N <∘ b⁻¹ : by rewrite glcoset_inv
... = b⁻¹ ∘> N : by rewrite nsubg_normal
definition nsubg_setoid [instance] : setoid A :=
setoid.mk (same_lcoset N)
(mk_equivalence (same_lcoset N) (subg_same_lcoset.refl) (subg_same_lcoset.symm) (subg_same_lcoset.trans))
definition coset_of : Type := quot (nsubg_setoid N)
definition coset_inv_base (a : A) : coset_of N := ⟦a⁻¹⟧
definition coset_product (a b : A) : coset_of N := ⟦a*b⟧
lemma coset_product_well_defined : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ⟦a1*a2⟧ = ⟦b1*b2⟧ :=
take a1 a2 b1 b2, assume P1 P2,
quot.sound (nsubg_same_lcoset_product N a1 a2 b1 b2 P1 P2)
definition coset_mul (aN bN : coset_of N) : coset_of N :=
quot.lift_on₂ aN bN (coset_product N) (coset_product_well_defined N)
lemma coset_inv_well_defined : ∀ a b, (a ~ b) → ⟦a⁻¹⟧ = ⟦b⁻¹⟧ :=
take a b, assume P, quot.sound (nsubg_same_lcoset_inv N a b P)
definition coset_inv (aN : coset_of N) : coset_of N :=
quot.lift_on aN (coset_inv_base N) (coset_inv_well_defined N)
definition coset_one : coset_of N := ⟦1⟧
local infixl `cx`:70 := coset_mul N
example (a b c : A) : ⟦a⟧ cx ⟦b*c⟧ = ⟦a*(b*c)⟧ := rfl
lemma coset_product_assoc (a b c : A) : ⟦a⟧ cx ⟦b⟧ cx ⟦c⟧ = ⟦a⟧ cx (⟦b⟧ cx ⟦c⟧) := calc
⟦a*b*c⟧ = ⟦a*(b*c)⟧ : {mul.assoc a b c}
... = ⟦a⟧ cx ⟦b*c⟧ : rfl
lemma coset_product_left_id (a : A) : ⟦1⟧ cx ⟦a⟧ = ⟦a⟧ := calc
⟦1*a⟧ = ⟦a⟧ : {one_mul a}
lemma coset_product_right_id (a : A) : ⟦a⟧ cx ⟦1⟧ = ⟦a⟧ := calc
⟦a*1⟧ = ⟦a⟧ : {mul_one a}
lemma coset_product_left_inv (a : A) : ⟦a⁻¹⟧ cx ⟦a⟧ = ⟦1⟧ := calc
⟦a⁻¹*a⟧ = ⟦1⟧ : {mul.left_inv a}
lemma coset_mul.assoc (aN bN cN : coset_of N) : aN cx bN cx cN = aN cx (bN cx cN) :=
quot.ind (λ a, quot.ind (λ b, quot.ind (λ c, coset_product_assoc N a b c) cN) bN) aN
lemma coset_mul.one_mul (aN : coset_of N) : coset_one N cx aN = aN :=
quot.ind (coset_product_left_id N) aN
lemma coset_mul.mul_one (aN : coset_of N) : aN cx (coset_one N) = aN :=
quot.ind (coset_product_right_id N) aN
lemma coset_mul.left_inv (aN : coset_of N) : (coset_inv N aN) cx aN = (coset_one N) :=
quot.ind (coset_product_left_inv N) aN
definition mk_quotient_group : group (coset_of N):=
group.mk (coset_mul N) (coset_mul.assoc N) (coset_one N) (coset_mul.one_mul N) (coset_mul.mul_one N) (coset_inv N) (coset_mul.left_inv N)
end normal_subg
namespace group
namespace quotient
section
open quot
variable {A : Type}
variable [s : group A]
include s
variable {N : set A}
variable [is_nsubg : is_normal_subgroup N]
include is_nsubg
definition quotient_group [instance] : group (coset_of N) := mk_quotient_group N
example (aN : coset_of N) : aN * aN⁻¹ = 1 := mul.right_inv aN
definition natural (a : A) : coset_of N := ⟦a⟧
end
end quotient
end group
end algebra
|
67d91a1d4d7f59a865e979210d40cb2c989cf67d | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /src/Lean/Syntax.lean | 9ebe9ed32969e8d006a84b7ceaa87558aa889d8d | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,098 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich, Leonardo de Moura
-/
import Lean.Data.Name
import Lean.Data.Format
namespace Lean
def SourceInfo.updateTrailing (trailing : Substring) : SourceInfo → SourceInfo
| SourceInfo.original leading pos _ endPos => SourceInfo.original leading pos trailing endPos
| info => info
/- Syntax AST -/
inductive IsNode : Syntax → Prop where
| mk (kind : SyntaxNodeKind) (args : Array Syntax) : IsNode (Syntax.node kind args)
def SyntaxNode : Type := {s : Syntax // IsNode s }
def unreachIsNodeMissing {β} (h : IsNode Syntax.missing) : β := False.elim (nomatch h)
def unreachIsNodeAtom {β} {info val} (h : IsNode (Syntax.atom info val)) : β := False.elim (nomatch h)
def unreachIsNodeIdent {β info rawVal val preresolved} (h : IsNode (Syntax.ident info rawVal val preresolved)) : β := False.elim (nomatch h)
namespace SyntaxNode
@[inline] def getKind (n : SyntaxNode) : SyntaxNodeKind :=
match n with
| ⟨Syntax.node k args, _⟩ => k
| ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h
| ⟨Syntax.atom .., h⟩ => unreachIsNodeAtom h
| ⟨Syntax.ident .., h⟩ => unreachIsNodeIdent h
@[inline] def withArgs {β} (n : SyntaxNode) (fn : Array Syntax → β) : β :=
match n with
| ⟨Syntax.node _ args, _⟩ => fn args
| ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h
| ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h
| ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h
@[inline] def getNumArgs (n : SyntaxNode) : Nat :=
withArgs n $ fun args => args.size
@[inline] def getArg (n : SyntaxNode) (i : Nat) : Syntax :=
withArgs n $ fun args => args.get! i
@[inline] def getArgs (n : SyntaxNode) : Array Syntax :=
withArgs n $ fun args => args
@[inline] def modifyArgs (n : SyntaxNode) (fn : Array Syntax → Array Syntax) : Syntax :=
match n with
| ⟨Syntax.node kind args, _⟩ => Syntax.node kind (fn args)
| ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h
| ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h
| ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h
end SyntaxNode
namespace Syntax
def getAtomVal! : Syntax → String
| atom _ val => val
| _ => panic! "getAtomVal!: not an atom"
def setAtomVal : Syntax → String → Syntax
| atom info _, v => (atom info v)
| stx, _ => stx
@[inline] def ifNode {β} (stx : Syntax) (hyes : SyntaxNode → β) (hno : Unit → β) : β :=
match stx with
| Syntax.node k args => hyes ⟨Syntax.node k args, IsNode.mk k args⟩
| _ => hno ()
@[inline] def ifNodeKind {β} (stx : Syntax) (kind : SyntaxNodeKind) (hyes : SyntaxNode → β) (hno : Unit → β) : β :=
match stx with
| Syntax.node k args => if k == kind then hyes ⟨Syntax.node k args, IsNode.mk k args⟩ else hno ()
| _ => hno ()
def asNode : Syntax → SyntaxNode
| Syntax.node kind args => ⟨Syntax.node kind args, IsNode.mk kind args⟩
| _ => ⟨Syntax.node nullKind #[], IsNode.mk nullKind #[]⟩
def getIdAt (stx : Syntax) (i : Nat) : Name :=
(stx.getArg i).getId
@[inline] def modifyArgs (stx : Syntax) (fn : Array Syntax → Array Syntax) : Syntax :=
match stx with
| node k args => node k (fn args)
| stx => stx
@[inline] def modifyArg (stx : Syntax) (i : Nat) (fn : Syntax → Syntax) : Syntax :=
match stx with
| node k args => node k (args.modify i fn)
| stx => stx
@[specialize] partial def replaceM {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) : Syntax → m (Syntax)
| stx@(node kind args) => do
match (← fn stx) with
| some stx => return stx
| none => return node kind (← args.mapM (replaceM fn))
| stx => do
let o ← fn stx
return o.getD stx
@[specialize] partial def rewriteBottomUpM {m : Type → Type} [Monad m] (fn : Syntax → m (Syntax)) : Syntax → m (Syntax)
| node kind args => do
let args ← args.mapM (rewriteBottomUpM fn)
fn (node kind args)
| stx => fn stx
@[inline] def rewriteBottomUp (fn : Syntax → Syntax) (stx : Syntax) : Syntax :=
Id.run $ stx.rewriteBottomUpM fn
private def updateInfo : SourceInfo → String.Pos → String.Pos → SourceInfo
| SourceInfo.original lead pos trail endPos, leadStart, trailStop =>
SourceInfo.original { lead with startPos := leadStart } pos { trail with stopPos := trailStop } endPos
| info, _, _ => info
private def chooseNiceTrailStop (trail : Substring) : String.Pos :=
trail.startPos + trail.posOf '\n'
/- Remark: the State `String.Pos` is the `SourceInfo.trailing.stopPos` of the previous token,
or the beginning of the String. -/
@[inline]
private def updateLeadingAux : Syntax → StateM String.Pos (Option Syntax)
| atom info@(SourceInfo.original lead _ trail _) val => do
let trailStop := chooseNiceTrailStop trail
let newInfo := updateInfo info (← get) trailStop
set trailStop
pure $ some (atom newInfo val)
| ident info@(SourceInfo.original lead _ trail _) rawVal val pre => do
let trailStop := chooseNiceTrailStop trail
let newInfo := updateInfo info (← get) trailStop
set trailStop
pure $ some (ident newInfo rawVal val pre)
| _ => pure none
/-- Set `SourceInfo.leading` according to the trailing stop of the preceding token.
The result is a round-tripping syntax tree IF, in the input syntax tree,
* all leading stops, atom contents, and trailing starts are correct
* trailing stops are between the trailing start and the next leading stop.
Remark: after parsing, all `SourceInfo.leading` fields are empty.
The `Syntax` argument is the output produced by the parser for `source`.
This function "fixes" the `source.leading` field.
Additionally, we try to choose "nicer" splits between leading and trailing stops
according to some heuristics so that e.g. comments are associated to the (intuitively)
correct token.
Note that the `SourceInfo.trailing` fields must be correct.
The implementation of this Function relies on this property. -/
def updateLeading : Syntax → Syntax :=
fun stx => (replaceM updateLeadingAux stx).run' 0
partial def updateTrailing (trailing : Substring) : Syntax → Syntax
| Syntax.atom info val => Syntax.atom (info.updateTrailing trailing) val
| Syntax.ident info rawVal val pre => Syntax.ident (info.updateTrailing trailing) rawVal val pre
| n@(Syntax.node k args) =>
if args.size == 0 then n
else
let i := args.size - 1
let last := updateTrailing trailing args[i]
let args := args.set! i last;
Syntax.node k args
| s => s
partial def getTailWithPos : Syntax → Option Syntax
| stx@(atom info _) => info.getPos?.map fun _ => stx
| stx@(ident info ..) => info.getPos?.map fun _ => stx
| node _ args => args.findSomeRev? getTailWithPos
| _ => none
open SourceInfo in
/-- Split an `ident` into its dot-separated components while preserving source info.
Macro scopes are first erased. For example, `` `foo.bla.boo._@._hyg.4 `` ↦ `` [`foo, `bla, `boo] ``.
If `nFields` is set, we take that many fields from the end and keep the remaining components
as one name. For example, `` `foo.bla.boo `` with `(nFields := 1)` ↦ `` [`foo.bla, `boo] ``. -/
def identComponents (stx : Syntax) (nFields? : Option Nat := none) : List Syntax :=
match stx with
| ident (SourceInfo.original lead pos trail _) rawStr val _ =>
let val := val.eraseMacroScopes
-- With original info, we assume that `rawStr` represents `val`.
let nameComps := nameComps val nFields?
let rawComps := splitNameLit rawStr
let rawComps :=
if let some nFields := nFields? then
let nPrefix := rawComps.length - nFields
let prefixSz := rawComps.take nPrefix |>.foldl (init := 0) fun acc (ss : Substring) => acc + ss.bsize + 1
let prefixSz := prefixSz - 1 -- The last component has no dot
rawStr.extract 0 prefixSz :: rawComps.drop nPrefix
else
rawComps
assert! nameComps.length == rawComps.length
nameComps.zip rawComps |>.map fun (id, ss) =>
let off := ss.startPos - rawStr.startPos
let lead := if off == 0 then lead else "".toSubstring
let trail := if ss.stopPos == rawStr.stopPos then trail else "".toSubstring
let info := original lead (pos + off) trail (pos + off + ss.bsize)
ident info ss id []
| ident si _ val _ =>
let val := val.eraseMacroScopes
/- With non-original info:
- `rawStr` can take all kinds of forms so we only use `val`.
- there is no source extent to offset, so we pass it as-is. -/
nameComps val nFields? |>.map fun n => ident si n.toString.toSubstring n []
| _ => unreachable!
where
nameComps (n : Name) (nFields? : Option Nat) : List Name :=
if let some nFields := nFields? then
let nameComps := n.components
let nPrefix := nameComps.length - nFields
let namePrefix := nameComps.take nPrefix |>.foldl (init := Name.anonymous) fun acc n => acc ++ n
namePrefix :: nameComps.drop nPrefix
else
n.components
structure TopDown where
firstChoiceOnly : Bool
stx : Syntax
/--
`for _ in stx.topDown` iterates through each node and leaf in `stx` top-down, left-to-right.
If `firstChoiceOnly` is `true`, only visit the first argument of each choice node.
-/
def topDown (stx : Syntax) (firstChoiceOnly := false) : TopDown := ⟨firstChoiceOnly, stx⟩
partial instance : ForIn m TopDown Syntax where
forIn := fun ⟨firstChoiceOnly, stx⟩ init f => do
let rec @[specialize] loop stx b [Inhabited (typeOf% b)] := do
match (← f stx b) with
| ForInStep.yield b' =>
let mut b := b'
if let Syntax.node k args := stx then
if firstChoiceOnly && k == choiceKind then
return ← loop args[0] b
else
for arg in args do
match (← loop arg b) with
| ForInStep.yield b' => b := b'
| ForInStep.done b' => return ForInStep.done b'
return ForInStep.yield b
| ForInStep.done b => return ForInStep.done b
match (← @loop stx init ⟨init⟩) with
| ForInStep.yield b => return b
| ForInStep.done b => return b
partial def reprint (stx : Syntax) : Option String :=
OptionM.run do
let mut s := ""
for stx in stx.topDown (firstChoiceOnly := true) do
match stx with
| atom info val => s := s ++ reprintLeaf info val
| ident info rawVal _ _ => s := s ++ reprintLeaf info rawVal.toString
| node kind args =>
if kind == choiceKind then
-- this visit the first arg twice, but that should hardly be a problem
-- given that choice nodes are quite rare and small
let s0 ← reprint args[0]
for arg in args[1:] do
let s' ← reprint arg
guard (s0 == s')
| _ => pure ()
return s
where
reprintLeaf (info : SourceInfo) (val : String) : String :=
match info with
| SourceInfo.original lead _ trail _ => s!"{lead}{val}{trail}"
-- no source info => add gracious amounts of whitespace to definitely separate tokens
-- Note that the proper pretty printer does not use this function.
-- The parser as well always produces source info, so round-tripping is still
-- guaranteed.
| _ => s!" {val} "
def hasMissing (stx : Syntax) : Bool := do
for stx in stx.topDown do
if stx.isMissing then
return true
return false
/--
Represents a cursor into a syntax tree that can be read, written, and advanced down/up/left/right.
Indices are allowed to be out-of-bound, in which case `cur` is `Syntax.missing`.
If the `Traverser` is used linearly, updates are linear in the `Syntax` object as well.
-/
structure Traverser where
cur : Syntax
parents : Array Syntax
idxs : Array Nat
namespace Traverser
def fromSyntax (stx : Syntax) : Traverser :=
⟨stx, #[], #[]⟩
def setCur (t : Traverser) (stx : Syntax) : Traverser :=
{ t with cur := stx }
/-- Advance to the `idx`-th child of the current node. -/
def down (t : Traverser) (idx : Nat) : Traverser :=
if idx < t.cur.getNumArgs then
{ cur := t.cur.getArg idx, parents := t.parents.push $ t.cur.setArg idx arbitrary, idxs := t.idxs.push idx }
else
{ cur := Syntax.missing, parents := t.parents.push t.cur, idxs := t.idxs.push idx }
/-- Advance to the parent of the current node, if any. -/
def up (t : Traverser) : Traverser :=
if t.parents.size > 0 then
let cur := if t.idxs.back < t.parents.back.getNumArgs then t.parents.back.setArg t.idxs.back t.cur else t.parents.back
{ cur := cur, parents := t.parents.pop, idxs := t.idxs.pop }
else
t
/-- Advance to the left sibling of the current node, if any. -/
def left (t : Traverser) : Traverser :=
if t.parents.size > 0 then
t.up.down (t.idxs.back - 1)
else
t
/-- Advance to the right sibling of the current node, if any. -/
def right (t : Traverser) : Traverser :=
if t.parents.size > 0 then
t.up.down (t.idxs.back + 1)
else
t
end Traverser
/-- Monad class that gives read/write access to a `Traverser`. -/
class MonadTraverser (m : Type → Type) where
st : MonadState Traverser m
namespace MonadTraverser
variable {m : Type → Type} [Monad m] [t : MonadTraverser m]
def getCur : m Syntax := Traverser.cur <$> t.st.get
def setCur (stx : Syntax) : m Unit := @modify _ _ t.st (fun t => t.setCur stx)
def goDown (idx : Nat) : m Unit := @modify _ _ t.st (fun t => t.down idx)
def goUp : m Unit := @modify _ _ t.st (fun t => t.up)
def goLeft : m Unit := @modify _ _ t.st (fun t => t.left)
def goRight : m Unit := @modify _ _ t.st (fun t => t.right)
def getIdx : m Nat := do
let st ← t.st.get
st.idxs.back?.getD 0
end MonadTraverser
end Syntax
namespace SyntaxNode
@[inline] def getIdAt (n : SyntaxNode) (i : Nat) : Name :=
(n.getArg i).getId
end SyntaxNode
def mkListNode (args : Array Syntax) : Syntax :=
Syntax.node nullKind args
namespace Syntax
-- quotation node kinds are formed from a unique quotation name plus "quot"
def isQuot : Syntax → Bool
| Syntax.node (Name.str _ "quot" _) _ => true
| Syntax.node `Lean.Parser.Term.dynamicQuot _ => true
| _ => false
def getQuotContent (stx : Syntax) : Syntax :=
if stx.isOfKind `Lean.Parser.Term.dynamicQuot then
stx[3]
else
stx[1]
-- antiquotation node kinds are formed from the original node kind (if any) plus "antiquot"
def isAntiquot : Syntax → Bool
| Syntax.node (Name.str _ "antiquot" _) _ => true
| _ => false
def mkAntiquotNode (term : Syntax) (nesting := 0) (name : Option String := none) (kind := Name.anonymous) : Syntax :=
let nesting := mkNullNode (mkArray nesting (mkAtom "$"))
let term := match term.isIdent with
| true => term
| false => mkNode `antiquotNestedExpr #[mkAtom "(", term, mkAtom ")"]
let name := match name with
| some name => mkNode `antiquotName #[mkAtom ":", mkAtom name]
| none => mkNullNode
mkNode (kind ++ `antiquot) #[mkAtom "$", nesting, term, name]
-- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. Also works for antiquotation splices.
def isEscapedAntiquot (stx : Syntax) : Bool :=
!stx[1].getArgs.isEmpty
-- Also works for antiquotation splices.
def unescapeAntiquot (stx : Syntax) : Syntax :=
if isAntiquot stx then
stx.setArg 1 $ mkNullNode stx[1].getArgs.pop
else
stx
-- Also works for token antiquotations.
def getAntiquotTerm (stx : Syntax) : Syntax :=
let e := if stx.isAntiquot then stx[2] else stx[3]
if e.isIdent then e
else
-- `e` is from `"(" >> termParser >> ")"`
e[1]
def antiquotKind? : Syntax → Option SyntaxNodeKind
| Syntax.node (Name.str k "antiquot" _) args =>
if args[3].isOfKind `antiquotName then some k
else
-- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`)
some Name.anonymous
| _ => none
-- An "antiquotation splice" is something like `$[...]?` or `$[...]*`.
def antiquotSpliceKind? : Syntax → Option SyntaxNodeKind
| Syntax.node (Name.str k "antiquot_scope" _) args => some k
| _ => none
def isAntiquotSplice (stx : Syntax) : Bool :=
antiquotSpliceKind? stx |>.isSome
def getAntiquotSpliceContents (stx : Syntax) : Array Syntax :=
stx[3].getArgs
-- `$[..],*` or `$x,*` ~> `,*`
def getAntiquotSpliceSuffix (stx : Syntax) : Syntax :=
if stx.isAntiquotSplice then
stx[5]
else
stx[1]
def mkAntiquotSpliceNode (kind : SyntaxNodeKind) (contents : Array Syntax) (suffix : String) (nesting := 0) : Syntax :=
let nesting := mkNullNode (mkArray nesting (mkAtom "$"))
mkNode (kind ++ `antiquot_splice) #[mkAtom "$", nesting, mkAtom "[", mkNullNode contents, mkAtom "]", mkAtom suffix]
-- `$x,*` etc.
def antiquotSuffixSplice? : Syntax → Option SyntaxNodeKind
| Syntax.node (Name.str k "antiquot_suffix_splice" _) args => some k
| _ => none
def isAntiquotSuffixSplice (stx : Syntax) : Bool :=
antiquotSuffixSplice? stx |>.isSome
-- `$x` in the example above
def getAntiquotSuffixSpliceInner (stx : Syntax) : Syntax :=
stx[0]
def mkAntiquotSuffixSpliceNode (kind : SyntaxNodeKind) (inner : Syntax) (suffix : String) : Syntax :=
mkNode (kind ++ `antiquot_suffix_splice) #[inner, mkAtom suffix]
def isTokenAntiquot (stx : Syntax) : Bool :=
stx.isOfKind `token_antiquot
def isAnyAntiquot (stx : Syntax) : Bool :=
stx.isAntiquot || stx.isAntiquotSplice || stx.isAntiquotSuffixSplice || stx.isTokenAntiquot
end Syntax
end Lean
|
c712648de1b55a3264c75e97d88de49d4117bd6e | 6065973b1fa7bbacba932011c9e2f32bf7bdd6c1 | /src/data/list/nodup_equiv_fin.lean | 347d954720de00e66b80fcec5a06b9af6ef85335 | [
"Apache-2.0"
] | permissive | khmacdonald/mathlib | 90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb | 3669cb35c578441812ad30fd967d21a94b6f387e | refs/heads/master | 1,675,863,801,090 | 1,609,761,876,000 | 1,609,761,876,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,397 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import data.list.sort
import data.fin
/-!
# Isomorphism between `fin (length l)` and `{x // x ∈ l}`
Given a list `l,
* if `l` has no duplicates, then `list.nodup.nth_le_equiv` is the bijection between `fin (length l)`
and `{x // x ∈ l}` sending `⟨i, hi⟩` to `⟨nth_le l i hi, _⟩` with the inverse sending `⟨x, hx⟩` to
`⟨index_of x l, _⟩`;
* if `l` is sorted w.r.t. `(<)`, then `list.sorted.nth_le_iso` is the same bijection reinterpreted
as an `order_iso`.
-/
namespace list
variable {α : Type*}
namespace nodup
variable [decidable_eq α]
/-- If `l` has no duplicates, then `list.nth_le` defines a bijection between `fin (length l)` and
the set of elements of `l`. -/
def nth_le_equiv (l : list α) (H : nodup l) : fin (length l) ≃ {x // x ∈ l} :=
{ to_fun := λ i, ⟨nth_le l i i.2, nth_le_mem l i i.2⟩,
inv_fun := λ x, ⟨index_of ↑x l, index_of_lt_length.2 x.2⟩,
left_inv := λ i, by simp [H],
right_inv := λ x, by simp }
variables {l : list α} (H : nodup l) (x : {x // x ∈ l}) (i : fin (length l))
@[simp] lemma coe_nth_le_equiv_apply : (H.nth_le_equiv l i : α) = nth_le l i i.2 := rfl
@[simp] lemma coe_nth_le_equiv_symm_apply : ((H.nth_le_equiv l).symm x : ℕ) = index_of ↑x l := rfl
end nodup
namespace sorted
variables [preorder α] {l : list α}
lemma nth_le_mono (h : l.sorted (≤)) :
monotone (λ i : fin l.length, l.nth_le i i.2) :=
λ i j, nth_le_of_sorted_of_le h
lemma nth_le_strict_mono (h : l.sorted (<)) :
strict_mono (λ i : fin l.length, l.nth_le i i.2) :=
λ i j, pairwise_iff_nth_le.1 h i j j.2
variable [decidable_eq α]
/-- If `l` is a list sorted w.r.t. `(<)`, then `list.nth_le` defines an order isomorphism between
`fin (length l)` and the set of elements of `l`. -/
def nth_le_iso (l : list α) (H : sorted (<) l) : fin (length l) ≃o {x // x ∈ l} :=
{ to_equiv := H.nodup.nth_le_equiv l,
map_rel_iff' := λ i j, H.nth_le_strict_mono.le_iff_le.symm }
variables (H : sorted (<) l) {x : {x // x ∈ l}} {i : fin l.length}
@[simp] lemma coe_nth_le_iso_apply : (H.nth_le_iso l i : α) = nth_le l i i.2 := rfl
@[simp] lemma coe_nth_le_iso_symm_apply : ((H.nth_le_iso l).symm x : ℕ) = index_of ↑x l := rfl
end sorted
end list
|
58a7e1ba01b9fa59ee603059f5c84471aad8d4e3 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/simp_proof_failure.lean | 11bf1b66d3b362ce619f3444e746d22e1191fd8e | [
"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 | 230 | lean | def α : Type := ℕ → ℕ
set_option trace.app_builder true
example (x y : α) (H : x = y) (n : ℕ) : x n = y n :=
by simp [H]
example (x y : α) (H₁ : x = y) (m n : ℕ) (H₂ : m = n) : x m = y n :=
by simp [H₁, H₂]
|
dc13bbc4c339edac5116a81fce0b7432a2be70c5 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/analysis/box_integral/partition/basic.lean | fd35ecf8078b6cb9139e5dad9ea0e050738e4d69 | [
"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 | 29,302 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.box_integral.box.basic
/-!
# Partitions of rectangular boxes in `ℝⁿ`
In this file we define (pre)partitions of rectangular boxes in `ℝⁿ`. A partition of a box `I` in
`ℝⁿ` (see `box_integral.prepartition` and `box_integral.prepartition.is_partition`) is a finite set
of pairwise disjoint boxes such that their union is exactly `I`. We use `boxes : finset (box ι)` to
store the set of boxes.
Many lemmas about box integrals deal with pairwise disjoint collections of subboxes, so we define a
structure `box_integral.prepartition (I : box_integral.box ι)` that stores a collection of boxes
such that
* each box `J ∈ boxes` is a subbox of `I`;
* the boxes are pairwise disjoint as sets in `ℝⁿ`.
Then we define a predicate `box_integral.prepartition.is_partition`; `π.is_partition` means that the
boxes of `π` actually cover the whole `I`. We also define some operations on prepartitions:
* `box_integral.partition.bUnion`: split each box of a partition into smaller boxes;
* `box_integral.partition.restrict`: restrict a partition to a smaller box.
We also define a `semilattice_inf_top` structure on `box_integral.partition I` for all
`I : box_integral.box ι`.
## Tags
rectangular box, partition
-/
open set finset function
open_locale classical nnreal big_operators
noncomputable theory
namespace box_integral
variables {ι : Type*}
/-- A prepartition of `I : box_integral.box ι` is a finite set of pairwise disjoint subboxes of
`I`. -/
structure prepartition (I : box ι) :=
(boxes : finset (box ι))
(le_of_mem' : ∀ J ∈ boxes, J ≤ I)
(pairwise_disjoint : set.pairwise ↑boxes (disjoint on (coe : box ι → set (ι → ℝ))))
namespace prepartition
variables {I J J₁ J₂ : box ι} (π : prepartition I) {π₁ π₂ : prepartition I} {x : ι → ℝ}
instance : has_mem (box ι) (prepartition I) := ⟨λ J π, J ∈ π.boxes⟩
@[simp] lemma mem_boxes : J ∈ π.boxes ↔ J ∈ π := iff.rfl
@[simp] lemma mem_mk {s h₁ h₂} : J ∈ (mk s h₁ h₂ : prepartition I) ↔ J ∈ s := iff.rfl
lemma disjoint_coe_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (h : J₁ ≠ J₂) :
disjoint (J₁ : set (ι → ℝ)) J₂ :=
π.pairwise_disjoint J₁ h₁ J₂ h₂ h
lemma eq_of_mem_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hx₁ : x ∈ J₁) (hx₂ : x ∈ J₂) :
J₁ = J₂ :=
by_contra $ λ H, π.disjoint_coe_of_mem h₁ h₂ H ⟨hx₁, hx₂⟩
lemma eq_of_le_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle₁ : J ≤ J₁) (hle₂ : J ≤ J₂) :
J₁ = J₂ :=
π.eq_of_mem_of_mem h₁ h₂ (hle₁ J.upper_mem) (hle₂ J.upper_mem)
lemma eq_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle : J₁ ≤ J₂) : J₁ = J₂ :=
π.eq_of_le_of_le h₁ h₂ le_rfl hle
lemma le_of_mem (hJ : J ∈ π) : J ≤ I := π.le_of_mem' J hJ
lemma lower_le_lower (hJ : J ∈ π) : I.lower ≤ J.lower := box.antitone_lower (π.le_of_mem hJ)
lemma upper_le_upper (hJ : J ∈ π) : J.upper ≤ I.upper := box.monotone_upper (π.le_of_mem hJ)
lemma injective_boxes : function.injective (boxes : prepartition I → finset (box ι)) :=
by { rintro ⟨s₁, h₁, h₁'⟩ ⟨s₂, h₂, h₂'⟩ (rfl : s₁ = s₂), refl }
@[ext] lemma ext (h : ∀ J, J ∈ π₁ ↔ J ∈ π₂) : π₁ = π₂ := injective_boxes $ finset.ext h
/-- The singleton prepartition `{J}`, `J ≤ I`. -/
@[simps] def single (I J : box ι) (h : J ≤ I) : prepartition I :=
⟨{J}, by simpa, by simp⟩
@[simp] lemma mem_single {J'} (h : J ≤ I) : J' ∈ single I J h ↔ J' = J := mem_singleton
/-- We say that `π ≤ π'` if each box of `π` is a subbox of some box of `π'`. -/
instance : has_le (prepartition I) := ⟨λ π π', ∀ ⦃I⦄, I ∈ π → ∃ I' ∈ π', I ≤ I'⟩
instance : partial_order (prepartition I) :=
{ le := (≤),
le_refl := λ π I hI, ⟨I, hI, le_rfl⟩,
le_trans := λ π₁ π₂ π₃ h₁₂ h₂₃ I₁ hI₁,
let ⟨I₂, hI₂, hI₁₂⟩ := h₁₂ hI₁, ⟨I₃, hI₃, hI₂₃⟩ := h₂₃ hI₂ in ⟨I₃, hI₃, hI₁₂.trans hI₂₃⟩,
le_antisymm :=
begin
suffices : ∀ {π₁ π₂ : prepartition I}, π₁ ≤ π₂ → π₂ ≤ π₁ → π₁.boxes ⊆ π₂.boxes,
from λ π₁ π₂ h₁ h₂, injective_boxes (subset.antisymm (this h₁ h₂) (this h₂ h₁)),
intros π₁ π₂ h₁ h₂ J hJ,
rcases h₁ hJ with ⟨J', hJ', hle⟩, rcases h₂ hJ' with ⟨J'', hJ'', hle'⟩,
obtain rfl : J = J'', from π₁.eq_of_le hJ hJ'' (hle.trans hle'),
obtain rfl : J' = J, from le_antisymm ‹_› ‹_›,
assumption
end }
instance : order_top (prepartition I) :=
{ top := single I I le_rfl,
le_top := λ π J hJ, ⟨I, by simp, π.le_of_mem hJ⟩ }
instance : order_bot (prepartition I) :=
{ bot := ⟨∅, λ J hJ, false.elim hJ, λ J hJ, false.elim hJ⟩,
bot_le := λ π J hJ, false.elim hJ }
instance : inhabited (prepartition I) := ⟨⊤⟩
lemma le_def : π₁ ≤ π₂ ↔ ∀ J ∈ π₁, ∃ J' ∈ π₂, J ≤ J' := iff.rfl
@[simp] lemma mem_top : J ∈ (⊤ : prepartition I) ↔ J = I := mem_singleton
@[simp] lemma top_boxes : (⊤ : prepartition I).boxes = {I} := rfl
@[simp] lemma not_mem_bot : J ∉ (⊥ : prepartition I) := id
@[simp] lemma bot_boxes : (⊥ : prepartition I).boxes = ∅ := rfl
/-- An auxiliary lemma used to prove that the same point can't belong to more than
`2 ^ fintype.card ι` closed boxes of a prepartition. -/
lemma inj_on_set_of_mem_Icc_set_of_lower_eq (x : ι → ℝ) :
inj_on (λ J : box ι, {i | J.lower i = x i}) {J | J ∈ π ∧ x ∈ J.Icc} :=
begin
rintros J₁ ⟨h₁, hx₁⟩ J₂ ⟨h₂, hx₂⟩ (H : {i | J₁.lower i = x i} = {i | J₂.lower i = x i}),
suffices : ∀ i, (Ioc (J₁.lower i) (J₁.upper i) ∩ Ioc (J₂.lower i) (J₂.upper i)).nonempty,
{ choose y hy₁ hy₂,
exact π.eq_of_mem_of_mem h₁ h₂ hy₁ hy₂ },
intro i,
simp only [set.ext_iff, mem_set_of_eq] at H,
cases (hx₁.1 i).eq_or_lt with hi₁ hi₁,
{ have hi₂ : J₂.lower i = x i, from (H _).1 hi₁,
have H₁ : x i < J₁.upper i, by simpa only [hi₁] using J₁.lower_lt_upper i,
have H₂ : x i < J₂.upper i, by simpa only [hi₂] using J₂.lower_lt_upper i,
rw [Ioc_inter_Ioc, hi₁, hi₂, sup_idem, set.nonempty_Ioc],
exact lt_min H₁ H₂ },
{ have hi₂ : J₂.lower i < x i, from (hx₂.1 i).lt_of_ne (mt (H _).2 hi₁.ne),
exact ⟨x i, ⟨hi₁, hx₁.2 i⟩, ⟨hi₂, hx₂.2 i⟩⟩ }
end
/-- The set of boxes of a prepartition that contain `x` in their closures has cardinality
at most `2 ^ fintype.card ι`. -/
lemma card_filter_mem_Icc_le [fintype ι] (x : ι → ℝ) :
(π.boxes.filter (λ J : box ι, x ∈ J.Icc)).card ≤ 2 ^ fintype.card ι :=
begin
rw [← fintype.card_set],
refine finset.card_le_card_of_inj_on (λ J : box ι, {i | J.lower i = x i})
(λ _ _, finset.mem_univ _) _,
simpa only [finset.mem_filter] using π.inj_on_set_of_mem_Icc_set_of_lower_eq x
end
/-- Given a prepartition `π : box_integral.prepartition I`, `π.Union` is the part of `I` covered by
the boxes of `π`. -/
protected def Union : set (ι → ℝ) := ⋃ J ∈ π, ↑J
lemma Union_def : π.Union = ⋃ J ∈ π, ↑J := rfl
lemma Union_def' : π.Union = ⋃ J ∈ π.boxes, ↑J := rfl
@[simp] lemma mem_Union : x ∈ π.Union ↔ ∃ J ∈ π, x ∈ J := set.mem_bUnion_iff
@[simp] lemma Union_single (h : J ≤ I) : (single I J h).Union = J := by simp [Union_def]
@[simp] lemma Union_top : (⊤ : prepartition I).Union = I := by simp [prepartition.Union]
@[simp] lemma Union_eq_empty : π₁.Union = ∅ ↔ π₁ = ⊥ :=
by simp [← injective_boxes.eq_iff, finset.ext_iff, prepartition.Union, imp_false]
@[simp] lemma Union_bot : (⊥ : prepartition I).Union = ∅ := Union_eq_empty.2 rfl
lemma subset_Union (h : J ∈ π) : ↑J ⊆ π.Union := subset_bUnion_of_mem h
lemma Union_subset : π.Union ⊆ I := bUnion_subset π.le_of_mem'
@[mono] lemma Union_mono (h : π₁ ≤ π₂) : π₁.Union ⊆ π₂.Union :=
λ x hx, let ⟨J₁, hJ₁, hx⟩ := π₁.mem_Union.1 hx, ⟨J₂, hJ₂, hle⟩ := h hJ₁
in π₂.mem_Union.2 ⟨J₂, hJ₂, hle hx⟩
lemma disjoint_boxes_of_disjoint_Union (h : disjoint π₁.Union π₂.Union) :
disjoint π₁.boxes π₂.boxes :=
finset.disjoint_left.2 $ λ J h₁ h₂, h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂)
⟨J.upper_mem, J.upper_mem⟩
lemma le_iff_nonempty_imp_le_and_Union_subset : π₁ ≤ π₂ ↔
(∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J') ∧ π₁.Union ⊆ π₂.Union :=
begin
fsplit,
{ refine λ H, ⟨λ J hJ J' hJ' Hne, _, Union_mono H⟩,
rcases H hJ with ⟨J'', hJ'', Hle⟩, rcases Hne with ⟨x, hx, hx'⟩,
rwa π₂.eq_of_mem_of_mem hJ' hJ'' hx' (Hle hx) },
{ rintro ⟨H, HU⟩ J hJ, simp only [set.subset_def, mem_Union] at HU,
rcases HU J.upper ⟨J, hJ, J.upper_mem⟩ with ⟨J₂, hJ₂, hx⟩,
exact ⟨J₂, hJ₂, H _ hJ _ hJ₂ ⟨_, J.upper_mem, hx⟩⟩ }
end
lemma eq_of_boxes_subset_Union_superset (h₁ : π₁.boxes ⊆ π₂.boxes) (h₂ : π₂.Union ⊆ π₁.Union) :
π₁ = π₂ :=
le_antisymm (λ J hJ, ⟨J, h₁ hJ, le_rfl⟩) $ le_iff_nonempty_imp_le_and_Union_subset.2
⟨λ J₁ hJ₁ J₂ hJ₂ Hne, (π₂.eq_of_mem_of_mem hJ₁ (h₁ hJ₂) Hne.some_spec.1 Hne.some_spec.2).le, h₂⟩
/-- Given a prepartition `π` of a box `I` and a collection of prepartitions `πi J` of all boxes
`J ∈ π`, returns the prepartition of `I` into the union of the boxes of all `πi J`.
Though we only use the values of `πi` on the boxes of `π`, we require `πi` to be a globally defined
function. -/
@[simps] def bUnion (πi : Π J : box ι, prepartition J) : prepartition I :=
{ boxes := π.boxes.bUnion $ λ J, (πi J).boxes,
le_of_mem' := λ J hJ,
begin
simp only [finset.mem_bUnion, exists_prop, mem_boxes] at hJ,
rcases hJ with ⟨J', hJ', hJ⟩,
exact ((πi J').le_of_mem hJ).trans (π.le_of_mem hJ')
end,
pairwise_disjoint :=
begin
simp only [set.pairwise, finset.mem_coe, finset.mem_bUnion],
rintro J₁' ⟨J₁, hJ₁, hJ₁'⟩ J₂' ⟨J₂, hJ₂, hJ₂'⟩ Hne x ⟨hx₁, hx₂⟩, apply Hne,
obtain rfl : J₁ = J₂,
from π.eq_of_mem_of_mem hJ₁ hJ₂ ((πi J₁).le_of_mem hJ₁' hx₁)
((πi J₂).le_of_mem hJ₂' hx₂),
exact (πi J₁).eq_of_mem_of_mem hJ₁' hJ₂' hx₁ hx₂
end }
variables {πi πi₁ πi₂ : Π J : box ι, prepartition J}
@[simp] lemma mem_bUnion : J ∈ π.bUnion πi ↔ ∃ J' ∈ π, J ∈ πi J' :=
by simp [bUnion]
lemma bUnion_le (πi : Π J, prepartition J) : π.bUnion πi ≤ π :=
λ J hJ, let ⟨J', hJ', hJ⟩ := π.mem_bUnion.1 hJ in ⟨J', hJ', (πi J').le_of_mem hJ⟩
@[simp] lemma bUnion_top : π.bUnion (λ _, ⊤) = π := by { ext, simp }
@[congr] lemma bUnion_congr (h : π₁ = π₂) (hi : ∀ J ∈ π₁, πi₁ J = πi₂ J) :
π₁.bUnion πi₁ = π₂.bUnion πi₂ :=
by { subst π₂, ext J, simp [hi] { contextual := tt } }
lemma bUnion_congr_of_le (h : π₁ = π₂) (hi : ∀ J ≤ I, πi₁ J = πi₂ J) :
π₁.bUnion πi₁ = π₂.bUnion πi₂ :=
bUnion_congr h $ λ J hJ, hi J (π₁.le_of_mem hJ)
@[simp] lemma Union_bUnion (πi : Π J : box ι, prepartition J) :
(π.bUnion πi).Union = ⋃ J ∈ π, (πi J).Union :=
by simp [prepartition.Union]
@[simp] lemma sum_bUnion_boxes {M : Type*} [add_comm_monoid M] (π : prepartition I)
(πi : Π J, prepartition J) (f : box ι → M) :
∑ J in π.boxes.bUnion (λ J, (πi J).boxes), f J = ∑ J in π.boxes, ∑ J' in (πi J).boxes, f J' :=
begin
refine finset.sum_bUnion (λ J₁ h₁ J₂ h₂ hne, finset.disjoint_left.2 $ λ J' h₁' h₂', _),
exact hne (π.eq_of_le_of_le h₁ h₂ ((πi J₁).le_of_mem h₁') ((πi J₂).le_of_mem h₂'))
end
/-- Given a box `J ∈ π.bUnion πi`, returns the box `J' ∈ π` such that `J ∈ πi J'`.
For `J ∉ π.bUnion πi`, returns `I`. -/
def bUnion_index (πi : Π J, prepartition J) (J : box ι) :
box ι :=
if hJ : J ∈ π.bUnion πi then (π.mem_bUnion.1 hJ).some else I
lemma bUnion_index_mem (hJ : J ∈ π.bUnion πi) :
π.bUnion_index πi J ∈ π :=
by { rw [bUnion_index, dif_pos hJ], exact (π.mem_bUnion.1 hJ).some_spec.fst }
lemma bUnion_index_le (πi : Π J, prepartition J) (J : box ι) : π.bUnion_index πi J ≤ I :=
begin
by_cases hJ : J ∈ π.bUnion πi,
{ exact π.le_of_mem (π.bUnion_index_mem hJ) },
{ rw [bUnion_index, dif_neg hJ], exact le_rfl }
end
lemma mem_bUnion_index (hJ : J ∈ π.bUnion πi) : J ∈ πi (π.bUnion_index πi J) :=
by convert (π.mem_bUnion.1 hJ).some_spec.snd; exact dif_pos hJ
lemma le_bUnion_index (hJ : J ∈ π.bUnion πi) : J ≤ π.bUnion_index πi J :=
le_of_mem _ (π.mem_bUnion_index hJ)
/-- Uniqueness property of `box_integral.partition.bUnion_index`. -/
lemma bUnion_index_of_mem (hJ : J ∈ π) {J'} (hJ' : J' ∈ πi J) : π.bUnion_index πi J' = J :=
have J' ∈ π.bUnion πi, from π.mem_bUnion.2 ⟨J, hJ, hJ'⟩,
π.eq_of_le_of_le (π.bUnion_index_mem this) hJ (π.le_bUnion_index this) (le_of_mem _ hJ')
lemma bUnion_assoc (πi : Π J, prepartition J) (πi' : box ι → Π J : box ι, prepartition J) :
π.bUnion (λ J, (πi J).bUnion (πi' J)) = (π.bUnion πi).bUnion (λ J, πi' (π.bUnion_index πi J) J) :=
begin
ext J,
simp only [mem_bUnion, exists_prop],
fsplit,
{ rintro ⟨J₁, hJ₁, J₂, hJ₂, hJ⟩,
refine ⟨J₂, ⟨J₁, hJ₁, hJ₂⟩, _⟩,
rwa π.bUnion_index_of_mem hJ₁ hJ₂ },
{ rintro ⟨J₁, ⟨J₂, hJ₂, hJ₁⟩, hJ⟩,
refine ⟨J₂, hJ₂, J₁, hJ₁, _⟩,
rwa π.bUnion_index_of_mem hJ₂ hJ₁ at hJ }
end
/-- Create a `box_integral.prepartition` from a collection of possibly empty boxes by filtering out
the empty one if it exists. -/
def of_with_bot (boxes : finset (with_bot (box ι)))
(le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I)
(pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) :
prepartition I :=
{ boxes := boxes.erase_none,
le_of_mem' := λ J hJ,
begin
rw mem_erase_none at hJ,
simpa only [with_bot.some_eq_coe, with_bot.coe_le_coe] using le_of_mem _ hJ
end,
pairwise_disjoint := λ J₁ h₁ J₂ h₂ hne,
begin
simp only [mem_coe, mem_erase_none] at h₁ h₂,
exact box.disjoint_coe.1 (pairwise_disjoint _ h₁ _ h₂ (mt option.some_inj.1 hne))
end }
@[simp] lemma mem_of_with_bot {boxes : finset (with_bot (box ι))} {h₁ h₂} :
J ∈ (of_with_bot boxes h₁ h₂ : prepartition I) ↔ (J : with_bot (box ι)) ∈ boxes :=
mem_erase_none
@[simp] lemma Union_of_with_bot (boxes : finset (with_bot (box ι)))
(le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I)
(pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) :
(of_with_bot boxes le_of_mem pairwise_disjoint).Union = ⋃ J ∈ boxes, ↑J :=
begin
suffices : (⋃ (J : box ι) (hJ : ↑J ∈ boxes), ↑J) = ⋃ J ∈ boxes, ↑J,
by simpa [of_with_bot, prepartition.Union],
simp only [← box.bUnion_coe_eq_coe, @Union_comm _ _ (box ι), @Union_comm _ _ (@eq _ _ _),
Union_Union_eq_right]
end
lemma of_with_bot_le {boxes : finset (with_bot (box ι))}
{le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I}
{pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint}
(H : ∀ J ∈ boxes, J ≠ ⊥ → ∃ J' ∈ π, J ≤ ↑J') :
of_with_bot boxes le_of_mem pairwise_disjoint ≤ π :=
have ∀ (J : box ι), ↑J ∈ boxes → ∃ J' ∈ π, J ≤ J',
from λ J hJ, by simpa only [with_bot.coe_le_coe] using H J hJ (with_bot.coe_ne_bot J),
by simpa [of_with_bot, le_def]
lemma le_of_with_bot {boxes : finset (with_bot (box ι))}
{le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I}
{pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint}
(H : ∀ J ∈ π, ∃ J' ∈ boxes, ↑J ≤ J') :
π ≤ of_with_bot boxes le_of_mem pairwise_disjoint :=
begin
intros J hJ,
rcases H J hJ with ⟨J', J'mem, hle⟩,
lift J' to box ι using ne_bot_of_le_ne_bot (with_bot.coe_ne_bot _) hle,
exact ⟨J', mem_of_with_bot.2 J'mem, with_bot.coe_le_coe.1 hle⟩
end
lemma of_with_bot_mono {boxes₁ : finset (with_bot (box ι))}
{le_of_mem₁ : ∀ J ∈ boxes₁, (J : with_bot (box ι)) ≤ I}
{pairwise_disjoint₁ : set.pairwise (boxes₁ : set (with_bot (box ι))) disjoint}
{boxes₂ : finset (with_bot (box ι))}
{le_of_mem₂ : ∀ J ∈ boxes₂, (J : with_bot (box ι)) ≤ I}
{pairwise_disjoint₂ : set.pairwise (boxes₂ : set (with_bot (box ι))) disjoint}
(H : ∀ J ∈ boxes₁, J ≠ ⊥ → ∃ J' ∈ boxes₂, J ≤ J') :
of_with_bot boxes₁ le_of_mem₁ pairwise_disjoint₁ ≤
of_with_bot boxes₂ le_of_mem₂ pairwise_disjoint₂ :=
le_of_with_bot _ $ λ J hJ, H J (mem_of_with_bot.1 hJ) (with_bot.coe_ne_bot _)
lemma sum_of_with_bot {M : Type*} [add_comm_monoid M]
(boxes : finset (with_bot (box ι)))
(le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I)
(pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint)
(f : box ι → M) :
∑ J in (of_with_bot boxes le_of_mem pairwise_disjoint).boxes, f J =
∑ J in boxes, option.elim J 0 f :=
finset.sum_erase_none _ _
/-- Restrict a prepartition to a box. -/
def restrict (π : prepartition I) (J : box ι) :
prepartition J :=
of_with_bot (π.boxes.image (λ J', J ⊓ J'))
(λ J' hJ', by { rcases finset.mem_image.1 hJ' with ⟨J', -, rfl⟩, exact inf_le_left })
begin
simp only [set.pairwise, on_fun, finset.mem_coe, finset.mem_image],
rintro _ ⟨J₁, h₁, rfl⟩ _ ⟨J₂, h₂, rfl⟩ Hne,
have : J₁ ≠ J₂, by { rintro rfl, exact Hne rfl },
exact ((box.disjoint_coe.2 $ π.disjoint_coe_of_mem h₁ h₂ this).inf_left' _).inf_right' _
end
@[simp] lemma mem_restrict : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : with_bot (box ι)) = J ⊓ J' :=
by simp [restrict, eq_comm]
lemma mem_restrict' : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : set (ι → ℝ)) = J ∩ J' :=
by simp only [mem_restrict, ← box.with_bot_coe_inj, box.coe_inf, box.coe_coe]
@[mono] lemma restrict_mono {π₁ π₂ : prepartition I} (Hle : π₁ ≤ π₂) :
π₁.restrict J ≤ π₂.restrict J :=
begin
refine of_with_bot_mono (λ J₁ hJ₁ hne, _),
rw finset.mem_image at hJ₁, rcases hJ₁ with ⟨J₁, hJ₁, rfl⟩,
rcases Hle hJ₁ with ⟨J₂, hJ₂, hle⟩,
exact ⟨_, finset.mem_image_of_mem _ hJ₂, inf_le_inf_left _ $ with_bot.coe_le_coe.2 hle⟩
end
lemma monotone_restrict : monotone (λ π : prepartition I, restrict π J) :=
λ π₁ π₂, restrict_mono
/-- Restricting to a larger box does not change the set of boxes. We cannot claim equality
of prepartitions because they have different types. -/
lemma restrict_boxes_of_le (π : prepartition I) (h : I ≤ J) :
(π.restrict J).boxes = π.boxes :=
begin
simp only [restrict, of_with_bot, erase_none_eq_bUnion],
refine finset.image_bUnion.trans _,
refine (finset.bUnion_congr rfl _).trans finset.bUnion_singleton_eq_self,
intros J' hJ',
rw [inf_of_le_right, ← with_bot.some_eq_coe, option.to_finset_some],
exact with_bot.coe_le_coe.2 ((π.le_of_mem hJ').trans h)
end
@[simp] lemma restrict_self : π.restrict I = π :=
injective_boxes $ restrict_boxes_of_le π le_rfl
@[simp] lemma Union_restrict : (π.restrict J).Union = J ∩ π.Union :=
by simp [restrict, ← inter_Union, ← Union_def]
@[simp] lemma restrict_bUnion (πi : Π J, prepartition J) (hJ : J ∈ π) :
(π.bUnion πi).restrict J = πi J :=
begin
refine (eq_of_boxes_subset_Union_superset (λ J₁ h₁, _) _).symm,
{ refine (mem_restrict _).2 ⟨J₁, π.mem_bUnion.2 ⟨J, hJ, h₁⟩, (inf_of_le_right _).symm⟩,
exact with_bot.coe_le_coe.2 (le_of_mem _ h₁) },
{ simp only [Union_restrict, Union_bUnion, set.subset_def, set.mem_inter_eq, set.mem_Union],
rintro x ⟨hxJ, J₁, h₁, hx⟩,
obtain rfl : J = J₁, from π.eq_of_mem_of_mem hJ h₁ hxJ (Union_subset _ hx),
exact hx }
end
lemma bUnion_le_iff {πi : Π J, prepartition J} {π' : prepartition I} :
π.bUnion πi ≤ π' ↔ ∀ J ∈ π, πi J ≤ π'.restrict J :=
begin
fsplit; intros H J hJ,
{ rw ← π.restrict_bUnion πi hJ, exact restrict_mono H },
{ rw mem_bUnion at hJ, rcases hJ with ⟨J₁, h₁, hJ⟩,
rcases H J₁ h₁ hJ with ⟨J₂, h₂, Hle⟩,
rcases π'.mem_restrict.mp h₂ with ⟨J₃, h₃, H⟩,
exact ⟨J₃, h₃, Hle.trans $ with_bot.coe_le_coe.1 $ H.trans_le inf_le_right⟩ }
end
lemma le_bUnion_iff {πi : Π J, prepartition J} {π' : prepartition I} :
π' ≤ π.bUnion πi ↔ π' ≤ π ∧ ∀ J ∈ π, π'.restrict J ≤ πi J :=
begin
refine ⟨λ H, ⟨H.trans (π.bUnion_le πi), λ J hJ, _⟩, _⟩,
{ rw ← π.restrict_bUnion πi hJ, exact restrict_mono H },
{ rintro ⟨H, Hi⟩ J' hJ',
rcases H hJ' with ⟨J, hJ, hle⟩,
have : J' ∈ π'.restrict J,
from π'.mem_restrict.2 ⟨J', hJ', (inf_of_le_right $ with_bot.coe_le_coe.2 hle).symm⟩,
rcases Hi J hJ this with ⟨Ji, hJi, hlei⟩,
exact ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hlei⟩ }
end
instance : has_inf (prepartition I) :=
⟨λ π₁ π₂, π₁.bUnion (λ J, π₂.restrict J)⟩
lemma inf_def (π₁ π₂ : prepartition I) :
π₁ ⊓ π₂ = π₁.bUnion (λ J, π₂.restrict J) :=
rfl
@[simp] lemma mem_inf {π₁ π₂ : prepartition I} :
J ∈ π₁ ⊓ π₂ ↔ ∃ (J₁ ∈ π₁) (J₂ ∈ π₂), (J : with_bot (box ι)) = J₁ ⊓ J₂ :=
by simp only [inf_def, mem_bUnion, mem_restrict]
@[simp] lemma Union_inf (π₁ π₂ : prepartition I) : (π₁ ⊓ π₂).Union = π₁.Union ∩ π₂.Union :=
by simp only [inf_def, Union_bUnion, Union_restrict, ← Union_inter, ← Union_def]
instance : semilattice_inf_top (prepartition I) :=
{ inf_le_left := λ π₁ π₂, π₁.bUnion_le _,
inf_le_right := λ π₁ π₂, (bUnion_le_iff _).2 (λ J hJ, le_rfl),
le_inf := λ π π₁ π₂ h₁ h₂, π₁.le_bUnion_iff.2 ⟨h₁, λ J hJ, restrict_mono h₂⟩,
..prepartition.partial_order, .. prepartition.order_top, .. prepartition.has_inf }
instance : semilattice_inf_bot (prepartition I) :=
{ .. prepartition.order_bot, .. prepartition.semilattice_inf_top }
/-- The prepartition with boxes `{J ∈ π | p J}`. -/
@[simps] def filter (π : prepartition I) (p : box ι → Prop) : prepartition I :=
{ boxes := π.boxes.filter p,
le_of_mem' := λ J hJ, π.le_of_mem (mem_filter.1 hJ).1,
pairwise_disjoint := λ J₁ h₁ J₂ h₂, π.disjoint_coe_of_mem (mem_filter.1 h₁).1
(mem_filter.1 h₂).1 }
@[simp] lemma mem_filter {p : box ι → Prop} : J ∈ π.filter p ↔ J ∈ π ∧ p J := finset.mem_filter
lemma filter_le (π : prepartition I) (p : box ι → Prop) : π.filter p ≤ π :=
λ J hJ, let ⟨hπ, hp⟩ := π.mem_filter.1 hJ in ⟨J, hπ, le_rfl⟩
lemma filter_of_true {p : box ι → Prop} (hp : ∀ J ∈ π, p J) : π.filter p = π :=
by { ext J, simpa using hp J }
@[simp] lemma filter_true : π.filter (λ _, true) = π := π.filter_of_true (λ _ _, trivial)
@[simp] lemma Union_filter_not (π : prepartition I) (p : box ι → Prop) :
(π.filter (λ J, ¬p J)).Union = π.Union \ (π.filter p).Union :=
begin
simp only [prepartition.Union],
convert (@set.bUnion_diff_bUnion_eq _ (box ι) π.boxes (π.filter p).boxes coe _).symm,
{ ext J x, simp { contextual := tt } },
{ convert π.pairwise_disjoint, simp }
end
lemma sum_fiberwise {α M} [add_comm_monoid M] (π : prepartition I) (f : box ι → α) (g : box ι → M) :
∑ y in π.boxes.image f, ∑ J in (π.filter (λ J, f J = y)).boxes, g J = ∑ J in π.boxes, g J :=
by convert sum_fiberwise_of_maps_to (λ _, finset.mem_image_of_mem f) g
/-- Union of two disjoint prepartitions. -/
@[simps] def disj_union (π₁ π₂ : prepartition I) (h : disjoint π₁.Union π₂.Union) :
prepartition I :=
{ boxes := π₁.boxes ∪ π₂.boxes,
le_of_mem' := λ J hJ, (finset.mem_union.1 hJ).elim π₁.le_of_mem π₂.le_of_mem,
pairwise_disjoint :=
suffices ∀ (J₁ ∈ π₁) (J₂ ∈ π₂), J₁ ≠ J₂ → disjoint (J₁ : set (ι → ℝ)) J₂,
by simpa [pairwise_union_of_symmetric (symmetric_disjoint.comap _), pairwise_disjoint],
λ J₁ h₁ J₂ h₂ _, h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂) }
@[simp] lemma mem_disj_union (H : disjoint π₁.Union π₂.Union) :
J ∈ π₁.disj_union π₂ H ↔ J ∈ π₁ ∨ J ∈ π₂ :=
finset.mem_union
@[simp] lemma Union_disj_union (h : disjoint π₁.Union π₂.Union) :
(π₁.disj_union π₂ h).Union = π₁.Union ∪ π₂.Union :=
by simp [disj_union, prepartition.Union, Union_or, Union_union_distrib]
@[simp] lemma sum_disj_union_boxes {M : Type*} [add_comm_monoid M]
(h : disjoint π₁.Union π₂.Union) (f : box ι → M) :
∑ J in π₁.boxes ∪ π₂.boxes, f J = ∑ J in π₁.boxes, f J + ∑ J in π₂.boxes, f J :=
sum_union $ disjoint_boxes_of_disjoint_Union h
section distortion
variable [fintype ι]
/-- The distortion of a prepartition is the maximum of the distortions of the boxes of this
prepartition. -/
def distortion : ℝ≥0 := π.boxes.sup box.distortion
lemma distortion_le_of_mem (h : J ∈ π) : J.distortion ≤ π.distortion :=
le_sup h
lemma distortion_le_iff {c : ℝ≥0} : π.distortion ≤ c ↔ ∀ J ∈ π, box.distortion J ≤ c :=
sup_le_iff
lemma distortion_bUnion (π : prepartition I) (πi : Π J, prepartition J) :
(π.bUnion πi).distortion = π.boxes.sup (λ J, (πi J).distortion) :=
sup_bUnion _ _
@[simp] lemma distortion_disj_union (h : disjoint π₁.Union π₂.Union) :
(π₁.disj_union π₂ h).distortion = max π₁.distortion π₂.distortion :=
sup_union
lemma distortion_of_const {c} (h₁ : π.boxes.nonempty) (h₂ : ∀ J ∈ π, box.distortion J = c) :
π.distortion = c :=
(sup_congr rfl h₂).trans (sup_const h₁ _)
@[simp] lemma distortion_top (I : box ι) : distortion (⊤ : prepartition I) = I.distortion :=
sup_singleton
@[simp] lemma distortion_bot (I : box ι) : distortion (⊥ : prepartition I) = 0 := sup_empty
end distortion
/-- A prepartition `π` of `I` is a partition if the boxes of `π` cover the whole `I`. -/
def is_partition (π : prepartition I) := ∀ x ∈ I, ∃ J ∈ π, x ∈ J
lemma is_partition_iff_Union_eq {π : prepartition I} : π.is_partition ↔ π.Union = I :=
by simp_rw [is_partition, set.subset.antisymm_iff, π.Union_subset, true_and, set.subset_def,
mem_Union, box.mem_coe]
@[simp] lemma is_partition_single_iff (h : J ≤ I) : is_partition (single I J h) ↔ J = I :=
by simp [is_partition_iff_Union_eq]
lemma is_partition_top (I : box ι) : is_partition (⊤ : prepartition I) :=
λ x hx, ⟨I, mem_top.2 rfl, hx⟩
namespace is_partition
variables {π}
lemma Union_eq (h : π.is_partition) : π.Union = I := is_partition_iff_Union_eq.1 h
lemma Union_subset (h : π.is_partition) (π₁ : prepartition I) : π₁.Union ⊆ π.Union :=
h.Union_eq.symm ▸ π₁.Union_subset
protected lemma exists_unique (h : π.is_partition) (hx : x ∈ I) :
∃! J ∈ π, x ∈ J :=
begin
rcases h x hx with ⟨J, h, hx⟩,
exact exists_unique.intro2 J h hx (λ J' h' hx', π.eq_of_mem_of_mem h' h hx' hx),
end
lemma nonempty_boxes (h : π.is_partition) : π.boxes.nonempty :=
let ⟨J, hJ, _⟩ := h _ I.upper_mem in ⟨J, hJ⟩
lemma eq_of_boxes_subset (h₁ : π₁.is_partition) (h₂ : π₁.boxes ⊆ π₂.boxes) : π₁ = π₂ :=
eq_of_boxes_subset_Union_superset h₂ $ h₁.Union_subset _
lemma le_iff (h : π₂.is_partition) :
π₁ ≤ π₂ ↔ ∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J' :=
le_iff_nonempty_imp_le_and_Union_subset.trans $ and_iff_left $ h.Union_subset _
protected lemma bUnion (h : is_partition π) (hi : ∀ J ∈ π, is_partition (πi J)) :
is_partition (π.bUnion πi) :=
λ x hx, let ⟨J, hJ, hxi⟩ := h x hx, ⟨Ji, hJi, hx⟩ := hi J hJ x hxi in
⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hx⟩
protected lemma restrict (h : is_partition π) (hJ : J ≤ I) : is_partition (π.restrict J) :=
is_partition_iff_Union_eq.2 $ by simp [h.Union_eq, hJ]
protected lemma inf (h₁ : is_partition π₁) (h₂ : is_partition π₂) :
is_partition (π₁ ⊓ π₂) :=
is_partition_iff_Union_eq.2 $ by simp [h₁.Union_eq, h₂.Union_eq]
end is_partition
lemma Union_bUnion_partition (h : ∀ J ∈ π, (πi J).is_partition) : (π.bUnion πi).Union = π.Union :=
(Union_bUnion _ _).trans $ Union_congr id surjective_id $ λ J, Union_congr id surjective_id $ λ hJ,
(h J hJ).Union_eq
lemma is_partition_disj_union_of_eq_diff (h : π₂.Union = I \ π₁.Union) :
is_partition (π₁.disj_union π₂ (h.symm ▸ disjoint_diff)) :=
is_partition_iff_Union_eq.2 $ (Union_disj_union _).trans $ by simp [h, π₁.Union_subset]
end prepartition
end box_integral
|
48e4280fd669cfd7aea6134614ad03ea0d1ee98d | 47181b4ef986292573c77e09fcb116584d37ea8a | /src/for_mathlib/principal_ideal_domain.lean | feceafbb6b6f9173ca9eae914a77888aa85ec3a2 | [
"MIT"
] | permissive | RaitoBezarius/berkovich-spaces | 87662a2bdb0ac0beed26e3338b221e3f12107b78 | 0a49f75a599bcb20333ec86b301f84411f04f7cf | refs/heads/main | 1,690,520,666,912 | 1,629,328,012,000 | 1,629,328,012,000 | 332,238,095 | 4 | 0 | MIT | 1,629,312,085,000 | 1,611,414,506,000 | Lean | UTF-8 | Lean | false | false | 696 | lean |
import ring_theory.ideal.basic
import ring_theory.principal_ideal_domain
theorem submodule.is_principal.prime_generator_of_prime {α} [comm_ring α] (I: ideal α)
[submodule.is_principal I] [is_prime: ideal.is_prime I] (ne_bot: I ≠ ⊥):
prime (submodule.is_principal.generator I) :=
⟨
by {
intro h,
rw ← submodule.is_principal.eq_bot_iff_generator_eq_zero I at h,
exact ne_bot h,
},
by {
intro h,
have p₁: I = ⊤,
from ideal.eq_top_of_is_unit_mem I (submodule.is_principal.generator_mem I) h,
exact ideal.is_prime.ne_top is_prime p₁,
},
by {
simp only [← submodule.is_principal.mem_iff_generator_dvd I],
exact is_prime.2,
}
⟩
|
fa3f0852c1b65c82d7bfc2481e2e27edfa23bf4d | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/ring_theory/free_ring.lean | 2b507ef0f06e022b4d5f7a5fe00e95e49dddf002 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 3,757 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Johan Commelin
-/
import group_theory.free_abelian_group
import ring_theory.subring
/-!
# Free rings
The theory of the free ring over a type.
## Main definitions
* `free_ring α` : the free (not commutative in general) ring over a type.
* `lift (f : α → R)` : the ring hom `free_ring α →+* R` induced by `f`.
* `map (f : α → β)` : the ring hom `free_ring α →+* free_ring β` induced by `f`.
## Implementation details
`free_ring α` is implemented as the free abelian group over the free monoid on `α`.
## Tags
free ring
-/
universes u v
/-- The free ring over a type `α`. -/
def free_ring (α : Type u) : Type u :=
free_abelian_group $ free_monoid α
namespace free_ring
variables (α : Type u)
instance : ring (free_ring α) := free_abelian_group.ring _
instance : inhabited (free_ring α) := ⟨0⟩
variables {α}
/-- The canonical map from α to `free_ring α`. -/
def of (x : α) : free_ring α :=
free_abelian_group.of [x]
@[elab_as_eliminator] protected lemma induction_on
{C : free_ring α → Prop} (z : free_ring α)
(hn1 : C (-1)) (hb : ∀ b, C (of b))
(ha : ∀ x y, C x → C y → C (x + y))
(hm : ∀ x y, C x → C y → C (x * y)) : C z :=
have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih,
have h1 : C 1, from neg_neg (1 : free_ring α) ▸ hn _ hn1,
free_abelian_group.induction_on z
(add_left_neg (1 : free_ring α) ▸ ha _ _ hn1 h1)
(λ m, list.rec_on m h1 $ λ a m ih, hm _ _ (hb a) ih)
(λ m ih, hn _ ih)
ha
section lift
variables {R : Type v} [ring R] (f : α → R)
/-- The ring homomorphism `free_ring α →+* R` induced from a map `α → R`. -/
def lift : free_ring α →+* R :=
{ map_one' := free_abelian_group.lift.of _ _,
map_mul' := λ x y,
begin
refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _,
{ intros L2,
conv_lhs { dsimp only [free_abelian_group.mul_def] },
simp only [free_abelian_group.lift.of, add_monoid_hom.to_fun_eq_coe],
refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _,
{ intros L1, iterate 3 { rw free_abelian_group.lift.of },
show list.prod (list.map f (_ ++ _)) = _, rw [list.map_append, list.prod_append] },
{ intros L1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] },
{ intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } },
{ intros L2 ih,
simp only [add_monoid_hom.to_fun_eq_coe] at ih ⊢,
rw [mul_neg_eq_neg_mul_symm, add_monoid_hom.map_neg, add_monoid_hom.map_neg, mul_neg_eq_neg_mul_symm, ih] },
{ intros y1 y2 ih1 ih2,
simp only [add_monoid_hom.to_fun_eq_coe] at ih1 ih2 ⊢,
rw [mul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, mul_add, ih1, ih2] },
end,
.. free_abelian_group.lift $ λ L, (list.map f L).prod }
@[simp] lemma lift_of (x : α) : lift f (of x) = f x :=
(free_abelian_group.lift.of _ _).trans $ one_mul _
@[simp] lemma lift_comp_of (f : free_ring α →+* R) : lift (f ∘ of) = f :=
ring_hom.ext $ λ x, free_ring.induction_on x
(by rw [ring_hom.map_neg, ring_hom.map_one, f.map_neg, f.map_one])
(lift_of _)
(λ x y ihx ihy, by rw [ring_hom.map_add, f.map_add, ihx, ihy])
(λ x y ihx ihy, by rw [ring_hom.map_mul, f.map_mul, ihx, ihy])
end lift
variables {β : Type v} (f : α → β)
/-- The canonical ring homomorphism `free_ring α →+* free_ring β` generated by a map `α → β`. -/
def map : free_ring α →+* free_ring β :=
lift $ of ∘ f
@[simp]
lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _
end free_ring
|
fb70406fa233a0ab3a0dca4705c7a5da6eb45e9c | e94d3f31e48d06d252ee7307fe71efe1d500f274 | /library/data/list/basic.lean | bd96fa248b6eba341488904a6bc5a03678f170e1 | [
"Apache-2.0"
] | permissive | GallagherCommaJack/lean | e4471240a069d82f97cb361d2bf1a029de3f4256 | 226f8bafeb9baaa5a2ac58000c83d6beb29991e2 | refs/heads/master | 1,610,725,100,482 | 1,459,194,829,000 | 1,459,195,377,000 | 55,377,224 | 0 | 0 | null | 1,459,731,701,000 | 1,459,731,700,000 | null | UTF-8 | Lean | false | false | 26,371 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn
Basic properties of lists.
-/
import logic tools.helper_tactics data.nat.order data.nat.sub
open eq.ops nat prod function option
inductive list (T : Type) : Type :=
| nil {} : list T
| cons : T → list T → list T
protected definition list.is_inhabited [instance] (A : Type) : inhabited (list A) :=
inhabited.mk list.nil
namespace list
notation h :: t := cons h t
notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l
variable {T : Type}
lemma cons_ne_nil [simp] (a : T) (l : list T) : a::l ≠ [] :=
by contradiction
lemma head_eq_of_cons_eq {A : Type} {h₁ h₂ : A} {t₁ t₂ : list A} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
lemma tail_eq_of_cons_eq {A : Type} {h₁ h₂ : A} {t₁ t₂ : list A} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
lemma cons_inj {A : Type} {a : A} : injective (cons a) :=
take l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
/- append -/
definition append : list T → list T → list T
| [] l := l
| (h :: s) t := h :: (append s t)
notation l₁ ++ l₂ := append l₁ l₂
theorem append_nil_left [simp] (t : list T) : [] ++ t = t :=
rfl
theorem append_cons [simp] (x : T) (s t : list T) : (x::s) ++ t = x::(s ++ t) :=
rfl
theorem append_nil_right [simp] : ∀ (t : list T), t ++ [] = t :=
by rec_inst_simp
theorem append.assoc [simp] : ∀ (s t u : list T), s ++ t ++ u = s ++ (t ++ u) :=
by rec_inst_simp
/- length -/
definition length : list T → nat
| [] := 0
| (a :: l) := length l + 1
theorem length_nil [simp] : length (@nil T) = 0 :=
rfl
theorem length_cons [simp] (x : T) (t : list T) : length (x::t) = length t + 1 :=
rfl
theorem length_append [simp] : ∀ (s t : list T), length (s ++ t) = length s + length t :=
by rec_inst_simp
theorem eq_nil_of_length_eq_zero : ∀ {l : list T}, length l = 0 → l = []
| [] H := rfl
| (a::s) H := by contradiction
theorem ne_nil_of_length_eq_succ : ∀ {l : list T} {n : nat}, length l = succ n → l ≠ []
| [] n h := by contradiction
| (a::l) n h := by contradiction
/- concat -/
definition concat : Π (x : T), list T → list T
| a [] := [a]
| a (b :: l) := b :: concat a l
theorem concat_nil [simp] (x : T) : concat x [] = [x] :=
rfl
theorem concat_cons [simp] (x y : T) (l : list T) : concat x (y::l) = y::(concat x l) :=
rfl
theorem concat_eq_append [simp] (a : T) : ∀ (l : list T), concat a l = l ++ [a] :=
by rec_inst_simp
theorem concat_ne_nil [simp] (a : T) : ∀ (l : list T), concat a l ≠ [] :=
by intro l; induction l; repeat contradiction
theorem length_concat [simp] (a : T) : ∀ (l : list T), length (concat a l) = length l + 1 :=
by rec_inst_simp
theorem concat_append [simp] (a : T) : ∀ (l₁ l₂ : list T), concat a l₁ ++ l₂ = l₁ ++ a :: l₂ :=
by rec_inst_simp
theorem append_concat (a : T) : ∀(l₁ l₂ : list T), l₁ ++ concat a l₂ = concat a (l₁ ++ l₂) :=
by rec_inst_simp
/- last -/
definition last : Π l : list T, l ≠ [] → T
| [] h := absurd rfl h
| [a] h := a
| (a₁::a₂::l) h := last (a₂::l) !cons_ne_nil
lemma last_singleton [simp] (a : T) (h : [a] ≠ []) : last [a] h = a :=
rfl
lemma last_cons_cons [simp] (a₁ a₂ : T) (l : list T) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) !cons_ne_nil :=
rfl
theorem last_congr {l₁ l₂ : list T} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ :=
by subst l₁
theorem last_concat [simp] {x : T} : ∀ {l : list T} (h : concat x l ≠ []), last (concat x l) h = x :=
by rec_simp
-- add_rewrite append_nil append_cons
/- reverse -/
definition reverse : list T → list T
| [] := []
| (a :: l) := concat a (reverse l)
theorem reverse_nil [simp] : reverse (@nil T) = [] :=
rfl
theorem reverse_cons [simp] (x : T) (l : list T) : reverse (x::l) = concat x (reverse l) :=
rfl
theorem reverse_singleton [simp] (x : T) : reverse [x] = [x] :=
rfl
theorem reverse_append [simp] : ∀ (s t : list T), reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by rec_inst_simp
theorem reverse_reverse [simp] : ∀ (l : list T), reverse (reverse l) = l :=
by rec_inst_simp
theorem concat_eq_reverse_cons (x : T) (l : list T) : concat x l = reverse (x :: reverse l) :=
by inst_simp
theorem length_reverse : ∀ (l : list T), length (reverse l) = length l :=
by rec_inst_simp
/- head and tail -/
definition head [h : inhabited T] : list T → T
| [] := arbitrary T
| (a :: l) := a
theorem head_cons [simp] [h : inhabited T] (a : T) (l : list T) : head (a::l) = a :=
rfl
theorem head_append [simp] [h : inhabited T] (t : list T) : ∀ {s : list T}, s ≠ [] → head (s ++ t) = head s :=
by rec_inst_simp
definition tail : list T → list T
| [] := []
| (a :: l) := l
theorem tail_nil [simp] : tail (@nil T) = [] :=
rfl
theorem tail_cons [simp] (a : T) (l : list T) : tail (a::l) = l :=
rfl
theorem cons_head_tail [h : inhabited T] {l : list T} : l ≠ [] → (head l)::(tail l) = l :=
by rec_inst_simp
/- list membership -/
definition mem : T → list T → Prop
| a [] := false
| a (b :: l) := a = b ∨ mem a l
notation e ∈ s := mem e s
notation e ∉ s := ¬ e ∈ s
theorem mem_nil_iff (x : T) : x ∈ [] ↔ false :=
iff.rfl
theorem not_mem_nil (x : T) : x ∉ [] :=
iff.mp !mem_nil_iff
theorem mem_cons [simp] (x : T) (l : list T) : x ∈ x :: l :=
or.inl rfl
theorem mem_cons_of_mem (y : T) {x : T} {l : list T} : x ∈ l → x ∈ y :: l :=
assume H, or.inr H
theorem mem_cons_iff (x y : T) (l : list T) : x ∈ y::l ↔ (x = y ∨ x ∈ l) :=
iff.rfl
theorem eq_or_mem_of_mem_cons {x y : T} {l : list T} : x ∈ y::l → x = y ∨ x ∈ l :=
assume h, h
theorem mem_singleton {x a : T} : x ∈ [a] → x = a :=
suppose x ∈ [a], or.elim (eq_or_mem_of_mem_cons this)
(suppose x = a, this)
(suppose x ∈ [], absurd this !not_mem_nil)
theorem mem_of_mem_cons_of_mem {a b : T} {l : list T} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(suppose a = b, by substvars; exact binl)
(suppose a ∈ l, this)
theorem mem_or_mem_of_mem_append {x : T} {s t : list T} : x ∈ s ++ t → x ∈ s ∨ x ∈ t :=
list.induction_on s or.inr
(take y s,
assume IH : x ∈ s ++ t → x ∈ s ∨ x ∈ t,
suppose x ∈ y::s ++ t,
have x = y ∨ x ∈ s ++ t, from this,
have x = y ∨ x ∈ s ∨ x ∈ t, from or_of_or_of_imp_right this IH,
iff.elim_right or.assoc this)
theorem mem_append_of_mem_or_mem {x : T} {s t : list T} : x ∈ s ∨ x ∈ t → x ∈ s ++ t :=
list.induction_on s
(take H, or.elim H false.elim (assume H, H))
(take y s,
assume IH : x ∈ s ∨ x ∈ t → x ∈ s ++ t,
suppose x ∈ y::s ∨ x ∈ t,
or.elim this
(suppose x ∈ y::s,
or.elim (eq_or_mem_of_mem_cons this)
(suppose x = y, or.inl this)
(suppose x ∈ s, or.inr (IH (or.inl this))))
(suppose x ∈ t, or.inr (IH (or.inr this))))
theorem mem_append_iff (x : T) (s t : list T) : x ∈ s ++ t ↔ x ∈ s ∨ x ∈ t :=
iff.intro mem_or_mem_of_mem_append mem_append_of_mem_or_mem
theorem not_mem_of_not_mem_append_left {x : T} {s t : list T} : x ∉ s++t → x ∉ s :=
λ nxinst xins, absurd (mem_append_of_mem_or_mem (or.inl xins)) nxinst
theorem not_mem_of_not_mem_append_right {x : T} {s t : list T} : x ∉ s++t → x ∉ t :=
λ nxinst xint, absurd (mem_append_of_mem_or_mem (or.inr xint)) nxinst
theorem not_mem_append {x : T} {s t : list T} : x ∉ s → x ∉ t → x ∉ s++t :=
λ nxins nxint xinst, or.elim (mem_or_mem_of_mem_append xinst)
(λ xins, by contradiction)
(λ xint, by contradiction)
lemma length_pos_of_mem {a : T} : ∀ {l : list T}, a ∈ l → 0 < length l
| [] := assume Pinnil, by contradiction
| (b::l) := assume Pin, !zero_lt_succ
section
local attribute mem [reducible]
local attribute append [reducible]
theorem mem_split {x : T} {l : list T} : x ∈ l → ∃s t : list T, l = s ++ (x::t) :=
list.induction_on l
(suppose x ∈ [], false.elim (iff.elim_left !mem_nil_iff this))
(take y l,
assume IH : x ∈ l → ∃s t : list T, l = s ++ (x::t),
suppose x ∈ y::l,
or.elim (eq_or_mem_of_mem_cons this)
(suppose x = y,
exists.intro [] (!exists.intro (this ▸ rfl)))
(suppose x ∈ l,
obtain s (H2 : ∃t : list T, l = s ++ (x::t)), from IH this,
obtain t (H3 : l = s ++ (x::t)), from H2,
have y :: l = (y::s) ++ (x::t),
from H3 ▸ rfl,
!exists.intro (!exists.intro this)))
end
theorem mem_append_left {a : T} {l₁ : list T} (l₂ : list T) : a ∈ l₁ → a ∈ l₁ ++ l₂ :=
assume ainl₁, mem_append_of_mem_or_mem (or.inl ainl₁)
theorem mem_append_right {a : T} (l₁ : list T) {l₂ : list T} : a ∈ l₂ → a ∈ l₁ ++ l₂ :=
assume ainl₂, mem_append_of_mem_or_mem (or.inr ainl₂)
definition decidable_mem [instance] [H : decidable_eq T] (x : T) (l : list T) : decidable (x ∈ l) :=
list.rec_on l
(decidable.inr (not_of_iff_false !mem_nil_iff))
(take (h : T) (l : list T) (iH : decidable (x ∈ l)),
show decidable (x ∈ h::l), from
decidable.rec_on iH
(assume Hp : x ∈ l,
decidable.rec_on (H x h)
(suppose x = h,
decidable.inl (or.inl this))
(suppose x ≠ h,
decidable.inl (or.inr Hp)))
(suppose ¬x ∈ l,
decidable.rec_on (H x h)
(suppose x = h, decidable.inl (or.inl this))
(suppose x ≠ h,
have ¬(x = h ∨ x ∈ l), from
suppose x = h ∨ x ∈ l, or.elim this
(suppose x = h, by contradiction)
(suppose x ∈ l, by contradiction),
have ¬x ∈ h::l, from
iff.elim_right (not_iff_not_of_iff !mem_cons_iff) this,
decidable.inr this)))
theorem mem_of_ne_of_mem {x y : T} {l : list T} (H₁ : x ≠ y) (H₂ : x ∈ y :: l) : x ∈ l :=
or.elim (eq_or_mem_of_mem_cons H₂) (λe, absurd e H₁) (λr, r)
theorem ne_of_not_mem_cons {a b : T} {l : list T} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : T} {l : list T} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
lemma not_mem_cons_of_ne_of_not_mem {x y : T} {l : list T} : x ≠ y → x ∉ l → x ∉ y::l :=
assume P1 P2, not.intro (assume Pxin, absurd (eq_or_mem_of_mem_cons Pxin) (not_or P1 P2))
lemma ne_and_not_mem_of_not_mem_cons {x y : T} {l : list T} : x ∉ y::l → x ≠ y ∧ x ∉ l :=
assume P, and.intro (ne_of_not_mem_cons P) (not_mem_of_not_mem_cons P)
definition sublist (l₁ l₂ : list T) := ∀ ⦃a : T⦄, a ∈ l₁ → a ∈ l₂
infix ⊆ := sublist
theorem nil_sub [simp] (l : list T) : [] ⊆ l :=
λ b i, false.elim (iff.mp (mem_nil_iff b) i)
theorem sub.refl [simp] (l : list T) : l ⊆ l :=
λ b i, i
theorem sub.trans {l₁ l₂ l₃ : list T} (H₁ : l₁ ⊆ l₂) (H₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ :=
λ b i, H₂ (H₁ i)
theorem sub_cons [simp] (a : T) (l : list T) : l ⊆ a::l :=
λ b i, or.inr i
theorem sub_of_cons_sub {a : T} {l₁ l₂ : list T} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ :=
λ s b i, s b (mem_cons_of_mem _ i)
theorem cons_sub_cons {l₁ l₂ : list T} (a : T) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) :=
λ b Hin, or.elim (eq_or_mem_of_mem_cons Hin)
(λ e : b = a, or.inl e)
(λ i : b ∈ l₁, or.inr (s i))
theorem sub_append_left [simp] (l₁ l₂ : list T) : l₁ ⊆ l₁++l₂ :=
λ b i, iff.mpr (mem_append_iff b l₁ l₂) (or.inl i)
theorem sub_append_right [simp] (l₁ l₂ : list T) : l₂ ⊆ l₁++l₂ :=
λ b i, iff.mpr (mem_append_iff b l₁ l₂) (or.inr i)
theorem sub_cons_of_sub (a : T) {l₁ l₂ : list T} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) :=
λ (s : l₁ ⊆ l₂) (x : T) (i : x ∈ l₁), or.inr (s i)
theorem sub_app_of_sub_left (l l₁ l₂ : list T) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ (s : l ⊆ l₁) (x : T) (xinl : x ∈ l),
have x ∈ l₁, from s xinl,
mem_append_of_mem_or_mem (or.inl this)
theorem sub_app_of_sub_right (l l₁ l₂ : list T) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ (s : l ⊆ l₂) (x : T) (xinl : x ∈ l),
have x ∈ l₂, from s xinl,
mem_append_of_mem_or_mem (or.inr this)
theorem cons_sub_of_sub_of_mem {a : T} {l m : list T} : a ∈ m → l ⊆ m → a::l ⊆ m :=
λ (ainm : a ∈ m) (lsubm : l ⊆ m) (x : T) (xinal : x ∈ a::l), or.elim (eq_or_mem_of_mem_cons xinal)
(suppose x = a, by substvars; exact ainm)
(suppose x ∈ l, lsubm this)
theorem app_sub_of_sub_of_sub {l₁ l₂ l : list T} : l₁ ⊆ l → l₂ ⊆ l → l₁++l₂ ⊆ l :=
λ (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) (x : T) (xinl₁l₂ : x ∈ l₁++l₂),
or.elim (mem_or_mem_of_mem_append xinl₁l₂)
(suppose x ∈ l₁, l₁subl this)
(suppose x ∈ l₂, l₂subl this)
/- find -/
section
variable [H : decidable_eq T]
include H
definition find : T → list T → nat
| a [] := 0
| a (b :: l) := if a = b then 0 else succ (find a l)
theorem find_nil [simp] (x : T) : find x [] = 0 :=
rfl
theorem find_cons (x y : T) (l : list T) : find x (y::l) = if x = y then 0 else succ (find x l) :=
rfl
theorem find_cons_of_eq {x y : T} (l : list T) : x = y → find x (y::l) = 0 :=
assume e, if_pos e
theorem find_cons_of_ne {x y : T} (l : list T) : x ≠ y → find x (y::l) = succ (find x l) :=
assume n, if_neg n
theorem find_of_not_mem {l : list T} {x : T} : ¬x ∈ l → find x l = length l :=
list.rec_on l
(suppose ¬x ∈ [], rfl)
(take y l,
assume iH : ¬x ∈ l → find x l = length l,
suppose ¬x ∈ y::l,
have ¬(x = y ∨ x ∈ l), from iff.elim_right (not_iff_not_of_iff !mem_cons_iff) this,
have ¬x = y ∧ ¬x ∈ l, from (iff.elim_left !not_or_iff_not_and_not this),
calc
find x (y::l) = if x = y then 0 else succ (find x l) : !find_cons
... = succ (find x l) : if_neg (and.elim_left this)
... = succ (length l) : {iH (and.elim_right this)}
... = length (y::l) : !length_cons⁻¹)
lemma find_le_length : ∀ {a} {l : list T}, find a l ≤ length l
| a [] := !le.refl
| a (b::l) := decidable.rec_on (H a b)
(assume Peq, by rewrite [find_cons_of_eq l Peq]; exact !zero_le)
(assume Pne,
begin
rewrite [find_cons_of_ne l Pne, length_cons],
apply succ_le_succ, apply find_le_length
end)
lemma not_mem_of_find_eq_length : ∀ {a} {l : list T}, find a l = length l → a ∉ l
| a [] := assume Peq, !not_mem_nil
| a (b::l) := decidable.rec_on (H a b)
(assume Peq, by rewrite [find_cons_of_eq l Peq, length_cons]; contradiction)
(assume Pne,
begin
rewrite [find_cons_of_ne l Pne, length_cons, mem_cons_iff],
intro Plen, apply (not_or Pne),
exact not_mem_of_find_eq_length (succ.inj Plen)
end)
lemma find_lt_length {a} {l : list T} (Pin : a ∈ l) : find a l < length l :=
begin
apply nat.lt_of_le_and_ne,
apply find_le_length,
apply not.intro, intro Peq,
exact absurd Pin (not_mem_of_find_eq_length Peq)
end
end
/- nth element -/
section nth
definition nth : list T → nat → option T
| [] n := none
| (a :: l) 0 := some a
| (a :: l) (n+1) := nth l n
theorem nth_zero [simp] (a : T) (l : list T) : nth (a :: l) 0 = some a :=
rfl
theorem nth_succ [simp] (a : T) (l : list T) (n : nat) : nth (a::l) (succ n) = nth l n :=
rfl
theorem nth_eq_some : ∀ {l : list T} {n : nat}, n < length l → Σ a : T, nth l n = some a
| [] n h := absurd h !not_lt_zero
| (a::l) 0 h := ⟨a, rfl⟩
| (a::l) (succ n) h :=
have n < length l, from lt_of_succ_lt_succ h,
obtain (r : T) (req : nth l n = some r), from nth_eq_some this,
⟨r, by rewrite [nth_succ, req]⟩
open decidable
theorem find_nth [decidable_eq T] {a : T} : ∀ {l}, a ∈ l → nth l (find a l) = some a
| [] ain := absurd ain !not_mem_nil
| (b::l) ainbl := by_cases
(λ aeqb : a = b, by rewrite [find_cons_of_eq _ aeqb, nth_zero, aeqb])
(λ aneb : a ≠ b, or.elim (eq_or_mem_of_mem_cons ainbl)
(λ aeqb : a = b, absurd aeqb aneb)
(λ ainl : a ∈ l, by rewrite [find_cons_of_ne _ aneb, nth_succ, find_nth ainl]))
definition inth [h : inhabited T] (l : list T) (n : nat) : T :=
match nth l n with
| some a := a
| none := arbitrary T
end
theorem inth_zero [inhabited T] (a : T) (l : list T) : inth (a :: l) 0 = a :=
rfl
theorem inth_succ [inhabited T] (a : T) (l : list T) (n : nat) : inth (a::l) (n+1) = inth l n :=
rfl
end nth
section ith
definition ith : Π (l : list T) (i : nat), i < length l → T
| nil i h := absurd h !not_lt_zero
| (x::xs) 0 h := x
| (x::xs) (succ i) h := ith xs i (lt_of_succ_lt_succ h)
lemma ith_zero [simp] (a : T) (l : list T) (h : 0 < length (a::l)) : ith (a::l) 0 h = a :=
rfl
lemma ith_succ [simp] (a : T) (l : list T) (i : nat) (h : succ i < length (a::l))
: ith (a::l) (succ i) h = ith l i (lt_of_succ_lt_succ h) :=
rfl
end ith
open decidable
definition has_decidable_eq {A : Type} [H : decidable_eq A] : ∀ l₁ l₂ : list A, decidable (l₁ = l₂)
| [] [] := inl rfl
| [] (b::l₂) := inr (by contradiction)
| (a::l₁) [] := inr (by contradiction)
| (a::l₁) (b::l₂) :=
match H a b with
| inl Hab :=
match has_decidable_eq l₁ l₂ with
| inl He := inl (by congruence; repeat assumption)
| inr Hn := inr (by intro H; injection H; contradiction)
end
| inr Hnab := inr (by intro H; injection H; contradiction)
end
/- quasiequal a l l' means that l' is exactly l, with a added
once somewhere -/
section qeq
variable {A : Type}
inductive qeq (a : A) : list A → list A → Prop :=
| qhead : ∀ l, qeq a l (a::l)
| qcons : ∀ (b : A) {l l' : list A}, qeq a l l' → qeq a (b::l) (b::l')
open qeq
notation l' `≈`:50 a `|` l:50 := qeq a l l'
theorem qeq_app : ∀ (l₁ : list A) (a : A) (l₂ : list A), l₁++(a::l₂) ≈ a|l₁++l₂
| [] a l₂ := qhead a l₂
| (x::xs) a l₂ := qcons x (qeq_app xs a l₂)
theorem mem_head_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → a ∈ l₁ :=
take q, qeq.induction_on q
(λ l, !mem_cons)
(λ b l l' q r, or.inr r)
theorem mem_tail_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → ∀ x, x ∈ l₂ → x ∈ l₁ :=
take q, qeq.induction_on q
(λ l x i, or.inr i)
(λ b l l' q r x xinbl, or.elim (eq_or_mem_of_mem_cons xinbl)
(λ xeqb : x = b, xeqb ▸ mem_cons x l')
(λ xinl : x ∈ l, or.inr (r x xinl)))
theorem mem_cons_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → ∀ x, x ∈ l₁ → x ∈ a::l₂ :=
take q, qeq.induction_on q
(λ l x i, i)
(λ b l l' q r x xinbl', or.elim (eq_or_mem_of_mem_cons xinbl')
(λ xeqb : x = b, xeqb ▸ or.inr (mem_cons x l))
(λ xinl' : x ∈ l', or.elim (eq_or_mem_of_mem_cons (r x xinl'))
(λ xeqa : x = a, xeqa ▸ mem_cons x (b::l))
(λ xinl : x ∈ l, or.inr (or.inr xinl))))
theorem length_eq_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → length l₁ = succ (length l₂) :=
take q, qeq.induction_on q
(λ l, rfl)
(λ b l l' q r, by rewrite [*length_cons, r])
theorem qeq_of_mem {a : A} {l : list A} : a ∈ l → (∃l', l≈a|l') :=
list.induction_on l
(λ h : a ∈ nil, absurd h (not_mem_nil a))
(λ x xs r ainxxs, or.elim (eq_or_mem_of_mem_cons ainxxs)
(λ aeqx : a = x,
have aux : ∃ l, x::xs≈x|l, from
exists.intro xs (qhead x xs),
by rewrite aeqx; exact aux)
(λ ainxs : a ∈ xs,
have ∃l', xs ≈ a|l', from r ainxs,
obtain (l' : list A) (q : xs ≈ a|l'), from this,
have x::xs ≈ a | x::l', from qcons x q,
exists.intro (x::l') this))
theorem qeq_split {a : A} {l l' : list A} : l'≈a|l → ∃l₁ l₂, l = l₁++l₂ ∧ l' = l₁++(a::l₂) :=
take q, qeq.induction_on q
(λ t,
have t = []++t ∧ a::t = []++(a::t), from and.intro rfl rfl,
exists.intro [] (exists.intro t this))
(λ b t t' q r,
obtain (l₁ l₂ : list A) (h : t = l₁++l₂ ∧ t' = l₁++(a::l₂)), from r,
have b::t = (b::l₁)++l₂ ∧ b::t' = (b::l₁)++(a::l₂),
begin
rewrite [and.elim_right h, and.elim_left h],
constructor, repeat reflexivity
end,
exists.intro (b::l₁) (exists.intro l₂ this))
theorem sub_of_mem_of_sub_of_qeq {a : A} {l : list A} {u v : list A} : a ∉ l → a::l ⊆ v → v≈a|u → l ⊆ u :=
λ (nainl : a ∉ l) (s : a::l ⊆ v) (q : v≈a|u) (x : A) (xinl : x ∈ l),
have x ∈ v, from s (or.inr xinl),
have x ∈ a::u, from mem_cons_of_qeq q x this,
or.elim (eq_or_mem_of_mem_cons this)
(suppose x = a, by substvars; contradiction)
(suppose x ∈ u, this)
end qeq
section firstn
variable {A : Type}
definition firstn : nat → list A → list A
| 0 l := []
| (n+1) [] := []
| (n+1) (a::l) := a :: firstn n l
lemma firstn_zero [simp] : ∀ (l : list A), firstn 0 l = [] :=
by intros; reflexivity
lemma firstn_nil [simp] : ∀ n, firstn n [] = ([] : list A)
| 0 := rfl
| (n+1) := rfl
lemma firstn_cons : ∀ n (a : A) (l : list A), firstn (succ n) (a::l) = a :: firstn n l :=
by intros; reflexivity
lemma firstn_all : ∀ (l : list A), firstn (length l) l = l
| [] := rfl
| (a::l) := begin unfold [length, firstn], rewrite firstn_all end
lemma firstn_all_of_ge : ∀ {n} {l : list A}, n ≥ length l → firstn n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt !succ_pos)
| (n+1) [] h := rfl
| (n+1) (a::l) h := begin unfold firstn, rewrite [firstn_all_of_ge (le_of_succ_le_succ h)] end
lemma firstn_firstn : ∀ (n m) (l : list A), firstn n (firstn m l) = firstn (min n m) l
| n 0 l := by rewrite [min_zero, firstn_zero, firstn_nil]
| 0 m l := by rewrite [zero_min]
| (succ n) (succ m) nil := by rewrite [*firstn_nil]
| (succ n) (succ m) (a::l) := by rewrite [*firstn_cons, firstn_firstn, min_succ_succ]
lemma length_firstn_le : ∀ (n) (l : list A), length (firstn n l) ≤ n
| 0 l := by rewrite [firstn_zero]
| (succ n) (a::l) := by rewrite [firstn_cons, length_cons, add_one]; apply succ_le_succ; apply length_firstn_le
| (succ n) [] := by rewrite [firstn_nil, length_nil]; apply zero_le
lemma length_firstn_eq : ∀ (n) (l : list A), length (firstn n l) = min n (length l)
| 0 l := by rewrite [firstn_zero, zero_min]
| (succ n) (a::l) := by rewrite [firstn_cons, *length_cons, *add_one, min_succ_succ, length_firstn_eq]
| (succ n) [] := by rewrite [firstn_nil]
end firstn
section dropn
variables {A : Type}
-- 'dropn n l' drops the first 'n' elements of 'l'
definition dropn : ℕ → list A → list A
| 0 a := a
| (succ n) [] := []
| (succ n) (x::r) := dropn n r
theorem length_dropn
: ∀ (i : ℕ) (l : list A), length (dropn i l) = length l - i
| 0 l := rfl
| (succ i) [] := calc
length (dropn (succ i) []) = 0 - succ i : nat.zero_sub (succ i)
| (succ i) (x::l) := calc
length (dropn (succ i) (x::l))
= length (dropn i l) : rfl
... = length l - i : length_dropn i l
... = succ (length l) - succ i : succ_sub_succ (length l) i
end dropn
section count
variable {A : Type}
variable [decA : decidable_eq A]
include decA
definition count (a : A) : list A → nat
| [] := 0
| (x::xs) := if a = x then succ (count xs) else count xs
lemma count_nil (a : A) : count a [] = 0 :=
rfl
lemma count_cons (a b : A) (l : list A) : count a (b::l) = if a = b then succ (count a l) else count a l :=
rfl
lemma count_cons_eq (a : A) (l : list A) : count a (a::l) = succ (count a l) :=
if_pos rfl
lemma count_cons_of_ne {a b : A} (h : a ≠ b) (l : list A) : count a (b::l) = count a l :=
if_neg h
lemma count_cons_ge_count (a b : A) (l : list A) : count a (b::l) ≥ count a l :=
by_cases
(suppose a = b, begin subst b, rewrite count_cons_eq, apply le_succ end)
(suppose a ≠ b, begin rewrite (count_cons_of_ne this), apply le.refl end)
lemma count_singleton (a : A) : count a [a] = 1 :=
by rewrite count_cons_eq
lemma count_append (a : A) : ∀ l₁ l₂, count a (l₁++l₂) = count a l₁ + count a l₂
| [] l₂ := by rewrite [append_nil_left, count_nil, zero_add]
| (b::l₁) l₂ := by_cases
(suppose a = b, by rewrite [-this, append_cons, *count_cons_eq, succ_add, count_append])
(suppose a ≠ b, by rewrite [append_cons, *count_cons_of_ne this, count_append])
lemma count_concat (a : A) (l : list A) : count a (concat a l) = succ (count a l) :=
by rewrite [concat_eq_append, count_append, count_singleton]
lemma mem_of_count_gt_zero : ∀ {a : A} {l : list A}, count a l > 0 → a ∈ l
| a [] h := absurd h !lt.irrefl
| a (b::l) h := by_cases
(suppose a = b, begin subst b, apply mem_cons end)
(suppose a ≠ b,
have count a l > 0, by rewrite [count_cons_of_ne this at h]; exact h,
have a ∈ l, from mem_of_count_gt_zero this,
show a ∈ b::l, from mem_cons_of_mem _ this)
lemma count_gt_zero_of_mem : ∀ {a : A} {l : list A}, a ∈ l → count a l > 0
| a [] h := absurd h !not_mem_nil
| a (b::l) h := or.elim h
(suppose a = b, begin subst b, rewrite count_cons_eq, apply zero_lt_succ end)
(suppose a ∈ l, calc
count a (b::l) ≥ count a l : count_cons_ge_count
... > 0 : count_gt_zero_of_mem this)
lemma count_eq_zero_of_not_mem {a : A} {l : list A} (h : a ∉ l) : count a l = 0 :=
match count a l with
| zero := suppose count a l = zero, this
| (succ n) := suppose count a l = succ n, absurd (mem_of_count_gt_zero (begin rewrite this, exact dec_trivial end)) h
end rfl
end count
end list
attribute list.has_decidable_eq [instance]
attribute list.decidable_mem [instance]
|
d074619448acf985851471591abd35ae13a82246 | 3863d2564418bccb1859e057bf5a4ef240e75fd7 | /hott/types/prod.hlean | 81b88c52040ece0e4b61400d5896db0456ac2599 | [
"Apache-2.0"
] | permissive | JacobGross/lean | 118bbb067ff4d4af48a266face2c7eb9868fa91c | eb26087df940c54337cb807b4bc6d345d1fc1085 | refs/heads/master | 1,582,735,011,532 | 1,462,557,826,000 | 1,462,557,826,000 | 46,451,196 | 0 | 0 | null | 1,462,557,826,000 | 1,447,885,161,000 | C++ | UTF-8 | Lean | false | false | 9,080 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jakob von Raumer
Ported from Coq HoTT
Theorems about products
-/
open eq equiv is_equiv is_trunc prod prod.ops unit
variables {A A' B B' C D : Type} {P Q : A → Type}
{a a' a'' : A} {b b₁ b₂ b' b'' : B} {u v w : A × B}
namespace prod
/- Paths in a product space -/
protected definition eta [unfold 3] (u : A × B) : (pr₁ u, pr₂ u) = u :=
by cases u; apply idp
definition pair_eq [unfold 7 8] (pa : a = a') (pb : b = b') : (a, b) = (a', b') :=
by cases pa; cases pb; apply idp
definition prod_eq [unfold 3 4 5 6] (H₁ : u.1 = v.1) (H₂ : u.2 = v.2) : u = v :=
by cases u; cases v; exact pair_eq H₁ H₂
definition eq_pr1 [unfold 5] (p : u = v) : u.1 = v.1 :=
ap pr1 p
definition eq_pr2 [unfold 5] (p : u = v) : u.2 = v.2 :=
ap pr2 p
namespace ops
postfix `..1`:(max+1) := eq_pr1
postfix `..2`:(max+1) := eq_pr2
end ops
open ops
protected definition ap_pr1 (p : u = v) : ap pr1 p = p..1 := idp
protected definition ap_pr2 (p : u = v) : ap pr2 p = p..2 := idp
definition pair_prod_eq (p : u.1 = v.1) (q : u.2 = v.2)
: ((prod_eq p q)..1, (prod_eq p q)..2) = (p, q) :=
by induction u; induction v; esimp at *; induction p; induction q; reflexivity
definition prod_eq_pr1 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..1 = p :=
(pair_prod_eq p q)..1
definition prod_eq_pr2 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..2 = q :=
(pair_prod_eq p q)..2
definition prod_eq_eta (p : u = v) : prod_eq (p..1) (p..2) = p :=
by induction p; induction u; reflexivity
-- the uncurried version of prod_eq. We will prove that this is an equivalence
definition prod_eq_unc (H : u.1 = v.1 × u.2 = v.2) : u = v :=
by cases H with H₁ H₂;exact prod_eq H₁ H₂
definition pair_prod_eq_unc : Π(pq : u.1 = v.1 × u.2 = v.2),
((prod_eq_unc pq)..1, (prod_eq_unc pq)..2) = pq
| pair_prod_eq_unc (pq₁, pq₂) := pair_prod_eq pq₁ pq₂
definition prod_eq_unc_pr1 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..1 = pq.1 :=
(pair_prod_eq_unc pq)..1
definition prod_eq_unc_pr2 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..2 = pq.2 :=
(pair_prod_eq_unc pq)..2
definition prod_eq_unc_eta (p : u = v) : prod_eq_unc (p..1, p..2) = p :=
prod_eq_eta p
definition is_equiv_prod_eq [instance] [constructor] (u v : A × B)
: is_equiv (prod_eq_unc : u.1 = v.1 × u.2 = v.2 → u = v) :=
adjointify prod_eq_unc
(λp, (p..1, p..2))
prod_eq_unc_eta
pair_prod_eq_unc
definition prod_eq_equiv [constructor] (u v : A × B) : (u = v) ≃ (u.1 = v.1 × u.2 = v.2) :=
(equiv.mk prod_eq_unc _)⁻¹ᵉ
/- Groupoid structure -/
definition prod_eq_inv (p : a = a') (q : b = b') : (prod_eq p q)⁻¹ = prod_eq p⁻¹ q⁻¹ :=
by cases p; cases q; reflexivity
definition prod_eq_concat (p : a = a') (p' : a' = a'') (q : b = b') (q' : b' = b'')
: prod_eq p q ⬝ prod_eq p' q' = prod_eq (p ⬝ p') (q ⬝ q') :=
by cases p; cases q; cases p'; cases q'; reflexivity
/- Transport -/
definition prod_transport (p : a = a') (u : P a × Q a)
: p ▸ u = (p ▸ u.1, p ▸ u.2) :=
by induction p; induction u; reflexivity
definition prod_eq_transport (p : a = a') (q : b = b') {R : A × B → Type} (r : R (a, b))
: (prod_eq p q) ▸ r = p ▸ q ▸ r :=
by induction p; induction q; reflexivity
/- Pathovers -/
definition etao (p : a = a') (bc : P a × Q a) : bc =[p] (p ▸ bc.1, p ▸ bc.2) :=
by induction p; induction bc; apply idpo
definition prod_pathover (p : a = a') (u : P a × Q a) (v : P a' × Q a')
(r : u.1 =[p] v.1) (s : u.2 =[p] v.2) : u =[p] v :=
begin
induction u, induction v, esimp at *, induction r,
induction s using idp_rec_on,
apply idpo
end
/-
TODO:
* define the projections from the type u =[p] v
* show that the uncurried version of prod_pathover is an equivalence
-/
/- Functorial action -/
variables (f : A → A') (g : B → B')
definition prod_functor [unfold 7] (u : A × B) : A' × B' :=
(f u.1, g u.2)
definition ap_prod_functor (p : u.1 = v.1) (q : u.2 = v.2)
: ap (prod_functor f g) (prod_eq p q) = prod_eq (ap f p) (ap g q) :=
by induction u; induction v; esimp at *; induction p; induction q; reflexivity
/- Helpers for functions of two arguments -/
definition ap_diagonal {a a' : A} (p : a = a')
: ap (λx : A, (x,x)) p = prod_eq p p :=
by cases p; constructor
definition ap_binary (m : A → B → C) (p : a = a') (q : b = b')
: ap (λz : A × B, m z.1 z.2) (prod_eq p q)
= (ap (m a) q) ⬝ (ap (λx : A, m x b') p) :=
by cases p; cases q; constructor
/- Equivalences -/
definition is_equiv_prod_functor [instance] [constructor] [H : is_equiv f] [H : is_equiv g]
: is_equiv (prod_functor f g) :=
begin
apply adjointify _ (prod_functor f⁻¹ g⁻¹),
intro u, induction u, rewrite [▸*,right_inv f,right_inv g],
intro u, induction u, rewrite [▸*,left_inv f,left_inv g],
end
definition prod_equiv_prod_of_is_equiv [constructor] [H : is_equiv f] [H : is_equiv g]
: A × B ≃ A' × B' :=
equiv.mk (prod_functor f g) _
definition prod_equiv_prod [constructor] (f : A ≃ A') (g : B ≃ B') : A × B ≃ A' × B' :=
equiv.mk (prod_functor f g) _
definition prod_equiv_prod_left [constructor] (g : B ≃ B') : A × B ≃ A × B' :=
prod_equiv_prod equiv.refl g
definition prod_equiv_prod_right [constructor] (f : A ≃ A') : A × B ≃ A' × B :=
prod_equiv_prod f equiv.refl
/- Symmetry -/
definition is_equiv_flip [instance] [constructor] (A B : Type)
: is_equiv (flip : A × B → B × A) :=
adjointify flip
flip
(λu, destruct u (λb a, idp))
(λu, destruct u (λa b, idp))
definition prod_comm_equiv [constructor] (A B : Type) : A × B ≃ B × A :=
equiv.mk flip _
/- Associativity -/
definition prod_assoc_equiv [constructor] (A B C : Type) : A × (B × C) ≃ (A × B) × C :=
begin
fapply equiv.MK,
{ intro z, induction z with a z, induction z with b c, exact (a, b, c)},
{ intro z, induction z with z c, induction z with a b, exact (a, (b, c))},
{ intro z, induction z with z c, induction z with a b, reflexivity},
{ intro z, induction z with a z, induction z with b c, reflexivity},
end
definition prod_contr_equiv [constructor] (A B : Type) [H : is_contr B] : A × B ≃ A :=
equiv.MK pr1
(λx, (x, !center))
(λx, idp)
(λx, by cases x with a b; exact pair_eq idp !center_eq)
definition prod_unit_equiv [constructor] (A : Type) : A × unit ≃ A :=
!prod_contr_equiv
definition prod_empty_equiv (A : Type) : A × empty ≃ empty :=
begin
fapply equiv.MK,
{ intro x, cases x with a e, cases e },
{ intro e, cases e },
{ intro e, cases e },
{ intro x, cases x with a e, cases e }
end
/- Universal mapping properties -/
definition is_equiv_prod_rec [instance] [constructor] (P : A × B → Type)
: is_equiv (prod.rec : (Πa b, P (a, b)) → Πu, P u) :=
adjointify _
(λg a b, g (a, b))
(λg, eq_of_homotopy (λu, by induction u;reflexivity))
(λf, idp)
definition equiv_prod_rec [constructor] (P : A × B → Type) : (Πa b, P (a, b)) ≃ (Πu, P u) :=
equiv.mk prod.rec _
definition imp_imp_equiv_prod_imp (A B C : Type) : (A → B → C) ≃ (A × B → C) :=
!equiv_prod_rec
definition prod_corec_unc [unfold 4] {P Q : A → Type} (u : (Πa, P a) × (Πa, Q a)) (a : A)
: P a × Q a :=
(u.1 a, u.2 a)
definition is_equiv_prod_corec [constructor] (P Q : A → Type)
: is_equiv (prod_corec_unc : (Πa, P a) × (Πa, Q a) → Πa, P a × Q a) :=
adjointify _
(λg, (λa, (g a).1, λa, (g a).2))
(by intro g; apply eq_of_homotopy; intro a; esimp; induction (g a); reflexivity)
(by intro h; induction h with f g; reflexivity)
definition equiv_prod_corec [constructor] (P Q : A → Type)
: ((Πa, P a) × (Πa, Q a)) ≃ (Πa, P a × Q a) :=
equiv.mk _ !is_equiv_prod_corec
definition imp_prod_imp_equiv_imp_prod [constructor] (A B C : Type)
: (A → B) × (A → C) ≃ (A → (B × C)) :=
!equiv_prod_corec
theorem is_trunc_prod (A B : Type) (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B]
: is_trunc n (A × B) :=
begin
revert A B HA HB, induction n with n IH, all_goals intro A B HA HB,
{ fapply is_contr.mk,
exact (!center, !center),
intro u, apply prod_eq, all_goals apply center_eq},
{ apply is_trunc_succ_intro, intro u v,
apply is_trunc_equiv_closed_rev, apply prod_eq_equiv,
exact IH _ _ _ _}
end
end prod
attribute prod.is_trunc_prod [instance] [priority 1510]
definition tprod [constructor] {n : trunc_index} (A B : n-Type) : n-Type :=
trunctype.mk (A × B) _
infixr `×t`:30 := tprod
|
1b6ea057ec18fe139fb4e85019dce01a92c65aed | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/basic_auto.lean | b7e3649bead358b8a501e5dcfc3e453271d327a6 | [] | 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 | 26,033 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.subtype
import Mathlib.data.prod
import Mathlib.PostPort
universes u_1 u_2 u v w l
namespace Mathlib
/-!
# Basic definitions about `≤` and `<`
## Definitions
### Predicates on functions
- `monotone f`: a function between two types equipped with `≤` is monotone
if `a ≤ b` implies `f a ≤ f b`.
- `strict_mono f` : a function between two types equipped with `<` is strictly monotone
if `a < b` implies `f a < f b`.
- `order_dual α` : a type tag reversing the meaning of all inequalities.
### Transfering orders
- `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α`
using a function `f : α → β`.
- `partial_order.lift`, `linear_order.lift`: transfer a partial (resp., linear) order on `β` to a
partial (resp., linear) order on `α` using an injective function `f`.
### Extra classes
- `no_top_order`, `no_bot_order`: an order without a maximal/minimal element.
- `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists
`c`, `a<c<b`.
## Main theorems
- `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then
`f` is monotone;
- `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone.
## TODO
- expand module docs
- automatic construction of dual definitions / theorems
## See also
- `algebra.order` for basic lemmas about orders, and projection notation for orders
## Tags
preorder, order, partial order, linear order, monotone, strictly monotone
-/
theorem preorder.ext {α : Type u_1} {A : preorder α} {B : preorder α}
(H : ∀ (x y : α), x ≤ y ↔ x ≤ y) : A = B :=
sorry
theorem partial_order.ext {α : Type u_1} {A : partial_order α} {B : partial_order α}
(H : ∀ (x y : α), x ≤ y ↔ x ≤ y) : A = B :=
sorry
theorem linear_order.ext {α : Type u_1} {A : linear_order α} {B : linear_order α}
(H : ∀ (x y : α), x ≤ y ↔ x ≤ y) : A = B :=
sorry
/-- Given a relation `R` on `β` and a function `f : α → β`,
the preimage relation on `α` is defined by `x ≤ y ↔ f x ≤ f y`.
It is the unique relation on `α` making `f` a `rel_embedding`
(assuming `f` is injective). -/
@[simp] def order.preimage {α : Sort u_1} {β : Sort u_2} (f : α → β) (s : β → β → Prop) (x : α)
(y : α) :=
s (f x) (f y)
infixl:80 " ⁻¹'o " => Mathlib.order.preimage
/-- The preimage of a decidable order is decidable. -/
protected instance order.preimage.decidable {α : Sort u_1} {β : Sort u_2} (f : α → β)
(s : β → β → Prop) [H : DecidableRel s] : DecidableRel (f ⁻¹'o s) :=
fun (x y : α) => H (f x) (f y)
/-- A function between preorders is monotone if
`a ≤ b` implies `f a ≤ f b`. -/
def monotone {α : Type u} {β : Type v} [preorder α] [preorder β] (f : α → β) :=
∀ {a b : α}, a ≤ b → f a ≤ f b
theorem monotone_id {α : Type u} [preorder α] : monotone id := fun (x y : α) (h : x ≤ y) => h
theorem monotone_const {α : Type u} {β : Type v} [preorder α] [preorder β] {b : β} :
monotone fun (a : α) => b :=
fun (x y : α) (h : x ≤ y) => le_refl b
protected theorem monotone.comp {α : Type u} {β : Type v} {γ : Type w} [preorder α] [preorder β]
[preorder γ] {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) :=
fun (a b : α) (h : a ≤ b) => m_g (m_f h)
protected theorem monotone.iterate {α : Type u} [preorder α] {f : α → α} (hf : monotone f) (n : ℕ) :
monotone (nat.iterate f n) :=
nat.rec_on n monotone_id fun (n : ℕ) (ihn : monotone (nat.iterate f n)) => monotone.comp ihn hf
theorem monotone_of_monotone_nat {α : Type u} [preorder α] {f : ℕ → α}
(hf : ∀ (n : ℕ), f n ≤ f (n + 1)) : monotone f :=
sorry
theorem monotone.reflect_lt {α : Type u_1} {β : Type u_2} [linear_order α] [preorder β] {f : α → β}
(hf : monotone f) {x : α} {x' : α} (h : f x < f x') : x < x' :=
eq.mpr (id (Eq._oldrec (Eq.refl (x < x')) (Eq.symm (propext not_le))))
(id fun (h' : x' ≤ x) => not_le_of_lt h (hf h'))
/-- If `f` is a monotone function from `ℕ` to a preorder such that `y` lies between `f x` and
`f (x + 1)`, then `y` doesn't lie in the range of `f`. -/
theorem monotone.ne_of_lt_of_lt_nat {α : Type u_1} [preorder α] {f : ℕ → α} (hf : monotone f)
(x : ℕ) (x' : ℕ) {y : α} (h1 : f x < y) (h2 : y < f (x + 1)) : f x' ≠ y :=
sorry
/-- If `f` is a monotone function from `ℤ` to a preorder such that `y` lies between `f x` and
`f (x + 1)`, then `y` doesn't lie in the range of `f`. -/
theorem monotone.ne_of_lt_of_lt_int {α : Type u_1} [preorder α] {f : ℤ → α} (hf : monotone f)
(x : ℤ) (x' : ℤ) {y : α} (h1 : f x < y) (h2 : y < f (x + 1)) : f x' ≠ y :=
sorry
/-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/
def strict_mono {α : Type u} {β : Type v} [HasLess α] [HasLess β] (f : α → β) :=
∀ {a b : α}, a < b → f a < f b
theorem strict_mono_id {α : Type u} [HasLess α] : strict_mono id := fun (a b : α) => id
/-- A function `f` is strictly monotone increasing on `t` if `x < y` for `x,y ∈ t` implies
`f x < f y`. -/
def strict_mono_incr_on {α : Type u} {β : Type v} [HasLess α] [HasLess β] (f : α → β) (t : set α) :=
∀ {x : α}, x ∈ t → ∀ {y : α}, y ∈ t → x < y → f x < f y
/-- A function `f` is strictly monotone decreasing on `t` if `x < y` for `x,y ∈ t` implies
`f y < f x`. -/
def strict_mono_decr_on {α : Type u} {β : Type v} [HasLess α] [HasLess β] (f : α → β) (t : set α) :=
∀ {x : α}, x ∈ t → ∀ {y : α}, y ∈ t → x < y → f y < f x
/-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/
def order_dual (α : Type u_1) := α
namespace order_dual
protected instance nonempty (α : Type u_1) [h : Nonempty α] : Nonempty (order_dual α) := h
protected instance subsingleton (α : Type u_1) [h : subsingleton α] : subsingleton (order_dual α) :=
h
protected instance has_le (α : Type u_1) [HasLessEq α] : HasLessEq (order_dual α) :=
{ LessEq := fun (x y : α) => y ≤ x }
protected instance has_lt (α : Type u_1) [HasLess α] : HasLess (order_dual α) :=
{ Less := fun (x y : α) => y < x }
-- `dual_le` and `dual_lt` should not be simp lemmas:
-- they cause a loop since `α` and `order_dual α` are definitionally equal
theorem dual_le {α : Type u} [HasLessEq α] {a : α} {b : α} : a ≤ b ↔ b ≤ a := iff.rfl
theorem dual_lt {α : Type u} [HasLess α] {a : α} {b : α} : a < b ↔ b < a := iff.rfl
theorem dual_compares {α : Type u} [HasLess α] {a : α} {b : α} {o : ordering} :
ordering.compares o a b ↔ ordering.compares o b a :=
ordering.cases_on o iff.rfl eq_comm iff.rfl
protected instance preorder (α : Type u_1) [preorder α] : preorder (order_dual α) :=
preorder.mk LessEq Less sorry sorry
protected instance partial_order (α : Type u_1) [partial_order α] : partial_order (order_dual α) :=
partial_order.mk preorder.le preorder.lt sorry sorry sorry
protected instance linear_order (α : Type u_1) [linear_order α] : linear_order (order_dual α) :=
linear_order.mk partial_order.le partial_order.lt sorry sorry sorry sorry
((fun (this : DecidableRel fun (a b : α) => b ≤ a) => this)
fun (a b : α) => has_le.le.decidable b a)
Mathlib.decidable_eq_of_decidable_le
((fun (this : DecidableRel fun (a b : α) => b < a) => this)
fun (a b : α) => has_lt.lt.decidable b a)
protected instance inhabited {α : Type u} [Inhabited α] : Inhabited (order_dual α) := id
theorem preorder.dual_dual (α : Type u_1) [H : preorder α] :
order_dual.preorder (order_dual α) = H :=
preorder.ext fun (_x _x_1 : order_dual (order_dual α)) => iff.rfl
theorem partial_order.dual_dual (α : Type u_1) [H : partial_order α] :
order_dual.partial_order (order_dual α) = H :=
partial_order.ext fun (_x _x_1 : order_dual (order_dual α)) => iff.rfl
theorem linear_order.dual_dual (α : Type u_1) [H : linear_order α] :
order_dual.linear_order (order_dual α) = H :=
linear_order.ext fun (_x _x_1 : order_dual (order_dual α)) => iff.rfl
theorem cmp_le_flip {α : Type u_1} [HasLessEq α] [DecidableRel LessEq] (x : α) (y : α) :
cmp_le x y = cmp_le y x :=
rfl
end order_dual
namespace strict_mono_incr_on
protected theorem dual {α : Type u} {β : Type v} [preorder α] [preorder β] {f : α → β} {s : set α}
(H : strict_mono_incr_on f s) : strict_mono_incr_on f s :=
fun (x : order_dual α) (hx : x ∈ s) (y : order_dual α) (hy : y ∈ s) => H hy hx
protected theorem dual_right {α : Type u} {β : Type v} [preorder α] [preorder β] {f : α → β}
{s : set α} (H : strict_mono_incr_on f s) : strict_mono_decr_on f s :=
H
theorem le_iff_le {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β} {s : set α}
{x : α} {y : α} (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≤ f y ↔ x ≤ y :=
sorry
theorem lt_iff_lt {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β} {s : set α}
{x : α} {y : α} (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x < f y ↔ x < y :=
sorry
protected theorem compares {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β}
{s : set α} {x : α} {y : α} (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s)
{o : ordering} : ordering.compares o (f x) (f y) ↔ ordering.compares o x y :=
sorry
end strict_mono_incr_on
namespace strict_mono_decr_on
protected theorem dual {α : Type u} {β : Type v} [preorder α] [preorder β] {f : α → β} {s : set α}
(H : strict_mono_decr_on f s) : strict_mono_decr_on f s :=
fun (x : order_dual α) (hx : x ∈ s) (y : order_dual α) (hy : y ∈ s) => H hy hx
protected theorem dual_right {α : Type u} {β : Type v} [preorder α] [preorder β] {f : α → β}
{s : set α} (H : strict_mono_decr_on f s) : strict_mono_incr_on f s :=
H
theorem le_iff_le {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β} {s : set α}
{x : α} {y : α} (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≤ f y ↔ y ≤ x :=
strict_mono_incr_on.le_iff_le (strict_mono_decr_on.dual_right H) hy hx
theorem lt_iff_lt {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β} {s : set α}
{x : α} {y : α} (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x < f y ↔ y < x :=
strict_mono_incr_on.lt_iff_lt (strict_mono_decr_on.dual_right H) hy hx
protected theorem compares {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β}
{s : set α} {x : α} {y : α} (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s)
{o : ordering} : ordering.compares o (f x) (f y) ↔ ordering.compares o y x :=
iff.trans order_dual.dual_compares
(strict_mono_incr_on.compares (strict_mono_decr_on.dual_right H) hy hx)
end strict_mono_decr_on
namespace strict_mono
protected theorem strict_mono_incr_on {α : Type u} {β : Type v} [HasLess α] [HasLess β] {f : α → β}
(hf : strict_mono f) (s : set α) : strict_mono_incr_on f s :=
fun (x : α) (hx : x ∈ s) (y : α) (hy : y ∈ s) (hxy : x < y) => hf hxy
theorem comp {α : Type u} {β : Type v} {γ : Type w} [HasLess α] [HasLess β] [HasLess γ] {g : β → γ}
{f : α → β} (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) :=
fun (a b : α) (h : a < b) => hg (hf h)
protected theorem iterate {α : Type u} [HasLess α] {f : α → α} (hf : strict_mono f) (n : ℕ) :
strict_mono (nat.iterate f n) :=
nat.rec_on n strict_mono_id fun (n : ℕ) (ihn : strict_mono (nat.iterate f n)) => comp ihn hf
theorem id_le {φ : ℕ → ℕ} (h : strict_mono φ) (n : ℕ) : n ≤ φ n :=
nat.rec_on n (nat.zero_le (φ 0))
fun (n : ℕ) (hn : n ≤ φ n) => nat.succ_le_of_lt (lt_of_le_of_lt hn (h (nat.lt_succ_self n)))
protected theorem ite' {α : Type u} {β : Type v} [preorder α] [HasLess β] {f : α → β} {g : α → β}
(hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p]
(hp : ∀ {x y : α}, x < y → p y → p x) (hfg : ∀ {x y : α}, p x → ¬p y → x < y → f x < g y) :
strict_mono fun (x : α) => ite (p x) (f x) (g x) :=
sorry
protected theorem ite {α : Type u} {β : Type v} [preorder α] [preorder β] {f : α → β} {g : α → β}
(hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p]
(hp : ∀ {x y : α}, x < y → p y → p x) (hfg : ∀ (x : α), f x ≤ g x) :
strict_mono fun (x : α) => ite (p x) (f x) (g x) :=
strict_mono.ite' hf hg hp
fun (x y : α) (hx : p x) (hy : ¬p y) (h : x < y) => has_lt.lt.trans_le (hf h) (hfg y)
theorem lt_iff_lt {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β}
(H : strict_mono f) {a : α} {b : α} : f a < f b ↔ a < b :=
strict_mono_incr_on.lt_iff_lt (strict_mono.strict_mono_incr_on H set.univ) trivial trivial
protected theorem compares {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β}
(H : strict_mono f) {a : α} {b : α} {o : ordering} :
ordering.compares o (f a) (f b) ↔ ordering.compares o a b :=
strict_mono_incr_on.compares (strict_mono.strict_mono_incr_on H set.univ) trivial trivial
theorem injective {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β}
(H : strict_mono f) : function.injective f :=
fun (x y : α) (h : f x = f y) =>
(fun (this : ordering.compares ordering.eq x y) => this) (iff.mp (strict_mono.compares H) h)
theorem le_iff_le {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β}
(H : strict_mono f) {a : α} {b : α} : f a ≤ f b ↔ a ≤ b :=
strict_mono_incr_on.le_iff_le (strict_mono.strict_mono_incr_on H set.univ) trivial trivial
theorem top_preimage_top {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β}
(H : strict_mono f) {a : α} (h_top : ∀ (p : β), p ≤ f a) (x : α) : x ≤ a :=
iff.mp (le_iff_le H) (h_top (f x))
theorem bot_preimage_bot {α : Type u} {β : Type v} [linear_order α] [preorder β] {f : α → β}
(H : strict_mono f) {a : α} (h_bot : ∀ (p : β), f a ≤ p) (x : α) : a ≤ x :=
iff.mp (le_iff_le H) (h_bot (f x))
protected theorem nat {β : Type u_1} [preorder β] {f : ℕ → β} (h : ∀ (n : ℕ), f n < f (n + 1)) :
strict_mono f :=
sorry
-- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation,
-- then `strict_mono f` is vacuously true.
theorem monotone {α : Type u} {β : Type v} [partial_order α] [preorder β] {f : α → β}
(H : strict_mono f) : monotone f :=
fun (a b : α) (h : a ≤ b) =>
Or._oldrec (le_of_lt ∘ H)
(fun (h_1 : a = b) => Eq._oldrec (fun (h : a ≤ a) => le_refl (f a)) h_1 h) (lt_or_eq_of_le h)
end strict_mono
theorem injective_of_lt_imp_ne {α : Type u} {β : Type v} [linear_order α] {f : α → β}
(h : ∀ (x y : α), x < y → f x ≠ f y) : function.injective f :=
sorry
theorem strict_mono_of_monotone_of_injective {α : Type u} {β : Type v} [partial_order α]
[partial_order β] {f : α → β} (h₁ : monotone f) (h₂ : function.injective f) : strict_mono f :=
sorry
theorem monotone.strict_mono_iff_injective {α : Type u} {β : Type v} [linear_order α]
[partial_order β] {f : α → β} (h : monotone f) : strict_mono f ↔ function.injective f :=
{ mp := fun (h : strict_mono f) => strict_mono.injective h,
mpr := strict_mono_of_monotone_of_injective h }
theorem strict_mono_of_le_iff_le {α : Type u} {β : Type v} [preorder α] [preorder β] {f : α → β}
(h : ∀ (x y : α), x ≤ y ↔ f x ≤ f y) : strict_mono f :=
sorry
/-! ### Order instances on the function space -/
protected instance pi.preorder {ι : Type u} {α : ι → Type v} [(i : ι) → preorder (α i)] :
preorder ((i : ι) → α i) :=
preorder.mk (fun (x y : (i : ι) → α i) => ∀ (i : ι), x i ≤ y i)
(fun (a b : (i : ι) → α i) => (∀ (i : ι), a i ≤ b i) ∧ ¬∀ (i : ι), b i ≤ a i) sorry sorry
theorem pi.le_def {ι : Type u} {α : ι → Type v} [(i : ι) → preorder (α i)] {x : (i : ι) → α i}
{y : (i : ι) → α i} : x ≤ y ↔ ∀ (i : ι), x i ≤ y i :=
iff.rfl
theorem le_update_iff {ι : Type u} {α : ι → Type v} [(i : ι) → preorder (α i)] [DecidableEq ι]
{x : (i : ι) → α i} {y : (i : ι) → α i} {i : ι} {a : α i} :
x ≤ function.update y i a ↔ x i ≤ a ∧ ∀ (j : ι), j ≠ i → x j ≤ y j :=
function.forall_update_iff y fun (j : ι) (z : α j) => x j ≤ z
theorem update_le_iff {ι : Type u} {α : ι → Type v} [(i : ι) → preorder (α i)] [DecidableEq ι]
{x : (i : ι) → α i} {y : (i : ι) → α i} {i : ι} {a : α i} :
function.update x i a ≤ y ↔ a ≤ y i ∧ ∀ (j : ι), j ≠ i → x j ≤ y j :=
function.forall_update_iff x fun (j : ι) (z : α j) => z ≤ y j
protected instance pi.partial_order {ι : Type u} {α : ι → Type v} [(i : ι) → partial_order (α i)] :
partial_order ((i : ι) → α i) :=
partial_order.mk preorder.le preorder.lt sorry sorry sorry
theorem comp_le_comp_left_of_monotone {α : Type u} {β : Type v} {γ : Type w} [preorder α]
[preorder β] {f : β → α} {g : γ → β} {h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) :
f ∘ g ≤ f ∘ h :=
fun (x : γ) => m_f (le_gh x)
protected theorem monotone.order_dual {α : Type u} {γ : Type w} [preorder α] [preorder γ]
{f : α → γ} (hf : monotone f) : monotone f :=
fun (x y : order_dual α) (hxy : x ≤ y) => hf hxy
theorem monotone_lam {α : Type u} {β : Type v} {γ : Type w} [preorder α] [preorder γ]
{f : α → β → γ} (m : ∀ (b : β), monotone fun (a : α) => f a b) : monotone f :=
fun (a a' : α) (h : a ≤ a') (b : β) => m b h
theorem monotone_app {α : Type u} {β : Type v} {γ : Type w} [preorder α] [preorder γ]
(f : β → α → γ) (b : β) (m : monotone fun (a : α) (b : β) => f b a) : monotone (f b) :=
fun (a a' : α) (h : a ≤ a') => m h b
theorem strict_mono.order_dual {α : Type u} {β : Type v} [HasLess α] [HasLess β] {f : α → β}
(hf : strict_mono f) : strict_mono f :=
fun (x y : order_dual α) (hxy : x < y) => hf hxy
/-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/
def preorder.lift {α : Type u_1} {β : Type u_2} [preorder β] (f : α → β) : preorder α :=
preorder.mk (fun (x y : α) => f x ≤ f y) (fun (x y : α) => f x < f y) sorry sorry
/-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective
function `f : α → β`. -/
def partial_order.lift {α : Type u_1} {β : Type u_2} [partial_order β] (f : α → β)
(inj : function.injective f) : partial_order α :=
partial_order.mk preorder.le preorder.lt sorry sorry sorry
/-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective
function `f : α → β`. -/
def linear_order.lift {α : Type u_1} {β : Type u_2} [linear_order β] (f : α → β)
(inj : function.injective f) : linear_order α :=
linear_order.mk partial_order.le partial_order.lt sorry sorry sorry sorry
(fun (x y : α) => infer_instance)
(fun (x y : α) => decidable_of_iff (f x = f y) (function.injective.eq_iff inj))
fun (x y : α) => infer_instance
protected instance subtype.preorder {α : Type u_1} [preorder α] (p : α → Prop) :
preorder (Subtype p) :=
preorder.lift subtype.val
@[simp] theorem subtype.mk_le_mk {α : Type u_1} [preorder α] {p : α → Prop} {x : α} {y : α}
{hx : p x} {hy : p y} : { val := x, property := hx } ≤ { val := y, property := hy } ↔ x ≤ y :=
iff.rfl
@[simp] theorem subtype.mk_lt_mk {α : Type u_1} [preorder α] {p : α → Prop} {x : α} {y : α}
{hx : p x} {hy : p y} : { val := x, property := hx } < { val := y, property := hy } ↔ x < y :=
iff.rfl
@[simp] theorem subtype.coe_le_coe {α : Type u_1} [preorder α] {p : α → Prop} {x : Subtype p}
{y : Subtype p} : ↑x ≤ ↑y ↔ x ≤ y :=
iff.rfl
@[simp] theorem subtype.coe_lt_coe {α : Type u_1} [preorder α] {p : α → Prop} {x : Subtype p}
{y : Subtype p} : ↑x < ↑y ↔ x < y :=
iff.rfl
protected instance subtype.partial_order {α : Type u_1} [partial_order α] (p : α → Prop) :
partial_order (Subtype p) :=
partial_order.lift subtype.val subtype.val_injective
protected instance subtype.linear_order {α : Type u_1} [linear_order α] (p : α → Prop) :
linear_order (Subtype p) :=
linear_order.lift subtype.val subtype.val_injective
theorem subtype.mono_coe {α : Type u} [preorder α] (t : set α) : monotone coe :=
fun (x y : Subtype t) => id
theorem subtype.strict_mono_coe {α : Type u} [preorder α] (t : set α) : strict_mono coe :=
fun (x y : Subtype t) => id
protected instance prod.has_le (α : Type u) (β : Type v) [HasLessEq α] [HasLessEq β] :
HasLessEq (α × β) :=
{ LessEq := fun (p q : α × β) => prod.fst p ≤ prod.fst q ∧ prod.snd p ≤ prod.snd q }
protected instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] :
preorder (α × β) :=
preorder.mk LessEq (fun (a b : α × β) => a ≤ b ∧ ¬b ≤ a) sorry sorry
/-- The pointwise partial order on a product.
(The lexicographic ordering is defined in order/lexicographic.lean, and the instances are
available via the type synonym `lex α β = α × β`.) -/
protected instance prod.partial_order (α : Type u) (β : Type v) [partial_order α]
[partial_order β] : partial_order (α × β) :=
partial_order.mk preorder.le preorder.lt sorry sorry sorry
/-!
### Additional order classes
-/
/-- order without a top element; somtimes called cofinal -/
class no_top_order (α : Type u) [preorder α] where
no_top : ∀ (a : α), ∃ (a' : α), a < a'
theorem no_top {α : Type u} [preorder α] [no_top_order α] (a : α) : ∃ (a' : α), a < a' :=
no_top_order.no_top
protected instance nonempty_gt {α : Type u} [preorder α] [no_top_order α] (a : α) :
Nonempty (Subtype fun (x : α) => a < x) :=
iff.mpr nonempty_subtype (no_top a)
/-- order without a bottom element; somtimes called coinitial or dense -/
class no_bot_order (α : Type u) [preorder α] where
no_bot : ∀ (a : α), ∃ (a' : α), a' < a
theorem no_bot {α : Type u} [preorder α] [no_bot_order α] (a : α) : ∃ (a' : α), a' < a :=
no_bot_order.no_bot
protected instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] :
no_top_order (order_dual α) :=
no_top_order.mk fun (a : order_dual α) => no_bot a
protected instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] :
no_bot_order (order_dual α) :=
no_bot_order.mk fun (a : order_dual α) => no_top a
protected instance nonempty_lt {α : Type u} [preorder α] [no_bot_order α] (a : α) :
Nonempty (Subtype fun (x : α) => x < a) :=
iff.mpr nonempty_subtype (no_bot a)
/-- An order is dense if there is an element between any pair of distinct elements. -/
class densely_ordered (α : Type u) [preorder α] where
dense : ∀ (a₁ a₂ : α), a₁ < a₂ → ∃ (a : α), a₁ < a ∧ a < a₂
theorem exists_between {α : Type u} [preorder α] [densely_ordered α] {a₁ : α} {a₂ : α} :
a₁ < a₂ → ∃ (a : α), a₁ < a ∧ a < a₂ :=
densely_ordered.dense
protected instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] :
densely_ordered (order_dual α) :=
densely_ordered.mk
fun (a₁ a₂ : order_dual α) (ha : a₁ < a₂) =>
Exists.imp (fun (a : α) => and.symm) (exists_between ha)
theorem le_of_forall_le_of_dense {α : Type u} [linear_order α] [densely_ordered α] {a₁ : α} {a₂ : α}
(h : ∀ (a₃ : α), a₃ > a₂ → a₁ ≤ a₃) : a₁ ≤ a₂ :=
sorry
theorem eq_of_le_of_forall_le_of_dense {α : Type u} [linear_order α] [densely_ordered α] {a₁ : α}
{a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀ (a₃ : α), a₃ > a₂ → a₁ ≤ a₃) : a₁ = a₂ :=
le_antisymm (le_of_forall_le_of_dense h₂) h₁
theorem le_of_forall_ge_of_dense {α : Type u} [linear_order α] [densely_ordered α] {a₁ : α} {a₂ : α}
(h : ∀ (a₃ : α), a₃ < a₁ → a₃ ≤ a₂) : a₁ ≤ a₂ :=
sorry
theorem eq_of_le_of_forall_ge_of_dense {α : Type u} [linear_order α] [densely_ordered α] {a₁ : α}
{a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀ (a₃ : α), a₃ < a₁ → a₃ ≤ a₂) : a₁ = a₂ :=
le_antisymm (le_of_forall_ge_of_dense h₂) h₁
theorem dense_or_discrete {α : Type u} [linear_order α] (a₁ : α) (a₂ : α) :
(∃ (a : α), a₁ < a ∧ a < a₂) ∨ (∀ (a : α), a > a₁ → a₂ ≤ a) ∧ ∀ (a : α), a < a₂ → a ≤ a₁ :=
sorry
/-- Type synonym to create an instance of `linear_order` from a
`partial_order` and `[is_total α (≤)]` -/
def as_linear_order (α : Type u) := α
protected instance as_linear_order.inhabited {α : Type u_1} [Inhabited α] :
Inhabited (as_linear_order α) :=
{ default := Inhabited.default }
protected instance as_linear_order.linear_order {α : Type u_1} [partial_order α]
[is_total α LessEq] : linear_order (as_linear_order α) :=
linear_order.mk partial_order.le partial_order.lt partial_order.le_refl partial_order.le_trans
partial_order.le_antisymm sorry (classical.dec_rel LessEq) Mathlib.decidable_eq_of_decidable_le
Mathlib.decidable_lt_of_decidable_le
end Mathlib |
7008ba53bc9a0783364fc5c4610a2174e72c86c7 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /counterexamples/linear_order_with_pos_mul_pos_eq_zero.lean | 96fe79c14b7b810fe16201939d0b06f1d26507a5 | [
"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 | 2,139 | lean | /-
Copyright (c) 2021 Johan Commelin.
All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Damiano Testa, Kevin Buzzard
-/
import algebra.ordered_monoid
/-!
An example of a `linear_ordered_comm_monoid_with_zero` in which the product of two positive
elements vanishes.
This is the monoid with 3 elements `0, ε, 1` where `ε ^ 2 = 0` and everything else is forced.
The order is `0 < ε < 1`. Since `ε ^ 2 = 0`, the product of strictly positive elements can vanish.
Relevant Zulip chat:
https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/mul_pos
-/
/-- The three element monoid. -/
@[derive [decidable_eq]]
inductive foo
| zero
| eps
| one
namespace foo
instance inhabited : inhabited foo := ⟨zero⟩
instance : has_zero foo := ⟨zero⟩
instance : has_one foo := ⟨one⟩
notation `ε` := eps
/-- The order on `foo` is the one induced by the natural order on the image of `aux1`. -/
def aux1 : foo → ℕ
| 0 := 0
| ε := 1
| 1 := 2
/-- A tactic to prove facts by cases. -/
meta def boom : tactic unit :=
`[repeat {rintro ⟨⟩}; dec_trivial]
lemma aux1_inj : function.injective aux1 :=
by boom
instance : linear_order foo :=
linear_order.lift aux1 $ aux1_inj
/-- Multiplication on `foo`: the only external input is that `ε ^ 2 = 0`. -/
def mul : foo → foo → foo
| 1 x := x
| x 1 := x
| _ _ := 0
instance : comm_monoid foo :=
{ mul := mul,
one := 1,
one_mul := by boom,
mul_one := by boom,
mul_comm := by boom,
mul_assoc := by boom }
instance : linear_ordered_comm_monoid_with_zero foo :=
{ zero := 0,
zero_mul := by boom,
mul_zero := by boom,
mul_le_mul_left := by { rintro ⟨⟩ ⟨⟩ h ⟨⟩; revert h; dec_trivial },
zero_le_one := dec_trivial,
.. foo.linear_order,
.. foo.comm_monoid }
lemma not_mul_pos : ¬ ∀ {M : Type} [linear_ordered_comm_monoid_with_zero M], by exactI ∀
(a b : M) (ha : 0 < a) (hb : 0 < b),
0 < a * b :=
begin
intros h,
specialize h ε ε (by boom) (by boom),
exact (lt_irrefl 0 (h.trans_le (by boom))).elim,
end
example : 0 < ε ∧ ε * ε = 0 := by boom
end foo
|
8f3b763dfec80240e25b3cf4ba9628824beae209 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /src/Lean/Elab/Syntax.lean | 5b74d6f5af5e8837f3abfb5dbaa23cd2257677ec | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,738 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Command
import Lean.Parser.Syntax
import Lean.Elab.Util
namespace Lean.Elab.Term
/-
Expand `optional «precedence»` where
«precedence» := leading_parser " : " >> precedenceParser -/
def expandOptPrecedence (stx : Syntax) : MacroM (Option Nat) :=
if stx.isNone then
return none
else
return some (← evalPrec stx[0][1])
private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := do
if ds.size == 0 then
throwUnsupportedSyntax
else if ds.size == 1 then
pure ds[0]
else
let mut r := ds[0]
for d in ds[1:ds.size] do
r ← `(ParserDescr.binary `andthen $r $d)
return r
structure ToParserDescrContext where
catName : Name
first : Bool
leftRec : Bool -- true iff left recursion is allowed
/- See comment at `Parser.ParserCategory`. -/
behavior : Parser.LeadingIdentBehavior
abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT (Option Nat) TermElabM)
private def markAsTrailingParser (lhsPrec : Nat) : ToParserDescrM Unit := set (some lhsPrec)
@[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α :=
withReader (fun ctx => { ctx with first := false }) x
@[inline] private def withNestedParser {α} (x : ToParserDescrM α) : ToParserDescrM α :=
withReader (fun ctx => { ctx with leftRec := false, first := false }) x
def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do
let ctx ← read
unless ctx.first && stx.getKind == ``Lean.Parser.Syntax.cat do
return false
let cat := stx[0].getId.eraseMacroScopes
unless cat == ctx.catName do
return false
let prec? ← liftMacroM <| expandOptPrecedence stx[1]
unless ctx.leftRec do
throwErrorAt stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion"
markAsTrailingParser (prec?.getD 0)
return true
/--
Given a `stx` of category `syntax`, return a pair `(newStx, lhsPrec?)`,
where `newStx` is of category `term`. After elaboration, `newStx` should have type
`TrailingParserDescr` if `lhsPrec?.isSome`, and `ParserDescr` otherwise. -/
partial def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Option Nat) := do
let env ← getEnv
let behavior := Parser.leadingIdentBehavior env catName
(process stx { catName := catName, first := true, leftRec := true, behavior := behavior }).run none
where
process (stx : Syntax) : ToParserDescrM Syntax := withRef stx do
let kind := stx.getKind
if kind == nullKind then
processSeq stx
else if kind == choiceKind then
process stx[0]
else if kind == ``Lean.Parser.Syntax.paren then
process stx[1]
else if kind == ``Lean.Parser.Syntax.cat then
processNullaryOrCat stx
else if kind == ``Lean.Parser.Syntax.unary then
processUnary stx
else if kind == ``Lean.Parser.Syntax.binary then
processBinary stx
else if kind == ``Lean.Parser.Syntax.sepBy then
processSepBy stx
else if kind == ``Lean.Parser.Syntax.sepBy1 then
processSepBy1 stx
else if kind == ``Lean.Parser.Syntax.atom then
processAtom stx
else if kind == ``Lean.Parser.Syntax.nonReserved then
processNonReserved stx
else
let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _)
match stxNew? with
| some stxNew => process stxNew
| none => throwErrorAt stx "unexpected syntax kind of category `syntax`: {kind}"
/- Sequence (aka NullNode) -/
processSeq (stx : Syntax) := do
let args := stx.getArgs
if (← checkLeftRec stx[0]) then
if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax"
let args := args.eraseIdx 0
let args ← args.mapM fun arg => withNestedParser do process arg
mkParserSeq args
else
let args ← args.mapIdxM fun i arg => withReader (fun ctx => { ctx with first := ctx.first && i.val == 0 }) do process arg
mkParserSeq args
/- Resolve the given parser name and return a list of candidates.
Each candidate is a pair `(resolvedParserName, isDescr)`.
`isDescr == true` if the type of `resolvedParserName` is a `ParserDescr`. -/
resolveParserName (parserName : Syntax) : ToParserDescrM (List (Name × Bool)) := do
try
let candidates ← resolveGlobalConstWithInfos parserName
/- Convert `candidates` in a list of pairs `(c, isDescr)`, where `c` is the parser name,
and `isDescr` is true iff `c` has type `Lean.ParserDescr` or `Lean.TrailingParser` -/
let env ← getEnv
candidates.filterMap fun c =>
match env.find? c with
| none => none
| some info =>
match info.type with
| Expr.const ``Lean.Parser.TrailingParser _ _ => (c, false)
| Expr.const ``Lean.Parser.Parser _ _ => (c, false)
| Expr.const ``Lean.ParserDescr _ _ => (c, true)
| Expr.const ``Lean.TrailingParserDescr _ _ => (c, true)
| _ => none
catch _ => return []
ensureNoPrec (stx : Syntax) :=
unless stx[1].isNone do
throwErrorAt stx[1] "unexpected precedence"
processParserCategory (stx : Syntax) := do
let catName := stx[0].getId.eraseMacroScopes
if (← read).first && catName == (← read).catName then
throwErrorAt stx "invalid atomic left recursive syntax"
let prec? ← liftMacroM <| expandOptPrecedence stx[1]
let prec := prec?.getD 0
`(ParserDescr.cat $(quote catName) $(quote prec))
processNullaryOrCat (stx : Syntax) := do
match (← resolveParserName stx[0]) with
| [(c, true)] => ensureNoPrec stx; return mkIdentFrom stx c
| [(c, false)] => ensureNoPrec stx; `(ParserDescr.parser $(quote c))
| cs@(_ :: _ :: _) => throwError "ambiguous parser declaration {cs.map (·.1)}"
| [] =>
let id := stx[0].getId.eraseMacroScopes
if Parser.isParserCategory (← getEnv) id then
processParserCategory stx
else if (← Parser.isParserAlias id) then
ensureNoPrec stx
Parser.ensureConstantParserAlias id
`(ParserDescr.const $(quote id))
else
throwError "unknown parser declaration/category/alias '{id}'"
processUnary (stx : Syntax) := do
let aliasName := (stx[0].getId).eraseMacroScopes
Parser.ensureUnaryParserAlias aliasName
let d ← withNestedParser do process stx[2]
`(ParserDescr.unary $(quote aliasName) $d)
processBinary (stx : Syntax) := do
let aliasName := (stx[0].getId).eraseMacroScopes
Parser.ensureBinaryParserAlias aliasName
let d₁ ← withNestedParser do process stx[2]
let d₂ ← withNestedParser do process stx[4]
`(ParserDescr.binary $(quote aliasName) $d₁ $d₂)
processSepBy (stx : Syntax) := do
let p ← withNestedParser $ process stx[1]
let sep := stx[3]
let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1]
let allowTrailingSep := !stx[5].isNone
`(ParserDescr.sepBy $p $sep $psep $(quote allowTrailingSep))
processSepBy1 (stx : Syntax) := do
let p ← withNestedParser do process stx[1]
let sep := stx[3]
let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1]
let allowTrailingSep := !stx[5].isNone
`(ParserDescr.sepBy1 $p $sep $psep $(quote allowTrailingSep))
isValidAtom (s : String) : Bool :=
s[0] != '\'' &&
s[0] != '\"' &&
s[0] != '`' &&
!s[0].isDigit
processAtom (stx : Syntax) := do
match stx[0].isStrLit? with
| some atom =>
unless isValidAtom atom do
throwErrorAt stx "invalid atom"
/- For syntax categories where initialized with `LeadingIdentBehavior` different from default (e.g., `tactic`), we automatically mark
the first symbol as nonReserved. -/
if (← read).behavior != Parser.LeadingIdentBehavior.default && (← read).first then
`(ParserDescr.nonReservedSymbol $(quote atom) false)
else
`(ParserDescr.symbol $(quote atom))
| none => throwUnsupportedSyntax
processNonReserved (stx : Syntax) := do
match stx[1].isStrLit? with
| some atom => `(ParserDescr.nonReservedSymbol $(quote atom) false)
| none => throwUnsupportedSyntax
end Term
namespace Command
open Lean.Syntax
open Lean.Parser.Term hiding macroArg
open Lean.Parser.Command
private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do
if let Name.str _ suffix _ := catName then
let quotSymbol := "`(" ++ suffix ++ "|"
let name := catName ++ `quot
-- TODO(Sebastian): this might confuse the pretty printer, but it lets us reuse the elaborator
let kind := ``Lean.Parser.Term.quot
let cmd ← `(
@[termParser] def $(mkIdent name) : Lean.ParserDescr :=
Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec)
(Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol))
(Lean.ParserDescr.binary `andthen
(Lean.ParserDescr.unary `incQuotDepth (Lean.ParserDescr.cat $(quote catName) 0))
(Lean.ParserDescr.symbol ")"))))
elabCommand cmd
@[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do
let catName := stx[1].getId
let catBehavior :=
if stx[2].isNone then
Parser.LeadingIdentBehavior.default
else if stx[2][3].getKind == ``Parser.Command.catBehaviorBoth then
Parser.LeadingIdentBehavior.both
else
Parser.LeadingIdentBehavior.symbol
let attrName := catName.appendAfter "Parser"
let env ← getEnv
let env ← Parser.registerParserCategory env attrName catName catBehavior
setEnv env
declareSyntaxCatQuotParser catName
/--
Auxiliary function for creating declaration names from parser descriptions.
Example:
Given
```
syntax term "+" term : term
syntax "[" sepBy(term, ", ") "]" : term
```
It generates the names `term_+_` and `term[_,]`
-/
partial def mkNameFromParserSyntax (catName : Name) (stx : Syntax) : MacroM Name := do
mkUnusedBaseName <| Name.mkSimple <| appendCatName <| visit stx ""
where
visit (stx : Syntax) (acc : String) : String :=
match stx.isStrLit? with
| some val => acc ++ (val.trim.map fun c => if c.isWhitespace then '_' else c).capitalize
| none =>
match stx with
| Syntax.node k args =>
if k == ``Lean.Parser.Syntax.cat then
acc ++ "_"
else
args.foldl (init := acc) fun acc arg => visit arg acc
| Syntax.ident .. => acc
| Syntax.atom .. => acc
| Syntax.missing => acc
appendCatName (str : String) :=
match catName with
| Name.str _ s _ => s ++ str
| _ => str
/- We assume a new syntax can be treated as an atom when it starts and ends with a token.
Here are examples of atom-like syntax.
```
syntax "(" term ")" : term
syntax "[" (sepBy term ",") "]" : term
syntax "foo" : term
```
-/
private partial def isAtomLikeSyntax (stx : Syntax) : Bool :=
let kind := stx.getKind
if kind == nullKind then
isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1]
else if kind == choiceKind then
isAtomLikeSyntax stx[0] -- see toParserDescr
else if kind == ``Lean.Parser.Syntax.paren then
isAtomLikeSyntax stx[1]
else
kind == ``Lean.Parser.Syntax.atom
def resolveSyntaxKind (k : Name) : CommandElabM Name := do
checkSyntaxNodeKindAtNamespaces k (← getCurrNamespace)
<|>
throwError "invalid syntax node kind '{k}'"
@[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do
let `($[$doc?:docComment]? $attrKind:attrKind syntax $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $[$ps:stx]* : $catStx) ← pure stx
| throwUnsupportedSyntax
let cat := catStx.getId.eraseMacroScopes
unless (Parser.isParserCategory (← getEnv) cat) do
throwErrorAt catStx "unknown category '{cat}'"
let syntaxParser := mkNullNode ps
-- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise.
let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec
let prec ← match prec? with
| some prec => liftMacroM <| evalPrec prec
| none => precDefault
let name ← match name? with
| some name => pure name.getId
| none => liftMacroM <| mkNameFromParserSyntax cat syntaxParser
let prio ← liftMacroM <| evalOptPrio prio?
let stxNodeKind := (← getCurrNamespace) ++ name
let catParserId := mkIdentFrom stx (cat.appendAfter "Parser")
let (val, lhsPrec?) ← runTermElabM none fun _ => Term.toParserDescr syntaxParser cat
let declName := mkIdentFrom stx name
let d ←
if let some lhsPrec := lhsPrec? then
`($[$doc?:docComment]? @[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName:ident : Lean.TrailingParserDescr :=
ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $(quote lhsPrec) $val)
else
`($[$doc?:docComment]? @[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName:ident : Lean.ParserDescr :=
ParserDescr.node $(quote stxNodeKind) $(quote prec) $val)
trace `Elab fun _ => d
withMacroExpansion stx d <| elabCommand d
@[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do
let `($[$doc?:docComment]? syntax $declName:ident := $[$ps:stx]*) ← pure stx | throwUnsupportedSyntax
-- TODO: nonatomic names
let (val, _) ← runTermElabM none $ fun _ => Term.toParserDescr (mkNullNode ps) Name.anonymous
let stxNodeKind := (← getCurrNamespace) ++ declName.getId
let stx' ← `($[$doc?:docComment]? def $declName:ident : Lean.ParserDescr := ParserDescr.nodeWithAntiquot $(quote (toString declName.getId)) $(quote stxNodeKind) $val)
withMacroExpansion stx stx' $ elabCommand stx'
def checkRuleKind (given expected : SyntaxNodeKind) : Bool :=
given == expected || given == expected ++ `antiquot
def inferMacroRulesAltKind : Syntax → CommandElabM SyntaxNodeKind
| `(matchAltExpr| | $pats,* => $rhs) => do
let pat := pats.elemsAndSeps[0]
if !pat.isQuot then
throwUnsupportedSyntax
let quoted := getQuotContent pat
pure quoted.getKind
| _ => throwUnsupportedSyntax
/--
Infer syntax kind `k` from first pattern, put alternatives of same kind into new `macro/elab_rules (kind := k)` via `mkCmd (some k)`,
leave remaining alternatives (via `mkCmd none`) to be recursively expanded. -/
def expandNoKindMacroRulesAux (alts : Array Syntax) (cmdName : String) (mkCmd : Option Name → Array Syntax → CommandElabM Syntax) : CommandElabM Syntax := do
let mut k ← inferMacroRulesAltKind alts[0]
if k.isStr && k.getString! == "antiquot" then
k := k.getPrefix
if k == choiceKind then
throwErrorAt alts[0]
"invalid {cmdName} alternative, multiple interpretations for pattern (solution: specify node kind using `{cmdName} (kind := ...) ...`)"
else
let altsK ← alts.filterM fun alt => return checkRuleKind (← inferMacroRulesAltKind alt) k
let altsNotK ← alts.filterM fun alt => return !checkRuleKind (← inferMacroRulesAltKind alt) k
if altsNotK.isEmpty then
mkCmd k altsK
else
mkNullNode #[← mkCmd k altsK, ← mkCmd none altsNotK]
def strLitToPattern (stx: Syntax) : MacroM Syntax :=
match stx.isStrLit? with
| some str => pure $ mkAtomFrom stx str
| none => Macro.throwUnsupported
builtin_initialize
registerTraceClass `Elab.syntax
end Lean.Elab.Command
|
e1a647cfd1b0363af094f7e5330cf22f9ec27cfb | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/parsing_only.lean | e542e4cc685a950631ef31ac6d73327cc1d4e4a0 | [
"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 | 199 | lean | import logic
constant f : num → num
constant g : num → num
notation a `+++` := f a
notation [parsing_only] a `***` := g a
check 10 +++
check 10 ***
check Type.{8} -- Type₊ should not be used
|
4e456522acc53a9841cc7c7d8563d9594ede2ec5 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/macroElabRulesIssue2.lean | 640f98cda8320c2646bb9ea2cdfab4308dc409da | [
"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 | 489 | lean | import Lean
open Lean Elab
declare_syntax_cat fixDecl
syntax ident : fixDecl
syntax ident "<" term : fixDecl
syntax "Fix₁ " fixDecl : tactic
elab_rules : tactic
| `(tactic| Fix₁ $x:ident) => logInfo "simple"
elab_rules : tactic
| `(tactic| Fix₁ $x:ident < $bound:term) =>
throwError "Failed at elab_rules"
macro_rules
| `(ℕ) => `(Nat)
example : ∀ b : ℕ, ∀ a : Nat, a ≥ 2 → a / a = 1 := by
Fix₁ b
Fix₁ a < 2 -- should produce `Failed at elab_rules`
|
477888f87ab88bd6473c79a432f56f84c1248a60 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/bug_proving_eqn_lemmas.lean | 0bd728ff1bd65bc31e0de4c7424e96b39766c99d | [
"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 | 355 | lean | universe variables u
inductive bintree (α : Type u)
| leaf : α → bintree
| node : bintree → bintree → bintree
open bintree
def to_list {α : Type u} : bintree α → list α → list α
| (leaf α) l := α :: l
| (node t₁ t₂) l := to_list t₁ (to_list t₂ l)
#eval to_list (node (node (leaf 1) (leaf 2)) (node (leaf 3) (leaf 4))) []
|
d91027d991c857fb57751d181119df8452ea803f | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/eqn_sanitizer1.lean | e72a5561746789dd04528068aaa1b385f7090554 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 442 | lean | set_option eqn_compiler.dsimp true
attribute [eqn_sanitizer]
definition succ_eq (a : nat) : nat.succ a = a + 1 :=
rfl
attribute [eqn_sanitizer]
definition succ_add_eq (a : nat) : nat.succ (a + 1) = a + 2 :=
rfl
definition fib : nat → nat
| 0 := 1
| 1 := 1
| (n+2) := fib (n+1) + fib n
example : fib 0 = 1 := rfl
example : fib 1 = 1 := rfl
example (n : nat) : fib (n+2) = fib (n+1) + fib n := rfl
print fib._main.equations.eqn_3
|
d5d3706f8b3f48b9d3f63c18fb1dae43a1984bcc | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/monoidal/category_auto.lean | 6cf7cf6e56b56a3c863d66a934cdf44b97b50468 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,384 | lean | /-
Copyright (c) 2018 Michael Jendrusch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Jendrusch, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.products.basic
import Mathlib.PostPort
universes v u l
namespace Mathlib
/-!
# Monoidal categories
A monoidal category is a category equipped with a tensor product, unitors, and an associator.
In the definition, we provide the tensor product as a pair of functions
* `tensor_obj : C → C → C`
* `tensor_hom : (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))`
and allow use of the overloaded notation `⊗` for both.
The unitors and associator are provided componentwise.
The tensor product can be expressed as a functor via `tensor : C × C ⥤ C`.
The unitors and associator are gathered together as natural
isomorphisms in `left_unitor_nat_iso`, `right_unitor_nat_iso` and `associator_nat_iso`.
Some consequences of the definition are proved in other files,
e.g. `(λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom` in `category_theory.monoidal.unitors_equal`.
## Implementation
Dealing with unitors and associators is painful, and at this stage we do not have a useful
implementation of coherence for monoidal categories.
In an effort to lessen the pain, we put some effort into choosing the right `simp` lemmas.
Generally, the rule is that the component index of a natural transformation "weighs more"
in considering the complexity of an expression than does a structural isomorphism (associator, etc).
As an example when we prove Proposition 2.2.4 of
<http://www-math.mit.edu/~etingof/egnobookfinal.pdf>
we state it as a `@[simp]` lemma as
```
(λ_ (X ⊗ Y)).hom = (α_ (𝟙_ C) X Y).inv ≫ (λ_ X).hom ⊗ (𝟙 Y)
```
This is far from completely effective, but seems to prove a useful principle.
## References
* Tensor categories, Etingof, Gelaki, Nikshych, Ostrik,
http://www-math.mit.edu/~etingof/egnobookfinal.pdf
* https://stacks.math.columbia.edu/tag/0FFK.
-/
namespace category_theory
/--
In a monoidal category, we can take the tensor product of objects, `X ⊗ Y` and of morphisms `f ⊗ g`.
Tensor product does not need to be strictly associative on objects, but there is a
specified associator, `α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)`. There is a tensor unit `𝟙_ C`,
with specified left and right unitor isomorphisms `λ_ X : 𝟙_ C ⊗ X ≅ X` and `ρ_ X : X ⊗ 𝟙_ C ≅ X`.
These associators and unitors satisfy the pentagon and triangle equations.
See https://stacks.math.columbia.edu/tag/0FFK.
-/
-- curried tensor product of objects:
class monoidal_category (C : Type u) [𝒞 : category C] where
tensor_obj : C → C → C
tensor_hom : {X₁ Y₁ X₂ Y₂ : C} → (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → (tensor_obj X₁ X₂ ⟶ tensor_obj Y₁ Y₂)
tensor_id' :
autoParam (C → C → tensor_hom 𝟙 𝟙 = 𝟙)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
tensor_comp' :
autoParam
(∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂),
tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom f₁ f₂ ≫ tensor_hom g₁ g₂)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
tensor_unit : C
associator : (X Y Z : C) → tensor_obj (tensor_obj X Y) Z ≅ tensor_obj X (tensor_obj Y Z)
associator_naturality' :
autoParam
(∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃),
tensor_hom (tensor_hom f₁ f₂) f₃ ≫ iso.hom (associator Y₁ Y₂ Y₃) =
iso.hom (associator X₁ X₂ X₃) ≫ tensor_hom f₁ (tensor_hom f₂ f₃))
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
left_unitor : (X : C) → tensor_obj tensor_unit X ≅ X
left_unitor_naturality' :
autoParam
(∀ {X Y : C} (f : X ⟶ Y),
tensor_hom 𝟙 f ≫ iso.hom (left_unitor Y) = iso.hom (left_unitor X) ≫ f)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
right_unitor : (X : C) → tensor_obj X tensor_unit ≅ X
right_unitor_naturality' :
autoParam
(∀ {X Y : C} (f : X ⟶ Y),
tensor_hom f 𝟙 ≫ iso.hom (right_unitor Y) = iso.hom (right_unitor X) ≫ f)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
pentagon' :
autoParam
(∀ (W X Y Z : C),
tensor_hom (iso.hom (associator W X Y)) 𝟙 ≫
iso.hom (associator W (tensor_obj X Y) Z) ≫ tensor_hom 𝟙 (iso.hom (associator X Y Z)) =
iso.hom (associator (tensor_obj W X) Y Z) ≫ iso.hom (associator W X (tensor_obj Y Z)))
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
triangle' :
autoParam
(∀ (X Y : C),
iso.hom (associator X tensor_unit Y) ≫ tensor_hom 𝟙 (iso.hom (left_unitor Y)) =
tensor_hom (iso.hom (right_unitor X)) 𝟙)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
-- curried tensor product of morphisms:
-- tensor product laws:
-- tensor unit:
-- associator:
-- left unitor:
-- right unitor:
-- pentagon identity:
-- triangle identity:
@[simp] theorem monoidal_category.tensor_id {C : Type u} [𝒞 : category C] [c : monoidal_category C]
(X₁ : C) (X₂ : C) : monoidal_category.tensor_hom 𝟙 𝟙 = 𝟙 :=
sorry
@[simp] theorem monoidal_category.tensor_comp {C : Type u} [𝒞 : category C]
[c : monoidal_category C] {X₁ : C} {Y₁ : C} {Z₁ : C} {X₂ : C} {Y₂ : C} {Z₂ : C} (f₁ : X₁ ⟶ Y₁)
(f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) :
monoidal_category.tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) =
monoidal_category.tensor_hom f₁ f₂ ≫ monoidal_category.tensor_hom g₁ g₂ :=
sorry
theorem monoidal_category.tensor_comp_assoc {C : Type u} [𝒞 : category C] [c : monoidal_category C]
{X₁ : C} {Y₁ : C} {Z₁ : C} {X₂ : C} {Y₂ : C} {Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂)
(g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) {X' : C} (f' : monoidal_category.tensor_obj Z₁ Z₂ ⟶ X') :
monoidal_category.tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) ≫ f' =
monoidal_category.tensor_hom f₁ f₂ ≫ monoidal_category.tensor_hom g₁ g₂ ≫ f' :=
sorry
theorem monoidal_category.associator_naturality {C : Type u} [𝒞 : category C]
[c : monoidal_category C] {X₁ : C} {X₂ : C} {X₃ : C} {Y₁ : C} {Y₂ : C} {Y₃ : C} (f₁ : X₁ ⟶ Y₁)
(f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) :
monoidal_category.tensor_hom (monoidal_category.tensor_hom f₁ f₂) f₃ ≫
iso.hom (monoidal_category.associator Y₁ Y₂ Y₃) =
iso.hom (monoidal_category.associator X₁ X₂ X₃) ≫
monoidal_category.tensor_hom f₁ (monoidal_category.tensor_hom f₂ f₃) :=
sorry
theorem monoidal_category.associator_naturality_assoc {C : Type u} [𝒞 : category C]
[c : monoidal_category C] {X₁ : C} {X₂ : C} {X₃ : C} {Y₁ : C} {Y₂ : C} {Y₃ : C} (f₁ : X₁ ⟶ Y₁)
(f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) {X' : C}
(f' : monoidal_category.tensor_obj Y₁ (monoidal_category.tensor_obj Y₂ Y₃) ⟶ X') :
monoidal_category.tensor_hom (monoidal_category.tensor_hom f₁ f₂) f₃ ≫
iso.hom (monoidal_category.associator Y₁ Y₂ Y₃) ≫ f' =
iso.hom (monoidal_category.associator X₁ X₂ X₃) ≫
monoidal_category.tensor_hom f₁ (monoidal_category.tensor_hom f₂ f₃) ≫ f' :=
sorry
theorem monoidal_category.left_unitor_naturality {C : Type u} [𝒞 : category C]
[c : monoidal_category C] {X : C} {Y : C} (f : X ⟶ Y) :
monoidal_category.tensor_hom 𝟙 f ≫ iso.hom (monoidal_category.left_unitor Y) =
iso.hom (monoidal_category.left_unitor X) ≫ f :=
sorry
theorem monoidal_category.left_unitor_naturality_assoc {C : Type u} [𝒞 : category C]
[c : monoidal_category C] {X : C} {Y : C} (f : X ⟶ Y) {X' : C} (f' : Y ⟶ X') :
monoidal_category.tensor_hom 𝟙 f ≫ iso.hom (monoidal_category.left_unitor Y) ≫ f' =
iso.hom (monoidal_category.left_unitor X) ≫ f ≫ f' :=
sorry
theorem monoidal_category.right_unitor_naturality {C : Type u} [𝒞 : category C]
[c : monoidal_category C] {X : C} {Y : C} (f : X ⟶ Y) :
monoidal_category.tensor_hom f 𝟙 ≫ iso.hom (monoidal_category.right_unitor Y) =
iso.hom (monoidal_category.right_unitor X) ≫ f :=
sorry
theorem monoidal_category.right_unitor_naturality_assoc {C : Type u} [𝒞 : category C]
[c : monoidal_category C] {X : C} {Y : C} (f : X ⟶ Y) {X' : C} (f' : Y ⟶ X') :
monoidal_category.tensor_hom f 𝟙 ≫ iso.hom (monoidal_category.right_unitor Y) ≫ f' =
iso.hom (monoidal_category.right_unitor X) ≫ f ≫ f' :=
sorry
theorem monoidal_category.pentagon {C : Type u} [𝒞 : category C] [c : monoidal_category C] (W : C)
(X : C) (Y : C) (Z : C) :
monoidal_category.tensor_hom (iso.hom (monoidal_category.associator W X Y)) 𝟙 ≫
iso.hom (monoidal_category.associator W (monoidal_category.tensor_obj X Y) Z) ≫
monoidal_category.tensor_hom 𝟙 (iso.hom (monoidal_category.associator X Y Z)) =
iso.hom (monoidal_category.associator (monoidal_category.tensor_obj W X) Y Z) ≫
iso.hom (monoidal_category.associator W X (monoidal_category.tensor_obj Y Z)) :=
sorry
@[simp] theorem monoidal_category.triangle {C : Type u} [𝒞 : category C] [c : monoidal_category C]
(X : C) (Y : C) :
iso.hom (monoidal_category.associator X (monoidal_category.tensor_unit C) Y) ≫
monoidal_category.tensor_hom 𝟙 (iso.hom (monoidal_category.left_unitor Y)) =
monoidal_category.tensor_hom (iso.hom (monoidal_category.right_unitor X)) 𝟙 :=
sorry
@[simp] theorem monoidal_category.triangle_assoc {C : Type u} [𝒞 : category C]
[c : monoidal_category C] (X : C) (Y : C) {X' : C}
(f' : monoidal_category.tensor_obj X Y ⟶ X') :
iso.hom (monoidal_category.associator X (monoidal_category.tensor_unit C) Y) ≫
monoidal_category.tensor_hom 𝟙 (iso.hom (monoidal_category.left_unitor Y)) ≫ f' =
monoidal_category.tensor_hom (iso.hom (monoidal_category.right_unitor X)) 𝟙 ≫ f' :=
sorry
infixr:70 " ⊗ " => Mathlib.category_theory.monoidal_category.tensor_obj
infixr:70 " ⊗ " => Mathlib.category_theory.monoidal_category.tensor_hom
notation:1024 "𝟙_" => Mathlib.category_theory.monoidal_category.tensor_unit
notation:1024 "α_" => Mathlib.category_theory.monoidal_category.associator
notation:1024 "λ_" => Mathlib.category_theory.monoidal_category.left_unitor
notation:1024 "ρ_" => Mathlib.category_theory.monoidal_category.right_unitor
/-- The tensor product of two isomorphisms is an isomorphism. -/
def tensor_iso {C : Type u} {X : C} {Y : C} {X' : C} {Y' : C} [category C] [monoidal_category C]
(f : X ≅ Y) (g : X' ≅ Y') : X ⊗ X' ≅ Y ⊗ Y' :=
iso.mk (iso.hom f ⊗ iso.hom g) (iso.inv f ⊗ iso.inv g)
infixr:70 " ⊗ " => Mathlib.category_theory.tensor_iso
namespace monoidal_category
protected instance tensor_is_iso {C : Type u} [category C] [monoidal_category C] {W : C} {X : C}
{Y : C} {Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : is_iso (f ⊗ g) :=
is_iso.mk (iso.inv (as_iso f ⊗ as_iso g))
@[simp] theorem inv_tensor {C : Type u} [category C] [monoidal_category C] {W : C} {X : C} {Y : C}
{Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : inv (f ⊗ g) = inv f ⊗ inv g :=
rfl
-- When `rewrite_search` lands, add @[search] attributes to
-- monoidal_category.tensor_id monoidal_category.tensor_comp monoidal_category.associator_naturality
-- monoidal_category.left_unitor_naturality monoidal_category.right_unitor_naturality
-- monoidal_category.pentagon monoidal_category.triangle
-- tensor_comp_id tensor_id_comp comp_id_tensor_tensor_id
-- triangle_assoc_comp_left triangle_assoc_comp_right
-- triangle_assoc_comp_left_inv triangle_assoc_comp_right_inv
-- left_unitor_tensor left_unitor_tensor_inv
-- right_unitor_tensor right_unitor_tensor_inv
-- pentagon_inv
-- associator_inv_naturality
-- left_unitor_inv_naturality
-- right_unitor_inv_naturality
@[simp] theorem comp_tensor_id {C : Type u} [category C] [monoidal_category C] {W : C} {X : C}
{Y : C} {Z : C} (f : W ⟶ X) (g : X ⟶ Y) : f ≫ g ⊗ 𝟙 = (f ⊗ 𝟙) ≫ (g ⊗ 𝟙) :=
sorry
@[simp] theorem id_tensor_comp {C : Type u} [category C] [monoidal_category C] {W : C} {X : C}
{Y : C} {Z : C} (f : W ⟶ X) (g : X ⟶ Y) : 𝟙 ⊗ f ≫ g = (𝟙 ⊗ f) ≫ (𝟙 ⊗ g) :=
sorry
@[simp] theorem id_tensor_comp_tensor_id {C : Type u} [category C] [monoidal_category C] {W : C}
{X : C} {Y : C} {Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : (𝟙 ⊗ f) ≫ (g ⊗ 𝟙) = g ⊗ f :=
sorry
@[simp] theorem tensor_id_comp_id_tensor_assoc {C : Type u} [category C] [monoidal_category C]
{W : C} {X : C} {Y : C} {Z : C} (f : W ⟶ X) (g : Y ⟶ Z) {X' : C} (f' : Z ⊗ X ⟶ X') :
(g ⊗ 𝟙) ≫ (𝟙 ⊗ f) ≫ f' = (g ⊗ f) ≫ f' :=
sorry
theorem left_unitor_inv_naturality {C : Type u} [category C] [monoidal_category C] {X : C} {X' : C}
(f : X ⟶ X') : f ≫ iso.inv λ_ = iso.inv λ_ ≫ (𝟙 ⊗ f) :=
sorry
theorem right_unitor_inv_naturality {C : Type u} [category C] [monoidal_category C] {X : C} {X' : C}
(f : X ⟶ X') : f ≫ iso.inv ρ_ = iso.inv ρ_ ≫ (f ⊗ 𝟙) :=
sorry
@[simp] theorem right_unitor_conjugation {C : Type u} [category C] [monoidal_category C] {X : C}
{Y : C} (f : X ⟶ Y) : iso.inv ρ_ ≫ (f ⊗ 𝟙) ≫ iso.hom ρ_ = f :=
sorry
@[simp] theorem left_unitor_conjugation {C : Type u} [category C] [monoidal_category C] {X : C}
{Y : C} (f : X ⟶ Y) : iso.inv λ_ ≫ (𝟙 ⊗ f) ≫ iso.hom λ_ = f :=
sorry
@[simp] theorem tensor_left_iff {C : Type u} [category C] [monoidal_category C] {X : C} {Y : C}
(f : X ⟶ Y) (g : X ⟶ Y) : 𝟙 ⊗ f = 𝟙 ⊗ g ↔ f = g :=
sorry
@[simp] theorem tensor_right_iff {C : Type u} [category C] [monoidal_category C] {X : C} {Y : C}
(f : X ⟶ Y) (g : X ⟶ Y) : f ⊗ 𝟙 = g ⊗ 𝟙 ↔ f = g :=
sorry
-- We now prove:
-- ((α_ (𝟙_ C) X Y).hom) ≫
-- ((λ_ (X ⊗ Y)).hom)
-- = ((λ_ X).hom ⊗ (𝟙 Y))
-- (and the corresponding fact for right unitors)
-- following the proof on nLab:
-- Lemma 2.2 at <https://ncatlab.org/nlab/revision/monoidal+category/115>
theorem left_unitor_product_aux_perimeter {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) :
(iso.hom α_ ⊗ 𝟙) ≫ iso.hom α_ ≫ (𝟙 ⊗ iso.hom α_) ≫ (𝟙 ⊗ iso.hom λ_) =
((iso.hom ρ_ ⊗ 𝟙) ⊗ 𝟙) ≫ iso.hom α_ :=
sorry
theorem left_unitor_product_aux_triangle {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : (iso.hom α_ ⊗ 𝟙) ≫ ((𝟙 ⊗ iso.hom λ_) ⊗ 𝟙) = (iso.hom ρ_ ⊗ 𝟙) ⊗ 𝟙 :=
sorry
theorem left_unitor_product_aux_square {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : iso.hom α_ ≫ (𝟙 ⊗ iso.hom λ_ ⊗ 𝟙) = ((𝟙 ⊗ iso.hom λ_) ⊗ 𝟙) ≫ iso.hom α_ :=
sorry
theorem left_unitor_product_aux {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
(𝟙 ⊗ iso.hom α_) ≫ (𝟙 ⊗ iso.hom λ_) = 𝟙 ⊗ iso.hom λ_ ⊗ 𝟙 :=
sorry
theorem right_unitor_product_aux_perimeter {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) :
(iso.hom α_ ⊗ 𝟙) ≫ iso.hom α_ ≫ (𝟙 ⊗ iso.hom α_) ≫ (𝟙 ⊗ 𝟙 ⊗ iso.hom λ_) =
(iso.hom ρ_ ⊗ 𝟙) ≫ iso.hom α_ :=
sorry
theorem right_unitor_product_aux_triangle {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : (𝟙 ⊗ iso.hom α_) ≫ (𝟙 ⊗ 𝟙 ⊗ iso.hom λ_) = 𝟙 ⊗ iso.hom ρ_ ⊗ 𝟙 :=
sorry
theorem right_unitor_product_aux_square {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : iso.hom α_ ≫ (𝟙 ⊗ iso.hom ρ_ ⊗ 𝟙) = ((𝟙 ⊗ iso.hom ρ_) ⊗ 𝟙) ≫ iso.hom α_ :=
sorry
theorem right_unitor_product_aux {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
(iso.hom α_ ⊗ 𝟙) ≫ ((𝟙 ⊗ iso.hom ρ_) ⊗ 𝟙) = iso.hom ρ_ ⊗ 𝟙 :=
sorry
-- See Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf>
theorem left_unitor_tensor' {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
iso.hom α_ ≫ iso.hom λ_ = iso.hom λ_ ⊗ 𝟙 :=
sorry
@[simp] theorem left_unitor_tensor {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
iso.hom λ_ = iso.inv α_ ≫ (iso.hom λ_ ⊗ 𝟙) :=
sorry
theorem left_unitor_tensor_inv' {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
iso.inv λ_ ≫ iso.inv α_ = iso.inv λ_ ⊗ 𝟙 :=
sorry
@[simp] theorem left_unitor_tensor_inv {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : iso.inv λ_ = (iso.inv λ_ ⊗ 𝟙) ≫ iso.hom α_ :=
sorry
@[simp] theorem right_unitor_tensor {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : iso.hom ρ_ = iso.hom α_ ≫ (𝟙 ⊗ iso.hom ρ_) :=
sorry
@[simp] theorem right_unitor_tensor_inv {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : iso.inv ρ_ = (𝟙 ⊗ iso.inv ρ_) ≫ iso.inv α_ :=
sorry
theorem associator_inv_naturality {C : Type u} [category C] [monoidal_category C] {X : C} {Y : C}
{Z : C} {X' : C} {Y' : C} {Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') :
(f ⊗ g ⊗ h) ≫ iso.inv α_ = iso.inv α_ ≫ ((f ⊗ g) ⊗ h) :=
sorry
theorem pentagon_inv {C : Type u} [category C] [monoidal_category C] (W : C) (X : C) (Y : C)
(Z : C) : (𝟙 ⊗ iso.inv α_) ≫ iso.inv α_ ≫ (iso.inv α_ ⊗ 𝟙) = iso.inv α_ ≫ iso.inv α_ :=
sorry
theorem triangle_assoc_comp_left {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
iso.hom α_ ≫ (𝟙 ⊗ iso.hom λ_) = iso.hom ρ_ ⊗ 𝟙 :=
triangle X Y
@[simp] theorem triangle_assoc_comp_right {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : iso.inv α_ ≫ (iso.hom ρ_ ⊗ 𝟙) = 𝟙 ⊗ iso.hom λ_ :=
sorry
@[simp] theorem triangle_assoc_comp_right_inv {C : Type u} [category C] [monoidal_category C]
(X : C) (Y : C) : (iso.inv ρ_ ⊗ 𝟙) ≫ iso.hom α_ = 𝟙 ⊗ iso.inv λ_ :=
sorry
@[simp] theorem triangle_assoc_comp_left_inv {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) : (𝟙 ⊗ iso.inv λ_) ≫ iso.inv α_ = iso.inv ρ_ ⊗ 𝟙 :=
sorry
/-- The tensor product expressed as a functor. -/
def tensor (C : Type u) [category C] [monoidal_category C] : C × C ⥤ C :=
functor.mk (fun (X : C × C) => prod.fst X ⊗ prod.snd X)
fun {X Y : C × C} (f : X ⟶ Y) => prod.fst f ⊗ prod.snd f
/-- The left-associated triple tensor product as a functor. -/
def left_assoc_tensor (C : Type u) [category C] [monoidal_category C] : C × C × C ⥤ C :=
functor.mk (fun (X : C × C × C) => (prod.fst X ⊗ prod.fst (prod.snd X)) ⊗ prod.snd (prod.snd X))
fun {X Y : C × C × C} (f : X ⟶ Y) =>
(prod.fst f ⊗ prod.fst (prod.snd f)) ⊗ prod.snd (prod.snd f)
@[simp] theorem left_assoc_tensor_obj (C : Type u) [category C] [monoidal_category C]
(X : C × C × C) :
functor.obj (left_assoc_tensor C) X =
(prod.fst X ⊗ prod.fst (prod.snd X)) ⊗ prod.snd (prod.snd X) :=
rfl
@[simp] theorem left_assoc_tensor_map (C : Type u) [category C] [monoidal_category C]
{X : C × C × C} {Y : C × C × C} (f : X ⟶ Y) :
functor.map (left_assoc_tensor C) f =
(prod.fst f ⊗ prod.fst (prod.snd f)) ⊗ prod.snd (prod.snd f) :=
rfl
/-- The right-associated triple tensor product as a functor. -/
def right_assoc_tensor (C : Type u) [category C] [monoidal_category C] : C × C × C ⥤ C :=
functor.mk (fun (X : C × C × C) => prod.fst X ⊗ prod.fst (prod.snd X) ⊗ prod.snd (prod.snd X))
fun {X Y : C × C × C} (f : X ⟶ Y) => prod.fst f ⊗ prod.fst (prod.snd f) ⊗ prod.snd (prod.snd f)
@[simp] theorem right_assoc_tensor_obj (C : Type u) [category C] [monoidal_category C]
(X : C × C × C) :
functor.obj (right_assoc_tensor C) X =
prod.fst X ⊗ prod.fst (prod.snd X) ⊗ prod.snd (prod.snd X) :=
rfl
@[simp] theorem right_assoc_tensor_map (C : Type u) [category C] [monoidal_category C]
{X : C × C × C} {Y : C × C × C} (f : X ⟶ Y) :
functor.map (right_assoc_tensor C) f =
prod.fst f ⊗ prod.fst (prod.snd f) ⊗ prod.snd (prod.snd f) :=
rfl
/-- The functor `λ X, 𝟙_ C ⊗ X`. -/
def tensor_unit_left (C : Type u) [category C] [monoidal_category C] : C ⥤ C :=
functor.mk (fun (X : C) => 𝟙_ ⊗ X) fun {X Y : C} (f : X ⟶ Y) => 𝟙 ⊗ f
/-- The functor `λ X, X ⊗ 𝟙_ C`. -/
def tensor_unit_right (C : Type u) [category C] [monoidal_category C] : C ⥤ C :=
functor.mk (fun (X : C) => X ⊗ 𝟙_) fun {X Y : C} (f : X ⟶ Y) => f ⊗ 𝟙
-- We can express the associator and the unitors, given componentwise above,
-- as natural isomorphisms.
/-- The associator as a natural isomorphism. -/
@[simp] theorem associator_nat_iso_hom_app (C : Type u) [category C] [monoidal_category C]
(X : C × C × C) : nat_trans.app (iso.hom (associator_nat_iso C)) X = iso.hom α_ :=
Eq.refl (iso.hom α_)
/-- The left unitor as a natural isomorphism. -/
@[simp] theorem left_unitor_nat_iso_inv_app (C : Type u) [category C] [monoidal_category C]
(X : C) : nat_trans.app (iso.inv (left_unitor_nat_iso C)) X = iso.inv λ_ :=
Eq.refl (iso.inv λ_)
/-- The right unitor as a natural isomorphism. -/
@[simp] theorem right_unitor_nat_iso_inv_app (C : Type u) [category C] [monoidal_category C]
(X : C) : nat_trans.app (iso.inv (right_unitor_nat_iso C)) X = iso.inv ρ_ :=
Eq.refl (iso.inv ρ_)
/-- Tensoring on the left with a fixed object, as a functor. -/
@[simp] theorem tensor_left_map {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C)
(Y' : C) (f : Y ⟶ Y') : functor.map (tensor_left X) f = 𝟙 ⊗ f :=
Eq.refl (functor.map (tensor_left X) f)
/--
Tensoring on the left with `X ⊗ Y` is naturally isomorphic to
tensoring on the left with `Y`, and then again with `X`.
-/
def tensor_left_tensor {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
tensor_left (X ⊗ Y) ≅ tensor_left Y ⋙ tensor_left X :=
nat_iso.of_components α_ sorry
@[simp] theorem tensor_left_tensor_hom_app {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) (Z : C) : nat_trans.app (iso.hom (tensor_left_tensor X Y)) Z = iso.hom α_ :=
rfl
@[simp] theorem tensor_left_tensor_inv_app {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) (Z : C) : nat_trans.app (iso.inv (tensor_left_tensor X Y)) Z = iso.inv α_ :=
rfl
/-- Tensoring on the right with a fixed object, as a functor. -/
@[simp] theorem tensor_right_obj {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
functor.obj (tensor_right X) Y = Y ⊗ X :=
Eq.refl (functor.obj (tensor_right X) Y)
/--
Tensoring on the right, as a functor from `C` into endofunctors of `C`.
We later show this is a monoidal functor.
-/
def tensoring_right (C : Type u) [category C] [monoidal_category C] : C ⥤ C ⥤ C :=
functor.mk tensor_right fun (X Y : C) (f : X ⟶ Y) => nat_trans.mk fun (Z : C) => 𝟙 ⊗ f
protected instance tensoring_right.category_theory.faithful (C : Type u) [category C]
[monoidal_category C] : faithful (tensoring_right C) :=
faithful.mk
/--
Tensoring on the right with `X ⊗ Y` is naturally isomorphic to
tensoring on the right with `X`, and then again with `Y`.
-/
def tensor_right_tensor {C : Type u} [category C] [monoidal_category C] (X : C) (Y : C) :
tensor_right (X ⊗ Y) ≅ tensor_right X ⋙ tensor_right Y :=
nat_iso.of_components (fun (Z : C) => iso.symm α_) sorry
@[simp] theorem tensor_right_tensor_hom_app {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) (Z : C) : nat_trans.app (iso.hom (tensor_right_tensor X Y)) Z = iso.inv α_ :=
rfl
@[simp] theorem tensor_right_tensor_inv_app {C : Type u} [category C] [monoidal_category C] (X : C)
(Y : C) (Z : C) : nat_trans.app (iso.inv (tensor_right_tensor X Y)) Z = iso.hom α_ :=
rfl
end Mathlib |
e02e2c40813f657a342fe756738c221897f09ce3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/finsupp_vector_space.lean | 30f725e3751984fd523401b82c3fab8041ef7f01 | [
"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 | 5,618 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import linear_algebra.std_basis
/-!
# Linear structures on function with finite support `ι →₀ M`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains results on the `R`-module structure on functions of finite support from a type
`ι` to an `R`-module `M`, in particular in the case that `R` is a field.
-/
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
open set linear_map submodule
open_locale cardinal
universes u v w
namespace finsupp
section ring
variables {R : Type*} {M : Type*} {ι : Type*}
variables [ring R] [add_comm_group M] [module R M]
lemma linear_independent_single {φ : ι → Type*}
{f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) :
linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) :=
begin
apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)),
{ assume i,
have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)),
{ rw ker_lsingle,
exact disjoint_bot_right },
apply (hf i).map h_disjoint },
{ intros i t ht hit,
refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _,
{ rw span_le,
simp only [supr_singleton],
rw range_coe,
apply range_comp_subset_range },
{ refine supr₂_mono (λ i hi, _),
rw [span_le, range_coe],
apply range_comp_subset_range } }
end
end ring
section semiring
variables {R : Type*} {M : Type*} {ι : Type*}
variables [semiring R] [add_comm_monoid M] [module R M]
open linear_map submodule
/-- The basis on `ι →₀ M` with basis vectors `λ ⟨i, x⟩, single i (b i x)`. -/
protected def basis {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) :
basis (Σ i, φ i) R (ι →₀ M) :=
basis.of_repr
{ to_fun := λ g,
{ to_fun := λ ix, (b ix.1).repr (g ix.1) ix.2,
support := g.support.sigma (λ i, ((b i).repr (g i)).support),
mem_support_to_fun := λ ix,
by { simp only [finset.mem_sigma, mem_support_iff, and_iff_right_iff_imp, ne.def],
intros b hg,
simpa [hg] using b } },
inv_fun := λ g,
{ to_fun := λ i, (b i).repr.symm (g.comap_domain _
(set.inj_on_of_injective sigma_mk_injective _)),
support := g.support.image sigma.fst,
mem_support_to_fun := λ i,
by { rw [ne.def, ← (b i).repr.injective.eq_iff, (b i).repr.apply_symm_apply, ext_iff],
simp only [exists_prop, linear_equiv.map_zero, comap_domain_apply, zero_apply,
exists_and_distrib_right, mem_support_iff, exists_eq_right, sigma.exists,
finset.mem_image, not_forall] } },
left_inv := λ g,
by { ext i, rw ← (b i).repr.injective.eq_iff, ext x,
simp only [coe_mk, linear_equiv.apply_symm_apply, comap_domain_apply] },
right_inv := λ g,
by { ext ⟨i, x⟩,
simp only [coe_mk, linear_equiv.apply_symm_apply, comap_domain_apply] },
map_add' := λ g h, by { ext ⟨i, x⟩, simp only [coe_mk, add_apply, linear_equiv.map_add] },
map_smul' := λ c h, by { ext ⟨i, x⟩, simp only [coe_mk, smul_apply, linear_equiv.map_smul,
ring_hom.id_apply] } }
@[simp] lemma basis_repr {φ : ι → Type*} (b : ∀ i, basis (φ i) R M)
(g : ι →₀ M) (ix) :
(finsupp.basis b).repr g ix = (b ix.1).repr (g ix.1) ix.2 :=
rfl
@[simp] lemma coe_basis {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) :
⇑(finsupp.basis b) = λ (ix : Σ i, φ i), single ix.1 (b ix.1 ix.2) :=
funext $ λ ⟨i, x⟩, basis.apply_eq_iff.mpr $
begin
ext ⟨j, y⟩,
by_cases h : i = j,
{ cases h,
simp only [basis_repr, single_eq_same, basis.repr_self,
finsupp.single_apply_left sigma_mk_injective] },
simp only [basis_repr, single_apply, h, false_and, if_false, linear_equiv.map_zero, zero_apply]
end
/-- The basis on `ι →₀ M` with basis vectors `λ i, single i 1`. -/
@[simps]
protected def basis_single_one :
basis ι R (ι →₀ R) :=
basis.of_repr (linear_equiv.refl _ _)
@[simp] lemma coe_basis_single_one :
(finsupp.basis_single_one : ι → (ι →₀ R)) = λ i, finsupp.single i 1 :=
funext $ λ i, basis.apply_eq_iff.mpr rfl
end semiring
end finsupp
/-! TODO: move this section to an earlier file. -/
namespace basis
variables {R M n : Type*}
variables [decidable_eq n] [fintype n]
variables [semiring R] [add_comm_monoid M] [module R M]
lemma _root_.finset.sum_single_ite (a : R) (i : n) :
finset.univ.sum (λ (x : n), finsupp.single x (ite (i = x) a 0)) = finsupp.single i a :=
begin
rw finset.sum_congr_set {i} (λ (x : n), finsupp.single x (ite (i = x) a 0))
(λ _, finsupp.single i a),
{ simp },
{ intros x hx,
rw set.mem_singleton_iff at hx,
simp [hx] },
intros x hx,
have hx' : ¬i = x :=
begin
refine ne_comm.mp _,
rwa mem_singleton_iff at hx,
end,
simp [hx'],
end
@[simp] lemma equiv_fun_symm_std_basis (b : basis n R M) (i : n) :
b.equiv_fun.symm (linear_map.std_basis R (λ _, R) i 1) = b i :=
begin
have := equiv_like.injective b.repr,
apply_fun b.repr,
simp only [equiv_fun_symm_apply, std_basis_apply', linear_equiv.map_sum,
linear_equiv.map_smulₛₗ, ring_hom.id_apply, repr_self, finsupp.smul_single', boole_mul],
exact finset.sum_single_ite 1 i,
end
end basis
|
e99f89a09e6a2540d66b984d06c473b206316fa3 | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/pseudo_normed_group/category.lean | 1db8ec57a93b664403e22763c223a55a365ac42f | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,459 | lean | import category_theory.concrete_category.bundled_hom
import topology.category.Profinite
import data.equiv.fin
import pseudo_normed_group.with_Tinv
/-!
# The category of profinitely filtered pseudo-normed groups.
The category of profinite pseudo-normed groups, and the category of
profinitely filtered pseudo-normed groups equipped with an action of T⁻¹.
-/
universe variables u
open category_theory
open_locale nnreal
local attribute [instance] type_pow
noncomputable theory
/-- The category of profinitely filtered pseudo-normed groups. -/
def ProFiltPseuNormGrp : Type (u+1) :=
bundled profinitely_filtered_pseudo_normed_group
/-- The category of profinitely filtered pseudo-normed groups with action of `T⁻¹`. -/
def ProFiltPseuNormGrpWithTinv (r : ℝ≥0) : Type (u+1) :=
bundled (@profinitely_filtered_pseudo_normed_group_with_Tinv r)
namespace ProFiltPseuNormGrp
instance bundled_hom : bundled_hom @profinitely_filtered_pseudo_normed_group_hom :=
⟨@profinitely_filtered_pseudo_normed_group_hom.to_fun,
@profinitely_filtered_pseudo_normed_group_hom.id,
@profinitely_filtered_pseudo_normed_group_hom.comp,
@profinitely_filtered_pseudo_normed_group_hom.coe_inj⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] ProFiltPseuNormGrp
/-- Construct a bundled `ProFiltPseuNormGrp` from the underlying type and typeclass. -/
def of (M : Type u) [profinitely_filtered_pseudo_normed_group M] : ProFiltPseuNormGrp :=
bundled.of M
instance : has_zero ProFiltPseuNormGrp := ⟨of punit⟩
instance : inhabited ProFiltPseuNormGrp := ⟨0⟩
instance (M : ProFiltPseuNormGrp) : profinitely_filtered_pseudo_normed_group M := M.str
@[simp] lemma coe_of (V : Type u) [profinitely_filtered_pseudo_normed_group V] : (ProFiltPseuNormGrp.of V : Type u) = V := rfl
@[simp] lemma coe_id (V : ProFiltPseuNormGrp) : ⇑(𝟙 V) = id := rfl
@[simp] lemma coe_comp {A B C : ProFiltPseuNormGrp} (f : A ⟶ B) (g : B ⟶ C) :
⇑(f ≫ g) = g ∘ f := rfl
@[simp] lemma coe_comp_apply {A B C : ProFiltPseuNormGrp} (f : A ⟶ B) (g : B ⟶ C) (x : A) :
(f ≫ g) x = g (f x) := rfl
open pseudo_normed_group
section
variables (M : Type*) [profinitely_filtered_pseudo_normed_group M] (c : ℝ≥0)
instance : t2_space (Top.of (filtration M c)) := by { dsimp, apply_instance }
instance : totally_disconnected_space (Top.of (filtration M c)) := by { dsimp, apply_instance }
instance : compact_space (Top.of (filtration M c)) := by { dsimp, apply_instance }
end
end ProFiltPseuNormGrp
namespace ProFiltPseuNormGrpWithTinv
variables (r' : ℝ≥0)
instance bundled_hom : bundled_hom (@profinitely_filtered_pseudo_normed_group_with_Tinv_hom r') :=
⟨@profinitely_filtered_pseudo_normed_group_with_Tinv_hom.to_fun r',
@profinitely_filtered_pseudo_normed_group_with_Tinv_hom.id r',
@profinitely_filtered_pseudo_normed_group_with_Tinv_hom.comp r',
@profinitely_filtered_pseudo_normed_group_with_Tinv_hom.coe_inj r'⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] ProFiltPseuNormGrpWithTinv
/-- Construct a bundled `ProFiltPseuNormGrpWithTinv` from the underlying type and typeclass. -/
def of (r' : ℝ≥0) (M : Type u) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] :
ProFiltPseuNormGrpWithTinv r' :=
bundled.of M
instance : has_zero (ProFiltPseuNormGrpWithTinv r') :=
⟨{ α := punit, str := punit.profinitely_filtered_pseudo_normed_group_with_Tinv r' }⟩
instance : inhabited (ProFiltPseuNormGrpWithTinv r') := ⟨0⟩
instance (M : ProFiltPseuNormGrpWithTinv r') :
profinitely_filtered_pseudo_normed_group_with_Tinv r' M := M.str
@[simp] lemma coe_of (V : Type u) [profinitely_filtered_pseudo_normed_group_with_Tinv r' V] :
(ProFiltPseuNormGrpWithTinv.of r' V : Type u) = V := rfl
@[simp] lemma of_coe (M : ProFiltPseuNormGrpWithTinv r') : of r' M = M :=
by { cases M, refl }
@[simp] lemma coe_id (V : ProFiltPseuNormGrpWithTinv r') : ⇑(𝟙 V) = id := rfl
@[simp] lemma coe_comp {A B C : ProFiltPseuNormGrpWithTinv r'} (f : A ⟶ B) (g : B ⟶ C) :
⇑(f ≫ g) = g ∘ f := rfl
@[simp] lemma coe_comp_apply {A B C : ProFiltPseuNormGrpWithTinv r'} (f : A ⟶ B) (g : B ⟶ C) (x : A) :
(f ≫ g) x = g (f x) := rfl
open pseudo_normed_group
section
variables (M : Type*) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] (c : ℝ≥0)
include r'
instance : t2_space (Top.of (filtration M c)) := by { dsimp, apply_instance }
instance : totally_disconnected_space (Top.of (filtration M c)) := by { dsimp, apply_instance }
instance : compact_space (Top.of (filtration M c)) := by { dsimp, apply_instance }
end
-- @[simps] def Filtration (c : ℝ≥0) : ProFiltPseuNormGrp ⥤ Profinite :=
-- { obj := λ M, ⟨Top.of (filtration M c)⟩,
-- map := λ M₁ M₂ f, ⟨f.level c, f.level_continuous c⟩,
-- map_id' := by { intros, ext, refl },
-- map_comp' := by { intros, ext, refl } }
open pseudo_normed_group profinitely_filtered_pseudo_normed_group_with_Tinv_hom
open profinitely_filtered_pseudo_normed_group_with_Tinv (Tinv)
variables {r'}
variables {M M₁ M₂ : ProFiltPseuNormGrpWithTinv.{u} r'}
variables {f : M₁ ⟶ M₂}
/-- The isomorphism induced by a bijective `profinitely_filtered_pseudo_normed_group_with_Tinv_hom`
whose inverse is strict. -/
def iso_of_equiv_of_strict (e : M₁ ≃+ M₂) (he : ∀ x, f x = e x)
(strict : ∀ ⦃c x⦄, x ∈ filtration M₂ c → e.symm x ∈ filtration M₁ c) :
M₁ ≅ M₂ :=
{ hom := f,
inv := inv_of_equiv_of_strict e he strict,
hom_inv_id' := by { ext x, simp [inv_of_equiv_of_strict, he] },
inv_hom_id' := by { ext x, simp [inv_of_equiv_of_strict, he] } }
@[simp]
lemma iso_of_equiv_of_strict.apply (e : M₁ ≃+ M₂) (he : ∀ x, f x = e x)
(strict : ∀ ⦃c x⦄, x ∈ filtration M₂ c → e.symm x ∈ filtration M₁ c) (x : M₁) :
(iso_of_equiv_of_strict e he strict).hom x = f x := rfl
@[simp]
lemma iso_of_equiv_of_strict_symm.apply (e : M₁ ≃+ M₂) (he : ∀ x, f x = e x)
(strict : ∀ ⦃c x⦄, x ∈ filtration M₂ c → e.symm x ∈ filtration M₁ c) (x : M₂) :
(iso_of_equiv_of_strict e he strict).symm.hom x = e.symm x := rfl
def iso_of_equiv_of_strict'
(e : M₁ ≃+ M₂)
(strict' : ∀ c x, x ∈ filtration M₁ c ↔ e x ∈ filtration M₂ c)
(continuous' : ∀ c, continuous (pseudo_normed_group.level e (λ c x, (strict' c x).1) c))
(map_Tinv' : ∀ x, e (Tinv x) = Tinv (e x)) :
M₁ ≅ M₂ :=
@iso_of_equiv_of_strict r' M₁ M₂
{to_fun := e,
strict' := λ c x, (strict' c x).1,
continuous' := continuous',
map_Tinv' := map_Tinv',
..e.to_add_monoid_hom } e (λ _, rfl)
(by { intros c x hx, rwa [strict', e.apply_symm_apply] })
@[simp]
lemma iso_of_equiv_of_strict'_hom_apply
(e : M₁ ≃+ M₂)
(strict' : ∀ c x, x ∈ filtration M₁ c ↔ e x ∈ filtration M₂ c)
(continuous' : ∀ c, continuous (pseudo_normed_group.level e (λ c x, (strict' c x).1) c))
(map_Tinv' : ∀ x, e (Tinv x) = Tinv (e x))
(x : M₁) :
(iso_of_equiv_of_strict' e strict' continuous' map_Tinv').hom x = e x := rfl
@[simp]
lemma iso_of_equiv_of_strict'_inv_apply
(e : M₁ ≃+ M₂)
(strict' : ∀ c x, x ∈ filtration M₁ c ↔ e x ∈ filtration M₂ c)
(continuous' : ∀ c, continuous (pseudo_normed_group.level e (λ c x, (strict' c x).1) c))
(map_Tinv' : ∀ x, e (Tinv x) = Tinv (e x))
(x : M₂) :
(iso_of_equiv_of_strict' e strict' continuous' map_Tinv').inv x = e.symm x := rfl
variables (r')
@[simps]
def Pow (n : ℕ) : ProFiltPseuNormGrpWithTinv.{u} r' ⥤ ProFiltPseuNormGrpWithTinv.{u} r' :=
{ obj := λ M, of r' $ M ^ n,
map := λ M₁ M₂ f, profinitely_filtered_pseudo_normed_group_with_Tinv.pi_map r' _ _ (λ i, f),
map_id' := λ M, by { ext, refl },
map_comp' := by { intros, ext, refl } }
@[simps]
def Pow_Pow_X_equiv (N n : ℕ) :
M ^ (N * n) ≃+ (M ^ N) ^ n :=
{ to_fun := ((equiv.curry _ _ _).symm.trans (((equiv.prod_comm _ _).trans fin_prod_fin_equiv).arrow_congr (equiv.refl _))).symm,
map_add' := λ x y, by { ext, refl },
.. ((equiv.curry _ _ _).symm.trans (((equiv.prod_comm _ _).trans fin_prod_fin_equiv).arrow_congr (equiv.refl _))).symm }
open profinitely_filtered_pseudo_normed_group
@[simps]
def Pow_Pow_X (N n : ℕ) (M : ProFiltPseuNormGrpWithTinv.{u} r') :
(Pow r' N ⋙ Pow r' n).obj M ≅ (Pow r' (N * n)).obj M :=
iso.symm $
iso_of_equiv_of_strict'
(Pow_Pow_X_equiv r' N n)
begin
intros c x,
dsimp,
split; intro h,
{ intros i j, exact h (fin_prod_fin_equiv (j, i)) },
{ intro ij,
have := h (fin_prod_fin_equiv.symm ij).2 (fin_prod_fin_equiv.symm ij).1,
dsimp at this, simpa only [prod.mk.eta, equiv.apply_symm_apply] using this, },
end
begin
intro c, dsimp,
rw [← (filtration_pi_homeo (λ _, M ^ N) c).comp_continuous_iff,
← (filtration_pi_homeo (λ _, M) c).symm.comp_continuous_iff'],
apply continuous_pi,
intro i,
rw [← (filtration_pi_homeo (λ _, M) c).comp_continuous_iff],
apply continuous_pi,
intro j,
have := @continuous_apply _ (λ _, filtration M c) _ (fin_prod_fin_equiv (j, i)),
dsimp [function.comp] at this ⊢,
simpa only [subtype.coe_eta],
end
(by { intros, ext, refl })
@[simps hom inv]
def Pow_mul (N n : ℕ) : Pow r' (N * n) ≅ Pow r' N ⋙ Pow r' n :=
nat_iso.of_components (λ M, (Pow_Pow_X r' N n M).symm)
begin
intros X Y f,
ext x i j,
refl,
end
end ProFiltPseuNormGrpWithTinv
|
5ac311f7a075a3e81c631d7496452ddb1d5212ce | ec040be767d27b10d2f864ddcfdf756aeb7a9a0a | /src/assignments/assignment_3/assignment_3.lean | df3019beb2cff5eb3d8257575f052f656b084e1c | [] | no_license | RoboticPanda77/complogic-s21 | b26a9680dfb98ac650e40539296c0cafc86f5cb4 | 93c5bcc0139c0926cc261075f50a8b1ead6aa40c | refs/heads/master | 1,682,196,614,558 | 1,620,625,035,000 | 1,620,625,035,000 | 337,230,148 | 0 | 0 | null | 1,620,625,036,000 | 1,612,824,240,000 | Lean | UTF-8 | Lean | false | false | 6,777 | lean | /-
HIGHER-ORDER FUNCTION WARMUP
ncm5jv
-/
/-
1. Write a function, double, that takes
a natural number and returns its double.
Write it using the following recursive
definition:
- double 0 = 0
- double (n' + 1) = double n' + 2
-/
def double : ℕ → ℕ
| 0 := 0
| (n' + 1) := (double n') + 2
/-
2. Write a function, map_list_nat, that
takes as its arguments (1) a list, l, of
natural numbers, and (2) a function, f,
from nat to nat, and that returns a new
list of natural numbers constructed by
applying f to each element of l. Make f
the first argument and l the second. The
function will work by case analysis and
recursion on l.
-/
def map_list_nat : (ℕ → ℕ) → (list ℕ) → (list ℕ)
| f list.nil := list.nil
| f (h::t) := list.cons (f h) (map_list_nat f t)
/-
3. Test your map_list_nat function by
applying it to several lists, both empty
and not, passing double as the function
value. Include [], [2], and [1,2,3] in
your set of test inputs and use comments
to document the expected return values.
-/
#eval map_list_nat nat.succ []
#eval map_list_nat nat.succ [2]
#eval map_list_nat nat.succ [1,2,3]
#eval map_list_nat nat.succ [1,1,1]
#eval map_list_nat nat.succ [0]
/-
4. In Lean, repr is an "overloaded"
function. When applied to a value of a
type for which it's defined (we'll see
later how that happens) it returns a
string representation of the value. It
is defined for the nat type, and so
when applied to a nat value it returns
a corresponding string. It's "toString"
for Lean. Here's an example.
-/
#eval repr 5
/-
Write a function map_list_nat_string
that takes a list of nat values and
returns a list of strings in which
each nat in the given list has been
converted to a string using repr.
-/
def map_list_nat_string : list ℕ → list string
| list.nil := list.nil
| (h::t) := list.cons (repr h) (map_list_nat_string t)
/-
5. Write a function, filterZeros,
that takes a list of natural numbers
and returns the same list but with any
and all zero values removed. Given
[0], for example, it should return
[]; given [1,2,0,3,4,0, 0, 5] it
should return [1,2,3,4,5].
-/
def filterZeros : list ℕ → list ℕ
| list.nil := list.nil
| (h::t) :=
if h = 0
then t
else list.cons h (filterZeros t)
/-
6. Write a function, isEqN, that
takes a natural number, n, and returns
a function that takes a natural number,
m, and returns true (tt) if m = n and
that returns false (ff) otherwise. Be
sure to test your function.
-/
def isEqN : ℕ → (ℕ → bool) :=
λ n,
λ m,
n = m
#eval isEqN 5
#eval isEqN 5 6
#eval isEqN 5 5
#check isEqN 5
#check isEqN 5
#check isEqN 5 6
#check isEqN 5 5
/-
7. Write a function filterNs that takes
a function, pred, from nat to bool
and a list, l, of natural numbers, and
that returns a list like l but with all
the numbers that satisfy the predicate
function removed. Test your function
using isEqN to produce a few predicate
functions (functions that for a given
argument return true or false).
-/
def filterNs : (ℕ → bool) → list ℕ → list ℕ
| pred list.nil := list.nil
| pred (h::t) :=
if pred h
then filterNs pred t
else list.cons h (filterNs pred t)
/-
8. Write a function, iterate, that
takes as its arguments (1) a function,
f, of type nat → nat, and (2) a natural
number, n, and that returns a function
that takes an argument, (m : nat), and
that returns the result of applying f
to m n times. For example, if n = 3, it
should return f (f (f m)). The result
of applying f zero times is just m.
Hint: use case analysis on n, and
recursion. Test your function using
nat.succ, your double function, and
(nat.add 4) as function arguments.
-/
def iterate : (ℕ → ℕ) → ℕ → (ℕ → ℕ)
| f 0 := λ m, m
| f (n' + 1) := λ m, f (iterate f (n') m)
#eval iterate nat.succ 3 5
#eval iterate double 3 5
#eval iterate (nat.add 4) 3 5
/-
9. Write a function, list_add, that takes
a list of natural numbers and returns the
sum of all the numbers in the list.
-/
def list_add : list ℕ → ℕ
| list.nil := 0
| (h::t) := h + list_add t
/-
10. Write a function, list_mul, that takes
a list of natural numbers and returns the
product of all the numbers in the list.
-/
def list_mul : list ℕ → ℕ
| list.nil := 1
| (h::t) := h * list_mul t
/-
11. Write a function, list_has_zero, that
takes a list of natural numbers and returns
tt if the list contains any zero values and
that returns false otherwise. Use isEqN in
your solution. Test your solution on both
empty and non-empty lists including lists
that both have and don't have zero values.
-/
def list_has_zero : list ℕ → bool
| list.nil := ff
| (h::t) := if h = 0
then tt
else list_has_zero t
#eval list_has_zero []
#eval list_has_zero [1,0,1]
#eval list_has_zero [0]
#eval list_has_zero [1,1,1]
/-
12. Write a function, compose_nat_nat,
that takes two functions, f : ℕ → ℕ,
and g : ℕ → ℕ, and that returns a
function that takes a nat, n, and that
returns g (f n). Test your function
using at least nat.succ and double as
argument values.
-/
def compose_nat_nat : (ℕ → ℕ) → (ℕ → ℕ) → (ℕ → ℕ) :=
λ f,
λ g,
λ n,
g (f n)
#eval compose_nat_nat nat.succ double 4
#eval compose_nat_nat double nat.succ 4
#check compose_nat_nat nat.succ double 4
#check compose_nat_nat nat.succ double
/-
13. Write a polymorphic map_box function
of type
Π (α β : Type u),
(α → β) → box α → box β
that takes a function, f, of type
(α → β), and a box, b, containing a
value of type α and that returns a
box containing that value transformed
by the application of f.
-/
universe u
structure box (α : Type u) : Type u :=
(val : α)
def map_box {α β : Type u}
(f : α → β) : (box α → box β) :=
λ b,
box.mk (f b.val)
/-
14.
Write a function, map_option, that
takes a function, f, of type α → β
and an option α and that transforms
it into an option β, where none goes
to none, and some (a : α) goes to
some b, where b is a transformed by
f.
-/
def map_option {α β : Type u} (f : α → β) : (option α) → (option β) :=
λ opa,
match opa with
| option.none := option.none
| option.some (a : α) := option.some (f a)
end
/-
15. Write three functions, default_nat,
default_bool, and default_list α, each
taking no arguments (other than a type,
argument, α, in the third case), and
each returning a default value of the
given type: a nat, a bool, and a list.
Don't overthink this: Yes, a function
that takes no arguments is basically
a constant. You'll need to declare a
universe variable for the list problem.
-/
def default_nat : ℕ := 0
def default_bool : bool := ff
def default_list {α : Type u} : list α := list.nil
|
02f6d9152280f7e4b76c2ae0c78659e3d81801f0 | dfd42d30132c2867977fefe7edae98b6dc703aeb | /src/similarity.lean | 3b7ea822bb3d430256cb41b16a084f8bcb7413eb | [] | no_license | justadzr/lean-2021 | 1e42057ac75c794c94b8f148a27a24150c685f68 | dfc6b30de2f27bdba5fbc51183e2b84e73a920d1 | refs/heads/master | 1,689,652,366,522 | 1,630,313,809,000 | 1,630,313,809,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,481 | lean | import analysis.normed_space.conformal_linear_map
import analysis.calculus.times_cont_diff
noncomputable theory
open filter continuous_linear_map
open_locale real_inner_product_space classical filter topological_space
section conformality
lemma is_conformal_map.symm {R : Type*} {X Y : Type*} [nondiscrete_normed_field R]
[normed_group X] [normed_group Y] [normed_space R X] [normed_space R Y]
{f' : X ≃L[R] Y} (hf' : is_conformal_map (f' : X →L[R] Y)) :
is_conformal_map (f'.symm : Y →L[R] X) :=
begin
rcases hf' with ⟨c, hc, li, hli⟩,
simp only [f'.coe_coe] at hli,
have surj : li.to_linear_map.range = ⊤ :=
begin
refine linear_map.range_eq_top.mpr (λ y, ⟨c • f'.symm y, _⟩),
simp only [li.coe_to_linear_map, li.map_smul],
have : c • li (f'.symm y) = f' (f'.symm y) := by simp only [hli, pi.smul_apply],
rw [this, f'.apply_symm_apply]
end,
let le := linear_equiv.of_bijective li.to_linear_map
(linear_map.ker_eq_bot.mpr li.injective) surj,
let lie : X ≃ₗᵢ[R] Y :=
{ to_linear_equiv := le,
norm_map' := by simp },
refine ⟨c⁻¹, inv_ne_zero hc, lie.symm.to_linear_isometry, _⟩,
ext1 y,
have key : (li : X → Y) = lie,
{ ext1 x,
simp only [linear_isometry_equiv.coe_mk, linear_equiv.of_bijective_apply,
li.coe_to_linear_map] },
rw [f'.symm.coe_coe, f'.symm_apply_eq, hli],
simp only [pi.smul_apply, function.comp_app, li.map_smul, lie.symm.coe_to_linear_isometry],
rw [key, lie.apply_symm_apply, smul_smul, mul_inv_cancel hc, one_smul]
end
end conformality
section similarity_all
variables {E F : Type*} [inner_product_space ℝ E] [inner_product_space ℝ F]
section similarity1
def similarity_factor (x : E) {f' : E →L[ℝ] F} (h : is_conformal_map f') : ℝ :=
classical.some ((is_conformal_map_iff _).mp h)
lemma similarity_factor_prop (x : E) {f' : E →L[ℝ] F} (h : is_conformal_map f') :
0 < similarity_factor x h ∧ ∀ u v, ⟪f' u, f' v⟫ = (similarity_factor x h) * ⟪u, v⟫ :=
classical.some_spec ((is_conformal_map_iff _).mp h)
lemma is_conformal_map_of_eq {f' : E →L[ℝ] F} {f'' : E →L[ℝ] F}
(hf' : is_conformal_map f') (H : f' = f'') : is_conformal_map f'' :=
H ▸ hf'
lemma similarity_factor_eq_of_eq [nontrivial E] {x : E} {f' : E →L[ℝ] F} {f'' : E →L[ℝ] F}
(hf' : is_conformal_map f') (H : f' = f'') :
similarity_factor x (is_conformal_map_of_eq hf' H) = similarity_factor x hf' :=
begin
rcases exists_ne (0 : E) with ⟨u, hu⟩,
have minor₁ := (similarity_factor_prop x hf').2 u u,
have minor₂ := (similarity_factor_prop x $ is_conformal_map_of_eq hf' H).2 u u,
have minor₃ : ⟪u, u⟫ ≠ 0 := λ w, hu (inner_self_eq_zero.mp w),
have key : ⟪f' u, f' u⟫ = ⟪f'' u, f'' u⟫ := by rw H,
rw [minor₁, minor₂] at key,
exact mul_right_cancel' minor₃ key.symm
end
variables {f' : E → (E →L[ℝ] F)}
/-- TODO: refine the hypothesis `h` -/
lemma similarity_factor_times_cont_diff_at [nontrivial E] (x : E)
(h : ∀ y, is_conformal_map $ f' y) {n : ℕ} (H : times_cont_diff_at ℝ n f' x) :
times_cont_diff_at ℝ n (λ y, similarity_factor y $ h y) x :=
begin
rcases exists_ne (0 : E) with ⟨v, hv⟩,
have minor₁ : ∥v∥ ≠ 0 := λ w, hv (norm_eq_zero.mp w),
have minor₂ : ∀ y, similarity_factor y (h y) = ∥f' y v∥ ^ 2 / ∥v∥ ^ 2 :=
λ y, by rw [← mul_div_cancel (similarity_factor y $ h y) (pow_ne_zero 2 minor₁), pow_two,
← real_inner_self_eq_norm_sq, ← (similarity_factor_prop y $ h y).2,
real_inner_self_eq_norm_sq, ← pow_two],
have minor₃ : (λ x, similarity_factor x $ h x) =
λ x, ∥(λ y, ((apply ℝ F v) ∘ f') y) x∥ ^ 2 / ∥v∥ ^ 2,
{ ext1 x,
simp only [minor₂ x, apply_apply, function.comp_app] },
rw [minor₃],
apply times_cont_diff_at.div_const,
apply times_cont_diff_at.norm_sq,
simp only [congr_arg],
exact times_cont_diff_at.comp _ (apply ℝ F v).times_cont_diff.times_cont_diff_at H
end
end similarity1
section similarity2
def similarity_factor_sqrt (x : E) {f' : E →L[ℝ] F} (h : is_conformal_map f') : ℝ :=
real.sqrt (similarity_factor x h)
lemma similarity_factor_sqrt_eq' {x : E} {f' : E →L[ℝ] F} (h : is_conformal_map f') :
similarity_factor_sqrt x h ^ 2 = similarity_factor x h :=
by simp only [similarity_factor_sqrt, real.sq_sqrt (le_of_lt (similarity_factor_prop x h).1)]
lemma similarity_factor_sqrt_prop (x : E) {f' : E →L[ℝ] F} (h : is_conformal_map f') :
similarity_factor_sqrt x h ≠ 0 ∧
∀ u v, ⟪f' u, f' v⟫ = (similarity_factor_sqrt x h) ^ 2 * ⟪u, v⟫ :=
begin
refine ⟨real.sqrt_ne_zero'.mpr (similarity_factor_prop x h).1, λ u v, _⟩,
simp only [(similarity_factor_prop x h).2, similarity_factor_sqrt,
real.sq_sqrt (le_of_lt (similarity_factor_prop x h).1)]
end
variables {f' : E → (E →L[ℝ] F)}
/-- TODO: refine the hypothesis `h` -/
lemma similarity_factor_sqrt_times_cont_diff_at [nontrivial E] (x : E)
(h : ∀ y, is_conformal_map $ f' y) {n : ℕ} (H : times_cont_diff_at ℝ n f' x) :
times_cont_diff_at ℝ n (λ y, similarity_factor_sqrt y $ h y) x :=
begin
simp only [similarity_factor_sqrt],
refine times_cont_diff_at.sqrt _ (ne_of_gt (similarity_factor_prop x $ h x).1),
exact similarity_factor_times_cont_diff_at x h H
end
lemma similarity_factor_sqrt_eq (h : ∀ y, is_conformal_map $ f' y) :
(λ x, (similarity_factor_sqrt x $ h x) ^ 2) = (λ x, similarity_factor x $ h x) :=
begin
ext1 y,
simp only [similarity_factor_sqrt, real.sq_sqrt (le_of_lt (similarity_factor_prop y $ h y).1)]
end
lemma similarity_factor_sqrt_eq_of_eq [nontrivial E] {x : E}
{f' : E →L[ℝ] F} {f'' : E →L[ℝ] F} (hf' : is_conformal_map f') (H : f' = f'') :
similarity_factor_sqrt x (is_conformal_map_of_eq hf' H) = similarity_factor_sqrt x hf' :=
by simp only [similarity_factor_sqrt, similarity_factor_eq_of_eq]
end similarity2
section similarity3
def similarity_factor_sqrt_inv (x : E) {f' : E →L[ℝ] F} (h : is_conformal_map f') : ℝ :=
(similarity_factor_sqrt x h)⁻¹
lemma similarity_factor_sqrt_inv_eq' (x : E) {f' : E →L[ℝ] F} (h : is_conformal_map f') :
(similarity_factor_sqrt_inv x h)⁻¹ ^ 2 = similarity_factor x h :=
by simp only [similarity_factor_sqrt_inv, similarity_factor_sqrt,
inv_inv', real.sq_sqrt (le_of_lt (similarity_factor_prop x h).1)]
lemma similarity_factor_sqrt_inv_prop (x : E) {f' : E →L[ℝ] F} (h : is_conformal_map f') :
similarity_factor_sqrt_inv x h ≠ 0 ∧
∀ u v, ⟪f' u, f' v⟫ = ((similarity_factor_sqrt_inv x h)⁻¹) ^ 2 * ⟪u, v⟫ :=
begin
refine ⟨inv_ne_zero (similarity_factor_sqrt_prop x h).1, λ u v, _⟩,
simp only [(similarity_factor_sqrt_prop x h).2, similarity_factor_sqrt_inv, inv_inv']
end
variables {f' : E → (E →L[ℝ] F)}
/-- TODO: refine the hypothesis `h` -/
lemma similarity_factor_sqrt_inv_eq (h : ∀ y, is_conformal_map $ f' y) :
(λ x, (similarity_factor_sqrt_inv x $ h x)⁻¹ ^ 2) = (λ x, similarity_factor x $ h x) :=
begin
ext1 y,
simp only [similarity_factor_sqrt_inv, inv_inv'],
have := congr_fun (similarity_factor_sqrt_eq h) y,
simpa [congr_arg] using this
end
lemma similarity_factor_sqrt_inv_eq_of_eq [nontrivial E] {x : E}
{f' : E →L[ℝ] F} {f'' : E →L[ℝ] F} (hf' : is_conformal_map f') (H : f' = f'') :
similarity_factor_sqrt_inv x (is_conformal_map_of_eq hf' H) = similarity_factor_sqrt_inv x hf' :=
by simp only [similarity_factor_sqrt_inv, similarity_factor_sqrt_eq_of_eq]
/-- TODO: refine the hypothesis `h` -/
lemma similarity_factor_sqrt_inv_eq_comp_inv (h : ∀ y, is_conformal_map $ f' y) :
(λ x, similarity_factor_sqrt_inv x $ h x) = (λ x, x⁻¹) ∘ (λ x, similarity_factor_sqrt x $ h x) :=
begin
ext1,
simp only [function.comp_app, similarity_factor_sqrt_inv]
end
/-- TODO: refine the hypothesis `h` -/
lemma similarity_factor_sqrt_inv_times_cont_diff_at [nontrivial E] (x : E)
(h : ∀ y, is_conformal_map $ f' y) {n : ℕ} (H : times_cont_diff_at ℝ n f' x) :
times_cont_diff_at ℝ n (λ x, similarity_factor_sqrt_inv x $ h x) x :=
begin
simp only [similarity_factor_sqrt_inv],
refine times_cont_diff_at.inv _ (similarity_factor_sqrt_prop x $ h x).1,
exact similarity_factor_sqrt_times_cont_diff_at x h H
end
/-- TODO: refine the hypothesis `h` -/
lemma similarity_factor_sqrt_inv_fderiv [nontrivial E] (x : E) (h : ∀ y, is_conformal_map $ f' y)
{n : ℕ} (hn : 0 < n) (H : times_cont_diff_at ℝ n f' x) :
(fderiv ℝ (λ y, similarity_factor_sqrt_inv y $ h y) x : E → ℝ) =
-(fderiv ℝ (λ y, similarity_factor_sqrt y $ h y) x) * (λ y, (similarity_factor x $ h x)⁻¹) :=
begin
have minor₁ := (similarity_factor_sqrt_prop x $ h x).1,
have minor₂ : (1 : with_top ℕ) ≤ n :=
by { apply with_top.coe_le_coe.mpr, linarith [hn] },
have minor₃ := (similarity_factor_sqrt_times_cont_diff_at x h H).differentiable_at minor₂,
rw [similarity_factor_sqrt_inv_eq_comp_inv, fderiv.comp _ (differentiable_at_inv _), fderiv_inv];
[skip, exact minor₁, exact minor₃, exact minor₁],
simp only [continuous_linear_map.coe_comp'],
ext1 y,
simp only [function.comp_app, continuous_linear_map.smul_right_apply,
continuous_linear_map.one_apply, smul_eq_mul, pi.mul_apply,
pi.neg_apply, pi.inv_apply],
rw [similarity_factor_sqrt_eq' (h x), neg_mul_comm]
end
end similarity3
end similarity_all |
f487278734d70a3330d6b4dc8bea3dd6c06099ac | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/logic/quantifiers.lean | ca55b9cdd983e24a530cc382cd67fbdd92f80bda | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,021 | 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
Universal and existential quantifiers. See also init.logic.
-/
import .connectives
open inhabited nonempty
theorem exists_imp_distrib {A : Type} {B : Prop} {P : A → Prop} : ((∃ a : A, P a) → B) ↔ (∀ a : A, P a → B) :=
iff.intro (λ e x H, e (exists.intro x H)) Exists.rec
theorem forall_iff_not_exists {A : Type} {P : A → Prop} : (¬ ∃ a : A, P a) ↔ ∀ a : A, ¬ P a :=
exists_imp_distrib
theorem not_forall_not_of_exists {A : Type} {p : A → Prop} (H : ∃ x, p x) : ¬ ∀ x, ¬ p x :=
assume H1 : ∀ x, ¬ p x,
obtain (w : A) (Hw : p w), from H,
absurd Hw (H1 w)
theorem not_exists_not_of_forall {A : Type} {p : A → Prop} (H2 : ∀ x, p x) : ¬ ∃ x, ¬p x :=
assume H1 : ∃ x, ¬ p x,
obtain (w : A) (Hw : ¬ p w), from H1,
absurd (H2 w) Hw
theorem not_forall_of_exists_not {A : Type} {P : A → Prop} (H : ∃ a : A, ¬ P a) : ¬ ∀ a : A, P a :=
assume H', not_exists_not_of_forall H' H
theorem forall_congr {A : Type} {φ ψ : A → Prop} : (∀ x, φ x ↔ ψ x) → ((∀ x, φ x) ↔ (∀ x, ψ x)) :=
forall_iff_forall
theorem exists_congr {A : Type} {φ ψ : A → Prop} : (∀ x, φ x ↔ ψ x) → ((∃ x, φ x) ↔ (∃ x, ψ x)) :=
exists_iff_exists
theorem forall_true_iff_true (A : Type) : (∀ x : A, true) ↔ true :=
iff_true_intro (λH, trivial)
theorem forall_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∀ x : A, p) ↔ p :=
iff.intro (inhabited.destruct H) (λ Hr x, Hr)
theorem exists_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∃ x : A, p) ↔ p :=
iff.intro (Exists.rec (λ x Hp, Hp)) (inhabited.destruct H exists.intro)
theorem forall_and_distribute {A : Type} (φ ψ : A → Prop) :
(∀ x, φ x ∧ ψ x) ↔ (∀ x, φ x) ∧ (∀ x, ψ x) :=
iff.intro
(assume H, and.intro (take x, and.left (H x)) (take x, and.right (H x)))
(assume H x, and.intro (and.left H x) (and.right H x))
theorem exists_or_distribute {A : Type} (φ ψ : A → Prop) :
(∃ x, φ x ∨ ψ x) ↔ (∃ x, φ x) ∨ (∃ x, ψ x) :=
iff.intro
(Exists.rec (λ x, or.imp !exists.intro !exists.intro))
(or.rec (exists_imp_exists (λ x, or.inl))
(exists_imp_exists (λ x, or.inr)))
section
open decidable eq.ops
variables {A : Type} (P : A → Prop) (a : A) [H : decidable (P a)]
include H
definition decidable_forall_eq [instance] : decidable (∀ x, x = a → P x) :=
if pa : P a then inl (λ x heq, eq.substr heq pa)
else inr (not.mto (λH, H a rfl) pa)
definition decidable_exists_eq [instance] : decidable (∃ x, x = a ∧ P x) :=
if pa : P a then inl (exists.intro a (and.intro rfl pa))
else inr (Exists.rec (λh, and.rec (λheq, eq.substr heq pa)))
end
/- 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 {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 {A : Type} {p : A → Prop} {b : Prop}
(H2 : ∃!x, p x) (H1 : ∀x, p x → (∀y, p y → y = x) → b) : b :=
obtain w Hw, from H2,
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 :=
obtain x px, from Hex,
exists_unique.intro x px (take y, suppose p y, show y = x, from !Hunique this px)
theorem exists_of_exists_unique {A : Type} {p : A → Prop} (H : ∃! x, p x) :
∃ x, p x :=
obtain x Hx, from H,
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₂)))
/- definite description -/
section
open classical
noncomputable definition the {A : Type} {p : A → Prop} (H : ∃! x, p x) : A :=
some (exists_of_exists_unique H)
theorem the_spec {A : Type} {p : A → Prop} (H : ∃! x, p x) : p (the H) :=
some_spec (exists_of_exists_unique H)
theorem eq_the {A : Type} {p : A → Prop} (H : ∃! x, p x) {y : A} (Hy : p y) :
y = the H :=
unique_of_exists_unique H Hy (the_spec H)
end
/- congruences -/
section
variables {A : Type} {p₁ p₂ : A → Prop} (H : ∀ x, p₁ x ↔ p₂ x)
theorem congr_forall : (∀ x, p₁ x) ↔ (∀ x, p₂ x) :=
forall_congr H
theorem congr_exists : (∃ x, p₁ x) ↔ (∃ x, p₂ x) :=
exists_congr H
include H
theorem congr_exists_unique : (∃! x, p₁ x) ↔ (∃! x, p₂ x) :=
congr_exists (λx, congr_and (H x) (congr_forall
(λy, congr_imp (H y) iff.rfl)))
end
|
dd7e95f3991ceba5e6eb3d60d5b33ab0b616bc31 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/nat/cast.lean | 23af44230e9ab0b15f8bdf67c8bc7d667c443b9c | [
"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 | 11,935 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.ordered_field
import data.nat.basic
/-!
# Cast of naturals
This file defines the *canonical* homomorphism from the natural numbers into a type `α` with `0`,
`1` and `+` (typically an `add_monoid` with one).
## Main declarations
* `cast`: Canonical homomorphism `ℕ → α` where `α` has a `0`, `1` and `+`.
* `bin_cast`: Binary representation version of `cast`.
* `cast_add_monoid_hom`: `cast` bundled as an `add_monoid_hom`.
* `cast_ring_hom`: `cast` bundled as a `ring_hom`.
## Implementation note
Setting up the coercions priorities is tricky. See Note [coercion into rings].
-/
namespace nat
variables {α : Type*}
section
variables [has_zero α] [has_one α] [has_add α]
/-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/
protected def cast : ℕ → α
| 0 := 0
| (n+1) := cast n + 1
/-- Computationally friendlier cast than `nat.cast`, using binary representation. -/
protected def bin_cast (n : ℕ) : α :=
@nat.binary_rec (λ _, α) 0 (λ odd k a, cond odd (a + a + 1) (a + a)) n
/--
Coercions such as `nat.cast_coe` that go from a concrete structure such as
`ℕ` to an arbitrary ring `α` should be set up as follows:
```lean
@[priority 900] instance : has_coe_t ℕ α := ⟨...⟩
```
It needs to be `has_coe_t` instead of `has_coe` because otherwise type-class
inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`.
The reduced priority is necessary so that it doesn't conflict with instances
such as `has_coe_t α (option α)`.
For this to work, we reduce the priority of the `coe_base` and `coe_trans`
instances because we want the instances for `has_coe_t` to be tried in the
following order:
1. `has_coe_t` instances declared in mathlib (such as `has_coe_t α (with_top α)`, etc.)
2. `coe_base`, which contains instances such as `has_coe (fin n) n`
3. `nat.cast_coe : has_coe_t ℕ α` etc.
4. `coe_trans`
If `coe_trans` is tried first, then `nat.cast_coe` doesn't get a chance to apply.
-/
library_note "coercion into rings"
attribute [instance, priority 950] coe_base
attribute [instance, priority 500] coe_trans
-- see note [coercion into rings]
@[priority 900] instance cast_coe : has_coe_t ℕ α := ⟨nat.cast⟩
@[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl
theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl
@[simp, norm_cast, priority 500]
theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl
@[simp, norm_cast] theorem cast_ite (P : Prop) [decidable P] (m n : ℕ) :
(((ite P m n) : ℕ) : α) = ite P (m : α) (n : α) :=
by { split_ifs; refl, }
end
@[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _
@[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n
| 0 := (add_zero _).symm
| (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc]
@[simp] lemma bin_cast_eq [add_monoid α] [has_one α] (n : ℕ) :
(nat.bin_cast n : α) = ((n : ℕ) : α) :=
begin
rw nat.bin_cast,
apply binary_rec _ _ n,
{ rw [binary_rec_zero, cast_zero] },
{ intros b k h,
rw [binary_rec_eq, h],
{ cases b; simp [bit, bit0, bit1] },
{ simp } },
end
/-- `coe : ℕ → α` as an `add_monoid_hom`. -/
def cast_add_monoid_hom (α : Type*) [add_monoid α] [has_one α] : ℕ →+ α :=
{ to_fun := coe,
map_add' := cast_add,
map_zero' := cast_zero }
@[simp] lemma coe_cast_add_monoid_hom [add_monoid α] [has_one α] :
(cast_add_monoid_hom α : ℕ → α) = coe := rfl
@[simp, norm_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) :
((bit0 n : ℕ) : α) = bit0 n := cast_add _ _
@[simp, norm_cast] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) :
((bit1 n : ℕ) : α) = bit1 n :=
by rw [bit1, cast_add_one, cast_bit0]; refl
lemma cast_two {α : Type*} [add_monoid α] [has_one α] : ((2 : ℕ) : α) = 2 := by simp
@[simp, norm_cast] theorem cast_pred [add_group α] [has_one α] :
∀ {n}, 0 < n → ((n - 1 : ℕ) : α) = n - 1
| (n+1) h := (add_sub_cancel (n:α) 1).symm
@[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) :
((n - m : ℕ) : α) = n - m :=
eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h]
@[simp, norm_cast] theorem cast_mul [non_assoc_semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n
| 0 := (mul_zero _).symm
| (n+1) := (cast_add _ _).trans $
show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one]
@[simp] theorem cast_dvd {α : Type*} [field α] {m n : ℕ} (n_dvd : n ∣ m) (n_nonzero : (n:α) ≠ 0) :
((m / n : ℕ) : α) = m / n :=
begin
rcases n_dvd with ⟨k, rfl⟩,
have : n ≠ 0, {rintro rfl, simpa using n_nonzero},
rw nat.mul_div_cancel_left _ (pos_iff_ne_zero.2 this),
rw [nat.cast_mul, mul_div_cancel_left _ n_nonzero],
end
/-- `coe : ℕ → α` as a `ring_hom` -/
def cast_ring_hom (α : Type*) [non_assoc_semiring α] : ℕ →+* α :=
{ to_fun := coe,
map_one' := cast_one,
map_mul' := cast_mul,
.. cast_add_monoid_hom α }
@[simp] lemma coe_cast_ring_hom [non_assoc_semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl
lemma cast_commute [non_assoc_semiring α] (n : ℕ) (x : α) : commute ↑n x :=
nat.rec_on n (commute.zero_left x) $ λ n ihn, ihn.add_left $ commute.one_left x
lemma cast_comm [non_assoc_semiring α] (n : ℕ) (x : α) : (n : α) * x = x * n :=
(cast_commute n x).eq
lemma commute_cast [semiring α] (x : α) (n : ℕ) : commute x n :=
(n.cast_commute x).symm
section
variables [ordered_semiring α]
@[simp] theorem cast_nonneg : ∀ n : ℕ, 0 ≤ (n : α)
| 0 := le_refl _
| (n+1) := add_nonneg (cast_nonneg n) zero_le_one
theorem mono_cast : monotone (coe : ℕ → α) :=
λ m n h, let ⟨k, hk⟩ := le_iff_exists_add.1 h in by simp [hk]
variable [nontrivial α]
theorem strict_mono_cast : strict_mono (coe : ℕ → α) :=
λ m n h, nat.le_induction (lt_add_of_pos_right _ zero_lt_one)
(λ n _ h, lt_add_of_lt_of_pos h zero_lt_one) _ h
@[simp, norm_cast] theorem cast_le {m n : ℕ} :
(m : α) ≤ n ↔ m ≤ n :=
strict_mono_cast.le_iff_le
@[simp, norm_cast] theorem cast_lt {m n : ℕ} : (m : α) < n ↔ m < n :=
strict_mono_cast.lt_iff_lt
@[simp] theorem cast_pos {n : ℕ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
lemma cast_add_one_pos (n : ℕ) : 0 < (n : α) + 1 :=
add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one
@[simp, norm_cast] theorem one_lt_cast {n : ℕ} : 1 < (n : α) ↔ 1 < n :=
by rw [← cast_one, cast_lt]
@[simp, norm_cast] theorem one_le_cast {n : ℕ} : 1 ≤ (n : α) ↔ 1 ≤ n :=
by rw [← cast_one, cast_le]
@[simp, norm_cast] theorem cast_lt_one {n : ℕ} : (n : α) < 1 ↔ n = 0 :=
by rw [← cast_one, cast_lt, lt_succ_iff, le_zero_iff]
@[simp, norm_cast] theorem cast_le_one {n : ℕ} : (n : α) ≤ 1 ↔ n ≤ 1 :=
by rw [← cast_one, cast_le]
end
@[simp, norm_cast] theorem cast_min [linear_ordered_semiring α] {a b : ℕ} :
(↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp, norm_cast] theorem cast_max [linear_ordered_semiring α] {a b : ℕ} :
(↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp, norm_cast] theorem abs_cast [linear_ordered_ring α] (a : ℕ) :
abs (a : α) = a :=
abs_of_nonneg (cast_nonneg a)
lemma coe_nat_dvd [comm_semiring α] {m n : ℕ} (h : m ∣ n) :
(m : α) ∣ (n : α) :=
ring_hom.map_dvd (nat.cast_ring_hom α) h
alias coe_nat_dvd ← has_dvd.dvd.nat_cast
section linear_ordered_field
variables [linear_ordered_field α]
lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ :=
inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one
lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) :=
by { rw one_div, exact inv_pos_of_nat }
lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) :=
by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa }
lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) :=
by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa }
end linear_ordered_field
end nat
namespace add_monoid_hom
variables {A B : Type*} [add_monoid A]
@[ext] lemma ext_nat {f g : ℕ →+ A} (h : f 1 = g 1) : f = g :=
ext $ λ n, nat.rec_on n (f.map_zero.trans g.map_zero.symm) $ λ n ihn,
by simp only [nat.succ_eq_add_one, *, map_add]
variables [has_one A] [add_monoid B] [has_one B]
lemma eq_nat_cast (f : ℕ →+ A) (h1 : f 1 = 1) :
∀ n : ℕ, f n = n :=
congr_fun $ show f = nat.cast_add_monoid_hom A, from ext_nat (h1.trans nat.cast_one.symm)
lemma map_nat_cast (f : A →+ B) (h1 : f 1 = 1) (n : ℕ) : f n = n :=
(f.comp (nat.cast_add_monoid_hom A)).eq_nat_cast (by simp [h1]) _
end add_monoid_hom
namespace monoid_with_zero_hom
variables {A : Type*} [monoid_with_zero A]
/-- If two `monoid_with_zero_hom`s agree on the positive naturals they are equal. -/
@[ext] theorem ext_nat {f g : monoid_with_zero_hom ℕ A}
(h_pos : ∀ {n : ℕ}, 0 < n → f n = g n) : f = g :=
begin
ext (_ | n),
{ rw [f.map_zero, g.map_zero] },
{ exact h_pos n.zero_lt_succ, },
end
end monoid_with_zero_hom
namespace ring_hom
variables {R : Type*} {S : Type*} [non_assoc_semiring R] [non_assoc_semiring S]
@[simp] lemma eq_nat_cast (f : ℕ →+* R) (n : ℕ) : f n = n :=
f.to_add_monoid_hom.eq_nat_cast f.map_one n
@[simp] lemma map_nat_cast (f : R →+* S) (n : ℕ) :
f n = n :=
(f.comp (nat.cast_ring_hom R)).eq_nat_cast n
lemma ext_nat (f g : ℕ →+* R) : f = g :=
coe_add_monoid_hom_injective $ add_monoid_hom.ext_nat $ f.map_one.trans g.map_one.symm
end ring_hom
@[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n :=
((ring_hom.id ℕ).eq_nat_cast n).symm
@[simp] theorem nat.cast_with_bot : ∀ (n : ℕ),
@coe ℕ (with_bot ℕ) (@coe_to_lift _ _ nat.cast_coe) n = n
| 0 := rfl
| (n+1) := by rw [with_bot.coe_add, nat.cast_add, nat.cast_with_bot n]; refl
instance nat.subsingleton_ring_hom {R : Type*} [non_assoc_semiring R] : subsingleton (ℕ →+* R) :=
⟨ring_hom.ext_nat⟩
namespace with_top
variables {α : Type*}
variables [has_zero α] [has_one α] [has_add α]
@[simp, norm_cast] lemma coe_nat : ∀(n : nat), ((n : α) : with_top α) = n
| 0 := rfl
| (n+1) := by { push_cast, rw [coe_nat n] }
@[simp] lemma nat_ne_top (n : nat) : (n : with_top α) ≠ ⊤ :=
by { rw [←coe_nat n], apply coe_ne_top }
@[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n :=
by { rw [←coe_nat n], apply top_ne_coe }
lemma add_one_le_of_lt {i n : with_top ℕ} (h : i < n) : i + 1 ≤ n :=
begin
cases n, { exact le_top },
cases i, { exact (not_le_of_lt h le_top).elim },
exact with_top.coe_le_coe.2 (with_top.coe_lt_coe.1 h)
end
lemma one_le_iff_pos {n : with_top ℕ} : 1 ≤ n ↔ 0 < n :=
⟨λ h, (coe_lt_coe.2 zero_lt_one).trans_le h,
λ h, by simpa only [zero_add] using add_one_le_of_lt h⟩
@[elab_as_eliminator]
lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ)
(h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a :=
begin
have A : ∀n:ℕ, P n := λ n, nat.rec_on n h0 hsuc,
cases a,
{ exact htop A },
{ exact A a }
end
end with_top
namespace pi
variables {α β : Type*}
lemma nat_apply [has_zero β] [has_one β] [has_add β] :
∀ (n : ℕ) (a : α), (n : α → β) a = n
| 0 a := rfl
| (n+1) a := by rw [nat.cast_succ, nat.cast_succ, add_apply, nat_apply, one_apply]
@[simp] lemma coe_nat [has_zero β] [has_one β] [has_add β] (n : ℕ) :
(n : α → β) = λ _, n :=
by { ext, rw pi.nat_apply }
end pi
|
eb590ab034403f689f0bee280c8117712787a5d6 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/measure_theory/measure_space.lean | ec15e9c46077a01be3c7c2d9ffbadefcce54b0ba | [
"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 | 35,583 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.set.lattice data.set.finite
import topology.instances.ennreal
measure_theory.outer_measure
/-!
# Measure spaces
Measures are restricted to a measurable space (associated by the type class `measurable_space`).
This allows us to prove equalities between measures by restricting to a generating set of the
measurable space.
On the other hand, the `μ.measure s` projection (i.e. the measure of `s` on the measure space `μ`)
is the _outer_ measure generated by `μ`. This gives us a unrestricted monotonicity rule and it is
somehow well-behaved on non-measurable sets.
This allows us for the `lebesgue` measure space to have the `borel` measurable space, but still be
a complete measure.
-/
noncomputable theory
open classical set filter finset function
open_locale classical topological_space
universes u v w x
namespace measure_theory
section of_measurable
parameters {α : Type*} [measurable_space α]
parameters (m : Π (s : set α), is_measurable s → ennreal)
parameters (m0 : m ∅ is_measurable.empty = 0)
include m0
/-- Measure projection which is ∞ for non-measurable sets.
`measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/
def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, m s h
lemma measure'_eq {s} (h : is_measurable s) : measure' s = m s h :=
by simp [measure', h]
lemma measure'_empty : measure' ∅ = 0 :=
(measure'_eq is_measurable.empty).trans m0
lemma measure'_Union_nat
{f : ℕ → set α}
(hm : ∀i, is_measurable (f i))
(mU : m (⋃i, f i) (is_measurable.Union hm) = (∑i, m (f i) (hm i))) :
measure' (⋃i, f i) = (∑i, measure' (f i)) :=
(measure'_eq _).trans $ mU.trans $
by congr; funext i; rw measure'_eq
/-- outer measure of a measure -/
def outer_measure' : outer_measure α :=
outer_measure.of_function measure' measure'_empty
lemma measure'_Union_le_tsum_nat'
(mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
m (⋃i, f i) (is_measurable.Union hm) ≤ (∑i, m (f i) (hm i)))
(s : ℕ → set α) :
measure' (⋃i, s i) ≤ (∑i, measure' (s i)) :=
begin
by_cases h : ∀i, is_measurable (s i),
{ rw [measure'_eq _ _ (is_measurable.Union h),
congr_arg tsum _], {apply mU h},
funext i, apply measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) }
end
parameter (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union hm) = (∑i, m (f i) (hm i)))
include mU
lemma measure'_Union
{β} [encodable β] {f : β → set α}
(hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) :
measure' (⋃i, f i) = (∑i, measure' (f i)) :=
begin
rw [encodable.Union_decode2, outer_measure.Union_aux],
{ exact measure'_Union_nat _ _
(λ n, encodable.Union_decode2_cases is_measurable.empty hm)
(mU _ (measurable_space.Union_decode2_disjoint_on hd)) },
{ apply measure'_empty },
end
lemma measure'_union {s₁ s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
measure' (s₁ ∪ s₂) = measure' s₁ + measure' s₂ :=
begin
rw [union_eq_Union, measure'_Union _ _ @mU
(pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩),
tsum_fintype],
change _+_ = _, simp
end
lemma measure'_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) :
measure' s₁ ≤ measure' s₂ :=
le_infi $ λ h₂, begin
have := measure'_union _ _ @mU disjoint_diff h₁ (h₂.diff h₁),
rw union_diff_cancel hs at this,
rw ← measure'_eq m m0 _,
exact le_iff_exists_add.2 ⟨_, this⟩
end
lemma measure'_Union_le_tsum_nat : ∀ (s : ℕ → set α),
measure' (⋃i, s i) ≤ (∑i, measure' (s i)) :=
measure'_Union_le_tsum_nat' $ λ f h, begin
simp [Union_disjointed.symm] {single_pass := tt},
rw [mU (is_measurable.disjointed h) disjoint_disjointed],
refine ennreal.tsum_le_tsum (λ i, _),
rw [← measure'_eq m m0, ← measure'_eq m m0],
exact measure'_mono _ _ @mU (is_measurable.disjointed h _) (inter_subset_left _ _)
end
lemma outer_measure'_eq {s : set α} (hs : is_measurable s) :
outer_measure' s = m s hs :=
by rw ← measure'_eq m m0 hs; exact
(le_antisymm (outer_measure.of_function_le _ _ _) $
le_infi $ λ f, le_infi $ λ hf,
le_trans (measure'_mono _ _ @mU hs hf) $
measure'_Union_le_tsum_nat _ _ @mU _)
lemma outer_measure'_eq_measure' {s : set α} (hs : is_measurable s) :
outer_measure' s = measure' s :=
by rw [measure'_eq m m0 hs, outer_measure'_eq m m0 @mU hs]
end of_measurable
namespace outer_measure
variables {α : Type*} [measurable_space α] (m : outer_measure α)
def trim : outer_measure α :=
outer_measure' (λ s _, m s) m.empty
theorem trim_ge : m ≤ m.trim :=
λ s, le_infi $ λ f, le_infi $ λ hs,
le_trans (m.mono hs) $ le_trans (m.Union_nat f) $
ennreal.tsum_le_tsum $ λ i, le_infi $ λ hf, le_refl _
theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s :=
le_antisymm (le_trans (of_function_le _ _ _) (infi_le _ hs)) (trim_ge _ _)
theorem trim_congr {m₁ m₂ : outer_measure α}
(H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) :
m₁.trim = m₂.trim :=
by unfold trim; congr; funext s hs; exact H hs
theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim :=
λ s, infi_le_infi $ λ f, infi_le_infi $ λ hs,
ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _
theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔
∀ s, is_measurable s → m₁ s ≤ m₂ s :=
le_of_function.trans $ forall_congr $ λ s, le_infi_iff
theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t :=
begin
refine le_antisymm
(le_infi $ λ t, le_infi $ λ st, le_infi $ λ ht, _)
(le_infi $ λ f, le_infi $ λ hf, _),
{ rw ← trim_eq m ht, exact (trim m).mono st },
{ by_cases h : ∀i, is_measurable (f i),
{ refine infi_le_of_le _ (infi_le_of_le hf $
infi_le_of_le (is_measurable.Union h) _),
rw congr_arg tsum _, {exact m.Union_nat _},
funext i, exact measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } }
end
theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t.1 :=
by simp [infi_subtype, infi_and, trim_eq_infi]
theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim :=
le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (trim_ge _)
theorem trim_zero : (0 : outer_measure α).trim = 0 :=
ext $ λ s, le_antisymm
(le_trans ((trim 0).mono (subset_univ s)) $
le_of_eq $ trim_eq _ is_measurable.univ)
(zero_le _)
theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim :=
ext $ λ s, begin
simp [trim_eq_infi'],
rw ennreal.infi_add_infi,
rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩,
exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩,
add_le_add'
(m₁.mono' (inter_subset_left _ _))
(m₂.mono' (inter_subset_right _ _))⟩,
end
theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim :=
λ s, by simp [trim_eq_infi]; exact
λ t st ht, ennreal.tsum_le_tsum (λ i,
infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht)
end outer_measure
structure measure (α : Type*) [measurable_space α] extends outer_measure α :=
(m_Union {f : ℕ → set α} :
(∀i, is_measurable (f i)) → pairwise (disjoint on f) →
measure_of (⋃i, f i) = (∑i, measure_of (f i)))
(trimmed : to_outer_measure.trim = to_outer_measure)
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) :=
⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩
namespace measure
def of_measurable {α} [measurable_space α]
(m : Π (s : set α), is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑i, m (f i) (h i))) :
measure α :=
{ m_Union := λ f hf hd,
show outer_measure' m m0 (Union f) =
∑ i, outer_measure' m m0 (f i), begin
rw [outer_measure'_eq m m0 @mU, mU hf hd],
congr, funext n, rw outer_measure'_eq m m0 @mU
end,
trimmed :=
show (outer_measure' m m0).trim = outer_measure' m m0, begin
unfold outer_measure.trim,
congr, funext s hs,
exact outer_measure'_eq m m0 @mU hs
end,
..outer_measure' m m0 }
lemma of_measurable_apply {α} [measurable_space α]
{m : Π (s : set α), is_measurable s → ennreal}
{m0 : m ∅ is_measurable.empty = 0}
{mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑i, m (f i) (h i))}
(s : set α) (hs : is_measurable s) :
of_measurable m m0 @mU s = m s hs :=
outer_measure'_eq m m0 @mU hs
@[ext] lemma ext {α} [measurable_space α] :
∀ {μ₁ μ₂ : measure α}, (∀s, is_measurable s → μ₁ s = μ₂ s) → μ₁ = μ₂
| ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h := by congr; rw [← h₁, ← h₂];
exact outer_measure.trim_congr h
end measure
section
variables {α : Type*} {β : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ : set α}
@[simp] lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl
lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s :=
by rw μ.trimmed; refl
lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t :=
by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl
lemma measure_eq_outer_measure' :
μ s = outer_measure' (λ s _, μ s) μ.empty s :=
measure_eq_trim _
lemma to_outer_measure_eq_outer_measure' :
μ.to_outer_measure = outer_measure' (λ s _, μ s) μ.empty :=
μ.trimmed.symm
lemma measure_eq_measure' (hs : is_measurable s) :
μ s = measure' (λ s _, μ s) μ.empty s :=
by rw [measure_eq_outer_measure',
outer_measure'_eq_measure' (λ s _, μ s) _ μ.m_Union hs]
@[simp] lemma measure_empty : μ ∅ = 0 := μ.empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h
lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 :=
by rw [← le_zero_iff_eq, ← h₂]; exact measure_mono h
lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
begin
rw [measure_eq_infi] at h,
have h := (infi_eq_bot _).1 h,
choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ μ t < n⁻¹,
{ assume n,
have : (0 : ennreal) < n⁻¹ :=
(zero_lt_iff_ne_zero.2 $ ennreal.inv_ne_zero.2 $ ennreal.nat_ne_top _),
rcases h _ this with ⟨t, ht⟩,
use [t],
simpa [(>), infi_lt_iff, -add_comm] using ht },
refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩,
refine eq_of_le_of_forall_le_of_dense bot_le (assume r hr, _),
rcases ennreal.exists_inv_nat_lt (ne_of_gt hr) with ⟨n, hn⟩,
calc μ (⋂n, t n) ≤ μ (t n) : measure_mono (Inter_subset _ _)
... ≤ n⁻¹ : le_of_lt (ht n).2.2
... ≤ r : le_of_lt hn
end
theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑i, μ (s i)) :=
μ.to_outer_measure.Union _
lemma measure_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 :=
μ.to_outer_measure.Union_null
theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ :=
μ.to_outer_measure.union _ _
lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 :=
μ.to_outer_measure.union_null
lemma measure_Union {β} [encodable β] {f : β → set α}
(hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) :
μ (⋃i, f i) = (∑i, μ (f i)) :=
by rw [measure_eq_measure' (is_measurable.Union h),
measure'_Union (λ s _, μ s) _ μ.m_Union hn h];
simp [measure_eq_measure', h]
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
by rw [measure_eq_measure' (h₁.union h₂),
measure'_union (λ s _, μ s) _ μ.m_Union hd h₁ h₂];
simp [measure_eq_measure', h₁, h₂]
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑p:s, μ (f p.1) :=
begin
haveI := hs.to_encodable,
rw [← measure_Union, bUnion_eq_Union],
{ rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩,
exact hd i hi j hj (mt subtype.eq' ij:_) ⟨h₁, h₂⟩ },
{ simpa }
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) :
μ (⋃₀ S) = ∑s:S, μ s.1 :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁)
(h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) :
μ (⋃i, s i) = (⨆i, μ (s i)) :=
begin
refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _),
rw [← Union_disjointed,
measure_Union disjoint_disjointed (is_measurable.disjointed h),
ennreal.tsum_eq_supr_nat],
refine supr_le (λ n, _),
cases n, {apply zero_le _},
suffices : (finset.range n.succ).sum (λ i, μ (disjointed s i)) = μ (s n),
{ rw this, exact le_supr _ n },
rw [← Union_disjointed_of_mono hs, measure_Union, tsum_eq_sum],
{ apply sum_congr rfl, intros i hi,
simp [finset.mem_range.1 hi] },
{ intros i hi, simp [mt finset.mem_range.2 hi] },
{ rintro i j ij x ⟨⟨_, ⟨_, rfl⟩, h₁⟩, ⟨_, ⟨_, rfl⟩, h₂⟩⟩,
exact disjoint_disjointed i j ij ⟨h₁, h₂⟩ },
{ intro i,
by_cases h' : i < n.succ; simp [h', is_measurable.empty],
apply is_measurable.disjointed h }
end
lemma measure_Inter_eq_infi_nat {s : ℕ → set α}
(h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i)
(hfin : ∃i, μ (s i) < ⊤) :
μ (⋂i, s i) = (⨅i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k),
ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h)
(lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk),
diff_Inter, measure_Union_eq_supr_nat],
{ congr, funext i,
cases le_total k i with ik ik,
{ exact measure_diff (hs _ _ ik) (h k) (h i)
(lt_of_le_of_lt (measure_mono (hs _ _ ik)) hk) },
{ rw [diff_eq_empty.2 (hs _ _ ik), measure_empty,
ennreal.sub_eq_zero_of_le (measure_mono (hs _ _ ik))] } },
{ exact λ i, (h k).diff (h i) },
{ exact λ i j ij, diff_subset_diff_right (hs _ _ ij) }
end
lemma measure_eq_inter_diff {μ : measure α} {s t : set α}
(hs : is_measurable s) (ht : is_measurable t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋃n, s n))) :=
begin
rw measure_Union_eq_supr_nat hs hm,
exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm $ hnm)
end
lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : ∀n m, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋂n, s n))) :=
begin
rw measure_Inter_eq_infi_nat hs hm hf,
exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm _ _ $ hnm),
end
end
def outer_measure.to_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α]
(μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_outer_measure',
refine outer_measure.caratheodory_is_measurable (λ t, le_infi $ λ ht, _),
rw [← measure_eq_measure' (ht.inter hs),
← measure_eq_measure' (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
lemma to_measure_to_outer_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory)
{s : set α} (hs : is_measurable s) :
m.to_measure h s = m s := m.trim_eq hs
lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
namespace measure
variables {α : Type*} {β : Type*} {γ : Type*}
[measurable_space α] [measurable_space β] [measurable_space γ]
instance : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure :
(0 : measure α).to_outer_measure = 0 := rfl
@[simp] theorem zero_apply (s : set α) : (0 : measure α) s = 0 := rfl
instance : inhabited (measure α) := ⟨0⟩
instance : has_add (measure α) :=
⟨λμ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λs hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑ i, μ₁ (s i) + μ₂ (s i),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp] theorem add_apply (μ₁ μ₂ : measure α) (s : set α) :
(μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance add_comm_monoid : add_comm_monoid (measure α) :=
{ zero := 0,
add := (+),
add_assoc := assume a b c, ext $ assume s hs, add_assoc _ _ _,
add_comm := assume a b, ext $ assume s hs, add_comm _ _,
zero_add := assume a, ext $ assume s hs, zero_add _,
add_zero := assume a, ext $ assume s hs, add_zero _ }
instance : partial_order (measure α) :=
{ le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le {μ₁ μ₂ : measure α} :
μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
section
variables {m : set (measure α)} {μ : measure α}
lemma Inf_caratheodory (s : set α) (hs : is_measurable s) :
(Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable s :=
begin
rw [outer_measure.Inf_eq_of_function_Inf_gen],
refine outer_measure.caratheodory_is_measurable (assume t, _),
cases t.eq_empty_or_nonempty with ht ht, by simp [ht],
simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff,
to_outer_measure_apply, measure_eq_infi t],
assume μ hμ u htu hu,
have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ assume s t hst,
rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add' (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance : has_Inf (measure α) :=
⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) :
Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance : has_Sup (measure α) := ⟨λs, Inf {μ' | ∀μ∈s, μ ≤ μ' }⟩
private lemma le_Sup (h : μ ∈ m) : μ ≤ Sup m := le_Inf $ assume μ' h', h' _ h
private lemma Sup_le (h : ∀μ' ∈ m, μ' ≤ μ) : Sup m ≤ μ := Inf_le h
instance : order_bot (measure α) :=
{ bot := 0, bot_le := assume a s hs, bot_le, .. measure.partial_order }
instance : order_top (measure α) :=
{ top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
.. measure.partial_order }
instance : complete_lattice (measure α) :=
{ Inf := Inf,
Sup := Sup,
inf := λa b, Inf {a, b},
sup := λa b, Sup {a, b},
le_Sup := assume s μ h, le_Sup h,
Sup_le := assume s μ h, Sup_le h,
Inf_le := assume s μ h, Inf_le h,
le_Inf := assume s μ h, le_Inf h,
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 hac hbc, Sup_le $ by simp [*, or_imp_distrib] {contextual := tt},
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 hac hbc, le_Inf $ by simp [*, or_imp_distrib] {contextual := tt},
.. measure.partial_order, .. measure.order_top, .. measure.order_bot }
end
def map (f : α → β) (μ : measure α) : measure β :=
if hf : measurable f then
(μ.to_outer_measure.map f).to_measure $ λ s hs t,
le_to_outer_measure_caratheodory μ _ (hf _ hs) (f ⁻¹' t)
else 0
variables {μ ν : measure α}
@[simp] theorem map_apply {f : α → β} (hf : measurable f)
{s : set β} (hs : is_measurable s) :
(map f μ : measure β) s = μ (f ⁻¹' s) :=
by rw [map, dif_pos hf, to_measure_apply _ _ hs]; refl
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg.preimage hs, hg.comp hf];
rw ← preimage_comp
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
@[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) :
(dirac a : measure α) s = ⨆ h : a ∈ s, 1 :=
to_measure_apply _ _ hs
/-- Sum of an indexed family of measures. -/
def sum {ι : Type*} (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
@[class] def is_complete {α} {_:measurable_space α} (μ : measure α) : Prop :=
∀ s, μ s = 0 → is_measurable s
/-- The "almost everywhere" filter of co-null sets. -/
def a_e (μ : measure α) : filter α :=
{ sets := {s | μ (-s) = 0},
univ_sets := by simp [measure_empty],
inter_sets := λ s t hs ht, by simp [compl_inter]; exact measure_union_null hs ht,
sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs }
lemma mem_a_e_iff (s : set α) : s ∈ μ.a_e.sets ↔ μ (- s) = 0 := iff.rfl
end measure
end measure_theory
section is_complete
open measure_theory
variables {α : Type*} [measurable_space α] (μ : measure α)
def is_null_measurable (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0
theorem is_null_measurable_iff {μ : measure α} {s : set α} :
is_null_measurable μ s ↔
∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α}
(st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem is_measurable.is_null_measurable
{s : set α} (hs : is_measurable s) : is_null_measurable μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem is_null_measurable_of_complete [c : μ.is_complete]
{s : set α} : is_null_measurable μ s ↔ is_measurable s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
is_measurable.union ht (c _ hz),
λ h, h.is_null_measurable _⟩
variables {μ}
theorem is_null_measurable.union_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_is_null_measurable {z : set α}
(hz : μ z = 0) : is_null_measurable μ z :=
by simpa using (is_measurable.empty.is_null_measurable _).union_null hz
theorem is_null_measurable.Union_nat {s : ℕ → set α}
(hs : ∀ i, is_null_measurable μ (s i)) :
is_null_measurable μ (Union s) :=
begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine is_null_measurable_iff.2
⟨Union t, Union_subset_Union st, is_measurable.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem is_measurable.diff_null {s z : set α}
(hs : is_measurable s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α,
z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal),
{ rintro ⟨ε, ε0⟩,
have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine is_null_measurable_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (is_measurable.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem is_null_measurable.diff_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem is_null_measurable.compl {s : set α}
(hs : is_null_measurable μ s) :
is_null_measurable μ (-s) :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
def null_measurable {α : Type u} [measurable_space α]
(μ : measure α) : measurable_space α :=
{ is_measurable := is_null_measurable μ,
is_measurable_empty := is_measurable.empty.is_null_measurable _,
is_measurable_compl := λ s hs, hs.compl,
is_measurable_Union := λ f, is_null_measurable.Union_nat }
def completion {α : Type u} [measurable_space α] (μ : measure α) :
@measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑ i, μ (s i), begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw is_null_measurable_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (is_null_measurable_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.trim_ge _),
rw outer_measure.trim_eq_infi,
dsimp, clear _inst,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩)
end }
instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) :
(completion μ).is_complete :=
λ z hz, null_is_null_measurable hz
end is_complete
namespace measure_theory
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type*) extends measurable_space α :=
(μ {} : measure α)
end prio
section measure_space
variables {α : Type*} [measure_space α] {s₁ s₂ : set α}
open measure_space
def volume : set α → ennreal := @μ α _
@[simp] lemma volume_empty : volume (∅ : set α) = 0 := μ.empty
lemma volume_mono : s₁ ⊆ s₂ → volume s₁ ≤ volume s₂ := measure_mono
lemma volume_mono_null : s₁ ⊆ s₂ → volume s₂ = 0 → volume s₁ = 0 :=
measure_mono_null
theorem volume_Union_le {β} [encodable β] :
∀ (s : β → set α), volume (⋃i, s i) ≤ (∑i, volume (s i)) :=
measure_Union_le
lemma volume_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, volume (s i) = 0) → volume (⋃i, s i) = 0 :=
measure_Union_null
theorem volume_union_le : ∀ (s₁ s₂ : set α), volume (s₁ ∪ s₂) ≤ volume s₁ + volume s₂ :=
measure_union_le
lemma volume_union_null : volume s₁ = 0 → volume s₂ = 0 → volume (s₁ ∪ s₂) = 0 :=
measure_union_null
lemma volume_Union {β} [encodable β] {f : β → set α} :
pairwise (disjoint on f) → (∀i, is_measurable (f i)) →
volume (⋃i, f i) = (∑i, volume (f i)) :=
measure_Union
lemma volume_union : disjoint s₁ s₂ → is_measurable s₁ → is_measurable s₂ →
volume (s₁ ∪ s₂) = volume s₁ + volume s₂ :=
measure_union
lemma volume_bUnion {β} {s : set β} {f : β → set α} : countable s →
pairwise_on s (disjoint on f) → (∀b∈s, is_measurable (f b)) →
volume (⋃b∈s, f b) = ∑p:s, volume (f p.1) :=
measure_bUnion
lemma volume_sUnion {S : set (set α)} : countable S →
pairwise_on S disjoint → (∀s∈S, is_measurable s) →
volume (⋃₀ S) = ∑s:S, volume s.1 :=
measure_sUnion
lemma volume_bUnion_finset {β} {s : finset β} {f : β → set α}
(hd : pairwise_on ↑s (disjoint on f)) (hm : ∀b∈s, is_measurable (f b)) :
volume (⋃b∈s, f b) = s.sum (λp, volume (f p)) :=
show volume (⋃b∈(↑s : set β), f b) = s.sum (λp, volume (f p)),
begin
rw [volume_bUnion (countable_finite (finset.finite_to_set s)) hd hm, tsum_eq_sum],
{ show s.attach.sum (λb:(↑s : set β), volume (f b)) = s.sum (λb, volume (f b)),
exact @finset.sum_attach _ _ s _ (λb, volume (f b)) },
simp
end
lemma volume_diff : s₂ ⊆ s₁ → is_measurable s₁ → is_measurable s₂ →
volume s₂ < ⊤ → volume (s₁ \ s₂) = volume s₁ - volume s₂ :=
measure_diff
/-- `∀ₘ a:α, p a` states that the property `p` is almost everywhere true in the measure space
associated with `α`. This means that the measure of the complementary of `p` is `0`.
In a probability measure, the measure of `p` is `1`, when `p` is measurable.
-/
def all_ae (p : α → Prop) : Prop :=
∀ᶠ a in μ.a_e, p a
notation `∀ₘ` binders `, ` r:(scoped P, all_ae P) := r
lemma all_ae_congr {p q : α → Prop} (h : ∀ₘ a, p a ↔ q a) : (∀ₘ a, p a) ↔ (∀ₘ a, q a) :=
iff.intro
(assume h', by filter_upwards [h, h'] assume a hpq hp, hpq.1 hp)
(assume h', by filter_upwards [h, h'] assume a hpq hq, hpq.2 hq)
lemma all_ae_iff {p : α → Prop} : (∀ₘ a, p a) ↔ volume { a | ¬ p a } = 0 := iff.rfl
lemma all_ae_of_all {p : α → Prop} : (∀a, p a) → ∀ₘ a, p a := univ_mem_sets'
lemma all_ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} :
(∀ₘ a, ∀i, p a i) ↔ (∀i, ∀ₘ a, p a i) :=
begin
refine iff.intro (assume h i, _) (assume h, _),
{ filter_upwards [h] assume a ha, ha i },
{ have h := measure_Union_null h,
rw [← compl_Inter] at h,
filter_upwards [h] assume a, mem_Inter.1 }
end
variables {β : Type*}
lemma all_ae_eq_refl (f : α → β) : ∀ₘ a, f a = f a :=
by { filter_upwards [], assume a, apply eq.refl }
lemma all_ae_eq_symm {f g : α → β} : (∀ₘ a, f a = g a) → (∀ₘ a, g a = f a) :=
by { assume h, filter_upwards [h], assume a, apply eq.symm }
lemma all_ae_eq_trans {f g h: α → β} (h₁ : ∀ₘ a, f a = g a) (h₂ : ∀ₘ a, g a = h a) :
∀ₘ a, f a = h a :=
by { filter_upwards [h₁, h₂], intro a, exact eq.trans }
end measure_space
end measure_theory
|
1760debd48fd55719c0409b90656a5a863a8772d | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/algebra/char_zero.lean | 973a44515c44bb7891460db01789e902d2600925 | [
"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 | 5,533 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.nat.cast
import data.fintype.basic
import tactic.wlog
/-!
# Characteristic zero
A ring `R` is called of characteristic zero if every natural number `n` is non-zero when considered
as an element of `R`. Since this definition doesn't mention the multiplicative structure of `R`
except for the existence of `1` in this file characteristic zero is defined for additive monoids
with `1`.
## Main definition
`char_zero` is the typeclass of an additive monoid with one such that the natural homomorphism
from the natural numbers into it is injective.
## Main statements
* A linearly ordered semiring has characteristic zero.
* Characteristic zero implies that the additive monoid is infinite.
## TODO
* Once order of a group is defined for infinite additive monoids redefine or at least connect to
order of `1` in the additive monoid with one.
* Unify with `char_p` (possibly using an out-parameter)
-/
/-- Typeclass for monoids with characteristic zero.
(This is usually stated on fields but it makes sense for any additive monoid with 1.) -/
class char_zero (R : Type*) [add_monoid R] [has_one R] : Prop :=
(cast_injective : function.injective (coe : ℕ → R))
theorem char_zero_of_inj_zero {R : Type*} [add_left_cancel_monoid R] [has_one R]
(H : ∀ n:ℕ, (n:R) = 0 → n = 0) : char_zero R :=
⟨λ m n, begin
assume h,
wlog hle : m ≤ n,
rcases nat.le.dest hle with ⟨k, rfl⟩,
rw [nat.cast_add, eq_comm, add_right_eq_self] at h,
rw [H k h, add_zero]
end⟩
/-- Note this is not an instance as `char_zero` implies `nontrivial`,
and this would risk forming a loop. -/
lemma ordered_semiring.to_char_zero {R : Type*} [ordered_semiring R] [nontrivial R] :
char_zero R :=
⟨nat.strict_mono_cast.injective⟩
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_semiring.to_char_zero {R : Type*}
[linear_ordered_semiring R] : char_zero R :=
ordered_semiring.to_char_zero
namespace nat
variables {R : Type*} [add_monoid R] [has_one R] [char_zero R]
theorem cast_injective : function.injective (coe : ℕ → R) :=
char_zero.cast_injective
@[simp, norm_cast] theorem cast_inj {m n : ℕ} : (m : R) = n ↔ m = n :=
cast_injective.eq_iff
@[simp, norm_cast] theorem cast_eq_zero {n : ℕ} : (n : R) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
@[norm_cast] theorem cast_ne_zero {n : ℕ} : (n : R) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
lemma cast_add_one_ne_zero (n : ℕ) : (n + 1 : R) ≠ 0 :=
by exact_mod_cast n.succ_ne_zero
@[simp, norm_cast]
theorem cast_dvd_char_zero {k : Type*} [field k] [char_zero k] {m n : ℕ}
(n_dvd : n ∣ m) : ((m / n : ℕ) : k) = m / n :=
begin
by_cases hn : n = 0,
{ subst hn,
simp },
{ exact cast_dvd n_dvd (cast_ne_zero.mpr hn), },
end
end nat
section
variables (M : Type*) [add_monoid M] [has_one M] [char_zero M]
@[priority 100] -- see Note [lower instance priority]
instance char_zero.infinite : infinite M :=
infinite.of_injective coe nat.cast_injective
variable {M}
@[field_simps] lemma two_ne_zero' : (2:M) ≠ 0 :=
have ((2:ℕ):M) ≠ 0, from nat.cast_ne_zero.2 dec_trivial,
by rwa [nat.cast_two] at this
end
section
variables {R : Type*} [semiring R] [no_zero_divisors R] [char_zero R]
@[simp]
lemma add_self_eq_zero {a : R} : a + a = 0 ↔ a = 0 :=
by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or]
@[simp]
lemma bit0_eq_zero {a : R} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero
@[simp]
lemma zero_eq_bit0 {a : R} : 0 = bit0 a ↔ a = 0 :=
by { rw [eq_comm], exact bit0_eq_zero }
end
section
variables {R : Type*} [ring R] [no_zero_divisors R] [char_zero R]
lemma nat_mul_inj {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) : n = 0 ∨ a = b :=
begin
rw [←sub_eq_zero, ←mul_sub, mul_eq_zero, sub_eq_zero] at h,
exact_mod_cast h,
end
lemma nat_mul_inj' {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) (w : n ≠ 0) : a = b :=
by simpa [w] using nat_mul_inj h
lemma bit0_injective : function.injective (bit0 : R → R) :=
λ a b h, begin
dsimp [bit0] at h,
simp only [(two_mul a).symm, (two_mul b).symm] at h,
refine nat_mul_inj' _ two_ne_zero,
exact_mod_cast h,
end
lemma bit1_injective : function.injective (bit1 : R → R) :=
λ a b h, begin
simp only [bit1, add_left_inj] at h,
exact bit0_injective h,
end
@[simp] lemma bit0_eq_bit0 {a b : R} : bit0 a = bit0 b ↔ a = b :=
bit0_injective.eq_iff
@[simp] lemma bit1_eq_bit1 {a b : R} : bit1 a = bit1 b ↔ a = b :=
bit1_injective.eq_iff
@[simp]
lemma bit1_eq_one {a : R} : bit1 a = 1 ↔ a = 0 :=
by rw [show (1 : R) = bit1 0, by simp, bit1_eq_bit1]
@[simp]
lemma one_eq_bit1 {a : R} : 1 = bit1 a ↔ a = 0 :=
by { rw [eq_comm], exact bit1_eq_one }
end
section
variables {R : Type*} [division_ring R] [char_zero R]
@[simp] lemma half_add_self (a : R) : (a + a) / 2 = a :=
by rw [← mul_two, mul_div_cancel a two_ne_zero']
@[simp] lemma add_halves' (a : R) : a / 2 + a / 2 = a :=
by rw [← add_div, half_add_self]
lemma sub_half (a : R) : a - a / 2 = a / 2 :=
by rw [sub_eq_iff_eq_add, add_halves']
lemma half_sub (a : R) : a / 2 - a = - (a / 2) :=
by rw [← neg_sub, sub_half]
end
namespace with_top
instance {R : Type*} [add_monoid R] [has_one R] [char_zero R] : char_zero (with_top R) :=
{ cast_injective := λ m n h, by rwa [← coe_nat, ← coe_nat n, coe_eq_coe, nat.cast_inj] at h }
end with_top
|
122f3bd567d4c3fb67ac96ec127c356648648782 | ba4794a0deca1d2aaa68914cd285d77880907b5c | /src/game/world10/level13.lean | c8e9b32247bf27cc16ad9c2caaa0c65ac1f6a2d5 | [
"Apache-2.0"
] | permissive | ChrisHughes24/natural_number_game | c7c00aa1f6a95004286fd456ed13cf6e113159ce | 9d09925424da9f6275e6cfe427c8bcf12bb0944f | refs/heads/master | 1,600,715,773,528 | 1,573,910,462,000 | 1,573,910,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 849 | lean | import game.world10.level12 -- hide
namespace mynat -- hide
/-
# Inequality world.
## Level 12: `not_succ_le_self`
Turns out that `¬ P` is *by definition* `P → false`, so you can just
start this one with `intro h` if you like.
## Pro tip:
```
conv begin
to_lhs,
rw hc,
end,
```
is an incantation which rewrites `hc` only on the left hand side of the goal.
Look carefully at the commas.
-/
/- Lemma
For all naturals $a$, $\operatorname{succ}(a)$ is not at most $a$.
-/
theorem not_succ_le_self (a : mynat) : ¬ (succ a ≤ a) :=
begin [less_leaky]
intro h,
induction a with d hd,
cases h with c hc,
rw succ_add at hc,
exact zero_ne_succ _ hc,
apply hd,
cases h with c hc,
use c,
apply succ_inj,
conv begin
to_lhs,
rw hc,
end,
rw ←succ_add,
rw ←hc,
refl,
end
end mynat -- hide
|
038196c1ca1d4ca0d27863b94267b2452222e0c6 | 5a6ff5f8d173cbfe51967eb4c96837e3a791fe3d | /mm0-lean/mm0/mm0.lean | bb62932ee46ce69e047ae9c31b49f25e85af51b5 | [
"CC0-1.0"
] | permissive | digama0/mm0 | 491ac09146708aa1bb775007bf3dbe339ffc0096 | 98496badaf6464e56ed7b4204e7d54b85667cb01 | refs/heads/master | 1,692,321,030,902 | 1,686,254,458,000 | 1,686,254,458,000 | 172,456,790 | 273 | 38 | CC0-1.0 | 1,689,939,563,000 | 1,551,080,059,000 | Rust | UTF-8 | Lean | false | false | 8,612 | lean | import data.finset
namespace mm0
structure sort_data := (pure strict provable free : bool := ff)
def sort_id := ℕ
def term_id := ℕ
def thm_id := ℕ
def var_id := ℕ
inductive binder
| bound : sort_id → binder
| reg : sort_id → finset var_id → binder
def binder.sort : binder → sort_id
| (binder.bound s) := s
| (binder.reg s _) := s
-- Lean doesn't do great with nested inductives
-- inductive sexpr
-- | var : var_id → sexpr
-- | app : term_id → list sexpr → sexpr
inductive sexpr
| var : var_id → sexpr
| term : term_id → sexpr
| app1 : sexpr → sexpr → sexpr
def sexpr.app' : sexpr → list sexpr → sexpr
| f [] := f
| f (x :: xs) := sexpr.app' (sexpr.app1 f x) xs
def sexpr.app (t : term_id) : list sexpr → sexpr :=
sexpr.app' (sexpr.term t)
def dep_type := sort_id × finset var_id
@[reducible] def ctx := list binder
inductive decl
| sort : sort_id → sort_data → decl
| term : term_id → ctx → dep_type → decl
| defn : term_id → ctx → dep_type → option (list sort_id × sexpr) → decl
| ax : ctx → list sexpr → sexpr → decl
| thm : ctx → list sexpr → sexpr → decl
@[reducible] def env := list decl
def env.get_sd (e : env) (s sd) : Prop :=
decl.sort s sd ∈ e
inductive env.get_term (e : env) (t a r) : option (list sort_id × sexpr) → Prop
| term : decl.term t a r ∈ e → env.get_term none
| defn {o} : decl.defn t a r o ∈ e → env.get_term o
def env.get_thm (e : env) (t a r) : Prop :=
decl.ax t a r ∈ e ∨ decl.thm t a r ∈ e
def env.is_sort (e : env) (s) : Prop := ∃ sd, e.get_sd s sd
def ctx.is_bound (Γ : ctx) (x) : Prop :=
∃ s, Γ.nth x = some (binder.bound s)
def dep_type.ok (e Γ) : dep_type → Prop
| ⟨s, vs⟩ := env.is_sort e s ∧ ∀ x ∈ vs, ctx.is_bound Γ x
-- Lean doesn't like induction on lists on the right, but
-- we write it this way for consistency with mm0.mm0
inductive ctx.ok (e : env) : ctx → Prop
| nil : ctx.ok []
| bound {s sd Γ} :
env.get_sd e s sd → ¬ sd.strict →
ctx.ok Γ → ctx.ok (Γ ++ [binder.bound s])
| reg {s vs Γ} : dep_type.ok e Γ (s, vs) →
ctx.ok Γ → ctx.ok (Γ ++ [binder.reg s vs])
-- Helper function to allow defining the mutual recursive functions Expr and ExprBi
def sexpr.ok_bi' (e : env) (Γ : ctx) (e : sexpr) (P : sort_id → Prop) : binder → Prop
| (binder.bound s) := ∃ v, e = sexpr.var v ∧ Γ.nth v = some (binder.bound s)
| (binder.reg s vs) := P s
-- The lean version has an extra argument because there are preterms
-- (unapplied expressions)
inductive sexpr.ok' (e : env) (Γ : ctx) : sexpr → list binder → sort_id → Prop
| var {v bi} : Γ.nth v = some bi → sexpr.ok' (sexpr.var v) [] bi.sort
| term {f bis ret o} : e.get_term f bis ret o →
sexpr.ok' (sexpr.term f) bis ret.1
| app_var {f s v bis ret} :
Γ.nth v = some (binder.bound s) →
sexpr.ok' f (binder.bound s :: bis) ret →
sexpr.ok' (sexpr.app1 f (sexpr.var v)) bis ret
| app_reg {f x s vs bis ret} :
sexpr.ok' f (binder.reg s vs :: bis) ret →
sexpr.ok' x [] s →
sexpr.ok' (sexpr.app1 f x) bis ret
def sexpr.ok (E : env) (Γ : ctx) (e : sexpr) (s : sort_id) : Prop :=
sexpr.ok' E Γ e [] s
def sexpr.ok_bi (E : env) (Γ : ctx) (e : sexpr) : binder → Prop
| (binder.bound s) := ∃ v, e = sexpr.var v ∧ Γ.nth v = some (binder.bound s)
| (binder.reg s vs) := sexpr.ok E Γ e s
def sexpr.ok_prov (E : env) (Γ : ctx) (e : sexpr) : Prop :=
∃ s sd, sexpr.ok E Γ e s ∧ E.get_sd s sd ∧ sd.provable
def append_dummies (Γ : ctx) (ds : list sort_id) : ctx :=
Γ ++ ds.map binder.bound
def sexpr.has_var (Γ : ctx) : sexpr → var_id → Prop
| (sexpr.var u) v := ∃ bi, Γ.nth u = some bi ∧
match bi with
| binder.bound s := u = v
| binder.reg s vs := v ∈ vs
end
| (sexpr.term f) v := false
| (sexpr.app1 f x) v := f.has_var v ∨ x.has_var v
def maybe_free_args (es : list sexpr) (a : binder) (v : var_id) : Prop :=
∃ s vs, a = binder.reg s vs ∧ ¬ ∃ u ∈ vs, es.nth u = some (sexpr.var v)
def sexpr.free' (E : env) (Γ : ctx) (v : var_id) :
sexpr → list sexpr → list Prop → Prop
| (sexpr.var u) _ _ := sexpr.has_var Γ (sexpr.var u) v
| (sexpr.term f) es ps := ∃ args r rs o,
E.get_term f args (r, rs) o ∧
(∃ n free a, ps.nth n = some free ∧ args.nth n = some a ∧
free ∧ maybe_free_args es a v) ∧
∃ u ∈ rs, es.nth u = some (sexpr.var v)
| (sexpr.app1 f x) es ps :=
sexpr.free' f (x :: es) (sexpr.free' x [] [] :: ps)
def sexpr.free (E : env) (Γ : ctx) (e : sexpr) (v : var_id) : Prop :=
sexpr.free' E Γ v e [] []
def term_ok (E : env) (t args ret) : Prop :=
(¬ ∃ a r v, E.get_term t a r v) ∧
ctx.ok E args ∧ dep_type.ok E args ret ∧
∃ sd, E.get_sd ret.1 sd ∧ ¬ sd.pure
def defn_ok (E : env) (t args ret ds e) : Prop :=
term_ok E t args ret ∧ let Γ := append_dummies args ds in
Γ.ok E ∧ sexpr.ok E Γ e ret.1 ∧
∀ v, sexpr.free E Γ e v → v ∈ ret.2 ∨
∃ sd s, (Γ.nth v = some (binder.bound s) ∧
E.get_sd s sd ∧ sd.free)
def axiom_ok (E : env) (args hs) (ret : sexpr) : Prop :=
ctx.ok E args ∧ ∀ x ∈ list.cons ret hs, sexpr.ok_prov E args x
def decl.ok (E : env) : decl → Prop
| (decl.sort id sd) := true
| (decl.term t args ret) := term_ok E t args ret
| (decl.defn t args ret none) := term_ok E t args ret
| (decl.defn t args ret (some (ds, e))) := defn_ok E t args ret ds e
| (decl.ax args hs ret) := axiom_ok E args hs ret
| (decl.thm args hs ret) := axiom_ok E args hs ret
inductive env.ok : env → Prop
| nil : env.ok []
| cons {E d} : env.ok E → decl.ok E d → env.ok (E ++ [d])
inductive env.extend : env → env → Prop
| nil : env.extend [] []
| keep {E1 E2 d} : env.extend E1 E2 → env.extend (E1 ++ [d]) (E2 ++ [d])
| defn_skip {E1 E2 id a r o} :
env.extend E1 E2 →
env.extend E1 (E2 ++ [decl.defn id a r o])
| defn_def {E1 E2 id a r o} :
env.extend E1 E2 →
env.extend (E2 ++ [decl.defn id a r none]) (E2 ++ [decl.defn id a r o])
| thm_skip {E1 E2 a h r} :
env.extend E1 E2 →
env.extend E1 (E2 ++ [decl.thm a h r])
instance : inhabited sexpr := ⟨sexpr.var (0:ℕ)⟩
def sexpr.subst (σ : list sexpr) : sexpr → sexpr
| (sexpr.var v) := σ.inth v
| (sexpr.term f) := sexpr.term f
| (sexpr.app1 f x) := f.subst.app1 x.subst
-- In mm0.mm0, we use a type CExpr to denote proofs and existentially
-- quantify over them to get the proof judgment. In Lean, we can do this
-- directly with an inductive proof predicate.
inductive conv' (E : env) (Γ : ctx) : sexpr → sexpr → list binder → sort_id → Prop
| refl {e args s} : sexpr.ok' E Γ e args s → conv' e e args s
| symm {e1 e2 s} : conv' e1 e2 [] s → conv' e2 e1 [] s
| cong {f1 f2 bi bis x1 x2 s} :
sexpr.ok_bi E Γ x1 bi → sexpr.ok_bi E Γ x2 bi →
conv' f1 f2 (bi :: bis) s →
conv' x1 x2 [] bi.sort →
conv' (sexpr.app1 f1 x1) (sexpr.app1 f2 x2) bis s
| unfold {t args ret ys val es zs e2 s} :
E.get_term t args ret (some (ys, val)) →
list.forall₂ (sexpr.ok_bi E Γ) es args →
list.forall₂ (λ y z, Γ.nth z = some (binder.bound y)) ys zs →
conv' (sexpr.app t es) e2 [] s →
conv' (sexpr.subst (es ++ list.map sexpr.var zs) val) e2 [] s
def conv (E : env) (Γ : ctx) (e1 e2 : sexpr) (s : sort_id) : Prop :=
conv' E Γ e1 e2 [] s
def safe_subst (Γ : ctx) (σ : list sexpr) : Prop :=
∀ u v, (∃ s, Γ.nth u = some (binder.bound s)) →
v < Γ.length → ¬ sexpr.has_var Γ (sexpr.var v) u →
∀ y e2, σ.nth u = some (sexpr.var y) → σ.nth v = some e2 →
¬ e2.has_var Γ y
-- We generalize to a possibly infinite set of hypotheses for no particular reason
inductive proof (E : env) (Γ : ctx) (Hs : set sexpr) : sexpr → Prop
| hyp {h} : h ∈ Hs → proof h
| thm {args hs ret σ} :
E.get_thm args hs ret →
list.forall₂ (sexpr.ok_bi E Γ) σ args →
safe_subst Γ σ →
(∀ h ∈ hs, proof (sexpr.subst σ h)) →
proof (sexpr.subst σ ret)
| conv {e1 e2 s} : conv E Γ e1 e2 s → proof e1 → proof e2
inductive env.proof' : env → Prop
| nil : env.proof' []
| sort {E s sd} : env.proof' E → env.proof' (E ++ [decl.sort s sd])
| term {E id a r} : env.proof' E → env.proof' (E ++ [decl.term id a r])
| defn {E id a r o} : env.proof' E → env.proof' (E ++ [decl.defn id a r (some o)])
| ax {E a h r} : env.proof' E → env.proof' (E ++ [decl.ax a h r])
| thm {E a hs r ds} :
let Γ := append_dummies a ds in
ctx.ok E Γ → proof E Γ {h | h ∈ hs} r →
env.proof' E → env.proof' (E ++ [decl.thm a hs r])
def env.proof (E : env) : Prop := ∃ E', env.extend E E' ∧ E'.proof'
end mm0 |
b5dc98ab14008c805416d3379566a3f727ee94c5 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/1292.lean | ceef3968152c01864e42e63ff0129b6b0afd72e4 | [
"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 | 402 | lean | def test : Nat :=
let inp : Array (Option Nat × Nat) := #[(some 0, 0), (none, 0)]
let fvars : Array Nat := inp.filterMap fun
| (some _, _) => none
| (none, fv) => fv
fvars.size
#eval test
def test2 : Nat :=
let inp : Array (Option Nat × Nat) := #[(some 0, 0)]
let fvars : Array Nat := inp.filterMap fun
| (some _, _) => none
| (none, fv) => fv
fvars.size
#eval test2
|
4ef976650e9907c14db29a758a36a0bbe1921239 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/analysis/calculus/specific_functions.lean | 2b22731aa29c5cacc395726431c40105fb0f00da | [
"Apache-2.0"
] | permissive | jumpy4/mathlib | d3829e75173012833e9f15ac16e481e17596de0f | af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13 | refs/heads/master | 1,693,508,842,818 | 1,636,203,271,000 | 1,636,203,271,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,946 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.iterated_deriv
import analysis.inner_product_space.euclidean_dist
/-!
# Infinitely smooth bump function
In this file we construct several infinitely smooth functions with properties that an analytic
function cannot have:
* `exp_neg_inv_glue` is equal to zero for `x ≤ 0` and is strictly positive otherwise; it is given by
`x ↦ exp (-1/x)` for `x > 0`;
* `real.smooth_transition` is equal to zero for `x ≤ 0` and is equal to one for `x ≥ 1`; it is given
by `exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x))`;
* `f : times_cont_diff_bump_of_inner c`, where `c` is a point in an inner product space, is
a bundled smooth function such that
- `f` is equal to `1` in `metric.closed_ball c f.r`;
- `support f = metric.ball c f.R`;
- `0 ≤ f x ≤ 1` for all `x`.
The structure `times_cont_diff_bump_of_inner` contains the data required to construct the
function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available
through `coe_fn`.
* `f : times_cont_diff_bump c`, where `c` is a point in a finite dimensional real vector space, is a
bundled smooth function such that
- `f` is equal to `1` in `euclidean.closed_ball c f.r`;
- `support f = euclidean.ball c f.R`;
- `0 ≤ f x ≤ 1` for all `x`.
The structure `times_cont_diff_bump` contains the data required to construct the function: real
numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`.
-/
noncomputable theory
open_locale classical topological_space
open polynomial real filter set function
/-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0`
for `x ≤ 0`. It is a basic building block to construct smooth partitions of unity. Its main property
is that it vanishes for `x ≤ 0`, it is positive for `x > 0`, and the junction between the two
behaviors is flat enough to retain smoothness. The fact that this function is `C^∞` is proved in
`exp_neg_inv_glue.smooth`. -/
def exp_neg_inv_glue (x : ℝ) : ℝ := if x ≤ 0 then 0 else exp (-x⁻¹)
namespace exp_neg_inv_glue
/-- Our goal is to prove that `exp_neg_inv_glue` is `C^∞`. For this, we compute its successive
derivatives for `x > 0`. The `n`-th derivative is of the form `P_aux n (x) exp(-1/x) / x^(2 n)`,
where `P_aux n` is computed inductively. -/
noncomputable def P_aux : ℕ → polynomial ℝ
| 0 := 1
| (n+1) := X^2 * (P_aux n).derivative + (1 - C ↑(2 * n) * X) * (P_aux n)
/-- Formula for the `n`-th derivative of `exp_neg_inv_glue`, as an auxiliary function `f_aux`. -/
def f_aux (n : ℕ) (x : ℝ) : ℝ :=
if x ≤ 0 then 0 else (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)
/-- The `0`-th auxiliary function `f_aux 0` coincides with `exp_neg_inv_glue`, by definition. -/
lemma f_aux_zero_eq : f_aux 0 = exp_neg_inv_glue :=
begin
ext x,
by_cases h : x ≤ 0,
{ simp [exp_neg_inv_glue, f_aux, h] },
{ simp [h, exp_neg_inv_glue, f_aux, ne_of_gt (not_le.1 h), P_aux] }
end
/-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n`
(given in this statement in unfolded form) is the `n+1`-th auxiliary function, since
the polynomial `P_aux (n+1)` was chosen precisely to ensure this. -/
lemma f_aux_deriv (n : ℕ) (x : ℝ) (hx : x ≠ 0) :
has_deriv_at (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n))
((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x :=
begin
have A : ∀k:ℕ, 2 * (k + 1) - 1 = 2 * k + 1,
{ assume k,
rw tsub_eq_iff_eq_add_of_le,
{ ring },
{ simpa [mul_add] using add_le_add (zero_le (2 * k)) one_le_two } },
convert (((P_aux n).has_deriv_at x).mul
(((has_deriv_at_exp _).comp x (has_deriv_at_inv hx).neg))).div
(has_deriv_at_pow (2 * n) x) (pow_ne_zero _ hx) using 1,
field_simp [hx, P_aux],
-- `ring_exp` can't solve `p ∨ q` goal generated by `mul_eq_mul_right_iff`
cases n; simp [nat.succ_eq_add_one, A, -mul_eq_mul_right_iff]; ring_exp
end
/-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n`
is the `n+1`-th auxiliary function. -/
lemma f_aux_deriv_pos (n : ℕ) (x : ℝ) (hx : 0 < x) :
has_deriv_at (f_aux n) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x :=
begin
apply (f_aux_deriv n x (ne_of_gt hx)).congr_of_eventually_eq,
filter_upwards [lt_mem_nhds hx],
assume y hy,
simp [f_aux, hy.not_le]
end
/-- To get differentiability at `0` of the auxiliary functions, we need to know that their limit
is `0`, to be able to apply general differentiability extension theorems. This limit is checked in
this lemma. -/
lemma f_aux_limit (n : ℕ) :
tendsto (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) (𝓝[Ioi 0] 0) (𝓝 0) :=
begin
have A : tendsto (λx, (P_aux n).eval x) (𝓝[Ioi 0] 0) (𝓝 ((P_aux n).eval 0)) :=
(P_aux n).continuous_within_at,
have B : tendsto (λx, exp (-x⁻¹) / x^(2 * n)) (𝓝[Ioi 0] 0) (𝓝 0),
{ convert (tendsto_pow_mul_exp_neg_at_top_nhds_0 (2 * n)).comp tendsto_inv_zero_at_top,
ext x,
field_simp },
convert A.mul B;
simp [mul_div_assoc]
end
/-- Deduce from the limiting behavior at `0` of its derivative and general differentiability
extension theorems that the auxiliary function `f_aux n` is differentiable at `0`,
with derivative `0`. -/
lemma f_aux_deriv_zero (n : ℕ) : has_deriv_at (f_aux n) 0 0 :=
begin
-- we check separately differentiability on the left and on the right
have A : has_deriv_within_at (f_aux n) (0 : ℝ) (Iic 0) 0,
{ apply (has_deriv_at_const (0 : ℝ) (0 : ℝ)).has_deriv_within_at.congr,
{ assume y hy,
simp at hy,
simp [f_aux, hy] },
{ simp [f_aux, le_refl] } },
have B : has_deriv_within_at (f_aux n) (0 : ℝ) (Ici 0) 0,
{ have diff : differentiable_on ℝ (f_aux n) (Ioi 0) :=
λx hx, (f_aux_deriv_pos n x hx).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff _ self_mem_nhds_within,
{ refine (f_aux_limit (n+1)).congr' _,
apply mem_of_superset self_mem_nhds_within (λx hx, _),
simp [(f_aux_deriv_pos n x hx).deriv] },
{ have : f_aux n 0 = 0, by simp [f_aux, le_refl],
simp only [continuous_within_at, this],
refine (f_aux_limit n).congr' _,
apply mem_of_superset self_mem_nhds_within (λx hx, _),
have : ¬(x ≤ 0), by simpa using hx,
simp [f_aux, this] } },
simpa using A.union B,
end
/-- At every point, the auxiliary function `f_aux n` has a derivative which is
equal to `f_aux (n+1)`. -/
lemma f_aux_has_deriv_at (n : ℕ) (x : ℝ) : has_deriv_at (f_aux n) (f_aux (n+1) x) x :=
begin
-- check separately the result for `x < 0`, where it is trivial, for `x > 0`, where it is done
-- in `f_aux_deriv_pos`, and for `x = 0`, done in
-- `f_aux_deriv_zero`.
rcases lt_trichotomy x 0 with hx|hx|hx,
{ have : f_aux (n+1) x = 0, by simp [f_aux, le_of_lt hx],
rw this,
apply (has_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq,
filter_upwards [gt_mem_nhds hx],
assume y hy,
simp [f_aux, hy.le] },
{ have : f_aux (n + 1) 0 = 0, by simp [f_aux, le_refl],
rw [hx, this],
exact f_aux_deriv_zero n },
{ have : f_aux (n+1) x = (P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n+1)),
by simp [f_aux, not_le_of_gt hx],
rw this,
exact f_aux_deriv_pos n x hx },
end
/-- The successive derivatives of the auxiliary function `f_aux 0` are the
functions `f_aux n`, by induction. -/
lemma f_aux_iterated_deriv (n : ℕ) : iterated_deriv n (f_aux 0) = f_aux n :=
begin
induction n with n IH,
{ simp },
{ simp [iterated_deriv_succ, IH],
ext x,
exact (f_aux_has_deriv_at n x).deriv }
end
/-- The function `exp_neg_inv_glue` is smooth. -/
protected theorem times_cont_diff {n} : times_cont_diff ℝ n exp_neg_inv_glue :=
begin
rw ← f_aux_zero_eq,
apply times_cont_diff_of_differentiable_iterated_deriv (λ m hm, _),
rw f_aux_iterated_deriv m,
exact λ x, (f_aux_has_deriv_at m x).differentiable_at
end
/-- The function `exp_neg_inv_glue` vanishes on `(-∞, 0]`. -/
lemma zero_of_nonpos {x : ℝ} (hx : x ≤ 0) : exp_neg_inv_glue x = 0 :=
by simp [exp_neg_inv_glue, hx]
/-- The function `exp_neg_inv_glue` is positive on `(0, +∞)`. -/
lemma pos_of_pos {x : ℝ} (hx : 0 < x) : 0 < exp_neg_inv_glue x :=
by simp [exp_neg_inv_glue, not_le.2 hx, exp_pos]
/-- The function exp_neg_inv_glue` is nonnegative. -/
lemma nonneg (x : ℝ) : 0 ≤ exp_neg_inv_glue x :=
begin
cases le_or_gt x 0,
{ exact ge_of_eq (zero_of_nonpos h) },
{ exact le_of_lt (pos_of_pos h) }
end
end exp_neg_inv_glue
/-- An infinitely smooth function `f : ℝ → ℝ` such that `f x = 0` for `x ≤ 0`,
`f x = 1` for `1 ≤ x`, and `0 < f x < 1` for `0 < x < 1`. -/
def real.smooth_transition (x : ℝ) : ℝ :=
exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x))
namespace real
namespace smooth_transition
variables {x : ℝ}
open exp_neg_inv_glue
lemma pos_denom (x) : 0 < exp_neg_inv_glue x + exp_neg_inv_glue (1 - x) :=
((@zero_lt_one ℝ _ _).lt_or_lt x).elim
(λ hx, add_pos_of_pos_of_nonneg (pos_of_pos hx) (nonneg _))
(λ hx, add_pos_of_nonneg_of_pos (nonneg _) (pos_of_pos $ sub_pos.2 hx))
lemma one_of_one_le (h : 1 ≤ x) : smooth_transition x = 1 :=
(div_eq_one_iff_eq $ (pos_denom x).ne').2 $ by rw [zero_of_nonpos (sub_nonpos.2 h), add_zero]
lemma zero_of_nonpos (h : x ≤ 0) : smooth_transition x = 0 :=
by rw [smooth_transition, zero_of_nonpos h, zero_div]
lemma le_one (x : ℝ) : smooth_transition x ≤ 1 :=
(div_le_one (pos_denom x)).2 $ le_add_of_nonneg_right (nonneg _)
lemma nonneg (x : ℝ) : 0 ≤ smooth_transition x :=
div_nonneg (exp_neg_inv_glue.nonneg _) (pos_denom x).le
lemma lt_one_of_lt_one (h : x < 1) : smooth_transition x < 1 :=
(div_lt_one $ pos_denom x).2 $ lt_add_of_pos_right _ $ pos_of_pos $ sub_pos.2 h
lemma pos_of_pos (h : 0 < x) : 0 < smooth_transition x :=
div_pos (exp_neg_inv_glue.pos_of_pos h) (pos_denom x)
protected lemma times_cont_diff {n} : times_cont_diff ℝ n smooth_transition :=
exp_neg_inv_glue.times_cont_diff.div
(exp_neg_inv_glue.times_cont_diff.add $ exp_neg_inv_glue.times_cont_diff.comp $
times_cont_diff_const.sub times_cont_diff_id) $
λ x, (pos_denom x).ne'
protected lemma times_cont_diff_at {x n} : times_cont_diff_at ℝ n smooth_transition x :=
smooth_transition.times_cont_diff.times_cont_diff_at
end smooth_transition
end real
variable {E : Type*}
/-- `f : times_cont_diff_bump_of_inner c`, where `c` is a point in an inner product space, is a
bundled smooth function such that
- `f` is equal to `1` in `metric.closed_ball c f.r`;
- `support f = metric.ball c f.R`;
- `0 ≤ f x ≤ 1` for all `x`.
The structure `times_cont_diff_bump_of_inner` contains the data required to construct the function:
real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through
`coe_fn`. -/
structure times_cont_diff_bump_of_inner (c : E) :=
(r R : ℝ)
(r_pos : 0 < r)
(r_lt_R : r < R)
namespace times_cont_diff_bump_of_inner
lemma R_pos {c : E} (f : times_cont_diff_bump_of_inner c) : 0 < f.R := f.r_pos.trans f.r_lt_R
instance (c : E) : inhabited (times_cont_diff_bump_of_inner c) := ⟨⟨1, 2, zero_lt_one, one_lt_two⟩⟩
variables [inner_product_space ℝ E] {c : E} (f : times_cont_diff_bump_of_inner c) {x : E}
/-- The function defined by `f : times_cont_diff_bump_of_inner c`. Use automatic coercion to
function instead. -/
def to_fun (f : times_cont_diff_bump_of_inner c) : E → ℝ :=
λ x, real.smooth_transition ((f.R - dist x c) / (f.R - f.r))
instance : has_coe_to_fun (times_cont_diff_bump_of_inner c) (λ _, E → ℝ) := ⟨to_fun⟩
open real (smooth_transition) real.smooth_transition metric
lemma one_of_mem_closed_ball (hx : x ∈ closed_ball c f.r) :
f x = 1 :=
one_of_one_le $ (one_le_div (sub_pos.2 f.r_lt_R)).2 $ sub_le_sub_left hx _
lemma nonneg : 0 ≤ f x := nonneg _
lemma le_one : f x ≤ 1 := le_one _
lemma pos_of_mem_ball (hx : x ∈ ball c f.R) : 0 < f x :=
pos_of_pos $ div_pos (sub_pos.2 hx) (sub_pos.2 f.r_lt_R)
lemma lt_one_of_lt_dist (h : f.r < dist x c) : f x < 1 :=
lt_one_of_lt_one $ (div_lt_one (sub_pos.2 f.r_lt_R)).2 $ sub_lt_sub_left h _
lemma zero_of_le_dist (hx : f.R ≤ dist x c) : f x = 0 :=
zero_of_nonpos $ div_nonpos_of_nonpos_of_nonneg (sub_nonpos.2 hx) (sub_nonneg.2 f.r_lt_R.le)
lemma support_eq : support (f : E → ℝ) = metric.ball c f.R :=
begin
ext x,
suffices : f x ≠ 0 ↔ dist x c < f.R, by simpa [mem_support],
cases lt_or_le (dist x c) f.R with hx hx,
{ simp [hx, (f.pos_of_mem_ball hx).ne'] },
{ simp [hx.not_lt, f.zero_of_le_dist hx] }
end
lemma eventually_eq_one_of_mem_ball (h : x ∈ ball c f.r) :
f =ᶠ[𝓝 x] 1 :=
((is_open_lt (continuous_id.dist continuous_const) continuous_const).eventually_mem h).mono $
λ z hz, f.one_of_mem_closed_ball (le_of_lt hz)
lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 :=
f.eventually_eq_one_of_mem_ball (mem_ball_self f.r_pos)
protected lemma times_cont_diff_at {n} :
times_cont_diff_at ℝ n f x :=
begin
rcases em (x = c) with rfl|hx,
{ refine times_cont_diff_at.congr_of_eventually_eq _ f.eventually_eq_one,
rw pi.one_def,
exact times_cont_diff_at_const },
{ exact real.smooth_transition.times_cont_diff_at.comp x
(times_cont_diff_at.div_const $ times_cont_diff_at_const.sub $
times_cont_diff_at_id.dist times_cont_diff_at_const hx) }
end
protected lemma times_cont_diff {n} :
times_cont_diff ℝ n f :=
times_cont_diff_iff_times_cont_diff_at.2 $ λ y, f.times_cont_diff_at
protected lemma times_cont_diff_within_at {s n} :
times_cont_diff_within_at ℝ n f s x :=
f.times_cont_diff_at.times_cont_diff_within_at
end times_cont_diff_bump_of_inner
/-- `f : times_cont_diff_bump c`, where `c` is a point in a finite dimensional real vector space, is
a bundled smooth function such that
- `f` is equal to `1` in `euclidean.closed_ball c f.r`;
- `support f = euclidean.ball c f.R`;
- `0 ≤ f x ≤ 1` for all `x`.
The structure `times_cont_diff_bump` contains the data required to construct the function: real
numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`.-/
structure times_cont_diff_bump [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] (c : E)
extends times_cont_diff_bump_of_inner (to_euclidean c)
namespace times_cont_diff_bump
variables [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {c x : E}
(f : times_cont_diff_bump c)
/-- The function defined by `f : times_cont_diff_bump c`. Use automatic coercion to function
instead. -/
def to_fun (f : times_cont_diff_bump c) : E → ℝ := f.to_times_cont_diff_bump_of_inner ∘ to_euclidean
instance : has_coe_to_fun (times_cont_diff_bump c) (λ _, E → ℝ) := ⟨to_fun⟩
instance (c : E) : inhabited (times_cont_diff_bump c) := ⟨⟨default _⟩⟩
lemma R_pos : 0 < f.R := f.to_times_cont_diff_bump_of_inner.R_pos
lemma coe_eq_comp : ⇑f = f.to_times_cont_diff_bump_of_inner ∘ to_euclidean := rfl
lemma one_of_mem_closed_ball (hx : x ∈ euclidean.closed_ball c f.r) :
f x = 1 :=
f.to_times_cont_diff_bump_of_inner.one_of_mem_closed_ball hx
lemma nonneg : 0 ≤ f x := f.to_times_cont_diff_bump_of_inner.nonneg
lemma le_one : f x ≤ 1 := f.to_times_cont_diff_bump_of_inner.le_one
lemma pos_of_mem_ball (hx : x ∈ euclidean.ball c f.R) : 0 < f x :=
f.to_times_cont_diff_bump_of_inner.pos_of_mem_ball hx
lemma lt_one_of_lt_dist (h : f.r < euclidean.dist x c) : f x < 1 :=
f.to_times_cont_diff_bump_of_inner.lt_one_of_lt_dist h
lemma zero_of_le_dist (hx : f.R ≤ euclidean.dist x c) : f x = 0 :=
f.to_times_cont_diff_bump_of_inner.zero_of_le_dist hx
lemma support_eq : support (f : E → ℝ) = euclidean.ball c f.R :=
by rw [euclidean.ball_eq_preimage, ← f.to_times_cont_diff_bump_of_inner.support_eq,
← support_comp_eq_preimage, coe_eq_comp]
lemma closure_support_eq : closure (support f) = euclidean.closed_ball c f.R :=
by rw [f.support_eq, euclidean.closure_ball _ f.R_pos]
lemma compact_closure_support : is_compact (closure (support f)) :=
by { rw f.closure_support_eq, exact euclidean.is_compact_closed_ball }
lemma eventually_eq_one_of_mem_ball (h : x ∈ euclidean.ball c f.r) :
f =ᶠ[𝓝 x] 1 :=
to_euclidean.continuous_at (f.to_times_cont_diff_bump_of_inner.eventually_eq_one_of_mem_ball h)
lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 :=
f.eventually_eq_one_of_mem_ball $ euclidean.mem_ball_self f.r_pos
protected lemma times_cont_diff {n} :
times_cont_diff ℝ n f :=
f.to_times_cont_diff_bump_of_inner.times_cont_diff.comp (to_euclidean : E ≃L[ℝ] _).times_cont_diff
protected lemma times_cont_diff_at {n} :
times_cont_diff_at ℝ n f x :=
f.times_cont_diff.times_cont_diff_at
protected lemma times_cont_diff_within_at {s n} :
times_cont_diff_within_at ℝ n f s x :=
f.times_cont_diff_at.times_cont_diff_within_at
lemma exists_closure_support_subset {s : set E} (hs : s ∈ 𝓝 c) :
∃ f : times_cont_diff_bump c, closure (support f) ⊆ s :=
let ⟨R, h0, hR⟩ := euclidean.nhds_basis_closed_ball.mem_iff.1 hs
in ⟨⟨⟨R / 2, R, half_pos h0, half_lt_self h0⟩⟩, by rwa closure_support_eq⟩
lemma exists_closure_subset {R : ℝ} (hR : 0 < R)
{s : set E} (hs : is_closed s) (hsR : s ⊆ euclidean.ball c R) :
∃ f : times_cont_diff_bump c, f.R = R ∧ s ⊆ euclidean.ball c f.r :=
begin
rcases euclidean.exists_pos_lt_subset_ball hR hs hsR with ⟨r, hr, hsr⟩,
exact ⟨⟨⟨r, R, hr.1, hr.2⟩⟩, rfl, hsr⟩
end
end times_cont_diff_bump
open finite_dimensional metric
/-- If `E` is a finite dimensional normed space over `ℝ`, then for any point `x : E` and its
neighborhood `s` there exists an infinitely smooth function with the following properties:
* `f y = 1` in a neighborhood of `x`;
* `f y = 0` outside of `s`;
* moreover, `closure (support f) ⊆ s` and `closure (support f)` is a compact set;
* `f y ∈ [0, 1]` for all `y`.
This lemma is a simple wrapper around lemmas about bundled smooth bump functions, see
`times_cont_diff_bump`. -/
lemma exists_times_cont_diff_bump_function_of_mem_nhds [normed_group E] [normed_space ℝ E]
[finite_dimensional ℝ E] {x : E} {s : set E} (hs : s ∈ 𝓝 x) :
∃ f : E → ℝ, f =ᶠ[𝓝 x] 1 ∧ (∀ y, f y ∈ Icc (0 : ℝ) 1) ∧ times_cont_diff ℝ ⊤ f ∧
is_compact (closure $ support f) ∧ closure (support f) ⊆ s :=
let ⟨f, hf⟩ := times_cont_diff_bump.exists_closure_support_subset hs in
⟨f, f.eventually_eq_one, λ y, ⟨f.nonneg, f.le_one⟩, f.times_cont_diff,
f.compact_closure_support, hf⟩
|
f2fdbe647f542ee1c4de5de1a79ac4c75af54a95 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/core.lean | 029427c258285abe3e39487de1386c29802aaf15 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,401 | 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.groupoid
import Mathlib.control.equiv_functor
import Mathlib.category_theory.types
import Mathlib.PostPort
universes u₁ v₁ u₂ v₂
namespace Mathlib
namespace category_theory
/-- The core of a category C is the groupoid whose morphisms are all the
isomorphisms of C. -/
def core (C : Type u₁) :=
C
protected instance core_category {C : Type u₁} [category C] : groupoid (core C) :=
groupoid.mk fun (X Y : core C) (f : X ⟶ Y) => iso.symm f
namespace core
@[simp] theorem id_hom {C : Type u₁} [category C] (X : core C) : iso.hom 𝟙 = 𝟙 :=
rfl
@[simp] theorem comp_hom {C : Type u₁} [category C] {X : core C} {Y : core C} {Z : core C} (f : X ⟶ Y) (g : Y ⟶ Z) : iso.hom (f ≫ g) = iso.hom f ≫ iso.hom g :=
rfl
/-- The core of a category is naturally included in the category. -/
def inclusion {C : Type u₁} [category C] : core C ⥤ C :=
functor.mk id fun (X Y : core C) (f : X ⟶ Y) => iso.hom f
/-- A functor from a groupoid to a category C factors through the core of C. -/
-- Note that this function is not functorial
-- (consider the two functors from [0] to [1], and the natural transformation between them).
def functor_to_core {C : Type u₁} [category C] {G : Type u₂} [groupoid G] (F : G ⥤ C) : G ⥤ core C :=
functor.mk (fun (X : G) => functor.obj F X)
fun (X Y : G) (f : X ⟶ Y) => iso.mk (functor.map F f) (functor.map F (inv f))
/--
We can functorially associate to any functor from a groupoid to the core of a category `C`,
a functor from the groupoid to `C`, simply by composing with the embedding `core C ⥤ C`.
-/
end core
def core.forget_functor_to_core {C : Type u₁} [category C] {G : Type u₂} [groupoid G] : (G ⥤ core C) ⥤ G ⥤ C :=
functor.obj (whiskering_right G (core C) C) core.inclusion
/--
`of_equiv_functor m` lifts a type-level `equiv_functor`
to a categorical functor `core (Type u₁) ⥤ core (Type u₂)`.
-/
def of_equiv_functor (m : Type u₁ → Type u₂) [equiv_functor m] : core (Type u₁) ⥤ core (Type u₂) :=
functor.mk m fun (α β : core (Type u₁)) (f : α ⟶ β) => equiv.to_iso (equiv_functor.map_equiv m (iso.to_equiv f))
|
54dc22ef1083c5b9641ec7408c4c4d06d25eece2 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/simp_result.lean | 7b79019f31d85a0852271a8ca28ffafa5bc28aab | [
"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 | 5,499 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Scott Morrison
-/
import tactic.core
/-!
# simp_result
`dsimp_result` and `simp_result` are a pair of tactics for
applying `dsimp` or `simp` to the result produced by other tactics.
As examples, tactics which use `revert` and `intro`
may insert additional `id` terms in the result they produce.
If there is some reason these are undesirable
(e.g. the result term needs to be human-readable, or
satisfying syntactic rather than just definitional properties),
wrapping those tactics in `dsimp_result`
can remove the `id` terms "after the fact".
Similarly, tactics using `subst` and `rw` will nearly always introduce `eq.rec` terms,
but sometimes these will be easy to remove,
for example by simplifying using `eq_rec_constant`.
This is a non-definitional simplification lemma,
and so wrapping these tactics in `simp_result` will result
in a definitionally different result.
There are several examples in the associated test file,
demonstrating these interactions with `revert` and `subst`.
These tactics should be used with some caution.
You should consider whether there is any real need for the simplification of the result,
and whether there is a more direct way of producing the result you wanted,
before relying on these tactics.
Both are implemented in terms of a generic `intercept_result` tactic,
which allows you to run an arbitrary tactic and modify the returned results.
-/
namespace tactic
/--
`intercept_result m t`
attempts to run a tactic `t`,
intercepts any results `t` assigns to the goals,
and runs `m : expr → tactic expr` on each of the expressions
before assigning the returned values to the original goals.
Because `intercept_result` uses `unsafe.type_context.assign` rather than `unify`,
if the tactic `m` does something unreasonable
you may produce terms that don't typecheck,
possibly with mysterious error messages.
Be careful!
-/
meta def intercept_result {α} (m : expr → tactic expr) (t : tactic α) : tactic α := do
-- Replace the goals with copies.
gs ← get_goals,
gs' ← gs.mmap (λ g, infer_type g >>= mk_meta_var),
set_goals gs',
-- Run the tactic on the copied goals.
a ← t,
-- Run `m` on the produced terms,
(gs.zip gs').mmap (λ ⟨g, g'⟩, do
g' ← instantiate_mvars g',
g'' ← with_local_goals' gs $ m g',
-- and assign to the original goals.
-- (We have to use `assign` here, as `unify` and `exact` are apparently
-- unreliable about which way they do the assignment!)
unsafe.type_context.run $ unsafe.type_context.assign g g''),
pure a
/--
`dsimp_result t`
attempts to run a tactic `t`,
intercepts any results it assigns to the goals,
and runs `dsimp` on those results
before assigning the simplified values to the original goals.
-/
meta def dsimp_result {α} (t : tactic α)
(cfg : dsimp_config := { fail_if_unchanged := ff }) (no_defaults := ff)
(attr_names : list name := []) (hs : list simp_arg_type := []) : tactic α :=
intercept_result (λ g,
g.dsimp cfg no_defaults attr_names hs) t
/--
`simp_result t`
attempts to run a tactic `t`,
intercepts any results `t` assigns to the goals,
and runs `simp` on those results
before assigning the simplified values to the original goals.
-/
meta def simp_result {α} (t : tactic α)
(cfg : simp_config := { fail_if_unchanged := ff }) (discharger : tactic unit := failed)
(no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic α :=
intercept_result (λ g, prod.fst <$>
g.simp cfg discharger no_defaults attr_names hs) t
namespace interactive
setup_tactic_parser
/--
`dsimp_result { tac }`
attempts to run a tactic block `tac`,
intercepts any results the tactic block would have assigned to the goals,
and runs `dsimp` on those results
before assigning the simplified values to the original goals.
You can use the usual interactive syntax for `dsimp`, e.g.
`dsimp_result only [a, b, c] with attr { tac }`.
-/
meta def dsimp_result
(no_defaults : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list)
(t : itactic) : itactic :=
tactic.dsimp_result t { fail_if_unchanged := ff } no_defaults attr_names hs
/--
`simp_result { tac }`
attempts to run a tactic block `tac`,
intercepts any results the tactic block would have assigned to the goals,
and runs `simp` on those results
before assigning the simplified values to the original goals.
You can use the usual interactive syntax for `simp`, e.g.
`simp_result only [a, b, c] with attr { tac }`.
-/
meta def simp_result
(no_defaults : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list)
(t : itactic) : itactic :=
tactic.simp_result t { fail_if_unchanged := ff } failed no_defaults attr_names hs
/--
`simp_result { tac }`
attempts to run a tactic block `tac`,
intercepts any results the tactic block would have assigned to the goals,
and runs `simp` on those results
before assigning the simplified values to the original goals.
You can use the usual interactive syntax for `simp`, e.g.
`simp_result only [a, b, c] with attr { tac }`.
`dsimp_result { tac }` works similarly, internally using `dsimp`
(and so only simplifiying along definitional lemmas).
-/
add_tactic_doc
{ name := "simp_result",
category := doc_category.tactic,
decl_names := [``simp_result, ``dsimp_result],
tags := ["simplification"] }
end interactive
end tactic
|
2c942ce9bb602ba4525e2956d31f663b63b2c9e3 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/sites/sheaf_of_types.lean | 1161cc8c4380c27b6a678862ad5bfef725db8fc4 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 40,804 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.sites.pretopology
import category_theory.limits.shapes.types
import category_theory.full_subcategory
/-!
# Sheaves of types on a Grothendieck topology
Defines the notion of a sheaf of types (usually called a sheaf of sets by mathematicians)
on a category equipped with a Grothendieck topology, as well as a range of equivalent
conditions useful in different situations.
First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular
presieve `R` on `X`:
* A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in
`R`. See `family_of_elements`.
* The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`,
and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of
`x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`.
See `family_of_elements.compatible`.
* An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in
`R`, the restriction of `t` on `f` is `x_f`.
See `family_of_elements.is_amalgamation`.
We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation,
and it is a *sheaf* for `R` if every compatible family has a unique amalgamation.
See `is_separated_for` and `is_sheaf_for`.
In the special case where `R` is a sieve, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of
`x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`).
See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`.
In the special case where `C` has pullbacks, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`,
the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g`
along `π₂ : pullback f g ⟶ Z`.
See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`.
Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the
topology. See `is_sheaf`.
In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for
every presieve in the pretopology. See `is_sheaf_pretopology`.
We also provide equivalent conditions to satisfy alternate definitions given in the literature.
* Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be
equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with
`is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.)
The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the
statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries
the same information as the unique existence.)
* Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf`
are equivalent. There are also alternate definitions given:
- Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in
`yoneda_condition_iff_sheaf_condition`.
- Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence
in `equalizer.sieve.sheaf_condition`.
- Matching family for presieves with pullback: `pullback_compatible_iff`.
- Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous.
- Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition`
combined with the previous.
## Implementation
The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u₁ v)`.
This doesn't seem to make a big difference, other than making a couple of definitions noncomputable,
but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements,
which can be convenient.
## References
* [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk:
Chapter III, Section 4.
* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1.
* https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site)
* https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology)
-/
universes w v₁ v₂ u₁ u₂
namespace category_theory
open opposite category_theory category limits sieve
namespace presieve
variables {C : Type u₁} [category.{v₁} C]
variables {P Q U : Cᵒᵖ ⥤ Type w}
variables {X Y : C} {S : sieve X} {R : presieve X}
variables (J J₂ : grothendieck_topology C)
/--
A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X`
consists of an element of `P Y` for every `f : Y ⟶ X` in `R`.
A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one
(resp, at most one) amalgamation.
This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete
version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is
more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant].
-/
def family_of_elements (P : Cᵒᵖ ⥤ Type w) (R : presieve X) :=
Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y)
instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩
/--
A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve
`R₁`.
-/
def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) :
family_of_elements P R₂ → family_of_elements P R₁ :=
λ x Y f hf, x f (h _ hf)
/--
A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and
`f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂`
commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and
restricting the element of `P Y₂` along `g₂` are the same.
In special cases, this condition can be simplified, see `pullback_compatible_iff` and
`compatible_iff_sieve_compatible`.
This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab:
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents
-/
def family_of_elements.compatible (x : family_of_elements P R) : Prop :=
∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄
(h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂)
/--
If the category `C` has pullbacks, this is an alternative condition for a family of elements to be
compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the
given elements for `f` and `g` to the pullback agree.
This is equivalent to being compatible (provided `C` has pullbacks), shown in
`pullback_compatible_iff`.
This is the definition for a "matching" family given in [MM92], Chapter III, Section 4,
Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in
https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`,
using the notation defined there.
-/
def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop :=
∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂),
P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂)
lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] :
x.compatible ↔ x.pullback_compatible :=
begin
split,
{ intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂,
apply t,
apply pullback.condition },
{ intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm,
rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂,
←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] }
end
/-- The restriction of a compatible family is compatible. -/
lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
{x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible :=
λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm
/--
Extend a family of elements to the sieve generated by an arrow set.
This is the construction described as "easy" in Lemma C2.1.3 of [Elephant].
-/
noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) :
family_of_elements P (generate R) :=
λ Z f hf, P.map hf.some_spec.some.op (x _ hf.some_spec.some_spec.some_spec.1)
/-- The extension of a compatible family to the generated sieve is compatible. -/
lemma family_of_elements.compatible.sieve_extend {x : family_of_elements P R} (hx : x.compatible) :
x.sieve_extend.compatible :=
begin
intros _ _ _ _ _ _ _ h₁ h₂ comm,
iterate 2 { erw ← functor_to_types.map_comp_apply, rw ← op_comp }, apply hx,
simp [comm, h₁.some_spec.some_spec.some_spec.2, h₂.some_spec.some_spec.some_spec.2],
end
/-- The extension of a family agrees with the original family. -/
lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) :
x.sieve_extend f (le_generate R Y hf) = x f hf :=
begin
have h := (le_generate R Y hf).some_spec,
unfold family_of_elements.sieve_extend,
rw t h.some (𝟙 _) _ hf _,
{ simp }, { rw id_comp, exact h.some_spec.some_spec.2 },
end
/-- The restriction of an extension is the original. -/
@[simp]
lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) :
x.sieve_extend.restrict (le_generate R) = x :=
begin
ext Y f hf,
exact extend_agrees t hf,
end
/--
If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the
consistency condition can be simplified.
This is an equivalent condition, see `compatible_iff_sieve_compatible`.
This is the notion of "matching" given for families on sieves given in [MM92], Chapter III,
Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family.
See also the discussion before Lemma C2.1.4 of [Elephant].
-/
def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop :=
∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf)
lemma compatible_iff_sieve_compatible (x : family_of_elements P S) :
x.compatible ↔ x.sieve_compatible :=
begin
split,
{ intros h Y Z f g hf,
simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) },
{ intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k,
simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] }
end
lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S}
(t : x.compatible) : x.sieve_compatible :=
(compatible_iff_sieve_compatible x).1 t
/--
Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted
to `R` and then extended back up to `S`, the resulting extension equals `x`.
-/
@[simp]
lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) :
(x.restrict (le_generate R)).sieve_extend = x :=
begin
rw compatible_iff_sieve_compatible at t,
ext _ _ h, apply (t _ _ _).symm.trans, congr,
exact h.some_spec.some_spec.some_spec.2,
end
/--
Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are
equal when restricted to `R`.
-/
lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)}
(t₁ : x₁.compatible) (t₂ : x₂.compatible) :
x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ :=
λ h, by { rw [←extend_restrict t₁, ←extend_restrict t₂], congr, exact h }
/-- Compatible families of elements for a presheaf of types `P` and a presieve `R`
are in 1-1 correspondence with compatible families for the same presheaf and
the sieve generated by `R`, through extension and restriction. -/
@[simps] noncomputable def compatible_equiv_generate_sieve_compatible :
{x : family_of_elements P R // x.compatible} ≃
{x : family_of_elements P (generate R) // x.compatible} :=
{ to_fun := λ x, ⟨x.1.sieve_extend, x.2.sieve_extend⟩,
inv_fun := λ x, ⟨x.1.restrict (le_generate R), x.2.restrict _⟩,
left_inv := λ x, subtype.ext (restrict_extend x.2),
right_inv := λ x, subtype.ext (extend_restrict x.2) }
lemma family_of_elements.comp_of_compatible (S : sieve X) {x : family_of_elements P S}
(t : x.compatible) {f : Y ⟶ X} (hf : S f) {Z} (g : Z ⟶ Y) :
x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf) :=
by simpa using t (𝟙 _) g (S.downward_closed hf g) hf (id_comp _)
section functor_pullback
variables {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {Z : D}
variables {T : presieve (F.obj Z)} {x : family_of_elements P T}
/--
Given a family of elements of a sieve `S` on `F(X)`, we can realize it as a family of elements of
`S.functor_pullback F`.
-/
def family_of_elements.functor_pullback (x : family_of_elements P T) :
family_of_elements (F.op ⋙ P) (T.functor_pullback F) := λ Y f hf, x (F.map f) hf
lemma family_of_elements.compatible.functor_pullback (h : x.compatible) :
(x.functor_pullback F).compatible :=
begin
intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq,
exact h (F.map g₁) (F.map g₂) h₁ h₂ (by simp only [← F.map_comp, eq])
end
end functor_pullback
/--
Given a family of elements of a sieve `S` on `X` whose values factors through `F`, we can
realize it as a family of elements of `S.functor_pushforward F`. Since the preimage is obtained by
choice, this is not well-defined generally.
-/
noncomputable
def family_of_elements.functor_pushforward {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {X : D}
{T : presieve X} (x : family_of_elements (F.op ⋙ P) T) :
family_of_elements P (T.functor_pushforward F) := λ Y f h,
by { obtain ⟨Z, g, h, h₁, _⟩ := get_functor_pushforward_structure h, exact P.map h.op (x g h₁) }
section pullback
/--
Given a family of elements of a sieve `S` on `X`, and a map `Y ⟶ X`, we can obtain a
family of elements of `S.pullback f` by taking the same elements.
-/
def family_of_elements.pullback (f : Y ⟶ X) (x : family_of_elements P S) :
family_of_elements P (S.pullback f) := λ _ g hg, x (g ≫ f) hg
lemma family_of_elements.compatible.pullback (f : Y ⟶ X) {x : family_of_elements P S}
(h : x.compatible) : (x.pullback f).compatible :=
begin
simp only [compatible_iff_sieve_compatible] at h ⊢,
intros W Z f₁ f₂ hf,
unfold family_of_elements.pullback,
rw ← (h (f₁ ≫ f) f₂ hf),
simp only [assoc],
end
end pullback
/--
Given a morphism of presheaves `f : P ⟶ Q`, we can take a family of elements valued in `P` to a
family of elements valued in `Q` by composing with `f`.
-/
def family_of_elements.comp_presheaf_map (f : P ⟶ Q) (x : family_of_elements P R) :
family_of_elements Q R := λ Y g hg, f.app (op Y) (x g hg)
@[simp]
lemma family_of_elements.comp_presheaf_map_id (x : family_of_elements P R) :
x.comp_presheaf_map (𝟙 P) = x := rfl
@[simp]
lemma family_of_elements.comp_prersheaf_map_comp (x : family_of_elements P R)
(f : P ⟶ Q) (g : Q ⟶ U) :
(x.comp_presheaf_map f).comp_presheaf_map g = x.comp_presheaf_map (f ≫ g) := rfl
lemma family_of_elements.compatible.comp_presheaf_map (f : P ⟶ Q) {x : family_of_elements P R}
(h : x.compatible) : (x.comp_presheaf_map f).compatible :=
begin
intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq,
unfold family_of_elements.comp_presheaf_map,
rwa [← functor_to_types.naturality, ← functor_to_types.naturality, h],
end
/--
The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every
restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`.
This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents,
and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4,
equation (2).
-/
def family_of_elements.is_amalgamation (x : family_of_elements P R)
(t : P.obj (op X)) : Prop :=
∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h
lemma family_of_elements.is_amalgamation.comp_presheaf_map
{x : family_of_elements P R} {t} (f : P ⟶ Q) (h : x.is_amalgamation t) :
(x.comp_presheaf_map f).is_amalgamation (f.app (op X) t) :=
begin
intros Y g hg,
dsimp [family_of_elements.comp_presheaf_map],
change (f.app _ ≫ Q.map _) _ = _,
simp [← f.naturality, h g hg],
end
lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R)
(h : ∃ t, x.is_amalgamation t) : x.compatible :=
begin
cases h with t ht,
intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm,
rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm],
simp,
end
lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
(x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
(x.restrict h).is_amalgamation t :=
λ Y f hf, ht f (h Y hf)
lemma is_amalgamation_sieve_extend {R : presieve X}
(x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
x.sieve_extend.is_amalgamation t :=
begin
intros Y f hf,
dsimp [family_of_elements.sieve_extend],
rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, hf.some_spec.some_spec.some_spec.2],
end
/-- A presheaf is separated for a presieve if there is at most one amalgamation. -/
def is_separated_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R) (t₁ t₂),
x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂
lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R)
{t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) :
t₁ = t₂ :=
hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl)
lemma is_separated_for_iff_generate :
is_separated_for P R ↔ is_separated_for P (generate R) :=
begin
split,
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.restrict (le_generate R)) t₁ t₂ _ _,
{ exact is_amalgamation_restrict _ x t₁ ht₁ },
{ exact is_amalgamation_restrict _ x t₂ ht₂ } },
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.sieve_extend),
{ exact is_amalgamation_sieve_extend x t₁ ht₁ },
{ exact is_amalgamation_sieve_extend x t₂ ht₂ } }
end
lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type w) : is_separated_for P (⊤ : presieve X) :=
λ x t₁ t₂ h₁ h₂,
begin
have q₁ := h₁ (𝟙 X) (by simp),
have q₂ := h₂ (𝟙 X) (by simp),
simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂,
rw [q₁, q₂],
end
/--
We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique
amalgamation.
This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents.
Using `compatible_iff_sieve_compatible`,
this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4.
-/
def is_sheaf_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t
/--
This is an equivalent condition to be a sheaf, which is useful for the abstraction to local
operators on elementary toposes. However this definition is defined only for sieves, not presieves.
The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`.
This version is also useful to establish that being a sheaf is preserved under isomorphism of
presheaves.
See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of
[Elephant]. This is also a direct reformulation of <https://stacks.math.columbia.edu/tag/00Z8>.
-/
def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v₁) (S : sieve X) : Prop :=
∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f
-- TODO: We can generalize the universe parameter v₁ above by composing with
-- appropriate `ulift_functor`s.
/--
(Implementation). This is a (primarily internal) equivalence between natural transformations
and compatible families.
Cf the discussion after Lemma 7.47.10 in <https://stacks.math.columbia.edu/tag/00YW>. See also
the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4.
-/
def nat_trans_equiv_compatible_family {P : Cᵒᵖ ⥤ Type v₁} :
(S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} :=
{ to_fun := λ α,
begin
refine ⟨λ Y f hf, _, _⟩,
{ apply α.app (op Y) ⟨_, hf⟩ },
{ rw compatible_iff_sieve_compatible,
intros Y Z f g hf,
dsimp,
rw ← functor_to_types.naturality _ _ α g.op,
refl }
end,
inv_fun := λ t,
{ app := λ Y f, t.1 _ f.2,
naturality' := λ Y Z g,
begin
ext ⟨f, hf⟩,
apply t.2.to_sieve_compatible _,
end },
left_inv := λ α,
begin
ext X ⟨_, _⟩,
refl
end,
right_inv :=
begin
rintro ⟨x, hx⟩,
refl,
end }
/-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/
lemma extension_iff_amalgamation {P : Cᵒᵖ ⥤ Type v₁} (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) :
S.functor_inclusion ≫ g = x ↔
(nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) :=
begin
change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩,
split,
{ rintro rfl Y f hf,
rw yoneda_equiv_naturality,
dsimp,
simp }, -- See note [dsimp, simp].
{ intro h,
ext Y ⟨f, hf⟩,
have : _ = x.app Y _ := h f hf,
rw yoneda_equiv_naturality at this,
rw ← this,
dsimp,
simp }, -- See note [dsimp, simp].
end
/--
The yoneda version of the sheaf condition is equivalent to the sheaf condition.
C2.1.4 of [Elephant].
-/
lemma is_sheaf_for_iff_yoneda_sheaf_condition {P : Cᵒᵖ ⥤ Type v₁} :
is_sheaf_for P S ↔ yoneda_sheaf_condition P S :=
begin
rw [is_sheaf_for, yoneda_sheaf_condition],
simp_rw [extension_iff_amalgamation],
rw equiv.forall_congr_left' nat_trans_equiv_compatible_family,
rw subtype.forall,
apply ball_congr,
intros x hx,
rw equiv.exists_unique_congr_left _,
simp,
end
/--
If `P` is a sheaf for the sieve `S` on `X`, a natural transformation from `S` (viewed as a functor)
to `P` can be (uniquely) extended to all of `yoneda.obj X`.
f
S → P
↓ ↗
yX
-/
noncomputable def is_sheaf_for.extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S)
(f : S.functor ⟶ P) : yoneda.obj X ⟶ P :=
(is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists.some
/--
Show that the extension of `f : S.functor ⟶ P` to all of `yoneda.obj X` is in fact an extension, ie
that the triangle below commutes, provided `P` is a sheaf for `S`
f
S → P
↓ ↗
yX
-/
@[simp, reassoc]
lemma is_sheaf_for.functor_inclusion_comp_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S)
(f : S.functor ⟶ P) : S.functor_inclusion ≫ h.extend f = f :=
(is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists.some_spec
/-- The extension of `f` to `yoneda.obj X` is unique. -/
lemma is_sheaf_for.unique_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) {f : S.functor ⟶ P}
(t : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t = f) :
t = h.extend f :=
((is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).unique ht (h.functor_inclusion_comp_extend f))
/--
If `P` is a sheaf for the sieve `S` on `X`, then if two natural transformations from `yoneda.obj X`
to `P` agree when restricted to the subfunctor given by `S`, they are equal.
-/
lemma is_sheaf_for.hom_ext {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (t₁ t₂ : yoneda.obj X ⟶ P)
(ht : S.functor_inclusion ≫ t₁ = S.functor_inclusion ≫ t₂) :
t₁ = t₂ :=
(h.unique_extend t₁ ht).trans (h.unique_extend t₂ rfl).symm
/-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/
lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for :
is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔
is_sheaf_for P R :=
begin
rw [is_separated_for, ←forall_and_distrib],
apply forall_congr,
intro x,
split,
{ intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 },
{ intros h,
refine ⟨_, (exists_of_exists_unique ∘ h)⟩,
intros t₁ t₂ ht₁ ht₂,
apply (h _).unique ht₁ ht₂,
exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ }
end
/--
If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`.
-/
lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) :
(∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) →
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
exact and.intro t,
end
/-- If `P` is a sheaf for `R`, it is separated for `R`. -/
lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R :=
λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1
/-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/
noncomputable def is_sheaf_for.amalgamate
(t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) :
P.obj (op X) :=
(t x hx).exists.some
lemma is_sheaf_for.is_amalgamation
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) :
x.is_amalgamation (t.amalgamate x hx) :=
(t x hx).exists.some_spec
@[simp]
lemma is_sheaf_for.valid_glue
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) :
P.map f.op (t.amalgamate x hx) = x f Hf :=
t.is_amalgamation hx f Hf
/-- C2.1.3 in [Elephant] -/
lemma is_sheaf_for_iff_generate (R : presieve X) :
is_sheaf_for P R ↔ is_sheaf_for P (generate R) :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_iff_generate,
apply and_congr (iff.refl _),
split,
{ intros q x hx,
apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))),
intros t ht,
simpa [hx] using is_amalgamation_sieve_extend _ _ ht },
{ intros q x hx,
apply exists_imp_exists _ (q _ hx.sieve_extend),
intros t ht,
simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht },
end
/--
Every presheaf is a sheaf for the family {𝟙 X}.
[Elephant] C2.1.5(i)
-/
lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type w) :
is_sheaf_for P (presieve.singleton (𝟙 X)) :=
begin
intros x hx,
refine ⟨x _ (presieve.singleton_self _), _, _⟩,
{ rintro _ _ ⟨rfl, rfl⟩,
simp },
{ intros t ht,
simpa using ht _ (presieve.singleton_self _) }
end
/--
Every presheaf is a sheaf for the maximal sieve.
[Elephant] C2.1.5(ii)
-/
lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type w) :
is_sheaf_for P ((⊤ : sieve X) : presieve X) :=
begin
rw ← generate_of_singleton_split_epi (𝟙 X),
rw ← is_sheaf_for_iff_generate,
apply is_sheaf_for_singleton_iso,
end
/--
If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that
"being a sheaf for a presieve" is a mathematical or hygenic property.
-/
lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R :=
begin
intros h x hx,
let x' := x.comp_presheaf_map i.inv,
have : x'.compatible := family_of_elements.compatible.comp_presheaf_map i.inv hx,
obtain ⟨t, ht1, ht2⟩ := h x' this,
use i.hom.app _ t,
fsplit,
{ convert family_of_elements.is_amalgamation.comp_presheaf_map i.hom ht1,
dsimp [x'],
simp },
{ intros y hy,
rw (show y = (i.inv.app (op X) ≫ i.hom.app (op X)) y, by simp),
simp [ ht2 (i.inv.app _ y) (family_of_elements.is_amalgamation.comp_presheaf_map i.inv hy)] }
end
/--
If a presieve `R` on `X` has a subsieve `S` such that:
* `P` is a sheaf for `S`.
* For every `f` in `R`, `P` is separated for the pullback of `S` along `f`,
then `P` is a sheaf for `R`.
This is closely related to [Elephant] C2.1.6(i).
-/
lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(hS : is_sheaf_for P S)
(trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) :
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
split,
{ intros x t₁ t₂ ht₁ ht₂,
exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁)
(is_amalgamation_restrict h x t₂ ht₂) },
{ intros x hx,
use hS.amalgamate _ (hx.restrict h),
intros W j hj,
apply (trans hj).ext,
intros Y f hf,
rw [←functor_to_types.map_comp_apply, ←op_comp,
hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict,
←hx (𝟙 _) f _ _ (id_comp _)],
simp },
end
/--
If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which
contains `S`.
This is closely related to [Elephant] C2.1.6.
-/
lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) :
is_sheaf_for P R :=
is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for)
/-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/
def is_separated (P : Cᵒᵖ ⥤ Type w) : Prop :=
∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S
/--
A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology.
If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to
check the sheaf condition at presieves in the pretopology.
-/
def is_sheaf (P : Cᵒᵖ ⥤ Type w) : Prop :=
∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S
lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type w} (hp : is_sheaf J P)
(R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R :=
(is_sheaf_for_iff_generate R).2 $ hp _ hr
lemma is_sheaf_of_le (P : Cᵒᵖ ⥤ Type w) {J₁ J₂ : grothendieck_topology C} :
J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P :=
λ h t X S hS, t S (h _ hS)
lemma is_separated_of_is_sheaf (P : Cᵒᵖ ⥤ Type w) (h : is_sheaf J P) : is_separated J P :=
λ X S hS, (h S hS).is_separated_for
/-- The property of being a sheaf is preserved by isomorphism. -/
lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' :=
λ X S hS, is_sheaf_for_iso i (h S hS)
lemma is_sheaf_of_yoneda {P : Cᵒᵖ ⥤ Type v₁}
(h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) : is_sheaf J P :=
λ X S hS, is_sheaf_for_iff_yoneda_sheaf_condition.2 (h _ hS)
/--
For a topology generated by a basis, it suffices to check the sheaf condition on the basis
presieves only.
-/
lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) :
is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) :=
begin
split,
{ intros PJ X R hR,
rw is_sheaf_for_iff_generate,
apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ },
{ rintro PK X S ⟨R, hR, RS⟩,
have gRS : ⇑(generate R) ≤ S,
{ apply gi_generate.gc.monotone_u,
rwa sets_iff_generate },
apply is_sheaf_for_subsieve P gRS _,
intros Y f,
rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate],
exact PK (pullback_arrows f R) (K.pullbacks f R hR) }
end
/-- Any presheaf is a sheaf for the bottom (trivial) grothendieck topology. -/
lemma is_sheaf_bot : is_sheaf (⊥ : grothendieck_topology C) P :=
λ X, by simp [is_sheaf_for_top_sieve]
end presieve
namespace equalizer
variables {C : Type u₁} [category.{v₁} C] (P : Cᵒᵖ ⥤ Type (max v₁ u₁))
{X : C} (R : presieve X) (S : sieve X)
noncomputable theory
/--
The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of <https://stacks.math.columbia.edu/tag/00VM>.
-/
def first_obj : Type (max v₁ u₁) :=
∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1))
/-- Show that `first_obj` is isomorphic to `family_of_elements`. -/
@[simps]
def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P :=
{ hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t,
inv := pi.lift (λ f x, x _ f.2.2),
hom_inv_id' :=
begin
ext ⟨Y, f, hf⟩ p,
simpa,
end,
inv_hom_id' :=
begin
ext x Y f hf,
apply limits.types.limit.lift_π_apply',
end }
instance : inhabited (first_obj P (⊥ : presieve X)) :=
((first_obj_eq_family P _).to_equiv).inhabited
/--
The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of <https://stacks.math.columbia.edu/tag/00VM>.
-/
def fork_map : P.obj (op X) ⟶ first_obj P R :=
pi.lift (λ f, P.map f.2.1.op)
/-!
This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and
the definition of `is_sheaf_for`.
-/
namespace sieve
/--
The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used
to check a family is compatible.
-/
def second_obj : Type (max v₁ u₁) :=
∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1))
/-- The map `p` of Equations (3,4) [MM92]. -/
def first_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f}))
instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ default⟩
/-- The map `a` of Equations (3,4) [MM92]. -/
def second_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op)
lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S :=
begin
apply limit.hom_ext,
rintro ⟨Y, Z, g, f, hf⟩,
simp [first_map, second_map, fork_map],
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P S) :
((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x :=
begin
rw presieve.compatible_iff_sieve_compatible,
split,
{ intro t,
ext ⟨Y, Z, g, f, hf⟩,
simpa [first_map, second_map] using t _ g hf },
{ intros t Y Z f g hf,
rw types.limit_ext_iff' at t,
simpa [first_map, second_map] using t ⟨Y, Z, g, f, hf⟩ }
end
/-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/
lemma equalizer_sheaf_condition :
presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) :=
begin
rw [types.type_equalizer_iff_unique,
← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm],
simp_rw ← compatible_iff,
simp only [inv_hom_id_apply, iso.to_equiv_symm_fun],
apply ball_congr,
intros x tx,
apply exists_unique_congr,
intro t,
rw ← iso.to_equiv_symm_fun,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [first_obj_eq_family, fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [first_obj_eq_family, fork_map] }
end
end sieve
/-!
This section establishes the equivalence between the sheaf condition of
https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`.
-/
namespace presieve
variables [has_pullbacks C]
/--
The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which
contains the data used to check a family of elements for a presieve is compatible.
-/
def second_obj : Type (max v₁ u₁) :=
∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})),
P.obj (op (pullback fg.1.2.1 fg.2.2.1)))
/-- The map `pr₀*` of <https://stacks.math.columbia.edu/tag/00VL>. -/
def first_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op)
instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ default⟩
/-- The map `pr₁*` of <https://stacks.math.columbia.edu/tag/00VL>. -/
def second_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op)
lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R :=
begin
apply limit.hom_ext,
rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩,
simp only [first_map, second_map, fork_map],
simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk,
subtype.val_eq_coe],
rw [← P.map_comp, ← op_comp, pullback.condition],
simp,
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P R) :
((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x :=
begin
rw presieve.pullback_compatible_iff,
split,
{ intro t,
ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩,
simpa [first_map, second_map] using t hf hg },
{ intros t Y Z f g hf hg,
rw types.limit_ext_iff' at t,
simpa [first_map, second_map] using t ⟨⟨Y, f, hf⟩, Z, g, hg⟩ }
end
/--
`P` is a sheaf for `R`, iff the fork given by `w` is an equalizer.
See <https://stacks.math.columbia.edu/tag/00VM>.
-/
lemma sheaf_condition :
R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) :=
begin
rw types.type_equalizer_iff_unique,
erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm,
simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply],
apply ball_congr,
intros x hx,
apply exists_unique_congr,
intros t,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [fork_map] }
end
end presieve
end equalizer
variables {C : Type u₁} [category.{v₁} C]
variables (J : grothendieck_topology C)
/-- The category of sheaves on a grothendieck topology. -/
structure SheafOfTypes (J : grothendieck_topology C) : Type (max u₁ v₁ (w+1)) :=
(val : Cᵒᵖ ⥤ Type w)
(cond : presieve.is_sheaf J val)
namespace SheafOfTypes
variable {J}
/-- Morphisms between sheaves of types are just morphisms between the underlying presheaves. -/
@[ext]
structure hom (X Y : SheafOfTypes J) :=
(val : X.val ⟶ Y.val)
@[simps]
instance : category (SheafOfTypes J) :=
{ hom := hom,
id := λ X, ⟨𝟙 _⟩,
comp := λ X Y Z f g, ⟨f.val ≫ g.val⟩,
id_comp' := λ X Y f, hom.ext _ _ $ id_comp _,
comp_id' := λ X Y f, hom.ext _ _ $ comp_id _,
assoc' := λ X Y Z W f g h, hom.ext _ _ $ assoc _ _ _ }
-- Let's make the inhabited linter happy...
instance (X : SheafOfTypes J) : inhabited (hom X X) := ⟨𝟙 X⟩
end SheafOfTypes
/-- The inclusion functor from sheaves to presheaves. -/
@[simps]
def SheafOfTypes_to_presheaf : SheafOfTypes J ⥤ (Cᵒᵖ ⥤ Type w) :=
{ obj := SheafOfTypes.val,
map := λ X Y f, f.val,
map_id' := λ X, rfl,
map_comp' := λ X Y Z f g, rfl }
instance : full (SheafOfTypes_to_presheaf J) := { preimage := λ X Y f, ⟨f⟩ }
instance : faithful (SheafOfTypes_to_presheaf J) := {}
/--
The category of sheaves on the bottom (trivial) grothendieck topology is equivalent to the category
of presheaves.
-/
@[simps]
def SheafOfTypes_bot_equiv : SheafOfTypes (⊥ : grothendieck_topology C) ≌ (Cᵒᵖ ⥤ Type w) :=
{ functor := SheafOfTypes_to_presheaf _,
inverse :=
{ obj := λ P, ⟨P, presieve.is_sheaf_bot⟩,
map := λ P₁ P₂ f, (SheafOfTypes_to_presheaf _).preimage f },
unit_iso :=
{ hom := { app := λ _, ⟨𝟙 _⟩ },
inv := { app := λ _, ⟨𝟙 _⟩ } },
counit_iso := iso.refl _ }
instance : inhabited (SheafOfTypes (⊥ : grothendieck_topology C)) :=
⟨SheafOfTypes_bot_equiv.inverse.obj ((functor.const _).obj punit)⟩
end category_theory
|
d1fc3299b2a74c9ec70492d8e3f0066971cf7b78 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/measure_theory/prod_group.lean | 7ea99b00276fffcd281432522cbfc3ef1bd9ea3f | [] | 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,387 | lean | /-
Copyright (c) 2021 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.measure_theory.prod
import Mathlib.measure_theory.group
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Measure theory in the product of groups
In this file we show properties about measure theory in products of topological groups
and properties of iterated integrals in topological groups.
These lemmas show the uniqueness of left invariant measures on locally compact groups, up to
scaling. In this file we follow the proof and refer to the book *Measure Theory* by Paul Halmos.
The idea of the proof is to use the translation invariance of measures to prove `μ(F) = c * μ(E)`
for two sets `E` and `F`, where `c` is a constant that does not depend on `μ`. Let `e` and `f` be
the characteristic functions of `E` and `F`.
Assume that `μ` and `ν` are left-invariant measures. Then the map `(x, y) ↦ (y * x, x⁻¹)`
preserves the measure `μ.prod ν`, which means that
```
∫ x, ∫ y, h x y ∂ν ∂μ = ∫ x, ∫ y, h (y * x) x⁻¹ ∂ν ∂μ
```
If we apply this to `h x y := e x * f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E)`, we can rewrite the RHS to
`μ(F)`, and the LHS to `c * μ(E)`, where `c = c(ν)` does not depend on `μ`.
Applying this to `μ` and to `ν` gives `μ (F) / μ (E) = ν (F) / ν (E)`, which is the uniqueness up to
scalar multiplication.
The proof in [Halmos] seems to contain an omission in §60 Th. A, see
`measure_theory.measure_lintegral_div_measure` and
https://math.stackexchange.com/questions/3974485/does-right-translation-preserve-finiteness-for-a-left-invariant-measure
-/
namespace measure_theory
/-- This condition is part of the definition of a measurable group in [Halmos, §59].
There, the map in this lemma is called `S`. -/
theorem map_prod_mul_eq {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} {ν : measure G} [sigma_finite ν] [sigma_finite μ] (hν : is_mul_left_invariant ⇑ν) : coe_fn (measure.map fun (z : G × G) => (prod.fst z, prod.fst z * prod.snd z)) (measure.prod μ ν) = measure.prod μ ν := sorry
/-- The function we are mapping along is `SR` in [Halmos, §59],
where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/
theorem map_prod_mul_eq_swap {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} {ν : measure G} [sigma_finite ν] [sigma_finite μ] (hμ : is_mul_left_invariant ⇑μ) : coe_fn (measure.map fun (z : G × G) => (prod.snd z, prod.snd z * prod.fst z)) (measure.prod μ ν) = measure.prod ν μ := sorry
/-- The function we are mapping along is `S⁻¹` in [Halmos, §59],
where `S` is the map in `map_prod_mul_eq`. -/
theorem map_prod_inv_mul_eq {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} {ν : measure G} [sigma_finite ν] [sigma_finite μ] (hν : is_mul_left_invariant ⇑ν) : coe_fn (measure.map fun (z : G × G) => (prod.fst z, prod.fst z⁻¹ * prod.snd z)) (measure.prod μ ν) = measure.prod μ ν :=
iff.mp
(measurable_equiv.map_apply_eq_iff_map_symm_apply_eq (homeomorph.to_measurable_equiv (homeomorph.shear_mul_right G)))
(map_prod_mul_eq hν)
/-- The function we are mapping along is `S⁻¹R` in [Halmos, §59],
where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/
theorem map_prod_inv_mul_eq_swap {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} {ν : measure G} [sigma_finite ν] [sigma_finite μ] (hμ : is_mul_left_invariant ⇑μ) : coe_fn (measure.map fun (z : G × G) => (prod.snd z, prod.snd z⁻¹ * prod.fst z)) (measure.prod μ ν) = measure.prod ν μ := sorry
/-- The function we are mapping along is `S⁻¹RSR` in [Halmos, §59],
where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/
theorem map_prod_mul_inv_eq {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} {ν : measure G} [sigma_finite ν] [sigma_finite μ] (hμ : is_mul_left_invariant ⇑μ) (hν : is_mul_left_invariant ⇑ν) : coe_fn (measure.map fun (z : G × G) => (prod.snd z * prod.fst z, prod.fst z⁻¹)) (measure.prod μ ν) = measure.prod μ ν := sorry
theorem measure_null_of_measure_inv_null {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} [sigma_finite μ] (hμ : is_mul_left_invariant ⇑μ) {E : set G} (hE : is_measurable E) (h2E : coe_fn μ ((fun (x : G) => x⁻¹) ⁻¹' E) = 0) : coe_fn μ E = 0 := sorry
theorem measure_inv_null {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} [sigma_finite μ] (hμ : is_mul_left_invariant ⇑μ) {E : set G} (hE : is_measurable E) : coe_fn μ ((fun (x : G) => x⁻¹) ⁻¹' E) = 0 ↔ coe_fn μ E = 0 := sorry
theorem measurable_measure_mul_right {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} [sigma_finite μ] {E : set G} (hE : is_measurable E) : measurable fun (x : G) => coe_fn μ ((fun (y : G) => y * x) ⁻¹' E) := sorry
theorem lintegral_lintegral_mul_inv {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} {ν : measure G} [sigma_finite ν] [sigma_finite μ] (hμ : is_mul_left_invariant ⇑μ) (hν : is_mul_left_invariant ⇑ν) (f : G → G → ennreal) (hf : measurable (function.uncurry f)) : (lintegral μ fun (x : G) => lintegral ν fun (y : G) => f (y * x) (x⁻¹)) =
lintegral μ fun (x : G) => lintegral ν fun (y : G) => f x y := sorry
theorem measure_mul_right_null {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} [sigma_finite μ] (hμ : is_mul_left_invariant ⇑μ) {E : set G} (hE : is_measurable E) (y : G) : coe_fn μ ((fun (x : G) => x * y) ⁻¹' E) = 0 ↔ coe_fn μ E = 0 := sorry
theorem measure_mul_right_ne_zero {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} [sigma_finite μ] (hμ : is_mul_left_invariant ⇑μ) {E : set G} (hE : is_measurable E) (h2E : coe_fn μ E ≠ 0) (y : G) : coe_fn μ ((fun (x : G) => x * y) ⁻¹' E) ≠ 0 :=
iff.mpr (not_iff_not_of_iff (measure_mul_right_null hμ hE y)) h2E
/-- A technical lemma relating two different measures. This is basically [Halmos, §60 Th. A].
Note that if `f` is the characteristic function of a measurable set `F` this states that
`μ F = c * μ E` for a constant `c` that does not depend on `μ`.
There seems to be a gap in the last step of the proof in [Halmos].
In the last line, the equality `g(x⁻¹)ν(Ex⁻¹) = f(x)` holds if we can prove that
`0 < ν(Ex⁻¹) < ∞`. The first inequality follows from §59, Th. D, but I couldn't find the second
inequality. For this reason, we use a compact `E` instead of a measurable `E` as in [Halmos], and
additionally assume that `ν` is a regular measure (we only need that it is finite on compact
sets). -/
theorem measure_lintegral_div_measure {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} {ν : measure G} [sigma_finite ν] [sigma_finite μ] [t2_space G] (hμ : is_mul_left_invariant ⇑μ) (hν : is_mul_left_invariant ⇑ν) (h2ν : measure.regular ν) {E : set G} (hE : is_compact E) (h2E : coe_fn ν E ≠ 0) (f : G → ennreal) (hf : measurable f) : (coe_fn μ E * lintegral ν fun (y : G) => f (y⁻¹) / coe_fn ν ((fun (h : G) => h * (y⁻¹)) ⁻¹' E)) =
lintegral μ fun (x : G) => f x := sorry
/-- This is roughly the uniqueness (up to a scalar) of left invariant Borel measures on a second
countable locally compact group. The uniqueness of Haar measure is proven from this in
`measure_theory.measure.haar_measure_unique` -/
theorem measure_mul_measure_eq {G : Type u_1} [topological_space G] [measurable_space G] [topological_space.second_countable_topology G] [borel_space G] [group G] [topological_group G] {μ : measure G} {ν : measure G} [sigma_finite ν] [sigma_finite μ] [t2_space G] (hμ : is_mul_left_invariant ⇑μ) (hν : is_mul_left_invariant ⇑ν) (h2ν : measure.regular ν) {E : set G} {F : set G} (hE : is_compact E) (hF : is_measurable F) (h2E : coe_fn ν E ≠ 0) : coe_fn μ E * coe_fn ν F = coe_fn ν E * coe_fn μ F := sorry
|
46b0aad432e997b9f849951614ce418b14b32d57 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /src/Lean/CoreM.lean | 3736d4aeb6220ab2d4d54112ce43a68a543d03cf | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,832 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.RecDepth
import Lean.Util.Trace
import Lean.Environment
import Lean.Exception
import Lean.InternalExceptionId
import Lean.Eval
import Lean.MonadEnv
namespace Lean
namespace Core
structure State :=
(env : Environment)
(ngen : NameGenerator := {})
(traceState : TraceState := {})
instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _ }⟩
structure Context :=
(options : Options := {})
(currRecDepth : Nat := 0)
(maxRecDepth : Nat := 1000)
(ref : Syntax := Syntax.missing)
abbrev CoreM := ReaderT Context $ StateRefT State $ EIO Exception
instance CoreM.inhabited {α} : Inhabited (CoreM α) :=
⟨fun _ _ => throw $ arbitrary _⟩
instance : MonadError CoreM :=
{ getRef := do ctx ← read; pure ctx.ref,
withRef := fun α ref x => adaptReader (fun (ctx : Context) => { ctx with ref := ref }) x,
addContext := fun ref msg => do
ctx ← read;
s ← get;
pure (ref, MessageData.withContext { env := s.env, mctx := {}, lctx := {}, opts := ctx.options } msg) }
instance : MonadEnv CoreM :=
{ getEnv := do s ← get; pure s.env,
modifyEnv := fun f => modify fun s => { s with env := f s.env } }
instance : MonadOptions CoreM :=
{ getOptions := do ctx ← read; pure ctx.options }
instance : MonadNameGenerator CoreM :=
{ getNGen := do s ← get; pure s.ngen,
setNGen := fun ngen => modify fun s => { s with ngen := ngen } }
instance : MonadRecDepth CoreM :=
{ withRecDepth := fun α d x => adaptReader (fun (ctx : Context) => { ctx with currRecDepth := d }) x,
getRecDepth := do ctx ← read; pure ctx.currRecDepth,
getMaxRecDepth := do ctx ← read; pure ctx.maxRecDepth }
@[inline] def liftIOCore {α} (x : IO α) : CoreM α := do
ref ← getRef;
liftM $ (adaptExcept (fun (err : IO.Error) => Exception.error ref (toString err)) x : EIO Exception α)
instance : MonadIO CoreM :=
{ liftIO := @liftIOCore }
instance : MonadTrace CoreM :=
{ getTraceState := do s ← get; pure s.traceState,
modifyTraceState := fun f => modify $ fun s => { s with traceState := f s.traceState } }
instance : AddMessageDataContext CoreM :=
{ addMessageDataContext := addMessageDataContextPartial }
@[inline] def CoreM.run {α} (x : CoreM α) (ctx : Context) (s : State) : EIO Exception (α × State) :=
(x.run ctx).run s
@[inline] def CoreM.run' {α} (x : CoreM α) (ctx : Context) (s : State) : EIO Exception α :=
Prod.fst <$> x.run ctx s
@[inline] def CoreM.toIO {α} (x : CoreM α) (ctx : Context) (s : State) : IO (α × State) :=
adaptExcept
(fun (ex : Exception) => match ex with
| Exception.error _ msg => IO.userError $ toString $ format msg
| Exception.internal id => IO.userError $ toString $ "internal exception #" ++ toString id.idx)
(x.run ctx s)
instance hasEval {α} [MetaHasEval α] : MetaHasEval (CoreM α) :=
⟨fun env opts x _ => do
(a, s) ← (finally x printTraces).toIO { maxRecDepth := getMaxRecDepth opts, options := opts} { env := env};
MetaHasEval.eval s.env opts a⟩
end Core
export Core (CoreM)
@[inline] def catchInternalId {α} {m : Type → Type} [MonadExcept Exception m] (id : InternalExceptionId) (x : m α) (h : Exception → m α) : m α :=
catch x fun ex => match ex with
| Exception.error _ _ => throw ex
| Exception.internal id' => if id == id' then h ex else throw ex
@[inline] def catchInternalIds {α} {m : Type → Type} [MonadExcept Exception m] (ids : List InternalExceptionId) (x : m α) (h : Exception → m α) : m α :=
catch x fun ex => match ex with
| Exception.error _ _ => throw ex
| Exception.internal id => if ids.contains id then h ex else throw ex
end Lean
|
a11086f24ff231b883e46e25264f9fd5b863202e | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/field_theory/subfield.lean | fd2c48262ba0fba70598fe435a578f2982921003 | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 4,935 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andreas Swerdlow
-/
import ring_theory.subring
variables {F : Type*} [field F] (S : set F)
section prio
set_option default_priority 100 -- see Note [default priority]
class is_subfield extends is_subring S : Prop :=
(inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S)
end prio
instance is_subfield.field [is_subfield S] : field S :=
{ inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩,
zero_ne_one := λ h : 0 = 1, (@zero_ne_one F _) (subtype.ext.1 h),
mul_inv_cancel := λ a ha, subtype.ext.2 (mul_inv_cancel
(λ h, ha $ subtype.ext.2 h)),
inv_zero := subtype.ext.2 inv_zero,
..show comm_ring S, by apply_instance }
instance univ.is_subfield : is_subfield (@set.univ F) :=
{ inv_mem := by intros; trivial }
/- note: in the next two declarations, if we let type-class inference figure out the instance
`ring_hom.is_subring_preimage` then that instance only applies when particular instances of
`is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones).
If we specify it explicitly, then it doesn't complain. -/
instance preimage.is_subfield {K : Type*} [field K]
(f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) :=
{ inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s,
by { rw [f.map_inv],
exact is_subfield.inv_mem ha },
..f.is_subring_preimage s }
instance image.is_subfield {K : Type*} [field K]
(f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) :=
{ inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv⟩,
..f.is_subring_image s }
instance range.is_subfield {K : Type*} [field K]
(f : F →+* K) : is_subfield (set.range f) :=
by { rw ← set.image_univ, apply_instance }
namespace field
/-- `field.closure s` is the minimal subfield that includes `s`. -/
def closure : set F :=
{ x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x }
variables {S}
theorem ring_closure_subset : ring.closure S ⊆ closure S :=
λ x hx, ⟨x, hx, 1, is_submonoid.one_mem, div_one x⟩
instance closure.is_submonoid : is_submonoid (closure S) :=
{ mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩;
exact ⟨p * r,
is_submonoid.mul_mem hp hr,
q * s,
is_submonoid.mul_mem hq hs,
(div_mul_div _ _ _ _).symm⟩,
one_mem := ring_closure_subset $ is_submonoid.one_mem }
instance closure.is_subfield : is_subfield (closure S) :=
have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem,
{ add_mem := begin
intros a b ha hb,
rcases (id ha) with ⟨p, hp, q, hq, rfl⟩,
rcases (id hb) with ⟨r, hr, s, hs, rfl⟩,
classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0],
exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs)
(is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs,
(div_add_div p r hq0 hs0).symm⟩
end,
zero_mem := h0,
neg_mem := begin
rintros _ ⟨p, hp, q, hq, rfl⟩,
exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩
end,
inv_mem := begin
rintros _ ⟨p, hp, q, hq, rfl⟩,
classical, by_cases hp0 : p = 0, by simp [hp0, h0],
exact ⟨q, hq, p, hp, inv_div.symm⟩
end }
theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S :=
ring_closure_subset $ ring.mem_closure ha
theorem subset_closure : S ⊆ closure S :=
λ _, mem_closure
theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T :=
by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_submonoid.mul_mem (ring.closure_subset H hp)
(is_subfield.inv_mem $ ring.closure_subset H hq)
theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, closure_subset⟩
theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans H subset_closure
end field
lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι]
(s : ι → set F) [∀ i, is_subfield (s i)]
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_subfield (⋃i, s i) :=
{ inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in
set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩,
to_is_subring := is_subring_Union_of_directed s directed }
instance is_subfield.inter (S₁ S₂ : set F) [is_subfield S₁] [is_subfield S₂] :
is_subfield (S₁ ∩ S₂) :=
{ inv_mem := λ x hx, ⟨is_subfield.inv_mem hx.1, is_subfield.inv_mem hx.2⟩ }
instance is_subfield.Inter {ι : Sort*} (S : ι → set F) [h : ∀ y : ι, is_subfield (S y)] :
is_subfield (set.Inter S) :=
{ inv_mem := λ x hx, set.mem_Inter.2 $ λ y, is_subfield.inv_mem $ set.mem_Inter.1 hx y }
|
4bc09678b397edbe14c6534ce269ac32f138b1d7 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Data/Lsp/TextSync.lean | 6ec1e39df59edfce5e724fc66e9a1b1226df4cf4 | [
"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 | 3,961 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Lean.Data.Json
import Lean.Data.Lsp.Basic
/-! Section "Text Document Synchronization" of the LSP spec. -/
namespace Lean
namespace Lsp
open Json
inductive TextDocumentSyncKind
| none
| full
| incremental
instance TextDocumentSyncKind.hasFromJson : HasFromJson TextDocumentSyncKind :=
⟨fun j => match j.getNat? with
| some 0 => TextDocumentSyncKind.none
| some 1 => TextDocumentSyncKind.full
| some 2 => TextDocumentSyncKind.incremental
| _ => none⟩
instance TextDocumentSyncKind.hasToJson : HasToJson TextDocumentSyncKind :=
⟨fun o => match o with
| TextDocumentSyncKind.none => (0 : Nat)
| TextDocumentSyncKind.full => (1 : Nat)
| TextDocumentSyncKind.incremental => (2 : Nat)⟩
structure DidOpenTextDocumentParams :=
(textDocument : TextDocumentItem)
instance DidOpenTextDocumentParams.hasFromJson : HasFromJson DidOpenTextDocumentParams :=
⟨fun j => DidOpenTextDocumentParams.mk <$> j.getObjValAs? TextDocumentItem "textDocument"⟩
instance DidOpenTextDocumentParams.hasToJson : HasToJson DidOpenTextDocumentParams :=
⟨fun o => mkObj $ [⟨"textDocument", toJson o.textDocument⟩]⟩
structure TextDocumentChangeRegistrationOptions :=
(documentSelector? : Option DocumentSelector := none)
(syncKind : TextDocumentSyncKind)
instance TextDocumentChangeRegistrationOptions.hasFromJson : HasFromJson TextDocumentChangeRegistrationOptions :=
⟨fun j => do
let documentSelector? := j.getObjValAs? DocumentSelector "documentSelector";
syncKind ← j.getObjValAs? TextDocumentSyncKind "syncKind";
pure ⟨documentSelector?, syncKind⟩⟩
inductive TextDocumentContentChangeEvent
-- omitted: deprecated rangeLength
| rangeChange (range : Range) (text : String)
| fullChange (text : String)
instance TextDocumentContentChangeEvent.hasFromJson : HasFromJson TextDocumentContentChangeEvent :=
⟨fun j =>
(do
range ← j.getObjValAs? Range "range";
text ← j.getObjValAs? String "text";
pure $ TextDocumentContentChangeEvent.rangeChange range text) <|>
(TextDocumentContentChangeEvent.fullChange <$> j.getObjValAs? String "text")⟩
structure DidChangeTextDocumentParams :=
(textDocument : VersionedTextDocumentIdentifier)
(contentChanges : Array TextDocumentContentChangeEvent)
instance DidChangeTextDocumentParams.hasFromJson : HasFromJson DidChangeTextDocumentParams :=
⟨fun j => do
textDocument ← j.getObjValAs? VersionedTextDocumentIdentifier "textDocument";
contentChanges ← j.getObjValAs? (Array TextDocumentContentChangeEvent) "contentChanges";
pure ⟨textDocument, contentChanges⟩⟩
-- TODO: missing:
-- WillSaveTextDocumentParams, TextDocumentSaveReason,
-- TextDocumentSaveRegistrationOptions, DidSaveTextDocumentParams
structure SaveOptions := (includeText : Bool)
instance SaveOptions.hasToJson : HasToJson SaveOptions :=
⟨fun o => mkObj $ [⟨"includeText", o.includeText⟩]⟩
structure DidCloseTextDocumentParams := (textDocument : TextDocumentIdentifier)
instance DidCloseTextDocumentParams.hasFromJson : HasFromJson DidCloseTextDocumentParams :=
⟨fun j => DidCloseTextDocumentParams.mk <$> j.getObjValAs? TextDocumentIdentifier "textDocument"⟩
-- TODO: TextDocumentSyncClientCapabilities
/- NOTE: This is defined twice in the spec. The latter version has more fields. -/
structure TextDocumentSyncOptions :=
(openClose : Bool)
(change : TextDocumentSyncKind)
(willSave : Bool)
(willSaveWaitUntil : Bool)
(save? : Option SaveOptions := none)
instance TextDocumentSyncOptions.hasToJson : HasToJson TextDocumentSyncOptions :=
⟨fun o => mkObj $
opt "save" o.save? ++ [
⟨"openClose", toJson o.openClose⟩,
⟨"change", toJson o.change⟩,
⟨"willSave", toJson o.willSave⟩,
⟨"willSaveWaitUntil", toJson o.willSaveWaitUntil⟩]⟩
end Lsp
end Lean
|
2a07c1f75837c1964352e87a1c89484be27ec01f | 675b8263050a5d74b89ceab381ac81ce70535688 | /src/data/list/basic.lean | 88df8f4f7d6220a8b1d90d1d06100bccfaab3bf3 | [
"Apache-2.0"
] | permissive | vozor/mathlib | 5921f55235ff60c05f4a48a90d616ea167068adf | f7e728ad8a6ebf90291df2a4d2f9255a6576b529 | refs/heads/master | 1,675,607,702,231 | 1,609,023,279,000 | 1,609,023,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 185,607 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import algebra.order_functions
import control.monad.basic
import data.nat.choose.basic
import order.rel_classes
/-!
# Basic properties of lists
-/
open function nat
namespace list
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
attribute [inline] list.head
instance : is_left_id (list α) has_append.append [] :=
⟨ nil_append ⟩
instance : is_right_id (list α) has_append.append [] :=
⟨ append_nil ⟩
instance : is_associative (list α) has_append.append :=
⟨ append_assoc ⟩
theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem cons_ne_self (a : α) (l : list α) : a::l ≠ l :=
mt (congr_arg length) (nat.succ_ne_self _)
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
@[simp] theorem cons_injective {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
cons_injective.eq_iff
theorem exists_cons_of_ne_nil {l : list α} (h : l ≠ nil) : ∃ b L, l = b :: L :=
by { induction l with c l', contradiction, use [c,l'], }
/-! ### mem -/
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, or.inl⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] :=
by intro e; rw e at h; cases h
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih, {cases h}, rcases h with rfl | h,
{ exact ⟨[], l, rfl⟩ },
{ rcases ih h with ⟨s, t, rfl⟩,
exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{cases h},
{rcases h with rfl | h,
{exact or.inl rfl},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) :
∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{cases h},
{cases (eq_or_mem_of_mem_cons h) with h h,
{exact ⟨c, mem_cons_self _ _, h.symm⟩},
{rcases ih h with ⟨a, ha₁, ha₂⟩,
exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} :
(∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) :=
begin
split,
{ assume H j hj,
exact H (f j) (mem_map_of_mem f hj) },
{ assume H i hi,
rcases mem_map.1 hi with ⟨j, hj, ji⟩,
rw ← ji,
exact H j hj }
end
@[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] :=
⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff],
λ h, h.symm ▸ rfl⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right,
exists_or_distrib, exists_eq_left]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp]
theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} :
b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) :
b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
lemma bind_map {g : α → list β} {f : β → γ} :
∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f)
| [] := rfl
| (a::l) := by simp only [cons_bind, map_append, bind_map l]
/-! ### length -/
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
@[simp] lemma length_singleton (a : α) : length [a] = 1 := rfl
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] :=
λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1)
theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l :=
λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0
theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] :=
⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩
theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] :=
⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩
lemma exists_of_length_succ {n} :
∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t
| [] H := absurd H.symm $ succ_ne_zero n
| (h :: t) H := ⟨h, t, rfl⟩
@[simp] lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α :=
begin
split,
{ intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl },
{ intros hα l1 l2 hl, induction l1 generalizing l2; cases l2,
{ refl }, { cases hl }, { cases hl },
congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl }
end
@[simp] lemma length_injective [subsingleton α] : injective (length : list α → ℕ) :=
length_injective_iff.mpr $ by apply_instance
/-! ### set-theoretic notation of lists -/
lemma empty_eq : (∅ : list α) = [] := by refl
lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl
lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) :
has_insert.insert x l = x :: l :=
if_neg h
lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) :
has_insert.insert x l = l :=
if_pos h
lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] :=
by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] }
/-! ### bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
theorem forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : list α},
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
ball_cons
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a :=
by simp only [mem_singleton, forall_eq]
theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_append, or_imp_distrib, forall_and_distrib]
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x.
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (mem_cons_self _ _) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, left, exact px end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
/-! ### list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
@[simp] theorem append_subset_iff {l₁ l₂ l : list α} :
l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l :=
begin
split,
{ intro h, simp only [subset_def] at *, split; intros; simp* },
{ rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 }
end
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ :=
λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩
theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) :
map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ :=
begin
refine ⟨_, map_subset f⟩, intros h2 x hx,
rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩,
cases h hxx', exact hx'
end
/-! ### append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
@[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: l := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and]
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true,
true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left']
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { rw nil_append, split,
{ rintro rfl, left, exact ⟨_, rfl, rfl⟩ },
{ rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } },
case cons : a as ih {
cases c,
{ simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'],
exact eq_comm },
{ simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left,
exists_and_distrib_left] } }
end
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj :
∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) :
s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_right h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_left' h rfl
theorem append_right_injective (s : list α) : function.injective (λ t, s ++ t) :=
λ t₁ t₂, append_left_cancel
theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
(append_right_injective s).eq_iff
theorem append_left_injective (t : list α) : function.injective (λ s, s ++ t) :=
λ s₁ s₂, append_right_cancel
theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
(append_left_injective t).eq_iff
theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β}
(h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ :=
begin
have := h, rw [← take_append_drop (length s₁) l] at this ⊢,
rw map_append at this,
refine ⟨_, _, rfl, append_inj this _⟩,
rw [length_map, length_take, min_eq_left],
rw [← length_map f l, h, length_append],
apply nat.le_add_right
end
/-! ### repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂;
unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n :=
by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) :
b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
@[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n :=
by induction n; [refl, simp only [*, repeat, map]]; split; refl
@[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred :=
by cases n; refl
@[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α :=
by induction n; [refl, simp only [*, repeat, join, append_nil]]
/-! ### pure -/
@[simp] theorem mem_pure {α} (x y : α) :
x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret]
/-! ### bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
@[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
@[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x :=
append_nil (f x)
/-! ### concat -/
theorem concat_nil (a : α) : concat [] a = [a] := rfl
theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp only [*, concat]; split; refl
theorem init_eq_of_concat_eq {a : α} {l₁ l₂ : list α} : concat l₁ a = concat l₂ a → l₁ = l₂ :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact append_right_cancel h
end
theorem last_eq_of_concat_eq {a b : α} {l : list α} : concat l a = concat l b → a = b :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact head_eq_of_cons_eq (append_left_cancel h)
end
theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by simp
theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by simp
theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp only [concat_eq_append, length_append, length]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by simp
/-! ### reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]],
(aux l nil).symm
theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ :=
by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]];
refl
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
by simp only [reverse_cons, concat_eq_append]
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; [rw [nil_append, reverse_nil, append_nil],
simp only [*, cons_append, reverse_cons, append_assoc]]
theorem reverse_concat (l : list α) (a : α) : reverse (concat l a) = a :: reverse l :=
by rw [concat_eq_append, reverse_append, reverse_singleton, singleton_append]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
@[simp] theorem reverse_involutive : involutive (@reverse α) :=
λ l, reverse_reverse l
@[simp] theorem reverse_injective : injective (@reverse α) :=
reverse_involutive.injective
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
@[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] :=
@reverse_inj _ l []
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp only [concat_eq_append, reverse_cons, reverse_reverse]
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; [refl, simp only [*, reverse_cons, length_append, length]]
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; [refl, simp only [*, map, reverse_cons, map_append]]
theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) :
map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) :=
by simp only [reverse_core_eq, map_append, map_reverse]
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff,
not_mem_nil, false_or, or_false, or_comm]]
@[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n :=
eq_repeat.2 ⟨by simp only [length_reverse, length_repeat],
λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩
/-! ### is_nil -/
lemma is_nil_iff_eq_nil {l : list α} : l.is_nil ↔ l = [] :=
list.cases_on l (by simp [is_nil]) (by simp [is_nil])
/-! ### init -/
@[simp] theorem length_init : ∀ (l : list α), length (init l) = length l - 1
| [] := rfl
| [a] := rfl
| (a :: b :: l) :=
begin
rw init,
simp only [add_left_inj, length, succ_add_sub_one],
exact length_init (b :: l)
end
/-! ### last -/
@[simp] theorem last_cons {a : α} {l : list α} :
∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
by induction l;
[refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]]
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp only [concat_eq_append, last_append]
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem init_append_last : ∀ {l : list α} (h : l ≠ []), init l ++ [last l h] = l
| [] h := absurd rfl h
| [a] h := rfl
| (a::b::l) h :=
begin
rw [init, cons_append, last_cons (cons_ne_nil _ _) (cons_ne_nil _ _)],
congr,
exact init_append_last (cons_ne_nil b l)
end
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l
| [] h := absurd rfl h
| [a] h := or.inl rfl
| (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) }
lemma last_repeat_succ (a m : ℕ) :
(repeat a m.succ).last (ne_nil_of_length_eq_succ
(show (repeat a m.succ).length = m.succ, by rw length_repeat)) = a :=
begin
induction m with k IH,
{ simp },
{ simpa only [repeat_succ, last] }
end
/-! ### last' -/
@[simp] theorem last'_is_none :
∀ {l : list α}, (last' l).is_none ↔ l = []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_none (b::l)]
@[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_some (b::l)]
theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h
| [] x hx := false.elim $ by simpa using hx
| [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩
| (a::b::l) x hx :=
begin
rw last' at hx,
rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩,
use cons_ne_nil _ _,
rwa [last_cons]
end
theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l :=
let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _
theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l
| [] a ha := (option.not_mem_none a ha).elim
| [a] _ rfl := rfl
| (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] }
theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget
| [] := by simp [ilast, arbitrary]
| [a] := rfl
| [a, b] := rfl
| [a, b, c] := rfl
| (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)]
@[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α),
last' (l₁ ++ a :: l₂) = last' (a :: l₂)
| [] a l₂ := rfl
| [b] a l₂ := rfl
| (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons]
theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []),
last' (l₁ ++ l₂) = last' l₂
| [] hl₂ := by contradiction
| (b::l₂) _ := last'_append_cons l₁ b l₂
/-! ### head(') and tail -/
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l
| [] h := (option.not_mem_none _ h).elim
| (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl }
@[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) :
head (s ++ t) = head s :=
by {induction s, contradiction, refl}
theorem tail_append_singleton_of_ne_nil {a : α} {l : list α} (h : l ≠ nil) :
tail (l ++ [a]) = tail l ++ [a] :=
by { induction l, contradiction, rw [tail,cons_append,tail], }
theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l
| [] a h := by contradiction
| (b::l) a h := by { simp at h, simp [h] }
theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l
| [] h := by contradiction
| (a::l) h := rfl
theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
cons_head'_tail (head_mem_head' h)
@[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl
/-! ### Induction from the right -/
/-- Induction principle from the right for lists: if a property holds for the empty list, and
for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
@[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ rw reverse_cons, exact H1 _ _ ih }
end
/-- Bidirectional induction principle for lists: if a property holds for the empty list, the
singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to
prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it
can also be used to construct data. -/
def bidirectional_rec {C : list α → Sort*}
(H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : ∀ l, C l
| [] := H0
| [a] := H1 a
| (a :: b :: l) :=
let l' := init (b :: l), b' := last (b :: l) (cons_ne_nil _ _) in
have length l' < length (a :: b :: l), by { change _ < length l + 2, simp },
begin
rw ←init_append_last (cons_ne_nil b l),
have : C l', from bidirectional_rec l',
exact Hn a l' b' ‹C l'›
end
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] }
/-- Like `bidirectional_rec`, but with the list parameter placed first. -/
@[elab_as_eliminator] def bidirectional_rec_on {C : list α → Sort*}
(l : list α) (H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : C l :=
bidirectional_rec H0 H1 Hn l
/-! ### sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) :
l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih, {refl},
{ rw reverse_cons, exact sublist_append_of_sublist_left ih },
{ rw [reverse_cons, reverse_cons], exact ih.append_right [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff]
using h.reverse,
λ h, h.append_right l⟩
theorem sublist.append {l₁ l₂ r₁ r₂ : list α}
(hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ :=
(hl.append_right _).trans ((append_sublist_append_left _).2 hr)
theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (sublist.subset s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, h.subset (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ s.subset
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h,
λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) :
l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/-! ### index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) :
index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp, priority 990]
theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih,
{ exact iff_of_true rfl (not_mem_nil _) },
simp only [length, mem_cons_iff, index_of_cons], split_ifs,
{ exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) },
{ simp only [h, false_or], rw ← ih, exact succ_inj' }
end
@[simp, priority 980]
theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih, {refl},
simp only [length, index_of_cons],
by_cases h : a = b, {rw if_pos h, exact nat.zero_le _},
rw if_neg h, exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/-! ### nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_len_le hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
@[simp]
theorem nth_eq_none_iff : ∀ {l : list α} {n}, nth l n = none ↔ length l ≤ n :=
begin
intros, split,
{ intro h, by_contradiction h',
have h₂ : ∃ h, l.nth_le n h = l.nth_le n (lt_of_not_ge h') := ⟨lt_of_not_ge h', rfl⟩,
rw [← nth_eq_some, h] at h₂, cases h₂ },
{ solve_by_elim [nth_len_le] },
end
theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a :=
let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩
theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l
| (a :: l) 0 h := mem_cons_self _ _
| (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _)
theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l :=
let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _
theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a :=
⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩
theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a :=
mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm
lemma nth_injective {α : Type u} {xs : list α} {i j : ℕ}
(h₀ : i < xs.length)
(h₁ : nodup xs)
(h₂ : xs.nth i = xs.nth j) : i = j :=
begin
induction xs with x xs generalizing i j,
{ cases h₀ },
{ cases i; cases j,
case nat.zero nat.zero
{ refl },
case nat.succ nat.succ
{ congr, cases h₁,
apply xs_ih;
solve_by_elim [lt_of_succ_lt_succ] },
iterate 2
{ dsimp at h₂,
cases h₁ with _ _ h h',
cases h x _ rfl,
rw mem_iff_nth,
exact ⟨_, h₂.symm⟩ <|>
exact ⟨_, h₂⟩ } },
end
@[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f
| [] n := rfl
| (a :: l) 0 := rfl
| (a :: l) (n+1) := nth_map l n
theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) :=
option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl
/-- A version of `nth_le_map` that can be used for rewriting. -/
theorem nth_le_map_rev (f : α → β) {l n} (H) :
f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) :=
(nth_le_map f _ _).symm
@[simp] theorem nth_le_map' (f : α → β) {l n} (H) :
nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f _ _
/-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as
`hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make
such a rewrite, with `rw (nth_le_of_eq h)`. -/
lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) :
nth_le L i hi = nth_le L' i (h ▸ hi) :=
by { congr, exact h}
@[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) :
nth_le [a] n hn = a :=
have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn),
by subst hn0; refl
lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) :
L.nth_le 0 h = L.head :=
by { cases L, cases h, simp, }
lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂),
(l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂
| [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim
| (a::l) _ 0 hn₁ hn₂ := rfl
| (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append];
exact nth_le_append _ _
lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ}
(h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length :=
begin
rw list.length_append at h₂,
convert (nat.sub_lt_sub_right_iff h₁).mpr h₂,
simp,
end
lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂),
(l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂)
| [] _ n h₁ h₂ := rfl
| (a :: l) _ (n+1) h₁ h₂ :=
begin
dsimp,
conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], },
rw nth_le_append_right (nat.lt_succ_iff.mp h₁),
end
@[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) :
(list.repeat a n).nth_le m h = a :=
eq_of_mem_repeat (nth_le_mem _ _ _)
lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) :
(l₁ ++ l₂).nth n = l₁.nth n :=
have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn
(by rw length_append; exact le_add_right _ _),
by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append]
lemma nth_append_right {l₁ l₂ : list α} {n : ℕ} (hn : l₁.length ≤ n) :
(l₁ ++ l₂).nth n = l₂.nth (n - l₁.length) :=
begin
by_cases hl : n < (l₁ ++ l₂).length,
{ rw [nth_le_nth hl, nth_le_nth, nth_le_append_right hn] },
{ rw [nth_len_le (le_of_not_lt hl), nth_len_le],
rw [not_lt, length_append] at hl,
exact nat.le_sub_left_of_add_le hl }
end
lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []),
last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos)
| [] h := rfl
| [a] h := by rw [last_singleton, nth_le_singleton]
| (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)],
refl, exact cons_ne_nil b l }
@[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a
| [] a := rfl
| (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length]
@[ext]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa;
simp only [aa, ext (λn, h (n+1))]; split; refl
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂)
(h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], }
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} :
∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b;
simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l]
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 :
∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i :=
by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1);
exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
lemma index_of_inj [decidable_eq α] {l : list α} {x y : α}
(hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y :=
⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) =
nth_le l (index_of y l) (index_of_lt_length.2 hy),
by simp only [h],
by simpa only [index_of_nth_le],
λ h, by subst h⟩
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) :
l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] :=
begin
refine ext_le (by convert h) (λ n h₁ h₂, _),
simp only [nth_le_singleton],
congr,
exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂)
end
lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) :
∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) =
l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l)
lemma modify_nth_tail_modify_nth_tail_le
{f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) :
(l.modify_nth_tail f n).modify_nth_tail g m =
l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n :=
begin
rcases le_iff_exists_add.1 h with ⟨m, rfl⟩,
rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail]
end
lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) :
(l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n :=
by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl
lemma modify_nth_tail_id :
∀n (l:list α), l.modify_nth_tail id n = l
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m;
simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj,
not_false_iff]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp only [update_nth_eq_modify_nth, modify_nth_length]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp only [nth_modify_nth, if_pos]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp only [nth_modify_nth, if_neg h, id_map']
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h]
@[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α)
(h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a :=
by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at *
@[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α)
(hj : j < (l.update_nth i a).length) :
(l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) :=
by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth]
lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α}
(h : a ∈ l.update_nth n b), a ∈ l ∨ a = b
| [] n a b h := false.elim h
| (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim
or.inr (or.inl ∘ mem_cons_of_mem _)
| (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim
(λ h, h ▸ or.inl (mem_cons_self _ _))
(λ h, (mem_or_eq_of_mem_update_nth h).elim
(or.inl ∘ mem_cons_of_mem _) or.inr)
section insert_nth
variable {a : α}
@[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl
@[simp] lemma insert_nth_succ_nil (n : ℕ) (a : α) : insert_nth (n + 1) a [] = [] := rfl
lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1
| 0 as h := rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h)
lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l :=
by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same];
from modify_nth_tail_id _ _
lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → n ≤ m →
insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n
| 0 0 [] has _ := (lt_irrefl _ has).elim
| 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth]
| 0 (m+1) (a::as) has hmn := rfl
| (n+1) (m+1) (a::as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1)
| n 0 (a :: as) has hmn := rfl
| (n + 1) (m + 1) (a :: as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_comm (a b : α) :
∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l),
(l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a
| 0 j l := by simp [insert_nth]
| (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim
| (i + 1) (j+1) [] := by simp
| (i + 1) (j+1) (c::l) :=
assume h₀ h₁,
by simp [insert_nth];
exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁)
lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length),
a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l
| 0 as h := iff.rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := begin
dsimp [list.insert_nth],
erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff,
← or.assoc, or_comm (a = a'), or.assoc]
end
end insert_nth
/-! ### map -/
@[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl
theorem map_eq_foldr (f : α → β) (l : list α) :
map f l = foldr (λ a bs, f a :: bs) [] l :=
by induction l; simp *
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in
by rw [map, map, h₁, map_congr h₂]
lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) :=
begin
refine ⟨_, map_congr⟩, intros h x hx,
rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩,
rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h
end
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; [refl, simp only [*, join, map, map_append]]
theorem bind_ret_eq_map (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *];
split; refl
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl
@[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) :=
by cases l; refl
@[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f :=
begin
split; intros h x y hxy,
{ suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] },
{ induction y generalizing x, simpa using hxy,
cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] }
end
/--
A single `list.map` of a composition of functions is equal to
composing a `list.map` with another `list.map`, fully applied.
This is the reverse direction of `list.map_map`.
-/
lemma comp_map (h : β → γ) (g : α → β) (l : list α) :
map (h ∘ g) l = map h (map g l) := (map_map _ _ _).symm
/--
Composing a `list.map` with another `list.map` is equal to
a single `list.map` of composed functions.
-/
@[simp] lemma map_comp_map (g : β → γ) (f : α → β) :
map g ∘ map f = map (g ∘ f) :=
by { ext l, rw comp_map }
theorem map_filter_eq_foldr (f : α → β) (p : α → Prop) [decidable_pred p] (as : list α) :
map f (filter p as) = foldr (λ a bs, if p a then f a :: bs else bs) [] as :=
by { induction as, { refl }, { simp! [*, apply_ite (map f)] } }
lemma last_map (f : α → β) {l : list α} (hl : l ≠ []) :
(l.map f).last (mt eq_nil_of_map_eq_nil hl) = f (l.last hl) :=
begin
induction l with l_ih l_tl l_ih,
{ apply (hl rfl).elim },
{ cases l_tl,
{ simp },
{ simpa using l_ih } }
end
/-! ### map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
@[simp] theorem map₂_flip (f : α → β → γ) :
∀ as bs, map₂ (flip f) bs as = map₂ f as bs
| [] [] := rfl
| [] (b :: bs) := rfl
| (a :: as) [] := rfl
| (a :: as) (b :: bs) := by { simp! [map₂_flip], refl }
/-! ### take, drop -/
@[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
@[simp] theorem take_length : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end
theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_le (le_of_succ_le_succ h)]
end
@[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁
| [] l₂ := rfl
| (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂)
theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take_left
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [min_zero, take_zero, take_nil]
| 0 m l := by rw [zero_min, take_zero, take_zero]
| (succ n) (succ m) nil := by simp only [take_nil]
| (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl
theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m)
| n 0 := by simp
| 0 m := by simp
| (succ n) (succ m) := by simp [min_succ_succ, take_repeat]
lemma map_take {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_take], }
lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ},
n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)]
/-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first
`i` elements of `l₂` to `l₁`. -/
lemma take_append {l₁ l₂ : list α} (i : ℕ) :
take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) :=
begin
induction l₁, { simp },
have : length l₁_tl + 1 + i = (length l₁_tl + i).succ,
by { rw nat.succ_eq_add_one, exact succ_add _ _ },
simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self]
end
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) :
nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) :=
by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ }
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) :
nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) :=
by { simp at hi, rw nth_le_take L _ hi.1 }
lemma nth_take {l : list α} {n m : ℕ} (h : m < n) :
(l.take n).nth m = l.nth m :=
begin
induction n with n hn generalizing l m,
{ simp only [nat.nat_zero_eq_zero] at h,
exact absurd h (not_lt_of_le m.zero_le) },
{ cases l with hd tl,
{ simp only [take_nil] },
{ cases m,
{ simp only [nth, take] },
{ simpa only using hn (nat.lt_of_succ_lt_succ h) } } },
end
@[simp] lemma nth_take_of_succ {l : list α} {n : ℕ} :
(l.take (n + 1)).nth n = l.nth n :=
nth_take (nat.lt_succ_self n)
lemma take_succ {l : list α} {n : ℕ} :
l.take (n + 1) = l.take n ++ (l.nth n).to_list :=
begin
induction l with hd tl hl generalizing n,
{ simp only [option.to_list, nth, take_nil, append_nil]},
{ cases n,
{ simp only [option.to_list, nth, eq_self_iff_true, and_self, take, nil_append] },
{ simp only [hl, cons_append, nth, eq_self_iff_true, and_self, take] } }
end
@[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
lemma mem_of_mem_drop {α} {n : ℕ} {l : list α} {x : α}
(h : x ∈ l.drop n) :
x ∈ l :=
begin
induction l generalizing n,
case list.nil : n h
{ simpa using h },
case list.cons : l_hd l_tl l_ih n h
{ cases n; simp only [mem_cons_iff, drop] at h ⊢,
{ exact h },
right, apply l_ih h },
end
@[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l
| [] := rfl
| (a :: l) := rfl
theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l)
| m 0 l := rfl
| m (n+1) [] := (drop_nil _).symm
| m (n+1) (a::l) := drop_add m n _
@[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂
| [] l₂ := rfl
| (a::l₁) l₂ := drop_left l₁ l₂
theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
drop n (l₁ ++ l₂) = l₂ :=
by rw ← h; apply drop_left
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
@[simp] lemma drop_length (l : list α) : l.drop l.length = [] :=
calc l.drop l.length = (l ++ []).drop l.length : by simp
... = [] : drop_left _ _
lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length →
(l₁ ++ l₂).drop n = l₁.drop n ++ l₂
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)]
/-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements
up to `i` in `l₂`. -/
lemma drop_append {l₁ l₂ : list α} (i : ℕ) :
drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ :=
begin
induction l₁, { simp },
have : length l₁_tl + 1 + i = (length l₁_tl + i).succ,
by { rw nat.succ_eq_add_one, exact succ_add _ _ },
simp only [cons_append, length, this, drop, l₁_ih]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) :
nth_le L (i + j) h = nth_le (L.drop i) j
begin
have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h,
rw (take_append_drop i L).symm at h,
simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h
end :=
begin
have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)],
rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right];
simp [A]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) :
nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) :=
by rw nth_le_drop
@[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l
| m [] := by simp
| 0 l := by simp
| (m+1) (a::l) :=
calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl
... = drop (n + m) l : drop_drop m l
... = drop (n + (m + 1)) (a :: l) : rfl
theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α),
drop m (take (m + n) l) = take n (drop m l)
| 0 n _ := by simp
| (m+1) n nil := by simp
| (m+1) n (_::l) :=
have h: m + 1 + n = (m+n) + 1, by ac_refl,
by simpa [take_cons, h] using drop_take m n l
lemma map_drop {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_drop], }
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
lemma reverse_take {α} {xs : list α} (n : ℕ)
(h : n ≤ xs.length) :
xs.reverse.take n = (xs.drop (xs.length - n)).reverse :=
begin
induction xs generalizing n; simp only [reverse_cons, drop, reverse_nil, nat.zero_sub, length, take_nil],
cases decidable.lt_or_eq_of_le h with h' h',
{ replace h' := le_of_succ_le_succ h',
rwa [take_append_of_le_length, xs_ih _ h'],
rw [show xs_tl.length + 1 - n = succ (xs_tl.length - n), from _, drop],
{ rwa [succ_eq_add_one, nat.sub_add_comm] },
{ rwa length_reverse } },
{ subst h', rw [length, nat.sub_self, drop],
rw [show xs_tl.length + 1 = (xs_tl.reverse ++ [xs_hd]).length, from _, take_length, reverse_cons],
rw [length_append, length_reverse], refl }
end
@[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] :=
by cases l; cases n; simp only [update_nth]
section take'
variable [inhabited α]
@[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n
| 0 l := rfl
| (n+1) l := congr_arg succ (take'_length _ _)
@[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n
| 0 := rfl
| (n+1) := congr_arg (cons _) (take'_nil _)
theorem take'_eq_take : ∀ {n} {l : list α},
n ≤ length l → take' n l = take n l
| 0 l h := rfl
| (n+1) (a::l) h := congr_arg (cons _) $
take'_eq_take $ le_of_succ_le_succ h
@[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ :=
(take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _)
theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take' n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take'_left
end take'
/-! ### foldl, foldr -/
lemma foldl_ext (f g : α → β → α) (a : α)
{l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) :
foldl f a l = foldl g a l :=
begin
induction l with hd tl ih generalizing a, {refl},
unfold foldl,
rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)]
end
lemma foldr_ext (f g : α → β → β) (b : β)
{l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) :
foldr f b l = foldr g b l :=
begin
induction l with hd tl ih, {refl},
simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H,
simp only [foldr, ih H.2, H.1]
end
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : α → β → α) :
∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂
| a [] l₂ := rfl
| a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂]
@[simp] theorem foldl_join (f : α → β → α) :
∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L
| a [] := rfl
| a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L]
@[simp] theorem foldr_join (f : α → β → β) :
∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L
| a [] := rfl
| a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) :
foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) :
foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl
@[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l :=
by rw ←foldr_reverse; simp
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) :
foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldl]]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) :
foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldr]]
theorem foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldl f' (g a) (l.map g) = g (list.foldl f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldr_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldr f' (g a) (l.map g) = g (list.foldr f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α)
(h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) :=
eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] }
theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α)
(h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) :=
by { revert a, induction l; intros; [refl, simp only [*, foldr]] }
lemma injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α}
(hl : ∀ f ∈ l, function.injective f) (hf : function.injective f):
function.injective (@list.foldl (α → α) (α → α) function.comp f l) :=
begin
induction l generalizing f,
{ exact hf },
{ apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)),
apply function.injective.comp hf,
apply hl _ (list.mem_cons_self _ _) }
end
/- scanl -/
section scanl
variables {f : β → α → β} {b : β} {a : α} {l : list α}
lemma length_scanl :
∀ a l, length (scanl f a l) = l.length + 1
| a [] := rfl
| a (x :: l) := by erw [length_cons, length_cons, length_scanl]
@[simp] lemma scanl_nil (b : β) : scanl f b nil = [b] := rfl
@[simp] lemma scanl_cons :
scanl f b (a :: l) = [b] ++ scanl f (f b a) l :=
by simp only [scanl, eq_self_iff_true, singleton_append, and_self]
@[simp] lemma nth_zero_scanl : (scanl f b l).nth 0 = some b :=
begin
cases l,
{ simp only [nth, scanl_nil] },
{ simp only [nth, scanl_cons, singleton_append] }
end
@[simp] lemma nth_le_zero_scanl {h : 0 < (scanl f b l).length} :
(scanl f b l).nth_le 0 h = b :=
begin
cases l,
{ simp only [nth_le, scanl_nil] },
{ simp only [nth_le, scanl_cons, singleton_append] }
end
lemma nth_succ_scanl {i : ℕ} :
(scanl f b l).nth (i + 1) = ((scanl f b l).nth i).bind (λ x, (l.nth i).map (λ y, f x y)) :=
begin
induction l with hd tl hl generalizing b i,
{ symmetry,
simp only [option.bind_eq_none', nth, forall_2_true_iff, not_false_iff, option.map_none',
scanl_nil, option.not_mem_none, forall_true_iff] },
{ simp only [nth, scanl_cons, singleton_append],
cases i,
{ simp only [option.map_some', nth_zero_scanl, nth, option.some_bind'] },
{ simp only [hl, nth] } }
end
lemma nth_le_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} :
(scanl f b l).nth_le (i + 1) h =
f ((scanl f b l).nth_le i (nat.lt_of_succ_lt h))
(l.nth_le i (nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) :=
begin
induction i with i hi generalizing b l,
{ cases l,
{ simp only [length, zero_add, scanl_nil] at h,
exact absurd h (lt_irrefl 1) },
{ simp only [scanl_cons, singleton_append, nth_le_zero_scanl, nth_le] } },
{ cases l,
{ simp only [length, add_lt_iff_neg_right, scanl_nil] at h,
exact absurd h (not_lt_of_lt nat.succ_pos') },
{ simp_rw scanl_cons,
rw nth_le_append_right _,
{ simpa only [hi, length, succ_add_sub_one] },
{ simp only [length, nat.zero_le, le_add_iff_nonneg_left] } } }
end
end scanl
/- scanr -/
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp only [scanr, scanr_aux, t, foldr_cons]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) :=
by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp only [foldl_cons];
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section foldl_eq_foldlr'
variables {f : α → β → α}
variables hf : ∀ a b c, f (f a b) c = f (f a c) b
include hf
theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b
| a b [] := rfl
| a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf]
theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l
| a [] := rfl
| a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl
end foldl_eq_foldlr'
section foldl_eq_foldlr'
variables {f : α → β → β}
variables hf : ∀ a b c, f a (f b c) = f b (f a c)
include hf
theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l
| a b [] := rfl
| a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl
end foldl_eq_foldlr'
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons]
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc];
rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/-! ### mfoldl, mfoldr -/
section mfoldl_mfoldr
variables {m : Type v → Type w} [monad m]
@[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl
@[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl
@[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} :
mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl
@[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} :
mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl
theorem mfoldr_eq_foldr (f : α → β → m β) (b l) :
mfoldr f b l = foldr (λ a mb, mb >>= f a) (pure b) l :=
by induction l; simp *
variables [is_lawful_monad m]
theorem mfoldl_eq_foldl (f : β → α → m β) (b l) :
mfoldl f b l = foldl (λ mb a, mb >>= λ b, f b a) (pure b) l :=
begin
suffices h : ∀ (mb : m β),
(mb >>= λ b, mfoldl f b l) = foldl (λ mb a, mb >>= λ b, f b a) mb l,
by simp [←h (pure b)],
induction l; intro,
{ simp },
{ simp only [mfoldl, foldl, ←l_ih] with monad_norm }
end
@[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂},
mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂
| _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind]
| _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc]
@[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂},
mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁
| _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure]
| _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc]
end mfoldl_mfoldr
/-! ### prod and sum -/
-- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet.
attribute [to_additive] list.prod
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[to_additive]
theorem prod_singleton : [a].prod = a := one_mul a
@[simp, to_additive]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, to_additive]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
theorem prod_ne_zero {R : Type*} [domain R] {L : list R} :
(∀ x ∈ L, (x : _) ≠ 0) → L.prod ≠ 0 :=
list.rec_on L (λ _, one_ne_zero) $ λ hd tl ih H,
by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) }
@[to_additive]
theorem prod_eq_foldr : l.prod = foldr (*) 1 l :=
list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl]
@[to_additive]
theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (l.map f).prod (l.map g).prod :=
list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl])
@[to_additive]
theorem prod_hom [monoid β] (l : list α) (f : α →* β) :
(l.map f).prod = f l.prod :=
by { simp only [prod, foldl_map, f.map_one.symm],
exact l.foldl_hom _ _ _ 1 f.map_mul }
-- `to_additive` chokes on the next few lemmas, so we do them by hand below
@[simp]
lemma prod_take_mul_prod_drop :
∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], }
@[simp]
lemma prod_take_succ :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], }
/-- A list with product not one must have positive length. -/
lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
lemma prod_update_nth : ∀ (L : list α) (n : ℕ) (a : α),
(L.update_nth n a).prod =
(L.take n).prod * (if n < L.length then a else 1) * (L.drop (n + 1)).prod
| (x::xs) 0 a := by simp [update_nth]
| (x::xs) (i+1) a := by simp [update_nth, prod_update_nth xs i a, mul_assoc]
| [] _ _ := by simp [update_nth, (nat.zero_le _).not_lt]
end monoid
section group
variables [group α]
/-- This is the `list.prod` version of `mul_inv_rev` -/
@[to_additive "This is the `list.sum` version of `add_neg_rev`"]
lemma prod_inv_reverse : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).reverse.prod
| [] := by simp
| (x :: xs) := by simp [prod_inv_reverse xs]
/-- A non-commutative variant of `list.prod_reverse` -/
@[to_additive "A non-commutative variant of `list.sum_reverse`"]
lemma prod_reverse_noncomm : ∀ (L : list α), L.reverse.prod = (L.map (λ x, x⁻¹)).prod⁻¹ :=
by simp [prod_inv_reverse]
end group
section comm_group
variables [comm_group α]
/-- This is the `list.prod` version of `mul_inv` -/
@[to_additive "This is the `list.sum` version of `add_neg`"]
lemma prod_inv : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).prod
| [] := by simp
| (x :: xs) := by simp [mul_comm, prod_inv xs]
end comm_group
@[simp]
lemma sum_take_add_sum_drop [add_monoid α] :
∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], }
@[simp]
lemma sum_take_succ [add_monoid α] :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], }
lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length)
(h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' :=
begin
apply ext_le h (λ i h₁ h₂, _),
have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁),
rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this,
exact add_left_cancel this
end
lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) :
monotone (λ i, (L.take i).sum) :=
begin
apply monotone_of_monotone_nat (λ n, _),
by_cases h : n < L.length,
{ rw sum_take_succ _ _ h,
exact le_add_right (le_refl _) },
{ push_neg at h,
simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] }
end
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
1 ≤ l.prod :=
begin
induction l with hd tl ih,
{ simp },
rw prod_cons,
exact one_le_mul (hl₁ hd (mem_cons_self hd tl)) (ih (λ x h, hl₁ x (mem_cons_of_mem hd h))),
end
@[to_additive]
lemma single_le_prod [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
∀ x ∈ l, x ≤ l.prod :=
begin
induction l,
{ simp },
simp_rw [prod_cons, forall_mem_cons] at ⊢ hl₁,
split,
{ exact le_mul_of_one_le_right' (one_le_prod_of_one_le hl₁.2) },
{ exact λ x H, le_mul_of_one_le_of_le hl₁.1 (l_ih hl₁.right x 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 [ordered_comm_monoid α]
{l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) (hl₂ : l.prod = 1) :
∀ x ∈ l, x = (1 : α) :=
λ x hx, le_antisymm (hl₂ ▸ single_le_prod hl₁ _ hx) (hl₁ x hx)
lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] (l : list α) :
l.sum = 0 ↔ ∀ x ∈ l, x = (0 : α) :=
⟨all_zero_of_le_zero_le_of_sum_eq_zero (λ _ _, zero_le _),
begin
induction l,
{ simp },
{ intro h,
rw [sum_cons, add_eq_zero_iff],
rw forall_mem_cons at h,
exact ⟨h.1, l_ih h.2⟩ },
end⟩
/-- A list with sum not zero must have positive length. -/
lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
/-- If all elements in a list are bounded below by `1`, then the length of the list is bounded
by the sum of the elements. -/
lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum :=
begin
induction L with j L IH h, { simp },
rw [sum_cons, length, add_comm],
exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi)))
end
-- Now we tie those lemmas back to their multiplicative versions.
attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one
/-- A list with positive sum must have positive length. -/
-- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications.
lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) :
0 < L.length :=
length_pos_of_sum_ne_zero L (ne_of_gt h)
@[simp, to_additive]
theorem prod_erase [decidable_eq α] [comm_monoid α] {a} :
Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b::l) h :=
begin
rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_monoid α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum :=
begin
induction l with x l ih,
{ exact dvd_zero _ },
{ rw [list.sum_cons],
exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) }
end
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; [refl, simp only [*, join, map, sum_cons, length_append]]
@[simp] theorem length_bind (l : list α) (f : α → list β) :
length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
lemma exists_lt_of_sum_lt [linear_ordered_cancel_add_comm_monoid β] {l : list α}
(f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x :=
begin
induction l with x l,
{ exfalso, exact lt_irrefl _ h },
{ by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) }
end
lemma exists_le_of_sum_le [linear_ordered_cancel_add_comm_monoid β] {l : list α}
(hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x :=
begin
cases l with x l,
{ contradiction },
{ by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩,
exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) }
end
-- Several lemmas about sum/head/tail for `list ℕ`.
-- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`.
-- We'd like to state this as `L.head * L.tail.prod = L.prod`,
-- but because `L.head` relies on an inhabited instances and
-- returns a garbage value for the empty list, this is not possible.
-- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`,
-- and below, restate the lemma just for `ℕ`.
@[to_additive]
lemma head_mul_tail_prod' [monoid α] (L : list α) :
(L.nth 0).get_or_else 1 * L.tail.prod = L.prod :=
by { cases L, { simp, refl, }, { simp, }, }
lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum :=
by { cases L, { simp, refl, }, { simp, }, }
lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum :=
nat.le.intro (head_add_tail_sum L)
lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head :=
by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel]
section
variables {G : Type*} [comm_group G]
attribute [to_additive] alternating_prod
@[simp, to_additive] lemma alternating_prod_nil :
alternating_prod ([] : list G) = 1 := rfl
@[simp, to_additive] lemma alternating_prod_singleton (g : G) :
alternating_prod [g] = g := rfl
@[simp, to_additive alternating_sum_cons_cons']
lemma alternating_prod_cons_cons (g h : G) (l : list G) :
alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl
lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) :
alternating_sum (g :: h :: l) = g - h + alternating_sum l :=
by rw [sub_eq_add_neg, alternating_sum]
end
/-! ### join -/
attribute [simp] join
theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = []
| [] := iff_of_true rfl (forall_mem_nil _)
| (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]]
lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join :=
by { induction l, simp, simp [l_ih] }
/-- In a join, taking the first elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join of the first `i` sublists. -/
lemma take_sum_join (L : list (list α)) (i : ℕ) :
L.join.take ((L.map length).take i).sum = (L.take i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [take_append, L_ih]
end
/-- In a join, dropping all the elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/
lemma drop_sum_join (L : list (list α)) (i : ℕ) :
L.join.drop ((L.map length).take i).sum = (L.drop i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [drop_append, L_ih],
end
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) :
(L.take (i+1)).drop i = [nth_le L i hi] :=
begin
induction L generalizing i,
{ simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim },
cases i, { simp },
have : i < L_tl.length,
{ simp at hi,
exact nat.lt_of_succ_lt_succ hi },
simp [L_ih this],
refl
end
/-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the
original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and
`B` is the sum of the lengths of sublists of index `≤ i`. -/
lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) :
(L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi :=
begin
have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take],
simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi]
end
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum :=
by simp [hi, sum_take_succ, hj]
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < L.join.length :=
begin
convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi),
have : L.length = (L.map length).length, by simp,
simp [this, -length_map]
end
/-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist,
where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists
of index `< i`, and adding `j`. -/
lemma nth_le_join (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) =
nth_le (nth_le L i hi) j hj :=
by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj),
nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)]
/-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the
sublists. -/
theorem eq_iff_join_eq (L L' : list (list α)) :
L = L' ↔ L.join = L'.join ∧ map length L = map length L' :=
begin
refine ⟨λ H, by simp [H], _⟩,
rintros ⟨join_eq, length_eq⟩,
apply ext_le,
{ have : length (map length L) = length (map length L'), by rw length_eq,
simpa using this },
{ assume n h₁ h₂,
rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] }
end
/-! ### lexicographic ordering -/
/-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which
`[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`.
The definition is given for any relation `r`, not only strict orders. -/
inductive lex (r : α → α → Prop) : list α → list α → Prop
| nil {a l} : lex [] (a :: l)
| cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂)
| rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂)
namespace lex
theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} :
lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ :=
⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h;
[exact h, exact (irrefl_of r a h).elim], lex.cons⟩
@[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l [].
instance is_order_connected (r : α → α → Prop)
[is_order_connected α r] [is_trichotomous α r] :
is_order_connected (list α) (lex r) :=
⟨λ l₁, match l₁ with
| _, [], c::l₃, nil := or.inr nil
| _, [], c::l₃, rel _ := or.inr nil
| _, [], c::l₃, cons _ := or.inr nil
| _, b::l₂, c::l₃, nil := or.inl nil
| a::l₁, b::l₂, c::l₃, rel h :=
(is_order_connected.conn _ b _ h).imp rel rel
| a::l₁, b::l₂, _::l₃, cons h := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match _ l₂ _ h).imp cons cons },
{ exact or.inr (rel ab) }
end
end⟩
instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] :
is_trichotomous (list α) (lex r) :=
⟨λ l₁, match l₁ with
| [], [] := or.inr (or.inl rfl)
| [], b::l₂ := or.inl nil
| a::l₁, [] := or.inr (or.inr nil)
| a::l₁, b::l₂ := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match l₁ l₂).imp cons
(or.imp (congr_arg _) cons) },
{ exact or.inr (or.inr (rel ab)) }
end
end⟩
instance is_asymm (r : α → α → Prop)
[is_asymm α r] : is_asymm (list α) (lex r) :=
⟨λ l₁, match l₁ with
| a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂
| a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁
| a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂
| a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ :=
by exact _match _ _ h₁ h₂
end⟩
instance is_strict_total_order (r : α → α → Prop)
[is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) :=
{..is_strict_weak_order_of_is_order_connected}
instance decidable_rel [decidable_eq α] (r : α → α → Prop)
[decidable_rel r] : decidable_rel (lex r)
| l₁ [] := is_false $ λ h, by cases h
| [] (b::l₂) := is_true lex.nil
| (a::l₁) (b::l₂) := begin
haveI := decidable_rel l₁ l₂,
refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩,
{ rcases h with h | ⟨rfl, h⟩,
{ exact lex.rel h },
{ exact lex.cons h } },
{ rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩,
{ exact or.inr ⟨rfl, h⟩ },
{ exact or.inl h } }
end
theorem append_right (r : α → α → Prop) :
∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t)
| _ _ t nil := nil
| _ _ t (cons h) := cons (append_right _ h)
| _ _ t (rel r) := rel r
theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) :
∀ s, lex R (s ++ t₁) (s ++ t₂)
| [] := h
| (a::l) := cons (append_left l)
theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) :
∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂
| _ _ nil := nil
| _ _ (cons h) := cons (imp _ _ h)
| _ _ (rel r) := rel (H _ _ r)
theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂
| _ _ (cons h) e := to_ne h (list.cons.inj e).2
| _ _ (rel r) e := r (list.cons.inj e).1
theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) :
lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨to_ne, λ h, begin
induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂,
{ contradiction },
{ apply nil },
{ exact (not_lt_of_ge H).elim (succ_pos _) },
{ cases classical.em (a = b) with ab ab,
{ subst b, apply cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact rel ab } }
end⟩
end lex
--Note: this overrides an instance in core lean
instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩
theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l :=
lex.nil
instance [linear_order α] : linear_order (list α) :=
linear_order_of_STO' (lex (<))
--Note: this overrides an instance in core lean
instance has_le' [linear_order α] : has_le (list α) :=
preorder.to_has_le _
/-! ### all & any -/
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) :
all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
simp only [all_cons, band_coe_iff, ih, forall_mem_cons]
end
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp only [all_iff_forall, bool.of_to_bool_iff]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) :
any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_false bool.not_ff (not_exists_mem_nil _) },
simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff]
end
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
@[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/-! ### map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β
| [] H := []
| (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {l : list α} (hx : x ∈ l) :
sizeof x < sizeof l :=
begin
induction l with h t ih; cases hx,
{ rw hx, exact lt_add_of_lt_of_nonneg (lt_one_add _) (nat.zero_le _) },
{ exact lt_add_of_pos_of_le (zero_lt_one_add _) (le_of_lt (ih hx)) }
end
theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) :
@pmap _ _ p (λ a _, f a) l H = map f l :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f l H₁ = pmap g l H₂ :=
by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]]
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_map {p : β → Prop} (g : ∀ b, p b → γ) (f : α → β)
(l H) : pmap g (map f l) H = pmap (λ a h, g (f a) h) l (λ a h, H _ (mem_map_of_mem _ h)) :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) :=
by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl)
theorem attach_map_val (l : list α) : l.attach.map subtype.val = l :=
by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l)
@[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ :=
by have := mem_map.1 (by rw [attach_map_val]; exact h);
{ rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m }
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b :=
by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists]
@[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β}
{l H} : length (pmap f l H) = length l :=
by induction l; [refl, simp only [*, pmap, length]]
@[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap
@[simp] lemma pmap_eq_nil {p : α → Prop} {f : Π a, p a → β}
{l H} : pmap f l H = [] ↔ l = [] :=
by rw [← length_eq_zero, length_pmap, length_eq_zero]
@[simp] lemma attach_eq_nil (l : list α) : l.attach = [] ↔ l = [] := pmap_eq_nil
lemma last_pmap {α β : Type*} (p : α → Prop) (f : Π a, p a → β)
(l : list α) (hl₁ : ∀ a ∈ l, p a) (hl₂ : l ≠ []) :
(l.pmap f hl₁).last (mt list.pmap_eq_nil.1 hl₂) = f (l.last hl₂) (hl₁ _ (list.last_mem hl₂)) :=
begin
induction l with l_hd l_tl l_ih,
{ apply (hl₂ rfl).elim },
{ cases l_tl,
{ simp },
{ apply l_ih } }
end
/-! ### find -/
section find
variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α}
@[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases h : p a,
{ simp only [find_cons_of_pos _ h, h, not_true, false_and] },
{ rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] }
end
theorem find_some (H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, exact h },
{ rw find_cons_of_neg _ h at H, exact IH H }
end
@[simp] theorem find_mem (H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self },
{ rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) }
end
end find
/-! ### lookmap -/
section lookmap
variables (f : α → option α)
@[simp] theorem lookmap_nil : [].lookmap f = [] := rfl
@[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) :
(a :: l).lookmap f = a :: l.lookmap f :=
by simp [lookmap, h]
@[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) :
(a :: l).lookmap f = b :: l :=
by simp [lookmap, h]
theorem lookmap_some : ∀ l : list α, l.lookmap some = l
| [] := rfl
| (a::l) := rfl
theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l
| [] := rfl
| (a::l) := congr_arg (cons a) (lookmap_none l)
theorem lookmap_congr {f g : α → option α} :
∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g
| [] H := rfl
| (a::l) H := begin
cases forall_mem_cons.1 H with H₁ H₂,
cases h : g a with b,
{ simp [h, H₁.trans h, lookmap_congr H₂] },
{ simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] }
end
theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l :=
(lookmap_congr H).trans (lookmap_none l)
theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) :
∀ l : list α, map g (l.lookmap f) = map g l
| [] := rfl
| (a::l) := begin
cases h' : f a with b,
{ simp [h', lookmap_map_eq] },
{ simp [lookmap_cons_some _ _ h', h _ _ h'] }
end
theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l :=
by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h
theorem length_lookmap (l : list α) : length (l.lookmap f) = length l :=
by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp
end lookmap
/-! ### filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp only [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp only [filter_map, h]; split; refl
lemma filter_map_append {α β : Type*} (l l' : list α) (f : α → option β) :
filter_map f (l ++ l') = filter_map f l ++ filter_map f l' :=
begin
induction l with hd tl hl generalizing l',
{ simp },
{ rw [cons_append, filter_map, filter_map],
cases f hd;
simp only [filter_map, hl, cons_append, eq_self_iff_true, and_self] }
end
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {refl},
simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {refl},
by_cases pa : p a,
{ simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl },
{ simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] }
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp only [h, option.none_bind'] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp only [h, h', option.some_bind']
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases h : p x,
{ simp only [option.guard, if_pos h, option.some_bind'] },
{ simp only [option.guard, if_neg h, option.none_bind'] }
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH,
{ split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } },
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, this, exists_eq_left] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp only [map_filter_map, H, filter_map_some]
theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp only [filter_map]; cases f a with b;
simp only [filter_map, IH, sublist.cons, sublist.cons2]
theorem sublist.map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
filter_map_eq_map f ▸ s.filter_map _
/-! ### reduce_option -/
@[simp] lemma reduce_option_cons_of_some (x : α) (l : list (option α)) :
reduce_option (some x :: l) = x :: l.reduce_option :=
by simp only [reduce_option, filter_map, id.def, eq_self_iff_true, and_self]
@[simp] lemma reduce_option_cons_of_none (l : list (option α)) :
reduce_option (none :: l) = l.reduce_option :=
by simp only [reduce_option, filter_map, id.def]
@[simp] lemma reduce_option_nil : @reduce_option α [] = [] := rfl
@[simp] lemma reduce_option_map {l : list (option α)} {f : α → β} :
reduce_option (map (option.map f) l) = map f (reduce_option l) :=
begin
induction l with hd tl hl,
{ simp only [reduce_option_nil, map_nil] },
{ cases hd;
simpa only [true_and, option.map_some', map, eq_self_iff_true,
reduce_option_cons_of_some] using hl },
end
lemma reduce_option_append (l l' : list (option α)) :
(l ++ l').reduce_option = l.reduce_option ++ l'.reduce_option :=
filter_map_append l l' id
lemma reduce_option_length_le (l : list (option α)) :
l.reduce_option.length ≤ l.length :=
begin
induction l with hd tl hl,
{ simp only [reduce_option_nil, length] },
{ cases hd,
{ exact nat.le_succ_of_le hl },
{ simpa only [length, add_le_add_iff_right, reduce_option_cons_of_some] using hl} }
end
lemma reduce_option_length_eq_iff {l : list (option α)} :
l.reduce_option.length = l.length ↔ ∀ x ∈ l, option.is_some x :=
begin
induction l with hd tl hl,
{ simp only [forall_const, reduce_option_nil, not_mem_nil,
forall_prop_of_false, eq_self_iff_true, length, not_false_iff] },
{ cases hd,
{ simp only [mem_cons_iff, forall_eq_or_imp, bool.coe_sort_ff, false_and,
reduce_option_cons_of_none, length, option.is_some_none, iff_false],
intro H,
have := reduce_option_length_le tl,
rw H at this,
exact absurd (nat.lt_succ_self _) (not_lt_of_le this) },
{ simp only [hl, true_and, mem_cons_iff, forall_eq_or_imp, add_left_inj,
bool.coe_sort_tt, length, option.is_some_some, reduce_option_cons_of_some] } }
end
lemma reduce_option_length_lt_iff {l : list (option α)} :
l.reduce_option.length < l.length ↔ none ∈ l :=
begin
convert not_iff_not.mpr reduce_option_length_eq_iff;
simp [lt_iff_le_and_ne, reduce_option_length_le l, option.is_none_iff_eq_none]
end
lemma reduce_option_singleton (x : option α) :
[x].reduce_option = x.to_list :=
by cases x; refl
lemma reduce_option_concat (l : list (option α)) (x : option α) :
(l.concat x).reduce_option = l.reduce_option ++ x.to_list :=
begin
induction l with hd tl hl generalizing x,
{ cases x;
simp [option.to_list] },
{ simp only [concat_eq_append, reduce_option_append] at hl,
cases hd;
simp [hl, reduce_option_append] }
end
lemma reduce_option_concat_of_some (l : list (option α)) (x : α) :
(l.concat (some x)).reduce_option = l.reduce_option.concat x :=
by simp only [reduce_option_nil, concat_eq_append, reduce_option_append, reduce_option_cons_of_some]
lemma reduce_option_mem_iff {l : list (option α)} {x : α} :
x ∈ l.reduce_option ↔ (some x) ∈ l :=
by simp only [reduce_option, id.def, mem_filter_map, exists_eq_right]
lemma reduce_option_nth_iff {l : list (option α)} {x : α} :
(∃ i, l.nth i = some (some x)) ↔ ∃ i, l.reduce_option.nth i = some x :=
by rw [←mem_iff_nth, ←mem_iff_nth, reduce_option_mem_iff]
/-! ### filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
theorem filter_eq_foldr (p : α → Prop) [decidable_pred p] (l : list α) :
filter p l = foldr (λ a out, if p a then a :: out else out) [] l :=
by induction l; simp [*, filter]
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
: ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l
| [] _ := rfl
| (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a;
[simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2],
simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]];
split; refl
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
(filter_sublist l).subset
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self
| (b::l) (or.inr ain) pa := if pb : p b
then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa
else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases p a,
{ rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] },
{ rw [filter_cons_of_neg _ h],
refine iff_of_false _ (mt and.left h), intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) }
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and]
variable (p)
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
filter_map_eq_filter p ▸ s.filter_map _
theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) :=
by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl
@[simp] theorem filter_filter (q) [decidable_pred q] : ∀ l,
filter p (filter q l) = filter (λ a, p a ∧ q a) l
| [] := rfl
| (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false,
true_and, false_and, filter_filter l, eq_self_iff_true]
@[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) :
@filter α (λ _, true) h l = l :=
by convert filter_eq_self.2 (λ _ _, trivial)
@[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) :
@filter α (λ _, false) h l = [] :=
by convert filter_eq_nil.2 (λ _ _, id)
@[simp] theorem span_eq_take_drop : ∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) :=
if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while]
else by simp only [span, take_while, drop_while, if_neg pa]
@[simp] theorem take_while_append_drop : ∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append,
take_while_append_drop l]
else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append]
@[simp] theorem countp_nil : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l ih; [refl, by_cases (p x)];
[simp only [filter_cons_of_pos _ h, countp, ih, if_pos h],
simp only [countp_cons_of_neg _ _ h, ih, filter_cons_of_neg _ h]]; refl
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp only [countp_eq_length_filter, filter_append, length_append]
theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a :=
by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop]
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter p s)
@[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) :
countp p (filter q l) = countp (λ a, p a ∧ q a) l :=
by simp only [countp_eq_length_filter, filter_filter]
end filter
/-! ### count -/
section count
variable [decidable_eq α]
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
begin rw count_cons, split_ifs; refl end
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length),
l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0
| (_ :: _) a h := by { rw [count_cons], split_ifs; simp }
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist _
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append _
theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by simp [-add_comm]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp only [count, countp_pos, exists_prop, exists_eq_right']
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} :
n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩
theorem repeat_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) :
repeat a (count a l) = l :=
eq_of_sublist_of_length_eq (le_count_iff_repeat_sublist.mp (le_refl (count a l)))
(eq.trans (length_repeat a (count a l)) h)
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {l : list α} (h : p a) : count a (filter p l) = count a l :=
by simp only [count, countp_filter]; congr; exact
set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h))
end count
/-! ### prefix, suffix, infix -/
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
@[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) :=
by rw ← list.append_assoc; apply infix_append
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp only [reverse_reverse]
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_right_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_right_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix
theorem tail_subset (l : list α) : tail l ⊆ l := (sublist_of_suffix (tail_suffix l)).subset
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} :
l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
lemma prefix_take_le_iff {L : list (list (option α))} {m n : ℕ} (hm : m < L.length) :
(take m L) <+: (take n L) ↔ m ≤ n :=
begin
simp only [prefix_iff_eq_take, length_take],
induction m with m IH generalizing L n,
{ simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] },
{ cases n,
{ simp only [nat.nat_zero_eq_zero, le_zero_iff_eq, take, take_nil],
split,
{ cases L,
{ exact absurd hm (not_lt_of_le m.succ.zero_le) },
{ simp only [forall_prop_of_false, not_false_iff, take] } },
{ intro h,
contradiction } },
{ cases L with l ls,
{ exact absurd hm (not_lt_of_le m.succ.zero_le) },
{ simp only [length] at hm,
specialize @IH ls n (nat.lt_of_succ_lt_succ hm),
simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH,
simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take],
exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ } } },
end
lemma cons_prefix_iff {l l' : list α} {x y : α} :
x :: l <+: y :: l' ↔ x = y ∧ l <+: l' :=
begin
split,
{ rintro ⟨L, hL⟩,
simp only [cons_append] at hL,
exact ⟨hL.left, ⟨L, hL.right⟩⟩ },
{ rintro ⟨rfl, h⟩,
rwa [prefix_cons_inj] },
end
lemma map_prefix {l l' : list α} (f : α → β) (h : l <+: l') :
l.map f <+: l'.map f :=
begin
induction l with hd tl hl generalizing l',
{ simp only [nil_prefix, map_nil] },
{ cases l' with hd' tl',
{ simpa only using eq_nil_of_prefix_nil h },
{ rw cons_prefix_iff at h,
simp only [h, prefix_cons_inj, hl, map] } },
end
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton],
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp only [tails, mem_singleton];
exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t];
exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| ._, t, or.inl rfl := suffix_refl _
| s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inl rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩)
end⟩
lemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) :=
by simp
lemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails :=
by simp
@[simp]
lemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l)
| [] [] := by simp
| [] (a::t) := by simp
| (a::s) t := by simp [inits_append s t]
@[simp]
lemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail
| [] [] := by simp
| [] (a::t) := by simp
| (a::s) t := by simp [tails_append s t]
-- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'`
lemma inits_eq_tails :
∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l)
| [] := by simp
| (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff]
lemma tails_eq_inits :
∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l)
| [] := by simp
| (a :: l) := by simp [tails_eq_inits l, append_left_inj]
lemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) :=
by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], }
lemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) :=
by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], }
lemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) :=
by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], }
lemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) :=
by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], }
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/-! ### sublists -/
@[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl
@[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl
theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) :
map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) :
sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_eq_sublists' (l f r) :
@sublists'_aux α β l f r = map f (sublists' l) ++ r :=
by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl
@[simp] theorem sublists'_cons (a : α) (l : list α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) :=
by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl
@[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t :=
begin
induction t with a t IH generalizing s,
{ simp only [sublists'_nil, mem_singleton],
exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ },
simp only [sublists'_cons, mem_append, IH, mem_map],
split; intro h, rcases h with h | ⟨s, h, rfl⟩,
{ exact sublist_cons_of_sublist _ h },
{ exact cons_sublist_cons _ h },
{ cases h with _ _ _ h s _ _ h,
{ exact or.inl h },
{ exact or.inr ⟨s, h, rfl⟩ } }
end
@[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l
| [] := rfl
| (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map,
length, pow_succ', mul_succ, mul_zero, zero_add]
@[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl
@[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl
theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β),
sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r)
| [] f := rfl
| (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc]
theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) :
sublists_aux l cons = sublists_aux₁ l (λ x, [x]) :=
by rw [sublists_aux₁_eq_sublists_aux]; refl
theorem sublists_aux_eq_foldr.aux {a : α} {l : list α}
(IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons))
(IH₂ : ∀ (f : list α → list (list α) → list (list α)),
sublists_aux l f = foldr f [] (sublists_aux l cons))
(f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) :=
begin
simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1,
induction sublists_aux l cons with _ _ ih, {refl},
simp only [ih, foldr_cons]
end
theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons) :=
suffices _ ∧ ∀ f : list α → list (list α) → list (list α),
sublists_aux l f = foldr f [] (sublists_aux l cons),
from this.1,
begin
induction l with a l IH, {split; intro; refl},
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2,
sublists_aux_eq_foldr.aux IH.2 IH.2⟩
end
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldr]; refl
theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β),
sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++
sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x)))
| [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil]
| (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc];
refl
theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) :
sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++
f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) :=
by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil]
theorem sublists_aux₁_bind : ∀ (l : list α)
(f : list α → list β) (g : β → list γ),
(sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g)
| [] f g := rfl
| (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l]
theorem sublists_aux_cons_append (l₁ l₂ : list α) :
sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++
(do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) :=
begin
simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind,
sublists_aux₁_bind],
congr, funext x, apply congr_arg _,
rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm
end
theorem sublists_append (l₁ l₂ : list α) :
sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) :=
by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind,
cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl
@[simp] theorem sublists_concat (l : list α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) :=
by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind,
map_eq_map, map_eq_map, map_id' (append_nil), append_nil]
theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) :=
by induction l with hd tl ih; [refl,
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]]
theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) :=
by rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) :=
by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)]
theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) :=
by rw [← sublists'_reverse, reverse_reverse]
theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons
| [] := id
| (a::l) := begin
rw [sublists_aux_cons_cons],
refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _,
have := sublists_aux_ne_nil l, revert this,
induction sublists_aux l cons; intro, {rwa foldr},
simp only [foldr, mem_cons_iff, false_or, not_or_distrib],
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
end
@[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t :=
by rw [← reverse_sublist_iff, ← mem_sublists',
sublists'_reverse, mem_map_of_injective reverse_injective]
@[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l :=
by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l :=
reverse_rec_on l (nil_sublist _) $
λ l a IH, by simp only [map, map_append, sublists_concat]; exact
((append_sublist_append_left _).2 $ singleton_sublist.2 $
mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans
((append_sublist_append_right _).2 IH)
/-! ### sublists_len -/
/-- Auxiliary function to construct the list of all sublists of a given length. Given an
integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of
of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/
def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β
| 0 l f r := f [] :: r
| (n+1) [] f r := r
| (n+1) (a::l) f r := sublists_len_aux (n + 1) l f
(sublists_len_aux n l (f ∘ list.cons a) r)
/-- The list of all sublists of a list `l` that are of length `n`. For instance, for
`l = [0, 1, 2, 3]` and `n = 2`, one gets
`[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/
def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) :=
sublists_len_aux n l id []
lemma sublists_len_aux_append {α β γ : Type*} :
∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ),
sublists_len_aux n l (g ∘ f) (r.map g ++ s) =
(sublists_len_aux n l f r).map g ++ s
| 0 l f g r s := rfl
| (n+1) [] f g r s := rfl
| (n+1) (a::l) f g r s := begin
unfold sublists_len_aux,
rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl,
sublists_len_aux_append, sublists_len_aux_append]
end
lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) :
sublists_len_aux n l f r = (sublists_len n l).map f ++ r :=
by rw [sublists_len, ← sublists_len_aux_append]; refl
lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) :
sublists_len_aux 0 l f r = f [] :: r := by cases l; refl
@[simp] lemma sublists_len_zero {α : Type*} (l : list α) :
sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _
@[simp] lemma sublists_len_succ_nil {α : Type*} (n) :
sublists_len (n+1) (@nil α) = [] := rfl
@[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) :
sublists_len (n + 1) (a::l) =
sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) :=
by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq,
sublists_len_aux_eq, map_id, append_nil]; refl
@[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α),
length (sublists_len n l) = nat.choose (length l) n
| 0 l := by simp
| (n+1) [] := by simp
| (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm
lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α),
sublists_len n l <+ sublists' l
| 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _))
| (n+1) [] := nil_sublist _
| (n+1) (a::l) := begin
rw [sublists_len_succ_cons, sublists'_cons],
exact (sublists_len_sublist_sublists' _ _).append
((sublists_len_sublist_sublists' _ _).map _)
end
lemma sublists_len_sublist_of_sublist
{α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl},
{ refine IH.trans _,
rw sublists_len_succ_cons,
apply sublist_append_left },
{ simp [sublists_len_succ_cons],
exact IH.append ((IHn s).map _) }
end
lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α},
l' ∈ sublists_len n l → length l' = n
| 0 l l' (or.inl rfl) := rfl
| (n+1) (a::l) l' h := begin
rw [sublists_len_succ_cons, mem_append, mem_map] at h,
rcases h with h | ⟨l', h, rfl⟩,
{ exact length_of_sublists_len h },
{ exact congr_arg (+1) (length_of_sublists_len h) },
end
lemma mem_sublists_len_self {α : Type*} {l l' : list α}
(h : l' <+ l) : l' ∈ sublists_len (length l') l :=
begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH,
{ exact or.inl rfl },
{ cases l₁ with b l₁,
{ exact or.inl rfl },
{ rw [length, sublists_len_succ_cons],
exact mem_append_left _ IH } },
{ rw [length, sublists_len_succ_cons],
exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) }
end
@[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} :
l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n :=
⟨λ h, ⟨mem_sublists'.1
((sublists_len_sublist_sublists' _ _).subset h),
length_of_sublists_len h⟩,
λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩
/-! ### permutations -/
section permutations
@[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by rw [permutations_aux, permutations_aux.rec]
@[simp] theorem permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by rw [permutations_aux, permutations_aux.rec]; refl
end permutations
/-! ### insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp, priority 980]
theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp only [insert.def, if_pos h]
@[simp, priority 970]
theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp only [insert.def, if_neg h]; split; refl
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l,
{ simp only [insert_of_mem h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h' },
simp only [insert_of_not_mem h', mem_cons_iff]
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by rw insert_of_mem h
@[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by rw insert_of_not_mem h; refl
end insert
/-! ### erasep -/
section erasep
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem erasep_nil : [].erasep p = [] := rfl
theorem erasep_cons (a : α) (l : list α) :
(a :: l).erasep p = if p a then l else a :: l.erasep p := rfl
@[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l :=
by simp [erasep_cons, h]
@[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) :
(a::l).erasep p = a :: l.erasep p :=
by simp [erasep_cons, h]
theorem erasep_of_forall_not {l : list α}
(h : ∀ a ∈ l, ¬ p a) : l.erasep p = l :=
by induction l with _ _ ih; [refl,
simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]]
theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) :
∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
induction l with b l IH, {cases al},
by_cases pb : p b,
{ exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ },
{ rcases al with rfl | al, {exact pb.elim pa},
rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩,
h₂, by rw h₃; refl, by simp [pb, h₄]⟩ }
end
theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) :
l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
by_cases h : ∃ a ∈ l, p a,
{ rcases h with ⟨a, ha, pa⟩,
exact or.inr (exists_of_erasep ha pa) },
{ simp at h, exact or.inl (erasep_of_forall_not h) }
end
@[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) :
length (l.erasep p) = pred (length l) :=
by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩;
rw e₂; simp [-add_comm, e₁]; refl
theorem erasep_append_left {a : α} (pa : p a) :
∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : p x; simp [h'],
rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h),
rintro rfl, exact pa
end
theorem erasep_append_right :
∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1,
erasep_append_right _ (forall_mem_cons.1 h).2]
theorem erasep_sublist (l : list α) : l.erasep p <+ l :=
by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩;
[rw h, {rw [h₄, h₃], simp}]
theorem erasep_subset (l : list α) : l.erasep p ⊆ l :=
(erasep_sublist l).subset
theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p :=
begin
induction s,
case list.sublist.slnil { refl },
case list.sublist.cons : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] },
case list.sublist.cons2 : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [s, IH.cons2 _ _ _] }
end
theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l :=
@erasep_subset _ _ _ _ _
@[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l :=
⟨mem_of_mem_erasep, λ al, begin
rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
{ rwa h },
{ rw h₄, rw h₃ at al,
have : a ≠ c, {rintro rfl, exact pa.elim h₂},
simpa [this] using al }
end⟩
theorem erasep_map (f : β → α) :
∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f))
| [] := rfl
| (b::l) := by by_cases p (f b); simp [h, erasep_map l]
@[simp] theorem extractp_eq_find_erasep :
∀ l : list α, extractp p l = (find p l, erasep p l)
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l]
end erasep
/-! ### erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) :
(b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp only [erase_cons, if_pos rfl]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) :
(b::l).erase a = b :: l.erase a :=
by simp only [erase_cons, if_neg h]; split; refl
theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) :=
by { induction l with b l, {refl},
by_cases a = b; [simp [h], simp [h, ne.symm h, *]] }
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h'
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩;
rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (l.erase a) = pred (length l) :=
by rw erase_eq_erasep; exact length_erasep_of_mem h rfl
theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) :
(l₁++l₂).erase a = l₁.erase a ++ l₂ :=
by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h
theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) :
(l₁++l₂).erase a = l₁ ++ l₂.erase a :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right];
rintro b h' rfl; exact h h'
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
by rw erase_eq_erasep; apply erasep_sublist
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
(erase_sublist a l).subset
theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a :=
by simp [erase_eq_erasep]; exact sublist.erasep h
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by rw ab else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)]
else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)]
theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α}
(l : list α) : map f (l.erase a) = (map f l).erase (f a) :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr;
ext b; simp [finj.eq_iff]
theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ :=
by induction l₂ generalizing l₁; [refl,
simp only [foldl_cons, map_erase finj, *]]
@[simp] theorem count_erase_self (a : α) :
∀ (s : list α), count a (list.erase s a) = pred (count a s)
| [] := by simp
| (h :: t) :=
begin
rw erase_cons,
by_cases p : h = a,
{ rw [if_pos p, count_cons', if_pos p.symm], simp },
{ rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self],
simp, }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) :
∀ (s : list α), count a (list.erase s b) = count a s
| [] := by simp
| (x :: xs) :=
begin
rw erase_cons,
split_ifs with h,
{ rw [count_cons', h, if_neg ab], simp },
{ rw [count_cons', count_cons', count_erase_of_ne] }
end
end erase
/-! ### diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
if h : a ∈ l₁ then by simp only [list.diff, if_pos h]
else by simp only [list.diff, if_neg h, erase_of_not_mem h]
@[simp] theorem nil_diff (l : list α) : [].diff l = [] :=
by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp only [diff_eq_foldl, foldl_append]
@[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) :=
by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁
| l₁ [] := sublist.refl _
| l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _
... <+ l₁.erase a : diff_sublist _ _
... <+ l₁ : list.erase_sublist _ _
theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ :=
(diff_sublist _ _).subset
theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂
| l₁ [] h₁ h₂ := h₁
| l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact
mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂)
theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃
| l₁ l₂ [] h := h
| l₁ l₂ (a::l₃) h := by simp only
[diff_cons, (h.erase _).diff_right]
theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α},
l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [] l₂ h := erase_sublist _ _
| (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]
else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons,
erase_comm a b l₂]
using erase_diff_erase_sublist_of_sublist (h.erase b)
end diff
/-! ### enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp only [enum, enum_from_nth, zero_add]; intros; refl
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
theorem mem_enum_from {x : α} {i : ℕ} :
∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs
| j [] := by simp [enum_from]
| j (y :: ys) :=
suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys →
j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys),
by simpa [enum_from, mem_enum_from ys],
begin
rintro (h|h),
{ refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩,
apply nat.lt_add_of_pos_right; simp },
{ obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h,
refine ⟨_, _, _⟩,
{ exact le_trans (nat.le_succ _) hji },
{ convert hijlen using 1, ac_refl },
{ simp [hmem] } }
end
/-! ### product -/
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; [exact (zero_mul _).symm,
simp only [length, product_cons, length_append, IH,
right_distrib, one_mul, length_map, add_comm]]
/-! ### sigma -/
section
variable {σ : α → Type*}
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left,
and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; [refl,
simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]]
end
/-! ### disjoint -/
section disjoint
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) :
disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) :
disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] :=
by rw disjoint_comm; exact disjoint_nil_left _
@[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp only [disjoint, mem_singleton, forall_eq]; refl
@[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp only [singleton_disjoint]
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint]
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₂ :=
(disjoint_append_right.1 d).2
theorem disjoint_take_drop {l : list α} {m n : ℕ} (hl : l.nodup) (h : m ≤ n) :
disjoint (l.take m) (l.drop n) :=
begin
induction l generalizing m n,
case list.nil : m n
{ simp },
case list.cons : x xs xs_ih m n
{ cases m; cases n; simp only [disjoint_cons_left, mem_cons_iff, disjoint_cons_right, drop,
true_or, eq_self_iff_true, not_true, false_and,
disjoint_nil_left, take],
{ cases h },
cases hl with _ _ h₀ h₁, split,
{ intro h, exact h₀ _ (mem_of_mem_drop h) rfl, },
solve_by_elim [le_of_succ_le_succ] { max_depth := 4 } },
end
end disjoint
/-! ### union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff,
mem_cons_iff, or_assoc, *]
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
if h : a ∈ l₁ ∪ l₂
then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩
else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h];
split; refl⟩
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp (λ a, and.right)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_union, or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/-! ### inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
@[simp] lemma inter_reverse {xs ys : list α} :
xs.inter ys.reverse = xs.inter ys :=
by simp only [list.inter, mem_reverse]; congr
end inter
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
/-! ### map₂_left' -/
section map₂_left'
-- The definitional equalities for `map₂_left'` can already be used by the
-- simplifie because `map₂_left'` is marked `@[simp]`.
@[simp] theorem map₂_left'_nil_right (f : α → option β → γ) (as) :
map₂_left' f as [] = (as.map (λ a, f a none), []) :=
by cases as; refl
end map₂_left'
/-! ### map₂_right' -/
section map₂_right'
variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem map₂_right'_nil_left :
map₂_right' f [] bs = (bs.map (f none), []) :=
by cases bs; refl
@[simp] theorem map₂_right'_nil_right :
map₂_right' f as [] = ([], as) :=
rfl
@[simp] theorem map₂_right'_nil_cons :
map₂_right' f [] (b :: bs) = (f none b :: bs.map (f none), []) :=
rfl
@[simp] theorem map₂_right'_cons_cons :
map₂_right' f (a :: as) (b :: bs) =
let rec := map₂_right' f as bs in
(f (some a) b :: rec.fst, rec.snd) :=
rfl
end map₂_right'
/-! ### zip_left' -/
section zip_left'
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_left'_nil_right :
zip_left' as ([] : list β) = (as.map (λ a, (a, none)), []) :=
by cases as; refl
@[simp] theorem zip_left'_nil_left :
zip_left' ([] : list α) bs = ([], bs) :=
rfl
@[simp] theorem zip_left'_cons_nil :
zip_left' (a :: as) ([] : list β) = ((a, none) :: as.map (λ a, (a, none)), []) :=
rfl
@[simp] theorem zip_left'_cons_cons :
zip_left' (a :: as) (b :: bs) =
let rec := zip_left' as bs in
((a, some b) :: rec.fst, rec.snd) :=
rfl
end zip_left'
/-! ### zip_right' -/
section zip_right'
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_right'_nil_left :
zip_right' ([] : list α) bs = (bs.map (λ b, (none, b)), []) :=
by cases bs; refl
@[simp] theorem zip_right'_nil_right :
zip_right' as ([] : list β) = ([], as) :=
rfl
@[simp] theorem zip_right'_nil_cons :
zip_right' ([] : list α) (b :: bs) = ((none, b) :: bs.map (λ b, (none, b)), []) :=
rfl
@[simp] theorem zip_right'_cons_cons :
zip_right' (a :: as) (b :: bs) =
let rec := zip_right' as bs in
((some a, b) :: rec.fst, rec.snd) :=
rfl
end zip_right'
/-! ### map₂_left -/
section map₂_left
variables (f : α → option β → γ) (as : list α)
-- The definitional equalities for `map₂_left` can already be used by the
-- simplifier because `map₂_left` is marked `@[simp]`.
@[simp] theorem map₂_left_nil_right :
map₂_left f as [] = as.map (λ a, f a none) :=
by cases as; refl
theorem map₂_left_eq_map₂_left' : ∀ as bs,
map₂_left f as bs = (map₂_left' f as bs).fst
| [] bs := by simp!
| (a :: as) [] := by simp!
| (a :: as) (b :: bs) := by simp! [*]
theorem map₂_left_eq_map₂ : ∀ as bs,
length as ≤ length bs →
map₂_left f as bs = map₂ (λ a b, f a (some b)) as bs
| [] [] h := by simp!
| [] (b :: bs) h := by simp!
| (a :: as) [] h := by { simp at h, contradiction }
| (a :: as) (b :: bs) h := by { simp at h, simp! [*] }
end map₂_left
/-! ### map₂_right -/
section map₂_right
variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem map₂_right_nil_left :
map₂_right f [] bs = bs.map (f none) :=
by cases bs; refl
@[simp] theorem map₂_right_nil_right :
map₂_right f as [] = [] :=
rfl
@[simp] theorem map₂_right_nil_cons :
map₂_right f [] (b :: bs) = f none b :: bs.map (f none) :=
rfl
@[simp] theorem map₂_right_cons_cons :
map₂_right f (a :: as) (b :: bs) = f (some a) b :: map₂_right f as bs :=
rfl
theorem map₂_right_eq_map₂_right' :
map₂_right f as bs = (map₂_right' f as bs).fst :=
by simp only [map₂_right, map₂_right', map₂_left_eq_map₂_left']
theorem map₂_right_eq_map₂ (h : length bs ≤ length as) :
map₂_right f as bs = map₂ (λ a b, f (some a) b) as bs :=
begin
have : (λ a b, flip f a (some b)) = (flip (λ a b, f (some a) b)) := rfl,
simp only [map₂_right, map₂_left_eq_map₂, map₂_flip, *]
end
end map₂_right
/-! ### zip_left -/
section zip_left
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_left_nil_right :
zip_left as ([] : list β) = as.map (λ a, (a, none)) :=
by cases as; refl
@[simp] theorem zip_left_nil_left :
zip_left ([] : list α) bs = [] :=
rfl
@[simp] theorem zip_left_cons_nil :
zip_left (a :: as) ([] : list β) = (a, none) :: as.map (λ a, (a, none)) :=
rfl
@[simp] theorem zip_left_cons_cons :
zip_left (a :: as) (b :: bs) = (a, some b) :: zip_left as bs :=
rfl
theorem zip_left_eq_zip_left' :
zip_left as bs = (zip_left' as bs).fst :=
by simp only [zip_left, zip_left', map₂_left_eq_map₂_left']
end zip_left
/-! ### zip_right -/
section zip_right
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_right_nil_left :
zip_right ([] : list α) bs = bs.map (λ b, (none, b)) :=
by cases bs; refl
@[simp] theorem zip_right_nil_right :
zip_right as ([] : list β) = [] :=
rfl
@[simp] theorem zip_right_nil_cons :
zip_right ([] : list α) (b :: bs) = (none, b) :: bs.map (λ b, (none, b)) :=
rfl
@[simp] theorem zip_right_cons_cons :
zip_right (a :: as) (b :: bs) = (some a, b) :: zip_right as bs :=
rfl
theorem zip_right_eq_zip_right' :
zip_right as bs = (zip_right' as bs).fst :=
by simp only [zip_right, zip_right', map₂_right_eq_map₂_right']
end zip_right
/-! ### Miscellaneous lemmas -/
theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l
| a [] := or.inl rfl
| a (b::l) := or.inr (ilast'_mem b l)
@[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) :
(L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) :=
calc (L.attach.nth_le i H).1
= (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map'
... = L.nth_le i _ : by congr; apply attach_map_val
end list
@[to_additive]
theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) :
f l.prod = (l.map f).prod :=
(l.prod_hom f).symm
namespace list
@[to_additive]
theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) :
(L.map (g ∘ f)).prod = g ((L.map f).prod) :=
by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm}
theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, r * f b)).sum = r * (L.map f).sum :=
sum_map_hom L f $ add_monoid_hom.mul_left r
theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, f b * r)).sum = (L.map f).sum * r :=
sum_map_hom L f $ add_monoid_hom.mul_right r
universes u v
@[simp]
theorem mem_map_swap {α : Type u} {β : Type v} (x : α) (y : β) (xs : list (α × β)) :
(y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs :=
begin
induction xs with x xs,
{ simp only [not_mem_nil, map_nil] },
{ cases x with a b,
simp only [mem_cons_iff, prod.mk.inj_iff, map, prod.swap_prod_mk, prod.exists, xs_ih],
tauto! },
end
lemma slice_eq {α} (xs : list α) (n m : ℕ) :
slice n m xs = xs.take n ++ xs.drop (n+m) :=
begin
induction n generalizing xs,
{ simp [slice] },
{ cases xs; simp [slice, *, nat.succ_add], }
end
lemma sizeof_slice_lt {α} [has_sizeof α] (i j : ℕ) (hj : 0 < j) (xs : list α) (hi : i < xs.length) :
sizeof (list.slice i j xs) < sizeof xs :=
begin
induction xs generalizing i j,
case list.nil : i j h
{ cases hi },
case list.cons : x xs xs_ih i j h
{ cases i; simp only [-slice_eq, list.slice],
{ cases j, cases h,
dsimp only [drop], unfold_wf,
apply @lt_of_le_of_lt _ _ _ xs.sizeof,
{ clear_except,
induction xs generalizing j; unfold_wf,
case list.nil : j
{ refl },
case list.cons : xs_hd xs_tl xs_ih j
{ cases j; unfold_wf, refl,
transitivity, apply xs_ih,
simp }, },
unfold_wf, apply zero_lt_one_add, },
{ unfold_wf, apply xs_ih _ _ h,
apply lt_of_succ_lt_succ hi, } },
end
end list
|
e47bd37dd23d073c73cf3b75aff2fd3645212caf | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/tactic/monotonicity/interactive.lean | 28415e9d88002b880377417a8b81c7fa34f2fa7a | [
"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 | 23,567 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic.monotonicity.basic
import control.traversable
import control.traversable.derive
import data.dlist
variables {a b c p : Prop}
namespace tactic.interactive
open lean lean.parser interactive
open interactive.types
open tactic
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta inductive mono_function (elab : bool := tt)
| non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function
| assoc : expr elab → option (expr elab) → option (expr elab) → mono_function
| assoc_comm : expr elab → expr elab → mono_function
meta instance : decidable_eq mono_function :=
by mk_dec_eq_instance
meta def mono_function.to_tactic_format : mono_function → tactic format
| (mono_function.non_assoc fn xs ys) := do
fn' ← pp fn,
xs' ← mmap pp xs,
ys' ← mmap pp ys,
return format!"{fn'} {xs'} _ {ys'}"
| (mono_function.assoc fn xs ys) := do
fn' ← pp fn,
xs' ← pp xs,
ys' ← pp ys,
return format!"{fn'} {xs'} _ {ys'}"
| (mono_function.assoc_comm fn xs) := do
fn' ← pp fn,
xs' ← pp xs,
return format!"{fn'} _ {xs'}"
meta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function :=
{ to_tactic_format := mono_function.to_tactic_format }
@[derive traversable]
meta structure ac_mono_ctx' (rel : Type) :=
(to_rel : rel)
(function : mono_function)
(left right rel_def : expr)
@[reducible]
meta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr))
@[reducible]
meta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr)
meta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=
do fn ← pp ctx.function,
l ← pp ctx.left,
r ← pp ctx.right,
rel ← pp ctx.rel_def,
return format!"{{ function := {fn}\n, left := {l}\n, right := {r}\n, rel_def := {rel} }"
meta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx :=
{ to_tactic_format := ac_mono_ctx.to_tactic_format }
meta def as_goal (e : expr) (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
set_goals [e],
tac,
set_goals gs
open list (hiding map) functor dlist
section config
parameter opt : mono_cfg
parameter asms : list expr
meta def unify_with_instance (e : expr) : tactic unit :=
as_goal e $
apply_instance
<|>
apply_opt_param
<|>
apply_auto_param
<|>
tactic.solve_by_elim { lemmas := some asms }
<|>
reflexivity
<|>
applyc ``id
<|>
return ()
private meta def match_rule_head (p : expr)
: list expr → expr → expr → tactic expr
| vs e t :=
(unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e)
<|>
do (expr.pi _ _ d b) ← return t | failed,
v ← mk_meta_var d,
match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)
meta def pi_head : expr → tactic expr
| (expr.pi n _ t b) :=
do v ← mk_meta_var t,
pi_head (b.instantiate_var v)
| e := return e
meta def delete_expr (e : expr)
: list expr → tactic (option (list expr))
| [] := return none
| (x :: xs) :=
(compare opt e x >> return (some xs))
<|>
(map (cons x) <$> delete_expr xs)
meta def match_ac'
: list expr → list expr → tactic (list expr × list expr × list expr)
| es (x :: xs) := do
es' ← delete_expr x es,
match es' with
| (some es') := do
(c,l,r) ← match_ac' es' xs, return (x::c,l,r)
| none := do
(c,l,r) ← match_ac' es xs, return (c,l,x::r)
end
| es [] := do
return ([],es,[])
meta def match_ac (l : list expr) (r : list expr)
: tactic (list expr × list expr × list expr) :=
do (s',l',r') ← match_ac' l r,
s' ← mmap instantiate_mvars s',
l' ← mmap instantiate_mvars l',
r' ← mmap instantiate_mvars r',
return (s',l',r')
meta def match_prefix
: list expr → list expr → tactic (list expr × list expr × list expr)
| (x :: xs) (y :: ys) :=
(do compare opt x y,
prod.map ((::) x) id <$> match_prefix xs ys)
<|> return ([],x :: xs,y :: ys)
| xs ys := return ([],xs,ys)
/--
`(prefix,left,right,suffix) ← match_assoc unif l r` finds the
longest prefix and suffix common to `l` and `r` and
returns them along with the differences -/
meta def match_assoc (l : list expr) (r : list expr)
: tactic (list expr × list expr × list expr × list expr) :=
do (pre,l₁,r₁) ← match_prefix l r,
(suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁),
return (pre,reverse l₂,reverse r₂,reverse suf)
meta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr)
| (expr.app (expr.app f x) y) :=
do t ← infer_type x,
a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,
c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,
i ← try_core (do
v ← mk_meta_var t,
l_inst_p ← to_expr ``(is_left_id %%t %%f %%v),
r_inst_p ← to_expr ``(is_right_id %%t %%f %%v),
l_v ← mk_meta_var l_inst_p,
r_v ← mk_meta_var r_inst_p ,
l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v],
mk_instance l_inst_p >>= unify l_v,
r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v],
mk_instance r_inst_p >>= unify r_v,
v' ← instantiate_mvars v,
return (l_id,r_id,v')),
return (a.is_some,c.is_some,i,f)
| _ := return (ff,ff,none,expr.var 1)
meta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr)
| e :=
(do (expr.app (expr.app f' x) y) ← return e,
is_def_eq f f',
(++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y)
<|> return (singleton e)
meta def parse_assoc_chain (f : expr) : expr → tactic (list expr) :=
map dlist.to_list ∘ parse_assoc_chain' f
meta def fold_assoc (op : expr) :
option (expr × expr × expr) → list expr → option (expr × list expr)
| _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, [])
| none [] := none
| (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id])
meta def fold_assoc1 (op : expr) : list expr → option expr
| (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs
| [] := none
meta def same_function_aux
: list expr → list expr → expr → expr → tactic (expr × list expr × list expr)
| xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) :=
same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁
| xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁)
meta def same_function : expr → expr → tactic (expr × list expr × list expr) :=
same_function_aux [] []
meta def parse_ac_mono_function (l r : expr)
: tactic (expr × expr × list expr × mono_function) :=
do (full_f,ls,rs) ← same_function l r,
(a,c,i,f) ← check_ac l,
if a
then if c
then do
(s,ls,rs) ← monad.join (match_ac
<$> parse_assoc_chain f l
<*> parse_assoc_chain f r),
(l',l_id) ← fold_assoc f i ls,
(r',r_id) ← fold_assoc f i rs,
s' ← fold_assoc1 f s,
return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')
else do -- a ∧ ¬ c
(pre,ls,rs,suff) ← monad.join (match_assoc
<$> parse_assoc_chain f l
<*> parse_assoc_chain f r),
(l',l_id) ← fold_assoc f i ls,
(r',r_id) ← fold_assoc f i rs,
let pre' := fold_assoc1 f pre,
let suff' := fold_assoc1 f suff,
return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff')
else do -- ¬ a
(xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs,
return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁)
meta def parse_ac_mono_function' (l r : pexpr) :=
do l' ← to_expr l,
r' ← to_expr r,
parse_ac_mono_function l' r'
meta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx)
| `(%%e₀ → %%e₁) :=
do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,
t₀ ← infer_type e₀,
t₁ ← infer_type e₁,
rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)),
return (e₀, e₁, id_rs,
{ function := f
, left := l, right := r
, to_rel := some $ expr.pi `x binder_info.default
, rel_def := rel_def })
| `(%%e₀ = %%e₁) :=
do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,
t₀ ← infer_type e₀,
t₁ ← infer_type e₁,
rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)),
return (e₀, e₁, id_rs,
{ function := f
, left := l, right := r
, to_rel := none
, rel_def := rel_def })
| (expr.app (expr.app rel e₀) e₁) :=
do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,
return (e₀, e₁, id_rs,
{ function := f
, left := l, right := r
, to_rel := expr.app ∘ expr.app rel
, rel_def := rel })
| _ := fail "invalid monotonicity goal"
meta def bin_op_left (f : expr) : option expr → expr → expr
| none e := e
| (some e₀) e₁ := f.mk_app [e₀,e₁]
meta def bin_op (f a b : expr) : expr :=
f.mk_app [a,b]
meta def bin_op_right (f : expr) : expr → option expr → expr
| e none := e
| e₀ (some e₁) := f.mk_app [e₀,e₁]
meta def mk_fun_app : mono_function → expr → expr
| (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y)
| (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y)
| (mono_function.assoc_comm f x) z := f.mk_app [z,x]
meta inductive mono_law
/- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove
x+(y₀+z) R x+(y₁+z);
if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/
| assoc : expr × expr → expr × expr → mono_law
/- `congr r` gives the rule to prove `x = y → f x = f y` -/
| congr : expr → mono_law
| other : expr → mono_law
meta def mono_law.to_tactic_format : mono_law → tactic format
| (mono_law.other e) := do e ← pp e, return format!"other {e}"
| (mono_law.congr r) := do e ← pp r, return format!"congr {e}"
| (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=
do x₀ ← pp x₀,
x₁ ← pp x₁,
y₀ ← pp y₀,
y₁ ← pp y₁,
return format!"assoc {x₀}; {x₁} | {y₀}; {y₁}"
meta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law :=
{ to_tactic_format := mono_law.to_tactic_format }
meta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr :=
ctx.to_rel (f ctx.left) (f ctx.right)
meta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr :=
do p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁],
prod.snd <$> solve_aux p
(do iterate_exactly (xs₁.length) (applyc `congr_fun),
applyc `congr_arg)
meta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr :=
match ctx.function with
| (mono_function.assoc f x₀ x₁) :=
if (x₀ <|> x₁).is_some
then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right
else failed
| (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right
| (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right
end
meta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law :=
match (sequence ctx : option (ac_mono_ctx' _)) with
| (some ctx) :=
match ctx.function with
| (mono_function.assoc f (some x) (some y)) :=
return $ mono_law.assoc
( mk_rel ctx (λ i, bin_op f x (bin_op f i y))
, mk_rel ctx (λ i, bin_op f i y))
( mk_rel ctx (λ i, bin_op f (bin_op f x i) y)
, mk_rel ctx (λ i, bin_op f x i))
| (mono_function.assoc f (some x) none) :=
return $ mono_law.other $
mk_rel ctx (λ e, mk_fun_app ctx.function e)
| (mono_function.assoc f none (some y)) :=
return $ mono_law.other $
mk_rel ctx (λ e, mk_fun_app ctx.function e)
| (mono_function.assoc f none none) :=
none
| _ :=
return $ mono_law.other $
mk_rel ctx (λ e, mk_fun_app ctx.function e)
end
| none := mono_law.congr <$> mk_congr_law ctx
end
meta def match_rule (pat : expr) (r : name) : tactic expr :=
do r' ← mk_const r,
t ← infer_type r',
t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [
simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)],
match_rule_head pat [] r' t
meta def find_lemma (pat : expr) : list name → tactic (list expr)
| [] := return []
| (r :: rs) :=
do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs
meta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) :=
do x' ← to_expr ``(%%x₁ → %%x₀),
r₀ ← find_lemma x' ls,
r₁ ← find_lemma x₁ ls,
return (expr.app <$> r₀ <*> r₁)
meta def find_rule (ls : list name) : mono_law → tactic (list expr)
| (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=
(match_chaining_rules ls x₀ x₁)
<|> (match_chaining_rules ls y₀ y₁)
| (mono_law.congr r) := return [r]
| (mono_law.other p) := find_lemma p ls
universes u v
def apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α}
(x' y' : α)
(h : R x y)
(hx : x = x')
(hy : y = y')
: R x' y' :=
by { rw [← hx,← hy], apply h }
meta def ac_refine (e : expr) : tactic unit :=
refine ``(eq.mp _ %%e) ; ac_refl
meta def one_line (e : expr) : tactic format :=
do lbl ← pp e,
asm ← infer_type e >>= pp,
return format!"\t{asm}\n"
meta def side_conditions (e : expr) : tactic format :=
do let vs := e.list_meta_vars,
ts ← mmap one_line vs.tail,
let r := e.get_app_fn.const_name,
return format!"{r}:\n{format.join ts}"
open monad
/-- tactic-facing function, similar to `interactive.tactic.generalize` with the
exception that meta variables -/
private meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) :=
do tgt ← target,
t ← infer_type v,
tgt' ← do {
⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target),
to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) }
<|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt),
t ← head_beta (tgt' v) >>= assert h,
swap,
r ← mk_eq_refl v,
solve1 $ tactic.exact (t v r),
prod.mk <$> tactic.intro x <*> tactic.intro h
private meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit :=
focus1 $
do tgt ← target >>= instantiate_mvars,
tactic.change tgt,
ctx ← local_context,
let vs := tgt.list_meta_vars,
vs' ← mmap (λ v,
do h ← get_unused_name `h,
x ← get_unused_name `x,
prod.snd <$> monotonicity.generalize' h v x) vs,
tac ctx;
vs'.mmap' (try ∘ tactic.subst)
meta def hide_meta_vars' (tac : itactic) : itactic :=
hide_meta_vars $ λ _, tac
end config
meta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
set_goals [v],
target >>= instantiate_mvars >>= tactic.change,
tac, done,
set_goals $ gs
def list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α
| [] := []
| (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b,
let k' := f b in
if k < k' then (k,a)
else if k' < k then (k', [b])
else (k,b :: a)) (f x, [x])
open format mono_selection
meta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit :=
do t ← target,
xs ← xs.mmap (λ x,
try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)),
let xs := xs.filter_map id,
let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs,
match r with
| [(_,gs,pr)] := tactic.exact pr >> set_goals gs
| [] := fail "no good match found"
| _ :=
do lmms ← r.mmap (λ ⟨l,gs,_⟩,
do ts ← gs.mmap infer_type,
msg ← ts.mmap pp,
pure $ foldl compose "\n\n" $
list.intersperse "\n" $ to_fmt l.get_app_fn.const_name :: msg),
let msg := foldl compose "" lmms,
fail format!("ambiguous match: {msg}\n\n" ++
"Tip: try asserting a side condition to distinguish between the lemmas")
end
meta def mono_aux (dir : parse side) :
tactic unit :=
do t ← target >>= instantiate_mvars,
ns ← get_monotonicity_lemmas t dir,
asms ← local_context,
rs ← find_lemma asms t ns,
focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law)
/--
- `mono` applies a monotonicity rule.
- `mono*` applies monotonicity rules repetitively.
- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed
propositions. Those help to select the right monotonicity rule.
- `mono left` or `mono right` is useful when proving strict orderings:
for `x + y < w + z` could be broken down into either
- left: `x ≤ w` and `y < z` or
- right: `x < w` and `y ≤ z`
- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.
- The general syntax is
`mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?`
To use it, first import `tactic.monotonicity`.
Here is an example of mono:
```lean
example (x y z k : ℤ)
(h : 3 ≤ (4 : ℤ))
(h' : z ≤ y) :
(k + 3 + x) - y ≤ (k + 4 + x) - z :=
begin
mono, -- unfold `(-)`, apply add_le_add
{ -- ⊢ k + 3 + x ≤ k + 4 + x
mono, -- apply add_le_add, refl
-- ⊢ k + 3 ≤ k + 4
mono },
{ -- ⊢ -y ≤ -z
mono /- apply neg_le_neg -/ }
end
```
More succinctly, we can prove the same goal as:
```lean
example (x y z k : ℤ)
(h : 3 ≤ (4 : ℤ))
(h' : z ≤ y) :
(k + 3 + x) - y ≤ (k + 4 + x) - z :=
by mono*
```
-/
meta def mono (many : parse (tk "*")?)
(dir : parse side)
(hyps : parse $ tk "with" *> pexpr_list_or_texpr <|> pure [])
(simp_rules : parse $ tk "using" *> simp_arg_list <|> pure []) :
tactic unit :=
do hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var),
hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr),
when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip),
if many.is_some
then repeat $ mono_aux dir
else mono_aux dir,
gs ← get_goals,
set_goals $ hyps ++ gs
add_tactic_doc
{ name := "mono",
category := doc_category.tactic,
decl_names := [`tactic.interactive.mono],
tags := ["monotonicity"] }
/--
transforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas
marked as `monotonic`.
Special care is taken when `f` is the repeated application of an
associative operator and if the operator is commutative
-/
meta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) :
tactic unit :=
hide_meta_vars $ λ asms,
do try `[simp only [sub_eq_add_neg]],
tgt ← target >>= instantiate_mvars,
(l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt
<|> fail "monotonic context not found",
ns ← get_monotonicity_lemmas tgt both,
p ← mk_pattern g,
rules ← find_rule asms ns p <|> fail "no applicable rules found",
when (rules = []) (fail "no applicable rules found"),
err ← format.join <$> mmap side_conditions rules,
focus1 $ best_match rules (λ rule, do
t₀ ← mk_meta_var `(Prop),
v₀ ← mk_meta_var t₀,
t₁ ← mk_meta_var `(Prop),
v₁ ← mk_meta_var t₁,
tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁),
solve_mvar v₀ (try (any_of id_rs rewrite_target) >>
( done <|>
refl <|>
ac_refl <|>
`[simp only [is_associative.assoc]]) ),
solve_mvar v₁ (try (any_of id_rs rewrite_target) >>
( done <|>
refl <|>
ac_refl <|>
`[simp only [is_associative.assoc]]) ),
n ← num_goals,
iterate_exactly (n-1) (try $ solve1 $ apply_instance <|>
tactic.solve_by_elim { lemmas := some asms }))
open sum nat
/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/
meta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit
| 0 t _ := fail "too many applications"
| (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u)
meta def repeat_until : tactic unit → tactic unit → tactic unit :=
repeat_until_or_at_most 100000
@[derive _root_.has_reflect, derive _root_.inhabited]
inductive rep_arity : Type
| one | exactly (n : ℕ) | many
meta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit
| rep_arity.one tac none := tac
| rep_arity.many tac none := repeat tac
| (rep_arity.exactly n) tac none := iterate_exactly' n tac
| rep_arity.one tac (some until) := tac >> until
| rep_arity.many tac (some until) := repeat_until tac until
| (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until
meta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) :=
(tk ":=" *> inl <$> texpr <|> (tk ":" *> inr <$> texpr))
meta def arity : lean.parser rep_arity :=
rep_arity.many <$ tk "*" <|>
rep_arity.exactly <$> (tk "^" *> small_nat) <|>
pure rep_arity.one
/--
`ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a
monotonic function `f` to `x ≺ y`.
`ac_mono*` unwraps monotonic functions until it can't.
`ac_mono^k`, for some literal number `k` applies monotonicity `k`
times.
`ac_mono := h`, with `h` a hypothesis, unwraps monotonic functions and
uses `h` to solve the remaining goal. Can be combined with `*` or `^k`:
`ac_mono* := h`
`ac_mono : p` asserts `p` and uses it to discharge the goal result
unwrapping a series of monotonic functions. Can be combined with * or
^k: `ac_mono* : p`
In the case where `f` is an associative or commutative operator,
`ac_mono` will consider any possible permutation of its arguments and
use the one the minimizes the difference between the left-hand side
and the right-hand side.
To use it, first import `tactic.monotonicity`.
`ac_mono` can be used as follows:
```lean
example (x y z k m n : ℕ)
(h₀ : z ≥ 0)
(h₁ : x ≤ y) :
(m + x + n) * z + k ≤ z * (y + n + m) + k :=
begin
ac_mono,
-- ⊢ (m + x + n) * z ≤ z * (y + n + m)
ac_mono,
-- ⊢ m + x + n ≤ y + n + m
ac_mono,
end
```
As with `mono*`, `ac_mono*` solves the goal in one go and so does
`ac_mono* := h₁`. The latter syntax becomes especially interesting in the
following example:
```lean
example (x y z k m n : ℕ)
(h₀ : z ≥ 0)
(h₁ : m + x + n ≤ y + n + m) :
(m + x + n) * z + k ≤ z * (y + n + m) + k :=
by ac_mono* := h₁.
```
By giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to
stop earlier than it would normally would.
-/
meta def ac_mono (rep : parse arity) :
parse assert_or_rule? →
opt_param mono_cfg { mono_cfg . } →
tactic unit
| none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none
| (some (inl h)) opt :=
do focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine)
| (some (inr t)) opt :=
do h ← i_to_expr t >>= assert `h,
tactic.swap,
focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h)
/-
TODO(Simon): with `ac_mono := h` and `ac_mono : p` split the remaining
gaol if the provided rule does not solve it completely.
-/
add_tactic_doc
{ name := "ac_mono",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ac_mono],
tags := ["monotonicity"] }
attribute [mono] and.imp or.imp
end tactic.interactive
|
5ad363d1a78e365e54c27b32244694e7dbd99d62 | b392eb79fb36952401156496daa60628ccb07438 | /MathPort/ProcessActionItem.lean | 6978b00a1416503fee15a4f5d684b48047a06564 | [
"Apache-2.0"
] | permissive | AurelienSaue/mathportsource | d9eabe74e3ab7774baa6a10a6dc8d4855ff92266 | 1a164e4fff7204c522c1f4ecc5024fd909be3b0b | refs/heads/master | 1,685,214,377,305 | 1,623,621,223,000 | 1,623,621,223,000 | 364,191,042 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,112 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam, Gabriel Ebner
-/
import MathPort.Util
import MathPort.Basic
import MathPort.ActionItem
import MathPort.Rules
import MathPort.Translate
import MathPort.OldRecursor
import MathPort.PrintSource
import Lean
namespace MathPort
open Lean Lean.Meta Lean.Elab Lean.Elab.Command Std
def shouldGenCodeFor (d : Declaration) : Bool :=
-- TODO: sadly, noncomputable comes after the definition
-- (so if this isn't good enough, we will need to refactor)
match d with
| Declaration.defnDecl _ => true
| _ => false
def addDeclLoud (n : Name) (d : Declaration) : PortM Unit := do
let path := (← read).path
println! "[addDecl] START {path.mrpath.path} {n}"
if n == `module.End.eigenvectors_linear_independent then
match d with
| Declaration.thmDecl d => println! "[fail] {d.type} \n\n\n\n{d.value}"
| _ => pure ()
try
addDecl d
catch | _ => ()
println! "[addDecl] END {path.mrpath.path} {n}"
if shouldGenCodeFor d then
match (← getEnv).compileDecl {} d with
| Except.ok env => println! "[compile] {n} SUCCESS!"
setEnv env
| Except.error err => let msg ← err.toMessageData (← getOptions)
let msg ← msg.toString
println! "[compile] {n} {msg}"
def setAttr (attr : Attribute) (declName : Name) : PortM Unit := do
let env ← getEnv
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError errMsg
| Except.ok attrImpl => liftMetaM $ attrImpl.add declName attr.stx attr.kind
def processMixfix (kind : MixfixKind) (n : Name) (prec : Nat) (tok : String) : PortM Unit := do
-- For now, we avoid the `=` `=` clash by making all Mathlib notations
-- lower priority than the Lean4 ones.
let prio : Nat := (← liftMacroM <| evalOptPrio none).pred
let stxPrec : Option Syntax := Syntax.mkNumLit (toString prec)
let stxName : Option Syntax := none
let stxPrio : Option Syntax := quote prio
let stxOp : Syntax := Syntax.mkStrLit tok
let stxFun : Syntax := Syntax.ident SourceInfo.none n.toString.toSubstring n []
let stx ←
match kind with
| MixfixKind.infixl =>
`(infixl $[: $stxPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.infixr =>
`(infixr $[: $stxPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.prefix =>
`(prefix $[: $stxPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.postfix =>
`(postfix $[: $stxPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.singleton =>
let correctPrec : Option Syntax := Syntax.mkNumLit (toString Parser.maxPrec)
`(notation $[: $correctPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
let nextIdx : Nat ← (← get).nNotations
modify λ s => { s with nNotations := nextIdx + 1 }
let ns : Syntax := mkIdent $ s!"{(← read).path.mrpath.toUnderscorePath}_{nextIdx}"
let stx ← `(namespace $ns:ident $stx end $ns:ident)
elabCommand stx
def maybeRegisterEquation (n : Name) : PortM Unit := do
-- example: list.nth.equations._eqn_1
-- def insertWith (m : HashMap α β) (merge : β → β → β) (a : α) (b : β) : HashMap α β :=
let n₁ : Name := n.getPrefix
if n₁.isStr && n₁.getString! == "equations" then
modify λ s => { s with name2equations := s.name2equations.insertWith (· ++ ·) n₁.getPrefix [n] }
def tryAddSimpLemma (n : Name) (prio : Nat) : PortM Unit :=
try
liftMetaM $ addSimpLemma n False AttributeKind.global prio
println! "[simp] {n} {prio}"
catch ex => warn ex
def isBadSUnfold (n : Name) : PortM Bool := do
if !n.isStr then return false
if n.getString! != "_sunfold" then return false
match (← getEnv).find? (n.getPrefix ++ `_main) with
| some cinfo =>
match cinfo.value? with
-- bad means the original function isn't actually recursive
| some v => Option.isNone $ v.find? fun e => e.isConst && e.constName!.isStr && e.constName!.getString! == "brec_on"
| _ => throwError "should have value"
| _ => return false /- this can happen when e.g. `nat.add._main -> Nat.add` (which may be needed due to eqn lemmas) -/
def processActionItem (actionItem : ActionItem) : PortM Unit := do
modify λ s => { s with decl := actionItem.toDecl }
let s ← get
let f n := translateName s (← getEnv) n
match actionItem with
| ActionItem.export d => do
println! "[export] {d.currNs} {d.ns} {d.nsAs} {d.hadExplicit}, renames={d.renames}, excepts={d.exceptNames}"
-- we use the variable names of elabExport
if not d.exceptNames.isEmpty then
warnStr s!"export of {d.ns} with exceptions is ignored"
else if d.nsAs != Name.anonymous then
warnStr s!"export of {d.ns} with 'nsAs' is ignored"
else if ¬ d.hadExplicit then
warnStr s!"export of {d.ns} with no explicits is ignored"
else
let mut env ← getEnv
for (n1, n2) in d.renames do
println! "[alias] {f n1} short for {f n2}"
env := addAlias env (f n1) (f n2)
setEnv env
| ActionItem.mixfix kind n prec tok =>
println! "[mixfix] {kind} {tok} {prec} {n}"
processMixfix kind (f n) prec tok
| ActionItem.simp n prio => do
tryAddSimpLemma (f n) prio
for eqn in (← get).name2equations.findD n [] do
tryAddSimpLemma (f eqn) prio
| ActionItem.reducibility n kind => do
-- (note: this will fail if it declares reducible in a new module)
println! "reducibility {n} {repr kind}"
try setAttr { name := reducibilityToName kind } (f n)
catch ex => warn ex
| ActionItem.projection proj => do
println! "[projection] {reprStr proj}"
setEnv $ addProjectionFnInfo (← getEnv) (f proj.projName) (f proj.ctorName) proj.nParams proj.index proj.fromClass
| ActionItem.class n => do
let env ← getEnv
if s.ignored.contains n then return ()
-- for meta classes, Lean4 won't know about the decl
match addClass env (f n) with
| Except.error msg => warnStr msg
| Except.ok env => setEnv env
| ActionItem.instance nc ni prio => do
-- for meta instances, Lean4 won't know about the decl
-- note: we use `prio.pred` so that the Lean4 builtin instances get priority
-- this is currently needed because Decidable instances aren't getting compiled!
match (← get).noInsts.find? ni with
| some _ => println! "[skipInstance] {ni}"
| none => try liftMetaM $ addInstance (f ni) AttributeKind.global prio
setAttr { name := `inferTCGoalsRL } (f ni)
catch ex => warn ex
| ActionItem.private _ _ => pure ()
| ActionItem.protected n =>
-- TODO: have the semantics changed here?
-- When we mark `nat.has_one` as `Protected`, the kernel
-- fails to find it when typechecking definitions (but not theorems)
setEnv $ addProtected (← getEnv) (f n)
pure ()
| ActionItem.position n line col => do
println! "[POSITION] {n}"
let n ← f n
let range ← DeclarationRanges.mk
{ pos := { line := line, column := col },
charUtf16 := col,
endPos := { line := line, column := col },
endCharUtf16 := col }
{ pos := { line := line, column := col },
charUtf16 := col,
endPos := { line := line, column := col },
endCharUtf16 := col}
Lean.addDeclarationRanges n range
| ActionItem.decl d => do
match d with
| Declaration.axiomDecl ax => do
let name := f ax.name
let type ← translate ax.type
if s.ignored.contains ax.name then return ()
maybeRegisterEquation ax.name
addDeclLoud ax.name $ Declaration.axiomDecl {
ax with
name := name,
type := type
}
| Declaration.thmDecl thm => do
let name := f thm.name
let type ← translate thm.type
if s.ignored.contains thm.name then return ()
maybeRegisterEquation thm.name
if s.sorries.contains thm.name ∨ (¬ (← read).proofs ∧ ¬ s.neverSorries.contains thm.name) then
addDeclLoud thm.name $ Declaration.axiomDecl {
thm with
name := name,
type := type,
isUnsafe := false -- TODO: what to put here?
}
else
let value ← translate thm.value
addDeclLoud thm.name $ Declaration.thmDecl {
thm with
name := name,
type := type,
value := value
}
| Declaration.defnDecl defn => do
let name := f defn.name
let type ← translate defn.type
if s.ignored.contains defn.name then return ()
if ← isBadSUnfold name then return ()
let value ← translate defn.value
let env ← getEnv
addDeclLoud defn.name $ Declaration.defnDecl {
defn with
name := name,
type := type,
value := value,
hints := defn.hints
}
| Declaration.inductDecl lps nps [ind] iu => do
let name := f ind.name
let type ← translate ind.type
if not (s.ignored.contains ind.name) then
-- TODO: why do I need this nested do? Because of the scope?
let ctors ← ind.ctors.mapM fun (ctor : Constructor) => do
let cname := f ctor.name
let ctype ← translate ctor.type
pure { ctor with name := cname, type := ctype }
addDeclLoud ind.name $ Declaration.inductDecl lps nps
[{ ind with name := name, type := type, ctors := ctors }] iu
try
-- these may fail for the invalid inductive types currently being accepted
-- by the temporary patch https://github.com/dselsam/lean4/commit/1bef1cb3498cf81f93095bda16ed8bc65af42535
mkRecOn name
mkCasesOn name
mkNoConfusion name
mkBelow name -- already there
mkIBelow name
mkBRecOn name
mkBInductionOn name
catch _ => pure ()
let oldRecName := mkOldRecName (f ind.name)
let oldRec ← liftMetaM $ mkOldRecursor (f ind.name) oldRecName
match oldRec with
| some oldRec => do
addDeclLoud oldRecName oldRec
setAttr { name := `reducible } oldRecName
| none => pure ()
| _ => throwError (toString d.names)
def addInfo (n : Name) (info : String) (pos : Nat := 0) (type : Expr := arbitrary): PortM Unit := do
let h ← (← get).name2info
let h ←
match h.find? n with
| some i =>
match info with
| "position" => h.insert n {i with position := pos}
| "autoGenerated" => h.insert n {i with autoGenerated := true}
| "instance" => h.insert n {i with «instance» := true}
| "class" => h.insert n {i with «class» := true}
| "protected" => h.insert n {i with «protected» := true}
| "private" => h.insert n {i with «private» := true}
| "simp" => h.insert n {i with simp := true}
| "type" => h.insert n {i with type := type}
| _ =>
println! "invalid argument info"
h
| none =>
match info with
| "position" => h.insert n {position := pos}
| "autoGenerated" => h.insert n {autoGenerated := true}
| "instance" => h.insert n {«instance» := true}
| "class" => h.insert n {«class» := true}
| "protected" => h.insert n {«protected» := true}
| "private" => h.insert n {«private» := true}
| "simp" => h.insert n {simp := true}
| "type" => h.insert n {type := type}
| _ =>
println! "invalid argument info"
h
modify $ λ s => { s with name2info := h }
def fillDeclInfo (actionItem : ActionItem) : PortM Unit := do
let s ← get
let f n := translateNamePrint s (← getEnv) n
match actionItem with
| ActionItem.simp n prio => addInfo (f n) "simp"
| ActionItem.class n => addInfo (f n) "class"
| ActionItem.instance nc ni prio => addInfo (f ni) "instance"
| ActionItem.private pretty real => addInfo (f real) "private"
| ActionItem.protected n => addInfo (f n) "protected"
| ActionItem.position n line col => addInfo (f n) "position" line
| ActionItem.decl d => do
let (name, type) ←
match d with
| Declaration.axiomDecl ax => (f ax.name, ax.type)
| Declaration.thmDecl thm => (f thm.name, thm.type)
| Declaration.defnDecl defn => (f defn.name, defn.type)
| Declaration.inductDecl lps nps [ind] iu => (f ind.name, ind.type)
| _ => arbitrary
addInfo name "type" 0 (← translate type)
| _ => ()
def fillUniverses (actionItem : ActionItem) : PortM Unit := do
let s ← get
match actionItem with
| ActionItem.decl d => do
let lps ←
match d with
| Declaration.axiomDecl ax => ax.levelParams
| Declaration.thmDecl thm => thm.levelParams
| Declaration.defnDecl defn => defn.levelParams
| Declaration.inductDecl lps nps [ind] iu => lps
| _ => arbitrary
for lp in lps do
if not (lp.toString.startsWith "_") && not ((← get).universes.contains lp) then
modify $ λ s => { s with «universes» := s.universes.push lp }
| _ => ()
def findAutoGenerated : PortM Unit := do
let mut positionMap : HashMap Nat (List Name) := mkHashMap
let h ← (← get).name2info
for (n,di) in h.toList do
positionMap := positionMap.insertWith (· ++ ·) di.position [n]
for (line, l) in positionMap.toList do
println! "ligne {line}"
let mut shortest := l.head!
for n in l.tail! do
if n.toString.containsStr "._" then
addInfo n "autoGenerated"
println! "{shortest} < {n}"
if n.getNumParts < shortest.getNumParts then
addInfo shortest "autoGenerated"
println! "{n} < {shortest}"
shortest := n
else
addInfo n "autoGenerated"
println! "{shortest} < {n}"
if line = 0 || shortest.toString.containsStr "._" then
println! "deleted {shortest}"
addInfo shortest "autoGenerated"
else
println! "chose {shortest}"
println! "{shortest}: {((← get).name2info.find! shortest).autoGenerated}"
let s ← get
let h ← (← get).name2info
println! "recap autogen:"
for (n,di) in h.toList do
println! "{n} : {di.autoGenerated}"
def findFirstLine : PortM Nat := do
let mut res := 0
let h ← (← get).name2info
for (n,di) in h.toList do
if di.position > 0 && (res = 0 || di.position < res) then
res := di.position
return res
def newPos (actionItem : ActionItem) : PortM Nat := do
let s ← get
let name2info ← s.name2info
let f n := translateNamePrint s (← getEnv) n
match actionItem with
| ActionItem.decl d => do
match d with
| Declaration.axiomDecl ax => do
let name := f ax.name
return (name2info.find! name).position
| Declaration.thmDecl thm => do
let name := f thm.name
return (name2info.find! name).position
| Declaration.defnDecl defn => do
let name := f defn.name
return (name2info.find! name).position
| Declaration.inductDecl lps nps [ind] iu => do
let name := f ind.name
return (name2info.find! name).position
| _ => throwError (toString d.names)
| _ => return s.currLine
def actionItemToSource (actionItem : ActionItem) : PortM String := do
modify λ s => { s with decl := actionItem.toDecl }
let s ← get
let f n := translateNamePrint s (← getEnv) n
match actionItem with
| ActionItem.export d => ""
-- println! "[export] {d.currNs} {d.ns} {d.nsAs} {d.hadExplicit}, renames={d.renames}, excepts={d.exceptNames}"
-- -- we use the variable names of elabExport
-- if not d.exceptNames.isEmpty then
-- warnStr s!"export of {d.ns} with exceptions is ignored"
-- else if d.nsAs != Name.anonymous then
-- warnStr s!"export of {d.ns} with 'nsAs' is ignored"
-- else if ¬ d.hadExplicit then
-- warnStr s!"export of {d.ns} with no explicits is ignored"
-- else
-- let mut env ← getEnv
-- for (n1, n2) in d.renames do
-- println! "[alias] {f n1} short for {f n2}"
-- env := addAlias env (f n1) (f n2)
-- setEnv env
| ActionItem.mixfix kind n prec tok => do
-- println! "[mixfix] {kind} {tok} {prec} {n}"
-- processMixfix kind (f n) prec tok
let n ← f n
let prio : Nat := (← liftMacroM <| evalOptPrio none).pred
let stxPrec : Option Syntax := Syntax.mkNumLit (toString prec)
let stxName : Option Syntax := none
let stxPrio : Option Syntax := quote prio
let stxOp : Syntax := Syntax.mkStrLit tok
let stxFun : Syntax := Syntax.ident SourceInfo.none n.toString.toSubstring n []
let stx ←
match kind with
| MixfixKind.infixl =>
`(infixl $[: $stxPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.infixr =>
`(infixr $[: $stxPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.prefix =>
`(prefix $[: $stxPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.postfix =>
`(postfix $[: $stxPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.singleton =>
let correctPrec : Option Syntax := Syntax.mkNumLit (toString Parser.maxPrec)
`(notation $[: $correctPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
let str ←
match kind with
| MixfixKind.infixl =>
s!"infixl:{prec} \"{tok}\" => {n}"
| MixfixKind.infixr =>
s!"infixr:{prec} \"{tok}\" => {n}"
| MixfixKind.prefix =>
s!"prefix:{prec} \"{tok}\" => {n}"
| MixfixKind.postfix =>
s!"postfix:{prec} \"{tok}\" => {n}"
| MixfixKind.singleton =>
let correctPrec := Parser.maxPrec
s!"notation:{correctPrec} \"{tok}\" => {n}"
let nextIdx : Nat ← (← get).nNotations
modify λ s => { s with nNotations := nextIdx + 1 }
let ns : Syntax := mkIdent $ s!"{(← read).path.mrpath.toUnderscorePath}_{nextIdx}"
let stx ← `(namespace $ns:ident $stx end $ns:ident)
println! "NOTATION {str}"
return s!"{str}\n\n"
| ActionItem.simp n prio => ""
-- tryAddSimpLemma (f n) prio
-- for eqn in (← get).name2equations.findD n [] do
-- tryAddSimpLemma (f eqn) prio
| ActionItem.reducibility n kind => ""
-- -- (note: this will fail if it declares reducible in a new module)
-- println! "reducibility {n} {repr kind}"
-- try setAttr { name := reducibilityToName kind } (f n)
-- catch ex => warn ex
| ActionItem.projection proj => ""
-- println! "[projection] {reprStr proj}"
-- setEnv $ addProjectionFnInfo (← getEnv) (f proj.projName) (f proj.ctorName) proj.nParams proj.index proj.fromClass
| ActionItem.class n => ""
-- if s.ignored.contains n then return ""
-- -- for meta classes, Lean4 won't know about the decl
-- match addClass env (f n) with
-- | Except.error msg => warnStr msg
-- | Except.ok env => setEnv env
| ActionItem.instance nc ni prio => ""
-- -- for meta instances, Lean4 won't know about the decl
-- -- note: we use `prio.pred` so that the Lean4 builtin instances get priority
-- -- this is currently needed because Decidable instances aren't getting compiled!
-- match (← get).noInsts.find? ni with
-- | some _ => println! "[skipInstance] {ni}"
-- | none => try liftMetaM $ addInstance (f ni) AttributeKind.global prio
-- setAttr { name := `inferTCGoalsRL } (f ni)
-- catch ex => warn ex
| ActionItem.private _ _ => pure ""
| ActionItem.protected n =>
-- TODO: have the semantics changed here?
-- When we mark `nat.has_one` as `Protected`, the kernel
-- fails to find it when typechecking definitions (but not theorems)
-- setEnv $ addProtected (← getEnv) (f n)
pure ""
| ActionItem.position n line col => ""
-- println! "[POSITION] {n}"
-- let n ← f n
-- let range ← DeclarationRanges.mk
-- { pos := { line := line, column := col },
-- charUtf16 := col,
-- endPos := { line := line, column := col },
-- endCharUtf16 := col }
-- { pos := { line := line, column := col },
-- charUtf16 := col,
-- endPos := { line := line, column := col },
-- endCharUtf16 := col}
-- Lean.addDeclarationRanges n range
| ActionItem.decl d => do
match d with
| Declaration.axiomDecl ax => do
let name := f ax.name
let type ← translate ax.type
if not printIgnored && s.ignored.contains ax.name then
println! "ignored {name}"
return ""
if (s.name2info.find! name).autoGenerated then
println! "autogenerated {name}"
return ""
println! " PRINTING axiom {name}"
return (← printAxiomLike "axiom" name ax.levelParams type s.currNamespace ax.isUnsafe).pretty 100 ++ "\n\n"
| Declaration.thmDecl thm => do
let name := f thm.name
let type ← translate thm.type
let value ← translate thm.value
if not printIgnored && s.ignored.contains thm.name then
println! "ignored {name}"
return ""
if (s.name2info.find! name).autoGenerated then
println! "autogenerated {name}"
return ""
-- maybeRegisterEquation thm.name
println! " PRINTING thm {name}"
if s.sorries.contains thm.name ∨ (¬ (← read).proofs ∧ ¬ s.neverSorries.contains thm.name) then
-- addDeclLoud thm.name $ Declaration.axiomDecl {
-- thm with
-- name := name,
-- type := type,
-- isUnsafe := false -- TODO: what to put here?
-- }
return (← printDefLike "theorem" name thm.levelParams type value s.currNamespace).pretty 100 ++ "\n\n"
else
-- let value ← translate thm.value
-- addDeclLoud thm.name $ Declaration.thmDecl {
-- thm with
-- name := name,
-- type := type,
-- value := value
-- }
return (← printDefLike "theorem" name thm.levelParams type value s.currNamespace).pretty 100 ++ "\n\n"
| Declaration.defnDecl defn => do
let name := f defn.name
let type ← translate defn.type
let value ← translate defn.value
if not printIgnored && s.ignored.contains defn.name then
println! "ignored {name}"
return ""
if ← isBadSUnfold name then
println! "bad unfold {name}"
return ""
if (s.name2info.find! name).autoGenerated then
println! "autogenerated {name}"
return ""
println! " PRINTING def {name}"
let value ← translate defn.value
-- let env ← getEnv
-- addDeclLoud defn.name $ Declaration.defnDecl {
-- defn with
-- name := name,
-- type := type,
-- value := value,
-- hints := defn.hints
-- }
return (← printDefLike "def" name defn.levelParams type value s.currNamespace defn.safety).pretty 100 ++ "\n\n"
| Declaration.inductDecl lps nps [ind] iu => do
let name := f ind.name
if not printIgnored && s.ignored.contains ind.name then
println! "ignored {name}"
return ""
if (s.name2info.find! name).autoGenerated then
println! "autogenerated {name}"
return ""
return (← constantToString name s.currNamespace "").pretty 100 ++ "\n\n"
| _ => throwError (toString d.names)
end MathPort
|
aca74348bf2836a7a29637aa6a7118ebfbef711b | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Init/Control/Monad.lean | 0252acd662df82e6cc59eea9e7c460d0fbe3b5c2 | [
"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 | 1,797 | lean | /-
Copyright (c) Luke Nelson and Jared Roesch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Luke Nelson, Jared Roesch, Sebastian Ullrich
-/
prelude
import Init.Control.Applicative
import Init.Coe
universes u v w
open Function
class HasBind (m : Type u → Type v) :=
(bind : ∀ {α β : Type u}, m α → (α → m β) → m β)
export HasBind (bind)
infixl `>>=` := bind
@[inline] def mcomp {α : Type u} {β δ : Type v} {m : Type v → Type w} [HasBind m] (f : α → m β) (g : β → m δ) : α → m δ :=
fun a => f a >>= g
infixr `>=>` := mcomp
class Monad (m : Type u → Type v) extends Applicative m, HasBind m : Type (max (u+1) v) :=
(map := fun α β f x => x >>= pure ∘ f)
(seq := fun α β f x => f >>= (fun y => y <$> x))
(seqLeft := fun α x y => x >>= fun a => y >>= fun _ => pure a)
(seqRight := fun β x y => x >>= fun _ => y)
instance monadInhabited' {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) :=
⟨pure⟩
instance monadInhabited {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) :=
⟨pure $ arbitrary _⟩
def joinM {m : Type u → Type u} [Monad m] {α : Type u} (a : m (m α)) : m α :=
bind a id
@[macroInline]
def condM {m : Type → Type u} [Monad m] {α : Type} (mbool : m Bool) (tm fm : m α) : m α := do
b ← mbool; cond b tm fm
@[macroInline]
def whenM {m : Type → Type u} [Monad m] (c : m Bool) (t : m Unit) : m Unit :=
condM c t (pure ())
@[macroInline]
def unlessM {m : Type → Type u} [Monad m] (c : m Bool) (t : m Unit) : m Unit :=
condM c (pure ()) t
@[inline] def coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β := do
a ← x;
pure $ coe a
|
ba288dd596ab6d24a6cf970206c368fb40a5a2d8 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/metric_space/gromov_hausdorff.lean | 1a2f9a7ecd65abe1920a5edbbc7176ded32b0cd7 | [
"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 | 55,399 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.metric_space.closeds
import set_theory.cardinal
import topology.metric_space.gromov_hausdorff_realized
import topology.metric_space.completion
import topology.metric_space.kuratowski
/-!
# Gromov-Hausdorff distance
This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces
up to isometry.
We introduce the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of `X` and `Y` in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
## Main results
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
noncomputable theory
open_locale classical topological_space
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function nat Kuratowski_embedding
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to `GH_space`. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private definition isometry_rel :
nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λ x y, nonempty (x.val ≃ᵢ y.val)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λ x, ⟨isometric.refl _⟩, λ x y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to `GH_space` -/
definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding X⟧
instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp⟩⟩
/-- A metric space representative of any abstract point in `GH_space` -/
@[nolint has_inhabited_instance]
definition GH_space.rep (p : GH_space) : Type := (quot.out p).val
lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space X ↔ ∃ Ψ : X → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val :=
begin
simp only [to_GH_space, quotient.eq],
split,
{ assume h,
rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding.isometry X).isometric_on_range.trans e,
use λ x, f x,
split,
{ apply isometry_subtype_coe.comp f.isometry },
{ rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe] } },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding.isometry X).isometric_on_range.symm.trans
isomΨ.isometric_on_range).symm,
have E : (range Ψ ≃ᵢ (nonempty_compacts.Kuratowski_embedding X).val) =
(p.val ≃ᵢ range (Kuratowski_embedding X)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
have g := cast E f,
exact ⟨g⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val :=
begin
refine eq_to_GH_space_iff.2 ⟨((λ x, x) : p.val → ℓ_infty_ℝ), _, subtype.range_coe⟩,
apply isometry_subtype_coe
end
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) :=
by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) :=
by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) :=
by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p :=
begin
change to_GH_space (quot.out p).val = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are
isometric. -/
lemma to_GH_space_eq_to_GH_space_iff_isometric {X : Type u} [metric_space X] [compact_space X]
[nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
to_GH_space X = to_GH_space Y ↔ nonempty (X ≃ᵢ Y) :=
⟨begin
simp only [to_GH_space, quotient.eq],
assume h,
rcases h with ⟨e⟩,
have I : ((nonempty_compacts.Kuratowski_embedding X).val ≃ᵢ
(nonempty_compacts.Kuratowski_embedding Y).val)
= ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have e' := cast I e,
have f := (Kuratowski_embedding.isometry X).isometric_on_range,
have g := (Kuratowski_embedding.isometry Y).isometric_on_range.symm,
have h := (f.trans e').trans g,
exact ⟨h⟩
end,
begin
rintros ⟨e⟩,
simp only [to_GH_space, quotient.eq],
have f := (Kuratowski_embedding.isometry X).isometric_on_range.symm,
have g := (Kuratowski_embedding.isometry Y).isometric_on_range,
have h := (f.trans e).trans g,
have I : ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))) =
((nonempty_compacts.Kuratowski_embedding X).val ≃ᵢ
(nonempty_compacts.Kuratowski_embedding Y).val),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have h' := cast I h,
exact ⟨h'⟩
end⟩
/-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λ x y, Inf $
(λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ,
Hausdorff_dist p.1.val p.2.val) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) }
/-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to
the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/
def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X]
[metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
{γ : Type w} [metric_space γ] {Φ : X → γ} {Ψ : Y → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist X Y ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized
in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not
separable in general. We restrict to the union of the images of `X` and `Y` in `γ`, which is
separable and therefore embeddable in `ℓ^∞(ℝ)`. -/
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : X → subtype s := λ y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : Y → subtype s := λ y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λ x y, ha x y,
have IΨ' : isometry Ψ' := λ x y, hb x y,
have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous),
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 ‹is_compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xX⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_coe) },
rw this,
-- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) =
Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _),
rw ← this,
-- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `ℓ^∞(ℝ)`, and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨(range_nonempty _).image _,
(is_compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _,
(is_compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩,
have AX : ⟦A⟧ = to_GH_space X,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Φ' x), ⟨(Kuratowski_embedding.isometry _).comp IΦ', by rw range_comp⟩⟩ },
have BY : ⟦B⟧ = to_GH_space Y,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Ψ' x), ⟨(Kuratowski_embedding.isometry _).comp IΨ', by rw range_comp⟩⟩ },
refine cInf_le ⟨0,
begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _,
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [AX, BY]
end
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y :=
begin
inhabit X, inhabit Y,
/- we only need to check the inequality `≤`, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on `X ⊕ Y` belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀ p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (p.val) (q.val) < diam (univ : set X) + 1 + diam (univ : set Y) →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y),
{ rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
have : ∃ y ∈ range Ψ, dist (Φ xX) y < diam (univ : set X) + 1 + diam (univ : set Y),
{ rw Ψrange,
have : Φ xX ∈ p.val := Φrange ▸ mem_range_self _,
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set X) := Φisom.diam_range,
have DΨ : diam (range Ψ) = diam (univ : set Y) := Ψisom.diam_range,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xX) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) +
diam (univ : set Y) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) }
... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring },
let f : X ⊕ Y → ℓ_infty_ℝ := λ x, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (X ⊕ Y) × (X ⊕ Y) → ℝ := λ p, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates X Y,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λ x y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq x y },
{ exact λ x y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq x y },
{ exact λ x y, dist_comm _ _ },
{ exact λ x y z, dist_triangle _ _ _ },
{ exact λ x y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀ z : X ⊕ Y, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact (p.2.2.union q.2.2).bounded,
end
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λ r hr, _)),
have I1 : ∀ x : X, (⨅ y, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux1 0) y
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀ y : Y, (⨅ x, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux2 0) x
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp [HD, csupr_le I1, csupr_le I2] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀ p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq,
by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set X) + 1 + diam (univ : set Y),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y))
≤ HD (candidates_b_dist X Y) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X]
(Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] :
∃ Φ : X → ℓ_infty_ℝ, ∃ Ψ : Y → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist X Y = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling X Y),
let Φ := F ∘ optimal_GH_injl X Y,
let Ψ := F ∘ optimal_GH_injr X Y,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) },
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm },
end
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance : metric_space GH_space :=
{ dist_self := λ x, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp, existsi [y, y], simpa } },
{ apply le_cInf,
{ exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λ x y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) ''
(set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) ''
(set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) :=
by { congr, funext, simp, rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, image_swap_prod],
end,
eq_of_dist_eq_zero := λ x y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : is_compact (range Φ) := is_compact_range Φisom.continuous,
have hΨ : is_compact (range Ψ) := is_compact_range Ψisom.continuous,
apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm),
{ exact hΦ.is_closed },
{ exact hΨ.is_closed },
{ exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _)
(range_nonempty _) hΦ.bounded hΨ.bounded } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometric_on_range.symm,
have e := Φisom.isometric_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric],
exact ⟨e⟩
end,
dist_triangle := λ x y z, begin
/- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling
between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space
`γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are
optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff
distance in `γ` to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) =
(to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y))
((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (range_nonempty _) _ _),
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injl X Y)))).bounded },
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injr X Y)))).bounded }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this
in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/
definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X]
(p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {X : Type u} [metric_space X]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (coe : p.val → X) := isometry_subtype_coe,
have hb : isometry (coe : q.val → X) := isometry_subtype_coe,
have A : dist p q = Hausdorff_dist p.val q.val := rfl,
have I : p.val = range (coe : p.val → X), by simp,
have J : q.val = range (coe : q.val → X), by simp,
rw [I, J] at A,
rw A,
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
to_GH_space_lipschitz.continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their
Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are
`ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff
distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable
coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
-- we want to ignore these instances in the following theorem
local attribute [instance, priority 10] sum.topological_space sum.uniform_space
/-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and
isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by
`ε₁ + ε₂/2 + ε₃`. -/
theorem GH_dist_le_of_approx_subsets {s : set X} (Φ : s → Y) {ε₁ ε₂ ε₃ : ℝ}
(hs : ∀ x : X, ∃ y ∈ s, dist x y ≤ ε₁) (hs' : ∀ x : Y, ∃ y : s, dist x (Φ y) ≤ ε₃)
(H : ∀ x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε₂) :
GH_dist X Y ≤ ε₁ + ε₂ / 2 + ε₃ :=
begin
refine le_of_forall_pos_le_add (λ δ δ0, _),
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
rcases hs xX with ⟨xs, hxs, Dxs⟩,
have sne : s.nonempty := ⟨xs, hxs⟩,
letI : nonempty s := sne.to_subtype,
have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε₂/2 + δ) := λ p q, calc
abs (dist p q - dist (Φ p) (Φ q)) ≤ ε₂ : H p q
... ≤ 2 * (ε₂/2 + δ) : by linarith,
-- glue `X` and `Y` along the almost matching subsets
letI : metric_space (X ⊕ Y) :=
glue_metric_approx (λ x:s, (x:X)) (λ x, Φ x) (ε₂/2 + δ) (by linarith) this,
let Fl := @sum.inl X Y,
let Fr := @sum.inr X Y,
have Il : isometry Fl := isometry_emetric_iff_metric.2 (λ x y, rfl),
have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λ x y, rfl),
/- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images
in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff
distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and
`Φ s`, and of `Φ s` and `Y` (in the coupling or, equivalently, in the original space). The first
term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is
bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by
construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive
constant where positivity is used to ensure that the coupling is really a metric space and not a
premetric space on `X ⊕ Y`). -/
have : GH_dist X Y ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded,
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded,
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded
((range_nonempty _).image _) (range_nonempty _)
(bounded.subset (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, hs x)
(λ x hx, ⟨x, mem_univ _, by simpa⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (λ x:s, (x:X)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Φ (ε₂/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty Y with ⟨xY, _⟩,
rcases hs' xY with ⟨xs', Dxs'⟩,
have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, ⟨x, mem_univ _, by simpa⟩) (λ x _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
instance : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λ δ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀ p:GH_space, ∃ s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λ p, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos,
-- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space
-- `p.rep` representing `p`)
choose s hs using this,
have : ∀ p:GH_space, ∀ t:set (p.rep), finite t → ∃ n:ℕ, ∃ e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset `s p` of `p.rep`, called `N p`
let N := λ p:GH_space, N p (s p) (hs p).1,
-- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p`
let E := λ p:GH_space, e p (s p) (hs p).1,
-- A function `F` associating to `p : GH_space` the data of all distances between points
-- in the `ε`-dense set `s p`.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λ p, ⟨N p, λ a b, floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))⟩,
refine ⟨_, by apply_instance, F, λ p q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
`p` and `q` with `F p = F q` are at distance `≤ δ`.
For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`)
to `q.rep` (representing `q`) which is almost an isometry on `s p`, and
with image `s q`. For this, we compose the identification of `s p` with `fin (N p)`
and the inverse of the identification of `s q` with `fin (N q)`. Together with
the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then
composing with the canonical inclusion we get `Φ`. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
-- Use the almost isometry `Φ` to show that `p.rep` and `q.rep`
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).is_lt,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀ x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).symm_apply_apply],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl },
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).symm_apply_apply],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] },
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp [ε], ring }
end
/-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required
to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (𝓝 0))
(hdiam : ∀ p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀ p ∈ t, ∀ n:ℕ, ∃ s : set (GH_space.rep p),
cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which
is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`,
up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to
reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λ δ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose `n` for which `u n < ε`
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n (le_refl _),
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n`
have : ∀ p:GH_space, ∃ s : set (p.rep), ∃ N ≤ K n, ∃ E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set (p.rep)) (fin 0)),
{ rw ← fintype.card_eq, simp },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp [hp, scover] } },
choose s N hN E hs using this,
-- Define a function `F` taking values in a finite type and associating to `p` enough data
-- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`.
let M := (floor (ε⁻¹ * max C 0)).to_nat,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λ p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λ a b, ⟨min M (floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))).to_nat,
lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, by apply_instance, (λ p, F p), _⟩,
-- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense
-- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows
-- from `GH_dist_le_of_approx_subsets`
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀ x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)), by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 :
by { congr; apply (fin.ext_iff _ _).2; refl }
... = min M (floor (ε⁻¹ * dist x y)).to_nat :
by simp only [F, (E p).symm_apply_apply]
... = (floor (ε⁻¹ * dist x y)).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 :
by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }
... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
by simp only [F, (E q).symm_apply_apply]
... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
{ rw [Ap, Aq] at this,
have D : 0 ≤ floor (ε⁻¹ * dist x y) :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] },
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp [ε], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀ n, metric_space (X n)] [∀ n, compact_space (X n)] [∀ n, nonempty (X n)]
/-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding
of a type `A` in another metric space. -/
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) :=
⟨{ space := A,
metric := by apply_instance,
embed := id,
isom := λ x y, rfl }⟩
/-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each
`X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space
at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n
{ space := X 0,
metric := by apply_instance,
embed := id,
isom := λ x y, rfl }
(λ n Y, by letI : metric_space Y.space := Y.metric; exact
{ space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))),
metric := by apply_instance,
embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))))
∘ (optimal_GH_injr (X n) (X (n+1))),
isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) })
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space GH_space :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other
refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) this (λ u hu, _),
-- `X n` is a representative of `u n`
let X := λ n, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n`
let Y := aux_gluing X,
letI : ∀ n, metric_space (Y n).space := λ n, (Y n).metric,
have E : ∀ n : ℕ,
glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space :=
λ n, by { simp [Y, aux_gluing], refl },
let c := λ n, cast (E n),
have ic : ∀ n, isometry (c n) := λ n x y, rfl,
-- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction
let f : Πn, (Y n).space → (Y n.succ).space :=
λ n, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))),
have I : ∀ n, isometry (f n),
{ assume n,
apply isometry.comp,
{ assume x y, refl },
{ apply to_glue_l_isometry } },
-- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z`
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let `X2 n` be the image of `X n` in the space `Z`
let X2 := λ n, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀ n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
apply isometry.comp completion.coe_isometry _,
apply isometry.comp _ (Y n).isom,
apply to_inductive_limit_isometry },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by `1/2^n`
have D2 : ∀ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply isometry.comp completion.coe_isometry _,
apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)),
apply to_inductive_limit_isometry } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λ n, ⟨X2 n,
⟨range_nonempty _, is_compact_range (isom n).continuous ⟩⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by `(1/2)^n`
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λ n, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λ n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) :=
tendsto.comp (to_GH_space_continuous.tendsto _) hL,
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀ n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometric],
constructor,
convert (isom n).isometric_on_range.symm,
},
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
667a1294c8db97cb98efb6299106f9f31e7d150a | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/order/filter/at_top_bot.lean | aba8aec7abd07b02576fada574f40405af5108fd | [
"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 | 61,836 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov, Patrick Massot
-/
import order.filter.bases
import data.finset.preimage
/-!
# `at_top` and `at_bot` filters on preorded sets, monoids and groups.
In this file we define the filters
* `at_top`: corresponds to `n → +∞`;
* `at_bot`: corresponds to `n → -∞`.
Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”.
-/
variables {ι ι' α β γ : Type*}
open set
open_locale classical filter big_operators
namespace filter
/-- `at_top` is the filter representing the limit `→ ∞` on an ordered set.
It is generated by the collection of up-sets `{b | a ≤ b}`.
(The preorder need not have a top element for this to be well defined,
and indeed is trivial when a top element exists.) -/
def at_top [preorder α] : filter α := ⨅ a, 𝓟 (Ici a)
/-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set.
It is generated by the collection of down-sets `{b | b ≤ a}`.
(The preorder need not have a bottom element for this to be well defined,
and indeed is trivial when a bottom element exists.) -/
def at_bot [preorder α] : filter α := ⨅ a, 𝓟 (Iic a)
lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ :=
mem_infi_of_mem a $ subset.refl _
lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) :=
let ⟨z, hz⟩ := no_top x in mem_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h
lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ :=
mem_infi_of_mem a $ subset.refl _
lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) :=
let ⟨z, hz⟩ := no_bot x in mem_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz
lemma at_top_basis [nonempty α] [semilattice_sup α] :
(@at_top α _).has_basis (λ _, true) Ici :=
has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2)
lemma at_top_basis' [semilattice_sup α] (a : α) :
(@at_top α _).has_basis (λ x, a ≤ x) Ici :=
⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans
⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩,
λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩
lemma at_bot_basis [nonempty α] [semilattice_inf α] :
(@at_bot α _).has_basis (λ _, true) Iic :=
@at_top_basis (order_dual α) _ _
lemma at_bot_basis' [semilattice_inf α] (a : α) :
(@at_bot α _).has_basis (λ x, x ≤ a) Iic :=
@at_top_basis' (order_dual α) _ _
@[instance]
lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) :=
at_top_basis.ne_bot_iff.2 $ λ a _, nonempty_Ici
@[instance]
lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) :=
@at_top_ne_bot (order_dual α) _ _
@[simp]
lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} :
s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s :=
at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _
@[simp]
lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} :
s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s :=
@mem_at_top_sets (order_dual α) _ _ _
@[simp]
lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} :
(∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) :=
mem_at_top_sets
@[simp]
lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} :
(∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) :=
mem_at_bot_sets
lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a
lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a
lemma eventually_gt_at_top [preorder α] [no_top_order α] (a : α) :
∀ᶠ x in at_top, a < x :=
Ioi_mem_at_top a
lemma eventually_lt_at_bot [preorder α] [no_bot_order α] (a : α) :
∀ᶠ x in at_bot, x < a :=
Iio_mem_at_bot a
lemma at_top_basis_Ioi [nonempty α] [semilattice_sup α] [no_top_order α] :
(@at_top α _).has_basis (λ _, true) Ioi :=
at_top_basis.to_has_basis (λ a ha, ⟨a, ha, Ioi_subset_Ici_self⟩) $
λ a ha, (no_top a).imp $ λ b hb, ⟨ha, Ici_subset_Ioi.2 hb⟩
lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] :
has_countable_basis (at_top : filter α) (λ _, true) Ici :=
{ countable := countable_encodable _,
.. at_top_basis }
lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [encodable α] :
has_countable_basis (at_bot : filter α) (λ _, true) Iic :=
{ countable := countable_encodable _,
.. at_bot_basis }
lemma is_countably_generated_at_top [nonempty α] [semilattice_sup α] [encodable α] :
(at_top : filter $ α).is_countably_generated :=
at_top_countable_basis.is_countably_generated
lemma is_countably_generated_at_bot [nonempty α] [semilattice_inf α] [encodable α] :
(at_bot : filter $ α).is_countably_generated :=
at_bot_countable_basis.is_countably_generated
lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ :=
le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique)
(le_infi $ λ b, le_principal_iff.2 le_top)
lemma order_bot.at_bot_eq (α) [order_bot α] : (at_bot : filter α) = pure ⊥ :=
@order_top.at_top_eq (order_dual α) _
@[nontriviality]
lemma subsingleton.at_top_eq (α) [subsingleton α] [preorder α] : (at_top : filter α) = ⊤ :=
begin
refine top_unique (λ s hs x, _),
letI : unique α := ⟨⟨x⟩, λ y, subsingleton.elim y x⟩,
rw [at_top, infi_unique, unique.default_eq x, mem_principal] at hs,
exact hs left_mem_Ici
end
@[nontriviality]
lemma subsingleton.at_bot_eq (α) [subsingleton α] [preorder α] : (at_bot : filter α) = ⊤ :=
@subsingleton.at_top_eq (order_dual α) _ _
lemma tendsto_at_top_pure [order_top α] (f : α → β) :
tendsto f at_top (pure $ f ⊤) :=
(order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _
lemma tendsto_at_bot_pure [order_bot α] (f : α → β) :
tendsto f at_bot (pure $ f ⊥) :=
@tendsto_at_top_pure (order_dual α) _ _ _
lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop}
(h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b :=
eventually_at_top.mp h
lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop}
(h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b :=
eventually_at_bot.mp h
lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} :
(∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) :=
by simp [at_top_basis.frequently_iff]
lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} :
(∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) :=
@frequently_at_top (order_dual α) _ _ _
lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} :
(∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) :=
by simp [at_top_basis_Ioi.frequently_iff]
lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_bot_order α] {p : α → Prop} :
(∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) :=
@frequently_at_top' (order_dual α) _ _ _ _
lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop}
(h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b :=
frequently_at_top.mp h
lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop}
(h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b :=
frequently_at_bot.mp h
lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} :
at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) :=
(at_top_basis.map _).eq_infi
lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} :
at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) :=
@map_at_top_eq (order_dual α) _ _ _ _
lemma tendsto_at_top [preorder β] {m : α → β} {f : filter α} :
tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) :=
by simp only [at_top, tendsto_infi, tendsto_principal, mem_Ici]
lemma tendsto_at_bot [preorder β] {m : α → β} {f : filter α} :
tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) :=
@tendsto_at_top α (order_dual β) _ m f
lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) :
tendsto f₁ l at_top → tendsto f₂ l at_top :=
assume h₁, tendsto_at_top.2 $ λ b, mp_mem (tendsto_at_top.1 h₁ b)
(monotone_mem (λ a ha ha₁, le_trans ha₁ ha) h)
lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) :
tendsto f₂ l at_bot → tendsto f₁ l at_bot :=
@tendsto_at_top_mono' _ (order_dual β) _ _ _ _ h
lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) :
tendsto f l at_top → tendsto g l at_top :=
tendsto_at_top_mono' l $ eventually_of_forall h
lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) :
tendsto g l at_bot → tendsto f l at_bot :=
@tendsto_at_top_mono _ (order_dual β) _ _ _ _ h
/-!
### Sequences
-/
lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} :
ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U :=
by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl
lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} :
ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U :=
@inf_map_at_top_ne_bot_iff (order_dual α) _ _ _ _ _
lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) :=
begin
choose u hu using h,
cases forall_and_distrib.mp hu with hu hu',
exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono_nat_of_lt_succ (λ n, hu _), λ n, hu' _⟩,
end
lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) :=
begin
rw frequently_at_top' at h,
exact extraction_of_frequently_at_top' h,
end
lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) :=
extraction_of_frequently_at_top h.frequently
lemma extraction_forall_of_frequently {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ᶠ k in at_top, P n k) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) :=
begin
simp only [frequently_at_top'] at h,
choose u hu hu' using h,
use (λ n, nat.rec_on n (u 0 0) (λ n v, u (n+1) v) : ℕ → ℕ),
split,
{ apply strict_mono_nat_of_lt_succ,
intro n,
apply hu },
{ intros n,
cases n ; simp [hu'] },
end
lemma extraction_forall_of_eventually {P : ℕ → ℕ → Prop} (h : ∀ n, ∀ᶠ k in at_top, P n k) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) :=
extraction_forall_of_frequently (λ n, (h n).frequently)
lemma extraction_forall_of_eventually' {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ N, ∀ k ≥ N, P n k) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) :=
extraction_forall_of_eventually (by simp [eventually_at_top, h])
lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β}
(h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b ≤ u a' :=
begin
have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x :=
(eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b),
haveI : nonempty α := ⟨a⟩,
rcases this.exists with ⟨a', ha, hb⟩,
exact ⟨a', ha, hb⟩
end
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β}
(h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b :=
@exists_le_of_tendsto_at_top _ (order_dual β) _ _ _ h
lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β]
{u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b < u a' :=
begin
cases no_top b with b' hb',
rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩,
exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩
end
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_bot_order β]
{u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b :=
@exists_lt_of_tendsto_at_top _ (order_dual β) _ _ _ _ h
/--
If `u` is a sequence which is unbounded above,
then after any point, it reaches a value strictly greater than all previous values.
-/
lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β}
(hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n :=
begin
intros N,
let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N}
have Ane : A.nonempty,
from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩,
let M := finset.max' A Ane,
have ex : ∃ n ≥ N, M < u n,
from exists_lt_of_tendsto_at_top hu _ _,
obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M,
{ use nat.find ex,
rw ← and_assoc,
split,
{ simpa using nat.find_spec ex },
{ intros k hk hk',
simpa [hk] using nat.find_min ex hk' } },
use [n, hnN],
intros k hk,
by_cases H : k ≤ N,
{ have : u k ∈ A,
from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H),
have : u k ≤ M,
from finset.le_max' A (u k) this,
exact lt_of_le_of_lt this hnM },
{ push_neg at H,
calc u k ≤ M : hn_min k (le_of_lt H) hk
... < u n : hnM },
end
/--
If `u` is a sequence which is unbounded below,
then after any point, it reaches a value strictly smaller than all previous values.
-/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma low_scores [linear_order β] [no_bot_order β] {u : ℕ → β}
(hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k :=
@high_scores (order_dual β) _ _ _ hu
/--
If `u` is a sequence which is unbounded above,
then it `frequently` reaches a value strictly greater than all previous values.
-/
lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β}
(hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n :=
by simpa [frequently_at_top] using high_scores hu
/--
If `u` is a sequence which is unbounded below,
then it `frequently` reaches a value strictly smaller than all previous values.
-/
lemma frequently_low_scores [linear_order β] [no_bot_order β] {u : ℕ → β}
(hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k :=
@frequently_high_scores (order_dual β) _ _ _ hu
lemma strict_mono_subseq_of_tendsto_at_top
{β : Type*} [linear_order β] [no_top_order β]
{u : ℕ → β} (hu : tendsto u at_top at_top) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) :=
let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in
⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩
lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) :=
strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id)
lemma _root_.strict_mono.tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) :
tendsto φ at_top at_top :=
tendsto_at_top_mono h.id_le tendsto_id
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β}
lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg
lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add_nonneg_left' _ (order_dual β) _ _ _ _ hf hg
lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg
lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add_nonneg_left _ (order_dual β) _ _ _ _ hf hg
lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_mono' l (monotone_mem (λ x, le_add_of_nonneg_right) hg) hf
lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add_nonneg_right' _ (order_dual β) _ _ _ _ hf hg
lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg)
lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add_nonneg_right _ (order_dual β) _ _ _ _ hf hg
lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_nonneg_left' (tendsto_at_top.mp hf 0) hg
lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add _ (order_dual β) _ _ _ _ hf hg
lemma tendsto.nsmul_at_top (hf : tendsto f l at_top) {n : ℕ} (hn : 0 < n) :
tendsto (λ x, n • f x) l at_top :=
tendsto_at_top.2 $ λ y, (tendsto_at_top.1 hf y).mp $ (tendsto_at_top.1 hf 0).mono $ λ x h₀ hy,
calc y ≤ f x : hy
... = 1 • f x : (one_nsmul _).symm
... ≤ n • f x : nsmul_le_nsmul h₀ hn
lemma tendsto.nsmul_at_bot (hf : tendsto f l at_bot) {n : ℕ} (hn : 0 < n) :
tendsto (λ x, n • f x) l at_bot :=
@tendsto.nsmul_at_top α (order_dual β) _ l f hf n hn
lemma tendsto_bit0_at_top : tendsto bit0 (at_top : filter β) at_top :=
tendsto_at_top_add tendsto_id tendsto_id
lemma tendsto_bit0_at_bot : tendsto bit0 (at_bot : filter β) at_bot :=
tendsto_at_bot_add tendsto_id tendsto_id
end ordered_add_comm_monoid
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β}
lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) :
tendsto f l at_top :=
tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (C + b)).mono (λ x, le_of_add_le_add_left)
lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) :
tendsto f l at_bot :=
@tendsto_at_top_of_add_const_left _ (order_dual β) _ _ _ C hf
lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) :
tendsto f l at_top :=
tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (b + C)).mono (λ x, le_of_add_le_add_right)
lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) :
tendsto f l at_bot :=
@tendsto_at_top_of_add_const_right _ (order_dual β) _ _ _ C hf
lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C)
(h : tendsto (λ x, f x + g x) l at_top) :
tendsto g l at_top :=
tendsto_at_top_of_add_const_left C
(tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h)
lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x)
(h : tendsto (λ x, f x + g x) l at_bot) :
tendsto g l at_bot :=
@tendsto_at_top_of_add_bdd_above_left' _ (order_dual β) _ _ _ _ C hC h
lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) :
tendsto (λ x, f x + g x) l at_top → tendsto g l at_top :=
tendsto_at_top_of_add_bdd_above_left' C (univ_mem' hC)
lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) :
tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot :=
@tendsto_at_top_of_add_bdd_above_left _ (order_dual β) _ _ _ _ C hC
lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C)
(h : tendsto (λ x, f x + g x) l at_top) :
tendsto f l at_top :=
tendsto_at_top_of_add_const_right C
(tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h)
lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x)
(h : tendsto (λ x, f x + g x) l at_bot) :
tendsto f l at_bot :=
@tendsto_at_top_of_add_bdd_above_right' _ (order_dual β) _ _ _ _ C hC h
lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) :
tendsto (λ x, f x + g x) l at_top → tendsto f l at_top :=
tendsto_at_top_of_add_bdd_above_right' C (univ_mem' hC)
lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) :
tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot :=
@tendsto_at_top_of_add_bdd_above_right _ (order_dual β) _ _ _ _ C hC
end ordered_cancel_add_comm_monoid
section ordered_group
variables [ordered_add_comm_group β] (l : filter α) {f g : α → β}
lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
@tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C)
(by simpa) (by simpa)
lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add_left_of_le' _ (order_dual β) _ _ _ _ C hf hg
lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_left_of_le' l C (univ_mem' hf) hg
lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add_left_of_le _ (order_dual β) _ _ _ _ C hf hg
lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) :
tendsto (λ x, f x + g x) l at_top :=
@tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C)
(by simp [hg]) (by simp [hf])
lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add_right_of_le' _ (order_dual β) _ _ _ _ C hf hg
lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_right_of_le' l C hf (univ_mem' hg)
lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) :
tendsto (λ x, f x + g x) l at_bot :=
@tendsto_at_top_add_right_of_le _ (order_dual β) _ _ _ _ C hf hg
lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) :
tendsto (λ x, C + f x) l at_top :=
tendsto_at_top_add_left_of_le' l C (univ_mem' $ λ _, le_refl C) hf
lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) :
tendsto (λ x, C + f x) l at_bot :=
@tendsto_at_top_add_const_left _ (order_dual β) _ _ _ C hf
lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) :
tendsto (λ x, f x + C) l at_top :=
tendsto_at_top_add_right_of_le' l C hf (univ_mem' $ λ _, le_refl C)
lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) :
tendsto (λ x, f x + C) l at_bot :=
@tendsto_at_top_add_const_right _ (order_dual β) _ _ _ C hf
lemma tendsto_neg_at_top_at_bot : tendsto (has_neg.neg : β → β) at_top at_bot :=
begin
simp only [tendsto_at_bot, neg_le],
exact λ b, eventually_ge_at_top _
end
lemma tendsto_neg_at_bot_at_top : tendsto (has_neg.neg : β → β) at_bot at_top :=
@tendsto_neg_at_top_at_bot (order_dual β) _
end ordered_group
section ordered_semiring
variables [ordered_semiring α] {l : filter β} {f g : β → α}
lemma tendsto_bit1_at_top : tendsto bit1 (at_top : filter α) at_top :=
tendsto_at_top_add_nonneg_right tendsto_bit0_at_top (λ _, zero_le_one)
lemma tendsto.at_top_mul_at_top (hf : tendsto f l at_top) (hg : tendsto g l at_top) :
tendsto (λ x, f x * g x) l at_top :=
begin
refine tendsto_at_top_mono' _ _ hg,
filter_upwards [hg.eventually (eventually_ge_at_top 0), hf.eventually (eventually_ge_at_top 1)],
exact λ x, le_mul_of_one_le_left
end
lemma tendsto_mul_self_at_top : tendsto (λ x : α, x * x) at_top at_top :=
tendsto_id.at_top_mul_at_top tendsto_id
/-- The monomial function `x^n` tends to `+∞` at `+∞` for any positive natural `n`.
A version for positive real powers exists as `tendsto_rpow_at_top`. -/
lemma tendsto_pow_at_top {n : ℕ} (hn : 1 ≤ n) : tendsto (λ x : α, x ^ n) at_top at_top :=
begin
refine tendsto_at_top_mono' _ ((eventually_ge_at_top 1).mono $ λ x hx, _) tendsto_id,
simpa only [pow_one] using pow_le_pow hx hn
end
end ordered_semiring
lemma zero_pow_eventually_eq [monoid_with_zero α] :
(λ n : ℕ, (0 : α) ^ n) =ᶠ[at_top] (λ n, 0) :=
eventually_at_top.2 ⟨1, λ n hn, zero_pow (zero_lt_one.trans_le hn)⟩
section ordered_ring
variables [ordered_ring α] {l : filter β} {f g : β → α}
lemma tendsto.at_top_mul_at_bot (hf : tendsto f l at_top) (hg : tendsto g l at_bot) :
tendsto (λ x, f x * g x) l at_bot :=
have _ := (hf.at_top_mul_at_top $ tendsto_neg_at_bot_at_top.comp hg),
by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp this
lemma tendsto.at_bot_mul_at_top (hf : tendsto f l at_bot) (hg : tendsto g l at_top) :
tendsto (λ x, f x * g x) l at_bot :=
have tendsto (λ x, (-f x) * g x) l at_top :=
( (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top hg),
by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp this
lemma tendsto.at_bot_mul_at_bot (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) :
tendsto (λ x, f x * g x) l at_top :=
have tendsto (λ x, (-f x) * (-g x)) l at_top :=
(tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top (tendsto_neg_at_bot_at_top.comp hg),
by simpa only [neg_mul_neg] using this
end ordered_ring
section linear_ordered_add_comm_group
variables [linear_ordered_add_comm_group α]
/-- $\lim_{x\to+\infty}|x|=+\infty$ -/
lemma tendsto_abs_at_top_at_top : tendsto (abs : α → α) at_top at_top :=
tendsto_at_top_mono le_abs_self tendsto_id
/-- $\lim_{x\to-\infty}|x|=+\infty$ -/
lemma tendsto_abs_at_bot_at_top : tendsto (abs : α → α) at_bot at_top :=
tendsto_at_top_mono neg_le_abs_self tendsto_neg_at_bot_at_top
end linear_ordered_add_comm_group
section linear_ordered_semiring
variables [linear_ordered_semiring α] {l : filter β} {f : β → α}
lemma tendsto.at_top_of_const_mul {c : α} (hc : 0 < c) (hf : tendsto (λ x, c * f x) l at_top) :
tendsto f l at_top :=
tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (c * b)).mono $ λ x hx, le_of_mul_le_mul_left hx hc
lemma tendsto.at_top_of_mul_const {c : α} (hc : 0 < c) (hf : tendsto (λ x, f x * c) l at_top) :
tendsto f l at_top :=
tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (b * c)).mono $ λ x hx, le_of_mul_le_mul_right hx hc
end linear_ordered_semiring
lemma nonneg_of_eventually_pow_nonneg [linear_ordered_ring α] {a : α}
(h : ∀ᶠ n in at_top, 0 ≤ a ^ (n : ℕ)) : 0 ≤ a :=
let ⟨n, hn⟩ := (tendsto_bit1_at_top.eventually h).exists in pow_bit1_nonneg_iff.1 hn
section linear_ordered_field
variables [linear_ordered_field α] {l : filter β} {f : β → α} {r : α}
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`filter.tendsto.const_mul_at_top'` instead. -/
lemma tendsto.const_mul_at_top (hr : 0 < r) (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
tendsto.at_top_of_const_mul (inv_pos.2 hr) $ by simpa only [inv_mul_cancel_left' hr.ne']
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`filter.tendsto.at_top_mul_const'` instead. -/
lemma tendsto.at_top_mul_const (hr : 0 < r) (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
by simpa only [mul_comm] using hf.const_mul_at_top hr
/-- If a function tends to infinity along a filter, then this function divided by a positive
constant also tends to infinity. -/
lemma tendsto.at_top_div_const (hr : 0 < r) (hf : tendsto f l at_top) :
tendsto (λx, f x / r) l at_top :=
by simpa only [div_eq_mul_inv] using hf.at_top_mul_const (inv_pos.2 hr)
/-- If a function tends to infinity along a filter, then this function multiplied by a negative
constant (on the left) tends to negative infinity. -/
lemma tendsto.neg_const_mul_at_top (hr : r < 0) (hf : tendsto f l at_top) :
tendsto (λ x, r * f x) l at_bot :=
by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg]
using tendsto_neg_at_top_at_bot.comp (hf.const_mul_at_top (neg_pos.2 hr))
/-- If a function tends to infinity along a filter, then this function multiplied by a negative
constant (on the right) tends to negative infinity. -/
lemma tendsto.at_top_mul_neg_const (hr : r < 0) (hf : tendsto f l at_top) :
tendsto (λ x, f x * r) l at_bot :=
by simpa only [mul_comm] using hf.neg_const_mul_at_top hr
/-- If a function tends to negative infinity along a filter, then this function multiplied by
a positive constant (on the left) also tends to negative infinity. -/
lemma tendsto.const_mul_at_bot (hr : 0 < r) (hf : tendsto f l at_bot) :
tendsto (λx, r * f x) l at_bot :=
by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg]
using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).const_mul_at_top hr)
/-- If a function tends to negative infinity along a filter, then this function multiplied by
a positive constant (on the right) also tends to negative infinity. -/
lemma tendsto.at_bot_mul_const (hr : 0 < r) (hf : tendsto f l at_bot) :
tendsto (λx, f x * r) l at_bot :=
by simpa only [mul_comm] using hf.const_mul_at_bot hr
/-- If a function tends to negative infinity along a filter, then this function divided by
a positive constant also tends to negative infinity. -/
lemma tendsto.at_bot_div_const (hr : 0 < r) (hf : tendsto f l at_bot) :
tendsto (λx, f x / r) l at_bot :=
by simpa only [div_eq_mul_inv] using hf.at_bot_mul_const (inv_pos.2 hr)
/-- If a function tends to negative infinity along a filter, then this function multiplied by
a negative constant (on the left) tends to positive infinity. -/
lemma tendsto.neg_const_mul_at_bot (hr : r < 0) (hf : tendsto f l at_bot) :
tendsto (λ x, r * f x) l at_top :=
by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg]
using tendsto_neg_at_bot_at_top.comp (hf.const_mul_at_bot (neg_pos.2 hr))
/-- If a function tends to negative infinity along a filter, then this function multiplied by
a negative constant (on the right) tends to positive infinity. -/
lemma tendsto.at_bot_mul_neg_const (hr : r < 0) (hf : tendsto f l at_bot) :
tendsto (λ x, f x * r) l at_top :=
by simpa only [mul_comm] using hf.neg_const_mul_at_bot hr
lemma tendsto_const_mul_pow_at_top {c : α} {n : ℕ}
(hn : 1 ≤ n) (hc : 0 < c) : tendsto (λ x, c * x^n) at_top at_top :=
tendsto.const_mul_at_top hc (tendsto_pow_at_top hn)
lemma tendsto_const_mul_pow_at_top_iff (c : α) (n : ℕ) :
tendsto (λ x, c * x^n) at_top at_top ↔ 1 ≤ n ∧ 0 < c :=
begin
refine ⟨λ h, _, λ h, tendsto_const_mul_pow_at_top h.1 h.2⟩,
simp only [tendsto_at_top, eventually_at_top] at h,
have : 0 < c := let ⟨x, hx⟩ := h 1 in
pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one (hx (max x 1) (le_max_left x 1)))
(pow_nonneg (le_trans zero_le_one (le_max_right x 1)) n),
refine ⟨nat.succ_le_iff.mp (lt_of_le_of_ne (zero_le n) (ne.symm (λ hn, _))), this⟩,
obtain ⟨x, hx⟩ := h (c + 1),
specialize hx x le_rfl,
rw [hn, pow_zero, mul_one, add_le_iff_nonpos_right] at hx,
exact absurd hx (not_le.mpr zero_lt_one),
end
lemma tendsto_neg_const_mul_pow_at_top {c : α} {n : ℕ}
(hn : 1 ≤ n) (hc : c < 0) : tendsto (λ x, c * x^n) at_top at_bot :=
tendsto.neg_const_mul_at_top hc (tendsto_pow_at_top hn)
lemma tendsto_neg_const_mul_pow_at_top_iff (c : α) (n : ℕ) :
tendsto (λ x, c * x^n) at_top at_bot ↔ 1 ≤ n ∧ c < 0 :=
begin
refine ⟨λ h, _, λ h, tendsto_neg_const_mul_pow_at_top h.1 h.2⟩,
simp only [tendsto_at_bot, eventually_at_top] at h,
have : c < 0 := let ⟨x, hx⟩ := h (-1) in
neg_of_mul_neg_right (lt_of_le_of_lt (hx (max x 1) (le_max_left x 1)) (by simp [zero_lt_one]))
(pow_nonneg (le_trans zero_le_one (le_max_right x 1)) n),
refine ⟨nat.succ_le_iff.mp (lt_of_le_of_ne (zero_le n) (ne.symm (λ hn, _))), this⟩,
obtain ⟨x, hx⟩ := h (c - 1),
specialize hx x le_rfl,
rw [hn, pow_zero, mul_one, le_sub, sub_self] at hx,
exact absurd hx (not_le.mpr zero_lt_one),
end
end linear_ordered_field
open_locale filter
lemma tendsto_at_top' [nonempty α] [semilattice_sup α] {f : α → β} {l : filter β} :
tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) :=
by simp only [tendsto_def, mem_at_top_sets]; refl
lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] {f : α → β} {l : filter β} :
tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) :=
@tendsto_at_top' (order_dual α) _ _ _ _ _
theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} :
tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s :=
by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl
theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} :
tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s :=
@tendsto_at_top_principal _ (order_dual β) _ _ _ _
/-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/
lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} :
tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a :=
iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal
lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} :
tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b :=
@tendsto_at_top_at_top α (order_dual β) _ _ _ f
lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} :
tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a :=
@tendsto_at_top_at_top (order_dual α) β _ _ _ f
lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} :
tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b :=
@tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f
lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f)
(h : ∀ b, ∃ a, b ≤ f a) :
tendsto f at_top at_top :=
tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in
mem_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha')
lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f)
(h : ∀ b, ∃ a, f a ≤ b) :
tendsto f at_bot at_bot :=
tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in
mem_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha
lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β]
{f : α → β} (hf : monotone f) :
tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a :=
tendsto_at_top_at_top.trans $ forall_congr $ λ b, exists_congr $ λ a,
⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩
lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β]
{f : α → β} (hf : monotone f) :
tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b :=
tendsto_at_bot_at_bot.trans $ forall_congr $ λ b, exists_congr $ λ a,
⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩
alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top
alias tendsto_at_bot_at_bot_of_monotone ← monotone.tendsto_at_bot_at_bot
alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff
alias tendsto_at_bot_at_bot_iff_of_monotone ← monotone.tendsto_at_bot_at_bot_iff
lemma tendsto_at_top_embedding [preorder β] [preorder γ]
{f : α → β} {e : β → γ} {l : filter α}
(hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) :
tendsto (e ∘ f) l at_top ↔ tendsto f l at_top :=
begin
refine ⟨_, (tendsto_at_top_at_top_of_monotone (λ b₁ b₂, (hm b₁ b₂).2) hu).comp⟩,
rw [tendsto_at_top, tendsto_at_top],
exact λ hc b, (hc (e b)).mono (λ a, (hm b (f a)).1)
end
/-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/
lemma tendsto_at_bot_embedding [preorder β] [preorder γ]
{f : α → β} {e : β → γ} {l : filter α}
(hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) :
tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot :=
@tendsto_at_top_embedding α (order_dual β) (order_dual γ) _ _ f e l (function.swap hm) hu
lemma tendsto_finset_range : tendsto finset.range at_top at_top :=
finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range
lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) :=
begin
refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _,
refine le_infi (λ s, le_principal_iff.2 $ mem_infi.2 _),
refine ⟨↑s, s.finite_to_set, _, λ i, mem_principal_self _, _⟩,
simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset,
finset.mem_singleton, finset.subset_iff, forall_eq], dsimp,
exact λ t, id
end
/-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then
`tendsto f at_top at_top`. -/
lemma tendsto_at_top_finset_of_monotone [preorder β]
{f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) :
tendsto f at_top at_top :=
begin
simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal],
intro a,
rcases h' a with ⟨b, hb⟩,
exact eventually.mono (mem_at_top b)
(λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')),
end
alias tendsto_at_top_finset_of_monotone ← monotone.tendsto_at_top_finset
lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) :
tendsto (finset.image j) at_top at_top :=
(finset.image_mono j).tendsto_at_top_finset $ assume a,
⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩
lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) :
tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top :=
(finset.monotone_preimage hf).tendsto_at_top_finset $
λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩
lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] :
(at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) :=
begin
casesI (is_empty_or_nonempty β₁).symm,
casesI (is_empty_or_nonempty β₂).symm,
{ simp [at_top, prod_infi_left, prod_infi_right, infi_prod],
exact infi_comm, },
{ simp only [at_top.filter_eq_bot_of_is_empty, prod_bot] },
{ simp only [at_top.filter_eq_bot_of_is_empty, bot_prod] },
end
lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] :
(at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) :=
@prod_at_top_at_top_eq (order_dual β₁) (order_dual β₂) _ _
lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂]
(u₁ : β₁ → α₁) (u₂ : β₂ → α₂) :
(map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top :=
by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def]
lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂]
(u₁ : β₁ → α₁) (u₂ : β₂ → α₂) :
(map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot :=
@prod_map_at_top_eq _ _ (order_dual β₁) (order_dual β₂) _ _ _ _
lemma tendsto.subseq_mem {F : filter α} {V : ℕ → set α} (h : ∀ n, V n ∈ F) {u : ℕ → α}
(hu : tendsto u at_top F) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, u (φ n) ∈ V n :=
extraction_forall_of_eventually' (λ n, tendsto_at_top'.mp hu _ (h n) : ∀ n, ∃ N, ∀ k ≥ N, u k ∈ V n)
lemma tendsto_at_bot_diagonal [semilattice_inf α] : tendsto (λ a : α, (a, a)) at_bot at_bot :=
by { rw ← prod_at_bot_at_bot_eq, exact tendsto_id.prod_mk tendsto_id }
lemma tendsto_at_top_diagonal [semilattice_sup α] : tendsto (λ a : α, (a, a)) at_top at_top :=
by { rw ← prod_at_top_at_top_eq, exact tendsto_id.prod_mk tendsto_id }
lemma tendsto.prod_map_prod_at_bot [semilattice_inf γ] {F : filter α} {G : filter β}
{f : α → γ} {g : β → γ} (hf : tendsto f F at_bot) (hg : tendsto g G at_bot) :
tendsto (prod.map f g) (F ×ᶠ G) at_bot :=
by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map hg, }
lemma tendsto.prod_map_prod_at_top [semilattice_sup γ] {F : filter α} {G : filter β}
{f : α → γ} {g : β → γ} (hf : tendsto f F at_top) (hg : tendsto g G at_top) :
tendsto (prod.map f g) (F ×ᶠ G) at_top :=
by { rw ← prod_at_top_at_top_eq, exact hf.prod_map hg, }
lemma tendsto.prod_at_bot [semilattice_inf α] [semilattice_inf γ]
{f g : α → γ} (hf : tendsto f at_bot at_bot) (hg : tendsto g at_bot at_bot) :
tendsto (prod.map f g) at_bot at_bot :=
by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map_prod_at_bot hg, }
lemma tendsto.prod_at_top [semilattice_sup α] [semilattice_sup γ]
{f g : α → γ} (hf : tendsto f at_top at_top) (hg : tendsto g at_top at_top) :
tendsto (prod.map f g) at_top at_top :=
by { rw ← prod_at_top_at_top_eq, exact hf.prod_map_prod_at_top hg, }
lemma eventually_at_bot_prod_self [semilattice_inf α] [nonempty α] {p : α × α → Prop} :
(∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k l, k ≤ a → l ≤ a → p (k, l)) :=
by simp [← prod_at_bot_at_bot_eq, at_bot_basis.prod_self.eventually_iff]
lemma eventually_at_top_prod_self [semilattice_sup α] [nonempty α] {p : α × α → Prop} :
(∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k l, a ≤ k → a ≤ l → p (k, l)) :=
by simp [← prod_at_top_at_top_eq, at_top_basis.prod_self.eventually_iff]
lemma eventually_at_bot_prod_self' [semilattice_inf α] [nonempty α] {p : α × α → Prop} :
(∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k ≤ a, ∀ l ≤ a, p (k, l)) :=
begin
rw filter.eventually_at_bot_prod_self,
apply exists_congr,
tauto,
end
lemma eventually_at_top_prod_self' [semilattice_sup α] [nonempty α] {p : α × α → Prop} :
(∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k ≥ a, ∀ l ≥ a, p (k, l)) :=
begin
rw filter.eventually_at_top_prod_self,
apply exists_congr,
tauto,
end
/-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a
Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an
insertion and a connetion above `b'`. -/
lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)
(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) :
map f at_top = at_top :=
begin
refine le_antisymm
(hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _,
rw [@map_at_top_eq _ _ ⟨g b'⟩],
refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _),
rw [mem_Ici, sup_le_iff] at hb,
exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 (le_refl _)) (hgi _ hb.2)⟩
end
lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β)
(hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) :
map f at_bot = at_bot :=
@map_at_top_eq_of_gc (order_dual α) (order_dual β) _ _ _ _ _ hf.order_dual gc hgi
lemma map_coe_at_top_of_Ici_subset [semilattice_sup α] {a : α} {s : set α} (h : Ici a ⊆ s) :
map (coe : s → α) at_top = at_top :=
begin
have : directed (≥) (λ x : s, 𝓟 (Ici x)),
{ intros x y,
use ⟨x ⊔ y ⊔ a, h le_sup_right⟩,
simp only [ge_iff_le, principal_mono, Ici_subset_Ici, ← subtype.coe_le_coe, subtype.coe_mk],
exact ⟨le_sup_left.trans le_sup_left, le_sup_right.trans le_sup_left⟩ },
haveI : nonempty s := ⟨⟨a, h le_rfl⟩⟩,
simp only [le_antisymm_iff, at_top, le_infi_iff, le_principal_iff, mem_map, mem_set_of_eq,
map_infi_eq this, map_principal],
split,
{ intro x,
refine mem_of_superset (mem_infi_of_mem ⟨x ⊔ a, h le_sup_right⟩ (mem_principal_self _)) _,
rintro _ ⟨y, hy, rfl⟩,
exact le_trans le_sup_left (subtype.coe_le_coe.2 hy) },
{ intro x,
filter_upwards [mem_at_top (↑x ⊔ a)],
intros b hb,
exact ⟨⟨b, h $ le_sup_right.trans hb⟩, subtype.coe_le_coe.1 (le_sup_left.trans hb), rfl⟩ }
end
/-- The image of the filter `at_top` on `Ici a` under the coercion equals `at_top`. -/
@[simp] lemma map_coe_Ici_at_top [semilattice_sup α] (a : α) :
map (coe : Ici a → α) at_top = at_top :=
map_coe_at_top_of_Ici_subset (subset.refl _)
/-- The image of the filter `at_top` on `Ioi a` under the coercion equals `at_top`. -/
@[simp] lemma map_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] (a : α) :
map (coe : Ioi a → α) at_top = at_top :=
begin
rcases no_top a with ⟨b, hb⟩,
exact map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb)
end
/-- The `at_top` filter for an open interval `Ioi a` comes from the `at_top` filter in the ambient
order. -/
lemma at_top_Ioi_eq [semilattice_sup α] (a : α) :
at_top = comap (coe : Ioi a → α) at_top :=
begin
nontriviality,
rcases nontrivial_iff_nonempty.1 ‹_› with ⟨b, hb⟩,
rw [← map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb), comap_map subtype.coe_injective]
end
/-- The `at_top` filter for an open interval `Ici a` comes from the `at_top` filter in the ambient
order. -/
lemma at_top_Ici_eq [semilattice_sup α] (a : α) :
at_top = comap (coe : Ici a → α) at_top :=
by rw [← map_coe_Ici_at_top a, comap_map subtype.coe_injective]
/-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient
order. -/
@[simp] lemma map_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] (a : α) :
map (coe : Iio a → α) at_bot = at_bot :=
@map_coe_Ioi_at_top (order_dual α) _ _ _
/-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient
order. -/
lemma at_bot_Iio_eq [semilattice_inf α] (a : α) :
at_bot = comap (coe : Iio a → α) at_bot :=
@at_top_Ioi_eq (order_dual α) _ _
/-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient
order. -/
@[simp] lemma map_coe_Iic_at_bot [semilattice_inf α] (a : α) :
map (coe : Iic a → α) at_bot = at_bot :=
@map_coe_Ici_at_top (order_dual α) _ _
/-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient
order. -/
lemma at_bot_Iic_eq [semilattice_inf α] (a : α) :
at_bot = comap (coe : Iic a → α) at_bot :=
@at_top_Ici_eq (order_dual α) _ _
lemma tendsto_Ioi_at_top [semilattice_sup α] {a : α} {f : β → Ioi a}
{l : filter β} :
tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top :=
by rw [at_top_Ioi_eq, tendsto_comap_iff]
lemma tendsto_Iio_at_bot [semilattice_inf α] {a : α} {f : β → Iio a}
{l : filter β} :
tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot :=
by rw [at_bot_Iio_eq, tendsto_comap_iff]
lemma tendsto_Ici_at_top [semilattice_sup α] {a : α} {f : β → Ici a} {l : filter β} :
tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top :=
by rw [at_top_Ici_eq, tendsto_comap_iff]
lemma tendsto_Iic_at_bot [semilattice_inf α] {a : α} {f : β → Iic a} {l : filter β} :
tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot :=
by rw [at_bot_Iic_eq, tendsto_comap_iff]
@[simp] lemma tendsto_comp_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] {a : α}
{f : α → β} {l : filter β} :
tendsto (λ x : Ioi a, f x) at_top l ↔ tendsto f at_top l :=
by rw [← map_coe_Ioi_at_top a, tendsto_map'_iff]
@[simp] lemma tendsto_comp_coe_Ici_at_top [semilattice_sup α] {a : α}
{f : α → β} {l : filter β} :
tendsto (λ x : Ici a, f x) at_top l ↔ tendsto f at_top l :=
by rw [← map_coe_Ici_at_top a, tendsto_map'_iff]
@[simp] lemma tendsto_comp_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] {a : α}
{f : α → β} {l : filter β} :
tendsto (λ x : Iio a, f x) at_bot l ↔ tendsto f at_bot l :=
by rw [← map_coe_Iio_at_bot a, tendsto_map'_iff]
@[simp] lemma tendsto_comp_coe_Iic_at_bot [semilattice_inf α] {a : α}
{f : α → β} {l : filter β} :
tendsto (λ x : Iic a, f x) at_bot l ↔ tendsto f at_bot l :=
by rw [← map_coe_Iic_at_bot a, tendsto_map'_iff]
lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top :=
map_at_top_eq_of_gc (λa, a - k) k
(assume a b h, add_le_add_right h k)
(assume a b h, (nat.le_sub_right_iff_add_le h).symm)
(assume a h, by rw [nat.sub_add_cancel h])
lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top :=
map_at_top_eq_of_gc (λa, a + k) 0
(assume a b h, nat.sub_le_sub_right h _)
(assume a b _, nat.sub_le_right_iff_le_add)
(assume b _, by rw [nat.add_sub_cancel])
lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top :=
le_of_eq (map_add_at_top_eq_nat k)
lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top :=
le_of_eq (map_sub_at_top_eq_nat k)
lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) :
tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l :=
show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l,
by rw [← tendsto_map'_iff, map_add_at_top_eq_nat]
lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top :=
map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1
(assume a b h, nat.div_le_div_right h)
(assume a b _,
calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff]
... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk
... ↔ _ :
begin
cases k,
exact (lt_irrefl _ hk).elim,
rw [add_mul, one_mul, nat.succ_sub_succ_eq_sub,
nat.sub_zero, nat.add_succ, nat.lt_succ_iff],
end)
(assume b _,
calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk]
... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _)
/-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded
above, then `tendsto u at_top at_top`. -/
lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α]
{u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) :
tendsto u at_top at_top :=
begin
apply h.tendsto_at_top_at_top,
intro b,
rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩,
exact ⟨N, le_of_lt hN⟩,
end
/-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded
below, then `tendsto u at_bot at_bot`. -/
lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α]
{u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) :
tendsto u at_bot at_bot :=
@tendsto_at_top_at_top_of_monotone' (order_dual ι) (order_dual α) _ _ _ h.order_dual H
lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β]
{f : α → β} (h : tendsto f at_top at_top) :
¬ bdd_above (range f) :=
begin
rintros ⟨M, hM⟩,
cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha,
apply lt_irrefl M,
calc
M < f a : ha a (le_refl _)
... ≤ M : hM (set.mem_range_self a)
end
lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β]
{f : α → β} (h : tendsto f at_top at_bot) :
¬ bdd_below (range f) :=
@unbounded_of_tendsto_at_top _ (order_dual β) _ _ _ _ _ h
lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_top_order β]
{f : α → β} (h : tendsto f at_bot at_top) :
¬ bdd_above (range f) :=
@unbounded_of_tendsto_at_top (order_dual α) _ _ _ _ _ _ h
lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β]
{f : α → β} (h : tendsto f at_bot at_bot) :
¬ bdd_below (range f) :=
@unbounded_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ h
/-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then
it tends to `at_top` along `at_top`. -/
lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι}
{u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) :
tendsto u at_top at_top :=
h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists
/-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then
it tends to `at_bot` along `at_bot`. -/
lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι}
{u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) :
tendsto u at_bot at_bot :=
@tendsto_at_top_of_monotone_of_filter (order_dual ι) (order_dual α) _ _ _ _ h.order_dual _ hu
lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α}
{φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l]
(H : tendsto (u ∘ φ) l at_top) :
tendsto u at_top at_top :=
tendsto_at_top_of_monotone_of_filter h (tendsto_map' H)
lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α}
{φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l]
(H : tendsto (u ∘ φ) l at_bot) :
tendsto u at_bot at_bot :=
tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H)
/-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient
condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with
`at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of
`Π b in s, f b` as `s → at_top` with the similar set for `g`. -/
@[to_additive]
lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α}
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) :
at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) :=
by rw [map_at_top_eq, map_at_top_eq];
from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $
by simp [set.image_subset_iff]; exact hv)
lemma has_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α}
{p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α}
(h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l :=
(at_top_basis.tendsto_iff hl.to_has_basis).2 $ assume i hi,
⟨i, trivial, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩
namespace is_countably_generated
/-- An abstract version of continuity of sequentially continuous functions on metric spaces:
if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u`
converging to `k`, `f ∘ u` tends to `l`. -/
lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β}
(hcb : k.is_countably_generated) :
tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) :=
suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l,
from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩,
begin
rcases hcb.exists_antimono_basis with ⟨g, gbasis, gmon, -⟩,
contrapose,
simp only [not_forall, gbasis.tendsto_left_iff, exists_const, not_exists, not_imp],
rintro ⟨B, hBl, hfBk⟩,
choose x h using hfBk,
use x, split,
{ exact (at_top_basis.tendsto_iff gbasis).2
(λ i _, ⟨i, trivial, λ j hj, gmon trivial trivial hj (h j).1⟩) },
{ simp only [tendsto_at_top', (∘), not_forall, not_exists],
use [B, hBl],
intro i, use [i, (le_refl _)],
apply (h i).right },
end
lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β}
(hcb : k.is_countably_generated) :
(∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l :=
hcb.tendsto_iff_seq_tendsto.2
lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f)
{u : ℕ → α}
(hx : ne_bot (f ⊓ map u at_top)) :
∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) :=
begin
rcases hf.exists_antimono_basis with ⟨B, h⟩,
have : ∀ N, ∃ n ≥ N, u n ∈ B N,
from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N,
choose φ hφ using this,
cases forall_and_distrib.mp hφ with φ_ge φ_in,
have lim_uφ : tendsto (u ∘ φ) at_top f,
from h.tendsto φ_in,
have lim_φ : tendsto φ at_top at_top,
from (tendsto_at_top_mono φ_ge tendsto_id),
obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ),
from strict_mono_subseq_of_tendsto_at_top lim_φ,
exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp hψ.tendsto_at_top⟩,
end
end is_countably_generated
end filter
open filter finset
section
variables {R : Type*} [linear_ordered_semiring R]
lemma exists_lt_mul_self (a : R) : ∃ x ≥ 0, a < x * x :=
let ⟨x, hxa, hx0⟩ :=((tendsto_mul_self_at_top.eventually (eventually_gt_at_top a)).and
(eventually_ge_at_top 0)).exists
in ⟨x, hx0, hxa⟩
lemma exists_le_mul_self (a : R) : ∃ x ≥ 0, a ≤ x * x :=
let ⟨x, hx0, hxa⟩ := exists_lt_mul_self a in ⟨x, hx0, hxa.le⟩
end
namespace order_iso
variables [preorder α] [preorder β]
@[simp] lemma comap_at_top (e : α ≃o β) : comap e at_top = at_top :=
by simp [at_top, ← e.surjective.infi_comp]
@[simp] lemma comap_at_bot (e : α ≃o β) : comap e at_bot = at_bot :=
e.dual.comap_at_top
@[simp] lemma map_at_top (e : α ≃o β) : map ⇑e at_top = at_top :=
by rw [← e.comap_at_top, map_comap_of_surjective e.surjective]
@[simp] lemma map_at_bot (e : α ≃o β) : map ⇑e at_bot = at_bot :=
e.dual.map_at_top
lemma tendsto_at_top (e : α ≃o β) : tendsto e at_top at_top :=
e.map_at_top.le
lemma tendsto_at_bot (e : α ≃o β) : tendsto e at_bot at_bot :=
e.map_at_bot.le
@[simp] lemma tendsto_at_top_iff {l : filter γ} {f : γ → α} (e : α ≃o β) :
tendsto (λ x, e (f x)) l at_top ↔ tendsto f l at_top :=
by rw [← e.comap_at_top, tendsto_comap_iff]
@[simp] lemma tendsto_at_bot_iff {l : filter γ} {f : γ → α} (e : α ≃o β) :
tendsto (λ x, e (f x)) l at_bot ↔ tendsto f l at_bot :=
e.dual.tendsto_at_top_iff
end order_iso
/-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g`
to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters
`at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide.
The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under
the same assumptions.-/
@[to_additive]
lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β}
(hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) :
map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top :=
begin
apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _),
{ refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩,
refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩,
rw [← finset.prod_image (hg.inj_on _)],
refine (prod_subset (subset_union_left _ _) _).symm,
simp only [finset.mem_union, finset.mem_image],
refine λ y hy hyt, hf y (mt _ hyt),
rintros ⟨x, rfl⟩,
exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ },
{ refine ⟨s.image g, λ t ht, _⟩,
simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)],
exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ }
end
/-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g`
to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the
filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide.
This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under
the same assumptions.-/
add_decl_doc function.injective.map_at_top_finset_sum_eq
|
0c16f0b5345ea842fb2e7565806a23f9ab43ad68 | 5d76f062116fa5bd22eda20d6fd74da58dba65bb | /src/pairing_based_snark_scheme.lean | 701b78a3e150744e633fd7d735979cc641d6d246 | [] | no_license | brando90/formal_baby_snark | 59e4732dfb43f97776a3643f2731262f58d2bb81 | 4732da237784bd461ff949729cc011db83917907 | refs/heads/master | 1,682,650,246,414 | 1,621,103,975,000 | 1,621,103,975,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 680 | lean |
import data.mv_polynomial.basic
section
/-!
This file should contain a general scheme for pairing based SNARKs in the sense of
What are the toxic waste elements?
What are the CRS elements?
What are the proof elements?
What equalities does the verification/the crs process enforce?
Does all this express in full generality the possibilities for a Pairing Based SNARK?
Should the scheme include the QAP as arguments, or should there be a separate function?
-/
-- TODO is a structure correct here, or a dependent tuple?
structure pairing_based_snark_scheme (F : Type) [field F] (toxic : Type) (crs_size : ℕ) (crs : fin crs_size -> mv_polynomial toxic F) (prove : sorry) |
fa97045f7f7aa757d2b3fd1f804540826f84d86a | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/polynomial/erase_lead.lean | 6dc66ac43f2fdfcae398e113fd6f7e72e0ccb807 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,977 | lean | /-
Copyright (c) 2020 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import data.polynomial.degree.trailing_degree
import data.polynomial.inductions
/-!
# Erase the leading term of a univariate polynomial
## Definition
* `erase_lead f`: the polynomial `f - leading term of f`
`erase_lead` serves as reduction step in an induction, shaving off one monomial from a polynomial.
The definition is set up so that it does not mention subtraction in the definition,
and thus works for polynomials over semirings as well as rings.
-/
noncomputable theory
open_locale classical
open polynomial finset
namespace polynomial
variables {R : Type*} [semiring R] {f : polynomial R}
/-- `erase_lead f` for a polynomial `f` is the polynomial obtained by
subtracting from `f` the leading term of `f`. -/
def erase_lead (f : polynomial R) : polynomial R :=
polynomial.erase f.nat_degree f
section erase_lead
lemma erase_lead_support (f : polynomial R) :
f.erase_lead.support = f.support.erase f.nat_degree :=
by simp only [erase_lead, support_erase]
lemma erase_lead_coeff (i : ℕ) :
f.erase_lead.coeff i = if i = f.nat_degree then 0 else f.coeff i :=
by simp only [erase_lead, coeff_erase]
@[simp] lemma erase_lead_coeff_nat_degree : f.erase_lead.coeff f.nat_degree = 0 :=
by simp [erase_lead_coeff]
lemma erase_lead_coeff_of_ne (i : ℕ) (hi : i ≠ f.nat_degree) :
f.erase_lead.coeff i = f.coeff i :=
by simp [erase_lead_coeff, hi]
@[simp] lemma erase_lead_zero : erase_lead (0 : polynomial R) = 0 :=
by simp only [erase_lead, erase_zero]
@[simp] lemma erase_lead_add_monomial_nat_degree_leading_coeff (f : polynomial R) :
f.erase_lead + monomial f.nat_degree f.leading_coeff = f :=
begin
ext i,
simp only [erase_lead_coeff, coeff_monomial, coeff_add, @eq_comm _ _ i],
split_ifs with h,
{ subst i, simp only [leading_coeff, zero_add] },
{ exact add_zero _ }
end
@[simp] lemma erase_lead_add_C_mul_X_pow (f : polynomial R) :
f.erase_lead + (C f.leading_coeff) * X ^ f.nat_degree = f :=
by rw [C_mul_X_pow_eq_monomial, erase_lead_add_monomial_nat_degree_leading_coeff]
@[simp] lemma self_sub_monomial_nat_degree_leading_coeff {R : Type*} [ring R] (f : polynomial R) :
f - monomial f.nat_degree f.leading_coeff = f.erase_lead :=
(eq_sub_iff_add_eq.mpr (erase_lead_add_monomial_nat_degree_leading_coeff f)).symm
@[simp] lemma self_sub_C_mul_X_pow {R : Type*} [ring R] (f : polynomial R) :
f - (C f.leading_coeff) * X ^ f.nat_degree = f.erase_lead :=
by rw [C_mul_X_pow_eq_monomial, self_sub_monomial_nat_degree_leading_coeff]
lemma erase_lead_ne_zero (f0 : 2 ≤ f.support.card) : erase_lead f ≠ 0 :=
begin
rw [ne.def, ← card_support_eq_zero, erase_lead_support],
exact (zero_lt_one.trans_le $ (tsub_le_tsub_right f0 1).trans
finset.pred_card_le_card_erase).ne.symm
end
@[simp] lemma nat_degree_not_mem_erase_lead_support : f.nat_degree ∉ (erase_lead f).support :=
by simp [not_mem_support_iff]
lemma ne_nat_degree_of_mem_erase_lead_support {a : ℕ} (h : a ∈ (erase_lead f).support) :
a ≠ f.nat_degree :=
by { rintro rfl, exact nat_degree_not_mem_erase_lead_support h }
lemma erase_lead_support_card_lt (h : f ≠ 0) : (erase_lead f).support.card < f.support.card :=
begin
rw erase_lead_support,
exact card_lt_card (erase_ssubset $ nat_degree_mem_support_of_nonzero h)
end
lemma erase_lead_card_support {c : ℕ} (fc : f.support.card = c) :
f.erase_lead.support.card = c - 1 :=
begin
by_cases f0 : f = 0,
{ rw [← fc, f0, erase_lead_zero, support_zero, card_empty] },
{ rw [erase_lead_support, card_erase_of_mem (nat_degree_mem_support_of_nonzero f0), fc],
exact c.pred_eq_sub_one },
end
lemma erase_lead_card_support' {c : ℕ} (fc : f.support.card = c + 1) :
f.erase_lead.support.card = c :=
erase_lead_card_support fc
@[simp] lemma erase_lead_monomial (i : ℕ) (r : R) :
erase_lead (monomial i r) = 0 :=
begin
by_cases hr : r = 0,
{ subst r, simp only [monomial_zero_right, erase_lead_zero] },
{ rw [erase_lead, nat_degree_monomial _ _ hr, erase_monomial] }
end
@[simp] lemma erase_lead_C (r : R) : erase_lead (C r) = 0 :=
erase_lead_monomial _ _
@[simp] lemma erase_lead_X : erase_lead (X : polynomial R) = 0 :=
erase_lead_monomial _ _
@[simp] lemma erase_lead_X_pow (n : ℕ) : erase_lead (X ^ n : polynomial R) = 0 :=
by rw [X_pow_eq_monomial, erase_lead_monomial]
@[simp] lemma erase_lead_C_mul_X_pow (r : R) (n : ℕ) : erase_lead (C r * X ^ n) = 0 :=
by rw [C_mul_X_pow_eq_monomial, erase_lead_monomial]
lemma erase_lead_degree_le : (erase_lead f).degree ≤ f.degree :=
begin
rw degree_le_iff_coeff_zero,
intros i hi,
rw erase_lead_coeff,
split_ifs with h, { refl },
apply coeff_eq_zero_of_degree_lt hi
end
lemma erase_lead_nat_degree_le : (erase_lead f).nat_degree ≤ f.nat_degree :=
nat_degree_le_nat_degree erase_lead_degree_le
lemma erase_lead_nat_degree_lt (f0 : 2 ≤ f.support.card) :
(erase_lead f).nat_degree < f.nat_degree :=
lt_of_le_of_ne erase_lead_nat_degree_le $ ne_nat_degree_of_mem_erase_lead_support $
nat_degree_mem_support_of_nonzero $ erase_lead_ne_zero f0
lemma erase_lead_nat_degree_lt_or_erase_lead_eq_zero (f : polynomial R) :
(erase_lead f).nat_degree < f.nat_degree ∨ f.erase_lead = 0 :=
begin
by_cases h : f.support.card ≤ 1,
{ right,
rw ← C_mul_X_pow_eq_self h,
simp },
{ left,
apply erase_lead_nat_degree_lt (lt_of_not_ge h) }
end
end erase_lead
/-- An induction lemma for polynomials. It takes a natural number `N` as a parameter, that is
required to be at least as big as the `nat_degree` of the polynomial. This is useful to prove
results where you want to change each term in a polynomial to something else depending on the
`nat_degree` of the polynomial itself and not on the specific `nat_degree` of each term. -/
lemma induction_with_nat_degree_le {R : Type*} [semiring R] {P : polynomial R → Prop} (N : ℕ)
(P_0 : P 0)
(P_C_mul_pow : ∀ n : ℕ, ∀ r : R, r ≠ 0 → n ≤ N → P (C r * X ^ n))
(P_C_add : ∀ f g : polynomial R, f.nat_degree ≤ N → g.nat_degree ≤ N → P f → P g → P (f + g)) :
∀ f : polynomial R, f.nat_degree ≤ N → P f :=
begin
intros f df,
generalize' hd : card f.support = c,
revert f,
induction c with c hc,
{ assume f df f0,
convert P_0,
simpa only [support_eq_empty, card_eq_zero] using f0},
-- exact λ f df f0, by rwa (finsupp.support_eq_empty.mp (card_eq_zero.mp f0)) },
{ intros f df f0,
rw ← erase_lead_add_C_mul_X_pow f,
refine P_C_add f.erase_lead _ (erase_lead_nat_degree_le.trans df) _ _ _,
{ exact (nat_degree_C_mul_X_pow_le f.leading_coeff f.nat_degree).trans df },
{ exact hc _ (erase_lead_nat_degree_le.trans df) (erase_lead_card_support f0) },
{ refine P_C_mul_pow _ _ _ df,
rw [ne.def, leading_coeff_eq_zero],
rintro rfl,
exact not_le.mpr c.succ_pos f0.ge } }
end
end polynomial
|
b5d93bbaf85878c26434764817e0e341a945584e | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/limits/constructions/over/products.lean | e4a1f3cb0764bed12309ab99d292abac1cae5dc0 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 6,143 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Reid Barton, Bhavik Mehta
-/
import category_theory.over
import category_theory.limits.shapes.pullbacks
import category_theory.limits.shapes.wide_pullbacks
import category_theory.limits.shapes.finite_products
/-!
# Products in the over category
Shows that products in the over category can be derived from wide pullbacks in the base category.
The main result is `over_product_of_wide_pullback`, which says that if `C` has `J`-indexed wide
pullbacks, then `over B` has `J`-indexed products.
-/
universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory category_theory.limits
variables {J : Type v}
variables {C : Type u} [category.{v} C]
variable {X : C}
namespace category_theory.over
namespace construct_products
/--
(Implementation)
Given a product diagram in `C/B`, construct the corresponding wide pullback diagram
in `C`.
-/
@[reducible]
def wide_pullback_diagram_of_diagram_over (B : C) {J : Type v} (F : discrete J ⥤ over B) :
wide_pullback_shape J ⥤ C :=
wide_pullback_shape.wide_cospan B (λ j, (F.obj j).left) (λ j, (F.obj j).hom)
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simps]
def cones_equiv_inverse_obj (B : C) {J : Type v} (F : discrete J ⥤ over B) (c : cone F) :
cone (wide_pullback_diagram_of_diagram_over B F) :=
{ X := c.X.left,
π :=
{ app := λ X, option.cases_on X c.X.hom (λ (j : J), (c.π.app j).left),
-- `tidy` can do this using `case_bash`, but let's try to be a good `-T50000` citizen:
naturality' := λ X Y f,
begin
dsimp, cases X; cases Y; cases f,
{ rw [category.id_comp, category.comp_id], },
{ rw [over.w, category.id_comp], },
{ rw [category.id_comp, category.comp_id], },
end } }
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simps]
def cones_equiv_inverse (B : C) {J : Type v} (F : discrete J ⥤ over B) :
cone F ⥤ cone (wide_pullback_diagram_of_diagram_over B F) :=
{ obj := cones_equiv_inverse_obj B F,
map := λ c₁ c₂ f,
{ hom := f.hom.left,
w' := λ j,
begin
cases j,
{ simp },
{ dsimp,
rw ← f.w j,
refl }
end } }
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simps]
def cones_equiv_functor (B : C) {J : Type v} (F : discrete J ⥤ over B) :
cone (wide_pullback_diagram_of_diagram_over B F) ⥤ cone F :=
{ obj := λ c,
{ X := over.mk (c.π.app none),
π :=
{ app := λ j, over.hom_mk (c.π.app (some j))
(by apply c.w (wide_pullback_shape.hom.term j)) } },
map := λ c₁ c₂ f,
{ hom := over.hom_mk f.hom } }
local attribute [tidy] tactic.case_bash
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simp]
def cones_equiv_unit_iso (B : C) (F : discrete J ⥤ over B) :
𝟭 (cone (wide_pullback_diagram_of_diagram_over B F)) ≅
cones_equiv_functor B F ⋙ cones_equiv_inverse B F :=
nat_iso.of_components (λ _, cones.ext {hom := 𝟙 _, inv := 𝟙 _} (by tidy)) (by tidy)
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simp]
def cones_equiv_counit_iso (B : C) (F : discrete J ⥤ over B) :
cones_equiv_inverse B F ⋙ cones_equiv_functor B F ≅ 𝟭 (cone F) :=
nat_iso.of_components
(λ _, cones.ext {hom := over.hom_mk (𝟙 _), inv := over.hom_mk (𝟙 _)} (by tidy)) (by tidy)
-- TODO: Can we add `. obviously` to the second arguments of `nat_iso.of_components` and
-- `cones.ext`?
/--
(Impl) Establish an equivalence between the category of cones for `F` and for the "grown" `F`.
-/
@[simps]
def cones_equiv (B : C) (F : discrete J ⥤ over B) :
cone (wide_pullback_diagram_of_diagram_over B F) ≌ cone F :=
{ functor := cones_equiv_functor B F,
inverse := cones_equiv_inverse B F,
unit_iso := cones_equiv_unit_iso B F,
counit_iso := cones_equiv_counit_iso B F, }
/-- Use the above equivalence to prove we have a limit. -/
lemma has_over_limit_discrete_of_wide_pullback_limit {B : C} (F : discrete J ⥤ over B)
[has_limit (wide_pullback_diagram_of_diagram_over B F)] :
has_limit F :=
has_limit.mk
{ cone := _,
is_limit := is_limit.of_right_adjoint
(cones_equiv B F).functor (limit.is_limit (wide_pullback_diagram_of_diagram_over B F)) }
/-- Given a wide pullback in `C`, construct a product in `C/B`. -/
lemma over_product_of_wide_pullback [has_limits_of_shape (wide_pullback_shape J) C] {B : C} :
has_limits_of_shape (discrete J) (over B) :=
{ has_limit := λ F, has_over_limit_discrete_of_wide_pullback_limit F }
/-- Given a pullback in `C`, construct a binary product in `C/B`. -/
lemma over_binary_product_of_pullback [has_pullbacks C] {B : C} :
has_binary_products (over B) :=
over_product_of_wide_pullback
/-- Given all wide pullbacks in `C`, construct products in `C/B`. -/
lemma over_products_of_wide_pullbacks [has_wide_pullbacks C] {B : C} :
has_products (over B) :=
λ J, over_product_of_wide_pullback
/-- Given all finite wide pullbacks in `C`, construct finite products in `C/B`. -/
lemma over_finite_products_of_finite_wide_pullbacks [has_finite_wide_pullbacks C] {B : C} :
has_finite_products (over B) :=
λ J 𝒥₁ 𝒥₂, by exactI over_product_of_wide_pullback
end construct_products
/--
Construct terminal object in the over category. This isn't an instance as it's not typically the
way we want to define terminal objects.
(For instance, this gives a terminal object which is different from the generic one given by
`over_product_of_wide_pullback` above.)
-/
lemma over_has_terminal (B : C) : has_terminal (over B) :=
{ has_limit := λ F, has_limit.mk
{ cone :=
{ X := over.mk (𝟙 _),
π := { app := λ p, pempty.elim p } },
is_limit :=
{ lift := λ s, over.hom_mk _,
fac' := λ _ j, j.elim,
uniq' := λ s m _,
begin
ext,
rw over.hom_mk_left,
have := m.w,
dsimp at this,
rwa [category.comp_id, category.comp_id] at this
end } } }
end category_theory.over
|
9a9601c35eed61ab0223029c2207aced26bba7f3 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/analysis/normed_space/banach.lean | 1f486c79d2f9dd9e7176f9a45de4e7db28c1ad9e | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 16,998 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.metric_space.baire
import analysis.normed_space.operator_norm
/-!
# Banach open mapping theorem
This file contains the Banach open mapping theorem, i.e., the fact that a bijective
bounded linear map between Banach spaces has a bounded inverse.
-/
open function metric set filter finset
open_locale classical topological_space big_operators nnreal
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
(f : E →L[𝕜] F)
include 𝕜
namespace continuous_linear_map
/-- A (possibly nonlinear) right inverse to a continuous linear map, which doesn't have to be
linear itself but which satisfies a bound `∥inverse x∥ ≤ C * ∥x∥`. A surjective continuous linear
map doesn't always have a continuous linear right inverse, but it always has a nonlinear inverse
in this sense, by Banach's open mapping theorem. -/
structure nonlinear_right_inverse :=
(to_fun : F → E)
(nnnorm : ℝ≥0)
(bound' : ∀ y, ∥to_fun y∥ ≤ nnnorm * ∥y∥)
(right_inv' : ∀ y, f (to_fun y) = y)
instance : has_coe_to_fun (nonlinear_right_inverse f) := ⟨_, λ fsymm, fsymm.to_fun⟩
@[simp] lemma nonlinear_right_inverse.right_inv {f : E →L[𝕜] F} (fsymm : nonlinear_right_inverse f)
(y : F) : f (fsymm y) = y :=
fsymm.right_inv' y
lemma nonlinear_right_inverse.bound {f : E →L[𝕜] F} (fsymm : nonlinear_right_inverse f) (y : F) :
∥fsymm y∥ ≤ fsymm.nnnorm * ∥y∥ :=
fsymm.bound' y
end continuous_linear_map
/-- Given a continuous linear equivalence, the inverse is in particular an instance of
`nonlinear_right_inverse` (which turns out to be linear). -/
noncomputable def continuous_linear_equiv.to_nonlinear_right_inverse (f : E ≃L[𝕜] F) :
continuous_linear_map.nonlinear_right_inverse (f : E →L[𝕜] F) :=
{ to_fun := f.inv_fun,
nnnorm := nnnorm (f.symm : F →L[𝕜] E),
bound' := λ y, continuous_linear_map.le_op_norm (f.symm : F →L[𝕜] E) _,
right_inv' := f.apply_symm_apply }
noncomputable instance (f : E ≃L[𝕜] F) :
inhabited (continuous_linear_map.nonlinear_right_inverse (f : E →L[𝕜] F)) :=
⟨f.to_nonlinear_right_inverse⟩
/-! ### Proof of the Banach open mapping theorem -/
variable [complete_space F]
/--
First step of the proof of the Banach open mapping theorem (using completeness of `F`):
by Baire's theorem, there exists a ball in `E` whose image closure has nonempty interior.
Rescaling everything, it follows that any `y ∈ F` is arbitrarily well approached by
images of elements of norm at most `C * ∥y∥`.
For further use, we will only need such an element whose image
is within distance `∥y∥/2` of `y`, to apply an iterative process. -/
lemma exists_approx_preimage_norm_le (surj : surjective f) :
∃C ≥ 0, ∀y, ∃x, dist (f x) y ≤ 1/2 * ∥y∥ ∧ ∥x∥ ≤ C * ∥y∥ :=
begin
have A : (⋃n:ℕ, closure (f '' (ball 0 n))) = univ,
{ refine subset.antisymm (subset_univ _) (λy hy, _),
rcases surj y with ⟨x, hx⟩,
rcases exists_nat_gt (∥x∥) with ⟨n, hn⟩,
refine mem_Union.2 ⟨n, subset_closure _⟩,
refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩,
rwa [mem_ball, dist_eq_norm, sub_zero] },
have : ∃ (n : ℕ) x, x ∈ interior (closure (f '' (ball 0 n))) :=
nonempty_interior_of_Union_of_closed (λn, is_closed_closure) A,
simp only [mem_interior_iff_mem_nhds, metric.mem_nhds_iff] at this,
rcases this with ⟨n, a, ε, ⟨εpos, H⟩⟩,
rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩,
refine ⟨(ε/2)⁻¹ * ∥c∥ * 2 * n, _, λy, _⟩,
{ refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _,
exacts [inv_nonneg.2 (div_nonneg (le_of_lt εpos) (by norm_num)), n.cast_nonneg] },
{ by_cases hy : y = 0,
{ use 0, simp [hy] },
{ rcases rescale_to_shell hc (half_pos εpos) hy with ⟨d, hd, ydlt, leyd, dinv⟩,
let δ := ∥d∥ * ∥y∥/4,
have δpos : 0 < δ :=
div_pos (mul_pos (norm_pos_iff.2 hd) (norm_pos_iff.2 hy)) (by norm_num),
have : a + d • y ∈ ball a ε,
by simp [dist_eq_norm, lt_of_le_of_lt ydlt.le (half_lt_self εpos)],
rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₁, z₁im, h₁⟩,
rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xz₁⟩,
rw ← xz₁ at h₁,
rw [mem_ball, dist_eq_norm, sub_zero] at hx₁,
have : a ∈ ball a ε, by { simp, exact εpos },
rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₂, z₂im, h₂⟩,
rcases (mem_image _ _ _).1 z₂im with ⟨x₂, hx₂, xz₂⟩,
rw ← xz₂ at h₂,
rw [mem_ball, dist_eq_norm, sub_zero] at hx₂,
let x := x₁ - x₂,
have I : ∥f x - d • y∥ ≤ 2 * δ := calc
∥f x - d • y∥ = ∥f x₁ - (a + d • y) - (f x₂ - a)∥ :
by { congr' 1, simp only [x, f.map_sub], abel }
... ≤ ∥f x₁ - (a + d • y)∥ + ∥f x₂ - a∥ :
norm_sub_le _ _
... ≤ δ + δ : begin
apply add_le_add,
{ rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ },
{ rw [← dist_eq_norm, dist_comm], exact le_of_lt h₂ }
end
... = 2 * δ : (two_mul _).symm,
have J : ∥f (d⁻¹ • x) - y∥ ≤ 1/2 * ∥y∥ := calc
∥f (d⁻¹ • x) - y∥ = ∥d⁻¹ • f x - (d⁻¹ * d) • y∥ :
by rwa [f.map_smul _, inv_mul_cancel, one_smul]
... = ∥d⁻¹ • (f x - d • y)∥ : by rw [mul_smul, smul_sub]
... = ∥d∥⁻¹ * ∥f x - d • y∥ : by rw [norm_smul, normed_field.norm_inv]
... ≤ ∥d∥⁻¹ * (2 * δ) : begin
apply mul_le_mul_of_nonneg_left I,
rw inv_nonneg,
exact norm_nonneg _
end
... = (∥d∥⁻¹ * ∥d∥) * ∥y∥ /2 : by { simp only [δ], ring }
... = ∥y∥/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] }
... = (1/2) * ∥y∥ : by ring,
rw ← dist_eq_norm at J,
have K : ∥d⁻¹ • x∥ ≤ (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ := calc
∥d⁻¹ • x∥ = ∥d∥⁻¹ * ∥x₁ - x₂∥ : by rw [norm_smul, normed_field.norm_inv]
... ≤ ((ε / 2)⁻¹ * ∥c∥ * ∥y∥) * (n + n) : begin
refine mul_le_mul dinv _ (norm_nonneg _) _,
{ exact le_trans (norm_sub_le _ _) (add_le_add (le_of_lt hx₁) (le_of_lt hx₂)) },
{ apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _),
exact inv_nonneg.2 (le_of_lt (half_pos εpos)) }
end
... = (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ : by ring,
exact ⟨d⁻¹ • x, J, K⟩ } },
end
variable [complete_space E]
/-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then
any point has a preimage with controlled norm. -/
theorem exists_preimage_norm_le (surj : surjective f) :
∃C > 0, ∀y, ∃x, f x = y ∧ ∥x∥ ≤ C * ∥y∥ :=
begin
obtain ⟨C, C0, hC⟩ := exists_approx_preimage_norm_le f surj,
/- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be
the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that
has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`,
leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage
of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a
preimage of `y`. This uses completeness of `E`. -/
choose g hg using hC,
let h := λy, y - f (g y),
have hle : ∀y, ∥h y∥ ≤ (1/2) * ∥y∥,
{ assume y,
rw [← dist_eq_norm, dist_comm],
exact (hg y).1 },
refine ⟨2 * C + 1, by linarith, λy, _⟩,
have hnle : ∀n:ℕ, ∥(h^[n]) y∥ ≤ (1/2)^n * ∥y∥,
{ assume n,
induction n with n IH,
{ simp only [one_div, nat.nat_zero_eq_zero, one_mul, iterate_zero_apply,
pow_zero] },
{ rw [iterate_succ'],
apply le_trans (hle _) _,
rw [pow_succ, mul_assoc],
apply mul_le_mul_of_nonneg_left IH,
norm_num } },
let u := λn, g((h^[n]) y),
have ule : ∀n, ∥u n∥ ≤ (1/2)^n * (C * ∥y∥),
{ assume n,
apply le_trans (hg _).2 _,
calc C * ∥(h^[n]) y∥ ≤ C * ((1/2)^n * ∥y∥) : mul_le_mul_of_nonneg_left (hnle n) C0
... = (1 / 2) ^ n * (C * ∥y∥) : by ring },
have sNu : summable (λn, ∥u n∥),
{ refine summable_of_nonneg_of_le (λn, norm_nonneg _) ule _,
exact summable.mul_right _ (summable_geometric_of_lt_1 (by norm_num) (by norm_num)) },
have su : summable u := summable_of_summable_norm sNu,
let x := tsum u,
have x_ineq : ∥x∥ ≤ (2 * C + 1) * ∥y∥ := calc
∥x∥ ≤ ∑'n, ∥u n∥ : norm_tsum_le_tsum_norm sNu
... ≤ ∑'n, (1/2)^n * (C * ∥y∥) :
tsum_le_tsum ule sNu (summable.mul_right _ summable_geometric_two)
... = (∑'n, (1/2)^n) * (C * ∥y∥) : tsum_mul_right
... = 2 * C * ∥y∥ : by rw [tsum_geometric_two, mul_assoc]
... ≤ 2 * C * ∥y∥ + ∥y∥ : le_add_of_nonneg_right (norm_nonneg y)
... = (2 * C + 1) * ∥y∥ : by ring,
have fsumeq : ∀n:ℕ, f (∑ i in range n, u i) = y - (h^[n]) y,
{ assume n,
induction n with n IH,
{ simp [f.map_zero] },
{ rw [sum_range_succ, f.map_add, IH, iterate_succ', sub_add] } },
have : tendsto (λn, ∑ i in range n, u i) at_top (𝓝 x) :=
su.has_sum.tendsto_sum_nat,
have L₁ : tendsto (λn, f (∑ i in range n, u i)) at_top (𝓝 (f x)) :=
(f.continuous.tendsto _).comp this,
simp only [fsumeq] at L₁,
have L₂ : tendsto (λn, y - (h^[n]) y) at_top (𝓝 (y - 0)),
{ refine tendsto_const_nhds.sub _,
rw tendsto_iff_norm_tendsto_zero,
simp only [sub_zero],
refine squeeze_zero (λ_, norm_nonneg _) hnle _,
rw [← zero_mul ∥y∥],
refine (tendsto_pow_at_top_nhds_0_of_lt_1 _ _).mul tendsto_const_nhds; norm_num },
have feq : f x = y - 0 := tendsto_nhds_unique L₁ L₂,
rw sub_zero at feq,
exact ⟨x, feq, x_ineq⟩
end
/-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is
open. -/
theorem open_mapping (surj : surjective f) : is_open_map f :=
begin
assume s hs,
rcases exists_preimage_norm_le f surj with ⟨C, Cpos, hC⟩,
refine is_open_iff.2 (λy yfs, _),
rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩,
rcases is_open_iff.1 hs x xs with ⟨ε, εpos, hε⟩,
refine ⟨ε/C, div_pos εpos Cpos, λz hz, _⟩,
rcases hC (z-y) with ⟨w, wim, wnorm⟩,
have : f (x + w) = z, by { rw [f.map_add, wim, fxy, add_sub_cancel'_right] },
rw ← this,
have : x + w ∈ ball x ε := calc
dist (x+w) x = ∥w∥ : by { rw dist_eq_norm, simp }
... ≤ C * ∥z - y∥ : wnorm
... < C * (ε/C) : begin
apply mul_lt_mul_of_pos_left _ Cpos,
rwa [mem_ball, dist_eq_norm] at hz,
end
... = ε : mul_div_cancel' _ (ne_of_gt Cpos),
exact set.mem_image_of_mem _ (hε this)
end
/-! ### Applications of the Banach open mapping theorem -/
namespace continuous_linear_map
lemma exists_nonlinear_right_inverse_of_surjective (f : E →L[𝕜] F) (hsurj : f.range = ⊤) :
∃ (fsymm : nonlinear_right_inverse f), 0 < fsymm.nnnorm :=
begin
choose C hC fsymm h using exists_preimage_norm_le _ (linear_map.range_eq_top.mp hsurj),
use { to_fun := fsymm,
nnnorm := ⟨C, hC.lt.le⟩,
bound' := λ y, (h y).2,
right_inv' := λ y, (h y).1 },
exact hC
end
/-- A surjective continuous linear map between Banach spaces admits a (possibly nonlinear)
controlled right inverse. In general, it is not possible to ensure that such a right inverse
is linear (take for instance the map from `E` to `E/F` where `F` is a closed subspace of `E`
without a closed complement. Then it doesn't have a continuous linear right inverse.) -/
@[irreducible] noncomputable def nonlinear_right_inverse_of_surjective
(f : E →L[𝕜] F) (hsurj : f.range = ⊤) : nonlinear_right_inverse f :=
classical.some (exists_nonlinear_right_inverse_of_surjective f hsurj)
lemma nonlinear_right_inverse_of_surjective_nnnorm_pos (f : E →L[𝕜] F) (hsurj : f.range = ⊤) :
0 < (nonlinear_right_inverse_of_surjective f hsurj).nnnorm :=
begin
rw nonlinear_right_inverse_of_surjective,
exact classical.some_spec (exists_nonlinear_right_inverse_of_surjective f hsurj)
end
end continuous_linear_map
namespace linear_equiv
/-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/
@[continuity]
theorem continuous_symm (e : E ≃ₗ[𝕜] F) (h : continuous e) :
continuous e.symm :=
begin
rw continuous_def,
intros s hs,
rw [← e.image_eq_preimage],
rw [← e.coe_coe] at h ⊢,
exact open_mapping ⟨↑e, h⟩ e.surjective s hs
end
/-- Associating to a linear equivalence between Banach spaces a continuous linear equivalence when
the direct map is continuous, thanks to the Banach open mapping theorem that ensures that the
inverse map is also continuous. -/
def to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) :
E ≃L[𝕜] F :=
{ continuous_to_fun := h,
continuous_inv_fun := e.continuous_symm h,
..e }
@[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) :
⇑(e.to_continuous_linear_equiv_of_continuous h) = e := rfl
@[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous_symm (e : E ≃ₗ[𝕜] F)
(h : continuous e) :
⇑(e.to_continuous_linear_equiv_of_continuous h).symm = e.symm := rfl
end linear_equiv
namespace continuous_linear_equiv
/-- Convert a bijective continuous linear map `f : E →L[𝕜] F` between two Banach spaces
to a continuous linear equivalence. -/
noncomputable def of_bijective (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) :
E ≃L[𝕜] F :=
(linear_equiv.of_bijective ↑f hinj hsurj).to_continuous_linear_equiv_of_continuous f.continuous
@[simp] lemma coe_fn_of_bijective (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) :
⇑(of_bijective f hinj hsurj) = f := rfl
lemma coe_of_bijective (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) :
↑(of_bijective f hinj hsurj) = f := by { ext, refl }
@[simp] lemma of_bijective_symm_apply_apply (f : E →L[𝕜] F) (hinj : f.ker = ⊥)
(hsurj : f.range = ⊤) (x : E) :
(of_bijective f hinj hsurj).symm (f x) = x :=
(of_bijective f hinj hsurj).symm_apply_apply x
@[simp] lemma of_bijective_apply_symm_apply (f : E →L[𝕜] F) (hinj : f.ker = ⊥)
(hsurj : f.range = ⊤) (y : F) :
f ((of_bijective f hinj hsurj).symm y) = y :=
(of_bijective f hinj hsurj).apply_symm_apply y
end continuous_linear_equiv
namespace continuous_linear_map
/-- Intermediate definition used to show
`continuous_linear_map.closed_complemented_range_of_is_compl_of_ker_eq_bot`.
This is `f.coprod G.subtypeL` as an `continuous_linear_equiv`. -/
noncomputable def coprod_subtypeL_equiv_of_is_compl
(f : E →L[𝕜] F) {G : submodule 𝕜 F}
(h : is_compl f.range G) [complete_space G] (hker : f.ker = ⊥) : (E × G) ≃L[𝕜] F :=
continuous_linear_equiv.of_bijective (f.coprod G.subtypeL)
(begin
rw ker_coprod_of_disjoint_range,
{ rw [hker, submodule.ker_subtypeL, submodule.prod_bot] },
{ rw submodule.range_subtypeL,
exact h.disjoint }
end)
(by simp only [range_coprod, h.sup_eq_top, submodule.range_subtypeL])
lemma range_eq_map_coprod_subtypeL_equiv_of_is_compl
(f : E →L[𝕜] F) {G : submodule 𝕜 F}
(h : is_compl f.range G) [complete_space G] (hker : f.ker = ⊥) :
f.range = ((⊤ : submodule 𝕜 E).prod (⊥ : submodule 𝕜 G)).map
(coprod_subtypeL_equiv_of_is_compl f h hker) :=
by rw [coprod_subtypeL_equiv_of_is_compl, _root_.coe_coe, continuous_linear_equiv.coe_of_bijective,
coe_coprod, linear_map.coprod_map_prod, submodule.map_bot, sup_bot_eq, submodule.map_top,
range]
/- TODO: remove the assumption `f.ker = ⊥` in the next lemma, by using the map induced by `f` on
`E / f.ker`, once we have quotient normed spaces. -/
lemma closed_complemented_range_of_is_compl_of_ker_eq_bot (f : E →L[𝕜] F) (G : submodule 𝕜 F)
(h : is_compl f.range G) (hG : is_closed (G : set F)) (hker : f.ker = ⊥) :
is_closed (f.range : set F) :=
begin
haveI : complete_space G := complete_space_coe_iff_is_complete.2 hG.is_complete,
let g := coprod_subtypeL_equiv_of_is_compl f h hker,
rw congr_arg coe (range_eq_map_coprod_subtypeL_equiv_of_is_compl f h hker ),
apply g.to_homeomorph.is_closed_image.2,
exact is_closed_univ.prod is_closed_singleton,
end
end continuous_linear_map
|
1a92c6c53c60833c9aa6e2767bb51bce0de6e56b | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Init/Control/Lawful.lean | 021e3926a4942830a5e78463c940b6acaec7406b | [
"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 | 14,267 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich, Leonardo de Moura
-/
prelude
import Init.SimpLemmas
import Init.Control.Except
import Init.Control.StateRef
open Function
@[simp] theorem monadLift_self [Monad m] (x : m α) : monadLift x = x :=
rfl
class LawfulFunctor (f : Type u → Type v) [Functor f] : Prop where
map_const : (Functor.mapConst : α → f β → f α) = Functor.map ∘ const β
id_map (x : f α) : id <$> x = x
comp_map (g : α → β) (h : β → γ) (x : f α) : (h ∘ g) <$> x = h <$> g <$> x
export LawfulFunctor (map_const id_map comp_map)
attribute [simp] id_map
@[simp] theorem id_map' [Functor m] [LawfulFunctor m] (x : m α) : (fun a => a) <$> x = x :=
id_map x
class LawfulApplicative (f : Type u → Type v) [Applicative f] extends LawfulFunctor f : Prop where
seqLeft_eq (x : f α) (y : f β) : x <* y = const β <$> x <*> y
seqRight_eq (x : f α) (y : f β) : x *> y = const α id <$> x <*> y
pure_seq (g : α → β) (x : f α) : pure g <*> x = g <$> x
map_pure (g : α → β) (x : α) : g <$> (pure x : f α) = pure (g x)
seq_pure {α β : Type u} (g : f (α → β)) (x : α) : g <*> pure x = (fun h => h x) <$> g
seq_assoc {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)) : h <*> (g <*> x) = ((@comp α β γ) <$> h) <*> g <*> x
comp_map g h x := (by
repeat rw [← pure_seq]
simp [seq_assoc, map_pure, seq_pure])
export LawfulApplicative (seqLeft_eq seqRight_eq pure_seq map_pure seq_pure seq_assoc)
attribute [simp] map_pure seq_pure
@[simp] theorem pure_id_seq [Applicative f] [LawfulApplicative f] (x : f α) : pure id <*> x = x := by
simp [pure_seq]
class LawfulMonad (m : Type u → Type v) [Monad m] extends LawfulApplicative m : Prop where
bind_pure_comp (f : α → β) (x : m α) : x >>= (fun a => pure (f a)) = f <$> x
bind_map {α β : Type u} (f : m (α → β)) (x : m α) : f >>= (. <$> x) = f <*> x
pure_bind (x : α) (f : α → m β) : pure x >>= f = f x
bind_assoc (x : m α) (f : α → m β) (g : β → m γ) : x >>= f >>= g = x >>= fun x => f x >>= g
map_pure g x := (by rw [← bind_pure_comp, pure_bind])
seq_pure g x := (by rw [← bind_map]; simp [map_pure, bind_pure_comp])
seq_assoc x g h := (by
-- TODO: support for applying `symm` at `simp` arguments
have bind_pure_comp_symm {α β : Type u} (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by
rw [bind_pure_comp]
have bind_map_symm {α β : Type u} (f : m (α → (β : Type u))) (x : m α) : f <*> x = f >>= (. <$> x) := by
rw [bind_map]
simp[bind_pure_comp_symm, bind_map_symm, bind_assoc, pure_bind])
export LawfulMonad (bind_pure_comp bind_map pure_bind bind_assoc)
attribute [simp] pure_bind bind_assoc
@[simp] theorem bind_pure [Monad m] [LawfulMonad m] (x : m α) : x >>= pure = x := by
show x >>= (fun a => pure (id a)) = x
rw [bind_pure_comp, id_map]
theorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by
rw [← bind_pure_comp]
theorem seq_eq_bind_map {α β : Type u} [Monad m] [LawfulMonad m] (f : m (α → β)) (x : m α) : f <*> x = f >>= (. <$> x) := by
rw [← bind_map]
theorem bind_congr [Bind m] {x : m α} {f g : α → m β} (h : ∀ a, f a = g a) : x >>= f = x >>= g := by
simp [funext h]
@[simp] theorem bind_pure_unit [Monad m] [LawfulMonad m] {x : m PUnit} : (x >>= fun _ => pure ⟨⟩) = x := by
rw [bind_pure]
theorem map_congr [Functor m] {x : m α} {f g : α → β} (h : ∀ a, f a = g a) : (f <$> x : m β) = g <$> x := by
simp [funext h]
theorem seq_eq_bind {α β : Type u} [Monad m] [LawfulMonad m] (mf : m (α → β)) (x : m α) : mf <*> x = mf >>= fun f => f <$> x := by
rw [bind_map]
theorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x *> y = x >>= fun _ => y := by
rw [seqRight_eq]
simp [map_eq_pure_bind, seq_eq_bind_map, const]
theorem seqLeft_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x <* y = x >>= fun a => y >>= fun _ => pure a := by
rw [seqLeft_eq]; simp [map_eq_pure_bind, seq_eq_bind_map]
/- Id -/
namespace Id
@[simp] theorem map_eq (x : Id α) (f : α → β) : f <$> x = f x := rfl
@[simp] theorem bind_eq (x : Id α) (f : α → id β) : x >>= f = f x := rfl
@[simp] theorem pure_eq (a : α) : (pure a : Id α) = a := rfl
instance : LawfulMonad Id := by
refine' { .. } <;> intros <;> rfl
end Id
/- ExceptT -/
namespace ExceptT
theorem ext [Monad m] {x y : ExceptT ε m α} (h : x.run = y.run) : x = y := by
simp [run] at h
assumption
@[simp] theorem run_pure [Monad m] : run (pure x : ExceptT ε m α) = pure (Except.ok x) := rfl
@[simp] theorem run_lift [Monad m] (x : m α) : run (ExceptT.lift x : ExceptT ε m α) = (Except.ok <$> x : m (Except ε α)) := rfl
@[simp] theorem run_throw [Monad m] : run (throw e : ExceptT ε m β) = pure (Except.error e) := rfl
@[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m α) (f : α → ExceptT ε m β) : run (ExceptT.lift x >>= f : ExceptT ε m β) = x >>= fun a => run (f a) := by
simp[ExceptT.run, ExceptT.lift, bind, ExceptT.bind, ExceptT.mk, ExceptT.bindCont, map_eq_pure_bind]
@[simp] theorem bind_throw [Monad m] [LawfulMonad m] (f : α → ExceptT ε m β) : (throw e >>= f) = throw e := by
simp [throw, throwThe, MonadExceptOf.throw, bind, ExceptT.bind, ExceptT.bindCont, ExceptT.mk]
theorem run_bind [Monad m] (x : ExceptT ε m α)
: run (x >>= f : ExceptT ε m β)
=
run x >>= fun
| Except.ok x => run (f x)
| Except.error e => pure (Except.error e) :=
rfl
@[simp] theorem lift_pure [Monad m] [LawfulMonad m] (a : α) : ExceptT.lift (pure a) = (pure a : ExceptT ε m α) := by
simp [ExceptT.lift, pure, ExceptT.pure]
@[simp] theorem run_map [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α)
: (f <$> x).run = Except.map f <$> x.run := by
simp [Functor.map, ExceptT.map, map_eq_pure_bind]
apply bind_congr
intro a; cases a <;> simp [Except.map]
protected theorem seq_eq {α β ε : Type u} [Monad m] (mf : ExceptT ε m (α → β)) (x : ExceptT ε m α) : mf <*> x = mf >>= fun f => f <$> x :=
rfl
protected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : x >>= pure ∘ f = f <$> x := by
intros; rfl
protected theorem seqLeft_eq {α β ε : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x <* y = const β <$> x <*> y := by
show (x >>= fun a => y >>= fun _ => pure a) = (const (α := α) β <$> x) >>= fun f => f <$> y
rw [← ExceptT.bind_pure_comp]
apply ext
simp [run_bind]
apply bind_congr
intro
| Except.error _ => simp
| Except.ok _ =>
simp [map_eq_pure_bind]; apply bind_congr; intro b;
cases b <;> simp [comp, Except.map, const]
protected theorem seqRight_eq [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x *> y = const α id <$> x <*> y := by
show (x >>= fun _ => y) = (const α id <$> x) >>= fun f => f <$> y
rw [← ExceptT.bind_pure_comp]
apply ext
simp [run_bind]
apply bind_congr
intro a; cases a <;> simp
instance [Monad m] [LawfulMonad m] : LawfulMonad (ExceptT ε m) where
id_map := by intros; apply ext; simp
map_const := by intros; rfl
seqLeft_eq := ExceptT.seqLeft_eq
seqRight_eq := ExceptT.seqRight_eq
pure_seq := by intros; apply ext; simp [ExceptT.seq_eq, run_bind]
bind_pure_comp := ExceptT.bind_pure_comp
bind_map := by intros; rfl
pure_bind := by intros; apply ext; simp [run_bind]
bind_assoc := by intros; apply ext; simp [run_bind]; apply bind_congr; intro a; cases a <;> simp
end ExceptT
/- ReaderT -/
namespace ReaderT
theorem ext [Monad m] {x y : ReaderT ρ m α} (h : ∀ ctx, x.run ctx = y.run ctx) : x = y := by
simp [run] at h
exact funext h
@[simp] theorem run_pure [Monad m] (a : α) (ctx : ρ) : (pure a : ReaderT ρ m α).run ctx = pure a := rfl
@[simp] theorem run_bind [Monad m] (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) (ctx : ρ)
: (x >>= f).run ctx = x.run ctx >>= λ a => (f a).run ctx := rfl
@[simp] theorem run_map [Monad m] (f : α → β) (x : ReaderT ρ m α) (ctx : ρ)
: (f <$> x).run ctx = f <$> x.run ctx := rfl
@[simp] theorem run_monadLift [MonadLiftT n m] (x : n α) (ctx : ρ)
: (monadLift x : ReaderT ρ m α).run ctx = (monadLift x : m α) := rfl
@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : ReaderT ρ m α) (ctx : ρ)
: (monadMap @f x : ReaderT ρ m α).run ctx = monadMap @f (x.run ctx) := rfl
@[simp] theorem run_read [Monad m] (ctx : ρ) : (ReaderT.read : ReaderT ρ m ρ).run ctx = pure ctx := rfl
@[simp] theorem run_seq {α β : Type u} [Monad m] [LawfulMonad m] (f : ReaderT ρ m (α → β)) (x : ReaderT ρ m α) (ctx : ρ) : (f <*> x).run ctx = (f.run ctx <*> x.run ctx) := by
rw [seq_eq_bind (m := m)]; rfl
@[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x *> y).run ctx = (x.run ctx *> y.run ctx) := by
rw [seqRight_eq_bind (m := m)]; rfl
@[simp] theorem run_seqLeft [Monad m] [LawfulMonad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x <* y).run ctx = (x.run ctx <* y.run ctx) := by
rw [seqLeft_eq_bind (m := m)]; rfl
instance [Monad m] [LawfulMonad m] : LawfulMonad (ReaderT ρ m) where
id_map := by intros; apply ext; intros; simp
map_const := by intros; rfl
seqLeft_eq := by intros; apply ext; intros; simp; apply LawfulApplicative.seqLeft_eq
seqRight_eq := by intros; apply ext; intros; simp; apply LawfulApplicative.seqRight_eq
pure_seq := by intros; apply ext; intros; simp; apply LawfulApplicative.pure_seq
bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp
bind_map := by intros; rfl
pure_bind := by intros; apply ext; intros; simp
bind_assoc := by intros; apply ext; intros; simp
end ReaderT
/- StateRefT -/
instance [Monad m] [LawfulMonad m] : LawfulMonad (StateRefT' ω σ m) :=
inferInstanceAs (LawfulMonad (ReaderT (ST.Ref ω σ) m))
/- StateT -/
namespace StateT
theorem ext {x y : StateT σ m α} (h : ∀ s, x.run s = y.run s) : x = y :=
funext h
@[simp] theorem run'_eq [Monad m] (x : StateT σ m α) (s : σ) : run' x s = (·.1) <$> run x s :=
rfl
@[simp] theorem run_pure [Monad m] (a : α) (s : σ) : (pure a : StateT σ m α).run s = pure (a, s) := rfl
@[simp] theorem run_bind [Monad m] (x : StateT σ m α) (f : α → StateT σ m β) (s : σ)
: (x >>= f).run s = x.run s >>= λ p => (f p.1).run p.2 := by
simp [bind, StateT.bind, run]
@[simp] theorem run_map {α β σ : Type u} [Monad m] [LawfulMonad m] (f : α → β) (x : StateT σ m α) (s : σ) : (f <$> x).run s = (fun (p : α × σ) => (f p.1, p.2)) <$> x.run s := by
simp [Functor.map, StateT.map, run, map_eq_pure_bind]
@[simp] theorem run_get [Monad m] (s : σ) : (get : StateT σ m σ).run s = pure (s, s) := rfl
@[simp] theorem run_set [Monad m] (s s' : σ) : (set s' : StateT σ m PUnit).run s = pure (⟨⟩, s') := rfl
@[simp] theorem run_modify [Monad m] (f : σ → σ) (s : σ) : (modify f : StateT σ m PUnit).run s = pure (⟨⟩, f s) := rfl
@[simp] theorem run_modifyGet [Monad m] (f : σ → α × σ) (s : σ) : (modifyGet f : StateT σ m α).run s = pure ((f s).1, (f s).2) := by
simp [modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, run]
@[simp] theorem run_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) : (StateT.lift x : StateT σ m α).run s = x >>= fun a => pure (a, s) := rfl
@[simp] theorem run_bind_lift {α σ : Type u} [Monad m] [LawfulMonad m] (x : m α) (f : α → StateT σ m β) (s : σ) : (StateT.lift x >>= f).run s = x >>= fun a => (f a).run s := by
simp [StateT.lift, StateT.run, bind, StateT.bind]
@[simp] theorem run_monadLift {α σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) : (monadLift x : StateT σ m α).run s = (monadLift x : m α) >>= fun a => pure (a, s) := rfl
@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : StateT σ m α) (s : σ)
: (monadMap @f x : StateT σ m α).run s = monadMap @f (x.run s) := rfl
@[simp] theorem run_seq {α β σ : Type u} [Monad m] [LawfulMonad m] (f : StateT σ m (α → β)) (x : StateT σ m α) (s : σ) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : α × σ) => (fs.1 p.1, p.2)) <$> x.run fs.2) := by
show (f >>= fun g => g <$> x).run s = _
simp
@[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x *> y).run s = (x.run s >>= fun p => y.run p.2) := by
show (x >>= fun _ => y).run s = _
simp
@[simp] theorem run_seqLeft {α β σ : Type u} [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x <* y).run s = (x.run s >>= fun p => y.run p.2 >>= fun p' => pure (p.1, p'.2)) := by
show (x >>= fun a => y >>= fun _ => pure a).run s = _
simp
theorem seqRight_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x *> y = const α id <$> x <*> y := by
apply ext; intro s
simp [map_eq_pure_bind, const]
apply bind_congr; intro p; cases p
simp [Prod.ext]
theorem seqLeft_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x <* y = const β <$> x <*> y := by
apply ext; intro s
simp [map_eq_pure_bind]
instance [Monad m] [LawfulMonad m] : LawfulMonad (StateT σ m) where
id_map := by intros; apply ext; intros; simp[Prod.ext]
map_const := by intros; rfl
seqLeft_eq := seqLeft_eq
seqRight_eq := seqRight_eq
pure_seq := by intros; apply ext; intros; simp
bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp
bind_map := by intros; rfl
pure_bind := by intros; apply ext; intros; simp
bind_assoc := by intros; apply ext; intros; simp
end StateT
|
2aa7a2629dd95e7dbbc9004580f29cc760d4b7ca | 37da0369b6c03e380e057bf680d81e6c9fdf9219 | /hott/hit/two_quotient.hlean | 0aacd9e55bfd1619330735d8d1d1563ee09ab285 | [
"Apache-2.0"
] | permissive | kodyvajjha/lean2 | 72b120d95c3a1d77f54433fa90c9810e14a931a4 | 227fcad22ab2bc27bb7471be7911075d101ba3f9 | refs/heads/master | 1,627,157,512,295 | 1,501,855,676,000 | 1,504,809,427,000 | 109,317,326 | 0 | 0 | null | 1,509,839,253,000 | 1,509,655,713,000 | C++ | UTF-8 | Lean | false | false | 31,482 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import homotopy.circle eq2 algebra.e_closure cubical.squareover cubical.cube
open quotient eq circle sum sigma equiv function relation e_closure
/-
This files defines a general class of nonrecursive 2-HITs using just quotients.
We can define any HIT X which has
- a single 0-constructor
f : A → X (for some type A)
- a single 1-constructor
e : Π{a a' : A}, R a a' → a = a' (for some (type-valued) relation R on A)
and furthermore has 2-constructors which are all of the form
p = p'
where p, p' are of the form
- refl (f a), for some a : A;
- e r, for some r : R a a';
- ap f q, where q : a = a' :> A;
- inverses of such paths;
- concatenations of such paths.
so an example 2-constructor could be (as long as it typechecks):
ap f q' ⬝ ((e r)⁻¹ ⬝ ap f q)⁻¹ ⬝ e r' = idp
We first define "simple two quotients" which have as requirement that the right hand side is idp
Then we define "two quotients" which can have an arbitrary path on the right hand side
Then we define "truncated two quotients", which is a two quotient followed by n-truncation,
and show that this satisfies the desired induction principle and computation rule.
Caveat: for none of these constructions we show that the induction priniciple computes on
2-paths. However, with truncated two quotients, if the truncation is a 1-truncation, then this
computation rule follows automatically, since the target is a 1-type.
-/
namespace simple_two_quotient
section
parameters {A : Type}
(R : A → A → Type)
local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R
parameter (Q : Π⦃a⦄, T a a → Type)
variables ⦃a a' : A⦄ {s : R a a'} {r : T a a}
local abbreviation B := A ⊎ Σ(a : A) (r : T a a), Q r
inductive pre_two_quotient_rel : B → B → Type :=
| pre_Rmk {} : Π⦃a a'⦄ (r : R a a'), pre_two_quotient_rel (inl a) (inl a')
--BUG: if {} not provided, the alias for pre_Rmk is wrong
definition pre_two_quotient := quotient pre_two_quotient_rel
open pre_two_quotient_rel
local abbreviation C := quotient pre_two_quotient_rel
protected definition j [constructor] (a : A) : C := class_of pre_two_quotient_rel (inl a)
protected definition pre_aux [constructor] (q : Q r) : C :=
class_of pre_two_quotient_rel (inr ⟨a, r, q⟩)
protected definition e (s : R a a') : j a = j a' := eq_of_rel _ (pre_Rmk s)
protected definition et (t : T a a') : j a = j a' := e_closure.elim e t
protected definition f [unfold 7] (q : Q r) : S¹ → C :=
circle.elim (j a) (et r)
protected definition pre_rec [unfold 8] {P : C → Type}
(Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q))
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') (x : C) : P x :=
begin
induction x with p,
{ induction p,
{ apply Pj},
{ induction a with a1 a2, induction a2, apply Pa}},
{ induction H, esimp, apply Pe},
end
protected definition pre_elim [unfold 8] {P : Type} (Pj : A → P)
(Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') (x : C)
: P :=
pre_rec Pj Pa (λa a' s, pathover_of_eq _ (Pe s)) x
protected theorem rec_e {P : C → Type}
(Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q))
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') ⦃a a' : A⦄ (s : R a a')
: apd (pre_rec Pj Pa Pe) (e s) = Pe s :=
!rec_eq_of_rel
protected theorem elim_e {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P)
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (s : R a a')
: ap (pre_elim Pj Pa Pe) (e s) = Pe s :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (e s)),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑pre_elim,rec_e],
end
protected definition elim_et {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P)
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (t : T a a')
: ap (pre_elim Pj Pa Pe) (et t) = e_closure.elim Pe t :=
ap_e_closure_elim_h e (elim_e Pj Pa Pe) t
protected definition rec_et {P : C → Type}
(Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q))
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') ⦃a a' : A⦄ (t : T a a')
: apd (pre_rec Pj Pa Pe) (et t) = e_closure.elimo e Pe t :=
ap_e_closure_elimo_h e Pe (rec_e Pj Pa Pe) t
inductive simple_two_quotient_rel : C → C → Type :=
| Rmk {} : Π{a : A} {r : T a a} (q : Q r) (x : circle),
simple_two_quotient_rel (f q x) (pre_aux q)
open simple_two_quotient_rel
definition simple_two_quotient := quotient simple_two_quotient_rel
local abbreviation D := simple_two_quotient
local abbreviation i := class_of simple_two_quotient_rel
definition incl0 (a : A) : D := i (j a)
protected definition aux (q : Q r) : D := i (pre_aux q)
definition incl1 (s : R a a') : incl0 a = incl0 a' := ap i (e s)
definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t
-- "wrong" version inclt, which is ap i (p ⬝ q) instead of ap i p ⬝ ap i q
-- it is used in the proof, because incltw is easier to work with
protected definition incltw (t : T a a') : incl0 a = incl0 a' := ap i (et t)
protected definition inclt_eq_incltw (t : T a a') : inclt t = incltw t :=
(ap_e_closure_elim i e t)⁻¹
definition incl2' (q : Q r) (x : S¹) : i (f q x) = aux q :=
eq_of_rel simple_two_quotient_rel (Rmk q x)
protected definition incl2w (q : Q r) : incltw r = idp :=
(ap02 i (elim_loop (j a) (et r))⁻¹) ⬝
(ap_compose i (f q) loop)⁻¹ ⬝
ap_is_constant (incl2' q) loop ⬝
!con.right_inv
definition incl2 (q : Q r) : inclt r = idp :=
inclt_eq_incltw r ⬝ incl2w q
local attribute simple_two_quotient f i D incl0 aux incl1 incl2' inclt [reducible]
local attribute i aux incl0 [constructor]
parameters {R Q}
protected definition rec {P : D → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r),
change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) (x : D) : P x :=
begin
induction x,
{ refine (pre_rec _ _ _ a),
{ exact P0},
{ intro a r q, exact incl2' q base ▸ P0 a},
{ intro a a' s, exact pathover_of_pathover_ap P i (P1 s)}},
{ exact abstract [irreducible] begin induction H, induction x,
{ esimp, exact pathover_tr (incl2' q base) (P0 a)},
{ apply pathover_pathover,
esimp, fold [i, incl2' q],
refine eq_hconcato _ _, apply _,
{ transitivity _,
{ apply ap (pathover_ap _ _),
transitivity _, apply apd_compose2 (pre_rec P0 _ _) (f q) loop,
apply ap (pathover_of_pathover_ap _ _),
transitivity _, apply apd_change_path, exact !elim_loop⁻¹,
transitivity _,
apply ap (change_path _),
transitivity _, apply rec_et,
transitivity (pathover_of_pathover_ap P i (change_path (inclt_eq_incltw r)
(e_closure.elimo incl1 (λ (a a' : A) (s : R a a'), P1 s) r))),
apply e_closure_elimo_ap,
exact idp,
apply change_path_pathover_of_pathover_ap},
esimp, transitivity _, apply pathover_ap_pathover_of_pathover_ap P i (f q),
transitivity _, apply ap (change_path _), apply to_right_inv !pathover_compose,
do 2 (transitivity _; exact !change_path_con⁻¹),
transitivity _, apply ap (change_path _),
exact (to_left_inv (change_path_equiv _ _ (incl2 q)) _)⁻¹, esimp,
rewrite P2, transitivity _; exact !change_path_con⁻¹, apply ap (λx, change_path x _),
rewrite [↑incl2, con_inv], transitivity _, exact !con.assoc⁻¹,
rewrite [inv_con_cancel_right, ↑incl2w, ↑ap02, +con_inv, +ap_inv, +inv_inv, -+con.assoc,
+con_inv_cancel_right], reflexivity},
rewrite [change_path_con, apd_constant],
apply squareover_change_path_left, apply squareover_change_path_right',
apply squareover_change_path_left,
refine change_square _ vrflo,
symmetry, apply inv_ph_eq_of_eq_ph, rewrite [ap_is_constant_natural_square],
apply whisker_bl_whisker_tl_eq} end end},
end
protected definition rec_on [reducible] {P : D → Type} (x : D) (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r),
change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) : P x :=
rec P0 P1 P2 x
theorem rec_incl1 {P : D → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r),
change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) ⦃a a' : A⦄ (s : R a a')
: apd (rec P0 P1 P2) (incl1 s) = P1 s :=
begin
unfold [rec, incl1], refine !apd_ap ⬝ _, esimp, rewrite rec_e,
apply to_right_inv !pathover_compose
end
theorem rec_inclt {P : D → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r),
change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) ⦃a a' : A⦄ (t : T a a')
: apd (rec P0 P1 P2) (inclt t) = e_closure.elimo incl1 P1 t :=
ap_e_closure_elimo_h incl1 P1 (rec_incl1 P0 P1 P2) t
protected definition elim {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
(x : D) : P :=
begin
induction x,
{ refine (pre_elim _ _ _ a),
{ exact P0},
{ intro a r q, exact P0 a},
{ exact P1}},
{ exact abstract begin induction H, induction x,
{ exact idpath (P0 a)},
{ unfold f, apply eq_pathover, apply hdeg_square,
exact abstract ap_compose (pre_elim P0 _ P1) (f q) loop ⬝
ap _ !elim_loop ⬝
!elim_et ⬝
P2 q ⬝
!ap_constant⁻¹ end} end end},
end
local attribute elim [unfold 8]
protected definition elim_on {P : Type} (x : D) (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
: P :=
elim P0 P1 P2 x
definition elim_incl1 {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s :=
(ap_compose (elim P0 P1 P2) i (e s))⁻¹ ⬝ !elim_e
definition elim_inclt {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t :=
ap_e_closure_elim_h incl1 (elim_incl1 P2) t
protected definition elim_incltw {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (incltw t) = e_closure.elim P1 t :=
(ap_compose (elim P0 P1 P2) i (et t))⁻¹ ⬝ !elim_et
protected theorem elim_inclt_eq_elim_incltw {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a a' : A⦄ (t : T a a')
: elim_inclt P2 t = ap (ap (elim P0 P1 P2)) (inclt_eq_incltw t) ⬝ elim_incltw P2 t :=
begin
unfold [elim_inclt,elim_incltw,inclt_eq_incltw,et],
refine !ap_e_closure_elim_h_eq ⬝ _,
rewrite [ap_inv,-con.assoc],
xrewrite [eq_of_square (ap_ap_e_closure_elim i (elim P0 P1 P2) e t)⁻¹ʰ],
rewrite [↓incl1,con.assoc], apply whisker_left,
rewrite [↑[elim_et,elim_incl1],+ap_e_closure_elim_h_eq,con_inv,↑[i,function.compose]],
rewrite [-con.assoc (_ ⬝ _),con.assoc _⁻¹,con.left_inv,▸*,-ap_inv,-ap_con],
apply ap (ap _),
krewrite [-eq_of_homotopy3_inv,-eq_of_homotopy3_con]
end
definition elim_incl2' {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a : A⦄ ⦃r : T a a⦄ (q : Q r) : ap (elim P0 P1 P2) (incl2' q base) = idpath (P0 a) :=
!elim_eq_of_rel
local attribute whisker_right [reducible]
protected theorem elim_incl2w {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a : A⦄ ⦃r : T a a⦄ (q : Q r)
: square (ap02 (elim P0 P1 P2) (incl2w q)) (P2 q) (elim_incltw P2 r) idp :=
begin
esimp [incl2w,ap02],
rewrite [+ap_con (ap _),▸*],
xrewrite [-ap_compose (ap _) (ap i)],
rewrite [+ap_inv],
xrewrite [eq_top_of_square
((ap_compose_natural (elim P0 P1 P2) i (elim_loop (j a) (et r)))⁻¹ʰ⁻¹ᵛ ⬝h
(ap_ap_compose (elim P0 P1 P2) i (f q) loop)⁻¹ʰ⁻¹ᵛ ⬝h
ap_ap_is_constant (elim P0 P1 P2) (incl2' q) loop ⬝h
ap_con_right_inv_sq (elim P0 P1 P2) (incl2' q base)),
↑[elim_incltw]],
apply whisker_tl,
rewrite [ap_is_constant_eq],
xrewrite [naturality_apd_eq (λx, !elim_eq_of_rel) loop],
rewrite [↑elim_2,rec_loop,square_of_pathover_concato_eq,square_of_pathover_eq_concato,
eq_of_square_vconcat_eq,eq_of_square_eq_vconcat],
apply eq_vconcat,
{ apply ap (λx, _ ⬝ eq_con_inv_of_con_eq ((_ ⬝ x ⬝ _)⁻¹ ⬝ _) ⬝ _),
transitivity _, apply ap eq_of_square,
apply to_right_inv !eq_pathover_equiv_square (hdeg_square (elim_1 P A R Q P0 P1 a r q P2)),
transitivity _, apply eq_of_square_hdeg_square,
unfold elim_1, reflexivity},
rewrite [+con_inv,whisker_left_inv,+inv_inv,-whisker_right_inv,
con.assoc (whisker_left _ _),con.assoc _ (whisker_right _ _),▸*,
whisker_right_con_whisker_left _ !ap_constant],
xrewrite [-con.assoc _ _ (whisker_right _ _)],
rewrite [con.assoc _ _ (whisker_left _ _),idp_con_whisker_left,▸*,
con.assoc _ !ap_constant⁻¹,con.left_inv],
xrewrite [eq_con_inv_of_con_eq_whisker_left,▸*],
rewrite [+con.assoc _ _ !con.right_inv,
right_inv_eq_idp (
(λ(x : ap (elim P0 P1 P2) (incl2' q base) = idpath
(elim P0 P1 P2 (class_of simple_two_quotient_rel (f q base)))), x)
(elim_incl2' P2 q)),
↑[whisker_left]],
xrewrite [con2_con_con2],
rewrite [idp_con,↑elim_incl2',con.left_inv,whisker_right_inv,↑whisker_right],
xrewrite [con.assoc _ _ (_ ◾ _)],
rewrite [con.left_inv,▸*,-+con.assoc,con.assoc _⁻¹,↑[elim,function.compose],con.left_inv,
▸*,↑j,con.left_inv,idp_con],
apply square_of_eq, reflexivity
end
theorem elim_incl2 {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a : A⦄ ⦃r : T a a⦄ (q : Q r)
: square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 r) idp :=
begin
rewrite [↑incl2,↑ap02,ap_con,elim_inclt_eq_elim_incltw],
apply whisker_tl,
apply elim_incl2w
end
end
end simple_two_quotient
export [unfold] simple_two_quotient
attribute simple_two_quotient.j simple_two_quotient.incl0 [constructor]
attribute simple_two_quotient.rec simple_two_quotient.elim [unfold 8] [recursor 8]
--attribute simple_two_quotient.elim_type [unfold 9] -- TODO
attribute simple_two_quotient.rec_on simple_two_quotient.elim_on [unfold 5]
--attribute simple_two_quotient.elim_type_on [unfold 6] -- TODO
namespace two_quotient
open simple_two_quotient
section
parameters {A : Type}
(R : A → A → Type)
local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R
parameter (Q : Π⦃a a'⦄, T a a' → T a a' → Type)
variables ⦃a a' a'' : A⦄ {s : R a a'} {t t' : T a a'}
inductive two_quotient_Q : Π⦃a : A⦄, e_closure R a a → Type :=
| Qmk : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄, Q t t' → two_quotient_Q (t ⬝r t'⁻¹ʳ)
open two_quotient_Q
local abbreviation Q2 := two_quotient_Q
definition two_quotient := simple_two_quotient R Q2
definition incl0 (a : A) : two_quotient := incl0 _ _ a
definition incl1 (s : R a a') : incl0 a = incl0 a' := incl1 _ _ s
definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t
definition incl2 (q : Q t t') : inclt t = inclt t' :=
eq_of_con_inv_eq_idp (incl2 _ _ (Qmk R q))
parameters {R Q}
protected definition rec {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
(x : two_quotient) : P x :=
begin
induction x,
{ exact P0 a},
{ exact P1 s},
{ exact abstract [irreducible] begin induction q with a a' t t' q,
rewrite [elimo_trans (simple_two_quotient.incl1 R Q2) P1,
elimo_symm (simple_two_quotient.incl1 R Q2) P1,
-whisker_right_eq_of_con_inv_eq_idp (simple_two_quotient.incl2 R Q2 (Qmk R q)),
change_path_con],
xrewrite [change_path_cono],
refine ap (λx, change_path _ (_ ⬝o x)) !change_path_invo ⬝ _, esimp,
apply cono_invo_eq_idpo, apply P2 end end}
end
protected definition rec_on [reducible] {P : two_quotient → Type} (x : two_quotient)
(P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') : P x :=
rec P0 P1 P2 x
theorem rec_incl1 {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
⦃a a' : A⦄ (s : R a a') : apd (rec P0 P1 P2) (incl1 s) = P1 s :=
rec_incl1 _ _ _ s
theorem rec_inclt {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
⦃a a' : A⦄ (t : T a a') : apd (rec P0 P1 P2) (inclt t) = e_closure.elimo incl1 P1 t :=
rec_inclt _ _ _ t
protected definition elim {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
(x : two_quotient) : P :=
begin
induction x,
{ exact P0 a},
{ exact P1 s},
{ exact abstract [unfold 10] begin induction q with a a' t t' q,
esimp [e_closure.elim],
apply con_inv_eq_idp, exact P2 q end end},
end
local attribute elim [unfold 8]
protected definition elim_on {P : Type} (x : two_quotient) (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
: P :=
elim P0 P1 P2 x
definition elim_incl1 {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s :=
!elim_incl1
definition elim_inclt {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t :=
ap_e_closure_elim_h incl1 (elim_incl1 P2) t
theorem elim_incl2 {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t')
: square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 t) (elim_inclt P2 t') :=
begin
rewrite [↑[incl2,elim],ap_eq_of_con_inv_eq_idp],
xrewrite [eq_top_of_square (elim_incl2 P0 P1 (elim_1 A R Q P P0 P1 P2) (Qmk R q))],
xrewrite [{simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2)
(t ⬝r t'⁻¹ʳ)}
idpath (ap_con (simple_two_quotient.elim P0 P1 (elim_1 A R Q P P0 P1 P2))
(inclt t) (inclt t')⁻¹ ⬝
(simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2) t ◾
(ap_inv (simple_two_quotient.elim P0 P1 (elim_1 A R Q P P0 P1 P2))
(inclt t') ⬝
inverse2 (simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2) t')))),▸*],
rewrite [-con.assoc _ _ (con_inv_eq_idp _),-con.assoc _ _ (_ ◾ _),con.assoc _ _ (ap_con _ _ _),
con.left_inv,↑whisker_left,con2_con_con2,-con.assoc (ap_inv _ _)⁻¹,
con.left_inv,+idp_con,eq_of_con_inv_eq_idp_con2],
xrewrite [to_left_inv !eq_equiv_con_inv_eq_idp (P2 q)],
apply top_deg_square
end
definition elim_inclt_rel [unfold_full] {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (r : R a a') : elim_inclt P2 [r] = elim_incl1 P2 r :=
idp
definition elim_inclt_inv [unfold_full] {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (t : T a a')
: elim_inclt P2 t⁻¹ʳ = ap_inv (elim P0 P1 P2) (inclt t) ⬝ (elim_inclt P2 t)⁻² :=
idp
definition elim_inclt_con [unfold_full] {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' a'' : A⦄ (t : T a a') (t': T a' a'')
: elim_inclt P2 (t ⬝r t') =
ap_con (elim P0 P1 P2) (inclt t) (inclt t') ⬝ (elim_inclt P2 t ◾ elim_inclt P2 t') :=
idp
definition inclt_rel [unfold_full] (r : R a a') : inclt [r] = incl1 r := idp
definition inclt_inv [unfold_full] (t : T a a') : inclt t⁻¹ʳ = (inclt t)⁻¹ := idp
definition inclt_con [unfold_full] (t : T a a') (t' : T a' a'')
: inclt (t ⬝r t') = inclt t ⬝ inclt t' := idp
end
end two_quotient
attribute two_quotient.incl0 [constructor]
attribute two_quotient.rec two_quotient.elim [unfold 8] [recursor 8]
--attribute two_quotient.elim_type [unfold 9]
attribute two_quotient.rec_on two_quotient.elim_on [unfold 5]
--attribute two_quotient.elim_type_on [unfold 6]
open two_quotient is_trunc trunc
namespace trunc_two_quotient
section
parameters (n : ℕ₋₂) {A : Type}
(R : A → A → Type)
local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R
parameter (Q : Π⦃a a'⦄, T a a' → T a a' → Type)
variables ⦃a a' a'' : A⦄ {s : R a a'} {t t' : T a a'}
definition trunc_two_quotient := trunc n (two_quotient R Q)
parameters {n R Q}
definition incl0 (a : A) : trunc_two_quotient := tr (!incl0 a)
definition incl1 (s : R a a') : incl0 a = incl0 a' := ap tr (!incl1 s)
definition incltw (t : T a a') : incl0 a = incl0 a' := ap tr (!inclt t)
definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t
definition incl2w (q : Q t t') : incltw t = incltw t' :=
ap02 tr (!incl2 q)
definition incl2 (q : Q t t') : inclt t = inclt t' :=
!ap_e_closure_elim⁻¹ ⬝ ap02 tr (!incl2 q) ⬝ !ap_e_closure_elim
local attribute trunc_two_quotient incl0 [reducible]
definition is_trunc_trunc_two_quotient [instance] : is_trunc n trunc_two_quotient := _
protected definition rec {P : trunc_two_quotient → Type} [H : Πx, is_trunc n (P x)]
(P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
(x : trunc_two_quotient) : P x :=
begin
induction x,
induction a,
{ exact P0 a},
{ exact !pathover_of_pathover_ap (P1 s)},
{ exact abstract [irreducible]
by rewrite [+ e_closure_elimo_ap, ↓incl1, -P2 q, change_path_pathover_of_pathover_ap,
- + change_path_con, ↑incl2, con_inv_cancel_right] end}
end
protected definition rec_on [reducible] {P : trunc_two_quotient → Type} [H : Πx, is_trunc n (P x)]
(x : trunc_two_quotient)
(P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') : P x :=
rec P0 P1 P2 x
theorem rec_incl1 {P : trunc_two_quotient → Type} [H : Πx, is_trunc n (P x)]
(P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
⦃a a' : A⦄ (s : R a a') : apd (rec P0 P1 P2) (incl1 s) = P1 s :=
!apd_ap ⬝ ap !pathover_ap !rec_incl1 ⬝ to_right_inv !pathover_compose (P1 s)
theorem rec_inclt {P : trunc_two_quotient → Type} [H : Πx, is_trunc n (P x)]
(P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
⦃a a' : A⦄ (t : T a a') : apd (rec P0 P1 P2) (inclt t) = e_closure.elimo incl1 P1 t :=
ap_e_closure_elimo_h incl1 P1 (rec_incl1 P0 P1 P2) t
protected definition elim {P : Type} (P0 : A → P) [H : is_trunc n P]
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
(x : trunc_two_quotient) : P :=
begin
induction x,
induction a,
{ exact P0 a},
{ exact P1 s},
{ exact P2 q},
end
local attribute elim [unfold 10]
protected definition elim_on {P : Type} [H : is_trunc n P] (x : trunc_two_quotient) (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
: P :=
elim P0 P1 P2 x
definition elim_incl1 {P : Type} [H : is_trunc n P] {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s :=
!ap_compose⁻¹ ⬝ !elim_incl1
definition elim_inclt {P : Type} [H : is_trunc n P] {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t :=
ap_e_closure_elim_h incl1 (elim_incl1 P2) t
open function
theorem elim_incl2 {P : Type} [H : is_trunc n P] (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t')
: square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 t) (elim_inclt P2 t') :=
begin
note Ht' := ap_ap_e_closure_elim tr (elim P0 P1 P2) (two_quotient.incl1 R Q) t',
note Ht := ap_ap_e_closure_elim tr (elim P0 P1 P2) (two_quotient.incl1 R Q) t,
note Hn := natural_square_tr (ap_compose (elim P0 P1 P2) tr) (two_quotient.incl2 R Q q),
note H7 := eq_top_of_square (Ht⁻¹ʰ ⬝h Hn⁻¹ᵛ ⬝h Ht'), clear [Hn, Ht, Ht'],
unfold [ap02,incl2], rewrite [+ap_con,ap_inv,-ap_compose (ap _)],
xrewrite [H7, ↑function.compose, eq_top_of_square (elim_incl2 P0 P1 P2 q)], clear [H7],
have H : Π(t : T a a'),
ap_e_closure_elim (elim P0 P1 P2) (λa a' (r : R a a'), ap tr (two_quotient.incl1 R Q r)) t ⬝
(ap_e_closure_elim_h (two_quotient.incl1 R Q)
(λa a' (s : R a a'), ap_compose (elim P0 P1 P2) tr (two_quotient.incl1 R Q s)) t)⁻¹ ⬝
two_quotient.elim_inclt P2 t = elim_inclt P2 t, from
ap_e_closure_elim_h_zigzag (elim P0 P1 P2)
(two_quotient.incl1 R Q)
(two_quotient.elim_incl1 P2),
rewrite [con.assoc5, con.assoc5, H t, -inv_con_inv_right, -con_inv], xrewrite [H t'],
apply top_deg_square
end
definition elim_inclt_rel [unfold_full] {P : Type} [is_trunc n P] {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (r : R a a') : elim_inclt P2 [r] = elim_incl1 P2 r :=
idp
definition elim_inclt_inv [unfold_full] {P : Type} [is_trunc n P] {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (t : T a a')
: elim_inclt P2 t⁻¹ʳ = ap_inv (elim P0 P1 P2) (inclt t) ⬝ (elim_inclt P2 t)⁻² :=
idp
definition elim_inclt_con [unfold_full] {P : Type} [is_trunc n P] {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' a'' : A⦄ (t : T a a') (t': T a' a'')
: elim_inclt P2 (t ⬝r t') =
ap_con (elim P0 P1 P2) (inclt t) (inclt t') ⬝ (elim_inclt P2 t ◾ elim_inclt P2 t') :=
idp
definition inclt_rel [unfold_full] (r : R a a') : inclt [r] = incl1 r := idp
definition inclt_inv [unfold_full] (t : T a a') : inclt t⁻¹ʳ = (inclt t)⁻¹ := idp
definition inclt_con [unfold_full] (t : T a a') (t' : T a' a'')
: inclt (t ⬝r t') = inclt t ⬝ inclt t' := idp
end
end trunc_two_quotient
attribute trunc_two_quotient.incl0 [constructor]
attribute trunc_two_quotient.rec trunc_two_quotient.elim [unfold 10] [recursor 10]
attribute trunc_two_quotient.rec_on trunc_two_quotient.elim_on [unfold 7]
|
4cedf76e1a63d0fb757bed9f52475060591e115c | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch4/ex0404.lean | 52404c170f40a5a7fee16196c0b9a76f9088eee6 | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 226 | lean | variables (α : Type) (p q : α → Prop)
example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x :=
exists.elim h
(assume w,
assume hw : p w ∧ q w,
show ∃ x, q x ∧ p x, from ⟨w, hw.right, hw.left⟩)
|
2eed65caee2a1b67dcbd1747d0b127891b1cb224 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /tests/lean/match1.lean | a3c63d0f8e08e86126945085f7e5581c64805a55 | [
"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 | 3,372 | lean | --
#print "---- h1"
def h1 (b : Bool) : Nat :=
match b with
| true => 0
| false => 10
#eval h1 false
#print "---- h2"
def h2 (x : List Nat) : Nat :=
match x with
| [x1, x2] => x1 + x2
| x::xs => x
| _ => 0
#eval h2 [1, 2]
#eval h2 [10, 4, 5]
#eval h2 []
#print "---- h3"
def h3 (x : Array Nat) : Nat :=
match x with
| #[x] => x
| #[x, y] => x + y
| xs => xs.size
#eval h3 #[10]
#eval h3 #[10, 20]
#eval h3 #[10, 20, 30, 40]
#print "---- inv"
inductive Image {α β : Type} (f : α → β) : β → Type
| mk (a : α) : Image f (f a)
def mkImage {α β : Type} (f : α → β) (a : α) : Image f (f a) :=
Image.mk a
def inv {α β : Type} {f : α → β} {b : β} (t : Image f b) : α :=
match b, t with
| _, Image.mk a => a
#eval inv (mkImage Nat.succ 10)
theorem foo {p q} (h : p ∨ q) : q ∨ p :=
match h with
| Or.inl h => Or.inr h
| Or.inr h => Or.inl h
def f (x : Nat × Nat) : Bool × Bool × Bool → Nat :=
match x with
| (a, b) => fun _ => a
structure S :=
(x y z : Nat := 0)
def f1 : S → S :=
fun { x := x, ..} => { y := x }
theorem ex2 : f1 { x := 10 } = { y := 10 } :=
rfl
universes u
inductive Vec (α : Type u) : Nat → Type u
| nil : Vec α 0
| cons {n} (head : α) (tail : Vec α n) : Vec α (n+1)
inductive VecPred {α : Type u} (P : α → Prop) : {n : Nat} → Vec α n → Prop
| nil : VecPred P Vec.nil
| cons {n : Nat} {head : α} {tail : Vec α n} : P head → VecPred P tail → VecPred P (Vec.cons head tail)
theorem ex3 {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P
| _, Vec.cons head _, VecPred.cons h _ => ⟨head, h⟩
theorem ex4 {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P
| _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ -- ERROR
axiom someNat : Nat
noncomputable def f2 (x : Nat) := -- must mark as noncomputable since it uses axiom `someNat`
x + someNat
inductive Parity : Nat -> Type
| even (n) : Parity (n + n)
| odd (n) : Parity (Nat.succ (n + n))
axiom nDiv2 (n : Nat) : n % 2 = 0 → n = n/2 + n/2
axiom nDiv2Succ (n : Nat) : n % 2 ≠ 0 → n = Nat.succ (n/2 + n/2)
def parity (n : Nat) : Parity n :=
if h : n % 2 = 0 then
Eq.ndrec (Parity.even (n/2)) (nDiv2 n h).symm
else
Eq.ndrec (Parity.odd (n/2)) (nDiv2Succ n h).symm
partial def natToBin : (n : Nat) → List Bool
| 0 => []
| n => match n, parity n with
| _, Parity.even j => false :: natToBin j
| _, Parity.odd j => true :: natToBin j
#eval natToBin 6
partial def natToBinBad (n : Nat) : List Bool :=
match n, parity n with
| 0, _ => []
| _, Parity.even j => false :: natToBin j
| _, Parity.odd j => true :: natToBin j
partial def natToBin2 (n : Nat) : List Bool :=
match n, parity n with
| _, Parity.even 0 => []
| _, Parity.even j => false :: natToBin j
| _, Parity.odd j => true :: natToBin j
#eval natToBin2 6
#check fun (a, b) => a -- Error type of pattern variable contains metavariables
#check fun (a, b) => (a:Nat) + b
#check fun (a, b) => a && b
#check fun ((a : Nat), (b : Nat)) => a + b
#check fun
| some a, some b => some (a + b : Nat)
| _, _ => none
-- overapplied matcher
#check fun x => (match x with 0 => id | x+1 => id) x
#check fun
| #[1, 2] => 2
| #[] => 0
| #[3, 4, 5] => 3
| _ => 4
|
f01b1ca977e635b083b54b7ab4f4b6d5efbcdce4 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/geometry/euclidean/basic.lean | 3edd5bc4fbb77c6604be85b97abbce511890dfb4 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 56,024 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Manuel Candales
-/
import analysis.inner_product_space.projection
import analysis.special_functions.trigonometric.inverse
import algebra.quadratic_discriminant
import linear_algebra.affine_space.finite_dimensional
/-!
# Euclidean spaces
This file makes some definitions and proves very basic geometrical
results about real inner product spaces and Euclidean affine spaces.
Results about real inner product spaces that involve the norm and
inner product but not angles generally go in
`analysis.normed_space.inner_product`. Results with longer
proofs or more geometrical content generally go in separate files.
## Main definitions
* `inner_product_geometry.angle` is the undirected angle between two
vectors.
* `euclidean_geometry.angle`, with notation `∠`, is the undirected
angle determined by three points.
* `euclidean_geometry.orthogonal_projection` is the orthogonal
projection of a point onto an affine subspace.
* `euclidean_geometry.reflection` is the reflection of a point in an
affine subspace.
## Implementation notes
To declare `P` as the type of points in a Euclidean affine space with
`V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]`. This works better with `out_param` to make
`V` implicit in most cases than having a separate type alias for
Euclidean affine spaces.
Rather than requiring Euclidean affine spaces to be finite-dimensional
(as in the definition on Wikipedia), this is specified only for those
theorems that need it.
## References
* https://en.wikipedia.org/wiki/Euclidean_space
-/
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
namespace inner_product_geometry
/-!
### Geometrical results on real inner product spaces
This section develops some geometrical definitions and results on real
inner product spaces, where those definitions and results can most
conveniently be developed in terms of vectors and then used to deduce
corresponding results for Euclidean affine spaces.
-/
variables {V : Type*} [inner_product_space ℝ V]
/-- The undirected angle between two vectors. If either vector is 0,
this is π/2. -/
def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥))
lemma is_conformal_map.preserves_angle {E F : Type*}
[inner_product_space ℝ E] [inner_product_space ℝ F]
{f' : E →L[ℝ] F} (h : is_conformal_map f') (u v : E) :
angle (f' u) (f' v) = angle u v :=
begin
obtain ⟨c, hc, li, hcf⟩ := h,
suffices : c * (c * inner u v) / (∥c∥ * ∥u∥ * (∥c∥ * ∥v∥)) = inner u v / (∥u∥ * ∥v∥),
{ simp [this, angle, hcf, norm_smul, inner_smul_left, inner_smul_right] },
by_cases hu : ∥u∥ = 0,
{ simp [norm_eq_zero.mp hu] },
by_cases hv : ∥v∥ = 0,
{ simp [norm_eq_zero.mp hv] },
have hc : ∥c∥ ≠ 0 := λ w, hc (norm_eq_zero.mp w),
field_simp,
have : c * c = ∥c∥ * ∥c∥ := by simp [real.norm_eq_abs, abs_mul_abs_self],
convert congr_arg (λ x, x * ⟪u, v⟫ * ∥u∥ * ∥v∥) this using 1; ring,
end
/-- If a real differentiable map `f` is conformal at a point `x`,
then it preserves the angles at that point. -/
lemma conformal_at.preserves_angle {E F : Type*}
[inner_product_space ℝ E] [inner_product_space ℝ F]
{f : E → F} {x : E} {f' : E →L[ℝ] F}
(h : has_fderiv_at f f' x) (H : conformal_at f x) (u v : E) :
angle (f' u) (f' v) = angle u v :=
let ⟨f₁, h₁, c⟩ := H in h₁.unique h ▸ is_conformal_map.preserves_angle c u v
/-- The cosine of the angle between two vectors. -/
lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) :=
real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
/-- The angle between two vectors does not depend on their order. -/
lemma angle_comm (x y : V) : angle x y = angle y x :=
begin
unfold angle,
rw [real_inner_comm, mul_comm]
end
/-- The angle between the negation of two vectors. -/
@[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y :=
begin
unfold angle,
rw [inner_neg_neg, norm_neg, norm_neg]
end
/-- The angle between two vectors is nonnegative. -/
lemma angle_nonneg (x y : V) : 0 ≤ angle x y :=
real.arccos_nonneg _
/-- The angle between two vectors is at most π. -/
lemma angle_le_pi (x y : V) : angle x y ≤ π :=
real.arccos_le_pi _
/-- The angle between a vector and the negation of another vector. -/
lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y :=
begin
unfold angle,
rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div]
end
/-- The angle between the negation of a vector and another vector. -/
lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y :=
by rw [←angle_neg_neg, neg_neg, angle_neg_right]
/-- The angle between the zero vector and a vector. -/
@[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 :=
begin
unfold angle,
rw [inner_zero_left, zero_div, real.arccos_zero]
end
/-- The angle between a vector and the zero vector. -/
@[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 :=
begin
unfold angle,
rw [inner_zero_right, zero_div, real.arccos_zero]
end
/-- The angle between a nonzero vector and itself. -/
@[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 :=
begin
unfold angle,
rw [←real_inner_self_eq_norm_sq, div_self (λ h, hx (inner_self_eq_zero.1 h)),
real.arccos_one]
end
/-- The angle between a nonzero vector and its negation. -/
@[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π :=
by rw [angle_neg_right, angle_self hx, sub_zero]
/-- The angle between the negation of a nonzero vector and that
vector. -/
@[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π :=
by rw [angle_comm, angle_self_neg_of_nonzero hx]
/-- The angle between a vector and a positive multiple of a vector. -/
@[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) :
angle x (r • y) = angle x y :=
begin
unfold angle,
rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc,
mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)]
end
/-- The angle between a positive multiple of a vector and a vector. -/
@[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) :
angle (r • x) y = angle x y :=
by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm]
/-- The angle between a vector and a negative multiple of a vector. -/
@[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) :
angle x (r • y) = angle x (-y) :=
by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr),
angle_neg_right]
/-- The angle between a negative multiple of a vector and a vector. -/
@[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) :
angle (r • x) y = angle (-x) y :=
by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm]
/-- The cosine of the angle between two vectors, multiplied by the
product of their norms. -/
lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y :=
begin
rw [cos_angle, div_mul_cancel_of_imp],
simp [or_imp_distrib] { contextual := tt },
end
/-- The sine of the angle between two vectors, multiplied by the
product of their norms. -/
lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) =
real.sqrt (inner x x * inner y y - inner x y * inner x y) :=
begin
unfold angle,
rw [real.sin_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2,
←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)),
←real.sqrt_mul' _ (mul_self_nonneg _), sq,
real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)),
real_inner_self_eq_norm_sq,
real_inner_self_eq_norm_sq],
by_cases h : (∥x∥ * ∥y∥) = 0,
{ rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero,
zero_sub],
cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy,
{ rw norm_eq_zero at hx,
rw [hx, inner_zero_left, zero_mul, neg_zero] },
{ rw norm_eq_zero at hy,
rw [hy, inner_zero_right, zero_mul, neg_zero] } },
{ field_simp [h],
ring_nf,
ring_nf, }
end
/-- The angle between two vectors is zero if and only if they are
nonzero and one is a positive multiple of the other. -/
lemma angle_eq_zero_iff {x y : V} : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) :=
begin
rw [angle, ← real_inner_div_norm_mul_norm_eq_one_iff, real.arccos_eq_zero, has_le.le.le_iff_eq,
eq_comm],
exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
end
/-- The angle between two vectors is π if and only if they are nonzero
and one is a negative multiple of the other. -/
lemma angle_eq_pi_iff {x y : V} : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) :=
begin
rw [angle, ← real_inner_div_norm_mul_norm_eq_neg_one_iff, real.arccos_eq_pi, has_le.le.le_iff_eq],
exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
end
/-- If the angle between two vectors is π, the angles between those
vectors and a third vector add to π. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) :
angle x z + angle y z = π :=
begin
rcases angle_eq_pi_iff.1 h with ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩,
rw [angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right]
end
/-- Two vectors have inner product 0 if and only if the angle between
them is π/2. -/
lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : ⟪x, y⟫ = 0 ↔ angle x y = π / 2 :=
iff.symm $ by simp [angle, or_imp_distrib] { contextual := tt }
/-- If the angle between two vectors is π, the inner product equals the negative product
of the norms. -/
lemma inner_eq_neg_mul_norm_of_angle_eq_pi {x y : V} (h : angle x y = π) : ⟪x, y⟫ = - (∥x∥ * ∥y∥) :=
by simp [← cos_angle_mul_norm_mul_norm, h]
/-- If the angle between two vectors is 0, the inner product equals the product of the norms. -/
lemma inner_eq_mul_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ⟪x, y⟫ = ∥x∥ * ∥y∥ :=
by simp [← cos_angle_mul_norm_mul_norm, h]
/-- The inner product of two non-zero vectors equals the negative product of their norms
if and only if the angle between the two vectors is π. -/
lemma inner_eq_neg_mul_norm_iff_angle_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
⟪x, y⟫ = - (∥x∥ * ∥y∥) ↔ angle x y = π :=
begin
refine ⟨λ h, _, inner_eq_neg_mul_norm_of_angle_eq_pi⟩,
have h₁ : (∥x∥ * ∥y∥) ≠ 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne',
rw [angle, h, neg_div, div_self h₁, real.arccos_neg_one],
end
/-- The inner product of two non-zero vectors equals the product of their norms
if and only if the angle between the two vectors is 0. -/
lemma inner_eq_mul_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ angle x y = 0 :=
begin
refine ⟨λ h, _, inner_eq_mul_norm_of_angle_eq_zero⟩,
have h₁ : (∥x∥ * ∥y∥) ≠ 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne',
rw [angle, h, div_self h₁, real.arccos_one],
end
/-- If the angle between two vectors is π, the norm of their difference equals
the sum of their norms. -/
lemma norm_sub_eq_add_norm_of_angle_eq_pi {x y : V} (h : angle x y = π) : ∥x - y∥ = ∥x∥ + ∥y∥ :=
begin
rw ← sq_eq_sq (norm_nonneg (x - y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)),
rw [norm_sub_pow_two_real, inner_eq_neg_mul_norm_of_angle_eq_pi h],
ring,
end
/-- If the angle between two vectors is 0, the norm of their sum equals
the sum of their norms. -/
lemma norm_add_eq_add_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ∥x + y∥ = ∥x∥ + ∥y∥ :=
begin
rw ← sq_eq_sq (norm_nonneg (x + y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)),
rw [norm_add_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h],
ring,
end
/-- If the angle between two vectors is 0, the norm of their difference equals
the absolute value of the difference of their norms. -/
lemma norm_sub_eq_abs_sub_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) :
∥x - y∥ = |∥x∥ - ∥y∥| :=
begin
rw [← sq_eq_sq (norm_nonneg (x - y)) (abs_nonneg (∥x∥ - ∥y∥)),
norm_sub_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h, sq_abs (∥x∥ - ∥y∥)],
ring,
end
/-- The norm of the difference of two non-zero vectors equals the sum of their norms
if and only the angle between the two vectors is π. -/
lemma norm_sub_eq_add_norm_iff_angle_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
∥x - y∥ = ∥x∥ + ∥y∥ ↔ angle x y = π :=
begin
refine ⟨λ h, _, norm_sub_eq_add_norm_of_angle_eq_pi⟩,
rw ← inner_eq_neg_mul_norm_iff_angle_eq_pi hx hy,
obtain ⟨hxy₁, hxy₂⟩ := ⟨norm_nonneg (x - y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩,
rw [← sq_eq_sq hxy₁ hxy₂, norm_sub_pow_two_real] at h,
calc inner x y = (∥x∥ ^ 2 + ∥y∥ ^ 2 - (∥x∥ + ∥y∥) ^ 2) / 2 : by linarith
... = -(∥x∥ * ∥y∥) : by ring,
end
/-- The norm of the sum of two non-zero vectors equals the sum of their norms
if and only the angle between the two vectors is 0. -/
lemma norm_add_eq_add_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
∥x + y∥ = ∥x∥ + ∥y∥ ↔ angle x y = 0 :=
begin
refine ⟨λ h, _, norm_add_eq_add_norm_of_angle_eq_zero⟩,
rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy,
obtain ⟨hxy₁, hxy₂⟩ := ⟨norm_nonneg (x + y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩,
rw [← sq_eq_sq hxy₁ hxy₂, norm_add_pow_two_real] at h,
calc inner x y = ((∥x∥ + ∥y∥) ^ 2 - ∥x∥ ^ 2 - ∥y∥ ^ 2)/ 2 : by linarith
... = ∥x∥ * ∥y∥ : by ring,
end
/-- The norm of the difference of two non-zero vectors equals the absolute value
of the difference of their norms if and only the angle between the two vectors is 0. -/
lemma norm_sub_eq_abs_sub_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
∥x - y∥ = |∥x∥ - ∥y∥| ↔ angle x y = 0 :=
begin
refine ⟨λ h, _, norm_sub_eq_abs_sub_norm_of_angle_eq_zero⟩,
rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy,
have h1 : ∥x - y∥ ^ 2 = (∥x∥ - ∥y∥) ^ 2, { rw h, exact sq_abs (∥x∥ - ∥y∥) },
rw norm_sub_pow_two_real at h1,
calc inner x y = ((∥x∥ + ∥y∥) ^ 2 - ∥x∥ ^ 2 - ∥y∥ ^ 2)/ 2 : by linarith
... = ∥x∥ * ∥y∥ : by ring,
end
/-- The norm of the sum of two vectors equals the norm of their difference if and only if
the angle between them is π/2. -/
lemma norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (x y : V) :
∥x + y∥ = ∥x - y∥ ↔ angle x y = π / 2 :=
begin
rw [← sq_eq_sq (norm_nonneg (x + y)) (norm_nonneg (x - y)),
← inner_eq_zero_iff_angle_eq_pi_div_two x y, norm_add_pow_two_real, norm_sub_pow_two_real],
split; intro h; linarith,
end
end inner_product_geometry
namespace euclidean_geometry
/-!
### Geometrical results on Euclidean affine spaces
This section develops some geometrical definitions and results on
Euclidean affine spaces.
-/
open inner_product_geometry
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
local notation `⟪`x`, `y`⟫` := @inner ℝ V _ x y
include V
/-- The undirected angle at `p2` between the line segments to `p1` and
`p3`. If either of those points equals `p2`, this is π/2. Use
`open_locale euclidean_geometry` to access the `∠ p1 p2 p3`
notation. -/
def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2)
localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry
/-- The angle at a point does not depend on the order of the other two
points. -/
lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 :=
angle_comm _ _
/-- The angle at a point is nonnegative. -/
lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 :=
angle_nonneg _ _
/-- The angle at a point is at most π. -/
lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π :=
angle_le_pi _ _
/-- The angle ∠AAB at a point. -/
lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 :=
begin
unfold angle,
rw vsub_self,
exact angle_zero_left _
end
/-- The angle ∠ABB at a point. -/
lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 :=
by rw [angle_comm, angle_eq_left]
/-- The angle ∠ABA at a point. -/
lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 :=
angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he))
/-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/
lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
∠ p2 p1 p3 = 0 :=
begin
unfold angle at h,
rw angle_eq_pi_iff at h,
rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩,
unfold angle,
rw angle_eq_zero_iff,
rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2,
use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one],
rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg],
simp [←hpr]
end
/-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/
lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
∠ p2 p3 p1 = 0 :=
begin
rw angle_comm at h,
exact angle_eq_zero_of_angle_eq_pi_left h
end
/-- If ∠BCD = π, then ∠ABC = ∠ABD. -/
lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) :
∠ p1 p2 p3 = ∠ p1 p2 p4 :=
begin
unfold angle at *,
rcases angle_eq_pi_iff.1 h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩,
rw [eq_comm],
convert angle_smul_right_of_pos (p1 -ᵥ p2) (p3 -ᵥ p2) (add_pos (neg_pos_of_neg hr) zero_lt_one),
rw [add_smul, ← neg_vsub_eq_vsub_rev p2 p3, smul_neg, neg_smul, ← hpr],
simp
end
/-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) :
∠ p1 p3 p2 + ∠ p1 p3 p4 = π :=
begin
unfold angle at h,
rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4],
unfold angle,
exact angle_add_angle_eq_pi_of_angle_eq_pi _ h
end
/-- Vertical Angles Theorem: angles opposite each other, formed by two intersecting straight
lines, are equal. -/
lemma angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi {p1 p2 p3 p4 p5 : P}
(hapc : ∠ p1 p5 p3 = π) (hbpd : ∠ p2 p5 p4 = π) : ∠ p1 p5 p2 = ∠ p3 p5 p4 :=
by linarith [angle_add_angle_eq_pi_of_angle_eq_pi p1 hbpd, angle_comm p4 p5 p1,
angle_add_angle_eq_pi_of_angle_eq_pi p4 hapc, angle_comm p4 p5 p3]
/-- If ∠ABC = π then dist A B ≠ 0. -/
lemma left_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p2 ≠ 0 :=
begin
by_contra heq,
rw [dist_eq_zero] at heq,
rw [heq, angle_eq_left] at h,
exact real.pi_ne_zero (by linarith),
end
/-- If ∠ABC = π then dist C B ≠ 0. -/
lemma right_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p3 p2 ≠ 0 :=
left_dist_ne_zero_of_angle_eq_pi $ (angle_comm _ _ _).trans h
/-- If ∠ABC = π, then (dist A C) = (dist A B) + (dist B C). -/
lemma dist_eq_add_dist_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
dist p1 p3 = dist p1 p2 + dist p3 p2 :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_add_norm_of_angle_eq_pi h,
end
/-- If A ≠ B and C ≠ B then ∠ABC = π if and only if (dist A C) = (dist A B) + (dist B C). -/
lemma dist_eq_add_dist_iff_angle_eq_pi {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) :
dist p1 p3 = dist p1 p2 + dist p3 p2 ↔ ∠ p1 p2 p3 = π :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_add_norm_iff_angle_eq_pi
((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)),
end
/-- If ∠ABC = 0, then (dist A C) = abs ((dist A B) - (dist B C)). -/
lemma dist_eq_abs_sub_dist_of_angle_eq_zero {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = 0) :
(dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_abs_sub_norm_of_angle_eq_zero h,
end
/-- If A ≠ B and C ≠ B then ∠ABC = 0 if and only if (dist A C) = abs ((dist A B) - (dist B C)). -/
lemma dist_eq_abs_sub_dist_iff_angle_eq_zero {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) :
(dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| ↔ ∠ p1 p2 p3 = 0 :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_abs_sub_norm_iff_angle_eq_zero
((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)),
end
/-- The midpoint of the segment AB is the same distance from A as it is from B. -/
lemma dist_left_midpoint_eq_dist_right_midpoint (p1 p2 : P) :
dist p1 (midpoint ℝ p1 p2) = dist p2 (midpoint ℝ p1 p2) :=
by rw [dist_left_midpoint p1 p2, dist_right_midpoint p1 p2]
/-- If M is the midpoint of the segment AB, then ∠AMB = π. -/
lemma angle_midpoint_eq_pi (p1 p2 : P) (hp1p2 : p1 ≠ p2) : ∠ p1 (midpoint ℝ p1 p2) p2 = π :=
have p2 -ᵥ midpoint ℝ p1 p2 = -(p1 -ᵥ midpoint ℝ p1 p2), by { rw neg_vsub_eq_vsub_rev, simp },
by simp [angle, this, hp1p2, -zero_lt_one]
/-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B
then ∠CMA = π / 2. -/
lemma angle_left_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) :
∠ p3 (midpoint ℝ p1 p2) p1 = π / 2 :=
begin
let m : P := midpoint ℝ p1 p2,
have h1 : p3 -ᵥ p1 = (p3 -ᵥ m) - (p1 -ᵥ m) := (vsub_sub_vsub_cancel_right p3 p1 m).symm,
have h2 : p3 -ᵥ p2 = (p3 -ᵥ m) + (p1 -ᵥ m),
{ rw [left_vsub_midpoint, ← midpoint_vsub_right, vsub_add_vsub_cancel] },
rw [dist_eq_norm_vsub V p3 p1, dist_eq_norm_vsub V p3 p2, h1, h2] at h,
exact (norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (p3 -ᵥ m) (p1 -ᵥ m)).mp h.symm,
end
/-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B
then ∠CMB = π / 2. -/
lemma angle_right_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) :
∠ p3 (midpoint ℝ p1 p2) p2 = π / 2 :=
by rw [midpoint_comm p1 p2, angle_left_midpoint_eq_pi_div_two_of_dist_eq h.symm]
/-- The inner product of two vectors given with `weighted_vsub`, in
terms of the pairwise distances. -/
lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P)
(h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P)
(h₂ : ∑ i in s₂, w₂ i = 0) :
inner (s₁.weighted_vsub p₁ w₁) (s₂.weighted_vsub p₂ w₂) =
(-∑ i₁ in s₁, ∑ i₂ in s₂,
w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 :=
begin
rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply,
inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂],
simp_rw [vsub_sub_vsub_cancel_right],
rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂)
end
/-- The distance between two points given with `affine_combination`,
in terms of the pairwise distances between the points in that
combination. -/
lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P)
(h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) :
dist (s.affine_combination p w₁) (s.affine_combination p w₂) *
dist (s.affine_combination p w₁) (s.affine_combination p w₂) =
(-∑ i₁ in s, ∑ i₂ in s,
(w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 :=
begin
rw [dist_eq_norm_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂),
←inner_self_eq_norm_sq, finset.affine_combination_vsub],
have h : ∑ i in s, (w₁ - w₂) i = 0,
{ simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] },
exact inner_weighted_vsub p h p h
end
/-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same
applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal
to that between `p₁` and `p₂`. (In two dimensions, this says that the
diagonals of a kite are orthogonal.) -/
lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁)
(hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 :=
begin
have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0,
{ conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁,
skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ },
rw [←add_sub_comm, inner_sub_left],
conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂,
skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ },
rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁,
dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂,
simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add,
neg_add_eq_sub, hc₁, hc₂, sub_zero] },
simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h
end
/-- The squared distance between points on a line (expressed as a
multiple of a fixed vector added to a point) and another point,
expressed as a quadratic. -/
lemma dist_smul_vadd_sq (r : ℝ) (v : V) (p₁ p₂ : P) :
dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ =
⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ :=
begin
rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_sq, vadd_vsub_assoc,
real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right],
ring
end
/-- The condition for two points on a line to be equidistant from
another point. -/
lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) :
dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) :=
begin
conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_sq,
←sub_eq_zero, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂,
←real_inner_self_eq_norm_sq, sub_self] },
have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv,
have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 =
(2 * inner v (p₁ -ᵥ p₂)) * (2 * inner v (p₁ -ᵥ p₂)),
{ rw discrim, ring },
rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul,
←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc,
mul_div_mul_left, mul_div_assoc],
norm_num
end
open affine_subspace finite_dimensional
/-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at
most two points `p₁` `p₂` in a two-dimensional subspace containing those points
(two circles intersect in at most two points). -/
lemma eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two {s : affine_subspace ℝ P}
[finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P}
(hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ}
(hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁)
(hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂)
(hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ :=
begin
have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 :=
inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hp₂c₁.symm) (hp₁c₂.trans hp₂c₂.symm),
have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 :=
inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hpc₁.symm) (hp₁c₂.trans hpc₂.symm),
let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁],
have hb : linear_independent ℝ b,
{ refine linear_independent_of_ne_zero_of_inner_eq_zero _ _,
{ intro i,
fin_cases i; simp [b, hc.symm, hp.symm], },
{ intros i j hij,
fin_cases i; fin_cases j; try { exact false.elim (hij rfl) },
{ exact ho },
{ rw real_inner_comm, exact ho } } },
have hbs : submodule.span ℝ (set.range b) = s.direction,
{ refine eq_of_le_of_finrank_eq _ _,
{ rw [submodule.span_le, set.range_subset_iff],
intro i,
fin_cases i,
{ exact vsub_mem_direction hc₂s hc₁s },
{ exact vsub_mem_direction hp₂s hp₁s } },
{ rw [finrank_span_eq_card hb, fintype.card_fin, hd] } },
have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁),
{ intros v hv,
have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁},
{ have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial,
rw [←fintype.coe_image_univ, hu],
simp,
refl },
rw [←hbs, hr, submodule.mem_span_insert] at hv,
rcases hv with ⟨t₁, v', hv', hv⟩,
rw submodule.mem_span_singleton at hv',
rcases hv' with ⟨t₂, rfl⟩,
exact ⟨t₁, t₂, hv⟩ },
rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩,
simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero,
inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop,
rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt,
subst hpt,
have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] },
have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] },
rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂,
simp only [one_ne_zero, false_or] at hp₂,
rw hp₂.symm at hpc₁,
cases hpc₁; simp [hpc₁]
end
/-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at
most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at
most two points). -/
lemma eq_of_dist_eq_of_dist_eq_of_finrank_eq_two [finite_dimensional ℝ V] (hd : finrank ℝ V = 2)
{c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁)
(hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂)
(hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ :=
begin
have hd' : finrank ℝ (⊤ : affine_subspace ℝ P).direction = 2,
{ rw [direction_top, finrank_top],
exact hd },
exact eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two hd'
(mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _)
hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂
end
variables {V}
/-- The orthogonal projection of a point onto a nonempty affine
subspace, whose direction is complete, as an unbundled function. This
definition is only intended for use in setting up the bundled version
`orthogonal_projection` and should not be used once that is
defined. -/
def orthogonal_projection_fn (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction]
(p : P) : P :=
classical.some $ inter_eq_singleton_of_nonempty_of_is_compl
(nonempty_subtype.mp ‹_›)
(mk'_nonempty p s.directionᗮ)
begin
convert submodule.is_compl_orthogonal_of_is_complete
(complete_space_coe_iff_is_complete.mp ‹_›),
exact direction_mk' p s.directionᗮ
end
/-- The intersection of the subspace and the orthogonal subspace
through the given point is the `orthogonal_projection_fn` of that
point onto the subspace. This lemma is only intended for use in
setting up the bundled version and should not be used once that is
defined. -/
lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
(s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection_fn s p} :=
classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl
(nonempty_subtype.mp ‹_›)
(mk'_nonempty p s.directionᗮ)
begin
convert submodule.is_compl_orthogonal_of_is_complete
(complete_space_coe_iff_is_complete.mp ‹_›),
exact direction_mk' p s.directionᗮ
end
/-- The `orthogonal_projection_fn` lies in the given subspace. This
lemma is only intended for use in setting up the bundled version and
should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ s :=
begin
rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn],
exact set.inter_subset_left _ _
end
/-- The `orthogonal_projection_fn` lies in the orthogonal
subspace. This lemma is only intended for use in setting up the
bundled version and should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
orthogonal_projection_fn s p ∈ mk' p s.directionᗮ :=
begin
rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn],
exact set.inter_subset_right _ _
end
/-- Subtracting `p` from its `orthogonal_projection_fn` produces a
result in the orthogonal direction. This lemma is only intended for
use in setting up the bundled version and should not be used once that
is defined. -/
lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
orthogonal_projection_fn s p -ᵥ p ∈ s.directionᗮ :=
direction_mk' p s.directionᗮ ▸
vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (self_mem_mk' _ _)
/-- The orthogonal projection of a point onto a nonempty affine
subspace, whose direction is complete. The corresponding linear map
(mapping a vector to the difference between the projections of two
points whose difference is that vector) is the `orthogonal_projection`
for real inner product spaces, onto the direction of the affine
subspace being projected onto. -/
def orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] :
P →ᵃ[ℝ] s :=
{ to_fun := λ p, ⟨orthogonal_projection_fn s p, orthogonal_projection_fn_mem p⟩,
linear := orthogonal_projection s.direction,
map_vadd' := λ p v, begin
have hs : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ s :=
vadd_mem_of_mem_direction (orthogonal_projection s.direction v).2
(orthogonal_projection_fn_mem p),
have ho : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈
mk' (v +ᵥ p) s.directionᗮ,
{ rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk',
vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc],
refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal p) _,
rw submodule.mem_orthogonal',
intros w hw,
rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ w hw, neg_zero], },
have hm : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈
({orthogonal_projection_fn s (v +ᵥ p)} : set P),
{ rw ←inter_eq_singleton_orthogonal_projection_fn (v +ᵥ p),
exact set.mem_inter hs ho },
rw set.mem_singleton_iff at hm,
ext,
exact hm.symm
end }
@[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
orthogonal_projection_fn s p = orthogonal_projection s p :=
rfl
/-- The linear map corresponding to `orthogonal_projection`. -/
@[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] :
(orthogonal_projection s).linear = _root_.orthogonal_projection s.direction :=
rfl
/-- The intersection of the subspace and the orthogonal subspace
through the given point is the `orthogonal_projection` of that point
onto the subspace. -/
lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
(s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection s p} :=
begin
rw ←orthogonal_projection_fn_eq,
exact inter_eq_singleton_orthogonal_projection_fn p
end
/-- The `orthogonal_projection` lies in the given subspace. -/
lemma orthogonal_projection_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction]
(p : P) : ↑(orthogonal_projection s p) ∈ s :=
(orthogonal_projection s p).2
/-- The `orthogonal_projection` lies in the orthogonal subspace. -/
lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
↑(orthogonal_projection s p) ∈ mk' p s.directionᗮ :=
orthogonal_projection_fn_mem_orthogonal p
/-- Subtracting a point in the given subspace from the
`orthogonal_projection` produces a result in the direction of the
given subspace. -/
lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) :
↑(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction) ∈ s.direction :=
(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction).2
/-- Subtracting the `orthogonal_projection` from a point in the given
subspace produces a result in the direction of the given subspace. -/
lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) :
↑((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction) ∈ s.direction :=
((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction).2
/-- A point equals its orthogonal projection if and only if it lies in
the subspace. -/
lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} :
↑(orthogonal_projection s p) = p ↔ p ∈ s :=
begin
split,
{ exact λ h, h ▸ orthogonal_projection_mem p },
{ intro h,
have hp : p ∈ ((s : set P) ∩ mk' p s.directionᗮ) := ⟨h, self_mem_mk' p _⟩,
rw [inter_eq_singleton_orthogonal_projection p] at hp,
symmetry,
exact hp }
end
@[simp] lemma orthogonal_projection_mem_subspace_eq_self {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : s) :
orthogonal_projection s p = p :=
begin
ext,
rw orthogonal_projection_eq_self_iff,
exact p.2
end
/-- Orthogonal projection is idempotent. -/
@[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p :=
begin
ext,
rw orthogonal_projection_eq_self_iff,
exact orthogonal_projection_mem p,
end
lemma eq_orthogonal_projection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s]
[nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) :
(orthogonal_projection s p : P) = (orthogonal_projection s' p : P) :=
begin
change orthogonal_projection_fn s p = orthogonal_projection_fn s' p,
congr,
exact h
end
/-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/
lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} :
dist p (orthogonal_projection s p) = 0 ↔ p ∈ s :=
by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff]
/-- The distance between a point and its orthogonal projection is
nonzero if it does not lie in the subspace. -/
lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} (hp : p ∉ s) :
dist p (orthogonal_projection s p) ≠ 0 :=
mt dist_orthogonal_projection_eq_zero_iff.mp hp
/-- Subtracting `p` from its `orthogonal_projection` produces a result
in the orthogonal direction. -/
lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
(orthogonal_projection s p : P) -ᵥ p ∈ s.directionᗮ :=
orthogonal_projection_fn_vsub_mem_direction_orthogonal p
/-- Subtracting the `orthogonal_projection` from `p` produces a result
in the orthogonal direction. -/
lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
p -ᵥ orthogonal_projection s p ∈ s.directionᗮ :=
direction_mk' p s.directionᗮ ▸
vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p)
/-- Subtracting the `orthogonal_projection` from `p` produces a result in the kernel of the linear
part of the orthogonal projection. -/
lemma orthogonal_projection_vsub_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
_root_.orthogonal_projection s.direction (p -ᵥ orthogonal_projection s p) = 0 :=
begin
apply orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero,
intros c hc,
rw [← neg_vsub_eq_vsub_rev, inner_neg_right,
(orthogonal_projection_vsub_mem_direction_orthogonal s p c hc), neg_zero]
end
/-- Adding a vector to a point in the given subspace, then taking the
orthogonal projection, produces the original point if the vector was
in the orthogonal direction. -/
lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} (hp : p ∈ s) {v : V}
(hv : v ∈ s.directionᗮ) :
orthogonal_projection s (v +ᵥ p) = ⟨p, hp⟩ :=
begin
have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p),
rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h,
refine (eq_of_vsub_eq_zero _).symm,
ext,
refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h,
exact (_ : s.direction).2
end
/-- Adding a vector to a point in the given subspace, then taking the
orthogonal projection, produces the original point if the vector is a
multiple of the result of subtracting a point's orthogonal projection
from that point. -/
lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P}
[nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) :
orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = ⟨p1, hp⟩ :=
orthogonal_projection_vadd_eq_self hp
(submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _))
/-- The square of the distance from a point in `s` to `p2` equals the
sum of the squares of the distances of the two points to the
`orthogonal_projection`. -/
lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq
{s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P}
(p2 : P) (hp1 : p1 ∈ s) :
dist p1 p2 * dist p1 p2 =
dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) +
dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) :=
begin
rw [pseudo_metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _,
dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2,
norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero],
exact submodule.inner_right_of_mem_orthogonal
(vsub_orthogonal_projection_mem_direction p2 hp1)
(orthogonal_projection_vsub_mem_direction_orthogonal s p2),
end
/-- The square of the distance between two points constructed by
adding multiples of the same orthogonal vector to points in the same
subspace. -/
lemma dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P}
{p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V}
(hv : v ∈ s.directionᗮ) :
dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) =
dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) :=
calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2)
= ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ * ∥(p1 -ᵥ p2) + (r1 - r2) • v∥
: by { rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul],
abel }
... = ∥p1 -ᵥ p2∥ * ∥p1 -ᵥ p2∥ + ∥(r1 - r2) • v∥ * ∥(r1 - r2) • v∥
: norm_add_sq_eq_norm_sq_add_norm_sq_real
(submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2)
(submodule.smul_mem _ _ hv))
... = ∥(p1 -ᵥ p2 : V)∥ * ∥(p1 -ᵥ p2 : V)∥ + |r1 - r2| * |r1 - r2| * ∥v∥ * ∥v∥
: by { rw [norm_smul, real.norm_eq_abs], ring }
... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥)
: by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] }
/-- Reflection in an affine subspace, which is expected to be nonempty
and complete. The word "reflection" is sometimes understood to mean
specifically reflection in a codimension-one subspace, and sometimes
more generally to cover operations such as reflection in a point. The
definition here, of reflection in an affine subspace, is a more
general sense of the word that includes both those common cases. -/
def reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] :
P ≃ᵃⁱ[ℝ] P :=
affine_isometry_equiv.mk'
(λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p)
(_root_.reflection s.direction)
↑(classical.arbitrary s)
begin
intros p,
let v := p -ᵥ ↑(classical.arbitrary s),
let a : V := _root_.orthogonal_projection s.direction v,
let b : P := ↑(classical.arbitrary s),
have key : a +ᵥ b -ᵥ (v +ᵥ b) +ᵥ (a +ᵥ b) = a + a - v +ᵥ (b -ᵥ b +ᵥ b),
{ rw [← add_vadd, vsub_vadd_eq_vsub_sub, vsub_vadd, vadd_vsub],
congr' 1,
abel },
have : p = v +ᵥ ↑(classical.arbitrary s) := (vsub_vadd p ↑(classical.arbitrary s)).symm,
simpa only [coe_vadd, reflection_apply, affine_map.map_vadd, orthogonal_projection_linear,
orthogonal_projection_mem_subspace_eq_self, vadd_vsub, continuous_linear_map.coe_coe,
continuous_linear_equiv.coe_coe, this] using key,
end
/-- The result of reflecting. -/
lemma reflection_apply (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) :
reflection s p = (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p :=
rfl
lemma eq_reflection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s]
[nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) :
(reflection s p : P) = (reflection s' p : P) :=
by unfreezingI { subst h }
/-- Reflecting twice in the same subspace. -/
@[simp] lemma reflection_reflection (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
reflection s (reflection s p) = p :=
begin
have : ∀ a : s, ∀ b : V, (_root_.orthogonal_projection s.direction) b = 0
→ reflection s (reflection s (b +ᵥ a)) = b +ᵥ a,
{ intros a b h,
have : (a:P) -ᵥ (b +ᵥ a) = - b,
{ rw [vsub_vadd_eq_vsub_sub, vsub_self, zero_sub] },
simp [reflection, h, this] },
rw ← vsub_vadd p (orthogonal_projection s p),
exact this (orthogonal_projection s p) _ (orthogonal_projection_vsub_orthogonal_projection s p),
end
/-- Reflection is its own inverse. -/
@[simp] lemma reflection_symm (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] :
(reflection s).symm = reflection s :=
by { ext, rw ← (reflection s).injective.eq_iff, simp }
/-- Reflection is involutive. -/
lemma reflection_involutive (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] :
function.involutive (reflection s) :=
reflection_reflection s
/-- A point is its own reflection if and only if it is in the
subspace. -/
lemma reflection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction]
(p : P) : reflection s p = p ↔ p ∈ s :=
begin
rw [←orthogonal_projection_eq_self_iff, reflection_apply],
split,
{ intro h,
rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc,
←two_smul ℝ (↑(orthogonal_projection s p) -ᵥ p), smul_eq_zero] at h,
norm_num at h,
exact h },
{ intro h,
simp [h] }
end
/-- Reflecting a point in two subspaces produces the same result if
and only if the point has the same orthogonal projection in each of
those subspaces. -/
lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P)
[nonempty s₁] [nonempty s₂] [complete_space s₁.direction] [complete_space s₂.direction] (p : P) :
reflection s₁ p = reflection s₂ p ↔
(orthogonal_projection s₁ p : P) = orthogonal_projection s₂ p :=
begin
rw [reflection_apply, reflection_apply],
split,
{ intro h,
rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm,
add_sub_assoc, vsub_sub_vsub_cancel_right,
←two_smul ℝ ((orthogonal_projection s₁ p : P) -ᵥ orthogonal_projection s₂ p),
smul_eq_zero] at h,
norm_num at h,
exact h },
{ intro h,
rw h }
end
/-- The distance between `p₁` and the reflection of `p₂` equals that
between the reflection of `p₁` and `p₂`. -/
lemma dist_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction]
(p₁ p₂ : P) :
dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ :=
begin
conv_lhs { rw ←reflection_reflection s p₁ },
exact (reflection s).dist_map _ _
end
/-- A point in the subspace is equidistant from another point and its
reflection. -/
lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction]
{p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) :
dist p₁ (reflection s p₂) = dist p₁ p₂ :=
begin
rw ←reflection_eq_self_iff p₁ at hp₁,
convert (reflection s).dist_map p₁ p₂,
rw hp₁
end
/-- The reflection of a point in a subspace is contained in any larger
subspace containing both the point and the subspace reflected in. -/
lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} [nonempty s₁]
[complete_space s₁.direction] (hle : s₁ ≤ s₂) {p : P}
(hp : p ∈ s₂) : reflection s₁ p ∈ s₂ :=
begin
rw [reflection_apply],
have ho : ↑(orthogonal_projection s₁ p) ∈ s₂ := hle (orthogonal_projection_mem p),
exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho
end
/-- Reflecting an orthogonal vector plus a point in the subspace
produces the negation of that vector plus the point. -/
lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} (hp : p ∈ s) {v : V}
(hv : v ∈ s.directionᗮ) : reflection s (v +ᵥ p) = -v +ᵥ p :=
begin
rw [reflection_apply, orthogonal_projection_vadd_eq_self hp hv, vsub_vadd_eq_vsub_sub],
simp
end
/-- Reflecting a vector plus a point in the subspace produces the
negation of that vector plus the point if the vector is a multiple of
the result of subtracting a point's orthogonal projection from that
point. -/
lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) :
reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) =
-(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ :=
reflection_orthogonal_vadd hp₁
(submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _))
omit V
/-- A set of points is cospherical if they are equidistant from some
point. In two dimensions, this is the same thing as being
concyclic. -/
def cospherical (ps : set P) : Prop :=
∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius
/-- The definition of `cospherical`. -/
lemma cospherical_def (ps : set P) :
cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius :=
iff.rfl
/-- A subset of a cospherical set is cospherical. -/
lemma cospherical_subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) :
cospherical ps₁ :=
begin
rcases hc with ⟨c, r, hcr⟩,
exact ⟨c, r, λ p hp, hcr p (hs hp)⟩
end
include V
/-- The empty set is cospherical. -/
lemma cospherical_empty : cospherical (∅ : set P) :=
begin
use add_torsor.nonempty.some,
simp,
end
omit V
/-- A single point is cospherical. -/
lemma cospherical_singleton (p : P) : cospherical ({p} : set P) :=
begin
use p,
simp
end
include V
/-- Two points are cospherical. -/
lemma cospherical_insert_singleton (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) :=
begin
use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)],
intro p,
rw [set.mem_insert_iff, set.mem_singleton_iff],
rintro ⟨_|_⟩,
{ rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul,
dist_eq_norm_vsub V p₂],
simp },
{ rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂],
conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) },
rw [←sub_smul, norm_smul],
norm_num }
end
/-- Any three points in a cospherical set are affinely independent. -/
lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P}
(hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_independent ℝ p :=
begin
rw affine_independent_iff_not_collinear,
intro hc,
rw collinear_iff_of_mem ℝ (set.mem_range_self (0 : fin 3)) at hc,
rcases hc with ⟨v, hv⟩,
rw set.forall_range_iff at hv,
have hv0 : v ≠ 0,
{ intro h,
have he : p 1 = p 0, by simpa [h] using hv 1,
exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) },
rcases hs with ⟨c, r, hs⟩,
have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps),
choose f hf using hv,
have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r,
{ intro i,
rw ←hf,
exact hs' i },
have hf0 : f 0 = 0,
{ have hf0' := hf 0,
rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0',
simpa [hv0] using hf0' },
have hfi : function.injective f,
{ intros i j h,
have hi := hf i,
rw [h, ←hf j] at hi,
exact hpi hi },
simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd,
have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2,
have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫,
{ intros i hi,
have hsdi := hsd i,
simpa [hfn0, hi] using hsdi },
have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] },
exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12)
end
end euclidean_geometry
|
8329a2591a59c72567134a7ebd8da44f4d6ef36b | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/omega/int/main.lean | 2d93acb268c4f5f3ab3922ca5ca6f799fc60ba89 | [
"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 | 6,301 | lean | /- Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
Main procedure for linear integer arithmetic. -/
import tactic.omega.prove_unsats
import tactic.omega.int.dnf
open tactic
namespace omega
namespace int
open_locale omega.int
run_cmd mk_simp_attr `sugar
attribute [sugar]
ne not_le not_lt
int.lt_iff_add_one_le
or_false false_or
and_true true_and
ge gt mul_add add_mul
one_mul mul_one
mul_comm sub_eq_add_neg
classical.imp_iff_not_or
classical.iff_iff_not_or_and_or_not
meta def desugar := `[try {simp only with sugar}]
lemma univ_close_of_unsat_clausify (m : nat) (p : preform) :
clauses.unsat (dnf (¬* p)) → univ_close p (λ x, 0) m | h1 :=
begin
apply univ_close_of_valid,
apply valid_of_unsat_not,
apply unsat_of_clauses_unsat,
exact h1
end
/-- Given a (p : preform), return the expr of a (t : univ_close m p) -/
meta def prove_univ_close (m : nat) (p : preform) : tactic expr :=
do x ← prove_unsats (dnf (¬*p)),
return `(univ_close_of_unsat_clausify %%`(m) %%`(p) %%x)
/-- Reification to imtermediate shadow syntax that retains exprs -/
meta def to_exprterm : expr → tactic exprterm
| `(- %%x) := --return (exprterm.exp (-1 : int) x)
( do z ← eval_expr' int x,
return (exprterm.cst (-z : int)) ) <|>
( return $ exprterm.exp (-1 : int) x )
| `(%%mx * %%zx) :=
do z ← eval_expr' int zx,
return (exprterm.exp z mx)
| `(%%t1x + %%t2x) :=
do t1 ← to_exprterm t1x,
t2 ← to_exprterm t2x,
return (exprterm.add t1 t2)
| x :=
( do z ← eval_expr' int x,
return (exprterm.cst z) ) <|>
( return $ exprterm.exp 1 x )
/-- Reification to imtermediate shadow syntax that retains exprs -/
meta def to_exprform : expr → tactic exprform
| `(%%tx1 = %%tx2) :=
do t1 ← to_exprterm tx1,
t2 ← to_exprterm tx2,
return (exprform.eq t1 t2)
| `(%%tx1 ≤ %%tx2) :=
do t1 ← to_exprterm tx1,
t2 ← to_exprterm tx2,
return (exprform.le t1 t2)
| `(¬ %%px) := do p ← to_exprform px, return (exprform.not p)
| `(%%px ∨ %%qx) :=
do p ← to_exprform px,
q ← to_exprform qx,
return (exprform.or p q)
| `(%%px ∧ %%qx) :=
do p ← to_exprform px,
q ← to_exprform qx,
return (exprform.and p q)
| `(_ → %%px) := to_exprform px
| x := trace "Cannot reify expr : " >> trace x >> failed
/-- List of all unreified exprs -/
meta def exprterm.exprs : exprterm → list expr
| (exprterm.cst _) := []
| (exprterm.exp _ x) := [x]
| (exprterm.add t s) := list.union t.exprs s.exprs
/-- List of all unreified exprs -/
meta def exprform.exprs : exprform → list expr
| (exprform.eq t s) := list.union t.exprs s.exprs
| (exprform.le t s) := list.union t.exprs s.exprs
| (exprform.not p) := p.exprs
| (exprform.or p q) := list.union p.exprs q.exprs
| (exprform.and p q) := list.union p.exprs q.exprs
/-- Reification to an intermediate shadow syntax which eliminates exprs,
but still includes non-canonical terms -/
meta def exprterm.to_preterm (xs : list expr) : exprterm → tactic preterm
| (exprterm.cst k) := return & k
| (exprterm.exp k x) :=
let m := xs.index_of x in
if m < xs.length
then return (k ** m)
else failed
| (exprterm.add xa xb) :=
do a ← xa.to_preterm,
b ← xb.to_preterm,
return (a +* b)
/-- Reification to an intermediate shadow syntax which eliminates exprs,
but still includes non-canonical terms -/
meta def exprform.to_preform (xs : list expr) : exprform → tactic preform
| (exprform.eq xa xb) :=
do a ← xa.to_preterm xs,
b ← xb.to_preterm xs,
return (a =* b)
| (exprform.le xa xb) :=
do a ← xa.to_preterm xs,
b ← xb.to_preterm xs,
return (a ≤* b)
| (exprform.not xp) :=
do p ← xp.to_preform,
return ¬* p
| (exprform.or xp xq) :=
do p ← xp.to_preform,
q ← xq.to_preform,
return (p ∨* q)
| (exprform.and xp xq) :=
do p ← xp.to_preform,
q ← xq.to_preform,
return (p ∧* q)
/-- Reification to an intermediate shadow syntax which eliminates exprs,
but still includes non-canonical terms. -/
meta def to_preform (x : expr) : tactic (preform × nat) :=
do xf ← to_exprform x,
let xs := xf.exprs,
f ← xf.to_preform xs,
return (f, xs.length)
/-- Return expr of proof of current LIA goal -/
meta def prove : tactic expr :=
do (p,m) ← target >>= to_preform,
trace_if_enabled `omega p,
prove_univ_close m p
/-- Succeed iff argument is the expr of ℤ -/
meta def eq_int (x : expr) : tactic unit :=
if x = `(int) then skip else failed
/-- Check whether argument is expr of a well-formed formula of LIA-/
meta def wff : expr → tactic unit
| `(¬ %%px) := wff px
| `(%%px ∨ %%qx) := wff px >> wff qx
| `(%%px ∧ %%qx) := wff px >> wff qx
| `(%%px ↔ %%qx) := wff px >> wff qx
| `(%%(expr.pi _ _ px qx)) :=
monad.cond
(if expr.has_var px then return tt else is_prop px)
(wff px >> wff qx)
(eq_int px >> wff qx)
| `(@has_lt.lt %%dx %%h _ _) := eq_int dx
| `(@has_le.le %%dx %%h _ _) := eq_int dx
| `(@eq %%dx _ _) := eq_int dx
| `(@ge %%dx %%h _ _) := eq_int dx
| `(@gt %%dx %%h _ _) := eq_int dx
| `(@ne %%dx _ _) := eq_int dx
| `(true) := skip
| `(false) := skip
| _ := failed
/-- Succeed iff argument is expr of term whose type is wff -/
meta def wfx (x : expr) : tactic unit :=
infer_type x >>= wff
/-- Intro all universal quantifiers over ℤ -/
meta def intro_ints_core : tactic unit :=
do x ← target,
match x with
| (expr.pi _ _ `(int) _) := intro_fresh >> intro_ints_core
| _ := skip
end
meta def intro_ints : tactic unit :=
do (expr.pi _ _ `(int) _) ← target,
intro_ints_core
/-- If the goal has universal quantifiers over integers, introduce all of them.
Otherwise, revert all hypotheses that are formulas of linear integer arithmetic. -/
meta def preprocess : tactic unit :=
intro_ints <|> (revert_cond_all wfx >> desugar)
end int
end omega
open omega.int
/-- The core omega tactic for integers. -/
meta def omega_int (is_manual : bool) : tactic unit :=
desugar ; (if is_manual then skip else preprocess) ; prove >>= apply >> skip
|
c8bcdc51f7a122996b51cb4375569b6b34f4eeff | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/finset/default_auto.lean | 5eb26c77867326d1b230648378ad27f1d190b5d9 | [] | 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 | 430 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.finset.basic
import Mathlib.data.finset.fold
import Mathlib.data.finset.intervals
import Mathlib.data.finset.lattice
import Mathlib.data.finset.nat_antidiagonal
import Mathlib.data.finset.pi
import Mathlib.data.finset.powerset
import Mathlib.data.finset.sort
import Mathlib.data.finset.preimage
import Mathlib.PostPort
namespace Mathlib
end Mathlib |
8b2d86061039b4a205a4a27ac036588a1fd96344 | e21db629d2e37a833531fdcb0b37ce4d71825408 | /src/use_cases/assign_mcl/defs.lean | 9d1b43e1d1739bebea92de854a98e99e1eb18c3d | [] | no_license | fischerman/GPU-transformation-verifier | 614a28cb4606a05a0eb27e8d4eab999f4f5ea60c | 75a5016f05382738ff93ce5859c4cfa47ccb63c1 | refs/heads/master | 1,586,985,789,300 | 1,579,290,514,000 | 1,579,290,514,000 | 165,031,073 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,314 | lean | import mcl.defs
import mcl.rhl
--import parlang
import syncablep
open mcl
open mcl.mclk
open mcl.rhl
open parlang
open parlang.state
open parlang.thread_state
namespace assign_mcl
def sigc : signature_core
| "tid" := { scope := scope.tlocal, type := ⟨1, type.int⟩ }
| _ := { scope := scope.shared, type := ⟨1, type.int⟩ }
def sig : signature := ⟨sigc, ⟨rfl, rfl, rfl⟩⟩
lemma a_is_shared : is_shared (sig.val "a") := by apply eq.refl
lemma tid_is_tlocal : is_tlocal (sig.val "tid") := by apply eq.refl
-- TODO generate those proofs directly from signature
-- make type classes out of those
-- make name explicit in state.update
def read_tid := (@expression.tlocal_var sig _ _ "tid" (λ_, 0) rfl rfl rfl)
instance : has_one (expression sig (type_of (sig.val "b"))) := begin
have : type_of (sig.val "b") = type.int := by apply eq.refl,
rw this,
apply_instance,
end
def p₁ : mclp sig := mclp.intro (λ m, 100) (
mclk.shared_assign "a" v[read_tid] rfl rfl read_tid ;;
mclk.shared_assign "b" v[read_tid] rfl rfl (read_tid + (expression.literal_int 1 rfl))
)
def p₂ : mclp sig := mclp.intro (λ m, 100) (
mclk.shared_assign "b" v[read_tid] rfl rfl (read_tid + (expression.literal_int 1 rfl)) ;;
mclk.shared_assign "a" v[read_tid] rfl rfl read_tid
)
end assign_mcl |
51aeab54968ed32842ee9c971095fcc8e8027808 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/number_theory/dioph.lean | dd5945c511e24ba62bf371487d0b0e88f3e24544 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 25,639 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fin.fin2
import data.pfun
import data.vector3
import number_theory.pell
/-!
# Diophantine functions and Matiyasevic's theorem
Hilbert's tenth problem asked whether there exists an algorithm which for a given integer polynomial
determines whether this polynomial has integer solutions. It was answered in the negative in 1970,
the final step being completed by Matiyasevic who showed that the power function is Diophantine.
Here a function is called Diophantine if its graph is Diophantine as a set. A subset `S ⊆ ℕ ^ α` in
turn is called Diophantine if there exists an integer polynomial on `α ⊕ β` such that `v ∈ S` iff
there exists `t : ℕ^β` with `p (v, t) = 0`.
## Main definitions
* `is_poly`: a predicate stating that a function is a multivariate integer polynomial.
* `poly`: the type of multivariate integer polynomial functions.
* `dioph`: a predicate stating that a set is Diophantine, i.e. a set `S ⊆ ℕ^α` is
Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there
exists `t : ℕ^β` with `p (v, t) = 0`.
* `dioph_fn`: a predicate on a function stating that it is Diophantine in the sense that its graph
is Diophantine as a set.
## Main statements
* `pell_dioph` states that solutions to Pell's equation form a Diophantine set.
* `pow_dioph` states that the power function is Diophantine, a version of Matiyasevic's theorem.
## References
* [M. Carneiro, _A Lean formalization of Matiyasevic's theorem_][carneiro2018matiyasevic]
* [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916]
## Tags
Matiyasevic's theorem, Hilbert's tenth problem
## TODO
* Finish the solution of Hilbert's tenth problem.
* Connect `poly` to `mv_polynomial`
-/
open fin2 function nat sum
local infixr ` ::ₒ `:67 := option.cons
local infixr ` ⊗ `:65 := sum.elim
universe u
/-!
### Multivariate integer polynomials
Note that this duplicates `mv_polynomial`.
-/
section polynomials
variables {α β γ : Type*}
/-- A predicate asserting that a function is a multivariate integer polynomial.
(We are being a bit lazy here by allowing many representations for multiplication,
rather than only allowing monomials and addition, but the definition is equivalent
and this is easier to use.) -/
inductive is_poly : ((α → ℕ) → ℤ) → Prop
| proj : ∀ i, is_poly (λ x : α → ℕ, x i)
| const : Π (n : ℤ), is_poly (λ x : α → ℕ, n)
| sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λ x, f x - g x)
| mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λ x, f x * g x)
lemma is_poly.neg {f : (α → ℕ) → ℤ} : is_poly f → is_poly (-f) :=
by { rw ←zero_sub, exact (is_poly.const 0).sub }
lemma is_poly.add {f g : (α → ℕ) → ℤ} (hf : is_poly f) (hg : is_poly g) : is_poly (f + g) :=
by { rw ←sub_neg_eq_add, exact hf.sub hg.neg }
/-- The type of multivariate integer polynomials -/
def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f}
namespace poly
section
instance fun_like : fun_like (poly α) (α → ℕ) (λ _, ℤ) := ⟨subtype.val, subtype.val_injective⟩
/-- Helper instance for when there are too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (poly α) (λ _, (α → ℕ) → ℤ) := fun_like.has_coe_to_fun
/-- The underlying function of a `poly` is a polynomial -/
protected lemma is_poly (f : poly α) : is_poly f := f.2
/-- Extensionality for `poly α` -/
@[ext] lemma ext {f g : poly α} : (∀ x, f x = g x) → f = g := fun_like.ext _ _
/-- The `i`th projection function, `x_i`. -/
def proj (i) : poly α := ⟨_, is_poly.proj i⟩
@[simp] lemma proj_apply (i : α) (x) : proj i x = x i := rfl
/-- The constant function with value `n : ℤ`. -/
def const (n) : poly α := ⟨_, is_poly.const n⟩
@[simp] lemma const_apply (n) (x : α → ℕ) : const n x = n := rfl
instance : has_zero (poly α) := ⟨const 0⟩
instance : has_one (poly α) := ⟨const 1⟩
instance : has_neg (poly α) := ⟨λ f, ⟨-f, f.2.neg⟩⟩
instance : has_add (poly α) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩
instance : has_sub (poly α) := ⟨λ f g, ⟨f - g, f.2.sub g.2⟩⟩
instance : has_mul (poly α) := ⟨λ f g, ⟨f * g, f.2.mul g.2⟩⟩
@[simp] lemma coe_zero : ⇑(0 : poly α) = const 0 := rfl
@[simp] lemma coe_one : ⇑(1 : poly α) = const 1 := rfl
@[simp] lemma coe_neg (f : poly α) : ⇑(-f) = -f := rfl
@[simp] lemma coe_add (f g : poly α) : ⇑(f + g) = f + g := rfl
@[simp] lemma coe_sub (f g : poly α) : ⇑(f - g) = f - g := rfl
@[simp] lemma coe_mul (f g : poly α) : ⇑(f * g) = f * g := rfl
@[simp] lemma zero_apply (x) : (0 : poly α) x = 0 := rfl
@[simp] lemma one_apply (x) : (1 : poly α) x = 1 := rfl
@[simp] lemma neg_apply (f : poly α) (x) : (-f) x = -f x := rfl
@[simp] lemma add_apply (f g : poly α) (x : α → ℕ) : (f + g) x = f x + g x := rfl
@[simp] lemma sub_apply (f g : poly α) (x : α → ℕ) : (f - g) x = f x - g x := rfl
@[simp] lemma mul_apply (f g : poly α) (x : α → ℕ) : (f * g) x = f x * g x := rfl
instance (α : Type*) : inhabited (poly α) := ⟨0⟩
instance : comm_ring (poly α) := by refine_struct
{ add := ((+) : poly α → poly α → poly α),
zero := 0,
neg := (has_neg.neg),
mul := (*),
one := 1,
sub := (has_sub.sub),
npow := @npow_rec _ ⟨(1 : poly α)⟩ ⟨(*)⟩,
nsmul := @nsmul_rec _ ⟨(0 : poly α)⟩ ⟨(+)⟩,
zsmul := @zsmul_rec _ ⟨(0 : poly α)⟩ ⟨(+)⟩ ⟨has_neg.neg⟩ };
intros; try { refl }; refine ext (λ _, _);
simp [sub_eq_add_neg, mul_add, mul_left_comm, mul_comm, add_comm, add_assoc]
lemma induction {C : poly α → Prop}
(H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n))
(H3 : ∀f g, C f → C g → C (f - g))
(H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f :=
begin
cases f with f pf,
induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg,
apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg
end
/-- The sum of squares of a list of polynomials. This is relevant for
Diophantine equations, because it means that a list of equations
can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is
equivalent to `x^2 + y^2 + z^2 = 0`. -/
def sumsq : list (poly α) → poly α
| [] := 0
| (p::ps) := p*p + sumsq ps
lemma sumsq_nonneg (x : α → ℕ) : ∀ l, 0 ≤ sumsq l x
| [] := le_refl 0
| (p::ps) := by rw sumsq; simp [-add_comm];
exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps)
lemma sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ l.all₂ (λ a : poly α, a x = 0)
| [] := eq_self_iff_true _
| (p::ps) := by rw [list.all₂_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact
⟨λ (h : p x * p x + sumsq ps x = 0),
have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm
(by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t)
(mul_self_nonneg _),
⟨this, by simp [this] at h; exact h⟩,
λ ⟨h1, h2⟩, by rw [h1, h2]; refl⟩
end
/-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/
def map {α β} (f : α → β) (g : poly α) : poly β :=
⟨λ v, g $ v ∘ f, g.induction
(λ i, by simp; apply is_poly.proj)
(λ n, by simp; apply is_poly.const)
(λ f g pf pg, by simp; apply is_poly.sub pf pg)
(λ f g pf pg, by simp; apply is_poly.mul pf pg)⟩
@[simp] lemma map_apply {α β} (f : α → β) (g : poly α) (v) : map f g v = g (v ∘ f) := rfl
end poly
end polynomials
/-! ### Diophantine sets -/
/-- A set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on
`α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/
def dioph {α : Type u} (S : set (α → ℕ)) : Prop :=
∃ {β : Type u} (p : poly (α ⊕ β)), ∀ v, S v ↔ ∃ t, p (v ⊗ t) = 0
namespace dioph
section
variables {α β γ : Type u} {S S' : set (α → ℕ)}
lemma ext (d : dioph S) (H : ∀ v, v ∈ S ↔ v ∈ S') : dioph S' := by rwa ←set.ext H
lemma of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ v, S v ↔ p v = 0) : dioph S :=
⟨pempty, p.map inl, λ v, (h v).trans ⟨λ h, ⟨pempty.rec _, h⟩, λ ⟨t, ht⟩, ht⟩⟩
lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x)
(p : poly (α ⊕ β)) (v : α → ℕ) :
(∃ t, p (v ⊗ t) = 0) ↔ ∃ t, p.map (inl ⊗ inr ∘ f) (v ⊗ t) = 0 :=
begin
dsimp, refine ⟨λ t, _, λ t, _⟩; cases t with t ht,
{ have : (v ⊗ (0 ::ₒ t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t :=
funext (λ s, by cases s with a b; dsimp [(∘)]; try {rw inv}; refl),
exact ⟨(0 ::ₒ t) ∘ g, by rwa this⟩ },
{ have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) :=
funext (λ s, by cases s with a b; refl),
exact ⟨t ∘ f, by rwa this⟩ }
end
lemma inject_dummies (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β))
(h : ∀ v, S v ↔ ∃ t, p (v ⊗ t) = 0) :
∃ q : poly (α ⊕ γ), ∀ v, S v ↔ ∃ t, q (v ⊗ t) = 0 :=
⟨p.map (inl ⊗ (inr ∘ f)), λ v, (h v).trans $ inject_dummies_lem f g inv _ _⟩
variables (β)
lemma reindex_dioph (f : α → β) : Π (d : dioph S), dioph {v | v ∘ f ∈ S}
| ⟨γ, p, pe⟩ := ⟨γ, p.map ((inl ∘ f) ⊗ inr), λ v, (pe _).trans $ exists_congr $ λ t,
suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this],
funext $ λ s, by cases s with a b; refl⟩
variables {β}
lemma dioph_list.all₂ (l : list (set $ α → ℕ)) (d : l.all₂ dioph) :
dioph {v | l.all₂ (λ S : set (α → ℕ), v ∈ S)} :=
suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v,
list.all₂ (λ S : set _, S v) l ↔ ∃ t, list.all₂ (λ p : poly (α ⊕ β), p (v ⊗ t) = 0) pl,
from let ⟨β, pl, h⟩ := this
in ⟨β, poly.sumsq pl, λ v, (h v).trans $ exists_congr $ λ t, (poly.sumsq_eq_zero _ _).symm⟩,
begin
induction l with S l IH,
exact ⟨ulift empty, [], λ v, by simp; exact ⟨λ ⟨t⟩, empty.rec _ t, trivial⟩⟩,
simp at d,
exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in
⟨β ⊕ γ, p.map (inl ⊗ inr ∘ inl) :: pl.map (λ q, q.map (inl ⊗ (inr ∘ inr))), λ v,
by simp; exact iff.trans (and_congr (pe v) (ple v))
⟨λ ⟨⟨m, hm⟩, ⟨n, hn⟩⟩,
⟨m ⊗ n, by rw [
show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m,
from funext $ λ s, by cases s with a b; refl]; exact hm,
by { refine list.all₂.imp (λ q hq, _) hn, dsimp [(∘)],
rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n,
from funext $ λ s, by cases s with a b; refl]; exact hq }⟩,
λ ⟨t, hl, hr⟩,
⟨⟨t ∘ inl, by rwa [
show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl,
from funext $ λ s, by cases s with a b; refl] at hl⟩,
⟨t ∘ inr, by
{ refine list.all₂.imp (λ q hq, _) hr, dsimp [(∘)] at hq,
rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr,
from funext $ λ s, by cases s with a b; refl] at hq }⟩⟩⟩⟩
end
lemma inter (d : dioph S) (d' : dioph S') : dioph (S ∩ S') := dioph_list.all₂ [S, S'] ⟨d, d'⟩
lemma union : ∀ (d : dioph S) (d' : dioph S'), dioph (S ∪ S')
| ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.map (inl ⊗ inr ∘ inl) * q.map (inl ⊗ inr ∘ inr), λ v,
begin
refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _))
(exists_or_distrib.symm.trans (exists_congr $ λ t,
(@mul_eq_zero _ _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl)))
(q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)),
exact inject_dummies_lem _ (some ⊗ (λ _, none)) (λ x, rfl) _ _,
exact inject_dummies_lem _ ((λ _, none) ⊗ some) (λ x, rfl) _ _,
end⟩
/-- A partial function is Diophantine if its graph is Diophantine. -/
def dioph_pfun (f : (α → ℕ) →. ℕ) : Prop := dioph {v : option α → ℕ | f.graph (v ∘ some, v none)}
/-- A function is Diophantine if its graph is Diophantine. -/
def dioph_fn (f : (α → ℕ) → ℕ) : Prop := dioph {v : option α → ℕ | f (v ∘ some) = v none}
lemma reindex_dioph_fn {f : (α → ℕ) → ℕ} (g : α → β) (d : dioph_fn f) : dioph_fn (λ v, f (v ∘ g)) :=
by convert reindex_dioph (option β) (option.map g) d
lemma ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph {v | ∃ x, v ⊗ x ∈ S}
| ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.map ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λ v,
⟨λ ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [
show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t,
from funext $ λ s, by cases s with a b; try {cases a}; refl]; exact ht⟩,
λ ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [
show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr,
from funext $ λ s, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩
lemma ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph {v | ∃ x, x ::ₒ v ∈ S}
| ⟨β, p, pe⟩ := ⟨option β, p.map (inr none ::ₒ inl ⊗ inr ∘ some), λ v,
⟨λ ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ::ₒ t, by simp; rw [
show (v ⊗ x ::ₒ t) ∘ (inr none ::ₒ inl ⊗ inr ∘ some) = x ::ₒ v ⊗ t,
from funext $ λ s, by cases s with a b; try {cases a}; refl]; exact ht⟩,
λ ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [
show (v ⊗ t) ∘ (inr none ::ₒ inl ⊗ inr ∘ some) = t none ::ₒ v ⊗ t ∘ some,
from funext $ λ s, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩
theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom :=
cast (congr_arg dioph $ set.ext $ λ v, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d)
theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f :=
by refine congr_arg dioph (set.ext $ λ v, _); exact pfun.lift_graph.symm
lemma abs_poly_dioph (p : poly α) : dioph_fn (λ v, (p v).nat_abs) :=
of_no_dummies _ ((p.map some - poly.proj none) * (p.map some + poly.proj none)) $ λ v,
by { dsimp, exact int.eq_nat_abs_iff_mul_eq_zero }
theorem proj_dioph (i : α) : dioph_fn (λ v, v i) :=
abs_poly_dioph (poly.proj i)
theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) :
dioph {v : α → ℕ | ∃ h : f.dom v, f.fn v h ::ₒ v ∈ S} :=
ext (ex1_dioph (d.inter df)) $ λ v,
⟨λ ⟨x, hS, (h: Exists _)⟩, by
rw [show (x ::ₒ v) ∘ some = v, from funext $ λ s, rfl] at h;
cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS,
λ ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _,
by rw [show (f.fn v x ::ₒ v) ∘ some = v, from funext $ λ s, rfl]; exact ⟨x, rfl⟩⟩⟩
theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) :
dioph {v | f v ::ₒ v ∈ S} :=
ext (dioph_pfun_comp1 d $ cast (dioph_fn_iff_pfun f) df) $ λ v,
⟨λ ⟨_, h⟩, h, λ h, ⟨trivial, h⟩⟩
end
section
variables {α β : Type} {n : ℕ}
open vector3
open_locale vector3
local attribute [reducible] vector3
lemma dioph_fn_vec_comp1 {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : vector3 ℕ n → ℕ}
(df : dioph_fn f) :
dioph {v : vector3 ℕ n | f v :: v ∈ S} :=
ext (dioph_fn_comp1 (reindex_dioph _ (none :: some) d) df) $ λ v,
by { dsimp, congr', ext x, cases x; refl }
theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) :
dioph {v : fin2 n → ℕ | ∃ x, x :: v ∈ S} :=
ext (ex1_dioph $ reindex_dioph _ (none :: some) d) $ λ v, exists_congr $ λ x, by { dsimp,
rw [show (option.cons x v) ∘ (cons none some) = x :: v,
from funext $ λ s, by cases s with a b; refl] }
lemma dioph_fn_vec (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph {v | f (v ∘ fs) = v fz} :=
⟨reindex_dioph _ (fz ::ₒ fs), reindex_dioph _ (none :: some)⟩
lemma dioph_pfun_vec (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph {v | f.graph (v ∘ fs, v fz)} :=
⟨reindex_dioph _ (fz ::ₒ fs), reindex_dioph _ (none :: some)⟩
lemma dioph_fn_compn : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S)
{f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f),
dioph {v : α → ℕ | v ⊗ (λ i, f i v) ∈ S}
| 0 S d f := λ df, ext (reindex_dioph _ (id ⊗ fin2.elim0) d) $ λ v,
by { dsimp, congr', ext x, obtain (_ | _ | _) := x, refl }
| (succ n) S d f := f.cons_elim $ λ f fl, by simp; exact λ df dfl,
have dioph {v |v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr ∈ S},
from ext (dioph_fn_comp1 (reindex_dioph _ (some ∘ inl ⊗ none :: some ∘ inr) d) $
reindex_dioph_fn inl df) $ λ v,
by { dsimp, congr', ext x, obtain (_ | _ | _) := x; refl },
have dioph {v | v ⊗ f v :: (λ (i : fin2 n), fl i v) ∈ S},
from @dioph_fn_compn n (λ v, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl,
ext this $ λ v, by { dsimp, congr', ext x, obtain (_ | _ | _) := x; refl }
lemma dioph_comp {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n)
(df : vector_allp dioph_fn f) : dioph {v | (λ i, f i v) ∈ S} :=
dioph_fn_compn (reindex_dioph _ inr d) df
lemma dioph_fn_comp {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n)
(dg : vector_allp dioph_fn g) : dioph_fn (λ v, f (λ i, g i v)) :=
dioph_comp ((dioph_fn_vec _).1 df) ((λ v, v none) :: λ i v, g i (v ∘ some)) $
by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λ i,
reindex_dioph_fn _ $ (vector_allp_iff_forall _ _).1 dg _⟩
localized "notation x ` D∧ `:35 y := dioph.inter x y" in dioph
localized "notation x ` D∨ `:35 y := dioph.union x y" in dioph
localized "notation `D∃`:30 := dioph.vec_ex1_dioph" in dioph
localized "prefix `&`:max := fin2.of_nat'" in dioph
theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λ v : vector3 ℕ n, v &m) :=
proj_dioph &m
localized "prefix `D&`:100 := dioph.proj_dioph_of_nat" in dioph
theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) :=
abs_poly_dioph (poly.const n)
localized "prefix `D.`:100 := dioph.const_dioph" in dioph
variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g)
include df dg
lemma dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λ v:vector3 ℕ 2, S (v &0) (v &1))) :
dioph (λ v, S (f v) (g v)) :=
dioph_comp d [f, g] (by exact ⟨df, dg⟩)
lemma dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λ v:vector3 ℕ 2, h (v &0) (v &1))) :
dioph_fn (λ v, h (f v) (g v)) :=
dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩)
lemma eq_dioph : dioph (λ v, f v = g v) :=
dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1)
(λ v, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans
⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩)
localized "infix ` D= `:50 := dioph.eq_dioph" in dioph
lemma add_dioph : dioph_fn (λ v, f v + g v) :=
dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1)
localized "infix ` D+ `:80 := dioph.add_dioph" in dioph
lemma mul_dioph : dioph_fn (λ v, f v * g v) :=
dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1)
localized "infix ` D* `:90 := dioph.mul_dioph" in dioph
lemma le_dioph : dioph {v | f v ≤ g v} :=
dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λ v, ⟨λ ⟨x, hx⟩, le.intro hx, le.dest⟩)
localized "infix ` D≤ `:50 := dioph.le_dioph" in dioph
lemma lt_dioph : dioph {v | f v < g v} := df D+ (D. 1) D≤ dg
localized "infix ` D< `:50 := dioph.lt_dioph" in dioph
lemma ne_dioph : dioph {v | f v ≠ g v} :=
ext (df D< dg D∨ dg D< df) $ λ v, by { dsimp, exact lt_or_lt_iff_ne }
localized "infix ` D≠ `:50 := dioph.ne_dioph" in dioph
lemma sub_dioph : dioph_fn (λ v, f v - g v) :=
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $
ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λ x y z,
show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from
⟨λ o, begin
rcases o with ae | ⟨yz, x0⟩,
{ rw [ae, add_tsub_cancel_right] },
{ rw [x0, tsub_eq_zero_iff_le.mpr yz] }
end, begin
rintro rfl,
cases le_total y z with yz zy,
{ exact or.inr ⟨yz, tsub_eq_zero_iff_le.mpr yz⟩ },
{ exact or.inl (tsub_add_cancel_of_le zy).symm },
end⟩
localized "infix ` D- `:80 := dioph.sub_dioph" in dioph
lemma dvd_dioph : dioph (λ v, f v ∣ g v) :=
dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩)
localized "infix ` D∣ `:50 := dioph.dvd_dioph" in dioph
lemma mod_dioph : dioph_fn (λ v, f v % g v) :=
have dioph (λ v : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1),
from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2),
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λ z x y,
show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from
⟨λ ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero],
exact mod_eq_of_lt hl end,
λ e, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λ h, mod_lt _ (nat.pos_of_ne_zero h), x / y,
mod_add_div _ _⟩⟩
localized "infix ` D% `:80 := dioph.mod_dioph" in dioph
lemma modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λ v, f v ≡ g v [MOD h v]) :=
df D% dh D= dg D% dh
localized "notation `D≡` := dioph.modeq_dioph" in dioph
lemma div_dioph : dioph_fn (λ v, f v / g v) :=
have dioph (λ v : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2),
from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2,
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λ z x y,
show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z,
by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim
(λ y0, by rw [y0, nat.div_zero]; exact
⟨λ o, (o.resolve_right $ λ ⟨_, h2⟩, nat.not_lt_zero _ h2).right, λ z0, or.inl ⟨rfl, z0⟩⟩)
(λ ypos, iff.trans ⟨λ o, o.resolve_left $ λ ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩
(le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $
iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul _ _ ypos)).symm)
localized "infix ` D/ `:80 := dioph.div_dioph" in dioph
omit df dg
open pell
lemma pell_dioph : dioph (λ v:vector3 ℕ 4, ∃ h : 1 < v &0,
xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) :=
have dioph {v : vector3 ℕ 4 |
1 < v &0 ∧ v &1 ≤ v &3 ∧
(v &2 = 1 ∧ v &3 = 0 ∨
∃ (u w s t b : ℕ),
v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧
u * u - (v &0 * v &0 - 1) * w * w = 1 ∧
s * s - (b * b - 1) * t * t = 1 ∧
1 < b ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧
0 < w ∧ v &3 * v &3 ∣ w ∧
(s ≡ v &2 [MOD u]) ∧
(t ≡ v &1 [MOD 4 * v &3]))}, from
D.1 D< D&0 D∧ D&1 D≤ D&3 D∧
((D&2 D= D.1 D∧ D&3 D= D.0) D∨
(D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $
D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧
D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧
D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧
D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧
D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧
(D≡ (D&2) (D&7) D&4) D∧
(D≡ (D&1) (D&6) (D.4 D* D&8)))),
dioph.ext this $ λ v, matiyasevic.symm
lemma xn_dioph : dioph_pfun (λ v:vector3 ℕ 2, ⟨1 < v &0, λ h, xn h (v &1)⟩) :=
have dioph (λ v:vector3 ℕ 3, ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from
let D_pell := pell_dioph.reindex_dioph (fin2 4) [&2, &3, &1, &0] in D∃3 D_pell,
(dioph_pfun_vec _).2 $ dioph.ext this $ λ v, ⟨λ ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩
include df dg
/-- A version of **Matiyasevic's theorem** -/
theorem pow_dioph : dioph_fn (λ v, f v ^ g v) :=
have dioph {v : vector3 ℕ 3 |
v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧
(v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧
∃ (w a t z x y : ℕ),
(∃ (a1 : 1 < a), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧
(x ≡ y * (a - v &1) + v &0 [MOD t]) ∧
2 * a * v &1 = t + (v &1 * v &1 + 1) ∧
v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧
a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from
let D_pell := pell_dioph.reindex_dioph (fin2 9) [&4, &8, &1, &0] in
(D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧
((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧
(D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧
(D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧
D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧
D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧
D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))),
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λ v, iff.symm $
eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $
⟨λ ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩,
λ ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩
end
end dioph
|
1a97b24b21afe972d1e92835d3b285368dfcd065 | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/data/polynomial/reverse.lean | 9c5bed695fe3b3b649c42036ed694161c50d8b38 | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,048 | 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.degree
/-!
# 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
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 : ℕ) (f : polynomial R) : polynomial R :=
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
ext1,
rw [reflect, mem_image, 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) :=
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.coeff (rev_at N i) : finsupp.emb_domain_apply _ _ _
@[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 :=
begin
split,
{ intros a,
injection a with f0 f1,
rwa [map_eq_empty, support_eq_empty] at f0, },
{ rintro rfl,
refl, },
end
@[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_coeff_zero.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
@[simp] lemma reverse_zero : reverse (0 : polynomial R) = 0 := rfl
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
@[simp] lemma coeff_zero_reverse (f : polynomial R) : coeff (reverse f) 0 = leading_coeff f :=
by simp [reverse, coeff_reflect]
@[simp] lemma coeff_one_reverse (f : polynomial R) : coeff (reverse f) 1 = next_coeff f :=
begin
rw [reverse, coeff_reflect, 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 polynomial
|
ad0e2340a547011d5cb66451396370aa440646f7 | 6b10c15e653d49d146378acda9f3692e9b5b1950 | /examples/basic_skills/unnamed_710.lean | 029722423034e5220da0b353b70acc08c80ecd0f | [] | no_license | gebner/mathematics_in_lean | 3cf7f18767208ea6c3307ec3a67c7ac266d8514d | 6d1462bba46d66a9b948fc1aef2714fd265cde0b | refs/heads/master | 1,655,301,945,565 | 1,588,697,505,000 | 1,588,697,505,000 | 261,523,603 | 0 | 0 | null | 1,588,695,611,000 | 1,588,695,610,000 | null | UTF-8 | Lean | false | false | 126 | lean | namespace my_ring
variables {R : Type*} [ring R]
-- BEGIN
theorem zero_mul (a : R) : 0 * a = 0 :=
sorry
-- END
end my_ring |
1bbfb00a2344fc2f922e6828c8cb3c6efd500390 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/seq/wseq.lean | 842bfc06f6f783357ebd8dde02c6a073904b3740 | [
"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 | 55,354 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.dlist
import data.list.basic
import data.seq.seq
open function
universes u v w
/-
coinductive wseq (α : Type u) : Type u
| nil : wseq α
| cons : α → wseq α → wseq α
| think : wseq α → wseq α
-/
/-- Weak sequences.
While the `seq` structure allows for lists which may not be finite,
a weak sequence also allows the computation of each element to
involve an indeterminate amount of computation, including possibly
an infinite loop. This is represented as a regular `seq` interspersed
with `none` elements to indicate that computation is ongoing.
This model is appropriate for Haskell style lazy lists, and is closed
under most interesting computation patterns on infinite lists,
but conversely it is difficult to extract elements from it. -/
def wseq (α) := seq (option α)
namespace wseq
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Turn a sequence into a weak sequence -/
def of_seq : seq α → wseq α := (<$>) some
/-- Turn a list into a weak sequence -/
def of_list (l : list α) : wseq α := of_seq l
/-- Turn a stream into a weak sequence -/
def of_stream (l : stream α) : wseq α := of_seq l
instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩
instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩
instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩
/-- The empty weak sequence -/
def nil : wseq α := seq.nil
instance : inhabited (wseq α) := ⟨nil⟩
/-- Prepend an element to a weak sequence -/
def cons (a : α) : wseq α → wseq α := seq.cons (some a)
/-- Compute for one tick, without producing any elements -/
def think : wseq α → wseq α := seq.cons none
/-- Destruct a weak sequence, to (eventually possibly) produce either
`none` for `nil` or `some (a, s)` if an element is produced. -/
def destruct : wseq α → computation (option (α × wseq α)) :=
computation.corec (λ s, match seq.destruct s with
| none := sum.inl none
| some (none, s') := sum.inr s'
| some (some a, s') := sum.inl (some (a, s'))
end)
def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil)
(h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s :=
seq.cases_on s h1 (λ o, option.cases_on o h3 h2)
protected def mem (a : α) (s : wseq α) := seq.mem (some a) s
instance : has_mem α (wseq α) :=
⟨wseq.mem⟩
theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a
/-- Get the head of a weak sequence. This involves a possibly
infinite computation. -/
def head (s : wseq α) : computation (option α) :=
computation.map ((<$>) prod.fst) (destruct s)
/-- Encode a computation yielding a weak sequence into additional
`think` constructors in a weak sequence -/
def flatten : computation (wseq α) → wseq α :=
seq.corec (λ c, match computation.destruct c with
| sum.inl s := seq.omap return (seq.destruct s)
| sum.inr c' := some (none, c')
end)
/-- Get the tail of a weak sequence. This doesn't need a `computation`
wrapper, unlike `head`, because `flatten` allows us to hide this
in the construction of the weak sequence itself. -/
def tail (s : wseq α) : wseq α :=
flatten $ (λ o, option.rec_on o nil prod.snd) <$> destruct s
/-- drop the first `n` elements from `s`. -/
def drop (s : wseq α) : ℕ → wseq α
| 0 := s
| (n+1) := tail (drop n)
attribute [simp] drop
/-- Get the nth element of `s`. -/
def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n)
/-- Convert `s` to a list (if it is finite and completes in finite time). -/
def to_list (s : wseq α) : computation (list α) :=
@computation.corec (list α) (list α × wseq α) (λ ⟨l, s⟩,
match seq.destruct s with
| none := sum.inl l.reverse
| some (none, s') := sum.inr (l, s')
| some (some a, s') := sum.inr (a::l, s')
end) ([], s)
/-- Get the length of `s` (if it is finite and completes in finite time). -/
def length (s : wseq α) : computation ℕ :=
@computation.corec ℕ (ℕ × wseq α) (λ ⟨n, s⟩,
match seq.destruct s with
| none := sum.inl n
| some (none, s') := sum.inr (n, s')
| some (some a, s') := sum.inr (n+1, s')
end) (0, s)
/-- A weak sequence is finite if `to_list s` terminates. Equivalently,
it is a finite number of `think` and `cons` applied to `nil`. -/
class is_finite (s : wseq α) : Prop := (out : (to_list s).terminates)
instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h.out
/-- Get the list corresponding to a finite weak sequence. -/
def get (s : wseq α) [is_finite s] : list α := (to_list s).get
/-- A weak sequence is *productive* if it never stalls forever - there are
always a finite number of `think`s between `cons` constructors.
The sequence itself is allowed to be infinite though. -/
class productive (s : wseq α) : Prop := (nth_terminates : ∀ n, (nth s n).terminates)
theorem productive_iff (s : wseq α) : productive s ↔ ∀ n, (nth s n).terminates :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
instance nth_terminates (s : wseq α) [h : productive s] :
∀ n, (nth s n).terminates := h.nth_terminates
instance head_terminates (s : wseq α) [productive s] :
(head s).terminates := s.nth_terminates 0
/-- Replace the `n`th element of `s` with `a`. -/
def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ ⟨n, s⟩,
match seq.destruct s, n with
| none, n := none
| some (none, s'), n := some (none, n, s')
| some (some a', s'), 0 := some (some a', 0, s')
| some (some a', s'), 1 := some (some a, 0, s')
| some (some a', s'), (n+2) := some (some a', n+1, s')
end) (n+1, s)
/-- Remove the `n`th element of `s`. -/
def remove_nth (s : wseq α) (n : ℕ) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ ⟨n, s⟩,
match seq.destruct s, n with
| none, n := none
| some (none, s'), n := some (none, n, s')
| some (some a', s'), 0 := some (some a', 0, s')
| some (some a', s'), 1 := some (none, 0, s')
| some (some a', s'), (n+2) := some (some a', n+1, s')
end) (n+1, s)
/-- Map the elements of `s` over `f`, removing any values that yield `none`. -/
def filter_map (f : α → option β) : wseq α → wseq β :=
seq.corec (λ s, match seq.destruct s with
| none := none
| some (none, s') := some (none, s')
| some (some a, s') := some (f a, s')
end)
/-- Select the elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α :=
filter_map (λ a, if p a then some a else none)
-- example of infinite list manipulations
/-- Get the first element of `s` satisfying `p`. -/
def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) :=
head $ filter p s
/-- Zip a function over two weak sequences -/
def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ :=
@seq.corec (option γ) (wseq α × wseq β) (λ ⟨s1, s2⟩,
match seq.destruct s1, seq.destruct s2 with
| some (none, s1'), some (none, s2') := some (none, s1', s2')
| some (some a1, s1'), some (none, s2') := some (none, s1, s2')
| some (none, s1'), some (some a2, s2') := some (none, s1', s2)
| some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2')
| _, _ := none
end) (s1, s2)
/-- Zip two weak sequences into a single sequence of pairs -/
def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk
/-- Get the list of indexes of elements of `s` satisfying `p` -/
def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ :=
(zip s (stream.nats : wseq ℕ)).filter_map
(λ ⟨a, n⟩, if p a then some n else none)
/-- Get the index of the first element of `s` satisfying `p` -/
def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ :=
(λ o, option.get_or_else o 0) <$> head (find_indexes p s)
/-- Get the index of the first occurrence of `a` in `s` -/
def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a)
/-- Get the indexes of occurrences of `a` in `s` -/
def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a)
/-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in
some order (nondeterministically). -/
def union (s1 s2 : wseq α) : wseq α :=
@seq.corec (option α) (wseq α × wseq α) (λ ⟨s1, s2⟩,
match seq.destruct s1, seq.destruct s2 with
| none, none := none
| some (a1, s1'), none := some (a1, s1', nil)
| none, some (a2, s2') := some (a2, nil, s2')
| some (none, s1'), some (none, s2') := some (none, s1', s2')
| some (some a1, s1'), some (none, s2') := some (some a1, s1', s2')
| some (none, s1'), some (some a2, s2') := some (some a2, s1', s2')
| some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2')
end) (s1, s2)
/-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/
def is_empty (s : wseq α) : computation bool :=
computation.map option.is_none $ head s
/-- Calculate one step of computation -/
def compute (s : wseq α) : wseq α :=
match seq.destruct s with
| some (none, s') := s'
| _ := s
end
/-- Get the first `n` elements of a weak sequence -/
def take (s : wseq α) (n : ℕ) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ ⟨n, s⟩,
match n, seq.destruct s with
| 0, _ := none
| m+1, none := none
| m+1, some (none, s') := some (none, m+1, s')
| m+1, some (some a, s') := some (some a, m, s')
end) (n, s)
/-- Split the sequence at position `n` into a finite initial segment
and the weak sequence tail -/
def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) :=
@computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ ⟨n, l, s⟩,
match n, seq.destruct s with
| 0, _ := sum.inl (l.reverse, s)
| m+1, none := sum.inl (l.reverse, s)
| m+1, some (none, s') := sum.inr (n, l, s')
| m+1, some (some a, s') := sum.inr (m, a::l, s')
end) (n, [], s)
/-- Returns `tt` if any element of `s` satisfies `p` -/
def any (s : wseq α) (p : α → bool) : computation bool :=
computation.corec (λ s : wseq α,
match seq.destruct s with
| none := sum.inl ff
| some (none, s') := sum.inr s'
| some (some a, s') := if p a then sum.inl tt else sum.inr s'
end) s
/-- Returns `tt` if every element of `s` satisfies `p` -/
def all (s : wseq α) (p : α → bool) : computation bool :=
computation.corec (λ s : wseq α,
match seq.destruct s with
| none := sum.inl tt
| some (none, s') := sum.inr s'
| some (some a, s') := if p a then sum.inr s' else sum.inl ff
end) s
/-- Apply a function to the elements of the sequence to produce a sequence
of partial results. (There is no `scanr` because this would require
working from the end of the sequence, which may not exist.) -/
def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α :=
cons a $ @seq.corec (option α) (α × wseq β) (λ ⟨a, s⟩,
match seq.destruct s with
| none := none
| some (none, s') := some (none, a, s')
| some (some b, s') := let a' := f a b in some (some a', a', s')
end) (a, s)
/-- Get the weak sequence of initial segments of the input sequence -/
def inits (s : wseq α) : wseq (list α) :=
cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩,
match seq.destruct s with
| none := none
| some (none, s') := some (none, l, s')
| some (some a, s') := let l' := l.concat a in
some (some l'.to_list, l', s')
end) (dlist.empty, s)
/-- Like take, but does not wait for a result. Calculates `n` steps of
computation and returns the sequence computed so far -/
def collect (s : wseq α) (n : ℕ) : list α :=
(seq.take n s).filter_map id
/-- Append two weak sequences. As with `seq.append`, this may not use
the second sequence if the first one takes forever to compute -/
def append : wseq α → wseq α → wseq α := seq.append
/-- Map a function over a weak sequence -/
def map (f : α → β) : wseq α → wseq β := seq.map (option.map f)
/-- Flatten a sequence of weak sequences. (Note that this allows
empty sequences, unlike `seq.join`.) -/
def join (S : wseq (wseq α)) : wseq α :=
seq.join ((λ o : option (wseq α), match o with
| none := seq1.ret none
| some s := (none, s)
end) <$> S)
/-- Monadic bind operator for weak sequences -/
def bind (s : wseq α) (f : α → wseq β) : wseq β :=
join (map f s)
@[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) :
option (α × wseq α) → option (β × wseq β) → Prop
| none none := true
| (some (a, s)) (some (b, t)) := R a b ∧ C s t
| _ _ := false
theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop}
(H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) :
∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p
| none none h := trivial
| (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h
| none (some _) h := false.elim h
| (some (_, _)) none h := false.elim h
theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop}
(H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p :=
lift_rel_o.imp (λ _ _, id) H
@[simp] def bisim_o (R : wseq α → wseq α → Prop) :
option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R
theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} :
bisim_o R o p → bisim_o S o p :=
lift_rel_o.imp_right _ H
/-- Two weak sequences are `lift_rel R` related if they are either both empty,
or they are both nonempty and the heads are `R` related and the tails are
`lift_rel R` related. (This is a coinductive definition.) -/
def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop :=
∃ C : wseq α → wseq β → Prop, C s t ∧
∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t)
/-- If two sequences are equivalent, then they have the same values and
the same computational behavior (i.e. if one loops forever then so does
the other), although they may differ in the number of `think`s needed to
arrive at the answer. -/
def equiv : wseq α → wseq α → Prop := lift_rel (=)
theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t →
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t)
| ⟨R, h1, h2⟩ :=
by refine computation.lift_rel.imp _ _ _ (h2 h1);
apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩
theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t ↔
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) :=
⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t),
or.inr h, λ s t h, begin
have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t),
{ cases h with h h, exact lift_rel_destruct h, assumption },
apply computation.lift_rel.imp _ _ _ h,
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl
end⟩⟩
infix ` ~ `:50 := equiv
theorem destruct_congr {s t : wseq α} :
s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) :=
lift_rel_destruct
theorem destruct_congr_iff {s t : wseq α} :
s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) :=
lift_rel_destruct_iff
theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) :=
λ s, begin
refine ⟨(=), rfl, λ s t (h : s = t), _⟩,
rw ←h, apply computation.lift_rel.refl,
intro a, cases a with a, simp, cases a; simp, apply H
end
theorem lift_rel_o.swap (R : α → β → Prop) (C) :
swap (lift_rel_o R C) = lift_rel_o (swap R) (swap C) :=
by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl }
theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) :
lift_rel (swap R) s2 s1 :=
begin
refine ⟨swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩,
rw [←lift_rel_o.swap, computation.lift_rel.swap],
apply lift_rel_destruct h
end
theorem lift_rel.swap (R : α → β → Prop) :
swap (lift_rel R) = lift_rel (swap R) :=
funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩
theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) :=
λ s1 s2 (h : swap (lift_rel R) s2 s1),
by rwa [lift_rel.swap, show swap R = R, from
funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h
theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) :=
λ s t u h1 h2, begin
refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩,
rcases h with ⟨t, h1, h2⟩,
have h1 := lift_rel_destruct h1,
have h2 := lift_rel_destruct h2,
refine computation.lift_rel_def.2
⟨(computation.terminates_of_lift_rel h1).trans
(computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩,
rcases h1.left ha with ⟨b, hb, t1⟩,
have t2 := computation.rel_of_lift_rel h2 hb hc,
cases a with a; cases c with c,
{ trivial },
{ cases b, {cases t2}, {cases t1} },
{ cases a, cases b with b, {cases t1}, {cases b, cases t2} },
{ cases a with a s, cases b with b, {cases t1},
cases b with b t, cases c with c u,
cases t1 with ab st, cases t2 with bc tu,
exact ⟨H ab bc, t, st, tu⟩ }
end
theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R)
| ⟨refl, symm, trans⟩ :=
⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩
@[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s :=
lift_rel.refl (=) eq.refl
@[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s :=
lift_rel.symm (=) (@eq.symm _)
@[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u :=
lift_rel.trans (=) (@eq.trans _)
theorem equiv.equivalence : equivalence (@equiv α) :=
⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩
open computation
local notation `return` := computation.return
@[simp] theorem destruct_nil : destruct (nil : wseq α) = return none :=
computation.destruct_eq_ret rfl
@[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) :=
computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap]
@[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think :=
computation.destruct_eq_think $ by simp [destruct, think, computation.rmap]
@[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none :=
seq.destruct_nil
@[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) :=
seq.destruct_cons _ _
@[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) :=
seq.destruct_cons _ _
@[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl
@[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl
@[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl
@[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s :=
begin
refine seq.eq_of_bisim (λ s1 s2, flatten (return s2) = s1) _ rfl,
intros s' s h, rw ←h, simp [flatten],
cases seq.destruct s, { simp },
{ cases val with o s', simp }
end
@[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) :=
seq.destruct_eq_cons $ by simp [flatten, think]
@[simp]
theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct :=
begin
refine computation.eq_of_bisim (λ c1 c2, c1 = c2 ∨
∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩),
intros c1 c2 h, exact match c1, c2, h with
| _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp
| _, _, (or.inr ⟨c, rfl, rfl⟩) := begin
apply c.cases_on (λ a, _) (λ c', _); repeat {simp},
{ cases (destruct a).destruct; simp },
{ exact or.inr ⟨c', rfl, rfl⟩ }
end end
end
theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) :=
terminates_map_iff _ (destruct s)
@[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail]
@[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail]
@[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail]
@[simp] theorem dropn_nil (n) :
drop (nil : wseq α) n = nil := by induction n; simp [*, drop]
@[simp] theorem dropn_cons (a : α) (s) (n) :
drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop]
@[simp] theorem dropn_think (s : wseq α) (n) :
drop (think s) n = (drop s n).think := by induction n; simp [*, drop]
theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n
| 0 := rfl
| (n+1) := congr_arg tail (dropn_add n)
theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) :=
by rw add_comm; symmetry; apply dropn_add
theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n :=
congr_arg head (dropn_add _ _ _)
theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) :=
congr_arg head (dropn_tail _ _)
@[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil
@[simp] theorem join_think (S : wseq (wseq α)) :
join (think S) = think (join S) :=
by { simp [think, join], unfold functor.map, simp [join, seq1.ret] }
@[simp] theorem join_cons (s : wseq α) (S) :
join (cons s S) = think (append s (join S)) :=
by { simp [think, join], unfold functor.map, simp [join, cons, append] }
@[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _
@[simp] theorem cons_append (a : α) (s t) :
append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _
@[simp] theorem think_append (s t : wseq α) :
append (think s) t = think (append s t) := seq.cons_append _ _ _
@[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _
@[simp] theorem append_assoc (s t u : wseq α) :
append (append s t) u = append s (append t u) := seq.append_assoc _ _ _
@[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α))
| none := return none
| (some (a, s)) := destruct s
theorem destruct_tail (s : wseq α) :
destruct (tail s) = destruct s >>= tail.aux :=
begin
simp [tail], rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc],
apply congr_arg, ext1 (_|⟨a, s⟩);
apply (@pure_bind computation _ _ _ _ _ _).trans _; simp
end
@[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α))
| 0 := return
| (n+1) := λ a, tail.aux a >>= drop.aux n
theorem drop.aux_none : ∀ n, @drop.aux α n none = return none
| 0 := rfl
| (n+1) := show computation.bind (return none) (drop.aux n) = return none,
by rw [ret_bind, drop.aux_none]
theorem destruct_dropn :
∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n
| s 0 := (bind_ret' _).symm
| s (n+1) := by rw [← dropn_tail, destruct_dropn _ n,
destruct_tail, is_lawful_monad.bind_assoc]; refl
theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] :
terminates (head s) :=
(head_terminates_iff _).2 $ begin
rcases (head_terminates_iff _).1 T with ⟨⟨a, h⟩⟩,
simp [tail] at h,
rcases exists_of_mem_bind h with ⟨s', h1, h2⟩,
unfold functor.map at h1,
exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3
end
theorem destruct_some_of_destruct_tail_some {s : wseq α} {a}
(h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s :=
begin
unfold tail functor.map at h, simp at h,
rcases exists_of_mem_bind h with ⟨t, tm, td⟩, clear h,
rcases exists_of_mem_map tm with ⟨t', ht', ht2⟩, clear tm,
cases t' with t'; rw ←ht2 at td; simp at td,
{ have := mem_unique td (ret_mem _), contradiction },
{ exact ⟨_, ht'⟩ }
end
theorem head_some_of_head_tail_some {s : wseq α} {a}
(h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s :=
begin
unfold head at h,
rcases exists_of_mem_map h with ⟨o, md, e⟩, clear h,
cases o with o; injection e with h', clear e h',
cases destruct_some_of_destruct_tail_some md with a am,
exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩
end
theorem head_some_of_nth_some {s : wseq α} {a n}
(h : some a ∈ nth s n) : ∃ a', some a' ∈ head s :=
begin
revert a, induction n with n IH; intros,
exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h']
end
instance productive_tail (s : wseq α) [productive s] : productive (tail s) :=
⟨λ n, by rw [nth_tail]; apply_instance⟩
instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) :=
⟨λ m, by rw [←nth_add]; apply_instance⟩
/-- Given a productive weak sequence, we can collapse all the `think`s to
produce a sequence. -/
def to_seq (s : wseq α) [productive s] : seq α :=
⟨λ n, (nth s n).get, λ n h,
begin
cases e : computation.get (nth s (n + 1)), {assumption},
have := mem_of_get_eq _ e,
simp [nth] at this h, cases head_some_of_head_tail_some this with a' h',
have := mem_unique h' (@mem_of_get_eq _ _ _ _ h),
contradiction
end⟩
theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) :
terminates (nth s n) → terminates (nth s m) :=
by induction h with m' h IH; [exact id,
exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)]
theorem head_terminates_of_nth_terminates {s : wseq α} {n} :
terminates (nth s n) → terminates (head s) :=
nth_terminates_le (nat.zero_le n)
theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) :
terminates (destruct s) :=
(head_terminates_iff _).1 $ head_terminates_of_nth_terminates T
theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s)
(h1 : ∀ b s', (a = b ∨ C s') → C (cons b s'))
(h2 : ∀ s, C s → C (think s)) : C s :=
begin
apply seq.mem_rec_on M,
intros o s' h, cases o with b,
{ apply h2, cases h, {contradiction}, {assumption} },
{ apply h1, apply or.imp_left _ h, intro h, injection h }
end
@[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s :=
begin
cases s with f al,
change some (some a) ∈ some none :: f ↔ some (some a) ∈ f,
constructor; intro h,
{ apply (stream.eq_or_mem_of_mem_cons h).resolve_left,
intro, injections },
{ apply stream.mem_cons_of_mem _ h }
end
theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} :
some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') :=
begin
generalize e : destruct s = c, intro h,
revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s;
apply s.cases_on _ (λ x s, _) (λ s, _); intros m;
have := congr_arg computation.destruct m; simp at this;
cases this with i1 i2,
{ rw [i1, i2],
cases s' with f al,
unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp,
have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp},
rw [h_a_eq_a'],
refine ⟨stream.eq_or_mem_of_mem_cons, λ o, _⟩,
{ cases o with e m,
{ rw e, apply stream.mem_cons },
{ exact stream.mem_cons_of_mem _ m } } },
{ simp, exact IH this }
end
@[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s :=
eq_or_mem_iff_mem $ by simp [ret_mem]
theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s :=
(mem_cons_iff _ _).2 (or.inr h)
theorem mem_cons (s : wseq α) (a) : a ∈ cons a s :=
(mem_cons_iff _ _).2 (or.inl rfl)
theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s :=
begin
intro h, have := h, cases h with n e, revert s, simp [stream.nth],
induction n with n IH; intro s; apply s.cases_on _ (λ x s, _) (λ s, _);
repeat{simp}; intros m e; injections,
{ exact or.inr m },
{ exact or.inr m },
{ apply IH m, rw e, cases tail s, refl }
end
theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s
| 0 h := h
| (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h)
theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s :=
begin
revert s, induction n with n IH; intros s h,
{ rcases exists_of_mem_map h with ⟨o, h1, h2⟩,
cases o with o; injection h2 with h',
cases o with a' s',
exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) },
{ have := @IH (tail s), rw nth_tail at this,
exact mem_of_mem_tail (this h) }
end
theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n :=
begin
apply mem_rec_on h,
{ intros a' s' h, cases h with h h,
{ existsi 0, simp [nth], rw h, apply ret_mem },
{ cases h with n h, existsi n+1,
simp [nth], exact h } },
{ intros s' h, cases h with n h,
existsi n, simp [nth], apply think_mem h }
end
theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) :
∃ n s', some (a, s') ∈ destruct (drop s n) :=
let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin
rcases (head_terminates_iff _).1 ⟨⟨_, h⟩⟩ with ⟨⟨o, om⟩⟩,
have := mem_unique (mem_map _ om) h,
cases o with o; injection this with i,
cases o with a' s', dsimp at i,
rw i at om, exact ⟨_, om⟩
end⟩
theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) :
∀ n, computation.lift_rel (lift_rel_o R (lift_rel R))
(destruct (drop s n)) (destruct (drop t n))
| 0 := lift_rel_destruct H
| (n+1) := begin
simp [destruct_tail],
apply lift_rel_bind,
apply lift_rel_dropn_destruct n,
exact λ a b o, match a, b, o with
| none, none, _ := by simp
| some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2
end
end
theorem exists_of_lift_rel_left {R : α → β → Prop} {s t}
(H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b :=
let ⟨n, h⟩ := exists_nth_of_mem h,
⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h,
⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in
⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩
theorem exists_of_lift_rel_right {R : α → β → Prop} {s t}
(H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b :=
by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h
theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) :=
let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨⟨_, h⟩⟩
theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ :=
seq.of_mem_append
theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ :=
seq.mem_append_left
theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b
| ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in
by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩
@[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil :=
by rw [lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) :
lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t :=
by rw [lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) :
lift_rel R (think s) t ↔ lift_rel R s t :=
by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) :
lift_rel R s (think t) ↔ lift_rel R s t :=
by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp
theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t :=
by unfold equiv; simp; exact h
theorem think_equiv (s : wseq α) : think s ~ s :=
by unfold equiv; simp; apply equiv.refl
theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t :=
by unfold equiv; simp; exact h
theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t :=
suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from
λ s t h o, ⟨this h, this h.symm⟩,
begin
intros s t h o ho,
rcases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩,
rw ←dse,
cases destruct_congr h with l r,
rcases l dsm with ⟨dt, dtm, dst⟩,
cases ds with a; cases dt with b,
{ apply mem_map _ dtm },
{ cases b, cases dst },
{ cases a, cases dst },
{ cases a with a s', cases b with b t', rw dst.left,
exact @mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst)
_ (destruct t) dtm }
end
theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s :=
begin
apply computation.mem_rec_on h, { simp },
{ intro s', apply equiv.trans, simp [think_equiv] }
end
theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)}
(h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) :=
let S := λ s t,
∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in
⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h,
match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin
simp, apply lift_rel_bind _ _ h,
intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab),
intros a b, apply lift_rel_o.imp_right,
intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h]
end end⟩
theorem flatten_congr {c1 c2 : computation (wseq α)} :
computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten
theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t :=
begin
apply flatten_congr,
unfold functor.map, rw [←bind_ret, ←bind_ret],
apply lift_rel_bind _ _ (destruct_congr h),
intros a b h, simp,
cases a with a; cases b with b,
{ trivial },
{ cases h },
{ cases a, cases h },
{ cases a with a s', cases b with b t', exact h.right }
end
theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n :=
by induction n; simp [*, tail_congr]
theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n :=
head_congr (dropn_congr h _)
theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t :=
suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩,
λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in
nth_mem ((nth_congr h _ _).1 hn)
theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t :=
by simp only [productive_iff]; exact
forall_congr (λ n, terminates_congr $ nth_congr h _)
theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t :=
⟨λ s t, ∀ n, nth s n ~ nth t n, h, λ s t h, begin
refine lift_rel_def.2 ⟨_, _⟩,
{ rw [←head_terminates_iff, ←head_terminates_iff],
exact terminates_congr (h 0) },
{ intros a b ma mb,
cases a with a; cases b with b,
{ trivial },
{ injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) },
{ injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) },
{ cases a with a s', cases b with b t',
injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab,
refine ⟨ab, λ n, _⟩,
refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans
((_ : nth (tail s) n ~ nth (tail t) n).trans
(nth_congr (flatten_equiv (mem_map _ mb)) n)),
rw [nth_tail, nth_tail], apply h } }
end⟩
theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) :=
begin
refine eq_of_bisim
(λ c1 c2, ∃ (l : list α) (s : wseq α),
c1 = corec length._match_2 (l.length, s) ∧
c2 = computation.map list.length (corec to_list._match_2 (l, s)))
_ ⟨[], s, rfl, rfl⟩,
intros s1 s2 h, rcases h with ⟨l, s, h⟩, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _);
repeat {simp [to_list, nil, cons, think, length]},
{ refine ⟨a::l, s, _, _⟩; simp },
{ refine ⟨l, s, _, _⟩; simp }
end
@[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl
@[simp] theorem of_list_cons (a : α) (l) :
of_list (a :: l) = cons a (of_list l) :=
show seq.map some (seq.of_list (a :: l)) =
seq.cons (some a) (seq.map some (seq.of_list l)), by simp
@[simp] theorem to_list'_nil (l : list α) :
corec to_list._match_2 (l, nil) = return l.reverse :=
destruct_eq_ret rfl
@[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) :
corec to_list._match_2 (l, cons a s) =
(corec to_list._match_2 (a::l, s)).think :=
destruct_eq_think $ by simp [to_list, cons]
@[simp] theorem to_list'_think (l : list α) (s : wseq α) :
corec to_list._match_2 (l, think s) =
(corec to_list._match_2 (l, s)).think :=
destruct_eq_think $ by simp [to_list, think]
theorem to_list'_map (l : list α) (s : wseq α) :
corec to_list._match_2 (l, s) =
((++) l.reverse) <$> to_list s :=
begin
refine eq_of_bisim
(λ c1 c2, ∃ (l' : list α) (s : wseq α),
c1 = corec to_list._match_2 (l' ++ l, s) ∧
c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s)))
_ ⟨[], s, rfl, rfl⟩,
intros s1 s2 h, rcases h with ⟨l', s, h⟩, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _);
repeat {simp [to_list, nil, cons, think, length]},
{ refine ⟨a::l', s, _, _⟩; simp },
{ refine ⟨l', s, _, _⟩; simp }
end
@[simp] theorem to_list_cons (a : α) (s) :
to_list (cons a s) = (list.cons a <$> to_list s).think :=
destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl
@[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] :=
destruct_eq_ret rfl
theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) :=
by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH)
@[simp] theorem destruct_of_seq (s : seq α) :
destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) :=
destruct_eq_ret $ begin
simp [of_seq, head, destruct, seq.destruct, seq.head],
rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth],
cases seq.nth s 0 with a, { refl },
unfold functor.map,
simp [destruct]
end
@[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head :=
by simp [head]; cases seq.head s; refl
@[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail :=
begin
simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl},
rw [seq.head_cons, seq.tail_cons], refl
end
@[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n)
| 0 := rfl
| (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq]
theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) :=
by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn]
instance productive_of_seq (s : seq α) : productive (of_seq s) :=
⟨λ n, by rw nth_of_seq; apply_instance⟩
theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s :=
begin
apply subtype.eq, funext n,
dsimp [to_seq], apply get_eq_of_mem,
rw nth_of_seq, apply ret_mem
end
/-- The monadic `return a` is a singleton list containing `a`. -/
def ret (a : α) : wseq α := of_list [a]
@[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl
@[simp] theorem map_cons (f : α → β) (a s) :
map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _
@[simp] theorem map_think (f : α → β) (s) :
map f (think s) = think (map f s) := seq.map_cons _ _ _
@[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map]
@[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret]
@[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) :=
seq.map_append _ _ _
theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) :
map (g ∘ f) s = map g (map f s) :=
begin
dsimp [map], rw ←seq.map_comp,
apply congr_fun, apply congr_arg,
ext ⟨⟩; refl
end
theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s :=
seq.mem_map (option.map f)
-- The converse is not true without additional assumptions
theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s :=
suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss →
a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h,
(this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _),
begin
intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S,
{ refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _);
intros ej m; simp at ej;
have := congr_arg seq.destruct ej; simp at this;
try {cases this}; try {contradiction},
substs b' ss,
simp at m ⊢,
cases o with e IH, { simp [e] },
cases m with e m, { simp [e] },
exact or.imp_left or.inr (IH _ _ rfl m) },
{ refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _);
intros ej m; simp at ej;
have := congr_arg seq.destruct ej; simp at this;
try { try {have := this.1}, contradiction }; subst ss,
{ apply or.inr, simp at m ⊢,
cases IH s S rfl m with as ex,
{ exact ⟨s, or.inl rfl, as⟩ },
{ rcases ex with ⟨s', sS, as⟩,
exact ⟨s', or.inr sS, as⟩ } },
{ apply or.inr, simp at m,
rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩,
exact ⟨s, by simp [sS], as⟩ },
{ simp at m IH ⊢, apply IH _ _ rfl m } }
end
theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b}
(h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a :=
let ⟨t, tm, bt⟩ := exists_of_mem_join h,
⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩
theorem destruct_map (f : α → β) (s : wseq α) :
destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) :=
begin
apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧
c2 = computation.map (option.map (prod.map f (map f))) (destruct s)),
{ intros c1 c2 h, cases h with s h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _); simp,
exact ⟨s, rfl, rfl⟩ },
{ exact ⟨s, rfl, rfl⟩ }
end
theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : wseq α} {s2 : wseq β}
{f1 : α → γ} {f2 : β → δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b))
: lift_rel S (map f1 s1) (map f2 s2) :=
⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t,
⟨s1, s2, rfl, rfl, h1⟩,
λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin
simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h),
intros o p h,
cases o with a; cases p with b; simp,
{ cases b; cases h },
{ cases a; cases h },
{ cases a with a s; cases b with b t, cases h with r h,
exact ⟨h2 r, s, rfl, t, rfl, h⟩ }
end end⟩
theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t :=
lift_rel_map _ _ h (λ _ _, congr_arg _)
@[simp] def destruct_append.aux (t : wseq α) :
option (α × wseq α) → computation (option (α × wseq α))
| none := destruct t
| (some (a, s)) := return (some (a, append s t))
theorem destruct_append (s t : wseq α) :
destruct (append s t) = (destruct s).bind (destruct_append.aux t) :=
begin
apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧
c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩,
intros c1 c2 h, rcases h with ⟨s, t, h⟩, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _); simp,
{ apply t.cases_on _ (λ b t, _) (λ t, _); simp,
{ refine ⟨nil, t, _, _⟩; simp } },
{ exact ⟨s, t, rfl, rfl⟩ }
end
@[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α))
| none := return none
| (some (s, S)) := (destruct (append s (join S))).think
theorem destruct_join (S : wseq (wseq α)) :
destruct (join S) = (destruct S).bind destruct_join.aux :=
begin
apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧
c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩),
intros c1 c2 h, exact match c1, c2, h with
| _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp
| _, _, or.inr ⟨S, rfl, rfl⟩ := begin
apply S.cases_on _ (λ s S, _) (λ S, _); simp,
{ refine or.inr ⟨S, rfl, rfl⟩ }
end end
end
theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β}
(h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) :
lift_rel R (append s1 s2) (append t1 t2) :=
⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1,
or.inr ⟨s1, t1, rfl, rfl, h1⟩,
λ s t h, match s, t, h with
| s, t, or.inl h := begin
apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h),
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl
end
| ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin
simp [destruct_append],
apply computation.lift_rel_bind _ _ (lift_rel_destruct h),
intros o p h,
cases o with a; cases p with b,
{ simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2),
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl },
{ cases b; cases h },
{ cases a; cases h },
{ cases a with a s; cases b with b t, cases h with r h,
simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ }
end
end⟩
theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop}
(ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧
lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) :
∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b :=
begin
cases exists_results_of_mem ma with n h, clear ma, revert a S T,
apply nat.strong_induction_on n _,
intros n IH a S T ST ra, simp [destruct_join] at ra, exact
let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra,
⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in
by exact match o, p, rop, rs1, rs2, mT with
| none, none, _, rs1, rs2, mT := by simp only [destruct_join]; exact
⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩
| some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT :=
by simp [destruct_append] at rs2; exact
let ⟨k1, rs3, ek⟩ := of_results_think rs2,
⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3,
⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in
by exact match o', p', rop', rs4, rs5, mt with
| none, none, _, rs4, rs5', mt :=
have n1 < n, begin
rw [en, ek, ek1],
apply lt_of_lt_of_le _ (nat.le_add_right _ _),
apply nat.lt_succ_of_le (nat.le_add_right _ _)
end,
let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩;
{ simp [destruct_join], apply mem_bind mT, simp [destruct_append],
apply think_mem, apply mem_bind mt, exact mb }
| some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin
simp at rs5,
refine ⟨some (b, append t' (join T')), _, _⟩,
{ simp [destruct_join], apply mem_bind mT, simp [destruct_append],
apply think_mem, apply mem_bind mt, apply ret_mem },
rw eq_of_ret_mem rs5.mem,
exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩
end end
end
end
theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)}
(h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) :=
⟨λ s1 s2, ∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧
lift_rel R s t ∧ lift_rel (lift_rel R) S T,
⟨nil, nil, S, T, by simp, by simp, by simp, h⟩,
λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin
clear _fun_match _x,
rw [h1, h2], rw [destruct_append, destruct_append],
apply computation.lift_rel_bind _ _ (lift_rel_destruct st),
exact λ o p h, match o, p, h with
| some (a, s), some (b, t), ⟨h1, h2⟩ :=
by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩
| none, none, _ := begin
dsimp [destruct_append.aux, computation.lift_rel], constructor,
{ intro, apply lift_rel_join.lem _ ST (λ _ _, id) },
{ intros b mb,
rw [←lift_rel_o.swap], apply lift_rel_join.lem (swap R),
{ rw [←lift_rel.swap R, ←lift_rel.swap], apply ST },
{ rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)],
exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩,
⟨t, s, T, S, h2, h1, st, ST⟩ },
{ exact mb } }
end end
end⟩
theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T :=
lift_rel_join _ h
theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : wseq α} {s2 : wseq β}
{f1 : α → wseq γ} {f2 : β → wseq δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b))
: lift_rel S (bind s1 f1) (bind s2 f2) :=
lift_rel_join _ (lift_rel_map _ _ h1 @h2)
theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β}
(h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 :=
lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2)
@[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s :=
by simp [ret]; apply think_equiv
@[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s :=
begin
refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩,
intros s' s h, rw ←h,
apply lift_rel_rec
(λ c1 c2, ∃ s,
c1 = destruct (join (map ret s)) ∧ c2 = destruct s),
{ exact λ c1 c2 h, match c1, c2, h with
| ._, ._, ⟨s, rfl, rfl⟩ := begin
clear h _match,
have : ∀ s, ∃ s' : wseq α, (map ret s).join.destruct = (map ret s').join.destruct ∧
destruct s = s'.destruct, from λ s, ⟨s, rfl, rfl⟩,
apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret, ret_mem, this, option.exists]
end end },
{ exact ⟨s, rfl, rfl⟩ }
end
@[simp] theorem join_append (S T : wseq (wseq α)) :
join (append S T) ~ append (join S) (join T) :=
begin
refine ⟨λ s1 s2, ∃ s S T,
s1 = append s (join (append S T)) ∧
s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩,
intros s1 s2 h,
apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T,
c1 = destruct (append s (join (append S T))) ∧
c2 = destruct (append s (append (join S) (join T)))) _ _ _
(let ⟨s, S, T, h1, h2⟩ := h in
⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩),
intros c1 c2 h,
exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin
clear _match h h,
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp,
{ apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp,
{ refine ⟨s, nil, T, _, _⟩; simp },
{ refine ⟨nil, nil, T, _, _⟩; simp } },
{ exact ⟨s, S, T, rfl, rfl⟩ },
{ refine ⟨nil, S, T, _, _⟩; simp } },
{ exact ⟨s, S, T, rfl, rfl⟩ },
{ exact ⟨s, S, T, rfl, rfl⟩ }
end end
end
@[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s :=
begin
dsimp [bind], change (λ x, ret (f x)) with (ret ∘ f),
rw [map_comp], apply join_map_ret
end
@[simp] theorem ret_bind (a : α) (f : α → wseq β) :
bind (ret a) f ~ f a := by simp [bind]
@[simp] theorem map_join (f : α → β) (S) :
map f (join S) = join (map (map f) S) :=
begin
apply seq.eq_of_bisim (λ s1 s2,
∃ s S, s1 = append s (map f (join S)) ∧
s2 = append s (join (map (map f) S))),
{ intros s1 s2 h,
exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp,
{ exact ⟨map f s, S, rfl, rfl⟩ },
{ refine ⟨nil, S, _, _⟩; simp } },
{ exact ⟨_, _, rfl, rfl⟩ },
{ exact ⟨_, _, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, _, _⟩; simp }
end
@[simp] theorem join_join (SS : wseq (wseq (wseq α))) :
join (join SS) ~ join (map join SS) :=
begin
refine ⟨λ s1 s2, ∃ s S SS,
s1 = append s (join (append S (join SS))) ∧
s2 = append s (append (join S) (join (map join SS))),
⟨nil, nil, SS, by simp, by simp⟩, _⟩,
intros s1 s2 h,
apply lift_rel_rec (λ c1 c2, ∃ s S SS,
c1 = destruct (append s (join (append S (join SS)))) ∧
c2 = destruct (append s (append (join S) (join (map join SS)))))
_ (destruct s1) (destruct s2)
(let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩),
intros c1 c2 h,
exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin
clear _match h h,
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp,
{ apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp,
{ refine ⟨nil, S, SS, _, _⟩; simp },
{ refine ⟨nil, nil, SS, _, _⟩; simp } },
{ exact ⟨s, S, SS, rfl, rfl⟩ },
{ refine ⟨nil, S, SS, _, _⟩; simp } },
{ exact ⟨s, S, SS, rfl, rfl⟩ },
{ exact ⟨s, S, SS, rfl, rfl⟩ }
end end
end
@[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) :
bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) :=
begin
simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join],
apply join_join
end
instance : monad wseq :=
{ map := @map,
pure := @ret,
bind := @bind }
/-
Unfortunately, wseq is not a lawful monad, because it does not satisfy
the monad laws exactly, only up to sequence equivalence.
Furthermore, even quotienting by the equivalence is not sufficient,
because the join operation involves lists of quotient elements,
with a lifted equivalence relation, and pure quotients cannot handle
this type of construction.
instance : is_lawful_monad wseq :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
-/
end wseq
|
c69521a11e96dae769f8535ec3f9b93f9f5accdd | e61a235b8468b03aee0120bf26ec615c045005d2 | /src/Init/Lean/MetavarContext.lean | 5137709b819a2e64a0b90936789930500e67a77c | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47,826 | 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.Reader
import Init.Data.Nat
import Init.Data.Option
import Init.Lean.Util.MonadCache
import Init.Lean.LocalContext
namespace Lean
/-
The metavariable context stores metavariable declarations and their
assignments. It is used in the elaborator, tactic framework, unifier
(aka `isDefEq`), and type class resolution (TC). First, we list all
the requirements imposed by these modules.
- We may invoke TC while executing `isDefEq`. We need this feature to
be able to solve unification problems such as:
```
f ?a (ringHasAdd ?s) ?x ?y =?= f Int intHasAdd n m
```
where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)`
During `isDefEq` (i.e., unification), it will need to solve the constrain
```
ringHasAdd ?s =?= intHasAdd
```
We say `ringHasAdd ?s` is stuck because it cannot be reduced until we
synthesize the term `?s : Ring ?a` using TC. This can be done since we
have assigned `?a := Int` when solving `?a =?= Int`.
- TC uses `isDefEq`, and `isDefEq` may create TC problems as shown
aaa. Thus, we may have nested TC problems.
- `isDefEq` extends the local context when going inside binders. Thus,
the local context for nested TC may be an extension of the local
context for outer TC.
- TC should not assign metavariables created by the elaborator, simp,
tactic framework, and outer TC problems. Reason: TC commits to the
first solution it finds. Consider the TC problem `HasCoe Nat ?x`,
where `?x` is a metavariable created by the caller. There are many
solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...),
and it doesn’t make sense to commit to the first one since TC does
not know the the constraints the caller may impose on `?x` after the
TC problem is solved.
Remark: we claim it is not feasible to make the whole system backtrackable,
and allow the caller to backtrack back to TC and ask it for another solution
if the first one found did not work. We claim it would be too inefficient.
- TC metavariables should not leak outside of TC. Reason: we want to
get rid of them after we synthesize the instance.
- `simp` invokes `isDefEq` for matching the left-hand-side of
equations to terms in our goal. Thus, it may invoke TC indirectly.
- In Lean3, we didn’t have to create a fresh pattern for trying to
match the left-hand-side of equations when executing `simp`. We had a
mechanism called tmp metavariables. It avoided this overhead, but it
created many problems since `simp` may indirectly call TC which may
recursively call TC. Moreover, we want to allow TC to invoke
tactics. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke
a tactic and `simp` itself. The Lean3 approach assumed that
metavariables were short-lived, this is not true in Lean4, and to some
extent was also not true in Lean3 since `simp`, in principle, could
trigger an arbitrary number of nested TC problems.
- Here are some possible call stack traces we could have in Lean3 (and Lean4).
```
Elaborator (-> TC -> isDefEq)+
Elaborator -> isDefEq (-> TC -> isDefEq)*
Elaborator -> simp -> isDefEq (-> TC -> isDefEq)*
```
In Lean4, TC may also invoke tactics.
- In Lean3 and Lean4, TC metavariables are not really short-lived. We
solve an arbitrary number of unification problems, and we may have
nested TC invocations.
- TC metavariables do not share the same local context even in the
same invocation. In the C++ and Lean implementations we use a trick to
ensure they do:
https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594
- Metavariables may be natural, synthetic or syntheticOpaque.
a) Natural metavariables may be assigned by unification (i.e., `isDefEq`).
b) Synthetic metavariables may still be assigned by unification,
but whenever possible `isDefEq` will avoid the assignment. For example,
if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic,
but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`.
We use synthetic metavariables for type class resolution.
Any module that creates synthetic metavariables, must also check
whether they have been assigned by `isDefEq`, and then still synthesize
them, and check whether the sythesized result is compatible with the one
assigned by `isDefEq`.
c) SyntheticOpaque metavariables are never assigned by `isDefEq`.
That is, the constraint `?n =?= Nat.succ Nat.zero` always fail
if `?n` is a syntheticOpaque metavariable. This kind of metavariable
is created by tactics such as `intro`. Reason: in the tactic framework,
subgoals as represented as metavariables, and a subgoal `?n` is considered
as solved whenever the metavariable is assigned.
This distinction was not precise in Lean3 and produced
counterintuitive behavior. For example, the following hack was added
in Lean3 to work around one of these issues:
https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751
- When creating lambda/forall expressions, we need to convert/abstract
free variables and convert them to bound variables. Now, suppose we a
trying to create a lambda/forall expression by abstracting free
variables `xs` and a term `t[?m]` which contains a metavariable `?m`,
and the local context of `?m` contains `xs`. The term
```
fun xs => t[?m]
```
will be ill-formed if we later assign a term `s` to `?m`, and
`s` contains free variables in `xs`. We address this issue by changing
the free variable abstraction procedure. We consider two cases: `?m`
is natural, `?m` is synthetic. Assume the type of `?m` is
`A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with
type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`.
In both cases, we produce the term `fun xs => t[?n xs]`
1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce
the term `fun xs => t[?n xs]`
2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable.
However, `?n` is managed by the metavariable context itself.
We say we have a "delayed assignment" `?n xs := ?m`.
That is, after a term `s` is assigned to `?m`, and `s`
does not contain metavariables, we replace any occurrence
`?n ts` with `s[xs := ts]`.
Gruesome details:
- When we create the type `forall xs => A` for `?n`, we may
encounter the same issue if `A` contains metavariables. So, the
process above is recursive. We claim it terminates because we keep
creating new metavariables with smaller local contexts.
- Suppose, we have `t[?m]` and we want to create a let-expression by
abstracting a let-decl free variable `x`, and the local context of
`?m` contatins `x`. Similarly to the previous case
```
let x : T := v; t[?m]
```
will be ill-formed if we later assign a term `s` to `?m`, and
`s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`.
1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with
and local context := local context of `?m` - `x`, we assign `?m := ?n`,
and produce the term `let x : T := v; t[?n]`. That is, we are just making
sure `?n` must never be assigned to a term containing `x`.
2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n`
with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`,
create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`.
Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since
`fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r`
with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic
may have reduced `let x : T := v; t[?n x]` into `t[?n v]`.
We are essentially using the pair "delayed assignment + application" to implement a delayed
substitution.
- We use TC for implementing coercions. Both Joe Hendrix and Reid Barton
reported a nasty limitation. In Lean3, TC will not be used if there are
metavariables in the TC problem. For example, the elaborator will not try
to synthesize `HasCoe Nat ?x`. This is good, but this constraint is too
strict for problems such as `HasCoe (Vector Bool ?n) (BV ?n)`. The coercion
exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw
an exception instead of return `false` whenever it tries to assign
a metavariable owned by its caller. The idea is to sign to the caller that
it cannot solve the TC problem at this point, and more information is needed.
That is, the caller must make progress an assign its metavariables before
trying to invoke TC again.
In Lean4, we are using a simpler design for the `MetavarContext`.
- No distinction betwen temporary and regular metavariables.
- Metavariables have a `depth` Nat field.
- MetavarContext also has a `depth` field.
- We bump the `MetavarContext` depth when we create a nested problem.
Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ...
- When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`.
- Metavariables from depth N+1 must be fully assigned before we return to level N.
- New design even allows us to invoke tactics from TC.
* Main concern
We don't have tmp metavariables anymore in Lean4. Thus, before trying to match
the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`,
create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with
these metavariables. We are hoping to minimize this overhead by
- Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`.
- Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`.
It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables,
and a new pattern.
- Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set.
- Adding support for AC-rewriting. In Lean3, users use AC lemmas as
rewriting rules for "sorting" terms. This is inefficient, requires
a quadratic number of rewrite steps, and does not preserve the
structure of the goal.
The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses
`isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3,
all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using
very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars,
we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars.
-/
structure LocalInstance :=
(className : Name)
(fvar : Expr)
abbrev LocalInstances := Array LocalInstance
def LocalInstance.beq (i₁ i₂ : LocalInstance) : Bool :=
i₁.fvar == i₂.fvar
instance LocalInstance.hasBeq : HasBeq LocalInstance := ⟨LocalInstance.beq⟩
/-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/
def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances :=
match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with
| some idx => localInsts.eraseIdx idx
| _ => localInsts
inductive MetavarKind
| natural
| synthetic
| syntheticOpaque
def MetavarKind.isSyntheticOpaque : MetavarKind → Bool
| MetavarKind.syntheticOpaque => true
| _ => false
structure MetavarDecl :=
(userName : Name := Name.anonymous)
(lctx : LocalContext)
(type : Expr)
(depth : Nat)
(localInstances : LocalInstances)
(kind : MetavarKind)
@[export lean_mk_metavar_decl]
def mkMetavarDeclEx (userName : Name) (lctx : LocalContext) (type : Expr) (depth : Nat) (localInstances : LocalInstances) (kind : MetavarKind) : MetavarDecl :=
{ userName := userName, lctx := lctx, type := type, depth := depth, localInstances := localInstances, kind := kind }
namespace MetavarDecl
instance : Inhabited MetavarDecl := ⟨{ lctx := arbitrary _, type := arbitrary _, depth := 0, localInstances := #[], kind := MetavarKind.natural }⟩
end MetavarDecl
/--
A delayed assignment for a metavariable `?m`. It represents an assignment of the form
`?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`.
Note that `fvars` may not be defined in the local context for `?m`.
- TODO: after we delete the old frontend, we can remove the field `lctx`.
This field is only used in old C++ implementation. -/
structure DelayedMetavarAssignment :=
(lctx : LocalContext)
(fvars : Array Expr)
(val : Expr)
structure MetavarContext :=
(depth : Nat := 0)
(lDepth : PersistentHashMap MVarId Nat := {})
(decls : PersistentHashMap MVarId MetavarDecl := {})
(lAssignment : PersistentHashMap MVarId Level := {})
(eAssignment : PersistentHashMap MVarId Expr := {})
(dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {})
namespace MetavarContext
instance : Inhabited MetavarContext := ⟨{}⟩
@[export lean_mk_metavar_ctx]
def mkMetavarContext : Unit → MetavarContext :=
fun _ => {}
/- Low level API for adding/declaring metavariable declarations.
It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`.
It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/
@[export lean_metavar_ctx_mk_decl]
def addExprMVarDecl (mctx : MetavarContext)
(mvarId : MVarId)
(userName : Name)
(lctx : LocalContext)
(localInstances : LocalInstances)
(type : Expr) (kind : MetavarKind := MetavarKind.natural) : MetavarContext :=
{ mctx with
decls := mctx.decls.insert mvarId {
userName := userName,
lctx := lctx,
localInstances := localInstances,
type := type,
depth := mctx.depth,
kind := kind } }
/- Low level API for adding/declaring universe level metavariable declarations.
It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`.
It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/
def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext :=
{ mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth }
@[export lean_metavar_ctx_find_decl]
def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl :=
mctx.decls.find? mvarId
def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl :=
match mctx.decls.find? mvarId with
| some decl => decl
| none => panic! "unknown metavariable"
def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext :=
let decl := mctx.getDecl mvarId;
{ mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } }
def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext :=
let decl := mctx.getDecl mvarId;
{ mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } }
def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat :=
mctx.lDepth.find? mvarId
def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat :=
match mctx.findLevelDepth? mvarId with
| some d => d
| none => panic! "unknown metavariable"
def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
match mctx.findDecl? mvarId with
| none => false
| some mvarDecl => mvarDecl.userName.isAnonymous
def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (newUserName : Name) : MetavarContext :=
match mctx.findDecl? mvarId with
| none => panic! "unknown metavariable"
| some mvarDecl => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with userName := newUserName } }
@[export lean_metavar_ctx_assign_level]
def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext :=
{ m with lAssignment := m.lAssignment.insert mvarId val }
@[export lean_metavar_ctx_assign_expr]
def assignExprCore (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext :=
{ m with eAssignment := m.eAssignment.insert mvarId val }
def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext :=
{ m with eAssignment := m.eAssignment.insert mvarId val }
@[export lean_metavar_ctx_assign_delayed]
def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext :=
{ m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } }
@[export lean_metavar_ctx_get_level_assignment]
def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level :=
m.lAssignment.find? mvarId
@[export lean_metavar_ctx_get_expr_assignment]
def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr :=
m.eAssignment.find? mvarId
@[export lean_metavar_ctx_get_delayed_assignment]
def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment :=
m.dAssignment.find? mvarId
@[export lean_metavar_ctx_is_level_assigned]
def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.lAssignment.contains mvarId
@[export lean_metavar_ctx_is_expr_assigned]
def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.eAssignment.contains mvarId
@[export lean_metavar_ctx_is_delayed_assigned]
def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.dAssignment.contains mvarId
@[export lean_metavar_ctx_erase_delayed]
def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext :=
{ m with dAssignment := m.dAssignment.erase mvarId }
def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
match mctx.lDepth.find? mvarId with
| some d => d == mctx.depth
| _ => panic! "unknown universe metavariable"
def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
let decl := mctx.getDecl mvarId;
decl.depth == mctx.depth
def incDepth (mctx : MetavarContext) : MetavarContext :=
{ mctx with depth := mctx.depth + 1 }
/-- Return true iff the given level contains an assigned metavariable. -/
def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool
| Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar lvl
| Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar lvl₂)
| Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar lvl₂)
| Level.mvar mvarId _ => mctx.isLevelAssigned mvarId
| Level.zero _ => false
| Level.param _ _ => false
/-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/
def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool
| Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx)
| Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl
| Expr.app f a _ => (f.hasMVar && hasAssignedMVar f) || (a.hasMVar && hasAssignedMVar a)
| Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar t) || (v.hasMVar && hasAssignedMVar v) || (b.hasMVar && hasAssignedMVar b)
| Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar d) || (b.hasMVar && hasAssignedMVar b)
| Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar d) || (b.hasMVar && hasAssignedMVar b)
| Expr.fvar _ _ => false
| Expr.bvar _ _ => false
| Expr.lit _ _ => false
| Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar e
| Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar e
| Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId
| Expr.localE _ _ _ _ => unreachable!
/-- Return true iff the given level contains a metavariable that can be assigned. -/
def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool
| Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar lvl
| Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar lvl₂)
| Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar lvl₂)
| Level.mvar mvarId _ => mctx.isLevelAssignable mvarId
| Level.zero _ => false
| Level.param _ _ => false
/-- Return `true` iff expression contains a metavariable that can be assigned. -/
def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool
| Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx)
| Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl
| Expr.app f a _ => (f.hasMVar && hasAssignableMVar f) || (a.hasMVar && hasAssignableMVar a)
| Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar t) || (v.hasMVar && hasAssignableMVar v) || (b.hasMVar && hasAssignableMVar b)
| Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar d) || (b.hasMVar && hasAssignableMVar b)
| Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar d) || (b.hasMVar && hasAssignableMVar b)
| Expr.fvar _ _ => false
| Expr.bvar _ _ => false
| Expr.lit _ _ => false
| Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar e
| Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar e
| Expr.mvar mvarId _ => mctx.isExprAssignable mvarId
| Expr.localE _ _ _ _ => unreachable!
partial def instantiateLevelMVars : Level → StateM MetavarContext Level
| lvl@(Level.succ lvl₁ _) => do lvl₁ ← instantiateLevelMVars lvl₁; pure (Level.updateSucc! lvl lvl₁)
| lvl@(Level.max lvl₁ lvl₂ _) => do lvl₁ ← instantiateLevelMVars lvl₁; lvl₂ ← instantiateLevelMVars lvl₂; pure (Level.updateMax! lvl lvl₁ lvl₂)
| lvl@(Level.imax lvl₁ lvl₂ _) => do lvl₁ ← instantiateLevelMVars lvl₁; lvl₂ ← instantiateLevelMVars lvl₂; pure (Level.updateIMax! lvl lvl₁ lvl₂)
| lvl@(Level.mvar mvarId _) => do
mctx ← get;
match getLevelAssignment? mctx mvarId with
| some newLvl =>
if !newLvl.hasMVar then pure newLvl
else do
newLvl' ← instantiateLevelMVars newLvl;
modify $ fun mctx => mctx.assignLevel mvarId newLvl';
pure newLvl'
| none => pure lvl
| lvl => pure lvl
namespace InstantiateExprMVars
private abbrev M := StateM (WithHashMapCache Expr Expr MetavarContext)
@[inline] def instantiateLevelMVars (lvl : Level) : M Level :=
WithHashMapCache.fromState $ MetavarContext.instantiateLevelMVars lvl
@[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr :=
if !e.hasMVar then pure e else checkCache e f
@[inline] private def getMCtx : M MetavarContext := do
s ← get; pure s.state
@[inline] private def modifyCtx (f : MetavarContext → MetavarContext) : M Unit :=
modify $ fun s => { s with state := f s.state }
/-- instantiateExprMVars main function -/
partial def main : Expr → M Expr
| e@(Expr.proj _ _ s _) => do s ← visit main s; pure (e.updateProj! s)
| e@(Expr.forallE _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateForallE! d b)
| e@(Expr.lam _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateLambdaE! d b)
| e@(Expr.letE _ t v b _) => do t ← visit main t; v ← visit main v; b ← visit main b; pure (e.updateLet! t v b)
| e@(Expr.const _ lvls _) => do lvls ← lvls.mapM instantiateLevelMVars; pure (e.updateConst! lvls)
| e@(Expr.sort lvl _) => do lvl ← instantiateLevelMVars lvl; pure (e.updateSort! lvl)
| e@(Expr.mdata _ b _) => do b ← visit main b; pure (e.updateMData! b)
| e@(Expr.app _ _ _) => e.withApp $ fun f args => do
let instArgs (f : Expr) : M Expr := do {
args ← args.mapM (visit main);
pure (mkAppN f args)
};
let instApp : M Expr := do {
let wasMVar := f.isMVar;
f ← visit main f;
if wasMVar && f.isLambda then
/- Some of the arguments in args are irrelevant after we beta reduce. -/
visit main (f.betaRev args.reverse)
else
instArgs f
};
match f with
| Expr.mvar mvarId _ => do
mctx ← getMCtx;
match mctx.getDelayedAssignment? mvarId with
| none => instApp
| some { fvars := fvars, val := val, .. } =>
/-
Apply "delayed substitution" (i.e., delayed assignment + application).
That is, `f` is some metavariable `?m`, that is delayed assigned to `val`.
If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain
metavariables, we replace the free variables `fvars` in `newVal` with the first
`fvars.size` elements of `args`. -/
if fvars.size > args.size then
/- We don't have sufficient arguments for instantiating the free variables `fvars`.
This can only happy if a tactic or elaboration function is not implemented correctly.
We decided to not use `panic!` here and report it as an error in the frontend
when we are checking for unassigned metavariables in an elaborated term. -/
instArgs f
else do
newVal ← visit main val;
if newVal.hasExprMVar then
instArgs f
else do
args ← args.mapM (visit main);
/-
Example: suppose we have
`?m t1 t2 t3`
That is, `f := ?m` and `args := #[t1, t2, t3]`
Morever, `?m` is delayed assigned
`?m #[x, y] := f x y`
where, `fvars := #[x, y]` and `newVal := f x y`.
After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`.
After `instantiaterRevRange 0 2 args`, we have `f t1 t2`.
After `mkAppRange 2 3`, we have `f t1 t2 t3` -/
let newVal := newVal.abstract fvars;
let result := newVal.instantiateRevRange 0 fvars.size args;
let result := mkAppRange result fvars.size args.size args;
pure $ result
| _ => instApp
| e@(Expr.mvar mvarId _) => checkCache e $ fun e => do
mctx ← getMCtx;
match mctx.getExprAssignment? mvarId with
| some newE => do
newE' ← visit main newE;
modifyCtx $ fun mctx => mctx.assignExpr mvarId newE';
pure newE'
| none => pure e
| e => pure e
end InstantiateExprMVars
def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext :=
if !e.hasMVar then (e, mctx)
else (WithHashMapCache.toState $ InstantiateExprMVars.main e).run mctx
def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext :=
lctx.foldl
(fun (result : LocalContext × MetavarContext) ldecl =>
let (lctx, mctx) := result;
match ldecl with
| LocalDecl.cdecl _ fvarId userName type bi =>
let (type, mctx) := mctx.instantiateMVars type;
(lctx.mkLocalDecl fvarId userName type bi, mctx)
| LocalDecl.ldecl _ fvarId userName type value =>
let (type, mctx) := mctx.instantiateMVars type;
let (value, mctx) := mctx.instantiateMVars value;
(lctx.mkLetDecl fvarId userName type value, mctx))
({}, mctx)
def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext :=
let mvarDecl := mctx.getDecl mvarId;
let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx;
let (type, mctx) := mctx.instantiateMVars mvarDecl.type;
{ mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } }
namespace DependsOn
private abbrev M := StateM ExprSet
private def visit? (e : Expr) : M Bool :=
if !e.hasMVar && !e.hasFVar then
pure false
else do
s ← get;
if s.contains e then
pure false
else do
modify $ fun s => s.insert e;
pure true
@[inline] private def visit (main : Expr → M Bool) (e : Expr) : M Bool :=
condM (visit? e) (main e) (pure false)
@[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) : Expr → M Bool
| e@(Expr.proj _ _ s _) => visit dep s
| e@(Expr.forallE _ d b _) => visit dep d <||> visit dep b
| e@(Expr.lam _ d b _) => visit dep d <||> visit dep b
| e@(Expr.letE _ t v b _) => visit dep t <||> visit dep v <||> visit dep b
| e@(Expr.mdata _ b _) => visit dep b
| e@(Expr.app f a _) => visit dep a <||> if f.isApp then dep f else visit dep f
| e@(Expr.mvar mvarId _) =>
match mctx.getExprAssignment? mvarId with
| some a => visit dep a
| none =>
let lctx := (mctx.getDecl mvarId).lctx;
pure $ lctx.any $ fun decl => p decl.fvarId
| e@(Expr.fvar fvarId _) => pure $ p fvarId
| e => pure false
@[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool :=
if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e
end DependsOn
/--
Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`.
For each metavariable `?m` occurring in `x`
1- If `?m := t`, then we visit `t` looking for `x`
2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`.
This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/
@[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool :=
(DependsOn.main mctx p e).run' {}
/--
Similar to `findExprDependsOn`, but checks the expressions in the given local declaration
depends on a free variable `x` s.t. `p x` is `true`. -/
@[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool :=
match localDecl with
| LocalDecl.cdecl _ _ _ type _ => findExprDependsOn mctx type p
| LocalDecl.ldecl _ _ _ type value => (DependsOn.main mctx p type <||> DependsOn.main mctx p value).run' {}
def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool :=
findExprDependsOn mctx e $ fun fvarId' => fvarId == fvarId'
def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool :=
findLocalDeclDependsOn mctx localDecl $ fun fvarId' => fvarId == fvarId'
namespace MkBinding
inductive Exception
| revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl)
def Exception.toString : Exception → String
| Exception.revertFailure _ lctx toRevert decl =>
"failed to revert "
++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'"))
++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator"
++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)"
instance Exception.hasToString : HasToString Exception := ⟨Exception.toString⟩
/--
`MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`.
We use a single state object for convenience.
We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/
structure State :=
(mctx : MetavarContext)
(ngen : NameGenerator)
(cache : HashMap Expr Expr := {}) --
abbrev MCore := EStateM Exception State
abbrev M := ReaderT Bool (EStateM Exception State)
def preserveOrder : M Bool := read
instance : MonadHashMapCacheAdapter Expr Expr M :=
{ getCache := do s ← get; pure s.cache,
modifyCache := fun f => modify $ fun s => { s with cache := f s.cache } }
/-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/
private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl :=
let d : LocalDecl := lctx.getFVar! $ xs.get! 0;
xs.foldlFrom
(fun d x =>
let decl := lctx.getFVar! x;
if decl.index < d.index then decl else d)
d 1
/-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations,
return a new array of free variables that contains `toRevert` and all free variables
in `lctx` that may depend on `toRevert`.
Remark: the result is sorted by `LocalDecl` indices. -/
private def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) :=
if toRevert.size == 0 then pure toRevert
else do
when preserveOrder $ do {
-- Make sure none of `toRevert` is an AuxDecl
-- Make sure toRevert[j] does not depend on toRevert[i] for j > i
toRevert.size.forM $ fun i => do
let fvar := toRevert.get! i;
let decl := lctx.getFVar! fvar;
when decl.binderInfo.isAuxDecl $
throw (Exception.revertFailure mctx lctx toRevert decl);
i.forM $ fun j =>
let prevFVar := toRevert.get! j;
let prevDecl := lctx.getFVar! prevFVar;
when (localDeclDependsOn mctx prevDecl fvar.fvarId!) $
throw (Exception.revertFailure mctx lctx toRevert prevDecl)
};
let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size;
let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert;
let initSize := newToRevert.size;
lctx.foldlFromM
(fun (newToRevert : Array Expr) decl =>
if initSize.any $ fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert
else if toRevert.any (fun x => decl.fvarId == x.fvarId!) then
pure (newToRevert.push decl.toExpr)
else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any $ fun x => x.fvarId! == fvarId) then
if decl.binderInfo.isAuxDecl then
throw (Exception.revertFailure mctx lctx toRevert decl)
else
pure (newToRevert.push decl.toExpr)
else
pure newToRevert)
newToRevert
firstDeclToVisit
/-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`.
We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/
private def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext :=
toRevert.foldr
(fun x lctx => lctx.erase x.fvarId!)
lctx
@[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr :=
if !e.hasMVar then pure e else checkCache e f
@[inline] private def getMCtx : M MetavarContext := do
s ← get; pure s.mctx
/-- Return free variables in `xs` that are in the local context `lctx` -/
private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr :=
xs.foldl
(fun scope x =>
if lctx.contains x.fvarId! then
scope.push x
else
scope)
#[]
/-- Execute `x` with an empty cache, and then restore the original cache. -/
@[inline] private def withFreshCache {α} (x : M α) : M α := do
cache ← modifyGet $ fun s => (s.cache, { s with cache := {} });
a ← x;
modify $ fun s => { s with cache := cache };
pure a
@[inline] private def abstractRangeAux (elimMVarDeps : Expr → M Expr) (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do
e ← elimMVarDeps e;
pure (e.abstractRange i xs)
private def mkAuxMVarType (elimMVarDeps : Expr → M Expr) (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do
e ← abstractRangeAux elimMVarDeps xs xs.size e;
xs.size.foldRevM
(fun i e =>
let x := xs.get! i;
match lctx.getFVar! x with
| LocalDecl.cdecl _ _ n type bi => do
type ← abstractRangeAux elimMVarDeps xs i type;
pure $ Lean.mkForall n bi type e
| LocalDecl.ldecl _ _ n type value => do
type ← abstractRangeAux elimMVarDeps xs i type;
value ← abstractRangeAux elimMVarDeps xs i value;
let e := mkLet n type value e;
match kind with
| MetavarKind.syntheticOpaque =>
-- See "Gruesome details" section in the beginning of the file
let e := e.liftLooseBVars 0 1;
pure $ mkForall n BinderInfo.default type e
| _ => pure e)
e
/--
Create an application `mvar ys` where `ys` are the free variables.
See "Gruesome details" in the beginning of the file for understanding
how let-decl free variables are handled. -/
private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr :=
xs.foldl
(fun e x =>
match kind with
| MetavarKind.syntheticOpaque => mkApp e x
| _ => if (lctx.getFVar! x).isLet then e else mkApp e x)
mvar
private def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) : M MVarId := do
s ← get;
let mvarId := s.ngen.curr;
modify $ fun s => { s with mctx := s.mctx.addExprMVarDecl mvarId Name.anonymous lctx localInsts type kind, ngen := s.ngen.next };
pure mvarId
/-- Return true iff some `e` in `es` depends on `fvarId` -/
private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool :=
es.any $ fun e => exprDependsOn mctx e fvarId
private partial def elimMVarDepsApp (elimMVarDepsAux : Expr → M Expr) (xs : Array Expr) : Expr → Array Expr → M Expr
| f, args =>
match f with
| Expr.mvar mvarId _ => do
let processDefault (newF : Expr) : M Expr := do {
if newF.isLambda then do
args ← args.mapM (visit elimMVarDepsAux);
elimMVarDepsAux $ newF.betaRev args.reverse
else if newF == f then do
args ← args.mapM (visit elimMVarDepsAux);
pure $ mkAppN newF args
else
elimMVarDepsApp newF args
};
mctx ← getMCtx;
match mctx.getExprAssignment? mvarId with
| some val => processDefault val
| _ =>
let mvarDecl := mctx.getDecl mvarId;
let mvarLCtx := mvarDecl.lctx;
let toRevert := getInScope mvarLCtx xs;
if toRevert.size == 0 then
processDefault f
else
let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind;
/- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`,
then `nestedFVars` is `#[x_1, ..., x_n]`.
In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment
```
?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n
```
where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`.
Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]`
-/
let continue (nestedFVars : Array Expr) : M Expr := do {
args ← args.mapM (visit elimMVarDepsAux);
preserve ← preserveOrder;
match collectDeps mctx mvarLCtx toRevert preserve with
| Except.error ex => throw ex
| Except.ok toRevert => do
let newMVarLCtx := reduceLocalContext mvarLCtx toRevert;
let newLocalInsts := mvarDecl.localInstances.filter $ fun inst => toRevert.all $ fun x => inst.fvar != x;
newMVarType ← mkAuxMVarType elimMVarDepsAux mvarLCtx toRevert newMVarKind mvarDecl.type;
newMVarId ← mkAuxMVar newMVarLCtx newLocalInsts newMVarType newMVarKind;
let newMVar := mkMVar newMVarId;
let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind;
match newMVarKind with
| MetavarKind.syntheticOpaque =>
modify $ fun s => { s with mctx := assignDelayed s.mctx newMVarId mvarLCtx (toRevert ++ nestedFVars) (mkAppN f nestedFVars) }
| _ =>
modify $ fun s => { s with mctx := assignExpr s.mctx mvarId result };
pure (mkAppN result args)
};
if !mvarDecl.kind.isSyntheticOpaque then
continue #[]
else match mctx.getDelayedAssignment? mvarId with
| none => continue #[]
| some { fvars := fvars, .. } => continue fvars
| _ => do
f ← visit elimMVarDepsAux f;
args ← args.mapM (visit elimMVarDepsAux);
pure (mkAppN f args)
private partial def elimMVarDepsAux (xs : Array Expr) : Expr → M Expr
| e@(Expr.proj _ _ s _) => do s ← visit elimMVarDepsAux s; pure (e.updateProj! s)
| e@(Expr.forallE _ d b _) => do d ← visit elimMVarDepsAux d; b ← visit elimMVarDepsAux b; pure (e.updateForallE! d b)
| e@(Expr.lam _ d b _) => do d ← visit elimMVarDepsAux d; b ← visit elimMVarDepsAux b; pure (e.updateLambdaE! d b)
| e@(Expr.letE _ t v b _) => do t ← visit elimMVarDepsAux t; v ← visit elimMVarDepsAux v; b ← visit elimMVarDepsAux b; pure (e.updateLet! t v b)
| e@(Expr.mdata _ b _) => do b ← visit elimMVarDepsAux b; pure (e.updateMData! b)
| e@(Expr.app _ _ _) => e.withApp $ fun f args => elimMVarDepsApp elimMVarDepsAux xs f args
| e@(Expr.mvar mvarId _) => elimMVarDepsApp elimMVarDepsAux xs e #[]
| e => pure e
partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr :=
if !e.hasMVar then
pure e
else
withFreshCache $ elimMVarDepsAux xs e
/--
Similar to `Expr.abstractRange`, but handles metavariables correctly.
It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not
contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`.
`elimMVarDeps` is defined later in this file. -/
@[inline] private def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do
e ← elimMVarDeps xs e;
pure (e.abstractRange i xs)
/--
Similar to `LocalContext.mkBinding`, but handles metavariables correctly.
If `usedOnly == false` then `forall` and `lambda` are created only for used variables. -/
@[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : M (Expr × Nat) := do
e ← abstractRange xs xs.size e;
xs.size.foldRevM
(fun i (p : Expr × Nat) =>
let (e, num) := p;
let x := xs.get! i;
match lctx.getFVar! x with
| LocalDecl.cdecl _ _ n type bi =>
if !usedOnly || e.hasLooseBVar 0 then do
type ← abstractRange xs i type;
if isLambda then
pure (Lean.mkLambda n bi type e, num + 1)
else
pure (Lean.mkForall n bi type e, num + 1)
else
pure (e.lowerLooseBVars 1 1, num)
| LocalDecl.ldecl _ _ n type value => do
if e.hasLooseBVar 0 then do
type ← abstractRange xs i type;
value ← abstractRange xs i value;
pure (mkLet n type value e, num + 1)
else
pure (e.lowerLooseBVars 1 1, num))
(e, 0)
end MkBinding
abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr :=
fun _ => MkBinding.elimMVarDeps xs e preserveOrder
def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : MkBindingM (Expr × Nat) :=
fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly false
@[inline] def mkLambda (xs : Array Expr) (e : Expr) : MkBindingM Expr := do
(e, _) ← mkBinding true xs e;
pure e
@[inline] def mkForall (xs : Array Expr) (e : Expr) : MkBindingM Expr := do
(e, _) ← mkBinding false xs e;
pure e
@[inline] def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MkBindingM (Expr × Nat) := do
mkBinding false xs e true
/--
`isWellFormed mctx lctx e` return true if
- All locals in `e` are declared in `lctx`
- All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/
partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool
| Expr.mdata _ e _ => isWellFormed e
| Expr.proj _ _ e _ => isWellFormed e
| e@(Expr.app f a _) => (e.hasExprMVar || e.hasFVar) && isWellFormed f && isWellFormed a
| e@(Expr.lam _ d b _) => (e.hasExprMVar || e.hasFVar) && isWellFormed d && isWellFormed b
| e@(Expr.forallE _ d b _) => (e.hasExprMVar || e.hasFVar) && isWellFormed d && isWellFormed b
| e@(Expr.letE _ t v b _) => (e.hasExprMVar || e.hasFVar) && isWellFormed t && isWellFormed v && isWellFormed b
| Expr.const _ _ _ => true
| Expr.bvar _ _ => true
| Expr.sort _ _ => true
| Expr.lit _ _ => true
| Expr.mvar mvarId _ =>
let mvarDecl := mctx.getDecl mvarId;
if mvarDecl.lctx.isSubPrefixOf lctx then true
else match mctx.getExprAssignment? mvarId with
| none => false
| some v => isWellFormed v
| Expr.fvar fvarId _ => lctx.contains fvarId
| Expr.localE _ _ _ _ => unreachable!
namespace LevelMVarToParam
structure Context :=
(paramNamePrefix : Name)
(alreadyUsedPred : Name → Bool)
structure State :=
(mctx : MetavarContext)
(paramNames : Array Name := #[])
(nextParamIdx : Nat)
abbrev M := ReaderT Context $ StateM State
partial def mkParamName : Unit → M Name
| _ => do
ctx ← read;
s ← get;
let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx;
if ctx.alreadyUsedPred newParamName then do
modify $ fun s => { s with nextParamIdx := s.nextParamIdx + 1 };
mkParamName ()
else do
modify $ fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName };
pure newParamName
partial def visitLevel : Level → M Level
| u@(Level.succ v _) => do v ← visitLevel v; pure (u.updateSucc v rfl)
| u@(Level.max v₁ v₂ _) => do v₁ ← visitLevel v₁; v₂ ← visitLevel v₂; pure (u.updateMax v₁ v₂ rfl)
| u@(Level.imax v₁ v₂ _) => do v₁ ← visitLevel v₁; v₂ ← visitLevel v₂; pure (u.updateIMax v₁ v₂ rfl)
| u@(Level.zero _) => pure u
| u@(Level.param _ _) => pure u
| u@(Level.mvar mvarId _) => do
s ← get;
match s.mctx.getLevelAssignment? mvarId with
| some v => visitLevel v
| none => do
p ← mkParamName ();
let p := mkLevelParam p;
modify $ fun s => { s with mctx := s.mctx.assignLevel mvarId p };
pure p
@[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr :=
if e.hasLevelMVar then f e else pure e
partial def main : Expr → M Expr
| e@(Expr.proj _ _ s _) => do s ← visit main s; pure (e.updateProj! s)
| e@(Expr.forallE _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateForallE! d b)
| e@(Expr.lam _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateLambdaE! d b)
| e@(Expr.letE _ t v b _) => do t ← visit main t; v ← visit main v; b ← visit main b; pure (e.updateLet! t v b)
| e@(Expr.app f a _) => do f ← visit main f; a ← visit main a; pure (e.updateApp! f a)
| e@(Expr.mdata _ b _) => do b ← visit main b; pure (e.updateMData! b)
| e@(Expr.const _ us _) => do us ← us.mapM visitLevel; pure (e.updateConst! us)
| e@(Expr.sort u _) => do u ← visitLevel u; pure (e.updateSort! u)
| e => pure e
end LevelMVarToParam
structure UnivMVarParamResult :=
(mctx : MetavarContext)
(newParamNames : Array Name)
(nextParamIdx : Nat)
(expr : Expr)
def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1)
: UnivMVarParamResult :=
let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx };
{ mctx := mctx,
newParamNames := s.paramNames,
nextParamIdx := s.nextParamIdx,
expr := e }
end MetavarContext
end Lean
|
38534c30098475471c14fb0a55d8beae7e13c609 | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/pseudo_normed_group/basic.lean | b609fb526fe87c13d6f6d6eabf78e09b4bd00801 | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,291 | lean | import data.real.nnreal
import algebra.group.hom
import algebra.big_operators
import algebra.module.pi
import topology.basic
import hacks_and_tricks.type_pow
/-!
# Pseudo-normed groups
This file contains definitions and basic properties of pseudo-normed (abelian additive) groups.
See for example the comments after the proof of Proposition 9.10 of `analytic.pdf`, although we do
not work in an arbitrary topos.
## Main definitions
`pseudo_normed_group` -- a pseudo-normed abelian additive group
## Implementation issues
Right now we let the M_c be subsets of M. An alternative approach would be to have
them all as types; this is more convenient for some parts of the argument.
-/
noncomputable theory
open_locale nnreal big_operators
local attribute [instance] type_pow
/-- A pseudo-normed group is an abelian group `M`
together with an increasing filtration indexed by `ℝ≥0` of subsets `M_{≤c}`
containing `0` and closed under negation,
and such that if `x₁ ∈ M_{≤c₁}` and `x₂ ∈ M_{c₂}`, then `x₁ + x₂ ∈ M_{≤c₁ + c₂}`.
See also the comments after Proposition 9.10 on p66 in [Analytic].
Implementation details:
* In [Analytic], the filtration is indexed by *positive* real numbers (excluding) `0`,
whereas this definition includes `0` in the indexing set.
* We do not ask for the filtration to be exhaustive (similar to [Analytic]),
which is convenient, because it means that `M₁ →+ M₂` is naturally a pseudo-normed group
if `M₁` and `M₂` are pseudo-normed groups. -/
class pseudo_normed_group (M : Type*) :=
[to_add_comm_group : add_comm_group M]
(filtration [] : ℝ≥0 → set M)
(filtration_mono : ∀ ⦃c₁ c₂⦄, c₁ ≤ c₂ → filtration c₁ ⊆ filtration c₂)
(zero_mem_filtration : ∀ c, (0:M) ∈ filtration c)
(neg_mem_filtration : ∀ ⦃c x⦄, x ∈ filtration c → (-x) ∈ filtration c)
(add_mem_filtration : ∀ ⦃c₁ c₂ x₁ x₂⦄,
x₁ ∈ filtration c₁ → x₂ ∈ filtration c₂ → x₁ + x₂ ∈ filtration (c₁ + c₂))
/-- The additive commutative group instance underlying a pseudo-normed group. -/
add_decl_doc pseudo_normed_group.to_add_comm_group
open function
-- An alternative attempt at pseudo-normed groups,
-- that we might want to keep/switch to in the future
-- class pseudo_normed_group' (B_ : ℝ≥0 → Type*) (M : out_param Type*) :=
-- [to_add_comm_group : add_comm_group M]
-- [has_zero : Π r, has_zero (B_ r)]
-- [has_neg : Π r, has_neg (B_ r)]
-- (map : ∀ ⦃c₁ c₂⦄, c₁ ≤ c₂ → B_ c₁ → B_ c₂) -- rename
-- (incl : ∀ c, B_ c → M)
-- (incl_injective : ∀ c, injective (incl c))
-- (incl_zero : ∀ c, incl c 0 = 0)
-- (incl_neg : ∀ {c} (f : B_ c), incl c (-f) = - (incl c f))
-- (incl_map : ∀ {c₁ c₂} (h : c₁ ≤ c₂), (incl c₂) ∘ (map h) = (incl c₁))
-- (B_add {c₁ c₂} : B_ c₁ → B_ c₂ → B_ (c₁ + c₂))
-- (incl_add {c₁ c₂} (f : B_ c₁) (g : B_ c₂) : incl _ (B_add f g) = incl _ f + incl _ g)
-- (map_refl {c} : map (le_refl c) = id)
-- (map_trans {c₁ c₂ c₃} (h1 : c₁ ≤ c₂) (h2 : c₂ ≤ c₃) : map (h1.trans h2) = map h2 ∘ map h1)
/-
class topological_pseudo_normed_group' (B_ : ℝ≥0 → Type*) (M : Type*)
extends pseudo_normed_group' B_ M :=
[is_top_space : Π r, topological_space (B_ r)]
-/
/-
Thought by Johan:
Maybe we want both defintions above, and write a bit of glue to move between them.
Both seem useful for different bits of what we want to do.
-/
attribute [instance] pseudo_normed_group.to_add_comm_group
namespace pseudo_normed_group
variables {M : Type*} [pseudo_normed_group M]
instance (c : ℝ≥0) : has_zero (filtration M c) := ⟨⟨0, zero_mem_filtration _⟩⟩
instance (c : ℝ≥0) : has_neg (filtration M c) := ⟨λ x, ⟨-x, neg_mem_filtration x.2⟩⟩
/-- Bounded uncurried addition for pseudo-normed groups. -/
def add' {c₁ c₂} (x : (filtration M c₁) × (filtration M c₂)) : filtration M (c₁ + c₂) :=
⟨(x.1 + x.2 : M), add_mem_filtration x.1.2 x.2.2⟩
@[simp] lemma add'_eq {c₁ c₂ : ℝ≥0} (x : (filtration M c₁) × (filtration M c₂)) :
(add' x : M) = x.1 + x.2 := rfl
/-- Bounded negation for pseudo-normed groups. -/
def neg' {c} (x : filtration M c) : filtration M c :=
⟨(-x : M), neg_mem_filtration x.2⟩
@[simp] lemma neg'_eq {c : ℝ≥0} (x : filtration M c) :
(neg' x : M) = -x := rfl
lemma sub_mem_filtration ⦃c₁ c₂ x₁ x₂⦄ (h₁ : x₁ ∈ filtration M c₁) (h₂ : x₂ ∈ filtration M c₂) :
x₁ - x₂ ∈ filtration M (c₁ + c₂) :=
by { rw [sub_eq_add_neg], exact add_mem_filtration h₁ (neg_mem_filtration h₂) }
lemma neg_mem_filtration_iff (c x) : -x ∈ filtration M c ↔ x ∈ filtration M c :=
⟨λ h, by { rw [← neg_neg x], exact neg_mem_filtration h }, λ h, neg_mem_filtration h⟩
lemma sum_mem_filtration {ι : Type*} (x : ι → M) (c : ι → ℝ≥0) (s : finset ι)
(h : ∀ i ∈ s, x i ∈ filtration M (c i)) :
(∑ i in s, x i) ∈ filtration M (∑ i in s, (c i)) :=
begin
classical,
revert h, apply finset.induction_on s; clear s,
{ intro, simpa only [finset.sum_empty] using zero_mem_filtration _ },
{ intros i s his IH h,
rw [finset.sum_insert his, finset.sum_insert his],
apply add_mem_filtration (h _ _) (IH _),
{ exact finset.mem_insert_self i s },
{ intros j hj, apply h, exact finset.mem_insert_of_mem hj } }
end
lemma nat_smul_mem_filtration (n : ℕ) (m : M) (c : ℝ≥0) (h : m ∈ filtration M c) :
(n • m) ∈ filtration M (n * c) :=
begin
induction n with n ih, { simpa only [zero_smul] using zero_mem_filtration _ },
simp only [nat.succ_eq_add_one, add_smul, one_smul, nat.cast_succ, add_mul, one_mul],
exact add_mem_filtration ih h,
end
lemma int_smul_mem_filtration (n : ℤ) (m : M) (c : ℝ≥0) (h : m ∈ filtration M c) :
(n • m) ∈ filtration M (n.nat_abs * c) :=
begin
by_cases hn : 0 ≤ n,
{ lift n to ℕ using hn,
simp only [int.nat_abs_of_nat, ← gsmul_eq_smul, gsmul_coe_nat, nsmul_eq_smul],
exact pseudo_normed_group.nat_smul_mem_filtration n m c h },
{ push_neg at hn, rw ← neg_pos at hn,
lift -n to ℕ using hn.le with k hk,
rw [← neg_neg n, int.nat_abs_neg, ← hk, int.nat_abs_of_nat, neg_smul],
apply neg_mem_filtration,
simp only [neg_smul, ← gsmul_eq_smul, gsmul_coe_nat, nsmul_eq_smul],
exact pseudo_normed_group.nat_smul_mem_filtration k m c h }
end
@[simps] def level {M₁ M₂ : Type*} [pseudo_normed_group M₁] [pseudo_normed_group M₂]
(f : M₁ → M₂) (strict : ∀ ⦃c x⦄, x ∈ filtration M₁ c → f x ∈ filtration M₂ c)
(c : ℝ≥0) : filtration M₁ c → filtration M₂ c :=
λ x, ⟨f x, strict x.2⟩
section pi
variables
instance pi {ι : Type*} (M : ι → Type*) [Π i, pseudo_normed_group (M i)] :
pseudo_normed_group (Π i, M i) :=
{ filtration := λ c, { x | ∀ i, x i ∈ filtration (M i) c },
filtration_mono := λ c₁ c₂ h x hx i, filtration_mono h (hx i),
zero_mem_filtration := λ c i, zero_mem_filtration _,
neg_mem_filtration := λ c x h i, neg_mem_filtration (h i),
add_mem_filtration := λ c₁ c₂ x₁ x₂ h₁ h₂ i, add_mem_filtration (h₁ i) (h₂ i) }
lemma mem_filtration_pi {ι : Type*} (M : ι → Type*) [Π i, pseudo_normed_group (M i)]
(c : ℝ≥0) (x : Π i, M i) :
x ∈ filtration (Π i, M i) c ↔ ∀ i, x i ∈ filtration (M i) c := iff.rfl
/-- The equivalence between `(Π i, M i)_c` and `Π i, (M i)_c`. -/
@[simps]
def filtration_pi_equiv {ι : Type*} (M : ι → Type*) [Π i, pseudo_normed_group (M i)] (c : ℝ≥0) :
filtration (Π i, M i) c ≃ Π i, filtration (M i) c :=
{ to_fun := λ x i, ⟨x.1 i, x.2 i⟩,
inv_fun := λ x, ⟨λ i, x i, λ i, (x i).2⟩,
left_inv := by { rintro ⟨x, hx⟩, refl },
right_inv := by { intro x, ext, refl } }
end pi
section prod
variables (M₁ M₂ : Type*) [pseudo_normed_group M₁] [pseudo_normed_group M₂]
instance prod :
pseudo_normed_group (M₁ × M₂) :=
{ filtration := λ c, { x | x.1 ∈ filtration M₁ c ∧ x.2 ∈ filtration M₂ c },
filtration_mono := λ c₁ c₂ h x hx, ⟨filtration_mono h hx.1, filtration_mono h hx.2⟩,
zero_mem_filtration := λ c, ⟨zero_mem_filtration _, zero_mem_filtration _⟩,
neg_mem_filtration := λ c x h, ⟨neg_mem_filtration h.1, neg_mem_filtration h.2⟩,
add_mem_filtration := λ c₁ c₂ x₁ x₂ h₁ h₂,
⟨add_mem_filtration h₁.1 h₂.1, add_mem_filtration h₁.2 h₂.2⟩ }
lemma mem_filtration_prod (c : ℝ≥0) (x : M₁ × M₂) :
x ∈ filtration (M₁ × M₂) c ↔ x.1 ∈ filtration M₁ c ∧ x.2 ∈ filtration M₂ c := iff.rfl
/-- The equivalence between `(M₁ × M₂)_c` and `(M₁)_c × (M₂)_c`. -/
@[simps]
def filtration_prod_equiv (c : ℝ≥0) :
filtration (M₁ × M₂) c ≃ filtration M₁ c × filtration M₂ c :=
{ to_fun := λ x, (⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩),
inv_fun := λ x, ⟨(x.1, x.2), ⟨x.1.2, x.2.2⟩⟩,
left_inv := by { rintro ⟨⟨x₁, x₂⟩, hx⟩, refl },
right_inv := by { rintro ⟨x₁, x₂⟩, ext; refl } }
end prod
/-- The natural inclusion `filtration M c₁ → filtration M c₂`,
for a pseudo-normed group `M`, and `c₁ ≤ c₂`. -/
def cast_le {c₁ c₂ : ℝ≥0} [h : fact (c₁ ≤ c₂)] (x : filtration M c₁) :
filtration M c₂ :=
⟨x, filtration_mono h.out x.2⟩
@[simp] lemma coe_cast_le {c₁ c₂ : ℝ≥0} [h : fact (c₁ ≤ c₂)] (x : filtration M c₁) :
((cast_le x : filtration M c₂) : M) = x := rfl
lemma injective_cast_le (c₁ c₂ : ℝ≥0) [fact (c₁ ≤ c₂)] :
function.injective (cast_le : filtration M c₁ → filtration M c₂) :=
λ x y h, subtype.coe_injective $
by simpa only [coe_cast_le] using congr_arg (coe : filtration M c₂ → M) h
variables (M)
end pseudo_normed_group
open pseudo_normed_group
namespace add_monoid_hom
variables {M M₁ M₂ M₃ : Type*}
variables [pseudo_normed_group M] [pseudo_normed_group M₁]
variables [pseudo_normed_group M₂] [pseudo_normed_group M₃]
instance : pseudo_normed_group (M₁ →+ M₂) :=
{ filtration := λ N, { f | ∀ ⦃c⦄ ⦃x : M₁⦄, x ∈ filtration M₁ c → f x ∈ filtration M₂ (N * c) },
filtration_mono := λ N₁ N₂ h f hf c x hx, filtration_mono (mul_le_mul_right' h c) (hf hx),
zero_mem_filtration := λ N c x hx, zero_mem_filtration _,
neg_mem_filtration := λ N f hf c x hx, neg_mem_filtration $ hf hx,
add_mem_filtration := λ N₁ N₂ f₁ f₂ hf₁ hf₂ c x hx,
by { rw add_mul, apply add_mem_filtration (hf₁ hx) (hf₂ hx) },
.. add_monoid_hom.add_comm_group }
lemma comp_mem_filtration {g f cg cf}
(hg : g ∈ filtration (M₂ →+ M₃) cg) (hf : f ∈ filtration (M₁ →+ M₂) cf) :
g.comp f ∈ filtration (M₁ →+ M₃) (cg * cf) :=
λ c x hx, by { rw mul_assoc, exact hg (hf hx) }
@[simp] lemma id_mem_filtration (c : ℝ≥0) (hc : 1 ≤ c) : id M ∈ filtration (M →+ M) c :=
λ c' x hx, by refine filtration_mono _ hx;
calc c' = 1 * c' : by rw one_mul
... ≤ c * c' : mul_le_mul_right' hc c'
-- move this, maybe it already exists?
/-- The additive monoid homomorphism into a product of additive monoids,
constructed from a family of monoid homomorphisms into the factors. -/
@[simps {rhs_md:=semireducible, fully_applied:=ff}]
def mk_to_pi {M₁} [add_monoid M₁] {ι : Type*} {M : ι → Type*} [Π i, add_monoid (M i)]
(f : Π i, M₁ →+ (M i)) :
M₁ →+ (Π i, M i) :=
{ to_fun := λ v i, f i v,
map_zero' := by { simp only [map_zero], refl },
map_add' := by { intros, simp only [map_add], refl } }
lemma mk_to_pi_mem_filtration {ι : Type*} {M : ι → Type*}
[Π i, pseudo_normed_group (M i)] (f : Π i, M₁ →+ (M i))
{c} (hfc : ∀ i, f i ∈ filtration (M₁ →+ (M i)) c) :
mk_to_pi f ∈ filtration (M₁ →+ (Π i, M i)) c :=
λ c' x h i, hfc i h
lemma eval_mem_filtration {ι : Type*} (M : ι → Type*) [Π i, pseudo_normed_group (M i)]
(i : ι) (c : ℝ≥0) (hc : 1 ≤ c) :
(pi.eval_add_monoid_hom M i) ∈ filtration ((Π i, M i) →+ M i) c :=
λ c' x hx, by refine filtration_mono _ (hx i);
calc c' = 1 * c' : by rw one_mul
... ≤ c * c' : mul_le_mul_right' hc c'
/-- The additive monoid homomorphism out of a finite product of additive monoids,
constructed from a family of monoid homomorphisms out of the factors. -/
def mk_from_pi {ι : Type*} [fintype ι] {M : ι → Type*} {M₂}
[Π i, add_monoid (M i)] [add_comm_monoid M₂] (f : Π i, (M i) →+ M₂) :
(Π i, M i) →+ M₂ :=
∑ i, (f i).comp (pi.eval_add_monoid_hom M i)
@[simp] lemma mk_from_pi_apply {ι : Type*} [fintype ι] {M : ι → Type*} [Π i, add_comm_monoid (M i)]
(f : Π i, M i →+ M₂) (x : Π i, M i) :
mk_from_pi f x = (∑ i, f i (x i)) :=
begin
show add_monoid_hom.eval x (mk_from_pi f) = _,
simp only [mk_from_pi, add_monoid_hom.map_sum],
refl
end
@[simp] lemma coe_mk_from_pi {ι : Type*} [fintype ι] {M : ι → Type*} [Π i, add_comm_monoid (M i)]
(f : Π i, M i →+ M₂) :
⇑(mk_from_pi f) = ∑ i, (f i ∘ pi.eval_add_monoid_hom M i) :=
by { ext x, rw [@mk_from_pi_apply M₂ _ ι _ M _ f x, fintype.sum_apply], refl }
lemma mk_from_pi_mem_filtration {ι : Type*} [fintype ι] {M : ι → Type*}
[Π i, pseudo_normed_group (M i)] (f : Π i, (M i) →+ M₂)
{c : ι → ℝ≥0} (hfc : ∀ i, f i ∈ filtration ((M i) →+ M₂) (c i)) :
(mk_from_pi f) ∈ filtration ((Π i, M i) →+ M₂) (∑ i, c i) :=
λ c' x h,
begin
rw [finset.sum_mul, @mk_from_pi_apply M₂ _ ι _ M _ f x],
refine sum_mem_filtration _ _ _ _,
rintro i -,
exact hfc i (h i)
end
lemma const_smul_hom_nat_mem_filtration (n : ℕ) (c : ℝ≥0) (h : ↑n ≤ c) :
const_smul_hom M n ∈ filtration (M →+ M) c :=
λ c' x hx, by simpa only [const_smul_hom_apply]
using filtration_mono (mul_le_mul_right' h c') (nat_smul_mem_filtration _ _ _ hx)
lemma const_smul_hom_int_mem_filtration (n : ℤ) (c : ℝ≥0) (h : ↑(n.nat_abs) ≤ c) :
const_smul_hom M n ∈ filtration (M →+ M) c :=
λ c' x hx, by simpa only [const_smul_hom_apply, smul_eq_mul]
using filtration_mono (mul_le_mul_right' h c') (int_smul_mem_filtration _ _ _ hx)
end add_monoid_hom
namespace pseudo_normed_group
section splittable
class splittable (M : Type*) [pseudo_normed_group M] (N : ℕ) (d : ℝ≥0) :=
(exists_sum : ∀ (c : ℝ≥0) (x : M) (hx : x ∈ filtration M c),
∃ y : fin N → M, (x = ∑ i, y i) ∧ (∀ i, y i ∈ filtration M (c/N + d)))
variables {M : Type*} [pseudo_normed_group M] (N : ℕ) (d : ℝ≥0) [splittable M N d]
lemma exists_sum (c : ℝ≥0) (x : M) (hx : x ∈ filtration M c) :
∃ y : fin N → M, (x = ∑ i, y i) ∧ (y ∈ filtration (M^N) (c/N + d)) :=
splittable.exists_sum c x hx
instance splittable_pi {ι : Type*} (M : ι → Type*) [Π i, pseudo_normed_group (M i)]
(N : ℕ) (d : ℝ≥0) [∀ i, splittable (M i) N d] :
splittable (Π i, M i) N d :=
{ exists_sum := λ c x hx,
begin
have := λ i, exists_sum N d c (x i) (hx i),
choose y hy1 hy2 using this,
refine ⟨swap y, _, swap hy2⟩,
ext i, rw [hy1], symmetry, convert finset.sum_apply i _ _,
end }
end splittable
end pseudo_normed_group
-- #lint- only unused_arguments def_lemma doc_blame
|
4f80ab17c77e4bc4a2cc734a9196b388a764a078 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/list/basic.lean | 735ee570ebdb93031eab63684018852c043e05dc | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 192,760 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import control.monad.basic
import data.nat.basic
/-!
# Basic properties of lists
-/
open function nat
namespace list
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
attribute [inline] list.head
instance : is_left_id (list α) has_append.append [] :=
⟨ nil_append ⟩
instance : is_right_id (list α) has_append.append [] :=
⟨ append_nil ⟩
instance : is_associative (list α) has_append.append :=
⟨ append_assoc ⟩
theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem cons_ne_self (a : α) (l : list α) : a::l ≠ l :=
mt (congr_arg length) (nat.succ_ne_self _)
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
@[simp] theorem cons_injective {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
cons_injective.eq_iff
theorem exists_cons_of_ne_nil {l : list α} (h : l ≠ nil) : ∃ b L, l = b :: L :=
by { induction l with c l', contradiction, use [c,l'], }
/-! ### mem -/
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, or.inl⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem _root_.decidable.list.eq_or_ne_mem_of_mem [decidable_eq α]
{a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
decidable.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} : a ∈ b :: l → a = b ∨ (a ≠ b ∧ a ∈ l) :=
by classical; exact decidable.list.eq_or_ne_mem_of_mem
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] :=
by intro e; rw e at h; cases h
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih, {cases h}, rcases h with rfl | h,
{ exact ⟨[], l, rfl⟩ },
{ rcases ih h with ⟨s, t, rfl⟩,
exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{cases h},
{rcases h with rfl | h,
{exact or.inl rfl},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) :
∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{cases h},
{cases (eq_or_mem_of_mem_cons h) with h h,
{exact ⟨c, mem_cons_self _ _, h.symm⟩},
{rcases ih h with ⟨a, ha₁, ha₂⟩,
exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} :
(∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) :=
begin
split,
{ assume H j hj,
exact H (f j) (mem_map_of_mem f hj) },
{ assume H i hi,
rcases mem_map.1 hi with ⟨j, hj, ji⟩,
rw ← ji,
exact H j hj }
end
@[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] :=
⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff],
λ h, h.symm ▸ rfl⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right,
exists_or_distrib, exists_eq_left]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp]
theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} :
b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) :
b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
lemma bind_map {g : α → list β} {f : β → γ} :
∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f)
| [] := rfl
| (a::l) := by simp only [cons_bind, map_append, bind_map l]
lemma map_bind (g : β → list γ) (f : α → β) :
∀ l : list α, (list.map f l).bind g = l.bind (λ a, g (f a))
| [] := rfl
| (a::l) := by simp only [cons_bind, map_cons, map_bind l]
/-- If each element of a list can be lifted to some type, then the whole list can be lifted to this
type. -/
instance [h : can_lift α β] : can_lift (list α) (list β) :=
{ coe := list.map h.coe,
cond := λ l, ∀ x ∈ l, can_lift.cond β x,
prf := λ l H,
begin
induction l with a l ihl, { exact ⟨[], rfl⟩ },
rcases ihl (λ x hx, H x (or.inr hx)) with ⟨l, rfl⟩,
rcases can_lift.prf a (H a (or.inl rfl)) with ⟨a, rfl⟩,
exact ⟨a :: l, rfl⟩
end}
/-! ### length -/
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
@[simp] lemma length_singleton (a : α) : length [a] = 1 := rfl
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] :=
λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1)
theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l :=
λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0
theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] :=
⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩
lemma exists_mem_of_ne_nil (l : list α) (h : l ≠ []) : ∃ x, x ∈ l :=
exists_mem_of_length_pos (length_pos_of_ne_nil h)
theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] :=
⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩
lemma exists_of_length_succ {n} :
∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t
| [] H := absurd H.symm $ succ_ne_zero n
| (h :: t) H := ⟨h, t, rfl⟩
@[simp] lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α :=
begin
split,
{ intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl },
{ intros hα l1 l2 hl, induction l1 generalizing l2; cases l2,
{ refl }, { cases hl }, { cases hl },
congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl }
end
@[simp] lemma length_injective [subsingleton α] : injective (length : list α → ℕ) :=
length_injective_iff.mpr $ by apply_instance
/-! ### set-theoretic notation of lists -/
lemma empty_eq : (∅ : list α) = [] := by refl
lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl
lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) :
has_insert.insert x l = x :: l :=
if_neg h
lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) :
has_insert.insert x l = l :=
if_pos h
lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] :=
by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] }
/-! ### bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
theorem forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : list α},
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
ball_cons
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a :=
by simp only [mem_singleton, forall_eq]
theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_append, or_imp_distrib, forall_and_distrib]
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x.
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (mem_cons_self _ _) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, left, exact px end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
/-! ### list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
@[simp] theorem append_subset_iff {l₁ l₂ l : list α} :
l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l :=
begin
split,
{ intro h, simp only [subset_def] at *, split; intros; simp* },
{ rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 }
end
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ :=
λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩
theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) :
map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ :=
begin
refine ⟨_, map_subset f⟩, intros h2 x hx,
rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩,
cases h hxx', exact hx'
end
/-! ### append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
@[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: l := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and]
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true,
true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left']
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { rw nil_append, split,
{ rintro rfl, left, exact ⟨_, rfl, rfl⟩ },
{ rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } },
case cons : a as ih {
cases c,
{ simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'],
exact eq_comm },
{ simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left,
exists_and_distrib_left] } }
end
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj :
∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) :
s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_right h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_left' h rfl
theorem append_right_injective (s : list α) : function.injective (λ t, s ++ t) :=
λ t₁ t₂, append_left_cancel
theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
(append_right_injective s).eq_iff
theorem append_left_injective (t : list α) : function.injective (λ s, s ++ t) :=
λ s₁ s₂, append_right_cancel
theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
(append_left_injective t).eq_iff
theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β}
(h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ :=
begin
have := h, rw [← take_append_drop (length s₁) l] at this ⊢,
rw map_append at this,
refine ⟨_, _, rfl, append_inj this _⟩,
rw [length_map, length_take, min_eq_left],
rw [← length_map f l, h, length_append],
apply nat.le_add_right
end
/-! ### repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n ↔ n ≠ 0 ∧ b = a
| 0 := by simp
| (n + 1) := by simp [mem_repeat]
theorem eq_of_mem_repeat {a b : α} {n} (h : b ∈ repeat a n) : b = a :=
(mem_repeat.1 h).2
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂;
unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n :=
by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) :
b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
@[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n :=
by induction n; [refl, simp only [*, repeat, map]]; split; refl
@[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred :=
by cases n; refl
@[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α :=
by induction n; [refl, simp only [*, repeat, join, append_nil]]
lemma repeat_left_injective {n : ℕ} (hn : n ≠ 0) :
function.injective (λ a : α, repeat a n) :=
λ a b h, (eq_repeat.1 h).2 _ $ mem_repeat.2 ⟨hn, rfl⟩
lemma repeat_left_inj {a b : α} {n : ℕ} (hn : n ≠ 0) :
repeat a n = repeat b n ↔ a = b :=
(repeat_left_injective hn).eq_iff
@[simp] lemma repeat_left_inj' {a b : α} :
∀ {n}, repeat a n = repeat b n ↔ n = 0 ∨ a = b
| 0 := by simp
| (n + 1) := (repeat_left_inj n.succ_ne_zero).trans $ by simp only [n.succ_ne_zero, false_or]
lemma repeat_right_injective (a : α) : function.injective (repeat a) :=
function.left_inverse.injective (length_repeat a)
@[simp] lemma repeat_right_inj {a : α} {n m : ℕ} :
repeat a n = repeat a m ↔ n = m :=
(repeat_right_injective a).eq_iff
/-! ### pure -/
@[simp] theorem mem_pure {α} (x y : α) :
x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret]
/-! ### bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
-- TODO: duplicate of a lemma in core
theorem bind_append (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
@[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x :=
append_nil (f x)
@[simp] theorem bind_singleton' (l : list α) : l.bind (λ x, [x]) = l := bind_pure l
theorem map_eq_bind {α β} (f : α → β) (l : list α) : map f l = l.bind (λ x, [f x]) :=
by { transitivity, rw [← bind_singleton' l, bind_map], refl }
theorem bind_assoc {α β} (l : list α) (f : α → list β) (g : β → list γ) :
(l.bind f).bind g = l.bind (λ x, (f x).bind g) :=
by induction l; simp *
/-! ### concat -/
theorem concat_nil (a : α) : concat [] a = [a] := rfl
theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp only [*, concat]; split; refl
theorem init_eq_of_concat_eq {a : α} {l₁ l₂ : list α} : concat l₁ a = concat l₂ a → l₁ = l₂ :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact append_right_cancel h
end
theorem last_eq_of_concat_eq {a b : α} {l : list α} : concat l a = concat l b → a = b :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact head_eq_of_cons_eq (append_left_cancel h)
end
theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by simp
theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by simp
theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp only [concat_eq_append, length_append, length]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by simp
/-! ### reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]],
(aux l nil).symm
theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ :=
by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]];
refl
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
by simp only [reverse_cons, concat_eq_append]
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; [rw [nil_append, reverse_nil, append_nil],
simp only [*, cons_append, reverse_cons, append_assoc]]
theorem reverse_concat (l : list α) (a : α) : reverse (concat l a) = a :: reverse l :=
by rw [concat_eq_append, reverse_append, reverse_singleton, singleton_append]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
@[simp] theorem reverse_involutive : involutive (@reverse α) :=
λ l, reverse_reverse l
@[simp] theorem reverse_injective : injective (@reverse α) :=
reverse_involutive.injective
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
lemma reverse_eq_iff {l l' : list α} :
l.reverse = l' ↔ l = l'.reverse :=
reverse_involutive.eq_iff
@[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] :=
@reverse_inj _ l []
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp only [concat_eq_append, reverse_cons, reverse_reverse]
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; [refl, simp only [*, reverse_cons, length_append, length]]
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; [refl, simp only [*, map, reverse_cons, map_append]]
theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) :
map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) :=
by simp only [reverse_core_eq, map_append, map_reverse]
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff,
not_mem_nil, false_or, or_false, or_comm]]
@[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n :=
eq_repeat.2 ⟨by simp only [length_reverse, length_repeat],
λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩
/-! ### empty -/
attribute [simp] list.empty
lemma empty_iff_eq_nil {l : list α} : l.empty ↔ l = [] :=
list.cases_on l (by simp) (by simp)
/-! ### init -/
@[simp] theorem length_init : ∀ (l : list α), length (init l) = length l - 1
| [] := rfl
| [a] := rfl
| (a :: b :: l) :=
begin
rw init,
simp only [add_left_inj, length, succ_add_sub_one],
exact length_init (b :: l)
end
/-! ### last -/
@[simp] theorem last_cons {a : α} {l : list α} :
∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
by induction l;
[refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]]
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp only [concat_eq_append, last_append]
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem init_append_last : ∀ {l : list α} (h : l ≠ []), init l ++ [last l h] = l
| [] h := absurd rfl h
| [a] h := rfl
| (a::b::l) h :=
begin
rw [init, cons_append, last_cons (cons_ne_nil _ _) (cons_ne_nil _ _)],
congr,
exact init_append_last (cons_ne_nil b l)
end
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l
| [] h := absurd rfl h
| [a] h := or.inl rfl
| (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) }
lemma last_repeat_succ (a m : ℕ) :
(repeat a m.succ).last (ne_nil_of_length_eq_succ
(show (repeat a m.succ).length = m.succ, by rw length_repeat)) = a :=
begin
induction m with k IH,
{ simp },
{ simpa only [repeat_succ, last] }
end
/-! ### last' -/
@[simp] theorem last'_is_none :
∀ {l : list α}, (last' l).is_none ↔ l = []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_none (b::l)]
@[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_some (b::l)]
theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h
| [] x hx := false.elim $ by simpa using hx
| [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩
| (a::b::l) x hx :=
begin
rw last' at hx,
rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩,
use cons_ne_nil _ _,
rwa [last_cons]
end
theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l :=
let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _
theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l
| [] a ha := (option.not_mem_none a ha).elim
| [a] _ rfl := rfl
| (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] }
theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget
| [] := by simp [ilast, arbitrary]
| [a] := rfl
| [a, b] := rfl
| [a, b, c] := rfl
| (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)]
@[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α),
last' (l₁ ++ a :: l₂) = last' (a :: l₂)
| [] a l₂ := rfl
| [b] a l₂ := rfl
| (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons]
theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []),
last' (l₁ ++ l₂) = last' l₂
| [] hl₂ := by contradiction
| (b::l₂) _ := last'_append_cons l₁ b l₂
/-! ### head(') and tail -/
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l
| [] h := (option.not_mem_none _ h).elim
| (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl }
@[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) :
head (s ++ t) = head s :=
by {induction s, contradiction, refl}
theorem tail_append_singleton_of_ne_nil {a : α} {l : list α} (h : l ≠ nil) :
tail (l ++ [a]) = tail l ++ [a] :=
by { induction l, contradiction, rw [tail,cons_append,tail], }
theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l
| [] a h := by contradiction
| (b::l) a h := by { simp at h, simp [h] }
theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l
| [] h := by contradiction
| (a::l) h := rfl
theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
cons_head'_tail (head_mem_head' h)
lemma head_mem_self [inhabited α] {l : list α} (h : l ≠ nil) : l.head ∈ l :=
begin
have h' := mem_cons_self l.head l.tail,
rwa cons_head_tail h at h',
end
@[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl
lemma tail_append_of_ne_nil (l l' : list α) (h : l ≠ []) :
(l ++ l').tail = l.tail ++ l' :=
begin
cases l,
{ contradiction },
{ simp }
end
@[simp]
lemma nth_le_tail (l : list α) (i) (h : i < l.tail.length)
(h' : i + 1 < l.length := by simpa [←lt_sub_iff_right] using h) :
l.tail.nth_le i h = l.nth_le (i + 1) h' :=
begin
cases l,
{ cases h, },
{ simpa }
end
/-! ### Induction from the right -/
/-- Induction principle from the right for lists: if a property holds for the empty list, and
for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
@[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ rw reverse_cons, exact H1 _ _ ih }
end
/-- Bidirectional induction principle for lists: if a property holds for the empty list, the
singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to
prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it
can also be used to construct data. -/
def bidirectional_rec {C : list α → Sort*}
(H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : ∀ l, C l
| [] := H0
| [a] := H1 a
| (a :: b :: l) :=
let l' := init (b :: l), b' := last (b :: l) (cons_ne_nil _ _) in
have length l' < length (a :: b :: l), by { change _ < length l + 2, simp },
begin
rw ←init_append_last (cons_ne_nil b l),
have : C l', from bidirectional_rec l',
exact Hn a l' b' ‹C l'›
end
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] }
/-- Like `bidirectional_rec`, but with the list parameter placed first. -/
@[elab_as_eliminator] def bidirectional_rec_on {C : list α → Sort*}
(l : list α) (H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : C l :=
bidirectional_rec H0 H1 Hn l
/-! ### sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) :
l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih, {refl},
{ rw reverse_cons, exact sublist_append_of_sublist_left ih },
{ rw [reverse_cons, reverse_cons], exact ih.append_right [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff]
using h.reverse,
λ h, h.append_right l⟩
theorem sublist.append {l₁ l₂ r₁ r₂ : list α}
(hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ :=
(hl.append_right _).trans ((append_sublist_append_left _).2 hr)
theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (sublist.subset s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, h.subset (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ s.subset
@[simp] theorem sublist_nil_iff_eq_nil {l : list α} : l <+ [] ↔ l = [] :=
⟨eq_nil_of_sublist_nil, λ H, H ▸ sublist.refl _⟩
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h,
λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) :
l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/-! ### index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) :
index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp, priority 990]
theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih,
{ exact iff_of_true rfl (not_mem_nil _) },
simp only [length, mem_cons_iff, index_of_cons], split_ifs,
{ exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) },
{ simp only [h, false_or], rw ← ih, exact succ_inj' }
end
@[simp, priority 980]
theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih, {refl},
simp only [length, index_of_cons],
by_cases h : a = b, {rw if_pos h, exact nat.zero_le _},
rw if_neg h, exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, decidable.by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/-! ### nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_len_le hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
@[simp]
theorem nth_eq_none_iff : ∀ {l : list α} {n}, nth l n = none ↔ length l ≤ n :=
begin
intros, split,
{ intro h, by_contradiction h',
have h₂ : ∃ h, l.nth_le n h = l.nth_le n (lt_of_not_ge h') := ⟨lt_of_not_ge h', rfl⟩,
rw [← nth_eq_some, h] at h₂, cases h₂ },
{ solve_by_elim [nth_len_le] },
end
theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a :=
let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩
theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l
| (a :: l) 0 h := mem_cons_self _ _
| (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _)
theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l :=
let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _
theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a :=
⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩
theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a :=
mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm
lemma nth_zero (l : list α) : l.nth 0 = l.head' := by cases l; refl
lemma nth_injective {α : Type u} {xs : list α} {i j : ℕ}
(h₀ : i < xs.length)
(h₁ : nodup xs)
(h₂ : xs.nth i = xs.nth j) : i = j :=
begin
induction xs with x xs generalizing i j,
{ cases h₀ },
{ cases i; cases j,
case nat.zero nat.zero
{ refl },
case nat.succ nat.succ
{ congr, cases h₁,
apply xs_ih;
solve_by_elim [lt_of_succ_lt_succ] },
iterate 2
{ dsimp at h₂,
cases h₁ with _ _ h h',
cases h x _ rfl,
rw mem_iff_nth,
exact ⟨_, h₂.symm⟩ <|>
exact ⟨_, h₂⟩ } },
end
@[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f
| [] n := rfl
| (a :: l) 0 := rfl
| (a :: l) (n+1) := nth_map l n
theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) :=
option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl
/-- A version of `nth_le_map` that can be used for rewriting. -/
theorem nth_le_map_rev (f : α → β) {l n} (H) :
f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) :=
(nth_le_map f _ _).symm
@[simp] theorem nth_le_map' (f : α → β) {l n} (H) :
nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f _ _
/-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as
`hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make
such a rewrite, with `rw (nth_le_of_eq h)`. -/
lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) :
nth_le L i hi = nth_le L' i (h ▸ hi) :=
by { congr, exact h}
@[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) :
nth_le [a] n hn = a :=
have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn),
by subst hn0; refl
lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) :
L.nth_le 0 h = L.head :=
by { cases L, cases h, simp, }
lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂),
(l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂
| [] _ n hn₁ hn₂ := (nat.not_lt_zero _ hn₂).elim
| (a::l) _ 0 hn₁ hn₂ := rfl
| (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append];
exact nth_le_append _ _
lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ}
(h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length :=
begin
rw list.length_append at h₂,
convert (sub_lt_sub_iff_right' h₁).mpr h₂,
simp,
end
lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂),
(l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂)
| [] _ n h₁ h₂ := rfl
| (a :: l) _ (n+1) h₁ h₂ :=
begin
dsimp,
conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], },
rw nth_le_append_right (nat.lt_succ_iff.mp h₁),
end
@[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) :
(list.repeat a n).nth_le m h = a :=
eq_of_mem_repeat (nth_le_mem _ _ _)
lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) :
(l₁ ++ l₂).nth n = l₁.nth n :=
have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn
(by rw length_append; exact nat.le_add_right _ _),
by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append]
lemma nth_append_right {l₁ l₂ : list α} {n : ℕ} (hn : l₁.length ≤ n) :
(l₁ ++ l₂).nth n = l₂.nth (n - l₁.length) :=
begin
by_cases hl : n < (l₁ ++ l₂).length,
{ rw [nth_le_nth hl, nth_le_nth, nth_le_append_right hn] },
{ rw [nth_len_le (le_of_not_lt hl), nth_len_le],
rw [not_lt, length_append] at hl,
exact le_sub_of_add_le_left' hl }
end
lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []),
last l h = l.nth_le (l.length - 1) (nat.sub_lt (length_pos_of_ne_nil h) one_pos)
| [] h := rfl
| [a] h := by rw [last_singleton, nth_le_singleton]
| (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)],
refl, exact cons_ne_nil b l }
@[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a
| [] a := rfl
| (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length]
lemma nth_le_cons_length (x : α) (xs : list α) (n : ℕ) (h : n = xs.length) :
(x :: xs).nth_le n (by simp [h]) = (x :: xs).last (cons_ne_nil x xs) :=
begin
rw last_eq_nth_le,
congr,
simp [h]
end
@[ext]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa;
simp only [aa, ext (λn, h (n+1))]; split; refl
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂)
(h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], }
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} :
∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b;
simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l]
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 :
∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i :=
by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1);
exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
lemma index_of_inj [decidable_eq α] {l : list α} {x y : α}
(hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y :=
⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) =
nth_le l (index_of y l) (index_of_lt_length.2 hy),
by simp only [h],
by simpa only [index_of_nth_le],
λ h, by subst h⟩
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (nat.not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
lemma nth_le_reverse' (l : list α) (n : ℕ) (hn : n < l.reverse.length) (hn') :
l.reverse.nth_le n hn = l.nth_le (l.length - 1 - n) hn' :=
begin
rw eq_comm,
convert nth_le_reverse l.reverse _ _ _ using 1,
{ simp },
{ simpa }
end
lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) :
l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] :=
begin
refine ext_le (by convert h) (λ n h₁ h₂, _),
simp only [nth_le_singleton],
congr,
exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂)
end
lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) :
∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) =
l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l)
lemma modify_nth_tail_modify_nth_tail_le
{f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) :
(l.modify_nth_tail f n).modify_nth_tail g m =
l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n :=
begin
rcases le_iff_exists_add.1 h with ⟨m, rfl⟩,
rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail]
end
lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) :
(l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n :=
by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl
lemma modify_nth_tail_id :
∀n (l:list α), l.modify_nth_tail id n = l
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m;
simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj,
not_false_iff]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp only [update_nth_eq_modify_nth, modify_nth_length]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp only [nth_modify_nth, if_pos]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp only [nth_modify_nth, if_neg h, id_map']
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h]
@[simp] lemma update_nth_nil (n : ℕ) (a : α) : [].update_nth n a = [] := rfl
@[simp] lemma update_nth_succ (x : α) (xs : list α) (n : ℕ) (a : α) :
(x :: xs).update_nth n.succ a = x :: xs.update_nth n a := rfl
lemma update_nth_comm (a b : α) : Π {n m : ℕ} (l : list α) (h : n ≠ m),
(l.update_nth n a).update_nth m b = (l.update_nth m b).update_nth n a
| _ _ [] _ := by simp
| 0 0 (x :: t) h := absurd rfl h
| (n + 1) 0 (x :: t) h := by simp [list.update_nth]
| 0 (m + 1) (x :: t) h := by simp [list.update_nth]
| (n + 1) (m + 1) (x :: t) h := by { simp only [update_nth, true_and, eq_self_iff_true],
exact update_nth_comm t (λ h', h $ nat.succ_inj'.mpr h'), }
@[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α)
(h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a :=
by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at *
@[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α)
(hj : j < (l.update_nth i a).length) :
(l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) :=
by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth]
lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α}
(h : a ∈ l.update_nth n b), a ∈ l ∨ a = b
| [] n a b h := false.elim h
| (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim
or.inr (or.inl ∘ mem_cons_of_mem _)
| (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim
(λ h, h ▸ or.inl (mem_cons_self _ _))
(λ h, (mem_or_eq_of_mem_update_nth h).elim
(or.inl ∘ mem_cons_of_mem _) or.inr)
section insert_nth
variable {a : α}
@[simp] lemma insert_nth_zero (s : list α) (x : α) : insert_nth 0 x s = x :: s := rfl
@[simp] lemma insert_nth_succ_nil (n : ℕ) (a : α) : insert_nth (n + 1) a [] = [] := rfl
@[simp] lemma insert_nth_succ_cons (s : list α) (hd x : α) (n : ℕ) :
insert_nth (n + 1) x (hd :: s) = hd :: (insert_nth n x s) := rfl
lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1
| 0 as h := rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h)
lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l :=
by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same];
from modify_nth_tail_id _ _
lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → n ≤ m →
insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n
| 0 0 [] has _ := (lt_irrefl _ has).elim
| 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth]
| 0 (m+1) (a::as) has hmn := rfl
| (n+1) (m+1) (a::as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1)
| n 0 (a :: as) has hmn := rfl
| (n + 1) (m + 1) (a :: as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_comm (a b : α) :
∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l),
(l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a
| 0 j l := by simp [insert_nth]
| (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim
| (i + 1) (j+1) [] := by simp
| (i + 1) (j+1) (c::l) :=
assume h₀ h₁,
by simp [insert_nth];
exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁)
lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length),
a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l
| 0 as h := iff.rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := begin
dsimp [list.insert_nth],
erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff,
← or.assoc, or_comm (a = a'), or.assoc]
end
lemma inj_on_insert_nth_index_of_not_mem (l : list α) (x : α) (hx : x ∉ l) :
set.inj_on (λ k, insert_nth k x l) {n | n ≤ l.length} :=
begin
induction l with hd tl IH,
{ intros n hn m hm h,
simp only [set.mem_singleton_iff, set.set_of_eq_eq_singleton, length, nonpos_iff_eq_zero]
at hn hm,
simp [hn, hm] },
{ intros n hn m hm h,
simp only [length, set.mem_set_of_eq] at hn hm,
simp only [mem_cons_iff, not_or_distrib] at hx,
cases n;
cases m,
{ refl },
{ simpa [hx.left] using h },
{ simpa [ne.symm hx.left] using h },
{ simp only [true_and, eq_self_iff_true, insert_nth_succ_cons] at h,
rw nat.succ_inj',
refine IH hx.right _ _ h,
{ simpa [nat.succ_le_succ_iff] using hn },
{ simpa [nat.succ_le_succ_iff] using hm } } }
end
lemma insert_nth_of_length_lt (l : list α) (x : α) (n : ℕ) (h : l.length < n) :
insert_nth n x l = l :=
begin
induction l with hd tl IH generalizing n,
{ cases n,
{ simpa using h },
{ simp } },
{ cases n,
{ simpa using h },
{ simp only [nat.succ_lt_succ_iff, length] at h,
simpa using IH _ h } }
end
@[simp] lemma insert_nth_length_self (l : list α) (x : α) :
insert_nth l.length x l = l ++ [x] :=
begin
induction l with hd tl IH,
{ simp },
{ simpa using IH }
end
lemma length_le_length_insert_nth (l : list α) (x : α) (n : ℕ) :
l.length ≤ (insert_nth n x l).length :=
begin
cases le_or_lt n l.length with hn hn,
{ rw length_insert_nth _ _ hn,
exact (nat.lt_succ_self _).le },
{ rw insert_nth_of_length_lt _ _ _ hn }
end
lemma length_insert_nth_le_succ (l : list α) (x : α) (n : ℕ) :
(insert_nth n x l).length ≤ l.length + 1 :=
begin
cases le_or_lt n l.length with hn hn,
{ rw length_insert_nth _ _ hn },
{ rw insert_nth_of_length_lt _ _ _ hn,
exact (nat.lt_succ_self _).le }
end
lemma nth_le_insert_nth_of_lt (l : list α) (x : α) (n k : ℕ) (hn : k < n)
(hk : k < l.length)
(hk' : k < (insert_nth n x l).length := hk.trans_le (length_le_length_insert_nth _ _ _)):
(insert_nth n x l).nth_le k hk' = l.nth_le k hk :=
begin
induction n with n IH generalizing k l,
{ simpa using hn },
{ cases l with hd tl,
{ simp },
{ cases k,
{ simp },
{ rw nat.succ_lt_succ_iff at hn,
simpa using IH _ _ hn _ } } }
end
@[simp] lemma nth_le_insert_nth_self (l : list α) (x : α) (n : ℕ)
(hn : n ≤ l.length) (hn' : n < (insert_nth n x l).length :=
by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff]) :
(insert_nth n x l).nth_le n hn' = x :=
begin
induction l with hd tl IH generalizing n,
{ simp only [length, nonpos_iff_eq_zero] at hn,
simp [hn] },
{ cases n,
{ simp },
{ simp only [nat.succ_le_succ_iff, length] at hn,
simpa using IH _ hn } }
end
lemma nth_le_insert_nth_add_succ (l : list α) (x : α) (n k : ℕ)
(hk' : n + k < l.length)
(hk : n + k + 1 < (insert_nth n x l).length :=
by rwa [length_insert_nth _ _ (le_self_add.trans hk'.le), nat.succ_lt_succ_iff]) :
(insert_nth n x l).nth_le (n + k + 1) hk = nth_le l (n + k) hk' :=
begin
induction l with hd tl IH generalizing n k,
{ simpa using hk' },
{ cases n,
{ simpa },
{ simpa [succ_add] using IH _ _ _ } }
end
lemma insert_nth_injective (n : ℕ) (x : α) : function.injective (insert_nth n x) :=
begin
induction n with n IH,
{ have : insert_nth 0 x = cons x := funext (λ _, rfl),
simp [this] },
{ rintros (_|⟨a, as⟩) (_|⟨b, bs⟩) h;
simpa [IH.eq_iff] using h <|> refl }
end
end insert_nth
/-! ### map -/
@[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl
theorem map_eq_foldr (f : α → β) (l : list α) :
map f l = foldr (λ a bs, f a :: bs) [] l :=
by induction l; simp *
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in
by rw [map, map, h₁, map_congr h₂]
lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) :=
begin
refine ⟨_, map_congr⟩, intros h x hx,
rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩,
rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h
end
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; [refl, simp only [*, join, map, map_append]]
theorem bind_ret_eq_map (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *];
split; refl
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl
@[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) :=
by cases l; refl
@[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f :=
begin
split; intros h x y hxy,
{ suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] },
{ induction y generalizing x, simpa using hxy,
cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] }
end
/--
A single `list.map` of a composition of functions is equal to
composing a `list.map` with another `list.map`, fully applied.
This is the reverse direction of `list.map_map`.
-/
lemma comp_map (h : β → γ) (g : α → β) (l : list α) :
map (h ∘ g) l = map h (map g l) := (map_map _ _ _).symm
/--
Composing a `list.map` with another `list.map` is equal to
a single `list.map` of composed functions.
-/
@[simp] lemma map_comp_map (g : β → γ) (f : α → β) :
map g ∘ map f = map (g ∘ f) :=
by { ext l, rw comp_map }
theorem map_filter_eq_foldr (f : α → β) (p : α → Prop) [decidable_pred p] (as : list α) :
map f (filter p as) = foldr (λ a bs, if p a then f a :: bs else bs) [] as :=
by { induction as, { refl }, { simp! [*, apply_ite (map f)] } }
lemma last_map (f : α → β) {l : list α} (hl : l ≠ []) :
(l.map f).last (mt eq_nil_of_map_eq_nil hl) = f (l.last hl) :=
begin
induction l with l_ih l_tl l_ih,
{ apply (hl rfl).elim },
{ cases l_tl,
{ simp },
{ simpa using l_ih } }
end
/-! ### map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
@[simp] theorem map₂_flip (f : α → β → γ) :
∀ as bs, map₂ (flip f) bs as = map₂ f as bs
| [] [] := rfl
| [] (b :: bs) := rfl
| (a :: as) [] := rfl
| (a :: as) (b :: bs) := by { simp! [map₂_flip], refl }
/-! ### take, drop -/
@[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
@[simp] theorem take_length : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end
theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_le (le_of_succ_le_succ h)]
end
@[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁
| [] l₂ := rfl
| (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂)
theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take_left
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [nat.min_zero, take_zero, take_nil]
| 0 m l := by rw [nat.zero_min, take_zero, take_zero]
| (succ n) (succ m) nil := by simp only [take_nil]
| (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl
theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m)
| n 0 := by simp
| 0 m := by simp
| (succ n) (succ m) := by simp [min_succ_succ, take_repeat]
lemma map_take {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_take], }
/-- Taking the first `n` elements in `l₁ ++ l₂` is the same as appending the first `n` elements
of `l₁` to the first `n - l₁.length` elements of `l₂`. -/
lemma take_append_eq_append_take {l₁ l₂ : list α} {n : ℕ} :
take n (l₁ ++ l₂) = take n l₁ ++ take (n - l₁.length) l₂ :=
begin
induction l₁ generalizing n, { simp },
cases n, { simp }, simp *
end
lemma take_append_of_le_length {l₁ l₂ : list α} {n : ℕ} (h : n ≤ l₁.length) :
(l₁ ++ l₂).take n = l₁.take n :=
by simp [take_append_eq_append_take, sub_eq_zero_iff_le.mpr h]
/-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first
`i` elements of `l₂` to `l₁`. -/
lemma take_append {l₁ l₂ : list α} (i : ℕ) :
take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) :=
by simp [take_append_eq_append_take, take_all_of_le le_self_add]
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) :
nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) :=
by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ }
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) :
nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) :=
by { simp at hi, rw nth_le_take L _ hi.1 }
lemma nth_take {l : list α} {n m : ℕ} (h : m < n) :
(l.take n).nth m = l.nth m :=
begin
induction n with n hn generalizing l m,
{ simp only [nat.nat_zero_eq_zero] at h,
exact absurd h (not_lt_of_le m.zero_le) },
{ cases l with hd tl,
{ simp only [take_nil] },
{ cases m,
{ simp only [nth, take] },
{ simpa only using hn (nat.lt_of_succ_lt_succ h) } } },
end
@[simp] lemma nth_take_of_succ {l : list α} {n : ℕ} :
(l.take (n + 1)).nth n = l.nth n :=
nth_take (nat.lt_succ_self n)
lemma take_succ {l : list α} {n : ℕ} :
l.take (n + 1) = l.take n ++ (l.nth n).to_list :=
begin
induction l with hd tl hl generalizing n,
{ simp only [option.to_list, nth, take_nil, append_nil]},
{ cases n,
{ simp only [option.to_list, nth, eq_self_iff_true, and_self, take, nil_append] },
{ simp only [hl, cons_append, nth, eq_self_iff_true, and_self, take] } }
end
@[simp] lemma take_eq_nil_iff {l : list α} {k : ℕ} :
l.take k = [] ↔ l = [] ∨ k = 0 :=
by { cases l; cases k; simp [nat.succ_ne_zero] }
lemma init_eq_take (l : list α) : l.init = l.take l.length.pred :=
begin
cases l with x l,
{ simp [init] },
{ induction l with hd tl hl generalizing x,
{ simp [init], },
{ simp [init, hl] } }
end
lemma init_take {n : ℕ} {l : list α} (h : n < l.length) :
(l.take n).init = l.take n.pred :=
by simp [init_eq_take, min_eq_left_of_lt h, take_take, pred_le]
@[simp] lemma drop_eq_nil_of_le {l : list α} {k : ℕ} (h : l.length ≤ k) :
l.drop k = [] :=
by simpa [←length_eq_zero] using nat.sub_eq_zero_of_le h
lemma drop_eq_nil_iff_le {l : list α} {k : ℕ} :
l.drop k = [] ↔ l.length ≤ k :=
begin
refine ⟨λ h, _, drop_eq_nil_of_le⟩,
induction k with k hk generalizing l,
{ simp only [drop] at h,
simp [h] },
{ cases l,
{ simp },
{ simp only [drop] at h,
simpa [nat.succ_le_succ_iff] using hk h } }
end
lemma tail_drop (l : list α) (n : ℕ) : (l.drop n).tail = l.drop (n + 1) :=
begin
induction l with hd tl hl generalizing n,
{ simp },
{ cases n,
{ simp },
{ simp [hl] } }
end
lemma cons_nth_le_drop_succ {l : list α} {n : ℕ} (hn : n < l.length) :
l.nth_le n hn :: l.drop (n + 1) = l.drop n :=
begin
induction l with hd tl hl generalizing n,
{ exact absurd n.zero_le (not_le_of_lt (by simpa using hn)) },
{ cases n,
{ simp },
{ simp only [nat.succ_lt_succ_iff, list.length] at hn,
simpa [list.nth_le, list.drop] using hl hn } }
end
theorem drop_nil : ∀ n, drop n [] = ([] : list α) :=
λ _, drop_eq_nil_of_le (nat.zero_le _)
lemma mem_of_mem_drop {α} {n : ℕ} {l : list α} {x : α}
(h : x ∈ l.drop n) :
x ∈ l :=
begin
induction l generalizing n,
case list.nil : n h
{ simpa using h },
case list.cons : l_hd l_tl l_ih n h
{ cases n; simp only [mem_cons_iff, drop] at h ⊢,
{ exact h },
right, apply l_ih h },
end
@[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l
| [] := rfl
| (a :: l) := rfl
theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l)
| m 0 l := rfl
| m (n+1) [] := (drop_nil _).symm
| m (n+1) (a::l) := drop_add m n _
@[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂
| [] l₂ := rfl
| (a::l₁) l₂ := drop_left l₁ l₂
theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
drop n (l₁ ++ l₂) = l₂ :=
by rw ← h; apply drop_left
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
@[simp] lemma drop_length (l : list α) : l.drop l.length = [] :=
calc l.drop l.length = (l ++ []).drop l.length : by simp
... = [] : drop_left _ _
/-- Dropping the elements up to `n` in `l₁ ++ l₂` is the same as dropping the elements up to `n`
in `l₁`, dropping the elements up to `n - l₁.length` in `l₂`, and appending them. -/
lemma drop_append_eq_append_drop {l₁ l₂ : list α} {n : ℕ} :
drop n (l₁ ++ l₂) = drop n l₁ ++ drop (n - l₁.length) l₂ :=
begin
induction l₁ generalizing n, { simp },
cases n, { simp }, simp *
end
lemma drop_append_of_le_length {l₁ l₂ : list α} {n : ℕ} (h : n ≤ l₁.length) :
(l₁ ++ l₂).drop n = l₁.drop n ++ l₂ :=
by simp [drop_append_eq_append_drop, sub_eq_zero_iff_le.mpr h]
/-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements
up to `i` in `l₂`. -/
lemma drop_append {l₁ l₂ : list α} (i : ℕ) :
drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ :=
by simp [drop_append_eq_append_drop, take_all_of_le le_self_add]
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) :
nth_le L (i + j) h = nth_le (L.drop i) j
begin
have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h,
rw (take_append_drop i L).symm at h,
simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h
end :=
begin
have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)],
rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right];
simp [A]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) :
nth_le (L.drop i) j h = nth_le L (i + j) (lt_sub_iff_left.mp ((length_drop i L) ▸ h)) :=
by rw nth_le_drop
lemma nth_drop (L : list α) (i j : ℕ) :
nth (L.drop i) j = nth L (i + j) :=
begin
ext,
simp only [nth_eq_some, nth_le_drop', option.mem_def],
split;
exact λ ⟨h, ha⟩, ⟨by simpa [lt_sub_iff_left] using h, ha⟩
end
@[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l
| m [] := by simp
| 0 l := by simp
| (m+1) (a::l) :=
calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl
... = drop (n + m) l : drop_drop m l
... = drop (n + (m + 1)) (a :: l) : rfl
theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α),
drop m (take (m + n) l) = take n (drop m l)
| 0 n _ := by simp
| (m+1) n nil := by simp
| (m+1) n (_::l) :=
have h: m + 1 + n = (m+n) + 1, by ac_refl,
by simpa [take_cons, h] using drop_take m n l
lemma map_drop {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_drop], }
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
lemma reverse_take {α} {xs : list α} (n : ℕ)
(h : n ≤ xs.length) :
xs.reverse.take n = (xs.drop (xs.length - n)).reverse :=
begin
induction xs generalizing n;
simp only [reverse_cons, drop, reverse_nil, nat.zero_sub, length, take_nil],
cases h.lt_or_eq_dec with h' h',
{ replace h' := le_of_succ_le_succ h',
rwa [take_append_of_le_length, xs_ih _ h'],
rw [show xs_tl.length + 1 - n = succ (xs_tl.length - n), from _, drop],
{ rwa [succ_eq_add_one, nat.sub_add_comm] },
{ rwa length_reverse } },
{ subst h', rw [length, nat.sub_self, drop],
suffices : xs_tl.length + 1 = (xs_tl.reverse ++ [xs_hd]).length,
by rw [this, take_length, reverse_cons],
rw [length_append, length_reverse], refl }
end
@[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] :=
by cases l; cases n; simp only [update_nth]
section take'
variable [inhabited α]
@[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n
| 0 l := rfl
| (n+1) l := congr_arg succ (take'_length _ _)
@[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n
| 0 := rfl
| (n+1) := congr_arg (cons _) (take'_nil _)
theorem take'_eq_take : ∀ {n} {l : list α},
n ≤ length l → take' n l = take n l
| 0 l h := rfl
| (n+1) (a::l) h := congr_arg (cons _) $
take'_eq_take $ le_of_succ_le_succ h
@[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ :=
(take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _)
theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take' n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take'_left
end take'
/-! ### foldl, foldr -/
lemma foldl_ext (f g : α → β → α) (a : α)
{l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) :
foldl f a l = foldl g a l :=
begin
induction l with hd tl ih generalizing a, {refl},
unfold foldl,
rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)]
end
lemma foldr_ext (f g : α → β → β) (b : β)
{l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) :
foldr f b l = foldr g b l :=
begin
induction l with hd tl ih, {refl},
simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H,
simp only [foldr, ih H.2, H.1]
end
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : α → β → α) :
∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂
| a [] l₂ := rfl
| a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂]
@[simp] theorem foldl_join (f : α → β → α) :
∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L
| a [] := rfl
| a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L]
@[simp] theorem foldr_join (f : α → β → β) :
∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L
| a [] := rfl
| a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) :
foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) :
foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl
@[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l :=
by rw ←foldr_reverse; simp
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) :
foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldl]]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) :
foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldr]]
theorem foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldl f' (g a) (l.map g) = g (list.foldl f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldr_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldr f' (g a) (l.map g) = g (list.foldr f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α)
(h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) :=
eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] }
theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α)
(h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) :=
by { revert a, induction l; intros; [refl, simp only [*, foldr]] }
lemma injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α}
(hl : ∀ f ∈ l, function.injective f) (hf : function.injective f):
function.injective (@list.foldl (α → α) (α → α) function.comp f l) :=
begin
induction l generalizing f,
{ exact hf },
{ apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)),
apply function.injective.comp hf,
apply hl _ (list.mem_cons_self _ _) }
end
/-- Induction principle for values produced by a `foldr`: if a property holds
for the seed element `b : β` and for all incremental `op : α → β → β`
performed on the elements `(a : α) ∈ l`. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
def foldr_rec_on {C : β → Sort*} (l : list α) (op : α → β → β) (b : β) (hb : C b)
(hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op a b)) :
C (foldr op b l) :=
begin
induction l with hd tl IH,
{ exact hb },
{ refine hl _ _ hd (mem_cons_self hd tl),
refine IH _,
intros y hy x hx,
exact hl y hy x (mem_cons_of_mem hd hx) }
end
/-- Induction principle for values produced by a `foldl`: if a property holds
for the seed element `b : β` and for all incremental `op : β → α → β`
performed on the elements `(a : α) ∈ l`. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
def foldl_rec_on {C : β → Sort*} (l : list α) (op : β → α → β) (b : β) (hb : C b)
(hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op b a)) :
C (foldl op b l) :=
begin
induction l with hd tl IH generalizing b,
{ exact hb },
{ refine IH _ _ _,
{ intros y hy x hx,
exact hl y hy x (mem_cons_of_mem hd hx) },
{ exact hl b hb hd (mem_cons_self hd tl) } }
end
@[simp] lemma foldr_rec_on_nil {C : β → Sort*} (op : α → β → β) (b) (hb : C b) (hl) :
foldr_rec_on [] op b hb hl = hb := rfl
@[simp] lemma foldr_rec_on_cons {C : β → Sort*} (x : α) (l : list α)
(op : α → β → β) (b) (hb : C b)
(hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ (x :: l)), C (op a b)) :
foldr_rec_on (x :: l) op b hb hl = hl _ (foldr_rec_on l op b hb
(λ b hb a ha, hl b hb a (mem_cons_of_mem _ ha))) x (mem_cons_self _ _) := rfl
@[simp] lemma foldl_rec_on_nil {C : β → Sort*} (op : β → α → β) (b) (hb : C b) (hl) :
foldl_rec_on [] op b hb hl = hb := rfl
/- scanl -/
section scanl
variables {f : β → α → β} {b : β} {a : α} {l : list α}
lemma length_scanl :
∀ a l, length (scanl f a l) = l.length + 1
| a [] := rfl
| a (x :: l) := by erw [length_cons, length_cons, length_scanl]
@[simp] lemma scanl_nil (b : β) : scanl f b nil = [b] := rfl
@[simp] lemma scanl_cons :
scanl f b (a :: l) = [b] ++ scanl f (f b a) l :=
by simp only [scanl, eq_self_iff_true, singleton_append, and_self]
@[simp] lemma nth_zero_scanl : (scanl f b l).nth 0 = some b :=
begin
cases l,
{ simp only [nth, scanl_nil] },
{ simp only [nth, scanl_cons, singleton_append] }
end
@[simp] lemma nth_le_zero_scanl {h : 0 < (scanl f b l).length} :
(scanl f b l).nth_le 0 h = b :=
begin
cases l,
{ simp only [nth_le, scanl_nil] },
{ simp only [nth_le, scanl_cons, singleton_append] }
end
lemma nth_succ_scanl {i : ℕ} :
(scanl f b l).nth (i + 1) = ((scanl f b l).nth i).bind (λ x, (l.nth i).map (λ y, f x y)) :=
begin
induction l with hd tl hl generalizing b i,
{ symmetry,
simp only [option.bind_eq_none', nth, forall_2_true_iff, not_false_iff, option.map_none',
scanl_nil, option.not_mem_none, forall_true_iff] },
{ simp only [nth, scanl_cons, singleton_append],
cases i,
{ simp only [option.map_some', nth_zero_scanl, nth, option.some_bind'] },
{ simp only [hl, nth] } }
end
lemma nth_le_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} :
(scanl f b l).nth_le (i + 1) h =
f ((scanl f b l).nth_le i (nat.lt_of_succ_lt h))
(l.nth_le i (nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) :=
begin
induction i with i hi generalizing b l,
{ cases l,
{ simp only [length, zero_add, scanl_nil] at h,
exact absurd h (lt_irrefl 1) },
{ simp only [scanl_cons, singleton_append, nth_le_zero_scanl, nth_le] } },
{ cases l,
{ simp only [length, add_lt_iff_neg_right, scanl_nil] at h,
exact absurd h (not_lt_of_lt nat.succ_pos') },
{ simp_rw scanl_cons,
rw nth_le_append_right _,
{ simpa only [hi, length, succ_add_sub_one] },
{ simp only [length, nat.zero_le, le_add_iff_nonneg_left] } } }
end
end scanl
/- scanr -/
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp only [scanr, scanr_aux, t, foldr_cons]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) :=
by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp only [foldl_cons];
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section foldl_eq_foldlr'
variables {f : α → β → α}
variables hf : ∀ a b c, f (f a b) c = f (f a c) b
include hf
theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b
| a b [] := rfl
| a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf]
theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l
| a [] := rfl
| a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl
end foldl_eq_foldlr'
section foldl_eq_foldlr'
variables {f : α → β → β}
variables hf : ∀ a b c, f a (f b c) = f b (f a c)
include hf
theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l
| a b [] := rfl
| a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl
end foldl_eq_foldlr'
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons]
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc];
rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/-! ### mfoldl, mfoldr, mmap -/
section mfoldl_mfoldr
variables {m : Type v → Type w} [monad m]
@[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl
@[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl
@[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} :
mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl
@[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} :
mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl
theorem mfoldr_eq_foldr (f : α → β → m β) (b l) :
mfoldr f b l = foldr (λ a mb, mb >>= f a) (pure b) l :=
by induction l; simp *
attribute [simp] mmap mmap'
variables [is_lawful_monad m]
theorem mfoldl_eq_foldl (f : β → α → m β) (b l) :
mfoldl f b l = foldl (λ mb a, mb >>= λ b, f b a) (pure b) l :=
begin
suffices h : ∀ (mb : m β),
(mb >>= λ b, mfoldl f b l) = foldl (λ mb a, mb >>= λ b, f b a) mb l,
by simp [←h (pure b)],
induction l; intro,
{ simp },
{ simp only [mfoldl, foldl, ←l_ih] with monad_norm }
end
@[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂},
mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂
| _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind]
| _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, is_lawful_monad.bind_assoc]
@[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂},
mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁
| _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure]
| _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, is_lawful_monad.bind_assoc]
end mfoldl_mfoldr
/-! ### prod and sum -/
-- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet.
attribute [to_additive] list.prod
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[to_additive]
theorem prod_singleton : [a].prod = a := one_mul a
@[simp, to_additive]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, to_additive]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
/-- If zero is an element of a list `L`, then `list.prod L = 0`. If the domain is a nontrivial
monoid with zero with no divisors, then this implication becomes an `iff`, see
`list.prod_eq_zero_iff`. -/
theorem prod_eq_zero {M₀ : Type*} [monoid_with_zero M₀] {L : list M₀} (h : (0 : M₀) ∈ L) :
L.prod = 0 :=
begin
induction L with a L ihL,
{ exact absurd h (not_mem_nil _) },
{ rw prod_cons,
cases (mem_cons_iff _ _ _).1 h with ha hL,
exacts [mul_eq_zero_of_left ha.symm _, mul_eq_zero_of_right _ (ihL hL)] }
end
/-- Product of elements of a list `L` equals zero if and only if `0 ∈ L`. See also
`list.prod_eq_zero` for an implication that needs weaker typeclass assumptions. -/
@[simp] theorem prod_eq_zero_iff {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀]
[no_zero_divisors M₀] {L : list M₀} :
L.prod = 0 ↔ (0 : M₀) ∈ L :=
begin
induction L with a L ihL,
{ simp },
{ rw [prod_cons, mul_eq_zero, ihL, mem_cons_iff, eq_comm] }
end
theorem prod_ne_zero {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀] [no_zero_divisors M₀]
{L : list M₀} (hL : (0 : M₀) ∉ L) : L.prod ≠ 0 :=
mt prod_eq_zero_iff.1 hL
@[to_additive]
theorem prod_eq_foldr : l.prod = foldr (*) 1 l :=
list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl]
@[to_additive]
theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (l.map f).prod (l.map g).prod :=
list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl])
@[to_additive]
theorem prod_hom [monoid β] (l : list α) (f : α →* β) :
(l.map f).prod = f l.prod :=
by { simp only [prod, foldl_map, f.map_one.symm],
exact l.foldl_hom _ _ _ 1 f.map_mul }
@[to_additive]
lemma prod_is_unit [monoid β] : Π {L : list β} (u : ∀ m ∈ L, is_unit m), is_unit L.prod
| [] _ := by simp
| (h :: t) u :=
begin
simp only [list.prod_cons],
exact is_unit.mul (u h (mem_cons_self h t)) (prod_is_unit (λ m mt, u m (mem_cons_of_mem h mt)))
end
-- `to_additive` chokes on the next few lemmas, so we do them by hand below
@[simp]
lemma prod_take_mul_prod_drop :
∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], }
@[simp]
lemma prod_take_succ :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], }
/-- A list with product not one must have positive length. -/
lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
lemma prod_update_nth : ∀ (L : list α) (n : ℕ) (a : α),
(L.update_nth n a).prod =
(L.take n).prod * (if n < L.length then a else 1) * (L.drop (n + 1)).prod
| (x::xs) 0 a := by simp [update_nth]
| (x::xs) (i+1) a := by simp [update_nth, prod_update_nth xs i a, mul_assoc]
| [] _ _ := by simp [update_nth, (nat.zero_le _).not_lt]
end monoid
section group
variables [group α]
/-- This is the `list.prod` version of `mul_inv_rev` -/
@[to_additive "This is the `list.sum` version of `add_neg_rev`"]
lemma prod_inv_reverse : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).reverse.prod
| [] := by simp
| (x :: xs) := by simp [prod_inv_reverse xs]
/-- A non-commutative variant of `list.prod_reverse` -/
@[to_additive "A non-commutative variant of `list.sum_reverse`"]
lemma prod_reverse_noncomm : ∀ (L : list α), L.reverse.prod = (L.map (λ x, x⁻¹)).prod⁻¹ :=
by simp [prod_inv_reverse]
end group
section comm_group
variables [comm_group α]
/-- This is the `list.prod` version of `mul_inv` -/
@[to_additive "This is the `list.sum` version of `add_neg`"]
lemma prod_inv : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).prod
| [] := by simp
| (x :: xs) := by simp [mul_comm, prod_inv xs]
end comm_group
@[simp]
lemma sum_take_add_sum_drop [add_monoid α] :
∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], }
@[simp]
lemma sum_take_succ [add_monoid α] :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], }
lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length)
(h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' :=
begin
apply ext_le h (λ i h₁ h₂, _),
have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁),
rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this,
exact add_left_cancel this
end
lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) :
monotone (λ i, (L.take i).sum) :=
begin
apply monotone_nat_of_le_succ (λ n, _),
by_cases h : n < L.length,
{ rw sum_take_succ _ _ h,
exact le_self_add },
{ push_neg at h,
simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] }
end
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
1 ≤ l.prod :=
begin
induction l with hd tl ih,
{ simp },
rw prod_cons,
exact one_le_mul (hl₁ hd (mem_cons_self hd tl)) (ih (λ x h, hl₁ x (mem_cons_of_mem hd h))),
end
@[to_additive]
lemma single_le_prod [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
∀ x ∈ l, x ≤ l.prod :=
begin
induction l,
{ simp },
simp_rw [prod_cons, forall_mem_cons] at ⊢ hl₁,
split,
{ exact le_mul_of_one_le_right' (one_le_prod_of_one_le hl₁.2) },
{ exact λ x H, le_mul_of_one_le_of_le hl₁.1 (l_ih hl₁.right x 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 [ordered_comm_monoid α]
{l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) (hl₂ : l.prod = 1) :
∀ x ∈ l, x = (1 : α) :=
λ x hx, le_antisymm (hl₂ ▸ single_le_prod hl₁ _ hx) (hl₁ x hx)
lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] (l : list α) :
l.sum = 0 ↔ ∀ x ∈ l, x = (0 : α) :=
⟨all_zero_of_le_zero_le_of_sum_eq_zero (λ _ _, zero_le _),
begin
induction l,
{ simp },
{ intro h,
rw [sum_cons, add_eq_zero_iff],
rw forall_mem_cons at h,
exact ⟨h.1, l_ih h.2⟩ },
end⟩
/-- A list with sum not zero must have positive length. -/
lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
/-- If all elements in a list are bounded below by `1`, then the length of the list is bounded
by the sum of the elements. -/
lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum :=
begin
induction L with j L IH h, { simp },
rw [sum_cons, length, add_comm],
exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi)))
end
-- Now we tie those lemmas back to their multiplicative versions.
attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one
/-- A list with positive sum must have positive length. -/
-- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications.
lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) :
0 < L.length :=
length_pos_of_sum_ne_zero L (ne_of_gt h)
-- TODO: develop theory of tropical rings
lemma sum_le_foldr_max [add_monoid α] [add_monoid β] [linear_order β] (f : α → β)
(h0 : f 0 ≤ 0) (hadd : ∀ x y, f (x + y) ≤ max (f x) (f y)) (l : list α) :
f l.sum ≤ (l.map f).foldr max 0 :=
begin
induction l with hd tl IH,
{ simpa using h0 },
{ simp only [list.sum_cons, list.foldr_map, le_max_iff, list.foldr] at IH ⊢,
cases le_or_lt (f tl.sum) (f hd),
{ left,
refine (hadd _ _).trans _,
simpa using h },
{ right,
refine (hadd _ _).trans _,
simp only [IH, max_le_iff, and_true, h.le.trans IH] } }
end
@[simp, to_additive]
theorem prod_erase [decidable_eq α] [comm_monoid α] {a} :
Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b::l) h :=
begin
rcases decidable.list.eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_monoid α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum :=
begin
induction l with x l ih,
{ exact dvd_zero _ },
{ rw [list.sum_cons],
exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) }
end
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; [refl, simp only [*, join, map, sum_cons, length_append]]
@[simp] theorem length_bind (l : list α) (f : α → list β) :
length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
lemma exists_lt_of_sum_lt [linear_ordered_cancel_add_comm_monoid β] {l : list α}
(f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x :=
begin
induction l with x l,
{ exfalso, exact lt_irrefl _ h },
{ by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) }
end
lemma exists_le_of_sum_le [linear_ordered_cancel_add_comm_monoid β] {l : list α}
(hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x :=
begin
cases l with x l,
{ contradiction },
{ by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩,
exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) }
end
-- Several lemmas about sum/head/tail for `list ℕ`.
-- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`.
-- We'd like to state this as `L.head * L.tail.prod = L.prod`,
-- but because `L.head` relies on an inhabited instances and
-- returns a garbage value for the empty list, this is not possible.
-- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`,
-- and below, restate the lemma just for `ℕ`.
@[to_additive]
lemma head_mul_tail_prod' [monoid α] (L : list α) :
(L.nth 0).get_or_else 1 * L.tail.prod = L.prod :=
by cases L; simp
lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum :=
by { cases L, { simp, refl, }, { simp, }, }
lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum :=
nat.le.intro (head_add_tail_sum L)
lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head :=
by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel]
section
variables {G : Type*} [comm_group G]
attribute [to_additive] alternating_prod
@[simp, to_additive] lemma alternating_prod_nil :
alternating_prod ([] : list G) = 1 := rfl
@[simp, to_additive] lemma alternating_prod_singleton (g : G) :
alternating_prod [g] = g := rfl
@[simp, to_additive alternating_sum_cons_cons']
lemma alternating_prod_cons_cons (g h : G) (l : list G) :
alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl
lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) :
alternating_sum (g :: h :: l) = g - h + alternating_sum l :=
by rw [sub_eq_add_neg, alternating_sum]
end
/-! ### join -/
attribute [simp] join
@[simp] lemma join_nil {α : Type u} : [([] : list α)].join = [] := rfl
@[simp] theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = []
| [] := iff_of_true rfl (forall_mem_nil _)
| (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]]
@[simp] theorem join_filter_empty_eq_ff [decidable_pred (λ l : list α, l.empty = ff)] :
∀ {L : list (list α)}, join (L.filter (λ l, l.empty = ff)) = L.join
| [] := rfl
| ([]::L) := by simp [@join_filter_empty_eq_ff L]
| ((a::l)::L) := by simp [@join_filter_empty_eq_ff L]
@[simp] theorem join_filter_ne_nil [decidable_pred (λ l : list α, l ≠ [])] {L : list (list α)} :
join (L.filter (λ l, l ≠ [])) = L.join :=
by simp [join_filter_empty_eq_ff, ← empty_iff_eq_nil]
lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join :=
by { induction l, simp, simp [l_ih] }
/-- In a join, taking the first elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join of the first `i` sublists. -/
lemma take_sum_join (L : list (list α)) (i : ℕ) :
L.join.take ((L.map length).take i).sum = (L.take i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [take_append, L_ih]
end
/-- In a join, dropping all the elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/
lemma drop_sum_join (L : list (list α)) (i : ℕ) :
L.join.drop ((L.map length).take i).sum = (L.drop i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [drop_append, L_ih],
end
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) :
(L.take (i+1)).drop i = [nth_le L i hi] :=
begin
induction L generalizing i,
{ simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim },
cases i, { simp },
have : i < L_tl.length,
{ simp at hi,
exact nat.lt_of_succ_lt_succ hi },
simp [L_ih this],
refl
end
/-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the
original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and
`B` is the sum of the lengths of sublists of index `≤ i`. -/
lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) :
(L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi :=
begin
have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take],
simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi]
end
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum :=
by simp [hi, sum_take_succ, hj]
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < L.join.length :=
begin
convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi),
have : L.length = (L.map length).length, by simp,
simp [this, -length_map]
end
/-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist,
where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists
of index `< i`, and adding `j`. -/
lemma nth_le_join (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) =
nth_le (nth_le L i hi) j hj :=
by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj),
nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)]
/-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the
sublists. -/
theorem eq_iff_join_eq (L L' : list (list α)) :
L = L' ↔ L.join = L'.join ∧ map length L = map length L' :=
begin
refine ⟨λ H, by simp [H], _⟩,
rintros ⟨join_eq, length_eq⟩,
apply ext_le,
{ have : length (map length L) = length (map length L'), by rw length_eq,
simpa using this },
{ assume n h₁ h₂,
rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] }
end
/-! ### intersperse -/
@[simp] lemma intersperse_nil {α : Type u} (a : α) : intersperse a [] = [] := rfl
@[simp] lemma intersperse_singleton {α : Type u} (a b : α) : intersperse a [b] = [b] := rfl
@[simp] lemma intersperse_cons_cons {α : Type u} (a b c : α) (tl : list α) :
intersperse a (b :: c :: tl) = b :: a :: intersperse a (c :: tl) := rfl
/-! ### split_at and split_on -/
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop]
@[simp] lemma split_on_nil {α : Type u} [decidable_eq α] (a : α) : [].split_on a = [[]] := rfl
/-- An auxiliary definition for proving a specification lemma for `split_on_p`.
`split_on_p_aux' P xs ys` splits the list `ys ++ xs` at every element satisfying `P`,
where `ys` is an accumulating parameter for the initial segment of elements not satisfying `P`.
-/
def split_on_p_aux' {α : Type u} (P : α → Prop) [decidable_pred P] : list α → list α → list (list α)
| [] xs := [xs]
| (h :: t) xs :=
if P h then xs :: split_on_p_aux' t []
else split_on_p_aux' t (xs ++ [h])
lemma split_on_p_aux_eq {α : Type u} (P : α → Prop) [decidable_pred P] (xs ys : list α) :
split_on_p_aux' P xs ys = split_on_p_aux P xs ((++) ys) :=
begin
induction xs with a t ih generalizing ys; simp! only [append_nil, eq_self_iff_true, and_self],
split_ifs; rw ih,
{ refine ⟨rfl, rfl⟩ },
{ congr, ext, simp }
end
lemma split_on_p_aux_nil {α : Type u} (P : α → Prop) [decidable_pred P] (xs : list α) :
split_on_p_aux P xs id = split_on_p_aux' P xs [] :=
by { rw split_on_p_aux_eq, refl }
/-- The original list `L` can be recovered by joining the lists produced by `split_on_p p L`,
interspersed with the elements `L.filter p`. -/
lemma split_on_p_spec {α : Type u} (p : α → Prop) [decidable_pred p] (as : list α) :
join (zip_with (++) (split_on_p p as) ((as.filter p).map (λ x, [x]) ++ [[]])) = as :=
begin
rw [split_on_p, split_on_p_aux_nil],
suffices : ∀ xs,
join (zip_with (++) (split_on_p_aux' p as xs) ((as.filter p).map(λ x, [x]) ++ [[]])) = xs ++ as,
{ rw this, refl },
induction as; intro; simp! only [split_on_p_aux', append_nil],
split_ifs; simp [zip_with, join, *],
end
/-! ### all & any -/
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) :
all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
simp only [all_cons, band_coe_iff, ih, forall_mem_cons]
end
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp only [all_iff_forall, bool.of_to_bool_iff]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) :
any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_false bool.not_ff (not_exists_mem_nil _) },
simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff]
end
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
@[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/-! ### map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β
| [] H := []
| (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {l : list α} (hx : x ∈ l) :
sizeof x < sizeof l :=
begin
induction l with h t ih; cases hx,
{ rw hx, exact lt_add_of_lt_of_nonneg (lt_one_add _) (nat.zero_le _) },
{ exact lt_add_of_pos_of_le (zero_lt_one_add _) (le_of_lt (ih hx)) }
end
theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) :
@pmap _ _ p (λ a _, f a) l H = map f l :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f l H₁ = pmap g l H₂ :=
by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]]
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_map {p : β → Prop} (g : ∀ b, p b → γ) (f : α → β)
(l H) : pmap g (map f l) H = pmap (λ a h, g (f a) h) l (λ a h, H _ (mem_map_of_mem _ h)) :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) :=
by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl)
theorem attach_map_val (l : list α) : l.attach.map subtype.val = l :=
by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l)
@[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ :=
by have := mem_map.1 (by rw [attach_map_val]; exact h);
{ rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m }
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b :=
by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists]
@[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β}
{l H} : length (pmap f l H) = length l :=
by induction l; [refl, simp only [*, pmap, length]]
@[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap
@[simp] lemma pmap_eq_nil {p : α → Prop} {f : Π a, p a → β}
{l H} : pmap f l H = [] ↔ l = [] :=
by rw [← length_eq_zero, length_pmap, length_eq_zero]
@[simp] lemma attach_eq_nil (l : list α) : l.attach = [] ↔ l = [] := pmap_eq_nil
lemma last_pmap {α β : Type*} (p : α → Prop) (f : Π a, p a → β)
(l : list α) (hl₁ : ∀ a ∈ l, p a) (hl₂ : l ≠ []) :
(l.pmap f hl₁).last (mt list.pmap_eq_nil.1 hl₂) = f (l.last hl₂) (hl₁ _ (list.last_mem hl₂)) :=
begin
induction l with l_hd l_tl l_ih,
{ apply (hl₂ rfl).elim },
{ cases l_tl,
{ simp },
{ apply l_ih } }
end
lemma nth_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) (n : ℕ) :
nth (pmap f l h) n = option.pmap f (nth l n) (λ x H, h x (nth_mem H)) :=
begin
induction l with hd tl hl generalizing n,
{ simp },
{ cases n; simp [hl] }
end
lemma nth_le_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) {n : ℕ}
(hn : n < (pmap f l h).length) :
nth_le (pmap f l h) n hn = f (nth_le l n (@length_pmap _ _ p f l h ▸ hn))
(h _ (nth_le_mem l n (@length_pmap _ _ p f l h ▸ hn))) :=
begin
induction l with hd tl hl generalizing n,
{ simp only [length, pmap] at hn,
exact absurd hn (not_lt_of_le n.zero_le) },
{ cases n,
{ simp },
{ simpa [hl] } }
end
/-! ### find -/
section find
variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α}
@[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases h : p a,
{ simp only [find_cons_of_pos _ h, h, not_true, false_and] },
{ rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] }
end
theorem find_some (H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, exact h },
{ rw find_cons_of_neg _ h at H, exact IH H }
end
@[simp] theorem find_mem (H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self },
{ rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) }
end
end find
/-! ### lookmap -/
section lookmap
variables (f : α → option α)
@[simp] theorem lookmap_nil : [].lookmap f = [] := rfl
@[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) :
(a :: l).lookmap f = a :: l.lookmap f :=
by simp [lookmap, h]
@[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) :
(a :: l).lookmap f = b :: l :=
by simp [lookmap, h]
theorem lookmap_some : ∀ l : list α, l.lookmap some = l
| [] := rfl
| (a::l) := rfl
theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l
| [] := rfl
| (a::l) := congr_arg (cons a) (lookmap_none l)
theorem lookmap_congr {f g : α → option α} :
∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g
| [] H := rfl
| (a::l) H := begin
cases forall_mem_cons.1 H with H₁ H₂,
cases h : g a with b,
{ simp [h, H₁.trans h, lookmap_congr H₂] },
{ simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] }
end
theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l :=
(lookmap_congr H).trans (lookmap_none l)
theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) :
∀ l : list α, map g (l.lookmap f) = map g l
| [] := rfl
| (a::l) := begin
cases h' : f a with b,
{ simp [h', lookmap_map_eq] },
{ simp [lookmap_cons_some _ _ h', h _ _ h'] }
end
theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l :=
by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h
theorem length_lookmap (l : list α) : length (l.lookmap f) = length l :=
by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp
end lookmap
/-! ### filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp only [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp only [filter_map, h]; split; refl
lemma filter_map_append {α β : Type*} (l l' : list α) (f : α → option β) :
filter_map f (l ++ l') = filter_map f l ++ filter_map f l' :=
begin
induction l with hd tl hl generalizing l',
{ simp },
{ rw [cons_append, filter_map, filter_map],
cases f hd;
simp only [filter_map, hl, cons_append, eq_self_iff_true, and_self] }
end
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {refl},
simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {refl},
by_cases pa : p a,
{ simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl },
{ simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] }
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp only [h, option.none_bind'] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp only [h, h', option.some_bind']
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases h : p x,
{ simp only [option.guard, if_pos h, option.some_bind'] },
{ simp only [option.guard, if_neg h, option.none_bind'] }
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH,
{ split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } },
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, this, exists_eq_left] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp only [map_filter_map, H, filter_map_some]
theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp only [filter_map]; cases f a with b;
simp only [filter_map, IH, sublist.cons, sublist.cons2]
theorem sublist.map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
filter_map_eq_map f ▸ s.filter_map _
/-! ### reduce_option -/
@[simp] lemma reduce_option_cons_of_some (x : α) (l : list (option α)) :
reduce_option (some x :: l) = x :: l.reduce_option :=
by simp only [reduce_option, filter_map, id.def, eq_self_iff_true, and_self]
@[simp] lemma reduce_option_cons_of_none (l : list (option α)) :
reduce_option (none :: l) = l.reduce_option :=
by simp only [reduce_option, filter_map, id.def]
@[simp] lemma reduce_option_nil : @reduce_option α [] = [] := rfl
@[simp] lemma reduce_option_map {l : list (option α)} {f : α → β} :
reduce_option (map (option.map f) l) = map f (reduce_option l) :=
begin
induction l with hd tl hl,
{ simp only [reduce_option_nil, map_nil] },
{ cases hd;
simpa only [true_and, option.map_some', map, eq_self_iff_true,
reduce_option_cons_of_some] using hl },
end
lemma reduce_option_append (l l' : list (option α)) :
(l ++ l').reduce_option = l.reduce_option ++ l'.reduce_option :=
filter_map_append l l' id
lemma reduce_option_length_le (l : list (option α)) :
l.reduce_option.length ≤ l.length :=
begin
induction l with hd tl hl,
{ simp only [reduce_option_nil, length] },
{ cases hd,
{ exact nat.le_succ_of_le hl },
{ simpa only [length, add_le_add_iff_right, reduce_option_cons_of_some] using hl} }
end
lemma reduce_option_length_eq_iff {l : list (option α)} :
l.reduce_option.length = l.length ↔ ∀ x ∈ l, option.is_some x :=
begin
induction l with hd tl hl,
{ simp only [forall_const, reduce_option_nil, not_mem_nil,
forall_prop_of_false, eq_self_iff_true, length, not_false_iff] },
{ cases hd,
{ simp only [mem_cons_iff, forall_eq_or_imp, bool.coe_sort_ff, false_and,
reduce_option_cons_of_none, length, option.is_some_none, iff_false],
intro H,
have := reduce_option_length_le tl,
rw H at this,
exact absurd (nat.lt_succ_self _) (not_lt_of_le this) },
{ simp only [hl, true_and, mem_cons_iff, forall_eq_or_imp, add_left_inj,
bool.coe_sort_tt, length, option.is_some_some, reduce_option_cons_of_some] } }
end
lemma reduce_option_length_lt_iff {l : list (option α)} :
l.reduce_option.length < l.length ↔ none ∈ l :=
begin
rw [(reduce_option_length_le l).lt_iff_ne, ne, reduce_option_length_eq_iff],
induction l; simp *,
rw [eq_comm, ← option.not_is_some_iff_eq_none, decidable.imp_iff_not_or]
end
lemma reduce_option_singleton (x : option α) :
[x].reduce_option = x.to_list :=
by cases x; refl
lemma reduce_option_concat (l : list (option α)) (x : option α) :
(l.concat x).reduce_option = l.reduce_option ++ x.to_list :=
begin
induction l with hd tl hl generalizing x,
{ cases x;
simp [option.to_list] },
{ simp only [concat_eq_append, reduce_option_append] at hl,
cases hd;
simp [hl, reduce_option_append] }
end
lemma reduce_option_concat_of_some (l : list (option α)) (x : α) :
(l.concat (some x)).reduce_option = l.reduce_option.concat x :=
by simp only [reduce_option_nil, concat_eq_append, reduce_option_append, reduce_option_cons_of_some]
lemma reduce_option_mem_iff {l : list (option α)} {x : α} :
x ∈ l.reduce_option ↔ (some x) ∈ l :=
by simp only [reduce_option, id.def, mem_filter_map, exists_eq_right]
lemma reduce_option_nth_iff {l : list (option α)} {x : α} :
(∃ i, l.nth i = some (some x)) ↔ ∃ i, l.reduce_option.nth i = some x :=
by rw [←mem_iff_nth, ←mem_iff_nth, reduce_option_mem_iff]
/-! ### filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
theorem filter_eq_foldr (p : α → Prop) [decidable_pred p] (l : list α) :
filter p l = foldr (λ a out, if p a then a :: out else out) [] l :=
by induction l; simp [*, filter]
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
: ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l
| [] _ := rfl
| (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a;
[simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2],
simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]];
split; refl
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
(filter_sublist l).subset
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self
| (b::l) (or.inr ain) pa := if pb : p b
then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa
else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
lemma monotone_filter_left (p : α → Prop) [decidable_pred p]
⦃l l' : list α⦄ (h : l ⊆ l') : filter p l ⊆ filter p l' :=
begin
intros x hx,
rw [mem_filter] at hx ⊢,
exact ⟨h hx.left, hx.right⟩
end
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases p a,
{ rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] },
{ rw [filter_cons_of_neg _ h],
refine iff_of_false _ (mt and.left h), intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) }
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and]
variable (p)
theorem sublist.filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
filter_map_eq_filter p ▸ s.filter_map _
lemma monotone_filter_right (l : list α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q]
(h : p ≤ q) : l.filter p <+ l.filter q :=
begin
induction l with hd tl IH,
{ refl },
{ by_cases hp : p hd,
{ rw [filter_cons_of_pos _ hp, filter_cons_of_pos _ (h _ hp)],
exact cons_sublist_cons hd IH },
{ rw filter_cons_of_neg _ hp,
by_cases hq : q hd,
{ rw filter_cons_of_pos _ hq,
exact sublist_cons_of_sublist hd IH },
{ rw filter_cons_of_neg _ hq,
exact IH } } }
end
theorem map_filter (f : β → α) (l : list β) :
filter p (map f l) = map f (filter (p ∘ f) l) :=
by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl
@[simp] theorem filter_filter (q) [decidable_pred q] : ∀ l,
filter p (filter q l) = filter (λ a, p a ∧ q a) l
| [] := rfl
| (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false,
true_and, false_and, filter_filter l, eq_self_iff_true]
@[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) :
@filter α (λ _, true) h l = l :=
by convert filter_eq_self.2 (λ _ _, trivial)
@[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) :
@filter α (λ _, false) h l = [] :=
by convert filter_eq_nil.2 (λ _ _, id)
@[simp] theorem span_eq_take_drop : ∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) :=
if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while]
else by simp only [span, take_while, drop_while, if_neg pa]
@[simp] theorem take_while_append_drop : ∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append,
take_while_append_drop l]
else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append]
@[simp] theorem countp_nil : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l ih; [refl, by_cases (p x)];
[simp only [filter_cons_of_pos _ h, countp, ih, if_pos h],
simp only [countp_cons_of_neg _ _ h, ih, filter_cons_of_neg _ h]]; refl
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp only [countp_eq_length_filter, filter_append, length_append]
theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a :=
by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop]
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa only [countp_eq_length_filter] using length_le_of_sublist (s.filter p)
@[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) :
countp p (filter q l) = countp (λ a, p a ∧ q a) l :=
by simp only [countp_eq_length_filter, filter_filter]
end filter
/-! ### count -/
section count
variable [decidable_eq α]
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
begin rw count_cons, split_ifs; refl end
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length),
l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0
| (_ :: _) a h := by { rw [count_cons], split_ifs; simp }
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist _
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append _
theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by simp [-add_comm]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp only [count, countp_pos, exists_prop, exists_eq_right']
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
decidable.by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} :
n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩
theorem repeat_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) :
repeat a (count a l) = l :=
eq_of_sublist_of_length_eq (le_count_iff_repeat_sublist.mp (le_refl (count a l)))
(eq.trans (length_repeat a (count a l)) h)
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {l : list α} (h : p a) : count a (filter p l) = count a l :=
by simp only [count, countp_filter]; congr; exact
set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h))
lemma count_bind {α β} [decidable_eq β] (l : list α) (f : α → list β) (x : β) :
count x (l.bind f) = sum (map (count x ∘ f) l) :=
begin
induction l with hd tl IH,
{ simp },
{ simpa }
end
@[simp] lemma count_map_map {α β} [decidable_eq α] [decidable_eq β] (l : list α) (f : α → β)
(hf : function.injective f) (x : α) :
count (f x) (map f l) = count x l :=
begin
induction l with y l IH generalizing x,
{ simp },
{ rw map_cons,
by_cases h : x = y,
{ simpa [h] using IH _ },
{ simpa [h, hf.ne h] using IH _ } }
end
end count
/-! ### prefix, suffix, infix -/
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
@[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) :=
by rw ← list.append_assoc; apply infix_append
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp only [reverse_reverse]
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
@[simp] theorem eq_nil_iff_infix_nil {l : list α} : l <:+: [] ↔ l = [] :=
⟨eq_nil_of_infix_nil, λ h, h ▸ infix_refl _⟩
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
@[simp] theorem eq_nil_iff_prefix_nil {l : list α} : l <+: [] ↔ l = [] :=
⟨eq_nil_of_prefix_nil, λ h, h ▸ prefix_refl _⟩
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
@[simp] theorem eq_nil_iff_suffix_nil {l : list α} : l <:+ [] ↔ l = [] :=
⟨eq_nil_of_suffix_nil, λ h, h ▸ suffix_refl _⟩
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem suffix_cons_iff {x : α} {l₁ l₂ : list α} :
l₁ <:+ x :: l₂ ↔ l₁ = x :: l₂ ∨ l₁ <:+ l₂ :=
begin
split,
{ rintro ⟨⟨hd, tl⟩, hl₃⟩,
{ exact or.inl hl₃ },
{ simp only [cons_append] at hl₃,
exact or.inr ⟨_, hl₃.2⟩ } },
{ rintro (rfl | hl₁),
{ exact (x :: l₂).suffix_refl },
{ exact hl₁.trans (l₂.suffix_cons _) } }
end
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_right_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_right_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix
lemma tail_sublist (l : list α) : l.tail <+ l := sublist_of_suffix (tail_suffix l)
theorem tail_subset (l : list α) : tail l ⊆ l := (tail_sublist l).subset
lemma mem_of_mem_tail {l : list α} {a : α} (h : a ∈ l.tail) : a ∈ l :=
tail_subset l h
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} :
l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
lemma prefix_take_le_iff {L : list (list (option α))} {m n : ℕ} (hm : m < L.length) :
(take m L) <+: (take n L) ↔ m ≤ n :=
begin
simp only [prefix_iff_eq_take, length_take],
induction m with m IH generalizing L n,
{ simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] },
{ cases n,
{ simp only [nat.nat_zero_eq_zero, nonpos_iff_eq_zero, take, take_nil],
split,
{ cases L,
{ exact absurd hm (not_lt_of_le m.succ.zero_le) },
{ simp only [forall_prop_of_false, not_false_iff, take] } },
{ intro h,
contradiction } },
{ cases L with l ls,
{ exact absurd hm (not_lt_of_le m.succ.zero_le) },
{ simp only [length] at hm,
specialize @IH ls n (nat.lt_of_succ_lt_succ hm),
simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH,
simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take],
exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ } } },
end
lemma cons_prefix_iff {l l' : list α} {x y : α} :
x :: l <+: y :: l' ↔ x = y ∧ l <+: l' :=
begin
split,
{ rintro ⟨L, hL⟩,
simp only [cons_append] at hL,
exact ⟨hL.left, ⟨L, hL.right⟩⟩ },
{ rintro ⟨rfl, h⟩,
rwa [prefix_cons_inj] },
end
lemma map_prefix {l l' : list α} (f : α → β) (h : l <+: l') :
l.map f <+: l'.map f :=
begin
induction l with hd tl hl generalizing l',
{ simp only [nil_prefix, map_nil] },
{ cases l' with hd' tl',
{ simpa only using eq_nil_of_prefix_nil h },
{ rw cons_prefix_iff at h,
simp only [h, prefix_cons_inj, hl, map] } },
end
lemma is_prefix.filter_map {l l' : list α} (h : l <+: l') (f : α → option β) :
l.filter_map f <+: l'.filter_map f :=
begin
induction l with hd tl hl generalizing l',
{ simp only [nil_prefix, filter_map_nil] },
{ cases l' with hd' tl',
{ simpa only using eq_nil_of_prefix_nil h },
{ rw cons_prefix_iff at h,
rw [←@singleton_append _ hd _, ←@singleton_append _ hd' _, filter_map_append,
filter_map_append, h.left, prefix_append_right_inj],
exact hl h.right } },
end
lemma is_prefix.reduce_option {l l' : list (option α)} (h : l <+: l') :
l.reduce_option <+: l'.reduce_option :=
h.filter_map id
lemma is_prefix.filter (p : α → Prop) [decidable_pred p]
⦃l l' : list α⦄ (h : l <+: l') : filter p l <+: filter p l' :=
begin
obtain ⟨xs, rfl⟩ := h,
rw filter_append,
exact prefix_append _ _
end
lemma is_suffix.filter (p : α → Prop) [decidable_pred p]
⦃l l' : list α⦄ (h : l <:+ l') : filter p l <:+ filter p l' :=
begin
obtain ⟨xs, rfl⟩ := h,
rw filter_append,
exact suffix_append _ _
end
lemma is_infix.filter (p : α → Prop) [decidable_pred p]
⦃l l' : list α⦄ (h : l <:+: l') : filter p l <:+: filter p l' :=
begin
obtain ⟨xs, ys, rfl⟩ := h,
rw [filter_append, filter_append],
exact infix_append _ _ _
end
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton],
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp only [tails, mem_singleton];
exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t];
exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| ._, t, or.inl rfl := suffix_refl _
| s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inl rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩)
end⟩
lemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) :=
by simp
lemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails :=
by simp
@[simp]
lemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l)
| [] [] := by simp
| [] (a::t) := by simp
| (a::s) t := by simp [inits_append s t]
@[simp]
lemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail
| [] [] := by simp
| [] (a::t) := by simp
| (a::s) t := by simp [tails_append s t]
-- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'`
lemma inits_eq_tails :
∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l)
| [] := by simp
| (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff]
lemma tails_eq_inits :
∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l)
| [] := by simp
| (a :: l) := by simp [tails_eq_inits l, append_left_inj]
lemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) :=
by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], }
lemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) :=
by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], }
lemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) :=
by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], }
lemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) :=
by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], }
@[simp] lemma length_tails (l : list α) : length (tails l) = length l + 1 :=
begin
induction l with x l IH,
{ simp },
{ simpa using IH }
end
@[simp] lemma length_inits (l : list α) : length (inits l) = length l + 1 :=
by simp [inits_eq_tails]
@[simp] lemma nth_le_tails (l : list α) (n : ℕ) (hn : n < length (tails l)) :
nth_le (tails l) n hn = l.drop n :=
begin
induction l with x l IH generalizing n,
{ simp },
{ cases n,
{ simp },
{ simpa using IH n _ } },
end
@[simp] lemma nth_le_inits (l : list α) (n : ℕ) (hn : n < length (inits l)) :
nth_le (inits l) n hn = l.take n :=
begin
induction l with x l IH generalizing n,
{ simp },
{ cases n,
{ simp },
{ simpa using IH n _ } }
end
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/-! ### insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp, priority 980]
theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp only [insert.def, if_pos h]
@[simp, priority 970]
theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp only [insert.def, if_neg h]; split; refl
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l,
{ simp only [insert_of_mem h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h' },
simp only [insert_of_not_mem h', mem_cons_iff]
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by rw insert_of_mem h
@[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by rw insert_of_not_mem h; refl
end insert
/-! ### erasep -/
section erasep
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem erasep_nil : [].erasep p = [] := rfl
theorem erasep_cons (a : α) (l : list α) :
(a :: l).erasep p = if p a then l else a :: l.erasep p := rfl
@[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l :=
by simp [erasep_cons, h]
@[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) :
(a::l).erasep p = a :: l.erasep p :=
by simp [erasep_cons, h]
theorem erasep_of_forall_not {l : list α}
(h : ∀ a ∈ l, ¬ p a) : l.erasep p = l :=
by induction l with _ _ ih; [refl,
simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]]
theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) :
∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
induction l with b l IH, {cases al},
by_cases pb : p b,
{ exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ },
{ rcases al with rfl | al, {exact pb.elim pa},
rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩,
h₂, by rw h₃; refl, by simp [pb, h₄]⟩ }
end
theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) :
l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
by_cases h : ∃ a ∈ l, p a,
{ rcases h with ⟨a, ha, pa⟩,
exact or.inr (exists_of_erasep ha pa) },
{ simp at h, exact or.inl (erasep_of_forall_not h) }
end
@[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) :
length (l.erasep p) = pred (length l) :=
by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩;
rw e₂; simp [-add_comm, e₁]; refl
theorem erasep_append_left {a : α} (pa : p a) :
∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : p x; simp [h'],
rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h),
rintro rfl, exact pa
end
theorem erasep_append_right :
∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1,
erasep_append_right _ (forall_mem_cons.1 h).2]
theorem erasep_sublist (l : list α) : l.erasep p <+ l :=
by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩;
[rw h, {rw [h₄, h₃], simp}]
theorem erasep_subset (l : list α) : l.erasep p ⊆ l :=
(erasep_sublist l).subset
theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p :=
begin
induction s,
case list.sublist.slnil { refl },
case list.sublist.cons : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] },
case list.sublist.cons2 : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [s, IH.cons2 _ _ _] }
end
theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l :=
@erasep_subset _ _ _ _ _
@[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l :=
⟨mem_of_mem_erasep, λ al, begin
rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
{ rwa h },
{ rw h₄, rw h₃ at al,
have : a ≠ c, {rintro rfl, exact pa.elim h₂},
simpa [this] using al }
end⟩
theorem erasep_map (f : β → α) :
∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f))
| [] := rfl
| (b::l) := by by_cases p (f b); simp [h, erasep_map l]
@[simp] theorem extractp_eq_find_erasep :
∀ l : list α, extractp p l = (find p l, erasep p l)
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l]
end erasep
/-! ### erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) :
(b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp only [erase_cons, if_pos rfl]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) :
(b::l).erase a = b :: l.erase a :=
by simp only [erase_cons, if_neg h]; split; refl
theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) :=
by { induction l with b l, {refl},
by_cases a = b; [simp [h], simp [h, ne.symm h, *]] }
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h'
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩;
rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (l.erase a) = pred (length l) :=
by rw erase_eq_erasep; exact length_erasep_of_mem h rfl
theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) :
(l₁++l₂).erase a = l₁.erase a ++ l₂ :=
by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h
theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) :
(l₁++l₂).erase a = l₁ ++ l₂.erase a :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right];
rintro b h' rfl; exact h h'
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
by rw erase_eq_erasep; apply erasep_sublist
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
(erase_sublist a l).subset
theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a :=
by simp [erase_eq_erasep]; exact sublist.erasep h
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by rw ab else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)]
else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)]
theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α}
(l : list α) : map f (l.erase a) = (map f l).erase (f a) :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr;
ext b; simp [finj.eq_iff]
theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ :=
by induction l₂ generalizing l₁; [refl,
simp only [foldl_cons, map_erase finj, *]]
@[simp] theorem count_erase_self (a : α) :
∀ (s : list α), count a (list.erase s a) = pred (count a s)
| [] := by simp
| (h :: t) :=
begin
rw erase_cons,
by_cases p : h = a,
{ rw [if_pos p, count_cons', if_pos p.symm], simp },
{ rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self],
simp, }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) :
∀ (s : list α), count a (list.erase s b) = count a s
| [] := by simp
| (x :: xs) :=
begin
rw erase_cons,
split_ifs with h,
{ rw [count_cons', h, if_neg ab], simp },
{ rw [count_cons', count_cons', count_erase_of_ne] }
end
end erase
/-! ### diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
if h : a ∈ l₁ then by simp only [list.diff, if_pos h]
else by simp only [list.diff, if_neg h, erase_of_not_mem h]
lemma diff_cons_right (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.diff l₂).erase a :=
begin
induction l₂ with b l₂ ih generalizing l₁ a,
{ simp_rw [diff_cons, diff_nil] },
{ rw [diff_cons, diff_cons, erase_comm, ← diff_cons, ih, ← diff_cons] }
end
lemma diff_erase (l₁ l₂ : list α) (a : α) : (l₁.diff l₂).erase a = (l₁.erase a).diff l₂ :=
by rw [← diff_cons_right, diff_cons]
@[simp] theorem nil_diff (l : list α) : [].diff l = [] :=
by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp only [diff_eq_foldl, foldl_append]
@[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) :=
by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁
| l₁ [] := sublist.refl _
| l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _
... <+ l₁.erase a : diff_sublist _ _
... <+ l₁ : list.erase_sublist _ _
theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ :=
(diff_sublist _ _).subset
theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂
| l₁ [] h₁ h₂ := h₁
| l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact
mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂)
theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃
| l₁ l₂ [] h := h
| l₁ l₂ (a::l₃) h := by simp only
[diff_cons, (h.erase _).diff_right]
theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α},
l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [] l₂ h := erase_sublist _ _
| (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]
else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons,
erase_comm a b l₂]
using erase_diff_erase_sublist_of_sublist (h.erase b)
end diff
/-! ### enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp only [enum, enum_from_nth, zero_add]; intros; refl
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
theorem mem_enum_from {x : α} {i : ℕ} :
∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs
| j [] := by simp [enum_from]
| j (y :: ys) :=
suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys →
j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys),
by simpa [enum_from, mem_enum_from ys],
begin
rintro (h|h),
{ refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩,
apply nat.lt_add_of_pos_right; simp },
{ obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h,
refine ⟨_, _, _⟩,
{ exact le_trans (nat.le_succ _) hji },
{ convert hijlen using 1, ac_refl },
{ simp [hmem] } }
end
/-! ### product -/
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; [exact (zero_mul _).symm,
simp only [length, product_cons, length_append, IH,
right_distrib, one_mul, length_map, add_comm]]
/-! ### sigma -/
section
variable {σ : α → Type*}
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left,
and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; [refl,
simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]]
end
/-! ### disjoint -/
section disjoint
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) :
disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) :
disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] :=
by rw disjoint_comm; exact disjoint_nil_left _
@[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp only [disjoint, mem_singleton, forall_eq]; refl
@[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp only [singleton_disjoint]
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint]
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₂ :=
(disjoint_append_right.1 d).2
theorem disjoint_take_drop {l : list α} {m n : ℕ} (hl : l.nodup) (h : m ≤ n) :
disjoint (l.take m) (l.drop n) :=
begin
induction l generalizing m n,
case list.nil : m n
{ simp },
case list.cons : x xs xs_ih m n
{ cases m; cases n; simp only [disjoint_cons_left, mem_cons_iff, disjoint_cons_right, drop,
true_or, eq_self_iff_true, not_true, false_and,
disjoint_nil_left, take],
{ cases h },
cases hl with _ _ h₀ h₁, split,
{ intro h, exact h₀ _ (mem_of_mem_drop h) rfl, },
solve_by_elim [le_of_succ_le_succ] { max_depth := 4 } },
end
end disjoint
/-! ### union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff,
mem_cons_iff, or_assoc, *]
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
if h : a ∈ l₁ ∪ l₂
then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩
else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h];
split; refl⟩
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp (λ a, and.right)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_union, or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/-! ### inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
@[simp] lemma inter_reverse {xs ys : list α} :
xs.inter ys.reverse = xs.inter ys :=
by simp only [list.inter, mem_reverse]; congr
end inter
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
/-! ### map₂_left' -/
section map₂_left'
-- The definitional equalities for `map₂_left'` can already be used by the
-- simplifie because `map₂_left'` is marked `@[simp]`.
@[simp] theorem map₂_left'_nil_right (f : α → option β → γ) (as) :
map₂_left' f as [] = (as.map (λ a, f a none), []) :=
by cases as; refl
end map₂_left'
/-! ### map₂_right' -/
section map₂_right'
variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem map₂_right'_nil_left :
map₂_right' f [] bs = (bs.map (f none), []) :=
by cases bs; refl
@[simp] theorem map₂_right'_nil_right :
map₂_right' f as [] = ([], as) :=
rfl
@[simp] theorem map₂_right'_nil_cons :
map₂_right' f [] (b :: bs) = (f none b :: bs.map (f none), []) :=
rfl
@[simp] theorem map₂_right'_cons_cons :
map₂_right' f (a :: as) (b :: bs) =
let rec := map₂_right' f as bs in
(f (some a) b :: rec.fst, rec.snd) :=
rfl
end map₂_right'
/-! ### zip_left' -/
section zip_left'
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_left'_nil_right :
zip_left' as ([] : list β) = (as.map (λ a, (a, none)), []) :=
by cases as; refl
@[simp] theorem zip_left'_nil_left :
zip_left' ([] : list α) bs = ([], bs) :=
rfl
@[simp] theorem zip_left'_cons_nil :
zip_left' (a :: as) ([] : list β) = ((a, none) :: as.map (λ a, (a, none)), []) :=
rfl
@[simp] theorem zip_left'_cons_cons :
zip_left' (a :: as) (b :: bs) =
let rec := zip_left' as bs in
((a, some b) :: rec.fst, rec.snd) :=
rfl
end zip_left'
/-! ### zip_right' -/
section zip_right'
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_right'_nil_left :
zip_right' ([] : list α) bs = (bs.map (λ b, (none, b)), []) :=
by cases bs; refl
@[simp] theorem zip_right'_nil_right :
zip_right' as ([] : list β) = ([], as) :=
rfl
@[simp] theorem zip_right'_nil_cons :
zip_right' ([] : list α) (b :: bs) = ((none, b) :: bs.map (λ b, (none, b)), []) :=
rfl
@[simp] theorem zip_right'_cons_cons :
zip_right' (a :: as) (b :: bs) =
let rec := zip_right' as bs in
((some a, b) :: rec.fst, rec.snd) :=
rfl
end zip_right'
/-! ### map₂_left -/
section map₂_left
variables (f : α → option β → γ) (as : list α)
-- The definitional equalities for `map₂_left` can already be used by the
-- simplifier because `map₂_left` is marked `@[simp]`.
@[simp] theorem map₂_left_nil_right :
map₂_left f as [] = as.map (λ a, f a none) :=
by cases as; refl
theorem map₂_left_eq_map₂_left' : ∀ as bs,
map₂_left f as bs = (map₂_left' f as bs).fst
| [] bs := by simp!
| (a :: as) [] := by simp!
| (a :: as) (b :: bs) := by simp! [*]
theorem map₂_left_eq_map₂ : ∀ as bs,
length as ≤ length bs →
map₂_left f as bs = map₂ (λ a b, f a (some b)) as bs
| [] [] h := by simp!
| [] (b :: bs) h := by simp!
| (a :: as) [] h := by { simp at h, contradiction }
| (a :: as) (b :: bs) h := by { simp at h, simp! [*] }
end map₂_left
/-! ### map₂_right -/
section map₂_right
variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem map₂_right_nil_left :
map₂_right f [] bs = bs.map (f none) :=
by cases bs; refl
@[simp] theorem map₂_right_nil_right :
map₂_right f as [] = [] :=
rfl
@[simp] theorem map₂_right_nil_cons :
map₂_right f [] (b :: bs) = f none b :: bs.map (f none) :=
rfl
@[simp] theorem map₂_right_cons_cons :
map₂_right f (a :: as) (b :: bs) = f (some a) b :: map₂_right f as bs :=
rfl
theorem map₂_right_eq_map₂_right' :
map₂_right f as bs = (map₂_right' f as bs).fst :=
by simp only [map₂_right, map₂_right', map₂_left_eq_map₂_left']
theorem map₂_right_eq_map₂ (h : length bs ≤ length as) :
map₂_right f as bs = map₂ (λ a b, f (some a) b) as bs :=
begin
have : (λ a b, flip f a (some b)) = (flip (λ a b, f (some a) b)) := rfl,
simp only [map₂_right, map₂_left_eq_map₂, map₂_flip, *]
end
end map₂_right
/-! ### zip_left -/
section zip_left
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_left_nil_right :
zip_left as ([] : list β) = as.map (λ a, (a, none)) :=
by cases as; refl
@[simp] theorem zip_left_nil_left :
zip_left ([] : list α) bs = [] :=
rfl
@[simp] theorem zip_left_cons_nil :
zip_left (a :: as) ([] : list β) = (a, none) :: as.map (λ a, (a, none)) :=
rfl
@[simp] theorem zip_left_cons_cons :
zip_left (a :: as) (b :: bs) = (a, some b) :: zip_left as bs :=
rfl
theorem zip_left_eq_zip_left' :
zip_left as bs = (zip_left' as bs).fst :=
by simp only [zip_left, zip_left', map₂_left_eq_map₂_left']
end zip_left
/-! ### zip_right -/
section zip_right
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_right_nil_left :
zip_right ([] : list α) bs = bs.map (λ b, (none, b)) :=
by cases bs; refl
@[simp] theorem zip_right_nil_right :
zip_right as ([] : list β) = [] :=
rfl
@[simp] theorem zip_right_nil_cons :
zip_right ([] : list α) (b :: bs) = (none, b) :: bs.map (λ b, (none, b)) :=
rfl
@[simp] theorem zip_right_cons_cons :
zip_right (a :: as) (b :: bs) = (some a, b) :: zip_right as bs :=
rfl
theorem zip_right_eq_zip_right' :
zip_right as bs = (zip_right' as bs).fst :=
by simp only [zip_right, zip_right', map₂_right_eq_map₂_right']
end zip_right
/-! ### to_chunks -/
section to_chunks
@[simp] theorem to_chunks_nil (n) : @to_chunks α n [] = [] := by cases n; refl
theorem to_chunks_aux_eq (n) : ∀ xs i,
@to_chunks_aux α n xs i = (xs.take i, (xs.drop i).to_chunks (n+1))
| [] i := by cases i; refl
| (x::xs) 0 := by rw [to_chunks_aux, drop, to_chunks]; cases to_chunks_aux n xs n; refl
| (x::xs) (i+1) := by rw [to_chunks_aux, to_chunks_aux_eq]; refl
theorem to_chunks_eq_cons' (n) : ∀ {xs : list α} (h : xs ≠ []),
xs.to_chunks (n+1) = xs.take (n+1) :: (xs.drop (n+1)).to_chunks (n+1)
| [] e := (e rfl).elim
| (x::xs) _ := by rw [to_chunks, to_chunks_aux_eq]; refl
theorem to_chunks_eq_cons : ∀ {n} {xs : list α} (n0 : n ≠ 0) (x0 : xs ≠ []),
xs.to_chunks n = xs.take n :: (xs.drop n).to_chunks n
| 0 _ e := (e rfl).elim
| (n+1) xs _ := to_chunks_eq_cons' _
theorem to_chunks_aux_join {n} : ∀ {xs i l L}, @to_chunks_aux α n xs i = (l, L) → l ++ L.join = xs
| [] _ _ _ rfl := rfl
| (x::xs) i l L e := begin
cases i; [
cases e' : to_chunks_aux n xs n with l L,
cases e' : to_chunks_aux n xs i with l L];
{ rw [to_chunks_aux, e', to_chunks_aux] at e, cases e,
exact (congr_arg (cons x) (to_chunks_aux_join e') : _) }
end
@[simp] theorem to_chunks_join : ∀ n xs, (@to_chunks α n xs).join = xs
| n [] := by cases n; refl
| 0 (x::xs) := by simp only [to_chunks, join]; rw append_nil
| (n+1) (x::xs) := begin
rw to_chunks,
cases e : to_chunks_aux n xs n with l L,
exact (congr_arg (cons x) (to_chunks_aux_join e) : _),
end
theorem to_chunks_length_le : ∀ n xs, n ≠ 0 → ∀ l : list α,
l ∈ @to_chunks α n xs → l.length ≤ n
| 0 _ e _ := (e rfl).elim
| (n+1) xs _ l := begin
refine (measure_wf length).induction xs _, intros xs IH h,
by_cases x0 : xs = [], {subst xs, cases h},
rw to_chunks_eq_cons' _ x0 at h, rcases h with rfl|h,
{ apply length_take_le },
{ refine IH _ _ h,
simp only [measure, inv_image, length_drop],
exact sub_lt_self' (length_pos_iff_ne_nil.2 x0) (succ_pos _) },
end
end to_chunks
/-! ### Miscellaneous lemmas -/
theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l
| a [] := or.inl rfl
| a (b::l) := or.inr (ilast'_mem b l)
@[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) :
(L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) :=
calc (L.attach.nth_le i H).1
= (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map'
... = L.nth_le i _ : by congr; apply attach_map_val
end list
@[to_additive]
theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) :
f l.prod = (l.map f).prod :=
(l.prod_hom f).symm
namespace list
@[to_additive]
theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) :
(L.map (g ∘ f)).prod = g ((L.map f).prod) :=
by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm}
theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, r * f b)).sum = r * (L.map f).sum :=
sum_map_hom L f $ add_monoid_hom.mul_left r
theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, f b * r)).sum = (L.map f).sum * r :=
sum_map_hom L f $ add_monoid_hom.mul_right r
universes u v
@[simp]
theorem mem_map_swap {α : Type u} {β : Type v} (x : α) (y : β) (xs : list (α × β)) :
(y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs :=
begin
induction xs with x xs,
{ simp only [not_mem_nil, map_nil] },
{ cases x with a b,
simp only [mem_cons_iff, prod.mk.inj_iff, map, prod.swap_prod_mk,
prod.exists, xs_ih, and_comm] },
end
lemma slice_eq {α} (xs : list α) (n m : ℕ) :
slice n m xs = xs.take n ++ xs.drop (n+m) :=
begin
induction n generalizing xs,
{ simp [slice] },
{ cases xs; simp [slice, *, nat.succ_add], }
end
lemma sizeof_slice_lt {α} [has_sizeof α] (i j : ℕ) (hj : 0 < j) (xs : list α) (hi : i < xs.length) :
sizeof (list.slice i j xs) < sizeof xs :=
begin
induction xs generalizing i j,
case list.nil : i j h
{ cases hi },
case list.cons : x xs xs_ih i j h
{ cases i; simp only [-slice_eq, list.slice],
{ cases j, cases h,
dsimp only [drop], unfold_wf,
apply @lt_of_le_of_lt _ _ _ xs.sizeof,
{ clear_except,
induction xs generalizing j; unfold_wf,
case list.nil : j
{ refl },
case list.cons : xs_hd xs_tl xs_ih j
{ cases j; unfold_wf, refl,
transitivity, apply xs_ih,
simp }, },
unfold_wf, apply zero_lt_one_add, },
{ unfold_wf, apply xs_ih _ _ h,
apply lt_of_succ_lt_succ hi, } },
end
end list
|
4f6d2d106fed095494c0be681463519222d615c9 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/mv_polynomial/basic.lean | ab08656db9308c4666c64a8fce378308043e0584 | [
"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 | 37,623 | 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, Johan Commelin, Mario Carneiro
-/
import data.polynomial.eval
import data.finsupp.antidiagonal
/-!
# Multivariate polynomials
This file defines polynomial rings over a base ring (or even semiring),
with variables from a general type `σ` (which could be infinite).
## Important definitions
Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary
type. This file creates the type `mv_polynomial σ R`, which mathematicians
might denote $R[X_i : i \in σ]$. It is the type of multivariate
(a.k.a. multivariable) polynomials, with variables
corresponding to the terms in `σ`, and coefficients in `R`.
### Notation
In the definitions below, we use the following notation:
+ `σ : Type*` (indexing the variables)
+ `R : Type*` `[comm_semiring R]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `a : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ R`
### Definitions
* `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients
in the commutative semiring `R`
* `monomial s a` : the monomial which mathematically would be denoted `a * X^s`
* `C a` : the constant polynomial with value `a`
* `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`.
* `coeff s p` : the coefficient of `s` in `p`.
* `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another
semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`.
Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested
that sticking to `eval` and `map` might make the code less brittle.
* `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation,
returning a term of type `R`
* `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of
coefficient semiring corresponding to `f`
## Implementation notes
Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite
support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`.
The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all
monomials in the variables, and the function to `R` sends a monomial to its coefficient in
the polynomial being represented.
## Tags
polynomial, multivariate polynomial, multivariable polynomial
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w x
variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`R` is the coefficient ring -/
def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ)
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
section instances
instance decidable_eq_mv_polynomial [comm_semiring R] [decidable_eq σ] [decidable_eq R] :
decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq
instance [comm_semiring R] : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring
instance [comm_semiring R] : inhabited (mv_polynomial σ R) := ⟨0⟩
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] :
distrib_mul_action R (mv_polynomial σ S₁) :=
add_monoid_algebra.distrib_mul_action
instance [semiring R] [comm_semiring S₁] [module R S₁] : module R (mv_polynomial σ S₁) :=
add_monoid_algebra.module
instance [monoid R] [monoid S₁] [comm_semiring S₂]
[has_scalar R S₁] [distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [is_scalar_tower R S₁ S₂] :
is_scalar_tower R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.is_scalar_tower
instance [monoid R] [monoid S₁][comm_semiring S₂]
[distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [smul_comm_class R S₁ S₂] :
smul_comm_class R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.smul_comm_class
instance [comm_semiring R] [comm_semiring S₁] [algebra R S₁] : algebra R (mv_polynomial σ S₁) :=
add_monoid_algebra.algebra
end instances
variables [comm_semiring R] [comm_semiring S₁] {p q : mv_polynomial σ R}
/-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/
def monomial (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := single s a
lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl
lemma mul_def : (p * q) = p.sum (λ m a, q.sum $ λ n b, monomial (m + n) (a * b)) := rfl
/-- `C a` is the constant polynomial with value `a` -/
def C : R →+* mv_polynomial σ R :=
{ to_fun := monomial 0, ..single_zero_ring_hom }
variables (R σ)
theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl
variables {R σ}
/-- `X n` is the degree `1` monomial $X_n$. -/
def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1
lemma C_apply : (C a : mv_polynomial σ R) = monomial 0 a := rfl
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C_apply, monomial]
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl
lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C_apply, monomial, single_mul_single]
@[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm
@[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n :=
by induction n; simp [pow_succ, *]
lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] :
function.injective (C : R → mv_polynomial σ R) :=
finsupp.single_injective _
lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) (hσ : ¬ nonempty σ) :
function.surjective (C : R → mv_polynomial σ R) :=
begin
refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩,
simpa [(finsupp.ext (λ x, absurd (nonempty.intro x) hσ) : a = 0), C_apply, monomial],
end
lemma C_surjective_fin_0 {R : Type*} [comm_ring R] :
function.surjective (mv_polynomial.C : R → mv_polynomial (fin 0) R) :=
C_surjective (fin 0) (λ h, let ⟨n⟩ := h in fin_zero_elim n)
@[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) :
(C r : mv_polynomial σ R) = C s ↔ r = s :=
(C_injective σ R).eq_iff
instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective C (C_injective _ _)
instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R]
[nontrivial R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective ((λ s : σ →₀ ℕ, monomial s 1) ∘ single (classical.arbitrary σ)) $
function.injective.comp
(λ m n, (finsupp.single_left_inj one_ne_zero).mp) (finsupp.single_injective _)
lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n :=
by induction n; simp [nat.succ_eq_add_one, *]
theorem C_mul' : mv_polynomial.C a * p = a • p :=
(algebra.smul_def a p).symm
lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm
lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : R) :=
begin
induction e,
{ simp [X], refl },
{ simp [pow_succ, e_ih],
simp [X, monomial, single_mul_single, nat.succ_eq_add_one, add_comm] }
end
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) :=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) :=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_eq_C_mul_X {s : σ} {a : R} {n : ℕ} :
monomial (single s n) a = C a * (X s)^n :=
by rw [← zero_add (single s n), monomial_add_single, C_apply]
@[simp] lemma monomial_add {s : σ →₀ ℕ} {a b : R} :
monomial s a + monomial s b = monomial s (a + b) :=
single_add.symm
@[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} :
monomial s a * monomial s' b = monomial (s + s') (a * b) :=
add_monoid_algebra.single_mul_single
@[simp] lemma monomial_zero {s : σ →₀ ℕ}: monomial s (0 : R) = 0 :=
single_zero
@[simp] lemma sum_monomial_eq {A : Type*} [add_comm_monoid A]
{u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) :
sum (monomial u r) b = b u r :=
sum_single_index w
@[simp] lemma sum_C {A : Type*} [add_comm_monoid A]
{b : (σ →₀ ℕ) → R → A} (w : b 0 0 = 0) :
sum (C a) b = b 0 a :=
by simp [C_apply, w]
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
begin
apply @finsupp.induction σ ℕ _ _ s,
{ simp only [C_apply, prod_zero_index]; exact (mul_one _).symm },
{ assume n e s hns he ih,
rw [monomial_single_add, ih, prod_add_index, prod_single_index, mul_left_comm],
{ simp only [pow_zero], },
{ intro a, simp only [pow_zero], },
{ intros, rw pow_add, }, }
end
@[recursor 5]
lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) :
M p :=
have ∀s a, M (monomial s a),
begin
assume s a,
apply @finsupp.induction σ ℕ _ _ s,
{ show M (monomial 0 a), from h_C a, },
{ assume n e p hpn he ih,
have : ∀e:ℕ, M (monomial p a * X n ^ e),
{ intro e,
induction e,
{ simp [ih] },
{ simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } },
simp [add_comm, monomial_add_single, this] }
end,
finsupp.induction p
(by have : M (C 0) := h_C 0; rwa [C_0] at this)
(assume s a p hsp ha hp, h_add _ _ (this s a) hp)
attribute [elab_as_eliminator]
theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a))
(h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p :=
finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this,
show P (monomial 0 0), from h1 0 0)
(λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf)
@[ext] lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A}
(hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) :
f = g :=
by { ext, exacts [hC _, hX _] }
lemma hom_eq_hom [semiring S₂]
(f g : mv_polynomial σ R →+* S₂)
(hC : ∀a:R, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) :
f p = g p :=
ring_hom.congr_fun (ring_hom_ext hC hX) p
lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R)
(hC : ∀a:R, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) :
f p = p :=
hom_eq_hom f (ring_hom.id _) hC hX p
@[ext] lemma alg_hom_ext {A : Type*} [comm_semiring A] [algebra R A]
{f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) :
f = g :=
by { ext, exact hf _ }
@[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) :
f (C r) = C r :=
f.commutes r
section support
/--
The finite set of all `m : σ →₀ ℕ` such that `X^m` has a non-zero coefficient.
-/
def support (p : mv_polynomial σ R) : finset (σ →₀ ℕ) :=
p.support
lemma support_monomial [decidable (a = 0)] : (monomial s a).support = if a = 0 then ∅ else {s} :=
by convert rfl
lemma support_monomial_subset : (monomial s a).support ⊆ {s} :=
support_single_subset
lemma support_add : (p + q).support ⊆ p.support ∪ q.support := finsupp.support_add
lemma support_X [nontrivial R] : (X n : mv_polynomial σ R).support = {single n 1} :=
by rw [X, support_monomial, if_neg]; exact one_ne_zero
end support
section coeff
/-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/
def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R :=
@coe_fn _ (monoid_algebra.has_coe_to_fun _ _) p m
@[simp] lemma mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∈ p.support ↔ p.coeff m ≠ 0 :=
by simp [support, coeff]
lemma not_mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∉ p.support ↔ p.coeff m = 0 :=
by simp
lemma sum_def {A} [add_comm_monoid A] {p : mv_polynomial σ R} {b : (σ →₀ ℕ) → R → A} :
p.sum b = ∑ m in p.support, b m (p.coeff m) :=
by simp [support, finsupp.sum, coeff]
lemma support_mul (p q : mv_polynomial σ R) :
(p * q).support ⊆ p.support.bUnion (λ a, q.support.bUnion $ λ b, {a + b}) :=
by convert add_monoid_algebra.support_mul p q; ext; convert iff.rfl
@[ext] lemma ext (p q : mv_polynomial σ R) :
(∀ m, coeff m p = coeff m q) → p = q := ext
lemma ext_iff (p q : mv_polynomial σ R) :
p = q ↔ (∀ m, coeff m p = coeff m q) :=
⟨ λ h m, by rw h, ext p q⟩
@[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) :
coeff m (p + q) = coeff m p + coeff m q := add_apply p q m
@[simp] lemma coeff_smul {S₁ : Type*} [monoid S₁] [distrib_mul_action S₁ R]
(m : σ →₀ ℕ) (c : S₁) (p : mv_polynomial σ R) :
coeff m (c • p) = c • coeff m p := smul_apply c p m
@[simp] lemma coeff_zero (m : σ →₀ ℕ) :
coeff m (0 : mv_polynomial σ R) = 0 := rfl
@[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 :=
single_eq_of_ne (λ h, by cases single_eq_zero.1 h)
instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) :
is_add_monoid_hom (coeff m : mv_polynomial σ R → R) :=
{ map_add := coeff_add m,
map_zero := coeff_zero m }
lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) :
coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) :=
(s.sum_hom _).symm
lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
by simp [monomial_eq]
@[simp] lemma coeff_monomial [decidable_eq σ] (m n) (a) :
coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 :=
single_apply
@[simp] lemma coeff_C [decidable_eq σ] (m) (a) :
coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 :=
single_apply
lemma coeff_one [decidable_eq σ] (m) :
coeff m (1 : mv_polynomial σ R) = if 0 = m then 1 else 0 :=
coeff_C m 1
@[simp] lemma coeff_zero_C (a) : coeff 0 (C a : mv_polynomial σ R) = a :=
single_eq_same
@[simp] lemma coeff_zero_one : coeff 0 (1 : mv_polynomial σ R) = 1 :=
coeff_zero_C 1
lemma coeff_X_pow [decidable_eq σ] (i : σ) (m) (k : ℕ) :
coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 :=
begin
have := coeff_monomial m (finsupp.single i k) (1:R),
rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _,
C_1, one_mul, finsupp.prod_single_index] at this,
exact pow_zero _
end
lemma coeff_X' [decidable_eq σ] (i : σ) (m) :
coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 :=
by rw [← coeff_X_pow, pow_one]
@[simp] lemma coeff_X (i : σ) :
coeff (single i 1) (X i : mv_polynomial σ R) = 1 :=
by rw [coeff_X', if_pos rfl]
@[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) :
coeff m (C a * p) = a * coeff m p :=
begin
rw [mul_def, sum_C],
{ simp [sum_def, coeff_sum] {contextual := tt} },
simp
end
lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) :
coeff n (p * q) = ∑ x in antidiagonal n, coeff x.1 p * coeff x.2 q :=
begin
rw mul_def,
-- We need to manipulate both sides into a shape to which we can apply `finset.sum_bij_ne_zero`,
-- so we need to turn both sides into a sum over a product.
have := @finset.sum_product R (σ →₀ ℕ) _ _ p.support q.support
(λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0),
convert this.symm using 1; clear this,
{ rw [coeff],
iterate 2 { rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only },
exact single_apply },
symmetry,
-- We are now ready to show that both sums are equal using `finset.sum_bij_ne_zero`.
apply finset.sum_bij_ne_zero (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)) _ _, (x.1, x.2)),
{ intros x hx hx',
simp only [mem_antidiagonal, eq_self_iff_true, if_false, forall_true_iff],
contrapose! hx',
rw [if_neg hx'] },
{ rintros ⟨i, j⟩ ⟨k, l⟩ hij hij' hkl hkl',
simpa only [and_imp, prod.mk.inj_iff, heq_iff_eq] using and.intro },
{ rintros ⟨i, j⟩ hij hij',
refine ⟨⟨i, j⟩, _, _⟩,
{ simp only [mem_support_iff, finset.mem_product],
contrapose! hij',
exact mul_eq_zero_of_ne_zero_imp_eq_zero hij' },
{ rw [mem_antidiagonal] at hij,
simp only [exists_prop, true_and, ne.def, if_pos hij, hij', not_false_iff] } },
{ intros x hx hx',
simp only [ne.def] at hx' ⊢,
split_ifs with H,
{ refl },
{ rw if_neg H at hx', contradiction } }
end
@[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) :
coeff (m + single s 1) (p * X s) = coeff m p :=
begin
have : (m, single s 1) ∈ (m + single s 1).antidiagonal := mem_antidiagonal.2 rfl,
rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
finset.sum_eq_zero, add_zero, coeff_X, mul_one],
rintros ⟨i,j⟩ hij,
rw [finset.mem_erase, mem_antidiagonal] at hij,
by_cases H : single s 1 = j,
{ subst j, simpa using hij },
{ rw [coeff_X', if_neg H, mul_zero] },
end
lemma coeff_mul_X' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) :
coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
nontriviality R,
split_ifs with h h,
{ conv_rhs {rw ← coeff_mul_X _ s},
congr' with t,
by_cases hj : s = t,
{ subst t, simp only [nat_sub_apply, add_apply, single_eq_same],
refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa finsupp.mem_support_iff at h },
{ simp [single_eq_of_ne hj] } },
{ rw ← not_mem_support_iff, intro hm, apply h,
have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H,
rcases H with ⟨j, hj, i', hi', H⟩,
rw [support_X, finset.mem_singleton] at hi', subst i',
rw finset.mem_singleton at H, subst m,
rw [finsupp.mem_support_iff, add_apply, single_apply, if_pos rfl],
intro H, rw [_root_.add_eq_zero_iff] at H, exact one_ne_zero H.2 }
end
lemma eq_zero_iff {p : mv_polynomial σ R} :
p = 0 ↔ ∀ d, coeff d p = 0 :=
by { rw ext_iff, simp only [coeff_zero], }
lemma ne_zero_iff {p : mv_polynomial σ R} :
p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 :=
by { rw [ne.def, eq_zero_iff], push_neg, }
lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) :
∃ d, coeff d p ≠ 0 :=
ne_zero_iff.mp h
lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) :
C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i :=
begin
split,
{ rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right },
{ intro h,
choose c hc using h,
classical,
let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0,
let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i),
use ψ,
apply mv_polynomial.ext, intro i,
simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'],
split_ifs with hi hi,
{ rw hc },
{ rw not_mem_support_iff at hi, rwa mul_zero } },
end
end coeff
section constant_coeff
/--
`constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`.
This is a ring homomorphism.
-/
def constant_coeff : mv_polynomial σ R →+* R :=
{ to_fun := coeff 0,
map_one' := by simp [coeff, add_monoid_algebra.one_def],
map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero],
map_zero' := coeff_zero _,
map_add' := coeff_add _ }
lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl
@[simp]
lemma constant_coeff_C (r : R) :
constant_coeff (C r : mv_polynomial σ R) = r :=
by simp [constant_coeff_eq]
@[simp]
lemma constant_coeff_X (i : σ) :
constant_coeff (X i : mv_polynomial σ R) = 0 :=
by simp [constant_coeff_eq]
lemma constant_coeff_monomial [decidable_eq σ] (d : σ →₀ ℕ) (r : R) :
constant_coeff (monomial d r) = if d = 0 then r else 0 :=
by rw [constant_coeff_eq, coeff_monomial]
variables (σ R)
@[simp] lemma constant_coeff_comp_C :
constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R :=
by { ext, apply constant_coeff_C }
@[simp] lemma constant_coeff_comp_algebra_map :
constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R :=
constant_coeff_comp_C _ _
end constant_coeff
section as_sum
@[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) :
∑ v in p.support, monomial v (coeff v p) = p :=
finsupp.sum_single p
lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) :=
(support_sum_monomial_coeff p).symm
end as_sum
section eval₂
variables (f : R →+* S₁) (g : σ → S₁)
/-- Evaluate a polynomial `p` given a valuation `g` of all the variables
and a ring hom `f` from the scalar ring to the target -/
def eval₂ (p : mv_polynomial σ R) : S₁ :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i :=
by { simp only [eval₂_eq, ← finsupp.prod_pow], refl }
@[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 :=
finsupp.sum_zero_index
section
@[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g :=
finsupp.sum_add_index
(by simp [is_semiring_hom.map_zero f])
(by simp [add_mul, is_semiring_hom.map_add f])
@[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) :=
finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f])
@[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a :=
by simp [eval₂_monomial, C, prod_zero_index]
@[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 :=
(eval₂_C _ _ _).trans (is_semiring_hom.map_one f)
@[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n :=
by simp [eval₂_monomial,
is_semiring_hom.map_one f, X, prod_single_index, pow_one]
lemma eval₂_mul_monomial :
∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) :=
begin
apply mv_polynomial.induction_on p,
{ assume a' s a,
simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] },
{ assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] },
{ assume p n ih s a,
from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g :
by simp [monomial_single_add, -add_comm, pow_one, mul_assoc]
... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) :
by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm,
is_semiring_hom.map_one f, -add_comm] }
end
@[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g :=
begin
apply mv_polynomial.induction_on q,
{ simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] },
{ simp [mul_add, eval₂_add] {contextual := tt} },
{ simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} }
end
@[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n
| 0 := by { rw [pow_zero, pow_zero], exact eval₂_one _ _ }
| (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow]
instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) :=
{ map_zero := eval₂_zero _ _,
map_one := eval₂_one _ _,
map_add := λ p q, eval₂_add _ _,
map_mul := λ p q, eval₂_mul _ _ }
/-- `mv_polynomial.eval₂` as a `ring_hom`. -/
def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ := ring_hom.of (eval₂ f g)
@[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) : ⇑(eval₂_hom f g) = eval₂ f g := rfl
lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} :
f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ :=
by rintros rfl rfl rfl; refl
end
@[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) :
eval₂_hom f g (C r) = f r := eval₂_C f g r
@[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) :
eval₂_hom f g (X i) = g i := eval₂_X f g i
@[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) :
φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) :=
begin
apply mv_polynomial.ring_hom_ext,
{ intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] },
{ intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] }
end
lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) :=
by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod,
ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X']
section
local attribute [instance, priority 10] is_semiring_hom.comp
lemma eval₂_comp_left {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, k.map_add,
eval₂_mul, k.map_mul] {contextual := tt}
end
@[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
lemma eval₂_congr (g₁ g₂ : σ → S₁)
(h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) :
p.eval₂ f g₁ = p.eval₂ f g₂ :=
begin
apply finset.sum_congr rfl,
intros c hc, dsimp, congr' 1,
apply finset.prod_congr rfl,
intros i hi, dsimp, congr' 1,
apply h hi,
rwa finsupp.mem_support_iff at hc
end
@[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) :=
(s.prod_hom _).symm
@[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) :=
(s.sum_hom _).symm
attribute [to_additive] eval₂_prod
lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) :
eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) :=
begin
show _ = eval₂_hom f g (eval₂ C q p),
rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp,
end
end eval₂
section eval
variables {f : σ → R}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f
lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i :=
eval₂_eq' (ring_hom.id R) x f
lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _
@[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p :=
by rw [smul_eq_C_mul, (eval x).map_mul, eval_C]
lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) :=
(eval g).map_sum _ _
@[to_additive]
lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) :=
(eval g).map_prod _ _
theorem eval_assoc {τ}
(f : σ → mv_polynomial τ R) (g : τ → R)
(p : mv_polynomial σ R) :
eval (eval g ∘ f) p = eval g (eval₂ C f p) :=
begin
rw eval₂_comp_left (eval g),
unfold eval, simp only [coe_eval₂_hom],
congr' with a, simp
end
end eval
section map
variables (f : R →+* S₁)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _
theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta
theorem map_map [comm_semiring S₂]
(g : S₁ →+* S₂)
(p : mv_polynomial σ R) :
map g (map f p) = map (g.comp f) p :=
(eval₂_comp_left (map g) (C.comp f) X p).trans $
begin
congr,
{ ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], },
{ ext1 n, simp only [map_X, comp_app], }
end
theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) :
p.eval₂ f g = eval g (map f p) :=
begin
unfold map eval, simp only [coe_eval₂_hom],
have h := eval₂_comp_left (eval₂_hom _ g),
dsimp at h,
rw h,
congr,
{ ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], },
{ ext1 n, simp only [comp_app, eval₂_X], },
end
lemma eval₂_comp_right {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] },
{ intros p s hp,
rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] }
end
lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) :
map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] },
{ intros p s hp,
rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] }
end
lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) :=
begin
apply mv_polynomial.induction_on p; clear p,
{ intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero },
{ intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add },
{ intros p i hp m, simp only [hp, (map f).map_mul, map_X],
simp only [hp, mem_support_iff, coeff_mul_X'],
split_ifs, {refl},
rw is_semiring_hom.map_zero f }
end
lemma map_injective (hf : function.injective f) :
function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) :=
begin
intros p q h,
simp only [ext_iff, coeff_map] at h ⊢,
intro m,
exact hf (h m),
end
@[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) :
eval g (map f p) = eval₂ f g p :=
by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } }
@[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂ φ g (map f p) = eval₂ (φ.comp f) g p :=
by { rw [← eval_map, ← eval_map, map_map], }
@[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p :=
eval₂_map f g φ p
@[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) :
constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) :=
coeff_map f φ 0
lemma constant_coeff_comp_map (f : R →+* S₁) :
(constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff :=
by { ext; simp }
lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support :=
begin
intro x,
simp only [mem_support_iff],
contrapose!,
change p.coeff x = 0 → (map f p).coeff x = 0,
rw coeff_map,
intro hx,
rw hx,
exact ring_hom.map_zero f
end
lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) :
(map f p).support = p.support :=
begin
apply finset.subset.antisymm,
{ exact mv_polynomial.support_map_subset _ _ },
intros x hx,
rw mem_support_iff,
contrapose! hx,
simp only [not_not, mem_support_iff],
change (map f p).coeff x = 0 at hx,
rw [coeff_map, ← f.map_zero] at hx,
exact hf hx
end
lemma C_dvd_iff_map_hom_eq_zero
(q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r')
(φ : mv_polynomial σ R) :
C r ∣ φ ↔ map q φ = 0 :=
begin
rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff],
simp only [coeff_map, ring_hom.coe_of, coeff_zero, hr],
end
lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) :
map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ :=
begin
rw mv_polynomial.ext_iff,
apply forall_congr, intro m,
rw [coeff_map],
apply eq_iff_eq_cancel_right.mpr,
refl
end
end map
section aeval
/-! ### The algebra of multivariate polynomials -/
variables (f : σ → S₁)
variables [algebra R S₁] [comm_semiring S₂]
/-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism
from multivariate polynomials over `σ` to `S₁`. -/
def aeval : mv_polynomial σ R →ₐ[R] S₁ :=
{ commutes' := λ r, eval₂_C _ _ _
.. eval₂_hom (algebra_map R S₁) f }
theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl
lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) :
aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl
@[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _
@[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _
theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) :
φ = aeval (φ ∘ X) :=
by { ext i, simp }
lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B]
(φ : S₁ →ₐ[R] B) :
φ.comp (aeval f) = aeval (λ i, φ (f i)) :=
by { ext i, simp }
@[simp] lemma map_aeval {B : Type*} [comm_semiring B]
(g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) :
φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
@[simp] lemma eval₂_hom_zero (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) :=
begin
suffices : eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff,
from ring_hom.congr_fun this p,
ext; simp
end
@[simp] lemma eval₂_hom_zero' (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) :=
eval₂_hom_zero f p
@[simp] lemma aeval_zero (p : mv_polynomial σ R) :
aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
eval₂_hom_zero (algebra_map R S₁) p
@[simp] lemma aeval_zero' (p : mv_polynomial σ R) :
aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
aeval_zero p
lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) :=
eval₂_hom_monomial _ _ _ _
lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) :
eval₂_hom f g φ = 0 :=
begin
rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero],
intros d hd,
obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd),
rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero],
rw [hgi, zero_pow],
rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff]
end
lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) :
aeval f φ = 0 :=
eval₂_hom_eq_zero _ _ _ h
end aeval
end comm_semiring
end mv_polynomial
|
03ea9e7b89888da97ce1f810f6a13ce5048569be | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/qpf/multivariate/constructions/fix_auto.lean | 64ea601068d01640b15216d7ba5986576da52f8b | [] | 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 | 12,123 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.pfunctor.multivariate.W
import Mathlib.data.qpf.multivariate.basic
import Mathlib.PostPort
universes u u_1
namespace Mathlib
/-!
# The initial algebra of a multivariate qpf is again a qpf.
For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with
regards to its last argument `αₙ`. The result is a `n`-ary functor: `fix F (α₀,..,αₙ₋₁)`.
Making `fix F` into a functor allows us to take the fixed point, compose with other functors
and take a fixed point again.
## Main definitions
* `fix.mk` - constructor
* `fix.dest - destructor
* `fix.rec` - recursor: basis for defining functions by structural recursion on `fix F α`
* `fix.drec` - dependent recursor: generalization of `fix.rec` where the result type of the function
is allowed to dependent on the `fix F α` value
* `fix.rec_eq` - defining equation for `recursor`
* `fix.ind` - induction principle for `fix F α`
## Implementation notes
For `F` a QPF`, we define `fix F α` in terms of the W-type of the polynomial functor `P` of `F`.
We define the relation `Wequiv` and take its quotient as the definition of `fix F α`.
```lean
inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop
| ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) :
(∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁)
| abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α)
(a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) :
abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ →
Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁)
| trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w
```
See [avigad-carneiro-hudon2019] for more details.
## Reference
* [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
namespace mvqpf
/-- `recF` is used as a basis for defining the recursor on `fix F α`. `recF`
traverses recursively the W-type generated by `q.P` using a function on `F`
as a recursive step -/
def recF {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n}
{β : Type u} (g : F (α ::: β) → β) : mvpfunctor.W (P F) α → β :=
mvpfunctor.W_rec (P F)
fun (a : mvpfunctor.A (P F)) (f' : typevec.arrow (mvpfunctor.B (mvpfunctor.drop (P F)) a) α)
(f : pfunctor.B (mvpfunctor.last (P F)) a → mvpfunctor.W (P F) α)
(rec : pfunctor.B (mvpfunctor.last (P F)) a → β) =>
g (abs (sigma.mk a (typevec.split_fun f' rec)))
theorem recF_eq {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n}
{β : Type u} (g : F (α ::: β) → β) (a : mvpfunctor.A (P F))
(f' : typevec.arrow (mvpfunctor.B (mvpfunctor.drop (P F)) a) α)
(f : pfunctor.B (mvpfunctor.last (P F)) a → mvpfunctor.W (P F) α) :
recF g (mvpfunctor.W_mk (P F) a f' f) =
g (abs (sigma.mk a (typevec.split_fun f' (recF g ∘ f)))) :=
sorry
theorem recF_eq' {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n}
{β : Type u} (g : F (α ::: β) → β) (x : mvpfunctor.W (P F) α) :
recF g x = g (abs (mvfunctor.map (typevec.id ::: recF g) (mvpfunctor.W_dest' (P F) x))) :=
sorry
/-- Equivalence relation on W-types that represent the same `fix F`
value -/
inductive Wequiv {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} : mvpfunctor.W (P F) α → mvpfunctor.W (P F) α → Prop
where
| ind :
∀ (a : mvpfunctor.A (P F)) (f' : typevec.arrow (mvpfunctor.B (mvpfunctor.drop (P F)) a) α)
(f₀ f₁ : pfunctor.B (mvpfunctor.last (P F)) a → mvpfunctor.W (P F) α),
(∀ (x : pfunctor.B (mvpfunctor.last (P F)) a), Wequiv (f₀ x) (f₁ x)) →
Wequiv (mvpfunctor.W_mk (P F) a f' f₀) (mvpfunctor.W_mk (P F) a f' f₁)
| abs :
∀ (a₀ : mvpfunctor.A (P F)) (f'₀ : typevec.arrow (mvpfunctor.B (mvpfunctor.drop (P F)) a₀) α)
(f₀ : pfunctor.B (mvpfunctor.last (P F)) a₀ → mvpfunctor.W (P F) α) (a₁ : mvpfunctor.A (P F))
(f'₁ : typevec.arrow (mvpfunctor.B (mvpfunctor.drop (P F)) a₁) α)
(f₁ : pfunctor.B (mvpfunctor.last (P F)) a₁ → mvpfunctor.W (P F) α),
abs (sigma.mk a₀ (mvpfunctor.append_contents (P F) f'₀ f₀)) =
abs (sigma.mk a₁ (mvpfunctor.append_contents (P F) f'₁ f₁)) →
Wequiv (mvpfunctor.W_mk (P F) a₀ f'₀ f₀) (mvpfunctor.W_mk (P F) a₁ f'₁ f₁)
| trans : ∀ (u v w : mvpfunctor.W (P F) α), Wequiv u v → Wequiv v w → Wequiv u w
theorem recF_eq_of_Wequiv {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
(α : typevec n) {β : Type u} (u : F (α ::: β) → β) (x : mvpfunctor.W (P F) α)
(y : mvpfunctor.W (P F) α) : Wequiv x y → recF u x = recF u y :=
sorry
theorem Wequiv.abs' {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} (x : mvpfunctor.W (P F) α) (y : mvpfunctor.W (P F) α)
(h : abs (mvpfunctor.W_dest' (P F) x) = abs (mvpfunctor.W_dest' (P F) y)) : Wequiv x y :=
sorry
theorem Wequiv.refl {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} (x : mvpfunctor.W (P F) α) : Wequiv x x :=
sorry
theorem Wequiv.symm {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} (x : mvpfunctor.W (P F) α) (y : mvpfunctor.W (P F) α) :
Wequiv x y → Wequiv y x :=
sorry
/-- maps every element of the W type to a canonical representative -/
def Wrepr {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n} :
mvpfunctor.W (P F) α → mvpfunctor.W (P F) α :=
recF (mvpfunctor.W_mk' (P F) ∘ repr)
theorem Wrepr_W_mk {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} (a : mvpfunctor.A (P F))
(f' : typevec.arrow (mvpfunctor.B (mvpfunctor.drop (P F)) a) α)
(f : pfunctor.B (mvpfunctor.last (P F)) a → mvpfunctor.W (P F) α) :
Wrepr (mvpfunctor.W_mk (P F) a f' f) =
mvpfunctor.W_mk' (P F)
(repr
(abs
(mvfunctor.map (typevec.id ::: Wrepr)
(sigma.mk a (mvpfunctor.append_contents (P F) f' f))))) :=
sorry
theorem Wrepr_equiv {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} (x : mvpfunctor.W (P F) α) : Wequiv (Wrepr x) x :=
sorry
theorem Wequiv_map {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} {β : typevec n} (g : typevec.arrow α β) (x : mvpfunctor.W (P F) α)
(y : mvpfunctor.W (P F) α) : Wequiv x y → Wequiv (mvfunctor.map g x) (mvfunctor.map g y) :=
sorry
/--
Define the fixed point as the quotient of trees under the equivalence relation.
-/
def W_setoid {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] (α : typevec n) :
setoid (mvpfunctor.W (P F) α) :=
setoid.mk Wequiv sorry
/-- Least fixed point of functor F. The result is a functor with one fewer parameters
than the input. For `F a b c` a ternary functor, fix F is a binary functor such that
```lean
fix F a b = F a b (fix F a b)
```
-/
def fix {n : ℕ} (F : typevec (n + 1) → Type u_1) [mvfunctor F] [q : mvqpf F] (α : typevec n) :=
quotient (W_setoid α)
/-- `fix F` is a functor -/
def fix.map {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n}
{β : typevec n} (g : typevec.arrow α β) : fix F α → fix F β :=
quotient.lift (fun (x : mvpfunctor.W (P F) α) => quotient.mk (mvpfunctor.W_map (P F) g x)) sorry
protected instance fix.mvfunctor {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F]
[q : mvqpf F] : mvfunctor (fix F) :=
mvfunctor.mk fix.map
/-- Recursor for `fix F` -/
def fix.rec {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n}
{β : Type u} (g : F (α ::: β) → β) : fix F α → β :=
Quot.lift (recF g) (recF_eq_of_Wequiv α g)
/-- Access W-type underlying `fix F` -/
def fix_to_W {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n} :
fix F α → mvpfunctor.W (P F) α :=
quotient.lift Wrepr sorry
/-- Constructor for `fix F` -/
def fix.mk {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n}
(x : F (α ::: fix F α)) : fix F α :=
Quot.mk setoid.r (mvpfunctor.W_mk' (P F) (mvfunctor.map (typevec.id ::: fix_to_W) (repr x)))
/-- Destructor for `fix F` -/
def fix.dest {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n} :
fix F α → F (α ::: fix F α) :=
fix.rec (mvfunctor.map (typevec.id ::: fix.mk))
theorem fix.rec_eq {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} {β : Type u} (g : F (α ::: β) → β) (x : F (α ::: fix F α)) :
fix.rec g (fix.mk x) = g (mvfunctor.map (typevec.id ::: fix.rec g) x) :=
sorry
theorem fix.ind_aux {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} (a : mvpfunctor.A (P F))
(f' : typevec.arrow (mvpfunctor.B (mvpfunctor.drop (P F)) a) α)
(f : pfunctor.B (mvpfunctor.last (P F)) a → mvpfunctor.W (P F) α) :
fix.mk
(abs
(sigma.mk a
(mvpfunctor.append_contents (P F) f'
fun (x : pfunctor.B (mvpfunctor.last (P F)) a) => quotient.mk (f x)))) =
quotient.mk (mvpfunctor.W_mk (P F) a f' f) :=
sorry
theorem fix.ind_rec {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} {β : Type u} (g₁ : fix F α → β) (g₂ : fix F α → β)
(h :
∀ (x : F (α ::: fix F α)),
mvfunctor.map (typevec.id ::: g₁) x = mvfunctor.map (typevec.id ::: g₂) x →
g₁ (fix.mk x) = g₂ (fix.mk x))
(x : fix F α) : g₁ x = g₂ x :=
sorry
theorem fix.rec_unique {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} {β : Type u} (g : F (α ::: β) → β) (h : fix F α → β)
(hyp : ∀ (x : F (α ::: fix F α)), h (fix.mk x) = g (mvfunctor.map (typevec.id ::: h) x)) :
fix.rec g = h :=
sorry
theorem fix.mk_dest {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} (x : fix F α) : fix.mk (fix.dest x) = x :=
sorry
theorem fix.dest_mk {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F]
{α : typevec n} (x : F (α ::: fix F α)) : fix.dest (fix.mk x) = x :=
sorry
theorem fix.ind {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n}
(p : fix F α → Prop)
(h : ∀ (x : F (α ::: fix F α)), mvfunctor.liftp (typevec.pred_last α p) x → p (fix.mk x))
(x : fix F α) : p x :=
sorry
protected instance mvqpf_fix {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] :
mvqpf (fix F) :=
mk (mvpfunctor.Wp (P F)) (fun (α : typevec n) => Quot.mk Wequiv) (fun (α : typevec n) => fix_to_W)
sorry sorry
/-- Dependent recursor for `fix F` -/
def fix.drec {n : ℕ} {F : typevec (n + 1) → Type u} [mvfunctor F] [q : mvqpf F] {α : typevec n}
{β : fix F α → Type u}
(g : (x : F (α ::: sigma β)) → β (fix.mk (mvfunctor.map (typevec.id ::: sigma.fst) x)))
(x : fix F α) : β x :=
let y : sigma β :=
fix.rec
(fun (i : F (α ::: sigma β)) =>
sigma.mk (fix.mk (mvfunctor.map (typevec.id ::: sigma.fst) i)) (g i))
x;
(fun (this : x = sigma.fst y) => cast sorry (sigma.snd y)) sorry
end Mathlib |
f4e595268a3606d84059c1452fffc815af460e81 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/modtest1.lean | 519fd8baec698576d9bae6afd111a8f2cf4c3d4a | [
"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 | 894 | lean | import init.lean.parser.module
open Lean
open Lean.Parser
partial def parseCommands (env : Environment) (displayStx : Bool) : ModuleParser → IO ModuleParser
| p =>
match parseCommand env p with
| (stx, p) =>
if isEOI stx then pure p
else do
when displayStx (IO.println stx);
parseCommands p
def testParser (input : String) (displayStx := true) : IO Unit :=
do
env ← mkEmptyEnvironment;
let (stx, p) := mkModuleParser env input "<input>";
when displayStx (IO.println stx);
p ← parseCommands env displayStx p;
p.messages.toList.mfor $ fun msg => IO.println msg;
pure ()
def main (xs : List String) : IO Unit :=
do
testParser "
prelude
import init.core
universes u v
def b : Type
class Alternative (f : Type u → Type v) extends Applicative f : Type (max (u+1) v) :=
(failure : ∀ {α : Type u}, f α)
(orelse : ∀ {α : Type u}, f α → f α → f α)
"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.