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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
defb0a0ab72def89fb9914bde34e58c82d1404d0 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/lattice.lean | fd452479a780c5fa0ad2c415e519bc408887cebf | [
"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 | 44,219 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import order.monotone
import tactic.simps
import tactic.pi_instances
/-!
# (Semi-)lattices
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/642
> Any changes to this file require a corresponding PR to mathlib4.
Semilattices are partially ordered sets with join (greatest lower bound, or `sup`) or
meet (least upper bound, or `inf`) operations. Lattices are posets that are both
join-semilattices and meet-semilattices.
Distributive lattices are lattices which satisfy any of four equivalent distributivity properties,
of `sup` over `inf`, on the left or on the right.
## Main declarations
* `semilattice_sup`: a type class for join semilattices
* `semilattice_sup.mk'`: an alternative constructor for `semilattice_sup` via proofs that `⊔` is
commutative, associative and idempotent.
* `semilattice_inf`: a type class for meet semilattices
* `semilattice_sup.mk'`: an alternative constructor for `semilattice_inf` via proofs that `⊓` is
commutative, associative and idempotent.
* `lattice`: a type class for lattices
* `lattice.mk'`: an alternative constructor for `lattice` via profs that `⊔` and `⊓` are
commutative, associative and satisfy a pair of "absorption laws".
* `distrib_lattice`: a type class for distributive lattices.
## Notations
* `a ⊔ b`: the supremum or join of `a` and `b`
* `a ⊓ b`: the infimum or meet of `a` and `b`
## TODO
* (Semi-)lattice homomorphisms
* Alternative constructors for distributive lattices from the other distributive properties
## Tags
semilattice, lattice
-/
set_option old_structure_cmd true
universes u v w
variables {α : Type u} {β : Type v}
-- TODO: move this eventually, if we decide to use them
attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans
section
-- TODO: this seems crazy, but it also seems to work reasonably well
@[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b :=
@le_antisymm _ _
end
/- TODO: automatic construction of dual definitions / theorems -/
/-!
### Join-semilattices
-/
/-- A `semilattice_sup` is a join-semilattice, that is, a partial order
with a join (a.k.a. lub / least upper bound, sup / supremum) operation
`⊔` which is the least element larger than both factors. -/
@[protect_proj, ancestor has_sup partial_order]
class semilattice_sup (α : Type u) extends has_sup α, partial_order α :=
(le_sup_left : ∀ a b : α, a ≤ a ⊔ b)
(le_sup_right : ∀ a b : α, b ≤ a ⊔ b)
(sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c)
/--
A type with a commutative, associative and idempotent binary `sup` operation has the structure of a
join-semilattice.
The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`.
-/
def semilattice_sup.mk' {α : Type*} [has_sup α]
(sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a)
(sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c))
(sup_idem : ∀ (a : α), a ⊔ a = a) : semilattice_sup α :=
{ sup := (⊔),
le := λ a b, a ⊔ b = b,
le_refl := sup_idem,
le_trans := λ a b c hab hbc,
begin
dsimp only [(≤)] at *,
rwa [←hbc, ←sup_assoc, hab],
end,
le_antisymm := λ a b hab hba,
begin
dsimp only [(≤)] at *,
rwa [←hba, sup_comm],
end,
le_sup_left := λ a b, show a ⊔ (a ⊔ b) = (a ⊔ b), by rw [←sup_assoc, sup_idem],
le_sup_right := λ a b, show b ⊔ (a ⊔ b) = (a ⊔ b), by rw [sup_comm, sup_assoc, sup_idem],
sup_le := λ a b c hac hbc,
begin
dsimp only [(≤), preorder.le] at *,
rwa [sup_assoc, hbc],
end }
instance (α : Type*) [has_inf α] : has_sup αᵒᵈ := ⟨((⊓) : α → α → α)⟩
instance (α : Type*) [has_sup α] : has_inf αᵒᵈ := ⟨((⊔) : α → α → α)⟩
section semilattice_sup
variables [semilattice_sup α] {a b c d : α}
@[simp] theorem le_sup_left : a ≤ a ⊔ b :=
semilattice_sup.le_sup_left a b
@[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) :=
le_sup_left
@[simp] theorem le_sup_right : b ≤ a ⊔ b :=
semilattice_sup.le_sup_right a b
@[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) :=
le_sup_right
theorem le_sup_of_le_left (h : c ≤ a) : c ≤ a ⊔ b :=
le_trans h le_sup_left
theorem le_sup_of_le_right (h : c ≤ b) : c ≤ a ⊔ b :=
le_trans h le_sup_right
theorem lt_sup_of_lt_left (h : c < a) : c < a ⊔ b :=
h.trans_le le_sup_left
theorem lt_sup_of_lt_right (h : c < b) : c < a ⊔ b :=
h.trans_le le_sup_right
theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c :=
semilattice_sup.sup_le a b c
@[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c :=
⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩,
assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩
@[simp] lemma sup_eq_left : a ⊔ b = a ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_rfl]
@[simp] lemma sup_eq_right : a ⊔ b = b ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_rfl]
@[simp] lemma left_eq_sup : a = a ⊔ b ↔ b ≤ a := eq_comm.trans sup_eq_left
@[simp] lemma right_eq_sup : b = a ⊔ b ↔ a ≤ b := eq_comm.trans sup_eq_right
alias sup_eq_left ↔ _ sup_of_le_left
alias sup_eq_right ↔ le_of_sup_eq sup_of_le_right
attribute [simp] sup_of_le_left sup_of_le_right
@[simp] theorem left_lt_sup : a < a ⊔ b ↔ ¬b ≤ a :=
le_sup_left.lt_iff_ne.trans $ not_congr left_eq_sup
@[simp] theorem right_lt_sup : b < a ⊔ b ↔ ¬a ≤ b :=
le_sup_right.lt_iff_ne.trans $ not_congr right_eq_sup
lemma left_or_right_lt_sup (h : a ≠ b) : (a < a ⊔ b ∨ b < a ⊔ b) :=
h.not_le_or_not_le.symm.imp left_lt_sup.2 right_lt_sup.2
theorem le_iff_exists_sup : a ≤ b ↔ ∃ c, b = a ⊔ c :=
begin
split,
{ intro h, exact ⟨b, (sup_eq_right.mpr h).symm⟩ },
{ rintro ⟨c, (rfl : _ = _ ⊔ _)⟩,
exact le_sup_left }
end
theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d :=
sup_le (le_sup_of_le_left h₁) (le_sup_of_le_right h₂)
theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b :=
sup_le_sup le_rfl h₁
theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c :=
sup_le_sup h₁ le_rfl
@[simp] theorem sup_idem : a ⊔ a = a :=
by apply le_antisymm; simp
instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩
theorem sup_comm : a ⊔ b = b ⊔ a :=
by apply le_antisymm; simp
instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩
theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) :=
eq_of_forall_ge_iff $ λ x, by simp only [sup_le_iff, and_assoc]
instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩
lemma sup_left_right_swap (a b c : α) : a ⊔ b ⊔ c = c ⊔ b ⊔ a :=
by rw [sup_comm, @sup_comm _ _ a, sup_assoc]
@[simp] lemma sup_left_idem : a ⊔ (a ⊔ b) = a ⊔ b :=
by rw [← sup_assoc, sup_idem]
@[simp] lemma sup_right_idem : (a ⊔ b) ⊔ b = a ⊔ b :=
by rw [sup_assoc, sup_idem]
lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) :=
by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a]
lemma sup_right_comm (a b c : α) : a ⊔ b ⊔ c = a ⊔ c ⊔ b :=
by rw [sup_assoc, sup_assoc, @sup_comm _ _ b]
lemma sup_sup_sup_comm (a b c d : α) : a ⊔ b ⊔ (c ⊔ d) = a ⊔ c ⊔ (b ⊔ d) :=
by rw [sup_assoc, sup_left_comm b, ←sup_assoc]
lemma sup_sup_distrib_left (a b c : α) : a ⊔ (b ⊔ c) = (a ⊔ b) ⊔ (a ⊔ c) :=
by rw [sup_sup_sup_comm, sup_idem]
lemma sup_sup_distrib_right (a b c : α) : (a ⊔ b) ⊔ c = (a ⊔ c) ⊔ (b ⊔ c) :=
by rw [sup_sup_sup_comm, sup_idem]
lemma sup_congr_left (hb : b ≤ a ⊔ c) (hc : c ≤ a ⊔ b) : a ⊔ b = a ⊔ c :=
(sup_le le_sup_left hb).antisymm $ sup_le le_sup_left hc
lemma sup_congr_right (ha : a ≤ b ⊔ c) (hb : b ≤ a ⊔ c) : a ⊔ c = b ⊔ c :=
(sup_le ha le_sup_right).antisymm $ sup_le hb le_sup_right
lemma sup_eq_sup_iff_left : a ⊔ b = a ⊔ c ↔ b ≤ a ⊔ c ∧ c ≤ a ⊔ b :=
⟨λ h, ⟨h ▸ le_sup_right, h.symm ▸ le_sup_right⟩, λ h, sup_congr_left h.1 h.2⟩
lemma sup_eq_sup_iff_right : a ⊔ c = b ⊔ c ↔ a ≤ b ⊔ c ∧ b ≤ a ⊔ c :=
⟨λ h, ⟨h ▸ le_sup_left, h.symm ▸ le_sup_left⟩, λ h, sup_congr_right h.1 h.2⟩
lemma ne.lt_sup_or_lt_sup (hab : a ≠ b) : a < a ⊔ b ∨ b < a ⊔ b :=
hab.symm.not_le_or_not_le.imp left_lt_sup.2 right_lt_sup.2
/-- If `f` is monotone, `g` is antitone, and `f ≤ g`, then for all `a`, `b` we have `f a ≤ g b`. -/
theorem monotone.forall_le_of_antitone {β : Type*} [preorder β] {f g : α → β}
(hf : monotone f) (hg : antitone g) (h : f ≤ g) (m n : α) :
f m ≤ g n :=
calc f m ≤ f (m ⊔ n) : hf le_sup_left
... ≤ g (m ⊔ n) : h _
... ≤ g n : hg le_sup_right
theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y)
(x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y :=
eq_of_forall_ge_iff $ λ c,
by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H]
theorem semilattice_sup.ext {α} {A B : semilattice_sup α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x),
casesI A, casesI B,
injection this; congr'
end
lemma ite_le_sup (s s' : α) (P : Prop) [decidable P] : ite P s s' ≤ s ⊔ s' :=
if h : P then (if_pos h).trans_le le_sup_left else (if_neg h).trans_le le_sup_right
end semilattice_sup
/-!
### Meet-semilattices
-/
/-- A `semilattice_inf` is a meet-semilattice, that is, a partial order
with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation
`⊓` which is the greatest element smaller than both factors. -/
@[protect_proj, ancestor has_inf partial_order]
class semilattice_inf (α : Type u) extends has_inf α, partial_order α :=
(inf_le_left : ∀ a b : α, a ⊓ b ≤ a)
(inf_le_right : ∀ a b : α, a ⊓ b ≤ b)
(le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c)
instance (α) [semilattice_inf α] : semilattice_sup αᵒᵈ :=
{ le_sup_left := semilattice_inf.inf_le_left,
le_sup_right := semilattice_inf.inf_le_right,
sup_le := assume a b c hca hcb, @semilattice_inf.le_inf α _ _ _ _ hca hcb,
.. order_dual.partial_order α, .. order_dual.has_sup α }
instance (α) [semilattice_sup α] : semilattice_inf αᵒᵈ :=
{ inf_le_left := @le_sup_left α _,
inf_le_right := @le_sup_right α _,
le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb,
.. order_dual.partial_order α, .. order_dual.has_inf α }
theorem semilattice_sup.dual_dual (α : Type*) [H : semilattice_sup α] :
order_dual.semilattice_sup αᵒᵈ = H :=
semilattice_sup.ext $ λ _ _, iff.rfl
section semilattice_inf
variables [semilattice_inf α] {a b c d : α}
@[simp] theorem inf_le_left : a ⊓ b ≤ a :=
semilattice_inf.inf_le_left a b
@[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a :=
semilattice_inf.inf_le_left a b
@[simp] theorem inf_le_right : a ⊓ b ≤ b :=
semilattice_inf.inf_le_right a b
@[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b :=
semilattice_inf.inf_le_right a b
theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c :=
semilattice_inf.le_inf a b c
theorem inf_le_of_left_le (h : a ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_left h
theorem inf_le_of_right_le (h : b ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_right h
theorem inf_lt_of_left_lt (h : a < c) : a ⊓ b < c :=
lt_of_le_of_lt inf_le_left h
theorem inf_lt_of_right_lt (h : b < c) : a ⊓ b < c :=
lt_of_le_of_lt inf_le_right h
@[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := @sup_le_iff αᵒᵈ _ _ _ _
@[simp] lemma inf_eq_left : a ⊓ b = a ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_rfl]
@[simp] lemma inf_eq_right : a ⊓ b = b ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_rfl]
@[simp] lemma left_eq_inf : a = a ⊓ b ↔ a ≤ b := eq_comm.trans inf_eq_left
@[simp] lemma right_eq_inf : b = a ⊓ b ↔ b ≤ a := eq_comm.trans inf_eq_right
alias inf_eq_left ↔ le_of_inf_eq inf_of_le_left
alias inf_eq_right ↔ _ inf_of_le_right
attribute [simp] inf_of_le_left inf_of_le_right
@[simp] theorem inf_lt_left : a ⊓ b < a ↔ ¬a ≤ b := @left_lt_sup αᵒᵈ _ _ _
@[simp] theorem inf_lt_right : a ⊓ b < b ↔ ¬b ≤ a := @right_lt_sup αᵒᵈ _ _ _
theorem inf_lt_left_or_right (h : a ≠ b) : a ⊓ b < a ∨ a ⊓ b < b :=
@left_or_right_lt_sup αᵒᵈ _ _ _ h
theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d :=
@sup_le_sup αᵒᵈ _ _ _ _ _ h₁ h₂
lemma inf_le_inf_right (a : α) {b c : α} (h : b ≤ c) : b ⊓ a ≤ c ⊓ a := inf_le_inf h le_rfl
lemma inf_le_inf_left (a : α) {b c : α} (h : b ≤ c) : a ⊓ b ≤ a ⊓ c := inf_le_inf le_rfl h
@[simp] lemma inf_idem : a ⊓ a = a := @sup_idem αᵒᵈ _ _
instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩
lemma inf_comm : a ⊓ b = b ⊓ a := @sup_comm αᵒᵈ _ _ _
instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩
lemma inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := @sup_assoc αᵒᵈ _ a b c
instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩
lemma inf_left_right_swap (a b c : α) : a ⊓ b ⊓ c = c ⊓ b ⊓ a := @sup_left_right_swap αᵒᵈ _ _ _ _
@[simp] lemma inf_left_idem : a ⊓ (a ⊓ b) = a ⊓ b := @sup_left_idem αᵒᵈ _ a b
@[simp] lemma inf_right_idem : (a ⊓ b) ⊓ b = a ⊓ b := @sup_right_idem αᵒᵈ _ a b
lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := @sup_left_comm αᵒᵈ _ a b c
lemma inf_right_comm (a b c : α) : a ⊓ b ⊓ c = a ⊓ c ⊓ b := @sup_right_comm αᵒᵈ _ a b c
lemma inf_inf_inf_comm (a b c d : α) : a ⊓ b ⊓ (c ⊓ d) = a ⊓ c ⊓ (b ⊓ d) :=
@sup_sup_sup_comm αᵒᵈ _ _ _ _ _
lemma inf_inf_distrib_left (a b c : α) : a ⊓ (b ⊓ c) = (a ⊓ b) ⊓ (a ⊓ c) :=
@sup_sup_distrib_left αᵒᵈ _ _ _ _
lemma inf_inf_distrib_right (a b c : α) : (a ⊓ b) ⊓ c = (a ⊓ c) ⊓ (b ⊓ c) :=
@sup_sup_distrib_right αᵒᵈ _ _ _ _
lemma inf_congr_left (hb : a ⊓ c ≤ b) (hc : a ⊓ b ≤ c) : a ⊓ b = a ⊓ c :=
@sup_congr_left αᵒᵈ _ _ _ _ hb hc
lemma inf_congr_right (h1 : b ⊓ c ≤ a) (h2 : a ⊓ c ≤ b) : a ⊓ c = b ⊓ c :=
@sup_congr_right αᵒᵈ _ _ _ _ h1 h2
lemma inf_eq_inf_iff_left : a ⊓ b = a ⊓ c ↔ a ⊓ c ≤ b ∧ a ⊓ b ≤ c :=
@sup_eq_sup_iff_left αᵒᵈ _ _ _ _
lemma inf_eq_inf_iff_right : a ⊓ c = b ⊓ c ↔ b ⊓ c ≤ a ∧ a ⊓ c ≤ b :=
@sup_eq_sup_iff_right αᵒᵈ _ _ _ _
lemma ne.inf_lt_or_inf_lt : a ≠ b → a ⊓ b < a ∨ a ⊓ b < b := @ne.lt_sup_or_lt_sup αᵒᵈ _ _ _
theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y)
(x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y :=
eq_of_forall_le_iff $ λ c,
by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H]
theorem semilattice_inf.ext {α} {A B : semilattice_inf α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x),
casesI A, casesI B,
injection this; congr'
end
theorem semilattice_inf.dual_dual (α : Type*) [H : semilattice_inf α] :
order_dual.semilattice_inf αᵒᵈ = H :=
semilattice_inf.ext $ λ _ _, iff.rfl
lemma inf_le_ite (s s' : α) (P : Prop) [decidable P] : s ⊓ s' ≤ ite P s s' :=
@ite_le_sup αᵒᵈ _ _ _ _ _
end semilattice_inf
/--
A type with a commutative, associative and idempotent binary `inf` operation has the structure of a
meet-semilattice.
The partial order is defined so that `a ≤ b` unfolds to `b ⊓ a = a`; cf. `inf_eq_right`.
-/
def semilattice_inf.mk' {α : Type*} [has_inf α]
(inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a)
(inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c))
(inf_idem : ∀ (a : α), a ⊓ a = a) : semilattice_inf α :=
begin
haveI : semilattice_sup αᵒᵈ := semilattice_sup.mk' inf_comm inf_assoc inf_idem,
haveI i := order_dual.semilattice_inf αᵒᵈ,
exact i,
end
/-!
### Lattices
-/
/-- A lattice is a join-semilattice which is also a meet-semilattice. -/
@[protect_proj, ancestor semilattice_sup semilattice_inf]
class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α
instance (α) [lattice α] : lattice αᵒᵈ :=
{ .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α }
/-- The partial orders from `semilattice_sup_mk'` and `semilattice_inf_mk'` agree
if `sup` and `inf` satisfy the lattice absorption laws `sup_inf_self` (`a ⊔ a ⊓ b = a`)
and `inf_sup_self` (`a ⊓ (a ⊔ b) = a`). -/
lemma semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order {α : Type*}
[has_sup α] [has_inf α]
(sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a)
(sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c))
(sup_idem : ∀ (a : α), a ⊔ a = a)
(inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a)
(inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c))
(inf_idem : ∀ (a : α), a ⊓ a = a)
(sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a)
(inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) :
@semilattice_sup.to_partial_order _ (semilattice_sup.mk' sup_comm sup_assoc sup_idem) =
@semilattice_inf.to_partial_order _ (semilattice_inf.mk' inf_comm inf_assoc inf_idem) :=
partial_order.ext $ λ a b, show a ⊔ b = b ↔ b ⊓ a = a, from
⟨λ h, by rw [←h, inf_comm, inf_sup_self],
λ h, by rw [←h, sup_comm, sup_inf_self]⟩
/--
A type with a pair of commutative and associative binary operations which satisfy two absorption
laws relating the two operations has the structure of a lattice.
The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`.
-/
def lattice.mk' {α : Type*} [has_sup α] [has_inf α]
(sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a)
(sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c))
(inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a)
(inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c))
(sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a)
(inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : lattice α :=
have sup_idem : ∀ (b : α), b ⊔ b = b := λ b,
calc b ⊔ b = b ⊔ b ⊓ (b ⊔ b) : by rw inf_sup_self
... = b : by rw sup_inf_self,
have inf_idem : ∀ (b : α), b ⊓ b = b := λ b,
calc b ⊓ b = b ⊓ (b ⊔ b ⊓ b) : by rw sup_inf_self
... = b : by rw inf_sup_self,
let semilatt_inf_inst := semilattice_inf.mk' inf_comm inf_assoc inf_idem,
semilatt_sup_inst := semilattice_sup.mk' sup_comm sup_assoc sup_idem,
-- here we help Lean to see that the two partial orders are equal
partial_order_inst := @semilattice_sup.to_partial_order _ semilatt_sup_inst in
have partial_order_eq :
partial_order_inst = @semilattice_inf.to_partial_order _ semilatt_inf_inst :=
semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order _ _ _ _ _ _
sup_inf_self inf_sup_self,
{ inf_le_left := λ a b, by { rw partial_order_eq, apply inf_le_left },
inf_le_right := λ a b, by { rw partial_order_eq, apply inf_le_right },
le_inf := λ a b c, by { rw partial_order_eq, apply le_inf },
..partial_order_inst,
..semilatt_sup_inst,
..semilatt_inf_inst, }
section lattice
variables [lattice α] {a b c d : α}
lemma inf_le_sup : a ⊓ b ≤ a ⊔ b := inf_le_left.trans le_sup_left
@[simp] lemma inf_lt_sup : a ⊓ b < a ⊔ b ↔ a ≠ b :=
begin
split,
{ rintro H rfl, simpa using H },
{ refine λ Hne, lt_iff_le_and_ne.2 ⟨inf_le_sup, λ Heq, Hne _⟩,
refine le_antisymm _ _,
exacts [le_sup_left.trans (Heq.symm.trans_le inf_le_right),
le_sup_right.trans (Heq.symm.trans_le inf_le_left)] }
end
@[simp] lemma sup_le_inf : a ⊔ b ≤ a ⊓ b ↔ a = b :=
⟨λ h, le_antisymm (le_sup_left.trans $ h.trans inf_le_right)
(le_sup_right.trans $ h.trans inf_le_left), by { rintro rfl, simp }⟩
/-!
#### Distributivity laws
-/
/- TODO: better names? -/
theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) :=
le_inf (sup_le_sup_left inf_le_left _) (sup_le_sup_left inf_le_right _)
theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) :=
sup_le (inf_le_inf_left _ le_sup_left) (inf_le_inf_left _ le_sup_right)
theorem inf_sup_self : a ⊓ (a ⊔ b) = a :=
by simp
theorem sup_inf_self : a ⊔ (a ⊓ b) = a :=
by simp
theorem sup_eq_iff_inf_eq : a ⊔ b = b ↔ a ⊓ b = a :=
by rw [sup_eq_right, ←inf_eq_left]
theorem lattice.ext {α} {A B : lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have SS : @lattice.to_semilattice_sup α A =
@lattice.to_semilattice_sup α B := semilattice_sup.ext H,
have II := semilattice_inf.ext H,
casesI A, casesI B,
injection SS; injection II; congr'
end
end lattice
/-!
### Distributive lattices
-/
/-- A distributive lattice is a lattice that satisfies any of four
equivalent distributive properties (of `sup` over `inf` or `inf` over `sup`,
on the left or right).
The definition here chooses `le_sup_inf`: `(x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)`. To prove distributivity
from the dual law, use `distrib_lattice.of_inf_sup_le`.
A classic example of a distributive lattice
is the lattice of subsets of a set, and in fact this example is
generic in the sense that every distributive lattice is realizable
as a sublattice of a powerset lattice. -/
@[protect_proj, ancestor lattice]
class distrib_lattice α extends lattice α :=
(le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z))
section distrib_lattice
variables [distrib_lattice α] {x y z : α}
theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) :=
distrib_lattice.le_sup_inf
theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) :=
le_antisymm sup_inf_le le_sup_inf
theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) :=
by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true]
theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) :=
calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self]
... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right,
eq_self_iff_true]
... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self]
... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm]
... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left]
instance (α : Type*) [distrib_lattice α] : distrib_lattice αᵒᵈ :=
{ le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm,
.. order_dual.lattice α }
theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) :=
by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true]
lemma le_of_inf_le_sup_le (h₁ : x ⊓ z ≤ y ⊓ z) (h₂ : x ⊔ z ≤ y ⊔ z) : x ≤ y :=
calc x ≤ (y ⊓ z) ⊔ x : le_sup_right
... = (y ⊔ x) ⊓ (x ⊔ z) : by rw [sup_inf_right, @sup_comm _ _ x]
... ≤ (y ⊔ x) ⊓ (y ⊔ z) : inf_le_inf_left _ h₂
... = y ⊔ (x ⊓ z) : sup_inf_left.symm
... ≤ y ⊔ (y ⊓ z) : sup_le_sup_left h₁ _
... ≤ _ : sup_le (le_refl y) inf_le_left
lemma eq_of_inf_eq_sup_eq {α : Type u} [distrib_lattice α] {a b c : α}
(h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c :=
le_antisymm
(le_of_inf_le_sup_le (le_of_eq h₁) (le_of_eq h₂))
(le_of_inf_le_sup_le (le_of_eq h₁.symm) (le_of_eq h₂.symm))
end distrib_lattice
/-- Prove distributivity of an existing lattice from the dual distributive law. -/
@[reducible] -- See note [reducible non-instances]
def distrib_lattice.of_inf_sup_le [lattice α]
(inf_sup_le : ∀ a b c : α, a ⊓ (b ⊔ c) ≤ (a ⊓ b) ⊔ (a ⊓ c)) : distrib_lattice α :=
{ ..‹lattice α›,
..@order_dual.distrib_lattice αᵒᵈ { le_sup_inf := inf_sup_le, ..order_dual.lattice _ } }
/-!
### Lattices derived from linear orders
-/
@[priority 100] -- see Note [lower instance priority]
instance linear_order.to_lattice {α : Type u} [o : linear_order α] :
lattice α :=
{ sup := max,
le_sup_left := le_max_left,
le_sup_right := le_max_right,
sup_le := assume a b c, max_le,
inf := min,
inf_le_left := min_le_left,
inf_le_right := min_le_right,
le_inf := assume a b c, le_min,
..o }
section linear_order
variables [linear_order α] {a b c d : α}
lemma sup_eq_max : a ⊔ b = max a b := rfl
lemma inf_eq_min : a ⊓ b = min a b := rfl
lemma sup_ind (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊔ b) :=
(is_total.total a b).elim (λ h : a ≤ b, by rwa sup_eq_right.2 h) (λ h, by rwa sup_eq_left.2 h)
@[simp] lemma le_sup_iff : a ≤ b ⊔ c ↔ a ≤ b ∨ a ≤ c :=
⟨λ h, (total_of (≤) c b).imp
(λ bc, by rwa sup_eq_left.2 bc at h)
(λ bc, by rwa sup_eq_right.2 bc at h),
λ h, h.elim le_sup_of_le_left le_sup_of_le_right⟩
@[simp] lemma lt_sup_iff : a < b ⊔ c ↔ a < b ∨ a < c :=
⟨λ h, (total_of (≤) c b).imp
(λ bc, by rwa sup_eq_left.2 bc at h)
(λ bc, by rwa sup_eq_right.2 bc at h),
λ h, h.elim lt_sup_of_lt_left lt_sup_of_lt_right⟩
@[simp] lemma sup_lt_iff : b ⊔ c < a ↔ b < a ∧ c < a :=
⟨λ h, ⟨le_sup_left.trans_lt h, le_sup_right.trans_lt h⟩, λ h, sup_ind b c h.1 h.2⟩
lemma inf_ind (a b : α) {p : α → Prop} : p a → p b → p (a ⊓ b) := @sup_ind αᵒᵈ _ _ _ _
@[simp] lemma inf_le_iff : b ⊓ c ≤ a ↔ b ≤ a ∨ c ≤ a := @le_sup_iff αᵒᵈ _ _ _ _
@[simp] lemma inf_lt_iff : b ⊓ c < a ↔ b < a ∨ c < a := @lt_sup_iff αᵒᵈ _ _ _ _
@[simp] lemma lt_inf_iff : a < b ⊓ c ↔ a < b ∧ a < c := @sup_lt_iff αᵒᵈ _ _ _ _
variables (a b c d)
lemma max_max_max_comm : max (max a b) (max c d) = max (max a c) (max b d) :=
sup_sup_sup_comm _ _ _ _
lemma min_min_min_comm : min (min a b) (min c d) = min (min a c) (min b d) :=
inf_inf_inf_comm _ _ _ _
end linear_order
lemma sup_eq_max_default [semilattice_sup α] [decidable_rel ((≤) : α → α → Prop)]
[is_total α (≤)] : (⊔) = (max_default : α → α → α) :=
begin
ext x y,
dunfold max_default,
split_ifs with h',
exacts [sup_of_le_right h', sup_of_le_left $ (total_of (≤) x y).resolve_left h']
end
lemma inf_eq_min_default [semilattice_inf α] [decidable_rel ((≤) : α → α → Prop)]
[is_total α (≤)] : (⊓) = (min_default : α → α → α) :=
begin
ext x y,
dunfold min_default,
split_ifs with h',
exacts [inf_of_le_left h', inf_of_le_right $ (total_of (≤) x y).resolve_left h']
end
/-- A lattice with total order is a linear order.
See note [reducible non-instances]. -/
@[reducible] def lattice.to_linear_order (α : Type u) [lattice α] [decidable_eq α]
[decidable_rel ((≤) : α → α → Prop)] [decidable_rel ((<) : α → α → Prop)]
[is_total α (≤)] :
linear_order α :=
{ decidable_le := ‹_›, decidable_eq := ‹_›, decidable_lt := ‹_›,
le_total := total_of (≤),
max := (⊔),
max_def := sup_eq_max_default,
min := (⊓),
min_def := inf_eq_min_default,
..‹lattice α› }
@[priority 100] -- see Note [lower instance priority]
instance linear_order.to_distrib_lattice {α : Type u} [o : linear_order α] :
distrib_lattice α :=
{ le_sup_inf := assume a b c,
match le_total b c with
| or.inl h := inf_le_of_left_le $ sup_le_sup_left (le_inf (le_refl b) h) _
| or.inr h := inf_le_of_right_le $ sup_le_sup_left (le_inf h (le_refl c)) _
end,
..linear_order.to_lattice }
instance nat.distrib_lattice : distrib_lattice ℕ :=
by apply_instance
/-! ### Dual order -/
open order_dual
@[simp] lemma of_dual_inf [has_sup α] (a b: αᵒᵈ) : of_dual (a ⊓ b) = of_dual a ⊔ of_dual b := rfl
@[simp] lemma of_dual_sup [has_inf α] (a b : αᵒᵈ) : of_dual (a ⊔ b) = of_dual a ⊓ of_dual b := rfl
@[simp] lemma to_dual_inf [has_inf α] (a b : α) : to_dual (a ⊓ b) = to_dual a ⊔ to_dual b := rfl
@[simp] lemma to_dual_sup [has_sup α] (a b : α) : to_dual (a ⊔ b) = to_dual a ⊓ to_dual b := rfl
section linear_order
variables [linear_order α]
@[simp] lemma of_dual_min (a b : αᵒᵈ) : of_dual (min a b) = max (of_dual a) (of_dual b) := rfl
@[simp] lemma of_dual_max (a b : αᵒᵈ) : of_dual (max a b) = min (of_dual a) (of_dual b) := rfl
@[simp] lemma to_dual_min (a b : α) : to_dual (min a b) = max (to_dual a) (to_dual b) := rfl
@[simp] lemma to_dual_max (a b : α) : to_dual (max a b) = min (to_dual a) (to_dual b) := rfl
end linear_order
/-! ### Function lattices -/
namespace pi
variables {ι : Type*} {α' : ι → Type*}
instance [Π i, has_sup (α' i)] : has_sup (Π i, α' i) := ⟨λ f g i, f i ⊔ g i⟩
@[simp] lemma sup_apply [Π i, has_sup (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊔ g) i = f i ⊔ g i :=
rfl
lemma sup_def [Π i, has_sup (α' i)] (f g : Π i, α' i) : f ⊔ g = λ i, f i ⊔ g i := rfl
instance [Π i, has_inf (α' i)] : has_inf (Π i, α' i) := ⟨λ f g i, f i ⊓ g i⟩
@[simp] lemma inf_apply [Π i, has_inf (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊓ g) i = f i ⊓ g i :=
rfl
lemma inf_def [Π i, has_inf (α' i)] (f g : Π i, α' i) : f ⊓ g = λ i, f i ⊓ g i := rfl
instance [Π i, semilattice_sup (α' i)] : semilattice_sup (Π i, α' i) :=
by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_inf (α' i)] : semilattice_inf (Π i, α' i) :=
by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, lattice (α' i)] : lattice (Π i, α' i) :=
{ .. pi.semilattice_sup, .. pi.semilattice_inf }
instance [Π i, distrib_lattice (α' i)] : distrib_lattice (Π i, α' i) :=
by refine_struct { .. pi.lattice }; tactic.pi_instance_derive_field
end pi
/-!
### Monotone functions and lattices
-/
namespace monotone
/-- Pointwise supremum of two monotone functions is a monotone function. -/
protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : monotone f)
(hg : monotone g) : monotone (f ⊔ g) :=
λ x y h, sup_le_sup (hf h) (hg h)
/-- Pointwise infimum of two monotone functions is a monotone function. -/
protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : monotone f)
(hg : monotone g) : monotone (f ⊓ g) :=
λ x y h, inf_le_inf (hf h) (hg h)
/-- Pointwise maximum of two monotone functions is a monotone function. -/
protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : monotone f)
(hg : monotone g) : monotone (λ x, max (f x) (g x)) :=
hf.sup hg
/-- Pointwise minimum of two monotone functions is a monotone function. -/
protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : monotone f)
(hg : monotone g) : monotone (λ x, min (f x) (g x)) :=
hf.inf hg
lemma le_map_sup [semilattice_sup α] [semilattice_sup β]
{f : α → β} (h : monotone f) (x y : α) :
f x ⊔ f y ≤ f (x ⊔ y) :=
sup_le (h le_sup_left) (h le_sup_right)
lemma map_inf_le [semilattice_inf α] [semilattice_inf β]
{f : α → β} (h : monotone f) (x y : α) :
f (x ⊓ y) ≤ f x ⊓ f y :=
le_inf (h inf_le_left) (h inf_le_right)
lemma of_map_inf [semilattice_inf α] [semilattice_inf β] {f : α → β}
(h : ∀ x y, f (x ⊓ y) = f x ⊓ f y) : monotone f :=
λ x y hxy, inf_eq_left.1 $ by rw [← h, inf_eq_left.2 hxy]
lemma of_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β}
(h : ∀ x y, f (x ⊔ y) = f x ⊔ f y) : monotone f :=
(@of_map_inf (order_dual α) (order_dual β) _ _ _ h).dual
variables [linear_order α]
lemma map_sup [semilattice_sup β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊔ y) = f x ⊔ f y :=
(is_total.total x y).elim
(λ h : x ≤ y, by simp only [h, hf h, sup_of_le_right])
(λ h, by simp only [h, hf h, sup_of_le_left])
lemma map_inf [semilattice_inf β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊓ y) = f x ⊓ f y :=
hf.dual.map_sup _ _
end monotone
namespace monotone_on
/-- Pointwise supremum of two monotone functions is a monotone function. -/
protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} {s : set α}
(hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (f ⊔ g) s :=
λ x hx y hy h, sup_le_sup (hf hx hy h) (hg hx hy h)
/-- Pointwise infimum of two monotone functions is a monotone function. -/
protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} {s : set α}
(hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (f ⊓ g) s :=
(hf.dual.sup hg.dual).dual
/-- Pointwise maximum of two monotone functions is a monotone function. -/
protected lemma max [preorder α] [linear_order β] {f g : α → β} {s : set α}
(hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, max (f x) (g x)) s :=
hf.sup hg
/-- Pointwise minimum of two monotone functions is a monotone function. -/
protected lemma min [preorder α] [linear_order β] {f g : α → β} {s : set α}
(hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, min (f x) (g x)) s :=
hf.inf hg
end monotone_on
namespace antitone
/-- Pointwise supremum of two monotone functions is a monotone function. -/
protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : antitone f)
(hg : antitone g) : antitone (f ⊔ g) :=
λ x y h, sup_le_sup (hf h) (hg h)
/-- Pointwise infimum of two monotone functions is a monotone function. -/
protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : antitone f)
(hg : antitone g) : antitone (f ⊓ g) :=
λ x y h, inf_le_inf (hf h) (hg h)
/-- Pointwise maximum of two monotone functions is a monotone function. -/
protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : antitone f)
(hg : antitone g) : antitone (λ x, max (f x) (g x)) :=
hf.sup hg
/-- Pointwise minimum of two monotone functions is a monotone function. -/
protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : antitone f)
(hg : antitone g) : antitone (λ x, min (f x) (g x)) :=
hf.inf hg
lemma map_sup_le [semilattice_sup α] [semilattice_inf β]
{f : α → β} (h : antitone f) (x y : α) :
f (x ⊔ y) ≤ f x ⊓ f y :=
h.dual_right.le_map_sup x y
lemma le_map_inf [semilattice_inf α] [semilattice_sup β]
{f : α → β} (h : antitone f) (x y : α) :
f x ⊔ f y ≤ f (x ⊓ y) :=
h.dual_right.map_inf_le x y
variables [linear_order α]
lemma map_sup [semilattice_inf β] {f : α → β} (hf : antitone f) (x y : α) : f (x ⊔ y) = f x ⊓ f y :=
hf.dual_right.map_sup x y
lemma map_inf [semilattice_sup β] {f : α → β} (hf : antitone f) (x y : α) : f (x ⊓ y) = f x ⊔ f y :=
hf.dual_right.map_inf x y
end antitone
namespace antitone_on
/-- Pointwise supremum of two antitone functions is a antitone function. -/
protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} {s : set α}
(hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (f ⊔ g) s :=
λ x hx y hy h, sup_le_sup (hf hx hy h) (hg hx hy h)
/-- Pointwise infimum of two antitone functions is a antitone function. -/
protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} {s : set α}
(hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (f ⊓ g) s :=
(hf.dual.sup hg.dual).dual
/-- Pointwise maximum of two antitone functions is a antitone function. -/
protected lemma max [preorder α] [linear_order β] {f g : α → β} {s : set α}
(hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, max (f x) (g x)) s :=
hf.sup hg
/-- Pointwise minimum of two antitone functions is a antitone function. -/
protected lemma min [preorder α] [linear_order β] {f g : α → β} {s : set α}
(hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, min (f x) (g x)) s :=
hf.inf hg
end antitone_on
/-!
### Products of (semi-)lattices
-/
namespace prod
variables (α β)
instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩
instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩
@[simp] lemma mk_sup_mk [has_sup α] [has_sup β] (a₁ a₂ : α) (b₁ b₂ : β) :
(a₁, b₁) ⊔ (a₂, b₂) = (a₁ ⊔ a₂, b₁ ⊔ b₂) := rfl
@[simp] lemma mk_inf_mk [has_inf α] [has_inf β] (a₁ a₂ : α) (b₁ b₂ : β) :
(a₁, b₁) ⊓ (a₂, b₂) = (a₁ ⊓ a₂, b₁ ⊓ b₂) := rfl
@[simp] lemma fst_sup [has_sup α] [has_sup β] (p q : α × β) : (p ⊔ q).fst = p.fst ⊔ q.fst := rfl
@[simp] lemma fst_inf [has_inf α] [has_inf β] (p q : α × β) : (p ⊓ q).fst = p.fst ⊓ q.fst := rfl
@[simp] lemma snd_sup [has_sup α] [has_sup β] (p q : α × β) : (p ⊔ q).snd = p.snd ⊔ q.snd := rfl
@[simp] lemma snd_inf [has_inf α] [has_inf β] (p q : α × β) : (p ⊓ q).snd = p.snd ⊓ q.snd := rfl
@[simp] lemma swap_sup [has_sup α] [has_sup β] (p q : α × β) : (p ⊔ q).swap = p.swap ⊔ q.swap := rfl
@[simp] lemma swap_inf [has_inf α] [has_inf β] (p q : α × β) : (p ⊓ q).swap = p.swap ⊓ q.swap := rfl
lemma sup_def [has_sup α] [has_sup β] (p q : α × β) : p ⊔ q = (p.fst ⊔ q.fst, p.snd ⊔ q.snd) := rfl
lemma inf_def [has_inf α] [has_inf β] (p q : α × β) : p ⊓ q = (p.fst ⊓ q.fst, p.snd ⊓ q.snd) := rfl
instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) :=
{ sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩,
le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩,
le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩,
.. prod.partial_order α β, .. prod.has_sup α β }
instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) :=
{ le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩,
inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩,
inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩,
.. prod.partial_order α β, .. prod.has_inf α β }
instance [lattice α] [lattice β] : lattice (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.semilattice_sup α β }
instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) :=
{ le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩,
.. prod.lattice α β }
end prod
/-!
### Subtypes of (semi-)lattices
-/
namespace subtype
/-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_sup [semilattice_sup α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} :=
{ sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩,
le_sup_left := λ x y, @le_sup_left _ _ (x : α) y,
le_sup_right := λ x y, @le_sup_right _ _ (x : α) y,
sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_inf [semilattice_inf α] {P : α → Prop}
(Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} :=
{ inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩,
inf_le_left := λ x y, @inf_le_left _ _ (x : α) y,
inf_le_right := λ x y, @inf_le_right _ _ (x : α) y,
le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a lattice if `⊔` and `⊓` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def lattice [lattice α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) :
lattice {x : α // P x} :=
{ ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup }
@[simp, norm_cast] lemma coe_sup [semilattice_sup α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (x y : subtype P) :
(by {haveI := subtype.semilattice_sup Psup, exact (x ⊔ y : subtype P)} : α) = x ⊔ y := rfl
@[simp, norm_cast] lemma coe_inf [semilattice_inf α] {P : α → Prop}
(Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) (x y : subtype P) :
(by {haveI := subtype.semilattice_inf Pinf, exact (x ⊓ y : subtype P)} : α) = x ⊓ y := rfl
@[simp] lemma mk_sup_mk [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y))
{x y : α} (hx : P x) (hy : P y) :
(by {haveI := subtype.semilattice_sup Psup, exact (⟨x, hx⟩ ⊔ ⟨y, hy⟩ : subtype P)}) =
⟨x ⊔ y, Psup hx hy⟩ := rfl
@[simp] lemma mk_inf_mk [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y))
{x y : α} (hx : P x) (hy : P y) :
(by {haveI := subtype.semilattice_inf Pinf, exact (⟨x, hx⟩ ⊓ ⟨y, hy⟩ : subtype P)}) =
⟨x ⊓ y, Pinf hx hy⟩ := rfl
end subtype
section lift
/-- A type endowed with `⊔` is a `semilattice_sup`, if it admits an injective map that
preserves `⊔` to a `semilattice_sup`.
See note [reducible non-instances]. -/
@[reducible] protected def function.injective.semilattice_sup [has_sup α] [semilattice_sup β]
(f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) :
semilattice_sup α :=
{ sup := has_sup.sup,
le_sup_left := λ a b, by { change f a ≤ f (a ⊔ b), rw map_sup, exact le_sup_left, },
le_sup_right := λ a b, by { change f b ≤ f (a ⊔ b), rw map_sup, exact le_sup_right, },
sup_le := λ a b c ha hb, by { change f (a ⊔ b) ≤ f c, rw map_sup, exact sup_le ha hb, },
..partial_order.lift f hf_inj}
/-- A type endowed with `⊓` is a `semilattice_inf`, if it admits an injective map that
preserves `⊓` to a `semilattice_inf`.
See note [reducible non-instances]. -/
@[reducible] protected def function.injective.semilattice_inf [has_inf α] [semilattice_inf β]
(f : α → β) (hf_inj : function.injective f) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) :
semilattice_inf α :=
{ inf := has_inf.inf,
inf_le_left := λ a b, by { change f (a ⊓ b) ≤ f a, rw map_inf, exact inf_le_left, },
inf_le_right := λ a b, by { change f (a ⊓ b) ≤ f b, rw map_inf, exact inf_le_right, },
le_inf := λ a b c ha hb, by { change f a ≤ f (b ⊓ c), rw map_inf, exact le_inf ha hb, },
..partial_order.lift f hf_inj}
/-- A type endowed with `⊔` and `⊓` is a `lattice`, if it admits an injective map that
preserves `⊔` and `⊓` to a `lattice`.
See note [reducible non-instances]. -/
@[reducible] protected def function.injective.lattice [has_sup α] [has_inf α] [lattice β]
(f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b)
(map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) :
lattice α :=
{ ..hf_inj.semilattice_sup f map_sup, ..hf_inj.semilattice_inf f map_inf}
/-- A type endowed with `⊔` and `⊓` is a `distrib_lattice`, if it admits an injective map that
preserves `⊔` and `⊓` to a `distrib_lattice`.
See note [reducible non-instances]. -/
@[reducible] protected def function.injective.distrib_lattice [has_sup α] [has_inf α]
[distrib_lattice β] (f : α → β) (hf_inj : function.injective f)
(map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) :
distrib_lattice α :=
{ le_sup_inf := λ a b c, by { change f ((a ⊔ b) ⊓ (a ⊔ c)) ≤ f (a ⊔ b ⊓ c),
rw [map_inf, map_sup, map_sup, map_sup, map_inf], exact le_sup_inf, },
..hf_inj.lattice f map_sup map_inf, }
end lift
--To avoid noncomputability poisoning from `bool.complete_boolean_algebra`
instance : distrib_lattice bool := linear_order.to_distrib_lattice
|
ccc60019ef776489427f05458fcc92cc9eddeaa5 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/extra/congr.lean | d2782de67b12fcfd966f4513ca001cfae06a189e | [
"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 | 4,506 | lean | section
variables p : nat → Prop
variables q : nat → nat → Prop
variables f : Π (x y : nat), p x → q x y → nat
example : (0:nat) = 0 := sorry
#congr @add
#congr p
#congr iff
end
exit
section
variables p : nat → Prop
variables q : Π (n m : nat), p n → p m → Prop
variables r : Π (n m : nat) (H₁ : p n) (H₂ : p m), q n m H₁ H₂ → Prop
variables h : Π (n m : nat)
(H₁ : p n) (H₂ : p m) (H₃ : q n n H₁ H₁) (H₄ : q n m H₁ H₂)
(H₅ : r n m H₁ H₂ H₄) (H₆ : r n n H₁ H₁ H₃), nat
definition h_congr (n₁ n₂ : nat) (e₁ : n₁ = n₂) (m₁ m₂ : nat) (e₂ : m₁ = m₂)
(H₁ : p n₁) (H₂ : p m₁)
(H₃ : q n₁ n₁ H₁ H₁)
(H₄ : q n₁ m₁ H₁ H₂)
(H₅ : r n₁ m₁ H₁ H₂ H₄)
(H₆ : r n₁ n₁ H₁ H₁ H₃) :
h n₁ m₁ H₁ H₂ H₃ H₄ H₅ H₆ =
h n₂ m₂ (eq.drec_on e₁ H₁)
(eq.drec_on e₂ H₂)
(eq.drec_on e₁ H₃)
(eq.drec_on e₁ (eq.drec_on e₂ H₄))
(eq.drec_on e₁ (eq.drec_on e₂ H₅))
(eq.drec_on e₁ H₆) :=
begin
apply eq.drec_on e₁,
apply eq.drec_on e₂,
apply rfl
end
-- set_option pp.implicit true
-- print h_congr
#congr h
exit
eq.drec_on e₁ (eq.drec_on e₂ (eq.refl (h n₂ m₂ (eq.rec_on e₁ H₁) (eq.rec_on e₂ H₂) (eq.drec_on e₁ H₃)
(eq.drec_on e₁ (eq.drec_on e₂ H₄))
(eq.drec_on e₁ (eq.drec_on e₂ H₅))
(eq.drec_on e₁ H₆))))
sorry
exit
q x₁ H₁) :
h x₁ H₁ H₂ = h x₂ (eq.rec_on e H₁) (eq.drec_on e H₂) :=
eq.drec_on e (eq.refl (h x₁ (eq.rec_on (eq.refl x₁) H₁) (eq.drec_on (eq.refl x₁) H₂)))
exit
variables h₂ : Π (n : nat) (H₁ : p n) (H₂ : q n H₁) (H₃ : r n H₁ H₂), nat
definition h_congr (x₁ x₂ : nat) (e : x₁ = x₂) (H₁ : p x₁) (H₂ : q x₁ H₁) :
h x₁ H₁ H₂ = h x₂ (eq.rec_on e H₁) (eq.drec_on e H₂) :=
eq.drec_on e (eq.refl (h x₁ (eq.rec_on (eq.refl x₁) H₁) (eq.drec_on (eq.refl x₁) H₂)))
definition h_congr₂ (x₁ x₂ : nat) (e : x₁ = x₂) (H₁ : p x₁) (H₂ : q x₁ H₁) (H₃ : r x₁ H₁ H₂) :
h₂ x₁ H₁ H₂ H₃ = h₂ x₂ (eq.rec_on e H₁) (eq.drec_on e H₂) (eq.drec_on e H₃) :=
eq.drec_on e (eq.refl (h₂ x₁ (eq.rec_on (eq.refl x₁) H₁) (eq.drec_on (eq.refl x₁) H₂) (eq.drec_on (eq.refl x₁) H₃)))
definition h_congr₃ (x₁ x₂ : nat) (e : x₁ = x₂) (H₁ : p x₁) (H₂ : q x₁ H₁) (H₃ : r x₁ H₁ H₂) :
h₂ x₁ H₁ H₂ H₃ = h₂ x₂ (eq.rec_on e H₁) (eq.drec_on e H₂) (eq.drec_on e H₃) :=
begin
congruence,
apply e
end
-- print h_congr₃
-- exit
set_option pp.all true
print h_congr₂
#congr h
exit
set_option pp.all true
print h_congr
#congr h
end
exit
variables g : Π (A : Type) (x y : A) (B : Type) (z : B), x = y → y == z → nat
#congr g
exit
lemma f_congr
(x₁ x₂ : nat) (e₁ : x₁ = x₂)
(y₁ y₂ : nat) (e₂ : y₁ = y₂)
(H₁ : p x₁)
(H₂ : q x₁ y₁) :
f x₁ y₁ H₁ H₂ =
f x₂ y₂ (@eq.rec_on nat x₁ (λ (a : ℕ), p a) x₂ e₁ H₁)
(@eq.rec_on nat x₁ (λ (a : ℕ), q a y₂) x₂ e₁ (@eq.rec_on nat y₁ (λ (a : ℕ), q x₁ a) y₂ e₂ H₂)) :=
let R := (eq.refl (f x₁ y₁ (@eq.rec_on nat x₁ (λ (a : ℕ), p a) x₁ (eq.refl x₁) H₁) (@eq.rec_on nat x₁ (λ (a : ℕ), q a y₁) x₁ (eq.refl x₁) (@eq.rec_on nat y₁ (λ (a : ℕ), q x₁ a) y₁ (eq.refl y₁) H₂)))) in
@eq.drec_on nat x₁
(λ (z : ℕ) (H : x₁ = z),
f x₁ y₁ H₁ H₂ =
f z y₂ (@eq.rec_on nat x₁ (λ a, p a) z H H₁)
(@eq.rec_on nat x₁ (λ a, q a y₂) z H (@eq.rec_on nat y₁ (λ a, q x₁ a) y₂ e₂ H₂)))
x₂ e₁
(@eq.drec_on nat y₁
(λ (z : ℕ) (H : y₁ = z),
f x₁ y₁ H₁ H₂ =
f x₁ z (@eq.rec_on nat x₁ (λ a, p a) x₁ (eq.refl x₁) H₁)
(@eq.rec_on nat x₁ (λ a, q a z) x₁ (eq.refl x₁) (@eq.rec_on nat y₁ (λ a, q x₁ a) z H H₂)))
y₂ e₂ R)
/-
f x₁ y₁ H₁ H₂ =
f x₁ y₂ (@eq.rec_on nat x₁ (λ a, p a) x₁ (eq.refl x₁) H₁)
(@eq.rec_on nat x₁ (λ a, q a y₂) x₁ (eq.refl x₁) (@eq.rec_on nat y₁ (λ a, q x₁ a) y₂ e₂ H₂)))
-/
|
b535f8fb883def3d3004001c44fdf3c3477214e0 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/groupoid.lean | 34075a9674b96854c2d3f9d0942059a456e1b089 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 4,476 | lean | /-
Copyright (c) 2018 Reid Barton All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Scott Morrison, David Wärn
-/
import category_theory.full_subcategory
import category_theory.products.basic
import category_theory.pi.basic
import category_theory.category.basic
import combinatorics.quiver.connected_component
/-!
# Groupoids
We define `groupoid` as a typeclass extending `category`,
asserting that all morphisms have inverses.
The instance `is_iso.of_groupoid (f : X ⟶ Y) : is_iso f` means that you can then write
`inv f` to access the inverse of any morphism `f`.
`groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y)` provides the equivalence between
isomorphisms and morphisms in a groupoid.
We provide a (non-instance) constructor `groupoid.of_is_iso` from an existing category
with `is_iso f` for every `f`.
## See also
See also `category_theory.core` for the groupoid of isomorphisms in a category.
-/
namespace category_theory
universes v v₂ u u₂ -- morphism levels before object levels. See note [category_theory universes].
/-- A `groupoid` is a category such that all morphisms are isomorphisms. -/
class groupoid (obj : Type u) extends category.{v} obj : Type (max u (v+1)) :=
(inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X))
(inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously)
(comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously)
restate_axiom groupoid.inv_comp'
restate_axiom groupoid.comp_inv'
/--
A `large_groupoid` is a groupoid
where the objects live in `Type (u+1)` while the morphisms live in `Type u`.
-/
abbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u} C
/--
A `small_groupoid` is a groupoid
where the objects and morphisms live in the same universe.
-/
abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u} C
section
variables {C : Type u} [groupoid.{v} C] {X Y : C}
@[priority 100] -- see Note [lower instance priority]
instance is_iso.of_groupoid (f : X ⟶ Y) : is_iso f :=
⟨⟨groupoid.inv f, groupoid.comp_inv f, groupoid.inv_comp f⟩⟩
@[simp] lemma groupoid.inv_eq_inv (f : X ⟶ Y) : groupoid.inv f = inv f :=
is_iso.eq_inv_of_hom_inv_id $ groupoid.comp_inv f
/-- `groupoid.inv` is involutive. -/
@[simps] def groupoid.inv_equiv : (X ⟶ Y) ≃ (Y ⟶ X) :=
⟨groupoid.inv, groupoid.inv, λ f, by simp, λ f, by simp⟩
@[priority 100]
instance groupoid_has_involutive_reverse : quiver.has_involutive_reverse C :=
{ reverse' := λ X Y f, groupoid.inv f,
inv' := λ X Y f, by { dsimp [quiver.reverse], simp, } }
@[simp] lemma groupoid.reverse_eq_inv (f : X ⟶ Y) : quiver.reverse f = groupoid.inv f := rfl
variables (X Y)
/-- In a groupoid, isomorphisms are equivalent to morphisms. -/
def groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y) :=
{ to_fun := iso.hom,
inv_fun := λ f, ⟨f, groupoid.inv f⟩,
left_inv := λ i, iso.ext rfl,
right_inv := λ f, rfl }
variables (C)
/-- The functor from a groupoid `C` to its opposite sending every morphism to its inverse. -/
@[simps] noncomputable def groupoid.inv_functor : C ⥤ Cᵒᵖ :=
{ obj := opposite.op,
map := λ {X Y} f, (inv f).op }
end
section
variables {C : Type u} [category.{v} C]
/-- A category where every morphism `is_iso` is a groupoid. -/
noncomputable
def groupoid.of_is_iso (all_is_iso : ∀ {X Y : C} (f : X ⟶ Y), is_iso f) : groupoid.{v} C :=
{ inv := λ X Y f, inv f }
/-- A category with a unique morphism between any two objects is a groupoid -/
def groupoid.of_hom_unique (all_unique : ∀ {X Y : C}, unique (X ⟶ Y)) : groupoid.{v} C :=
{ inv := λ X Y f, all_unique.default }
end
instance induced_category.groupoid {C : Type u} (D : Type u₂) [groupoid.{v} D] (F : C → D) :
groupoid.{v} (induced_category D F) :=
{ inv := λ X Y f, groupoid.inv f,
inv_comp' := λ X Y f, groupoid.inv_comp f,
comp_inv' := λ X Y f, groupoid.comp_inv f,
.. induced_category.category F }
section
instance groupoid_pi {I : Type u} {J : I → Type u₂} [∀ i, groupoid.{v} (J i)] :
groupoid.{max u v} (Π i : I, J i) :=
{ inv := λ (x y : Π i, J i) (f : Π i, x i ⟶ y i), (λ i : I, groupoid.inv (f i)), }
instance groupoid_prod {α : Type u} {β : Type v} [groupoid.{u₂} α] [groupoid.{v₂} β] :
groupoid.{max u₂ v₂} (α × β) :=
{ inv := λ (x y : α × β) (f : x ⟶ y), (groupoid.inv f.1, groupoid.inv f.2) }
end
end category_theory
|
e12cd1e986ef058505a054c422ec954c8682c35c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/special_functions/log.lean | 13f34d8d431aaf5c8e513194b3dbba986989ad90 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 10,585 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import analysis.special_functions.exp
/-!
# Real logarithm
In this file we define `real.log` to be the logarithm of a real number. As usual, we extend it from
its domain `(0, +∞)` to a globally defined function. We choose to do it so that `log 0 = 0` and
`log (-x) = log x`.
We prove some basic properties of this function and show that it is continuous.
## Tags
logarithm, continuity
-/
open set filter function
open_locale topological_space
noncomputable theory
namespace real
variables {x y : ℝ}
/-- The real logarithm function, equal to the inverse of the exponential for `x > 0`,
to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to
`(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and
the derivative of `log` is `1/x` away from `0`. -/
@[pp_nodot] noncomputable def log (x : ℝ) : ℝ :=
if hx : x = 0 then 0 else exp_order_iso.symm ⟨|x|, abs_pos.2 hx⟩
lemma log_of_ne_zero (hx : x ≠ 0) : log x = exp_order_iso.symm ⟨|x|, abs_pos.2 hx⟩ := dif_neg hx
lemma log_of_pos (hx : 0 < x) : log x = exp_order_iso.symm ⟨x, hx⟩ :=
by { rw [log_of_ne_zero hx.ne'], congr, exact abs_of_pos hx }
lemma exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = |x| :=
by rw [log_of_ne_zero hx, ← coe_exp_order_iso_apply, order_iso.apply_symm_apply, subtype.coe_mk]
lemma exp_log (hx : 0 < x) : exp (log x) = x :=
by { rw exp_log_eq_abs hx.ne', exact abs_of_pos hx }
lemma exp_log_of_neg (hx : x < 0) : exp (log x) = -x :=
by { rw exp_log_eq_abs (ne_of_lt hx), exact abs_of_neg hx }
@[simp] lemma log_exp (x : ℝ) : log (exp x) = x :=
exp_injective $ exp_log (exp_pos x)
lemma surj_on_log : surj_on log (Ioi 0) univ :=
λ x _, ⟨exp x, exp_pos x, log_exp x⟩
lemma log_surjective : surjective log :=
λ x, ⟨exp x, log_exp x⟩
@[simp] lemma range_log : range log = univ :=
log_surjective.range_eq
@[simp] lemma log_zero : log 0 = 0 := dif_pos rfl
@[simp] lemma log_one : log 1 = 0 :=
exp_injective $ by rw [exp_log zero_lt_one, exp_zero]
@[simp] lemma log_abs (x : ℝ) : log (|x|) = log x :=
begin
by_cases h : x = 0,
{ simp [h] },
{ rw [← exp_eq_exp, exp_log_eq_abs h, exp_log_eq_abs (abs_pos.2 h).ne', abs_abs] }
end
@[simp] lemma log_neg_eq_log (x : ℝ) : log (-x) = log x :=
by rw [← log_abs x, ← log_abs (-x), abs_neg]
lemma surj_on_log' : surj_on log (Iio 0) univ :=
λ x _, ⟨-exp x, neg_lt_zero.2 $ exp_pos x, by rw [log_neg_eq_log, log_exp]⟩
lemma log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y :=
exp_injective $
by rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul]
lemma log_div (hx : x ≠ 0) (hy : y ≠ 0) : log (x / y) = log x - log y :=
exp_injective $
by rw [exp_log_eq_abs (div_ne_zero hx hy), exp_sub, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_div]
@[simp] lemma log_inv (x : ℝ) : log (x⁻¹) = -log x :=
begin
by_cases hx : x = 0, { simp [hx] },
rw [← exp_eq_exp, exp_log_eq_abs (inv_ne_zero hx), exp_neg, exp_log_eq_abs hx, abs_inv]
end
lemma log_le_log (h : 0 < x) (h₁ : 0 < y) : log x ≤ log y ↔ x ≤ y :=
by rw [← exp_le_exp, exp_log h, exp_log h₁]
lemma log_lt_log (hx : 0 < x) : x < y → log x < log y :=
by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] }
lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y :=
by { rw [← exp_lt_exp, exp_log hx, exp_log hy] }
lemma log_le_iff_le_exp (hx : 0 < x) : log x ≤ y ↔ x ≤ exp y := by rw [←exp_le_exp, exp_log hx]
lemma log_lt_iff_lt_exp (hx : 0 < x) : log x < y ↔ x < exp y := by rw [←exp_lt_exp, exp_log hx]
lemma le_log_iff_exp_le (hy : 0 < y) : x ≤ log y ↔ exp x ≤ y := by rw [←exp_le_exp, exp_log hy]
lemma lt_log_iff_exp_lt (hy : 0 < y) : x < log y ↔ exp x < y := by rw [←exp_lt_exp, exp_log hy]
lemma log_pos_iff (hx : 0 < x) : 0 < log x ↔ 1 < x :=
by { rw ← log_one, exact log_lt_log_iff zero_lt_one hx }
lemma log_pos (hx : 1 < x) : 0 < log x :=
(log_pos_iff (lt_trans zero_lt_one hx)).2 hx
lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 :=
by { rw ← log_one, exact log_lt_log_iff h zero_lt_one }
lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1
lemma log_nonneg_iff (hx : 0 < x) : 0 ≤ log x ↔ 1 ≤ x :=
by rw [← not_lt, log_neg_iff hx, not_lt]
lemma log_nonneg (hx : 1 ≤ x) : 0 ≤ log x :=
(log_nonneg_iff (zero_lt_one.trans_le hx)).2 hx
lemma log_nonpos_iff (hx : 0 < x) : log x ≤ 0 ↔ x ≤ 1 :=
by rw [← not_lt, log_pos_iff hx, not_lt]
lemma log_nonpos_iff' (hx : 0 ≤ x) : log x ≤ 0 ↔ x ≤ 1 :=
begin
rcases hx.eq_or_lt with (rfl|hx),
{ simp [le_refl, zero_le_one] },
exact log_nonpos_iff hx
end
lemma log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 :=
(log_nonpos_iff' hx).2 h'x
lemma strict_mono_on_log : strict_mono_on log (set.Ioi 0) :=
λ x hx y hy hxy, log_lt_log hx hxy
lemma strict_anti_on_log : strict_anti_on log (set.Iio 0) :=
begin
rintros x (hx : x < 0) y (hy : y < 0) hxy,
rw [← log_abs y, ← log_abs x],
refine log_lt_log (abs_pos.2 hy.ne) _,
rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff]
end
lemma log_inj_on_pos : set.inj_on log (set.Ioi 0) :=
strict_mono_on_log.inj_on
lemma eq_one_of_pos_of_log_eq_zero {x : ℝ} (h₁ : 0 < x) (h₂ : log x = 0) : x = 1 :=
log_inj_on_pos (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one) (h₂.trans real.log_one.symm)
lemma log_ne_zero_of_pos_of_ne_one {x : ℝ} (hx_pos : 0 < x) (hx : x ≠ 1) : log x ≠ 0 :=
mt (eq_one_of_pos_of_log_eq_zero hx_pos) hx
@[simp] lemma log_eq_zero {x : ℝ} : log x = 0 ↔ x = 0 ∨ x = 1 ∨ x = -1 :=
begin
split,
{ intros h,
rcases lt_trichotomy x 0 with x_lt_zero | rfl | x_gt_zero,
{ refine or.inr (or.inr (eq_neg_iff_eq_neg.mp _)),
rw [←log_neg_eq_log x] at h,
exact (eq_one_of_pos_of_log_eq_zero (neg_pos.mpr x_lt_zero) h).symm, },
{ exact or.inl rfl },
{ exact or.inr (or.inl (eq_one_of_pos_of_log_eq_zero x_gt_zero h)), }, },
{ rintro (rfl|rfl|rfl); simp only [log_one, log_zero, log_neg_eq_log], }
end
@[simp] lemma log_pow (x : ℝ) (n : ℕ) : log (x ^ n) = n * log x :=
begin
induction n with n ih,
{ simp },
rcases eq_or_ne x 0 with rfl | hx,
{ simp },
rw [pow_succ', log_mul (pow_ne_zero _ hx) hx, ih, nat.cast_succ, add_mul, one_mul],
end
@[simp] lemma log_zpow (x : ℝ) (n : ℤ) : log (x ^ n) = n * log x :=
begin
induction n,
{ rw [int.of_nat_eq_coe, zpow_coe_nat, log_pow, int.cast_coe_nat] },
rw [zpow_neg_succ_of_nat, log_inv, log_pow, int.cast_neg_succ_of_nat, nat.cast_add_one,
neg_mul_eq_neg_mul],
end
lemma log_le_sub_one_of_pos {x : ℝ} (hx : 0 < x) : log x ≤ x - 1 :=
begin
rw le_sub_iff_add_le,
convert add_one_le_exp (log x),
rw exp_log hx,
end
lemma log_div_self_antitone_on : antitone_on (λ x : ℝ, log x / x) {x | exp 1 ≤ x} :=
begin
simp only [antitone_on, mem_set_of_eq],
intros x hex y hey hxy,
have x_pos : 0 < x := (exp_pos 1).trans_le hex,
have y_pos : 0 < y := (exp_pos 1).trans_le hey,
have hlogx : 1 ≤ log x := by rwa le_log_iff_exp_le x_pos,
have hyx : 0 ≤ y / x - 1 := by rwa [le_sub_iff_add_le, le_div_iff x_pos, zero_add, one_mul],
rw [div_le_iff y_pos, ←sub_le_sub_iff_right (log x)],
calc
log y - log x = log (y / x) : by rw [log_div (y_pos.ne') (x_pos.ne')]
... ≤ (y / x) - 1 : log_le_sub_one_of_pos (div_pos y_pos x_pos)
... ≤ log x * (y / x - 1) : le_mul_of_one_le_left hyx hlogx
... = log x / x * y - log x : by ring,
end
/-- The real logarithm function tends to `+∞` at `+∞`. -/
lemma tendsto_log_at_top : tendsto log at_top at_top :=
tendsto_comp_exp_at_top.1 $ by simpa only [log_exp] using tendsto_id
lemma tendsto_log_nhds_within_zero : tendsto log (𝓝[≠] 0) at_bot :=
begin
rw [← (show _ = log, from funext log_abs)],
refine tendsto.comp _ tendsto_abs_nhds_within_zero,
simpa [← tendsto_comp_exp_at_bot] using tendsto_id
end
lemma continuous_on_log : continuous_on log {0}ᶜ :=
begin
rw [continuous_on_iff_continuous_restrict, restrict],
conv in (log _) { rw [log_of_ne_zero (show (x : ℝ) ≠ 0, from x.2)] },
exact exp_order_iso.symm.continuous.comp (continuous_subtype_mk _ continuous_subtype_coe.norm)
end
@[continuity] lemma continuous_log : continuous (λ x : {x : ℝ // x ≠ 0}, log x) :=
continuous_on_iff_continuous_restrict.1 $ continuous_on_log.mono $ λ x hx, hx
@[continuity] lemma continuous_log' : continuous (λ x : {x : ℝ // 0 < x}, log x) :=
continuous_on_iff_continuous_restrict.1 $ continuous_on_log.mono $ λ x hx, ne_of_gt hx
lemma continuous_at_log (hx : x ≠ 0) : continuous_at log x :=
(continuous_on_log x hx).continuous_at $ is_open.mem_nhds is_open_compl_singleton hx
@[simp] lemma continuous_at_log_iff : continuous_at log x ↔ x ≠ 0 :=
begin
refine ⟨_, continuous_at_log⟩,
rintros h rfl,
exact not_tendsto_nhds_of_tendsto_at_bot tendsto_log_nhds_within_zero _
(h.tendsto.mono_left inf_le_left)
end
open_locale big_operators
lemma log_prod {α : Type*} (s : finset α) (f : α → ℝ) (hf : ∀ x ∈ s, f x ≠ 0):
log (∏ i in s, f i) = ∑ i in s, log (f i) :=
begin
classical,
induction s using finset.induction_on with a s ha ih,
{ simp },
simp only [finset.mem_insert, forall_eq_or_imp] at hf,
simp [ha, ih hf.2, log_mul hf.1 (finset.prod_ne_zero_iff.2 hf.2)],
end
end real
section continuity
open real
variables {α : Type*}
lemma filter.tendsto.log {f : α → ℝ} {l : filter α} {x : ℝ} (h : tendsto f l (𝓝 x)) (hx : x ≠ 0) :
tendsto (λ x, log (f x)) l (𝓝 (log x)) :=
(continuous_at_log hx).tendsto.comp h
variables [topological_space α] {f : α → ℝ} {s : set α} {a : α}
lemma continuous.log (hf : continuous f) (h₀ : ∀ x, f x ≠ 0) : continuous (λ x, log (f x)) :=
continuous_on_log.comp_continuous hf h₀
lemma continuous_at.log (hf : continuous_at f a) (h₀ : f a ≠ 0) :
continuous_at (λ x, log (f x)) a :=
hf.log h₀
lemma continuous_within_at.log (hf : continuous_within_at f s a) (h₀ : f a ≠ 0) :
continuous_within_at (λ x, log (f x)) s a :=
hf.log h₀
lemma continuous_on.log (hf : continuous_on f s) (h₀ : ∀ x ∈ s, f x ≠ 0) :
continuous_on (λ x, log (f x)) s :=
λ x hx, (hf x hx).log (h₀ x hx)
end continuity
|
0f367e525284ff797fa24d01647c66f005502de3 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/category_theory/abelian/non_preadditive.lean | 0a88735100cf9fa8d9fce6c91840994024e4f061 | [
"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 | 32,062 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.limits.shapes.finite_products
import category_theory.limits.shapes.kernels
import category_theory.limits.shapes.normal_mono
import category_theory.preadditive
/-!
# Every non_preadditive_abelian category is preadditive
In mathlib, we define an abelian category as a preadditive category with a zero object,
kernels and cokernels, products and coproducts and in which every monomorphism and epimorphis is
normal.
While virtually every interesting abelian category has a natural preadditive structure (which is why
it is included in the definition), preadditivity is not actually needed: Every category that has
all of the other properties appearing in the definition of an abelian category admits a preadditive
structure. This is the construction we carry out in this file.
The proof proceeds in roughly five steps:
1. Prove some results (for example that all equalizers exist) that would be trivial if we already
had the preadditive structure but are a bit of work without it.
2. Develop images and coimages to show that every monomorphism is the kernel of its cokernel.
The results of the first two steps are also useful for the "normal" development of abelian
categories, and will be used there.
3. For every object `A`, define a "subtraction" morphism `σ : A ⨯ A ⟶ A` and use it to define
subtraction on morphisms as `f - g := prod.lift f g ≫ σ`.
4. Prove a small number of identities about this subtraction from the definition of `σ`.
5. From these identities, prove a large number of other identities that imply that defining
`f + g := f - (0 - g)` indeed gives an abelian group structure on morphisms such that composition
is bilinear.
The construction is non-trivial and it is quite remarkable that this abelian group structure can
be constructed purely from the existence of a few limits and colimits. What's even more impressive
is that all additive structures on a category are in some sense isomorphic, so for abelian
categories with a natural preadditive structure, this construction manages to "almost" reconstruct
this natural structure. However, we have not formalized this isomorphism.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
noncomputable theory
open category_theory
open category_theory.limits
namespace category_theory
section
universes v u
variables (C : Type u) [category.{v} C]
/-- We call a category `non_preadditive_abelian` if it has a zero object, kernels, cokernels, binary
products and coproducts, and every monomorphism and every epimorphism is normal. -/
class non_preadditive_abelian :=
[has_zero_object : has_zero_object C]
[has_zero_morphisms : has_zero_morphisms C]
[has_kernels : has_kernels C]
[has_cokernels : has_cokernels C]
[has_finite_products : has_finite_products C]
[has_finite_coproducts : has_finite_coproducts C]
(normal_mono : Π {X Y : C} (f : X ⟶ Y) [mono f], normal_mono f)
(normal_epi : Π {X Y : C} (f : X ⟶ Y) [epi f], normal_epi f)
set_option default_priority 100
attribute [instance] non_preadditive_abelian.has_zero_object
attribute [instance] non_preadditive_abelian.has_zero_morphisms
attribute [instance] non_preadditive_abelian.has_kernels
attribute [instance] non_preadditive_abelian.has_cokernels
attribute [instance] non_preadditive_abelian.has_finite_products
attribute [instance] non_preadditive_abelian.has_finite_coproducts
end
end category_theory
open category_theory
namespace category_theory.non_preadditive_abelian
universes v u
variables {C : Type u} [category.{v} C]
section
variables [non_preadditive_abelian C]
section strong
local attribute [instance] non_preadditive_abelian.normal_epi
/-- In a `non_preadditive_abelian` category, every epimorphism is strong. -/
lemma strong_epi_of_epi {P Q : C} (f : P ⟶ Q) [epi f] : strong_epi f := by apply_instance
end strong
section mono_epi_iso
variables {X Y : C} (f : X ⟶ Y)
local attribute [instance] strong_epi_of_epi
/-- In a `non_preadditive_abelian` category, a monomorphism which is also an epimorphism is an
isomorphism. -/
lemma is_iso_of_mono_of_epi [mono f] [epi f] : is_iso f :=
is_iso_of_mono_of_strong_epi _
end mono_epi_iso
/-- The pullback of two monomorphisms exists. -/
@[irreducible]
lemma pullback_of_mono {X Y Z : C} (a : X ⟶ Z) (b : Y ⟶ Z) [mono a] [mono b] :
has_limit (cospan a b) :=
let ⟨P, f, haf, i⟩ := non_preadditive_abelian.normal_mono a in
let ⟨Q, g, hbg, i'⟩ := non_preadditive_abelian.normal_mono b in
let ⟨a', ha'⟩ := kernel_fork.is_limit.lift' i (kernel.ι (prod.lift f g)) $
calc kernel.ι (prod.lift f g) ≫ f
= kernel.ι (prod.lift f g) ≫ prod.lift f g ≫ limits.prod.fst : by rw prod.lift_fst
... = (0 : kernel (prod.lift f g) ⟶ P ⨯ Q) ≫ limits.prod.fst : by rw kernel.condition_assoc
... = 0 : zero_comp in
let ⟨b', hb'⟩ := kernel_fork.is_limit.lift' i' (kernel.ι (prod.lift f g)) $
calc kernel.ι (prod.lift f g) ≫ g
= kernel.ι (prod.lift f g) ≫ (prod.lift f g) ≫ limits.prod.snd : by rw prod.lift_snd
... = (0 : kernel (prod.lift f g) ⟶ P ⨯ Q) ≫ limits.prod.snd : by rw kernel.condition_assoc
... = 0 : zero_comp in
has_limit.mk { cone := pullback_cone.mk a' b' $ by { simp at ha' hb', rw [ha', hb'] },
is_limit := pullback_cone.is_limit.mk _
(λ s, kernel.lift (prod.lift f g) (pullback_cone.snd s ≫ b) $ prod.hom_ext
(calc ((pullback_cone.snd s ≫ b) ≫ prod.lift f g) ≫ limits.prod.fst
= pullback_cone.snd s ≫ b ≫ f : by simp only [prod.lift_fst, category.assoc]
... = pullback_cone.fst s ≫ a ≫ f : by rw pullback_cone.condition_assoc
... = pullback_cone.fst s ≫ 0 : by rw haf
... = 0 ≫ limits.prod.fst :
by rw [comp_zero, zero_comp])
(calc ((pullback_cone.snd s ≫ b) ≫ prod.lift f g) ≫ limits.prod.snd
= pullback_cone.snd s ≫ b ≫ g : by simp only [prod.lift_snd, category.assoc]
... = pullback_cone.snd s ≫ 0 : by rw hbg
... = 0 ≫ limits.prod.snd :
by rw [comp_zero, zero_comp]))
(λ s, (cancel_mono a).1 $
by { rw kernel_fork.ι_of_ι at ha', simp [ha', pullback_cone.condition s] })
(λ s, (cancel_mono b).1 $
by { rw kernel_fork.ι_of_ι at hb', simp [hb'] })
(λ s m h₁ h₂, (cancel_mono (kernel.ι (prod.lift f g))).1 $ calc m ≫ kernel.ι (prod.lift f g)
= m ≫ a' ≫ a : by { congr, exact ha'.symm }
... = pullback_cone.fst s ≫ a : by rw [←category.assoc, h₁]
... = pullback_cone.snd s ≫ b : pullback_cone.condition s
... = kernel.lift (prod.lift f g) (pullback_cone.snd s ≫ b) _ ≫ kernel.ι (prod.lift f g) :
by rw kernel.lift_ι) }
/-- The pushout of two epimorphisms exists. -/
@[irreducible]
lemma pushout_of_epi {X Y Z : C} (a : X ⟶ Y) (b : X ⟶ Z) [epi a] [epi b] :
has_colimit (span a b) :=
let ⟨P, f, hfa, i⟩ := non_preadditive_abelian.normal_epi a in
let ⟨Q, g, hgb, i'⟩ := non_preadditive_abelian.normal_epi b in
let ⟨a', ha'⟩ := cokernel_cofork.is_colimit.desc' i (cokernel.π (coprod.desc f g)) $
calc f ≫ cokernel.π (coprod.desc f g)
= coprod.inl ≫ coprod.desc f g ≫ cokernel.π (coprod.desc f g) : by rw coprod.inl_desc_assoc
... = coprod.inl ≫ (0 : P ⨿ Q ⟶ cokernel (coprod.desc f g)) : by rw cokernel.condition
... = 0 : has_zero_morphisms.comp_zero _ _ in
let ⟨b', hb'⟩ := cokernel_cofork.is_colimit.desc' i' (cokernel.π (coprod.desc f g)) $
calc g ≫ cokernel.π (coprod.desc f g)
= coprod.inr ≫ coprod.desc f g ≫ cokernel.π (coprod.desc f g) : by rw coprod.inr_desc_assoc
... = coprod.inr ≫ (0 : P ⨿ Q ⟶ cokernel (coprod.desc f g)) : by rw cokernel.condition
... = 0 : has_zero_morphisms.comp_zero _ _ in
has_colimit.mk
{ cocone := pushout_cocone.mk a' b' $ by { simp only [cofork.π_of_π] at ha' hb', rw [ha', hb'] },
is_colimit := pushout_cocone.is_colimit.mk _
(λ s, cokernel.desc (coprod.desc f g) (b ≫ pushout_cocone.inr s) $ coprod.hom_ext
(calc coprod.inl ≫ coprod.desc f g ≫ b ≫ pushout_cocone.inr s
= f ≫ b ≫ pushout_cocone.inr s : by rw coprod.inl_desc_assoc
... = f ≫ a ≫ pushout_cocone.inl s : by rw pushout_cocone.condition
... = 0 ≫ pushout_cocone.inl s : by rw reassoc_of hfa
... = coprod.inl ≫ 0 : by rw [comp_zero, zero_comp])
(calc coprod.inr ≫ coprod.desc f g ≫ b ≫ pushout_cocone.inr s
= g ≫ b ≫ pushout_cocone.inr s : by rw coprod.inr_desc_assoc
... = 0 ≫ pushout_cocone.inr s : by rw reassoc_of hgb
... = coprod.inr ≫ 0 : by rw [comp_zero, zero_comp]))
(λ s, (cancel_epi a).1 $
by { rw cokernel_cofork.π_of_π at ha', simp [reassoc_of ha', pushout_cocone.condition s] })
(λ s, (cancel_epi b).1 $ by { rw cokernel_cofork.π_of_π at hb', simp [reassoc_of hb'] })
(λ s m h₁ h₂, (cancel_epi (cokernel.π (coprod.desc f g))).1 $
calc cokernel.π (coprod.desc f g) ≫ m
= (a ≫ a') ≫ m : by { congr, exact ha'.symm }
... = a ≫ pushout_cocone.inl s : by rw [category.assoc, h₁]
... = b ≫ pushout_cocone.inr s : pushout_cocone.condition s
... = cokernel.π (coprod.desc f g) ≫
cokernel.desc (coprod.desc f g) (b ≫ pushout_cocone.inr s) _ :
by rw cokernel.π_desc) }
section
local attribute [instance] pullback_of_mono
/-- The pullback of `(𝟙 X, f)` and `(𝟙 X, g)` -/
private abbreviation P {X Y : C} (f g : X ⟶ Y)
[mono (prod.lift (𝟙 X) f)] [mono (prod.lift (𝟙 X) g)] : C :=
pullback (prod.lift (𝟙 X) f) (prod.lift (𝟙 X) g)
/-- The equalizer of `f` and `g` exists. -/
@[irreducible]
lemma has_limit_parallel_pair {X Y : C} (f g : X ⟶ Y) : has_limit (parallel_pair f g) :=
have huv : (pullback.fst : P f g ⟶ X) = pullback.snd, from
calc (pullback.fst : P f g ⟶ X) = pullback.fst ≫ 𝟙 _ : eq.symm $ category.comp_id _
... = pullback.fst ≫ prod.lift (𝟙 X) f ≫ limits.prod.fst : by rw prod.lift_fst
... = pullback.snd ≫ prod.lift (𝟙 X) g ≫ limits.prod.fst : by rw pullback.condition_assoc
... = pullback.snd : by rw [prod.lift_fst, category.comp_id],
have hvu : (pullback.fst : P f g ⟶ X) ≫ f = pullback.snd ≫ g, from
calc (pullback.fst : P f g ⟶ X) ≫ f
= pullback.fst ≫ prod.lift (𝟙 X) f ≫ limits.prod.snd : by rw prod.lift_snd
... = pullback.snd ≫ prod.lift (𝟙 X) g ≫ limits.prod.snd : by rw pullback.condition_assoc
... = pullback.snd ≫ g : by rw prod.lift_snd,
have huu : (pullback.fst : P f g ⟶ X) ≫ f = pullback.fst ≫ g, by rw [hvu, ←huv],
has_limit.mk { cone := fork.of_ι pullback.fst huu,
is_limit := fork.is_limit.mk _
(λ s, pullback.lift (fork.ι s) (fork.ι s) $ prod.hom_ext
(by simp only [prod.lift_fst, category.assoc])
(by simp only [fork.app_zero_right, fork.app_zero_left, prod.lift_snd, category.assoc]))
(λ s, by simp only [fork.ι_of_ι, pullback.lift_fst])
(λ s m h, pullback.hom_ext
(by simpa only [pullback.lift_fst] using h walking_parallel_pair.zero)
(by simpa only [huv.symm, pullback.lift_fst] using h walking_parallel_pair.zero)) }
end
section
local attribute [instance] pushout_of_epi
/-- The pushout of `(𝟙 Y, f)` and `(𝟙 Y, g)`. -/
private abbreviation Q {X Y : C} (f g : X ⟶ Y)
[epi (coprod.desc (𝟙 Y) f)] [epi (coprod.desc (𝟙 Y) g)] : C :=
pushout (coprod.desc (𝟙 Y) f) (coprod.desc (𝟙 Y) g)
/-- The coequalizer of `f` and `g` exists. -/
@[irreducible]
lemma has_colimit_parallel_pair {X Y : C} (f g : X ⟶ Y) : has_colimit (parallel_pair f g) :=
have huv : (pushout.inl : Y ⟶ Q f g) = pushout.inr, from
calc (pushout.inl : Y ⟶ Q f g) = 𝟙 _ ≫ pushout.inl : eq.symm $ category.id_comp _
... = (coprod.inl ≫ coprod.desc (𝟙 Y) f) ≫ pushout.inl : by rw coprod.inl_desc
... = (coprod.inl ≫ coprod.desc (𝟙 Y) g) ≫ pushout.inr :
by simp only [category.assoc, pushout.condition]
... = pushout.inr : by rw [coprod.inl_desc, category.id_comp],
have hvu : f ≫ (pushout.inl : Y ⟶ Q f g) = g ≫ pushout.inr, from
calc f ≫ (pushout.inl : Y ⟶ Q f g)
= (coprod.inr ≫ coprod.desc (𝟙 Y) f) ≫ pushout.inl : by rw coprod.inr_desc
... = (coprod.inr ≫ coprod.desc (𝟙 Y) g) ≫ pushout.inr :
by simp only [category.assoc, pushout.condition]
... = g ≫ pushout.inr : by rw coprod.inr_desc,
have huu : f ≫ (pushout.inl : Y ⟶ Q f g) = g ≫ pushout.inl, by rw [hvu, huv],
has_colimit.mk { cocone := cofork.of_π pushout.inl huu,
is_colimit := cofork.is_colimit.mk _
(λ s, pushout.desc (cofork.π s) (cofork.π s) $ coprod.hom_ext
(by simp only [coprod.inl_desc_assoc])
(by simp only [cofork.right_app_one, coprod.inr_desc_assoc, cofork.left_app_one]))
(λ s, by simp only [pushout.inl_desc, cofork.π_of_π])
(λ s m h, pushout.hom_ext
(by simpa only [pushout.inl_desc] using h walking_parallel_pair.one)
(by simpa only [huv.symm, pushout.inl_desc] using h walking_parallel_pair.one)) }
end
section
local attribute [instance] has_limit_parallel_pair
/-- A `non_preadditive_abelian` category has all equalizers. -/
@[priority 100] instance has_equalizers : has_equalizers C :=
has_equalizers_of_has_limit_parallel_pair _
end
section
local attribute [instance] has_colimit_parallel_pair
/-- A `non_preadditive_abelian` category has all coequalizers. -/
@[priority 100] instance has_coequalizers : has_coequalizers C :=
has_coequalizers_of_has_colimit_parallel_pair _
end
section
/-- If a zero morphism is a kernel of `f`, then `f` is a monomorphism. -/
lemma mono_of_zero_kernel {X Y : C} (f : X ⟶ Y) (Z : C)
(l : is_limit (kernel_fork.of_ι (0 : Z ⟶ X) (show 0 ≫ f = 0, by simp))) : mono f :=
⟨λ P u v huv,
begin
obtain ⟨W, w, hw, hl⟩ := non_preadditive_abelian.normal_epi (coequalizer.π u v),
obtain ⟨m, hm⟩ := coequalizer.desc' f huv,
have hwf : w ≫ f = 0,
{ rw [←hm, reassoc_of hw, zero_comp] },
obtain ⟨n, hn⟩ := kernel_fork.is_limit.lift' l _ hwf,
rw [fork.ι_of_ι, has_zero_morphisms.comp_zero] at hn,
haveI : is_iso (coequalizer.π u v) :=
by apply is_iso_colimit_cocone_parallel_pair_of_eq hn.symm hl,
apply (cancel_mono (coequalizer.π u v)).1,
exact coequalizer.condition _ _
end⟩
/-- If a zero morphism is a cokernel of `f`, then `f` is an epimorphism. -/
lemma epi_of_zero_cokernel {X Y : C} (f : X ⟶ Y) (Z : C)
(l : is_colimit (cokernel_cofork.of_π (0 : Y ⟶ Z) (show f ≫ 0 = 0, by simp))) : epi f :=
⟨λ P u v huv,
begin
obtain ⟨W, w, hw, hl⟩ := non_preadditive_abelian.normal_mono (equalizer.ι u v),
obtain ⟨m, hm⟩ := equalizer.lift' f huv,
have hwf : f ≫ w = 0,
{ rw [←hm, category.assoc, hw, comp_zero] },
obtain ⟨n, hn⟩ := cokernel_cofork.is_colimit.desc' l _ hwf,
rw [cofork.π_of_π, zero_comp] at hn,
haveI : is_iso (equalizer.ι u v) :=
by apply is_iso_limit_cone_parallel_pair_of_eq hn.symm hl,
apply (cancel_epi (equalizer.ι u v)).1,
exact equalizer.condition _ _
end⟩
local attribute [instance] has_zero_object.has_zero
/-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `0 : 0 ⟶ X` is a kernel of `f`. -/
def zero_kernel_of_cancel_zero {X Y : C} (f : X ⟶ Y)
(hf : ∀ (Z : C) (g : Z ⟶ X) (hgf : g ≫ f = 0), g = 0) :
is_limit (kernel_fork.of_ι (0 : 0 ⟶ X) (show 0 ≫ f = 0, by simp)) :=
fork.is_limit.mk _ (λ s, 0)
(λ s, by rw [hf _ _ (kernel_fork.condition s), zero_comp])
(λ s m h, by ext)
/-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `0 : Y ⟶ 0` is a cokernel of `f`. -/
def zero_cokernel_of_zero_cancel {X Y : C} (f : X ⟶ Y)
(hf : ∀ (Z : C) (g : Y ⟶ Z) (hgf : f ≫ g = 0), g = 0) :
is_colimit (cokernel_cofork.of_π (0 : Y ⟶ 0) (show f ≫ 0 = 0, by simp)) :=
cofork.is_colimit.mk _ (λ s, 0)
(λ s, by rw [hf _ _ (cokernel_cofork.condition s), comp_zero])
(λ s m h, by ext)
/-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `f` is a monomorphism. -/
lemma mono_of_cancel_zero {X Y : C} (f : X ⟶ Y)
(hf : ∀ (Z : C) (g : Z ⟶ X) (hgf : g ≫ f = 0), g = 0) : mono f :=
mono_of_zero_kernel f 0 $ zero_kernel_of_cancel_zero f hf
/-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `g` is a monomorphism. -/
lemma epi_of_zero_cancel {X Y : C} (f : X ⟶ Y)
(hf : ∀ (Z : C) (g : Y ⟶ Z) (hgf : f ≫ g = 0), g = 0) : epi f :=
epi_of_zero_cokernel f 0 $ zero_cokernel_of_zero_cancel f hf
end
section factor
variables {P Q : C} (f : P ⟶ Q)
/-- The kernel of the cokernel of `f` is called the image of `f`. -/
protected abbreviation image : C := kernel (cokernel.π f)
/-- The inclusion of the image into the codomain. -/
protected abbreviation image.ι : non_preadditive_abelian.image f ⟶ Q :=
kernel.ι (cokernel.π f)
/-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/
protected abbreviation factor_thru_image : P ⟶ non_preadditive_abelian.image f :=
kernel.lift (cokernel.π f) f $ cokernel.condition f
/-- `f` factors through its image via the canonical morphism `p`. -/
@[simp, reassoc] protected lemma image.fac :
non_preadditive_abelian.factor_thru_image f ≫ image.ι f = f :=
kernel.lift_ι _ _ _
/-- The map `p : P ⟶ image f` is an epimorphism -/
instance : epi (non_preadditive_abelian.factor_thru_image f) :=
let I := non_preadditive_abelian.image f, p := non_preadditive_abelian.factor_thru_image f,
i := kernel.ι (cokernel.π f) in
-- It will suffice to consider some g : I ⟶ R such that p ≫ g = 0 and show that g = 0.
epi_of_zero_cancel _ $ λ R (g : I ⟶ R) (hpg : p ≫ g = 0),
begin
-- Since C is abelian, u := ker g ≫ i is the kernel of some morphism h.
let u := kernel.ι g ≫ i,
haveI : mono u := mono_comp _ _,
haveI hu := non_preadditive_abelian.normal_mono u,
let h := hu.g,
-- By hypothesis, p factors through the kernel of g via some t.
obtain ⟨t, ht⟩ := kernel.lift' g p hpg,
have fh : f ≫ h = 0, calc
f ≫ h = (p ≫ i) ≫ h : (image.fac f).symm ▸ rfl
... = ((t ≫ kernel.ι g) ≫ i) ≫ h : ht ▸ rfl
... = t ≫ u ≫ h : by simp only [category.assoc]; conv_lhs { congr, skip, rw ←category.assoc }
... = t ≫ 0 : hu.w ▸ rfl
... = 0 : has_zero_morphisms.comp_zero _ _,
-- h factors through the cokernel of f via some l.
obtain ⟨l, hl⟩ := cokernel.desc' f h fh,
have hih : i ≫ h = 0, calc
i ≫ h = i ≫ cokernel.π f ≫ l : hl ▸ rfl
... = 0 ≫ l : by rw [←category.assoc, kernel.condition]
... = 0 : zero_comp,
-- i factors through u = ker h via some s.
obtain ⟨s, hs⟩ := normal_mono.lift' u i hih,
have hs' : (s ≫ kernel.ι g) ≫ i = 𝟙 I ≫ i, by rw [category.assoc, hs, category.id_comp],
haveI : epi (kernel.ι g) := epi_of_epi_fac ((cancel_mono _).1 hs'),
-- ker g is an epimorphism, but ker g ≫ g = 0 = ker g ≫ 0, so g = 0 as required.
exact zero_of_epi_comp _ (kernel.condition g)
end
instance mono_factor_thru_image [mono f] : mono (non_preadditive_abelian.factor_thru_image f) :=
mono_of_mono_fac $ image.fac f
instance is_iso_factor_thru_image [mono f] : is_iso (non_preadditive_abelian.factor_thru_image f) :=
is_iso_of_mono_of_epi _
/-- The cokernel of the kernel of `f` is called the coimage of `f`. -/
protected abbreviation coimage : C := cokernel (kernel.ι f)
/-- The projection onto the coimage. -/
protected abbreviation coimage.π : P ⟶ non_preadditive_abelian.coimage f :=
cokernel.π (kernel.ι f)
/-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/
protected abbreviation factor_thru_coimage : non_preadditive_abelian.coimage f ⟶ Q :=
cokernel.desc (kernel.ι f) f $ kernel.condition f
/-- `f` factors through its coimage via the canonical morphism `p`. -/
protected lemma coimage.fac : coimage.π f ≫ non_preadditive_abelian.factor_thru_coimage f = f :=
cokernel.π_desc _ _ _
/-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/
instance : mono (non_preadditive_abelian.factor_thru_coimage f) :=
let I := non_preadditive_abelian.coimage f, i := non_preadditive_abelian.factor_thru_coimage f,
p := cokernel.π (kernel.ι f) in
mono_of_cancel_zero _ $ λ R (g : R ⟶ I) (hgi : g ≫ i = 0),
begin
-- Since C is abelian, u := p ≫ coker g is the cokernel of some morphism h.
let u := p ≫ cokernel.π g,
haveI : epi u := epi_comp _ _,
haveI hu := non_preadditive_abelian.normal_epi u,
let h := hu.g,
-- By hypothesis, i factors through the cokernel of g via some t.
obtain ⟨t, ht⟩ := cokernel.desc' g i hgi,
have hf : h ≫ f = 0, calc
h ≫ f = h ≫ (p ≫ i) : (coimage.fac f).symm ▸ rfl
... = h ≫ (p ≫ (cokernel.π g ≫ t)) : ht ▸ rfl
... = h ≫ u ≫ t : by simp only [category.assoc]; conv_lhs { congr, skip, rw ←category.assoc }
... = 0 ≫ t : by rw [←category.assoc, hu.w]
... = 0 : zero_comp,
-- h factors through the kernel of f via some l.
obtain ⟨l, hl⟩ := kernel.lift' f h hf,
have hhp : h ≫ p = 0, calc
h ≫ p = (l ≫ kernel.ι f) ≫ p : hl ▸ rfl
... = l ≫ 0 : by rw [category.assoc, cokernel.condition]
... = 0 : comp_zero,
-- p factors through u = coker h via some s.
obtain ⟨s, hs⟩ := normal_epi.desc' u p hhp,
have hs' : p ≫ cokernel.π g ≫ s = p ≫ 𝟙 I, by rw [←category.assoc, hs, category.comp_id],
haveI : mono (cokernel.π g) := mono_of_mono_fac ((cancel_epi _).1 hs'),
-- coker g is a monomorphism, but g ≫ coker g = 0 = 0 ≫ coker g, so g = 0 as required.
exact zero_of_comp_mono _ (cokernel.condition g)
end
instance epi_factor_thru_coimage [epi f] : epi (non_preadditive_abelian.factor_thru_coimage f) :=
epi_of_epi_fac $ coimage.fac f
instance is_iso_factor_thru_coimage [epi f] :
is_iso (non_preadditive_abelian.factor_thru_coimage f) :=
is_iso_of_mono_of_epi _
end factor
section cokernel_of_kernel
variables {X Y : C} {f : X ⟶ Y}
/-- In a `non_preadditive_abelian` category, an epi is the cokernel of its kernel. More precisely:
If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel
of `fork.ι s`. -/
def epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) :
is_colimit (cokernel_cofork.of_π f (kernel_fork.condition s)) :=
is_cokernel.cokernel_iso _ _
(cokernel.of_iso_comp _ _
(limits.is_limit.cone_point_unique_up_to_iso (limit.is_limit _) h)
(cone_morphism.w (limits.is_limit.unique_up_to_iso (limit.is_limit _) h).hom _))
(as_iso $ non_preadditive_abelian.factor_thru_coimage f) (coimage.fac f)
/-- In a `non_preadditive_abelian` category, a mono is the kernel of its cokernel. More precisely:
If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel
of `cofork.π s`. -/
def mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) :
is_limit (kernel_fork.of_ι f (cokernel_cofork.condition s)) :=
is_kernel.iso_kernel _ _
(kernel.of_comp_iso _ _
(limits.is_colimit.cocone_point_unique_up_to_iso h (colimit.is_colimit _))
(cocone_morphism.w (limits.is_colimit.unique_up_to_iso h $ colimit.is_colimit _).hom _))
(as_iso $ non_preadditive_abelian.factor_thru_image f) (image.fac f)
end cokernel_of_kernel
section
/-- The composite `A ⟶ A ⨯ A ⟶ cokernel (Δ A)`, where the first map is `(𝟙 A, 0)` and the second map
is the canonical projection into the cokernel. -/
abbreviation r (A : C) : A ⟶ cokernel (diag A) := prod.lift (𝟙 A) 0 ≫ cokernel.π (diag A)
instance mono_Δ {A : C} : mono (diag A) := mono_of_mono_fac $ prod.lift_fst _ _
instance mono_r {A : C} : mono (r A) :=
begin
let hl : is_limit (kernel_fork.of_ι (diag A) (cokernel.condition (diag A))),
{ exact mono_is_kernel_of_cokernel _ (colimit.is_colimit _) },
apply mono_of_cancel_zero,
intros Z x hx,
have hxx : (x ≫ prod.lift (𝟙 A) (0 : A ⟶ A)) ≫ cokernel.π (diag A) = 0,
{ rw [category.assoc, hx] },
obtain ⟨y, hy⟩ := kernel_fork.is_limit.lift' hl _ hxx,
rw kernel_fork.ι_of_ι at hy,
have hyy : y = 0,
{ erw [←category.comp_id y, ←limits.prod.lift_snd (𝟙 A) (𝟙 A), ←category.assoc, hy,
category.assoc, prod.lift_snd, has_zero_morphisms.comp_zero] },
haveI : mono (prod.lift (𝟙 A) (0 : A ⟶ A)) := mono_of_mono_fac (prod.lift_fst _ _),
apply (cancel_mono (prod.lift (𝟙 A) (0 : A ⟶ A))).1,
rw [←hy, hyy, zero_comp, zero_comp]
end
instance epi_r {A : C} : epi (r A) :=
begin
have hlp : prod.lift (𝟙 A) (0 : A ⟶ A) ≫ limits.prod.snd = 0 := prod.lift_snd _ _,
let hp1 : is_limit (kernel_fork.of_ι (prod.lift (𝟙 A) (0 : A ⟶ A)) hlp),
{ refine fork.is_limit.mk _ (λ s, fork.ι s ≫ limits.prod.fst) _ _,
{ intro s,
ext; simp, erw category.comp_id },
{ intros s m h,
haveI : mono (prod.lift (𝟙 A) (0 : A ⟶ A)) := mono_of_mono_fac (prod.lift_fst _ _),
apply (cancel_mono (prod.lift (𝟙 A) (0 : A ⟶ A))).1,
convert h walking_parallel_pair.zero,
ext; simp } },
let hp2 : is_colimit (cokernel_cofork.of_π (limits.prod.snd : A ⨯ A ⟶ A) hlp),
{ exact epi_is_cokernel_of_kernel _ hp1 },
apply epi_of_zero_cancel,
intros Z z hz,
have h : prod.lift (𝟙 A) (0 : A ⟶ A) ≫ cokernel.π (diag A) ≫ z = 0,
{ rw [←category.assoc, hz] },
obtain ⟨t, ht⟩ := cokernel_cofork.is_colimit.desc' hp2 _ h,
rw cokernel_cofork.π_of_π at ht,
have htt : t = 0,
{ rw [←category.id_comp t],
change 𝟙 A ≫ t = 0,
rw [←limits.prod.lift_snd (𝟙 A) (𝟙 A), category.assoc, ht, ←category.assoc,
cokernel.condition, zero_comp] },
apply (cancel_epi (cokernel.π (diag A))).1,
rw [←ht, htt, comp_zero, comp_zero]
end
instance is_iso_r {A : C} : is_iso (r A) :=
is_iso_of_mono_of_epi _
/-- The composite `A ⨯ A ⟶ cokernel (diag A) ⟶ A` given by the natural projection into the cokernel
followed by the inverse of `r`. In the category of modules, using the normal kernels and
cokernels, this map is equal to the map `(a, b) ↦ a - b`, hence the name `σ` for
"subtraction". -/
abbreviation σ {A : C} : A ⨯ A ⟶ A := cokernel.π (diag A) ≫ inv (r A)
end
@[simp, reassoc] lemma diag_σ {X : C} : diag X ≫ σ = 0 :=
by rw [cokernel.condition_assoc, zero_comp]
@[simp, reassoc] lemma lift_σ {X : C} : prod.lift (𝟙 X) 0 ≫ σ = 𝟙 X :=
by rw [←category.assoc, is_iso.hom_inv_id]
@[reassoc] lemma lift_map {X Y : C} (f : X ⟶ Y) :
prod.lift (𝟙 X) 0 ≫ limits.prod.map f f = f ≫ prod.lift (𝟙 Y) 0 :=
by simp
/-- σ is a cokernel of Δ X. -/
def is_colimit_σ {X : C} : is_colimit (cokernel_cofork.of_π σ diag_σ) :=
cokernel.cokernel_iso _ σ (as_iso (r X)).symm (by rw [iso.symm_hom, as_iso_inv])
/-- This is the key identity satisfied by `σ`. -/
lemma σ_comp {X Y : C} (f : X ⟶ Y) : σ ≫ f = limits.prod.map f f ≫ σ :=
begin
obtain ⟨g, hg⟩ :=
cokernel_cofork.is_colimit.desc' is_colimit_σ (limits.prod.map f f ≫ σ) (by simp),
suffices hfg : f = g,
{ rw [←hg, cofork.π_of_π, hfg] },
calc f = f ≫ prod.lift (𝟙 Y) 0 ≫ σ : by rw [lift_σ, category.comp_id]
... = prod.lift (𝟙 X) 0 ≫ limits.prod.map f f ≫ σ : by rw lift_map_assoc
... = prod.lift (𝟙 X) 0 ≫ σ ≫ g : by rw [←hg, cokernel_cofork.π_of_π]
... = g : by rw [←category.assoc, lift_σ, category.id_comp]
end
section
/- We write `f - g` for `prod.lift f g ≫ σ`. -/
/-- Subtraction of morphisms in a `non_preadditive_abelian` category. -/
def has_sub {X Y : C} : has_sub (X ⟶ Y) := ⟨λ f g, prod.lift f g ≫ σ⟩
local attribute [instance] has_sub
/- We write `-f` for `0 - f`. -/
/-- Negation of morphisms in a `non_preadditive_abelian` category. -/
def has_neg {X Y : C} : has_neg (X ⟶ Y) := ⟨λ f, 0 - f⟩
local attribute [instance] has_neg
/- We write `f + g` for `f - (-g)`. -/
/-- Addition of morphisms in a `non_preadditive_abelian` category. -/
def has_add {X Y : C} : has_add (X ⟶ Y) := ⟨λ f g, f - (-g)⟩
local attribute [instance] has_add
lemma sub_def {X Y : C} (a b : X ⟶ Y) : a - b = prod.lift a b ≫ σ := rfl
lemma add_def {X Y : C} (a b : X ⟶ Y) : a + b = a - (-b) := rfl
lemma neg_def {X Y : C} (a : X ⟶ Y) : -a = 0 - a := rfl
lemma sub_zero {X Y : C} (a : X ⟶ Y) : a - 0 = a :=
begin
rw sub_def,
conv_lhs { congr, congr, rw ←category.comp_id a, skip, rw (show 0 = a ≫ (0 : Y ⟶ Y), by simp)},
rw [← prod.comp_lift, category.assoc, lift_σ, category.comp_id]
end
lemma sub_self {X Y : C} (a : X ⟶ Y) : a - a = 0 :=
by rw [sub_def, ←category.comp_id a, ← prod.comp_lift, category.assoc, diag_σ, comp_zero]
lemma lift_sub_lift {X Y : C} (a b c d : X ⟶ Y) :
prod.lift a b - prod.lift c d = prod.lift (a - c) (b - d) :=
begin
simp only [sub_def],
ext,
{ rw [category.assoc, σ_comp, prod.lift_map_assoc, prod.lift_fst, prod.lift_fst, prod.lift_fst] },
{ rw [category.assoc, σ_comp, prod.lift_map_assoc, prod.lift_snd, prod.lift_snd, prod.lift_snd] }
end
lemma sub_sub_sub {X Y : C} (a b c d : X ⟶ Y) : (a - c) - (b - d) = (a - b) - (c - d) :=
begin
rw [sub_def, ←lift_sub_lift, sub_def, category.assoc, σ_comp, prod.lift_map_assoc], refl
end
lemma neg_sub {X Y : C} (a b : X ⟶ Y) : (-a) - b = (-b) - a :=
by conv_lhs { rw [neg_def, ←sub_zero b, sub_sub_sub, sub_zero, ←neg_def] }
lemma neg_neg {X Y : C} (a : X ⟶ Y) : -(-a) = a :=
begin
rw [neg_def, neg_def],
conv_lhs { congr, rw ←sub_self a },
rw [sub_sub_sub, sub_zero, sub_self, sub_zero]
end
lemma add_comm {X Y : C} (a b : X ⟶ Y) : a + b = b + a :=
begin
rw [add_def],
conv_lhs { rw ←neg_neg a },
rw [neg_def, neg_def, neg_def, sub_sub_sub],
conv_lhs {congr, skip, rw [←neg_def, neg_sub] },
rw [sub_sub_sub, add_def, ←neg_def, neg_neg b, neg_def]
end
lemma add_neg {X Y : C} (a b : X ⟶ Y) : a + (-b) = a - b :=
by rw [add_def, neg_neg]
lemma add_neg_self {X Y : C} (a : X ⟶ Y) : a + (-a) = 0 :=
by rw [add_neg, sub_self]
lemma neg_add_self {X Y : C} (a : X ⟶ Y) : (-a) + a = 0 :=
by rw [add_comm, add_neg_self]
lemma neg_sub' {X Y : C} (a b : X ⟶ Y) : -(a - b) = (-a) + b :=
begin
rw [neg_def, neg_def],
conv_lhs { rw ←sub_self (0 : X ⟶ Y) },
rw [sub_sub_sub, add_def, neg_def]
end
lemma neg_add {X Y : C} (a b : X ⟶ Y) : -(a + b) = (-a) - b :=
by rw [add_def, neg_sub', add_neg]
lemma sub_add {X Y : C} (a b c : X ⟶ Y) : (a - b) + c = a - (b - c) :=
by rw [add_def, neg_def, sub_sub_sub, sub_zero]
lemma add_assoc {X Y : C} (a b c : X ⟶ Y) : (a + b) + c = a + (b + c) :=
begin
conv_lhs { congr, rw add_def },
rw [sub_add, ←add_neg, neg_sub', neg_neg]
end
lemma add_zero {X Y : C} (a : X ⟶ Y) : a + 0 = a :=
by rw [add_def, neg_def, sub_self, sub_zero]
lemma comp_sub {X Y Z : C} (f : X ⟶ Y) (g h : Y ⟶ Z) : f ≫ (g - h) = f ≫ g - f ≫ h :=
by rw [sub_def, ←category.assoc, prod.comp_lift, sub_def]
lemma sub_comp {X Y Z : C} (f g : X ⟶ Y) (h : Y ⟶ Z) : (f - g) ≫ h = f ≫ h - g ≫ h :=
by rw [sub_def, category.assoc, σ_comp, ←category.assoc, prod.lift_map, sub_def]
lemma comp_add (X Y Z : C) (f : X ⟶ Y) (g h : Y ⟶ Z) : f ≫ (g + h) = f ≫ g + f ≫ h :=
by rw [add_def, comp_sub, neg_def, comp_sub, comp_zero, add_def, neg_def]
lemma add_comp (X Y Z : C) (f g : X ⟶ Y) (h : Y ⟶ Z) : (f + g) ≫ h = f ≫ h + g ≫ h :=
by rw [add_def, sub_comp, neg_def, sub_comp, zero_comp, add_def, neg_def]
/-- Every `non_preadditive_abelian` category is preadditive. -/
def preadditive : preadditive C :=
{ hom_group := λ X Y,
{ add := (+),
add_assoc := add_assoc,
zero := 0,
zero_add := neg_neg,
add_zero := add_zero,
neg := λ f, -f,
add_left_neg := neg_add_self,
add_comm := add_comm },
add_comp' := add_comp,
comp_add' := comp_add }
end
end
end category_theory.non_preadditive_abelian
|
4ae0248aa221c20d37e909b92662456fe6f5d3d1 | ad0c7d243dc1bd563419e2767ed42fb323d7beea | /order/basic.lean | 465190da2b14616aea17b27bafd622544f4ffa69 | [
"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 | 18,813 | 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 tactic.interactive logic.basic data.sum data.set.basic algebra.order
open function
/- TODO: automatic construction of dual definitions / theorems -/
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop}
theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b :=
λ h, h ▸ le_refl a
theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩
theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩
theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) :=
⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩
theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) :=
⟨λ a b h₁ h₂, antisymm h₂ h₁⟩
theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) :=
⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩
theorem is_total.swap (r) [is_total α r] : is_total α (swap r) :=
⟨λ a b, (total_of r a b).swap⟩
theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) :=
⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩
theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) :=
{..@is_refl.swap α r _, ..@is_trans.swap α r _}
theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) :=
{..@is_irrefl.swap α r _, ..@is_trans.swap α r _}
theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) :=
{..@is_preorder.swap α r _, ..@is_antisymm.swap α r _}
theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) :=
{..@is_preorder.swap α r _, ..@is_total.swap α r _}
theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) :=
{..@is_partial_order.swap α r _, ..@is_total.swap α r _}
/- Convert algebraic structure style to explicit relation style typeclasses -/
instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩
instance [preorder α] : is_refl α (≥) := is_refl.swap _
instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩
instance [preorder α] : is_trans α (≥) := is_trans.swap _
instance [preorder α] : is_preorder α (≤) := {}
instance [preorder α] : is_preorder α (≥) := {}
instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩
instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _
instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩
instance [preorder α] : is_trans α (>) := is_trans.swap _
instance [preorder α] : is_strict_order α (<) := {}
instance [preorder α] : is_strict_order α (>) := {}
instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩
instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _
instance [partial_order α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩
instance [partial_order α] : is_asymm α (>) := is_asymm.swap _
instance [partial_order α] : is_partial_order α (≤) := {}
instance [partial_order α] : is_partial_order α (≥) := {}
instance [linear_order α] : is_total α (≤) := ⟨le_total⟩
instance [linear_order α] : is_total α (≥) := is_total.swap _
instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := {}
instance [linear_order α] : is_total_preorder α (≥) := {}
instance [linear_order α] : is_linear_order α (≤) := {}
instance [linear_order α] : is_linear_order α (≥) := {}
instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩
instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _
theorem preorder.ext {α} {A B : preorder α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
resetI, cases A, cases B, congr,
{ funext x y, exact propext (H x y) },
{ funext x y,
dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H,
simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] },
end
theorem partial_order.ext {α} {A B : partial_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by haveI this := preorder.ext H;
cases A; cases B; injection this; congr'
theorem linear_order.ext {α} {A B : linear_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by haveI this := partial_order.ext H;
cases A; cases B; injection this; congr'
/-- Given an order `R` on `β` and a function `f : α → β`,
the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`.
It is the unique order on `α` making `f` an order embedding
(assuming `f` is injective). -/
@[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y)
infix ` ⁻¹'o `:80 := order.preimage
section monotone
variables [preorder α] [preorder β] [preorder γ]
/-- A function between preorders is monotone if
`a ≤ b` implies `f a ≤ f b`. -/
def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b
theorem monotone_id : @monotone α α _ _ id := assume x y h, h
theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b
theorem monotone_comp {f : α → β} {g : β → γ} (m_f : monotone f) (m_g : monotone g) :
monotone (g ∘ f) :=
assume a b h, m_g (m_f h)
end monotone
def order_dual (α : Type*) := α
namespace order_dual
instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩
instance (α : Type*) [preorder α] : preorder (order_dual α) :=
{ le_refl := le_refl,
le_trans := assume a b c hab hbc, le_trans hbc hab,
.. order_dual.has_le α }
instance (α : Type*) [partial_order α] : partial_order (order_dual α) :=
{ le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α }
instance (α : Type*) [linear_order α] : linear_order (order_dual α) :=
{ le_total := assume a b:α, le_total b a, .. order_dual.partial_order α }
end order_dual
/- order instances on the function space -/
instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) :=
{ le := λx y, ∀i, x i ≤ y i,
le_refl := assume a i, le_refl (a i),
le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) }
instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) :=
{ le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)),
..pi.preorder }
theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] [preorder γ]
{f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) :=
assume x, m_f (le_gh x)
section monotone
variables [preorder α] [preorder γ]
theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f :=
assume a a' h b, m b h
theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) :=
assume a a' h, m h b
end monotone
def preorder.lift {α β} [preorder β] (f : α → β) : preorder α :=
{ le := λx y, f x ≤ f y,
le_refl := λ a, le_refl _,
le_trans := λ a b c, le_trans }
def partial_order.lift {α β} [partial_order β]
(f : α → β) (inj : injective f) : partial_order α :=
{ le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f }
def linear_order.lift {α β} [linear_order β]
(f : α → β) (inj : injective f) : linear_order α :=
{ le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj }
instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) :=
preorder.lift subtype.val
instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) :=
partial_order.lift subtype.val $ λ x y, subtype.eq'
instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) :=
linear_order.lift subtype.val $ λ x y, subtype.eq'
/- additional order classes -/
/-- order without a top element; somtimes called cofinal -/
class no_top_order (α : Type u) [preorder α] : Prop :=
(no_top : ∀a:α, ∃a', a < a')
lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' :=
no_top_order.no_top
/-- order without a bottom element; somtimes called coinitial or dense -/
class no_bot_order (α : Type u) [preorder α] : Prop :=
(no_bot : ∀a:α, ∃a', a' < a)
lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a :=
no_bot_order.no_bot
/-- An order is dense if there is an element between any pair of distinct elements. -/
class densely_ordered (α : Type u) [preorder α] : Prop :=
(dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂)
lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ :=
densely_ordered.dense
lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) :
a₁ ≤ a₂ :=
le_of_not_gt $ assume ha,
let ⟨a, ha₁, ha₂⟩ := dense ha in
lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›)
lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ :=
le_antisymm (le_of_forall_le_of_dense h₂) h₁
lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) :
a₁ ≤ a₂ :=
le_of_not_gt $ assume ha,
let ⟨a, ha₁, ha₂⟩ := dense ha in
lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a›
lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ :=
le_antisymm (le_of_forall_ge_of_dense h₂) h₁
section
variables {s : β → β → Prop} {t : γ → γ → Prop}
theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r :=
⟨λ a h, asymm h h⟩
/-- Construct a partial order from a `is_strict_order` relation -/
def partial_order_of_SO (r) [is_strict_order α r] : partial_order α :=
{ le := λ x y, x = y ∨ r x y,
lt := r,
le_refl := λ x, or.inl rfl,
le_trans := λ x y z h₁ h₂,
match y, z, h₁, h₂ with
| _, _, or.inl rfl, h₂ := h₂
| _, _, h₁, or.inl rfl := h₁
| _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂)
end,
le_antisymm := λ x y h₁ h₂,
match y, h₁, h₂ with
| _, or.inl rfl, h₂ := rfl
| _, h₁, or.inl rfl := rfl
| _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim
end,
lt_iff_le_not_le := λ x y,
⟨λ h, ⟨or.inr h, not_or
(λ e, by rw e at h; exact irrefl _ h)
(asymm h)⟩,
λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ }
/-- This is basically the same as `is_strict_total_order`, but that definition is
in Type (probably by mistake) and also has redundant assumptions. -/
@[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop.
/-- Construct a linear order from a `is_strict_total_order'` relation -/
def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α :=
{ le_total := λ x y,
match y, trichotomous_of r x y with
| y, or.inl h := or.inl (or.inr h)
| _, or.inr (or.inl rfl) := or.inl (or.inl rfl)
| _, or.inr (or.inr h) := or.inr (or.inr h)
end,
..partial_order_of_SO r }
/-- Construct a decidable linear order from a `is_strict_total_order'` relation -/
def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α :=
by letI LO := linear_order_of_STO' r; exact
{ decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x),
..LO }
noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α :=
{ decidable_le := classical.dec_rel _, ..LO }
theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) :=
{..is_trichotomous.swap r, ..is_strict_order.swap r}
instance [linear_order α] : is_strict_total_order' α (<) := {}
/-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`.
This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on
the constructive reals, and is also known as negative transitivity,
since the contrapositive asserts transitivity of the relation `¬ a < b`. -/
@[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop :=
(conn : ∀ a b c, lt a c → lt a b ∨ lt b c)
theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r]
{a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c :=
mt (is_order_connected.conn a b c) $ by simp [h₁, h₂]
theorem is_strict_weak_order_of_is_order_connected [is_asymm α r]
[is_order_connected α r] : is_strict_weak_order α r :=
{ trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂),
incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩,
⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩,
..@is_irrefl_of_is_asymm α r _ }
instance is_order_connected_of_is_strict_total_order'
[is_strict_total_order' α r] : is_order_connected α r :=
⟨λ a b c h, (trichotomous _ _).imp_right (λ o,
o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩
instance is_strict_total_order_of_is_strict_total_order'
[is_strict_total_order' α r] : is_strict_total_order α r :=
{..is_strict_weak_order_of_is_order_connected}
instance [linear_order α] : is_strict_total_order α (<) := by apply_instance
instance [linear_order α] : is_order_connected α (<) := by apply_instance
instance [linear_order α] : is_incomp_trans α (<) := by apply_instance
instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance
/-- An extensional relation is one in which an element is determined by its set
of predecessors. It is named for the `x ∈ y` relation in set theory, whose
extensionality is one of the first axioms of ZFC. -/
@[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop :=
(ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b)
instance is_extensional_of_is_strict_total_order'
[is_strict_total_order' α r] : is_extensional α r :=
⟨λ a b H, ((@trichotomous _ r _ a b)
.resolve_left $ mt (H _).2 (irrefl a))
.resolve_right $ mt (H _).1 (irrefl b)⟩
/-- A well order is a well-founded linear order. -/
@[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop :=
(wf : well_founded r)
instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation :=
{ trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _,
irrefl := λ a, id,
trans := λ a b c, false.elim,
wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ }
instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩
instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) :=
{ trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous,
irrefl := λ a, by cases a; simp; apply irrefl,
trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans,
wf := sum.lex_wf (is_well_order.wf r) (is_well_order.wf s) }
instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) :=
{ trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩,
match @trichotomous _ r _ a₁ b₁ with
| or.inl h₁ := or.inl $ prod.lex.left _ _ _ h₁
| or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ _ h₁
| or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with
| or.inl h := or.inl $ prod.lex.right _ _ h
| or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ _ h
| or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl
end
end,
irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h;
[exact irrefl _ h, exact irrefl _ h],
trans := λ a b c h₁ h₂, begin
cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab;
cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc,
{ exact prod.lex.left _ _ _ (trans ab bc) },
{ exact prod.lex.left _ _ _ ab },
{ exact prod.lex.left _ _ _ bc },
{ exact prod.lex.right _ _ (trans ab bc) }
end,
wf := prod.lex_wf (is_well_order.wf r) (is_well_order.wf s) }
theorem well_founded.has_min {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) : p ≠ ∅ → ∃ a ∈ p, ∀ x ∈ p, ¬ r x a :=
by haveI := classical.prop_decidable; exact
not_imp_comm.1 (λ he, set.eq_empty_iff_forall_not_mem.2 $ λ a,
acc.rec_on (H.apply a) $ λ a H IH h,
he ⟨_, h, λ y, imp_not_comm.1 (IH y)⟩)
/-- The minimum element of a nonempty set in a well-founded order -/
noncomputable def well_founded.min {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p ≠ ∅) : α :=
classical.some (H.has_min p h)
theorem well_founded.min_mem {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p ≠ ∅) : H.min p h ∈ p :=
let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h
theorem well_founded.not_lt_min {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p ≠ ∅) {x} (xp : x ∈ p) : ¬ r x (H.min p h) :=
let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp
variable (r)
local infix `≼` : 50 := r
/-- A family of elements of α is directed (with respect to a relation `≼` on α)
if there is a member of the family `≼`-above any pair in the family. -/
def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z
/-- A subset of α is directed if there is an element of the set `≼`-above any
pair of elements in the set. -/
def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z
theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) :=
by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl)
theorem directed_comp {ι} (f : ι → β) (g : β → α) :
directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl
theorem directed_mono {s : α → α → Prop} {ι} (f : ι → α)
(H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f :=
λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩
end
|
b5f5d7927cf8f0fc38a79e3cc35b94360d24b8ac | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/data/finmap.lean | e49b0f8498bed8b6b9728cdbac5e25f440b3ef0f | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 18,158 | lean | /-
Copyright (c) 2018 Sean Leather. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sean Leather, Mario Carneiro
Finite maps over `multiset`.
-/
import data.list.alist data.finset data.pfun
universes u v w
open list
variables {α : Type u} {β : α → Type v}
namespace multiset
/-- Multiset of keys of an association multiset. -/
def keys (s : multiset (sigma β)) : multiset α :=
s.map sigma.fst
@[simp] theorem coe_keys {l : list (sigma β)} :
keys (l : multiset (sigma β)) = (l.keys : multiset α) :=
rfl
/-- `nodupkeys s` means that `s` has no duplicate keys. -/
def nodupkeys (s : multiset (sigma β)) : Prop :=
quot.lift_on s list.nodupkeys (λ s t p, propext $ perm_nodupkeys p)
@[simp] theorem coe_nodupkeys {l : list (sigma β)} : @nodupkeys α β l ↔ l.nodupkeys := iff.rfl
end multiset
/-- `finmap β` is the type of finite maps over a multiset. It is effectively
a quotient of `alist β` by permutation of the underlying list. -/
structure finmap (β : α → Type v) : Type (max u v) :=
(entries : multiset (sigma β))
(nodupkeys : entries.nodupkeys)
/-- The quotient map from `alist` to `finmap`. -/
def alist.to_finmap (s : alist β) : finmap β := ⟨s.entries, s.nodupkeys⟩
local notation `⟦`:max a `⟧`:0 := alist.to_finmap a
theorem alist.to_finmap_eq {s₁ s₂ : alist β} :
⟦s₁⟧ = ⟦s₂⟧ ↔ s₁.entries ~ s₂.entries :=
by cases s₁; cases s₂; simp [alist.to_finmap]
@[simp] theorem alist.to_finmap_entries (s : alist β) : ⟦s⟧.entries = s.entries := rfl
def list.to_finmap [decidable_eq α] (s : list (sigma β)) : finmap β :=
alist.to_finmap (list.to_alist s)
namespace finmap
open alist
/-- Lift a permutation-respecting function on `alist` to `finmap`. -/
@[elab_as_eliminator] def lift_on
{γ} (s : finmap β) (f : alist β → γ)
(H : ∀ a b : alist β, a.entries ~ b.entries → f a = f b) : γ :=
begin
refine (quotient.lift_on s.1 (λ l, (⟨_, λ nd, f ⟨l, nd⟩⟩ : roption γ))
(λ l₁ l₂ p, roption.ext' (perm_nodupkeys p) _) : roption γ).get _,
{ exact λ h₁ h₂, H _ _ (by exact p) },
{ have := s.nodupkeys, rcases s.entries with ⟨l⟩, exact id }
end
@[simp] theorem lift_on_to_finmap {γ} (s : alist β) (f : alist β → γ) (H) :
lift_on ⟦s⟧ f H = f s := by cases s; refl
/-- Lift a permutation-respecting function on 2 `alist`s to 2 `finmap`s. -/
@[elab_as_eliminator] def lift_on₂
{γ} (s₁ s₂ : finmap β) (f : alist β → alist β → γ)
(H : ∀ a₁ b₁ a₂ b₂ : alist β, a₁.entries ~ a₂.entries → b₁.entries ~ b₂.entries → f a₁ b₁ = f a₂ b₂) : γ :=
lift_on s₁
(λ l₁, lift_on s₂ (f l₁) (λ b₁ b₂ p, H _ _ _ _ (perm.refl _) p))
(λ a₁ a₂ p, have H' : f a₁ = f a₂ := funext (λ _, H _ _ _ _ p (perm.refl _)), by simp only [H'])
@[simp] theorem lift_on₂_to_finmap {γ} (s₁ s₂ : alist β) (f : alist β → alist β → γ) (H) :
lift_on₂ ⟦s₁⟧ ⟦s₂⟧ f H = f s₁ s₂ :=
by cases s₁; cases s₂; refl
@[elab_as_eliminator] theorem induction_on
{C : finmap β → Prop} (s : finmap β) (H : ∀ (a : alist β), C ⟦a⟧) : C s :=
by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩
@[elab_as_eliminator] theorem induction_on₂ {C : finmap β → finmap β → Prop}
(s₁ s₂ : finmap β) (H : ∀ (a₁ a₂ : alist β), C ⟦a₁⟧ ⟦a₂⟧) : C s₁ s₂ :=
induction_on s₁ $ λ l₁, induction_on s₂ $ λ l₂, H l₁ l₂
@[elab_as_eliminator] theorem induction_on₃ {C : finmap β → finmap β → finmap β → Prop}
(s₁ s₂ s₃ : finmap β) (H : ∀ (a₁ a₂ a₃ : alist β), C ⟦a₁⟧ ⟦a₂⟧ ⟦a₃⟧) : C s₁ s₂ s₃ :=
induction_on₂ s₁ s₂ $ λ l₁ l₂, induction_on s₃ $ λ l₃, H l₁ l₂ l₃
@[extensionality] theorem ext : ∀ {s t : finmap β}, s.entries = t.entries → s = t
| ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr'
@[simp] theorem ext_iff {s t : finmap β} : s.entries = t.entries ↔ s = t :=
⟨ext, congr_arg _⟩
/-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/
instance : has_mem α (finmap β) := ⟨λ a s, a ∈ s.entries.keys⟩
theorem mem_def {a : α} {s : finmap β} :
a ∈ s ↔ a ∈ s.entries.keys := iff.rfl
@[simp] theorem mem_to_finmap {a : α} {s : alist β} :
a ∈ ⟦s⟧ ↔ a ∈ s := iff.rfl
/-- The set of keys of a finite map. -/
def keys (s : finmap β) : finset α :=
⟨s.entries.keys, induction_on s keys_nodup⟩
@[simp] theorem keys_val (s : alist β) : (keys ⟦s⟧).val = s.keys := rfl
@[simp] theorem keys_ext {s₁ s₂ : alist β} :
keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys :=
by simp [keys, alist.keys]
theorem mem_keys {a : α} {s : finmap β} : a ∈ s.keys ↔ a ∈ s :=
induction_on s $ λ s, alist.mem_keys
/-- The empty map. -/
instance : has_emptyc (finmap β) := ⟨⟨0, nodupkeys_nil⟩⟩
@[simp] theorem empty_to_finmap : (⟦∅⟧ : finmap β) = ∅ := rfl
@[simp] theorem to_finmap_nil [decidable_eq α] : (list.to_finmap [] : finmap β) = ∅ := rfl
theorem not_mem_empty {a : α} : a ∉ (∅ : finmap β) :=
multiset.not_mem_zero a
@[simp] theorem keys_empty : (∅ : finmap β).keys = ∅ := rfl
/-- The singleton map. -/
def singleton (a : α) (b : β a) : finmap β :=
⟦ alist.singleton a b ⟧
@[simp] theorem keys_singleton (a : α) (b : β a) :
(singleton a b).keys = finset.singleton a := rfl
@[simp] lemma mem_singleton (x y : α) (b : β y) : x ∈ singleton y b ↔ x = y :=
by simp only [singleton]; erw [mem_cons_eq,mem_nil_iff,or_false]
variables [decidable_eq α]
instance has_decidable_eq [∀ a, decidable_eq (β a)] : decidable_eq (finmap β)
| s₁ s₂ := decidable_of_iff _ ext_iff
/-- Look up the value associated to a key in a map. -/
def lookup (a : α) (s : finmap β) : option (β a) :=
lift_on s (lookup a) (λ s t, perm_lookup)
@[simp] theorem lookup_to_finmap (a : α) (s : alist β) :
lookup a ⟦s⟧ = s.lookup a := rfl
@[simp] theorem lookup_list_to_finmap (a : α) (s : list (sigma β)) : lookup a s.to_finmap = s.lookup a :=
by rw [list.to_finmap,lookup_to_finmap,lookup_to_alist]
@[simp] theorem lookup_empty (a) : lookup a (∅ : finmap β) = none :=
rfl
theorem lookup_is_some {a : α} {s : finmap β} :
(s.lookup a).is_some ↔ a ∈ s :=
induction_on s $ λ s, alist.lookup_is_some
theorem lookup_eq_none {a} {s : finmap β} : lookup a s = none ↔ a ∉ s :=
induction_on s $ λ s, alist.lookup_eq_none
@[simp] lemma lookup_singleton_eq {a : α} {b : β a} : (singleton a b).lookup a = some b :=
by rw [singleton,lookup_to_finmap,alist.singleton,alist.lookup,lookup_cons_eq]
instance (a : α) (s : finmap β) : decidable (a ∈ s) :=
decidable_of_iff _ lookup_is_some
/-- Replace a key with a given value in a finite map.
If the key is not present it does nothing. -/
def replace (a : α) (b : β a) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦replace a b t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_replace p
@[simp] theorem replace_to_finmap (a : α) (b : β a) (s : alist β) :
replace a b ⟦s⟧ = ⟦s.replace a b⟧ := by simp [replace]
@[simp] theorem keys_replace (a : α) (b : β a) (s : finmap β) :
(replace a b s).keys = s.keys :=
induction_on s $ λ s, by simp
@[simp] theorem mem_replace {a a' : α} {b : β a} {s : finmap β} :
a' ∈ replace a b s ↔ a' ∈ s :=
induction_on s $ λ s, by simp
/-- Fold a commutative function over the key-value pairs in the map -/
def foldl {δ : Type w} (f : δ → Π a, β a → δ)
(H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁)
(d : δ) (m : finmap β) : δ :=
m.entries.foldl (λ d s, f d s.1 s.2) (λ d s t, H _ _ _ _ _) d
def any (f : Π x, β x → bool) (s : finmap β) : bool :=
s.foldl (λ x y z, x ∨ f y z) (by simp [or_assoc]; intros; congr' 2; rw or_comm) ff
def all (f : Π x, β x → bool) (s : finmap β) : bool :=
s.foldl (λ x y z, x ∧ f y z) (by simp [and_assoc]; intros; congr' 2; rw and_comm) ff
/-- Erase a key from the map. If the key is not present it does nothing. -/
def erase (a : α) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦erase a t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_erase p
@[simp] theorem erase_to_finmap (a : α) (s : alist β) :
erase a ⟦s⟧ = ⟦s.erase a⟧ := by simp [erase]
@[simp] theorem keys_erase_to_finset (a : α) (s : alist β) :
keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a :=
by simp [finset.erase, keys, alist.erase, keys_kerase]
@[simp] theorem keys_erase (a : α) (s : finmap β) :
(erase a s).keys = s.keys.erase a :=
induction_on s $ λ s, by simp
@[simp] theorem mem_erase {a a' : α} {s : finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s :=
induction_on s $ λ s, by simp
theorem not_mem_erase_self {a : α} {s : finmap β} : ¬ a ∈ erase a s :=
by rw [mem_erase,not_and_distrib,not_not]; left; refl
@[simp] theorem lookup_erase (a) (s : finmap β) : lookup a (erase a s) = none :=
induction_on s $ lookup_erase a
@[simp] theorem lookup_erase_ne {a a'} {s : finmap β} (h : a ≠ a') :
lookup a (erase a' s) = lookup a s :=
induction_on s $ λ s, lookup_erase_ne h
@[simp] theorem erase_erase {a a' : α} {s : finmap β} : erase a (erase a' s) = erase a' (erase a s) :=
induction_on s $ λ s, ext (by simp)
lemma mem_iff {a : α} {s : finmap β} : a ∈ s ↔ ∃ b, s.lookup a = some b :=
induction_on s $ λ s,
iff.trans list.mem_keys $ exists_congr $ λ b,
(mem_lookup_iff s.nodupkeys).symm
lemma mem_of_lookup_eq_some {a : α} {b : β a} {s : finmap β} (h : s.lookup a = some b) : a ∈ s :=
mem_iff.mpr ⟨_,h⟩
/- sub -/
def sdiff (s s' : finmap β) : finmap β :=
s'.foldl (λ s x _, s.erase x) (λ a₀ a₁ _ a₂ _, erase_erase) s
instance : has_sdiff (finmap β) :=
⟨ sdiff ⟩
/- insert -/
/-- Insert a key-value pair into a finite map, replacing any existing pair with
the same key. -/
def insert (a : α) (b : β a) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦insert a b t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_insert p
@[simp] theorem insert_to_finmap (a : α) (b : β a) (s : alist β) :
insert a b ⟦s⟧ = ⟦s.insert a b⟧ := by simp [insert]
theorem insert_entries_of_neg {a : α} {b : β a} {s : finmap β} : a ∉ s →
(insert a b s).entries = ⟨a, b⟩ :: s.entries :=
induction_on s $ λ s h,
by simp [insert_entries_of_neg (mt mem_to_finmap.1 h)]
@[simp] theorem mem_insert {a a' : α} {b' : β a'} {s : finmap β} :
a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s :=
induction_on s mem_insert
@[simp] theorem lookup_insert {a} {b : β a} (s : finmap β) :
lookup a (insert a b s) = some b :=
induction_on s $ λ s,
by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert]
@[simp] theorem lookup_insert_of_ne {a a'} {b : β a} (s : finmap β) (h : a' ≠ a) :
lookup a' (insert a b s) = lookup a' s :=
induction_on s $ λ s,
by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert_ne h]
@[simp] theorem insert_insert {a} {b b' : β a} (s : finmap β) : (s.insert a b).insert a b' = s.insert a b' :=
induction_on s $ λ s,
by simp only [insert_to_finmap, insert_insert]
theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : finmap β) (h : a ≠ a') :
(s.insert a b).insert a' b' = (s.insert a' b').insert a b :=
induction_on s $ λ s,
by simp only [insert_to_finmap,alist.to_finmap_eq,insert_insert_of_ne _ h]
theorem to_finmap_cons (a : α) (b : β a) (xs : list (sigma β)) : list.to_finmap (⟨a,b⟩ :: xs) = insert a b xs.to_finmap := rfl
theorem mem_list_to_finmap (a : α) (xs : list (sigma β)) : a ∈ xs.to_finmap ↔ (∃ b : β a, sigma.mk a b ∈ xs) :=
by { induction xs with x xs; [skip, cases x];
simp only [to_finmap_cons, *, not_mem_empty, exists_or_distrib, list.not_mem_nil, finmap.to_finmap_nil, iff_self,
exists_false, mem_cons_iff, mem_insert, exists_and_distrib_left];
apply or_congr _ (iff.refl _),
conv { to_lhs, rw ← and_true (a = x_fst) },
apply and_congr_right, rintro ⟨⟩, simp only [exists_eq, iff_self, heq_iff_eq] }
@[simp] theorem insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b :=
by simp only [singleton, finmap.insert_to_finmap, alist.insert_singleton_eq]
/- extract -/
/-- Erase a key from the map, and return the corresponding value, if found. -/
def extract (a : α) (s : finmap β) : option (β a) × finmap β :=
lift_on s (λ t, prod.map id to_finmap (extract a t)) $
λ s₁ s₂ p, by simp [perm_lookup p, to_finmap_eq, perm_erase p]
@[simp] theorem extract_eq_lookup_erase (a : α) (s : finmap β) :
extract a s = (lookup a s, erase a s) :=
induction_on s $ λ s, by simp [extract]
/- union -/
/-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if
there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/
def union (s₁ s₂ : finmap β) : finmap β :=
lift_on₂ s₁ s₂ (λ s₁ s₂, ⟦s₁ ∪ s₂⟧) $
λ s₁ s₂ s₃ s₄ p₁₃ p₂₄, to_finmap_eq.mpr $ perm_union p₁₃ p₂₄
instance : has_union (finmap β) := ⟨union⟩
@[simp] theorem mem_union {a} {s₁ s₂ : finmap β} :
a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ :=
induction_on₂ s₁ s₂ $ λ _ _, mem_union
@[simp] theorem union_to_finmap (s₁ s₂ : alist β) : ⟦s₁⟧ ∪ ⟦s₂⟧ = ⟦s₁ ∪ s₂⟧ :=
by simp [(∪), union]
theorem keys_union {s₁ s₂ : finmap β} : (s₁ ∪ s₂).keys = s₁.keys ∪ s₂.keys :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, finset.ext' $ by simp [keys]
@[simp] theorem lookup_union_left {a} {s₁ s₂ : finmap β} :
a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_left
@[simp] theorem lookup_union_right {a} {s₁ s₂ : finmap β} :
a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_right
theorem lookup_union_left_of_not_in {a} {s₁ s₂ : finmap β} :
a ∉ s₂ → lookup a (s₁ ∪ s₂) = lookup a s₁ :=
begin
intros h,
by_cases h' : a ∈ s₁,
{ rw lookup_union_left h' },
{ rw [lookup_union_right h',lookup_eq_none.mpr h,lookup_eq_none.mpr h'] }
end
@[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : finmap β} :
b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, mem_lookup_union
theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : finmap β} :
b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) :=
induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, mem_lookup_union_middle
theorem insert_union {a} {b : β a} {s₁ s₂ : finmap β} :
insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ :=
induction_on₂ s₁ s₂ $ λ a₁ a₂, by simp [insert_union]
theorem union_assoc {s₁ s₂ s₃ : finmap β} : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃,
by simp only [alist.to_finmap_eq,union_to_finmap,alist.union_assoc]
@[simp] theorem empty_union {s₁ : finmap β} : ∅ ∪ s₁ = s₁ :=
induction_on s₁ $ λ s₁,
by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq,union_to_finmap,alist.union_assoc]
@[simp] theorem union_empty {s₁ : finmap β} : s₁ ∪ ∅ = s₁ :=
induction_on s₁ $ λ s₁,
by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq,union_to_finmap,alist.union_assoc]
theorem ext_lookup {s₁ s₂ : finmap β} : (∀ x, s₁.lookup x = s₂.lookup x) → s₁ = s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂ h,
by simp only [alist.lookup, lookup_to_finmap] at h;
rw [alist.to_finmap_eq]; apply lookup_ext s₁.nodupkeys s₂.nodupkeys;
intros x y; rw h
theorem erase_union_singleton (a : α) (b : β a) (s : finmap β) (h : s.lookup a = some b) :
s.erase a ∪ singleton a b = s :=
ext_lookup
(by { intro, by_cases h' : x = a,
{ subst a, rw [lookup_union_right not_mem_erase_self,lookup_singleton_eq,h], },
{ have : x ∉ singleton a b, { rw mem_singleton, exact h' },
rw [lookup_union_left_of_not_in this,lookup_erase_ne h'] } } )
/- disjoint -/
def disjoint (s₁ s₂ : finmap β) :=
∀ x ∈ s₁, ¬ x ∈ s₂
instance : decidable_rel (@disjoint α β _) :=
by intros x y; dsimp [disjoint]; apply_instance
lemma disjoint_empty (x : finmap β) : disjoint ∅ x .
@[symm]
lemma disjoint.symm (x y : finmap β) (h : disjoint x y) : disjoint y x :=
λ p hy hx, h p hx hy
lemma disjoint.symm_iff (x y : finmap β) : disjoint x y ↔ disjoint y x :=
⟨ disjoint.symm x y, disjoint.symm y x ⟩
lemma disjoint_union_left (x y z : finmap β) : disjoint (x ∪ y) z ↔ disjoint x z ∧ disjoint y z :=
by simp [disjoint,finmap.mem_union,or_imp_distrib,forall_and_distrib]
lemma disjoint_union_right (x y z : finmap β) : disjoint x (y ∪ z) ↔ disjoint x y ∧ disjoint x z :=
by rw [disjoint.symm_iff,disjoint_union_left,disjoint.symm_iff _ x,disjoint.symm_iff _ x]
theorem union_comm_of_disjoint {s₁ s₂ : finmap β} : disjoint s₁ s₂ → s₁ ∪ s₂ = s₂ ∪ s₁ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂,
by { intros h, simp only [alist.to_finmap_eq,union_to_finmap,alist.union_comm_of_disjoint h] }
theorem union_cancel {s₁ s₂ s₃ : finmap β} (h : disjoint s₁ s₃) (h' : disjoint s₂ s₃) : s₁ ∪ s₃ = s₂ ∪ s₃ ↔ s₁ = s₂ :=
⟨λ h'', begin
apply ext_lookup, intro x,
have : (s₁ ∪ s₃).lookup x = (s₂ ∪ s₃).lookup x, from h'' ▸ rfl,
by_cases hs₁ : x ∈ s₁,
{ rw [lookup_union_left hs₁,lookup_union_left_of_not_in (h _ hs₁)] at this,
exact this },
{ by_cases hs₂ : x ∈ s₂,
{ rw [lookup_union_left_of_not_in (h' _ hs₂),lookup_union_left hs₂] at this; exact this },
{ rw [lookup_eq_none.mpr hs₁,lookup_eq_none.mpr hs₂] } }
end,
λ h, h ▸ rfl⟩
end finmap
|
d42900c39e8f5620f258c36bf7540241a0ccae9f | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/runSTBug.lean | bf0d6425f9912857cfc30c3b2002d72b535603ec | [
"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 | 451 | lean | import Lean
open Lean
def f (xs : List Nat) (delta : Nat) : List Nat :=
runST (fun ω => visit xs |>.run)
where
visit {ω} : List Nat → MonadCacheT Nat Nat (ST ω) (List Nat)
| [] => return []
| a::as => do
let b ← checkCache a fun _ => return a + delta
return b :: (← visit as)
def tst (xs : List Nat) : IO Unit := do
IO.println (f xs 10)
IO.println (f xs 20)
IO.println (f xs 30)
#eval tst [1, 2, 3, 1, 2]
|
8650c2eb9369fd597c34e90025ed5a2013f9034b | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/topology/category/Top/opens.lean | a858c503665404478905c8c8718b557a5d270a79 | [
"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,927 | 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 topology.category.Top.basic
import category_theory.eq_to_hom
/-!
# The category of open sets in a topological space.
We define `to_Top : opens X ⥤ Top` and
`map (f : X ⟶ Y) : opens Y ⥤ opens X`, given by taking preimages of open sets.
Unfortunately `opens` isn't (usefully) a functor `Top ⥤ Cat`.
(One can in fact define such a functor,
but using it results in unresolvable `eq.rec` terms in goals.)
Really it's a 2-functor from (spaces, continuous functions, equalities)
to (categories, functors, natural isomorphisms).
We don't attempt to set up the full theory here, but do provide the natural isomorphisms
`map_id : map (𝟙 X) ≅ 𝟭 (opens X)` and
`map_comp : map (f ≫ g) ≅ map g ⋙ map f`.
Beyond that, there's a collection of simp lemmas for working with these constructions.
-/
open category_theory
open topological_space
open opposite
universe u
namespace topological_space.opens
variables {X Y Z : Top.{u}}
/-!
Since `opens X` has a partial order, it automatically receives a `category` instance.
Unfortunately, because we do not allow morphisms in `Prop`,
the morphisms `U ⟶ V` are not just proofs `U ≤ V`, but rather
`ulift (plift (U ≤ V))`.
-/
instance opens_hom_has_coe_to_fun {U V : opens X} : has_coe_to_fun (U ⟶ V) :=
{ F := λ f, U → V,
coe := λ f x, ⟨x, (le_of_hom f) x.2⟩ }
/-!
We now construct as morphisms various inclusions of open sets.
-/
-- This is tedious, but necessary because we decided not to allow Prop as morphisms in a category...
/--
The inclusion `U ⊓ V ⟶ U` as a morphism in the category of open sets.
-/
def inf_le_left (U V : opens X) : U ⊓ V ⟶ U :=
hom_of_le inf_le_left
/--
The inclusion `U ⊓ V ⟶ V` as a morphism in the category of open sets.
-/
def inf_le_right (U V : opens X) : U ⊓ V ⟶ V :=
hom_of_le inf_le_right
/--
The inclusion `U i ⟶ supr U` as a morphism in the category of open sets.
-/
def le_supr {ι : Type*} (U : ι → opens X) (i : ι) : U i ⟶ supr U :=
hom_of_le (le_supr U i)
/--
The inclusion `⊥ ⟶ U` as a morphism in the category of open sets.
-/
def bot_le (U : opens X) : ⊥ ⟶ U :=
hom_of_le bot_le
/--
The inclusion `U ⟶ ⊤` as a morphism in the category of open sets.
-/
def le_top (U : opens X) : U ⟶ ⊤ :=
hom_of_le le_top
-- We do not mark this as a simp lemma because it breaks open `x`.
-- Nevertheless, it is useful in `sheaf_of_functions`.
lemma inf_le_left_apply (U V : opens X) (x) :
(inf_le_left U V) x = ⟨x.1, (@_root_.inf_le_left _ _ U V : _ ≤ _) x.2⟩ :=
rfl
@[simp]
lemma inf_le_left_apply_mk (U V : opens X) (x) (m) :
(inf_le_left U V) ⟨x, m⟩ = ⟨x, (@_root_.inf_le_left _ _ U V : _ ≤ _) m⟩ :=
rfl
@[simp]
lemma le_supr_apply_mk {ι : Type*} (U : ι → opens X) (i : ι) (x) (m) :
(le_supr U i) ⟨x, m⟩ = ⟨x, (_root_.le_supr U i : _) m⟩ :=
rfl
/--
The functor from open sets in `X` to `Top`,
realising each open set as a topological space itself.
-/
def to_Top (X : Top.{u}) : opens X ⥤ Top :=
{ obj := λ U, ⟨U.val, infer_instance⟩,
map := λ U V i, ⟨λ x, ⟨x.1, (le_of_hom i) x.2⟩,
(embedding.continuous_iff embedding_subtype_coe).2 continuous_induced_dom⟩ }
@[simp]
lemma to_Top_map (X : Top.{u}) {U V : opens X} {f : U ⟶ V} {x} {h} :
((to_Top X).map f) ⟨x, h⟩ = ⟨x, (le_of_hom f) h⟩ :=
rfl
/--
The inclusion map from an open subset to the whole space, as a morphism in `Top`.
-/
@[simps]
def inclusion {X : Top.{u}} (U : opens X) : (to_Top X).obj U ⟶ X :=
{ to_fun := _,
continuous_to_fun := continuous_subtype_coe }
lemma inclusion_open_embedding {X : Top.{u}} (U : opens X) : open_embedding (inclusion U) :=
is_open.open_embedding_subtype_coe U.2
/-- `opens.map f` gives the functor from open sets in Y to open set in X,
given by taking preimages under f. -/
def map (f : X ⟶ Y) : opens Y ⥤ opens X :=
{ obj := λ U, ⟨ f ⁻¹' U.val, f.continuous _ U.property ⟩,
map := λ U V i, ⟨ ⟨ λ a b, (le_of_hom i) b ⟩ ⟩ }.
@[simp] lemma map_obj (f : X ⟶ Y) (U) (p) : (map f).obj ⟨U, p⟩ = ⟨f ⁻¹' U, f.continuous _ p⟩ :=
rfl
@[simp] lemma map_id_obj (U : opens X) : (map (𝟙 X)).obj U = U :=
by { ext, refl } -- not quite `rfl`, since we don't have eta for records
@[simp] lemma map_id_obj' (U) (p) : (map (𝟙 X)).obj ⟨U, p⟩ = ⟨U, p⟩ :=
rfl
@[simp] lemma map_id_obj_unop (U : (opens X)ᵒᵖ) : (map (𝟙 X)).obj (unop U) = unop U :=
by simp
@[simp] lemma op_map_id_obj (U : (opens X)ᵒᵖ) : (map (𝟙 X)).op.obj U = U :=
by simp
/--
The inclusion `U ⟶ (map f).obj ⊤` as a morphism in the category of open sets.
-/
def le_map_top (f : X ⟶ Y) (U : opens X) : U ⟶ (map f).obj ⊤ :=
hom_of_le $ λ _ _, trivial
@[simp] lemma map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) :
(map (f ≫ g)).obj U = (map f).obj ((map g).obj U) :=
by { ext, refl } -- not quite `rfl`, since we don't have eta for records
@[simp] lemma map_comp_obj' (f : X ⟶ Y) (g : Y ⟶ Z) (U) (p) :
(map (f ≫ g)).obj ⟨U, p⟩ = (map f).obj ((map g).obj ⟨U, p⟩) :=
rfl
@[simp] lemma map_comp_map (f : X ⟶ Y) (g : Y ⟶ Z) {U V} (i : U ⟶ V) :
(map (f ≫ g)).map i = (map f).map ((map g).map i) :=
rfl
@[simp] lemma map_comp_obj_unop (f : X ⟶ Y) (g : Y ⟶ Z) (U) :
(map (f ≫ g)).obj (unop U) = (map f).obj ((map g).obj (unop U)) :=
map_comp_obj f g (unop U)
@[simp] lemma op_map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) :
(map (f ≫ g)).op.obj U = (map f).op.obj ((map g).op.obj U) :=
by simp
section
variable (X)
/--
The functor `opens X ⥤ opens X` given by taking preimages under the identity function
is naturally isomorphic to the identity functor.
-/
@[simps]
def map_id : map (𝟙 X) ≅ 𝟭 (opens X) :=
{ hom := { app := λ U, eq_to_hom (map_id_obj U) },
inv := { app := λ U, eq_to_hom (map_id_obj U).symm } }
end
/--
The natural isomorphism between taking preimages under `f ≫ g`, and the composite
of taking preimages under `g`, then preimages under `f`.
-/
@[simps]
def map_comp (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f :=
{ hom := { app := λ U, eq_to_hom (map_comp_obj f g U) },
inv := { app := λ U, eq_to_hom (map_comp_obj f g U).symm } }
/--
If two continuous maps `f g : X ⟶ Y` are equal,
then the functors `opens Y ⥤ opens X` they induce are isomorphic.
-/
-- We could make `f g` implicit here, but it's nice to be able to see when
-- they are the identity (often!)
def map_iso (f g : X ⟶ Y) (h : f = g) : map f ≅ map g :=
nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg functor.obj (congr_arg map h)) U) )
(by obviously)
@[simp] lemma map_iso_refl (f : X ⟶ Y) (h) : map_iso f f h = iso.refl (map _) := rfl
@[simp] lemma map_iso_hom_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) :
(map_iso f g h).hom.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h)) U) :=
rfl
@[simp] lemma map_iso_inv_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) :
(map_iso f g h).inv.app U =
eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h.symm)) U) :=
rfl
end topological_space.opens
/--
An open map `f : X ⟶ Y` induces a functor `opens X ⥤ opens Y`.
-/
@[simps]
def is_open_map.functor {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) :
opens X ⥤ opens Y :=
{ obj := λ U, ⟨f '' U, hf U U.2⟩,
map := λ U V h, ⟨⟨set.image_subset _ h.down.down⟩⟩ }
/--
An open map `f : X ⟶ Y` induces an adjunction between `opens X` and `opens Y`.
-/
def is_open_map.adjunction {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) :
adjunction hf.functor (topological_space.opens.map f) :=
adjunction.mk_of_unit_counit
{ unit := { app := λ U, hom_of_le $ λ x hxU, ⟨x, hxU, rfl⟩ },
counit := { app := λ V, hom_of_le $ λ y ⟨x, hfxV, hxy⟩, hxy ▸ hfxV } }
|
71dd2bff610cd6593b5ff460013b89074b42ba04 | e39f04f6ff425fe3b3f5e26a8998b817d1dba80f | /data/finset.lean | 8ca1b5711667c874f5c1421940a865a296b09c08 | [
"Apache-2.0"
] | permissive | kristychoi/mathlib | c504b5e8f84e272ea1d8966693c42de7523bf0ec | 257fd84fe98927ff4a5ffe044f68c4e9d235cc75 | refs/heads/master | 1,586,520,722,896 | 1,544,030,145,000 | 1,544,031,933,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 73,206 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
Finite sets.
-/
import logic.embedding order.boolean_algebra algebra.order_functions
data.multiset data.sigma.basic data.set.lattice
open multiset subtype nat lattice
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type*) :=
(val : multiset α)
(nodup : nodup val)
namespace finset
theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ rfl := rfl
@[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t :=
⟨eq_of_veq, congr_arg _⟩
@[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 :=
erase_dup_eq_self.2 s.2
instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α)
| s₁ s₂ := decidable_of_iff _ val_inj
/- membership -/
instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩
theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl
@[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl
instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) :=
multiset.decidable_mem _ _
/- set coercion -/
/-- Convert a finset to a set in the natural way. -/
def to_set (s : finset α) : set α := {x | x ∈ s}
instance : has_lift (finset α) (set α) := ⟨to_set⟩
@[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl
@[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl
/- extensionality -/
theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ nodup_ext s₁.2 s₂.2
@[extensionality]
theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
ext.2
@[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ :=
(set.ext_iff _ _).trans ext.symm
/- subset -/
instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩
theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl
@[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _
theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans
theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset
theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩
theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl
@[simp] theorem coe_subset {s₁ s₂ : finset α} :
(↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2
instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩
instance : partial_order (finset α) :=
{ le := (⊆),
lt := (⊂),
le_refl := subset.refl,
le_trans := @subset.trans _,
le_antisymm := @subset.antisymm _ }
theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
@[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl
@[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ :=
show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁,
by simp only [set.ssubset_iff_subset_not_subset, finset.coe_subset]
@[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff $ not_congr val_le_iff
/- empty -/
protected def empty : finset α := ⟨0, nodup_zero⟩
instance : has_emptyc (finset α) := ⟨finset.empty⟩
instance : inhabited (finset α) := ⟨∅⟩
@[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl
@[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id
@[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅
| e := not_mem_empty a $ e ▸ h
@[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _
theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_not_mem H)
lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s :=
⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩
@[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅
theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
@[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl
/-- `singleton a` is the set `{a}` containing `a` and nothing else. -/
def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩
local prefix `ι`:90 := singleton
@[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton
theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton
theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl
theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b :=
⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩
@[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _)
@[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl
/- insert -/
section decidable_eq
variables [decidable_eq α]
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩
@[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl
theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl
@[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl
theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) :=
by rw [erase_dup_cons, erase_dup_eq_self]; refl
theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 :=
by rw [insert_val, ndinsert_of_not_mem h]
@[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert
theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1
theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h
theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
(mem_insert.1 h).resolve_left
@[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) :=
set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff]
@[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s :=
eq_of_veq $ ndinsert_of_mem h
theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) :=
ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm]
@[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s :=
ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self]
@[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ :=
ne_empty_of_mem (mem_insert_self a s)
theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib]
theorem subset_insert [h : decidable_eq α] (a : α) (s : finset α) : s ⊆ insert a s :=
λ b, mem_insert_of_mem
theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩
lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) :=
iff.intro
(assume ⟨h₁, h₂⟩,
have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂,
let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩)
(assume ⟨a, hat, has⟩,
let ⟨h₁, h₂⟩ := insert_subset.mp has in
⟨h₂, assume h, hat $ h h₁⟩)
lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff.mpr ⟨a, h, subset.refl _⟩
@[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α]
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s
| ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin
cases nodup_cons.1 nd with m nd',
rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)],
{ exact h₂ (by exact m) (IH nd') },
{ rw [insert_val, ndinsert_of_not_mem m] }
end) nd
@[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α]
(s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
@[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl
@[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl
@[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a :=
insert_eq_of_mem $ mem_singleton_self _
/- union -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩
theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl
@[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 :=
ndunion_eq_union s₁.2
@[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion
theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h
theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h
theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ :=
by rw [mem_union, not_or_distrib]
@[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union
theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ :=
val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩)
theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _
theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _
@[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ :=
ext.2 $ λ x, by simp only [mem_union, or_comm]
instance : is_commutative (finset α) (∪) := ⟨union_comm⟩
@[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
ext.2 $ λ x, by simp only [mem_union, or_assoc]
instance : is_associative (finset α) (∪) := ⟨union_assoc⟩
@[simp] theorem union_idempotent (s : finset α) : s ∪ s = s :=
ext.2 $ λ _, mem_union.trans $ or_self _
instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩
theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext.2 $ λ _, by simp only [mem_union, or.left_comm]
theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)]
@[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s
@[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s :=
ext.2 $ λ x, mem_union.trans $ or_false _
@[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s :=
ext.2 $ λ x, mem_union.trans $ false_or _
theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl
@[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) :=
by simp only [insert_eq, union_assoc]
@[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) :=
by simp only [insert_eq, union_left_comm]
theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t :=
by simp only [insert_union, union_insert, insert_idem]
/- inter -/
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩
theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl
@[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 :=
ndinter_eq_inter s₁.2
@[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left
theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right
theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ :=
by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial
@[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter
@[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ :=
ext.2 $ λ _, by simp only [mem_inter, and_comm]
@[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) :=
ext.2 $ λ _, by simp only [mem_inter, and_assoc]
@[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext.2 $ λ _, by simp only [mem_inter, and.left_comm]
@[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext.2 $ λ _, by simp only [mem_inter, and.right_comm]
@[simp] theorem inter_self (s : finset α) : s ∩ s = s :=
ext.2 $ λ _, mem_inter.trans $ and_self _
@[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ :=
ext.2 $ λ _, mem_inter.trans $ and_false _
@[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ :=
ext.2 $ λ _, mem_inter.trans $ false_and _
@[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h,
by simp only [mem_inter, mem_insert, or_and_distrib_left, this]
@[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) :=
by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H,
by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or]
@[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
by rw [inter_comm, insert_inter_of_not_mem h, inter_comm]
@[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a :=
show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter]
@[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ :=
eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h
@[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a :=
by rw [inter_comm, singleton_inter_of_mem h]
@[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ :=
by rw [inter_comm, singleton_inter_of_not_mem h]
/- lattice laws -/
instance : lattice (finset α) :=
{ sup := (∪),
sup_le := assume a b c, union_subset,
le_sup_left := subset_union_left,
le_sup_right := subset_union_right,
inf := (∩),
le_inf := assume a b c, subset_inter,
inf_le_left := inter_subset_left,
inf_le_right := inter_subset_right,
..finset.partial_order }
@[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl
instance : semilattice_inf_bot (finset α) :=
{ bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice }
instance : distrib_lattice (finset α) :=
{ le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c,
by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt};
simp only [true_or, imp_true_iff, true_and, or_true],
..finset.lattice.lattice }
theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left
theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right
theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left
theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right
/- erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩
@[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl
@[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
mem_erase_iff_of_nodup s.2
theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2
@[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl
theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a :=
by simp only [mem_erase]; exact and.left
theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase
theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b :=
by simp only [mem_erase]; exact and.intro
theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s :=
ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or];
apply and_iff_right_of_imp; rintro H rfl; exact h H
theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s :=
ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and];
apply or_iff_right_of_imp; rintro rfl; exact h
theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h
theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _
@[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) :=
set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl
lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s :=
calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _
... = _ : insert_erase h
theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq $ erase_of_not_mem h
theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t :=
by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp];
exact forall_congr (λ x, forall_swap)
theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 $ subset.refl _
theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 $ subset.refl _
/- sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩
@[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} :
a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2
@[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ :=
ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm,
or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a)
@[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ :=
(union_comm _ _).trans (sdiff_union_of_subset h)
@[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ :=
eq_empty_of_forall_not_mem $
by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h
@[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ :=
(inter_comm _ _).trans (inter_sdiff_self _ _)
theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ :=
by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂)
@[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) :=
set.ext $ λ _, mem_sdiff
end decidable_eq
/- attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the
subtype `{x // x ∈ s}`. -/
def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩
@[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl
@[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _
@[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl
section decidable_pi_exists
variables {s : finset α}
instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∀a (h : a ∈ s), p a h) :=
multiset.decidable_dforall_multiset
/-- decidable equality for functions whose domain is bounded by finsets -/
instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈s, β a) :=
multiset.decidable_eq_pi_multiset
instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∃a (h : a ∈ s), p a h) :=
multiset.decidable_dexists_multiset
end decidable_pi_exists
/- filter -/
section filter
variables {p q : α → Prop} [decidable_pred p] [decidable_pred q]
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α :=
⟨_, nodup_filter p s.2⟩
@[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl
@[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter
@[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _
theorem filter_filter (s : finset α) :
(s.filter p).filter q = s.filter (λa, p a ∧ q a) :=
ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm]
@[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] :
@finset.filter α (λ _, true) h s = s :=
by ext; simp
@[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ :=
ext.2 $ assume a, by simp only [mem_filter, and_false]; refl
lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s :=
eq_of_veq $ filter_congr H
variable [decidable_eq α]
theorem filter_union (s₁ s₂ : finset α) :
(s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p :=
ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right]
theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q :=
ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left]
theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q :=
ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self]
theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p :=
ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $
λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm
theorem sdiff_eq_filter (s₁ s₂ : finset α) :
s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter]
theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s :=
by simp only [filter_not, union_sdiff_of_subset (filter_subset s)]
theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ :=
by simp only [filter_not, inter_sdiff_self]
@[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
set.ext $ λ _, mem_filter
end filter
/- range -/
section range
variables {n m l : ℕ}
/-- `range n` is the set of natural numbers less than `n`. -/
def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩
@[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl
@[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range
@[simp] theorem range_zero : range 0 = ∅ := rfl
@[simp] theorem range_one : range 1 = {0} := rfl
theorem range_succ : range (succ n) = insert n (range n) :=
eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm
@[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self
@[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset
theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n :=
finset.induction_on s ⟨0, empty_subset _⟩ $ λ a s ha ⟨n, hn⟩,
⟨max (a + 1) n, insert_subset.2
⟨by simpa only [mem_range] using le_max_left (a+1) n,
subset.trans hn (by simpa only [range_subset] using le_max_right (a+1) n)⟩⟩
end range
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false :=
by simp only [not_mem_empty, false_and, exists_false]
theorem exists_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) :=
by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true :=
iff_true_intro $ λ _, false.elim
theorem forall_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) :=
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
end finset
namespace option
/-- Construct an empty or singleton finset from an `option` -/
def to_finset (o : option α) : finset α :=
match o with
| none := ∅
| some a := finset.singleton a
end
@[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl
@[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl
@[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o :=
by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl
end option
/- erase_dup on list and multiset -/
namespace multiset
variable [decidable_eq α]
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩
@[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl
theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset :=
finset.val_inj.1 (erase_dup_eq_self.2 n).symm
@[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s :=
mem_erase_dup
@[simp] lemma to_finset_zero :
to_finset (0 : multiset α) = ∅ :=
rfl
@[simp] lemma to_finset_cons (a : α) (s : multiset α) :
to_finset (a :: s) = insert a (to_finset s) :=
finset.eq_of_veq erase_dup_cons
@[simp] lemma to_finset_add (s t : multiset α) :
to_finset (s + t) = to_finset s ∪ to_finset t :=
finset.ext' $ by simp
end multiset
namespace list
variable [decidable_eq α]
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset (l : list α) : finset α := multiset.to_finset l
@[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl
theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset :=
multiset.to_finset_eq n
@[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l :=
mem_erase_dup
@[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ :=
rfl
@[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) :=
finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h]
end list
namespace finset
section map
open function
def map (f : α ↪ β) (s : finset α) : finset β :=
⟨s.1.map f, nodup_map f.2 s.2⟩
@[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl
@[simp] theorem map_empty (f : α ↪ β) (s : finset α) : (∅ : finset α).map f = ∅ := rfl
variables {f : α ↪ β} {s : finset α}
@[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b :=
mem_map.trans $ by simp only [exists_prop]; refl
theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s :=
mem_map_of_inj f.2
@[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f :=
(mem_map' _).2
theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} :
s.to_finset.map f = (s.map f).to_finset :=
ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset]
theorem map_refl : s.map (embedding.refl _) = s :=
ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right
theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq $ by simp only [map_val, multiset.map_map]; refl
theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ :=
⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs,
λ h, by simp [subset_def, map_subset_map h]⟩
theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ :=
by simp only [subset.antisymm_iff, map_subset_map]
def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩
@[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl
theorem map_filter {p : β → Prop} [decidable_pred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩,
by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem map_union [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem map_inter [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact
⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩,
by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩
@[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) :=
ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm
@[simp] theorem map_insert [decidable_eq α] [decidable_eq β]
(f : α ↪ β) (a : α) (s : finset α) :
(insert a s).map f = insert (f a) (s.map f) :=
by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton]
@[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s :=
eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _
end map
section image
variables [decidable_eq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset
@[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl
@[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl
variables {f : α → β} {s : finset α}
@[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b :=
by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop]
@[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f :=
mem_image.2 ⟨_, h, rfl⟩
@[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s :=
set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl
theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset :=
ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map]
@[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f :=
multiset.erase_dup_eq_self.2 (nodup_map_on H s.2)
theorem image_id [decidable_eq α] : s.image id = s :=
ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right]
theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map]
theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f :=
by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h]
theorem image_filter {p : β → Prop} [decidable_pred p] :
(s.image f).filter p = (s.filter (p ∘ f)).image f :=
ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩,
by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b,
⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩,
λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩.
@[simp] theorem image_singleton [decidable_eq α] (f : α → β) (a : α) : (singleton a).image f = singleton (f a) :=
ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm
@[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) :
(insert a s).image f = insert (f a) (s.image f) :=
by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union]
@[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s :=
eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self]
@[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} :
attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s})
((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) :=
ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx)
(assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h)
(assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩),
λ _, finset.mem_attach _ _⟩
theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f :=
eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm
lemma image_const [decidable_eq β] {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b :=
ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right,
exists_mem_of_ne_empty h, true_and, mem_singleton, eq_comm]
protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) :=
(s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩,
λ x y H, subtype.eq $ subtype.mk.inj H⟩
@[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} :
∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s
| ⟨a, ha⟩ := by simp [finset.subtype, ha]
end image
/- card -/
section card
/-- `card s` is the cardinality (number of elements) of `s`. -/
def card (s : finset α) : nat := s.1.card
theorem card_def (s : finset α) : s.card = s.1.card := rfl
@[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl
@[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ :=
card_eq_zero.trans val_eq_zero
theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
@[simp] theorem card_insert_of_not_mem [decidable_eq α]
{a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 :=
by simpa only [card_cons, card, insert_val] using
congr_arg multiset.card (ndinsert_of_not_mem h)
theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 :=
by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right},
rw [card_insert_of_not_mem h]]
@[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _
theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem
@[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n
@[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach
theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α}
(H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s :=
by simp only [card, image_val_of_inj_on H, card_map]
theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α)
(H : function.injective f) : card (image f s) = card s :=
card_image_of_inj_on $ λ x _ y _ h, H h
lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ}
(f : ∀i, i < n → α)
(hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s)
(f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) :
card s = n :=
have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a,
from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩,
assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩,
have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)),
by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and],
calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) :
by rw [this]
... = card ((range n).attach) :
card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq,
subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq
... = card (range n) : card_attach
... = n : card_range n
lemma card_eq_succ [decidable_eq α] {s : finset α} {a : α} {n : ℕ} :
s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) :=
iff.intro
(assume eq,
have card s > 0, from eq.symm ▸ nat.zero_lt_succ _,
let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in
⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩)
(assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat)
theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t :=
multiset.card_le_of_le ∘ val_le_iff.mpr
theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t :=
eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂
lemma card_lt_card [decidable_eq α] {s t : finset α} (h : s ⊂ t) : s.card < t.card :=
card_lt_of_lt (val_lt_iff.2 h)
lemma card_le_card_of_inj_on [decidable_eq α] [decidable_eq β] {s : finset α} {t : finset β}
(f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) :
card s ≤ card t :=
calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj]
... ≤ card t : card_le_of_subset $
assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end
lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α}
(f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s :=
calc n = card (range n) : (card_range n).symm
... ≤ card s : card_le_card_of_inj_on f
(by simpa only [mem_range])
(by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂)
@[elab_as_eliminator] lemma strong_induction_on {p : finset α → Sort*} :
∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s
| ⟨s, nd⟩ ih := multiset.strong_induction_on s
(λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd
@[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop}
(s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s :=
finset.strong_induction_on s $ λ s,
finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $
λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _)
lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β)
(h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b)
(h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card :=
by haveI := classical.prop_decidable; exact
calc s.card = s.attach.card : card_attach.symm
... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card :
eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h)))
... = t.card : congr_arg card (finset.ext.2 $ λ b,
⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _,
λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩)
lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) :
(s ∪ t).card + (s ∩ t).card = s.card + t.card :=
finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt})
lemma card_union_le [decidable_eq α] (s t : finset α) :
(s ∪ t).card ≤ s.card + t.card :=
card_union_add_card_inter s t ▸ le_add_right _ _
lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂)
(hst : card t ≤ card s) :
(∀ b ∈ t, ∃ a ha, b = f a ha) :=
by haveI := classical.dec_eq β; exact
λ b hb,
have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s,
from @card_attach _ s ▸ card_image_of_injective _
(λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h),
have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t :=
eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in
ha₂ ▸ hf _ _) (by simp [hst, h]),
begin
rw ← h₁ at hb,
rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩,
exact ⟨a, a.2, ha₂.symm⟩,
end
end card
section bind
variables [decidable_eq β] {s : finset α} {t : α → finset β}
/-- `bind s t` is the union of `t x` over `x ∈ s` -/
protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset
@[simp] theorem bind_val (s : finset α) (t : α → finset β) :
(s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl
@[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl
@[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a :=
by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop]
@[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t :=
ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert,
or_and_distrib_right, exists_or_distrib, exists_eq_left]
-- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib]
@[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a :=
show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _
theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} :
(s.image f).bind t = s.bind (λa, t (f a)) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [image_insert, bind_insert, ih])
theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} :
(s.bind t).image f = s.bind (λa, (t a).image f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [bind_insert, image_union, ih])
theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) :
(s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) :=
ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop]
lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ :=
have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a),
from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩,
by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop]
lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f :=
ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm]
lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) :
(s.image g).bind (λa, s.filter $ (λc, g c = a)) = s :=
begin
ext b,
simp,
split,
{ rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb },
{ rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ }
end
end bind
section prod
variables {s : finset α} {t : finset β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩
@[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = s.bind (λa, t.image $ λb, (a, b)) :=
ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
@[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t :=
multiset.card_product _ _
end prod
section sigma
variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)}
/-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/
protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) :=
⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩
@[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma
theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)}
(H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ :=
λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩
theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) :
s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) :=
ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right]
end sigma
section pi
variables {δ : α → Type*} [decidable_eq α]
def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) :=
⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩
@[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) :
(s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl
@[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} :
f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) :=
mem_pi _ _ _
def pi.empty (β : α → Sort*) [decidable_eq α] (a : α) (h : a ∈ (∅ : finset α)) : β a :=
multiset.pi.empty β a h
def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' :=
multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h)
@[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) :
pi.cons s a b f a h = b :=
multiset.pi.cons_same _
lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') :
pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) :=
multiset.pi.cons_ne _ _
lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume e₁ e₂ eq,
@multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $
funext $ assume e, funext $ assume h,
have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h),
by rw [eq],
this
@[simp] lemma pi_empty {t : Πa:α, finset (δ a)} :
pi (∅ : finset α) t = singleton (pi.empty δ) := rfl
@[simp] lemma pi_insert [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) :
pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) :=
begin
apply eq_of_veq,
rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2,
refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) =
erase_dup ((t a).1.bind $ λ b,
erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $
λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha),
subst s', rw pi_cons,
congr, funext b,
rw multiset.erase_dup_eq_self.2,
exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2,
end
end pi
section powerset
def powerset (s : finset α) : finset (finset α) :=
⟨s.1.powerset.pmap finset.mk
(λ t h, nodup_of_le (mem_powerset.1 h) s.2),
nodup_pmap (λ a ha b hb, congr_arg finset.val)
(nodup_powerset.2 s.2)⟩
@[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t :=
by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff
@[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s :=
mem_powerset.2 (empty_subset _)
@[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s :=
mem_powerset.2 (subset.refl _)
@[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t :=
⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _),
λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩
@[simp] theorem card_powerset (s : finset α) :
card (powerset s) = 2 ^ card s :=
(card_pmap _ _ _).trans (card_powerset s.1)
end powerset
section fold
variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op]
local notation a * b := op a b
include hc ha
/-- `fold op b f s` folds the commutative associative operation `op` over the
`f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/
def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b
variables {op} {f : α → β} {b : β} {s : finset α} {a : α}
@[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl
@[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f :=
by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left]
@[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl
@[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ}
(H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) :=
by simp only [fold, image_val_of_inj_on H, multiset.map_map]
@[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g :=
by rw [fold, fold, map_congr H]
theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} :
s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g :=
by simp only [fold, fold_distrib]
theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op']
{m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) :
s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) :=
by rw [fold, fold, ← fold_hom op hm, multiset.map_map]
theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} :
(s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f :=
by unfold fold; rw [← fold_add op, ← map_add, union_val,
inter_val, union_add_inter, map_add, hc.comm, fold_add]
@[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] :
(insert a s).fold op b f = f a * s.fold op b f :=
by haveI := classical.prop_decidable;
rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq,
fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold]
end fold
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/
def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma sup_val : s.sup f = (s.1.map f).sup := rfl
@[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ :=
fold_empty
@[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f :=
fold_insert_idem
@[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b :=
calc _ = f b ⊔ (∅:finset β).sup f : sup_insert
... = f b : sup_bot_eq
lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f :=
finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih,
by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc]
lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_refl _) (λ a s has ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2))
lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f :=
by letI := classical.dec_eq β; from
calc f b ≤ f b ⊔ s.sup f : le_sup_left
... = (insert b s).sup f : sup_insert.symm
... = s.sup f : by rw [insert_eq_of_mem hb]
lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, bot_le) (λ n s hns ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [sup_insert]; exact sup_le H.1 (ih H.2))
lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) :=
iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le
lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f :=
sup_le $ assume b hb, le_sup (h hb)
lemma sup_lt [is_total α (≤)] {a : α} : (⊥ < a) → (∀b ∈ s, f b < a) → s.sup f < a :=
have A : ∀ x y, x < a → y < a → x ⊔ y < a :=
begin
assume x y hx hy,
cases (is_total.total (≤) x y) with h,
{ simpa [sup_of_le_right h] using hy },
{ simpa [sup_of_le_left h] using hx }
end,
by letI := classical.dec_eq β; from
finset.induction_on s (by simp) (by simp [A] {contextual := tt})
lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ]
(g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) :=
have A : ∀x y, g (x ⊔ y) = g x ⊔ g y :=
begin
assume x y,
cases (is_total.total (≤) x y) with h,
{ simp [sup_of_le_right h, sup_of_le_right (mono_g h)] },
{ simp [sup_of_le_left h, sup_of_le_left (mono_g h)] }
end,
by letI := classical.dec_eq β; from
finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt})
end sup
lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) :=
le_antisymm
(finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha)
(supr_le $ assume a, supr_le $ assume ha, le_sup ha)
section inf
variables [semilattice_inf_top α]
/-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/
def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma inf_val : s.inf f = (s.1.map f).inf := rfl
@[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ :=
fold_empty
@[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f :=
fold_insert_idem
@[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b :=
calc _ = f b ⊓ (∅:finset β).inf f : inf_insert
... = f b : inf_top_eq
lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f :=
finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih,
by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc]
lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_refl _) (λ a s has ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2))
lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b :=
by letI := classical.dec_eq β; from
calc f b ≥ f b ⊓ s.inf f : inf_le_left
... = (insert b s).inf f : inf_insert.symm
... = s.inf f : by rw [insert_eq_of_mem hb]
lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_top) (λ n s hns ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [inf_insert]; exact le_inf H.1 (ih H.2))
lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) :=
iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf
lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f :=
le_inf $ assume b hb, inf_le (h hb)
lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f :=
have A : ∀ x y, a < x → a < y → a < x ⊓ y :=
begin
assume x y hx hy,
cases (is_total.total (≤) x y) with h,
{ simpa [inf_of_le_left h] using hy },
{ simpa [inf_of_le_right h] using hx }
end,
by letI := classical.dec_eq β; from
finset.induction_on s (by simp) (by simp [A] {contextual := tt})
lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ]
(g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) :=
have A : ∀x y, g (x ⊓ y) = g x ⊓ g y :=
begin
assume x y,
cases (is_total.total (≤) x y) with h,
{ simp [inf_of_le_left h, inf_of_le_left (mono_g h)] },
{ simp [inf_of_le_right h, inf_of_le_right (mono_g h)] }
end,
by letI := classical.dec_eq β; from
finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt})
end inf
lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) :=
le_antisymm
(le_infi $ assume a, le_infi $ assume ha, inf_le ha)
(finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha)
/- max and min of finite sets -/
section max_min
variables [decidable_linear_order α]
protected def max : finset α → option α :=
fold (option.lift_or_get max) none some
theorem max_eq_sup_with_bot (s : finset α) :
s.max = @sup (with_bot α) α _ s some := rfl
@[simp] theorem max_empty : (∅ : finset α).max = none := rfl
@[simp] theorem max_insert {a : α} {s : finset α} :
(insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem
@[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert
@[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton
theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max :=
(@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem max_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.max :=
let ⟨a, ha⟩ := exists_mem_of_ne_empty h in max_of_mem ha
theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ :=
⟨λ h, by_contradiction $
λ hs, let ⟨a, ha⟩ := max_of_ne_empty hs in by rw [h] at ha; cases ha,
λ h, h.symm ▸ max_empty⟩
theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s :=
finset.induction_on s (λ _ H, by cases H)
(λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice max_choice (some b) s.max with q q;
rw [max_insert, q] at h,
{ cases h, cases p rfl },
{ exact mem_insert_of_mem (ih h) } }
end)
theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b :=
by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
protected def min : finset α → option α :=
fold (option.lift_or_get min) none some
theorem min_eq_inf_with_top (s : finset α) :
s.min = @inf (with_top α) α _ s some := rfl
@[simp] theorem min_empty : (∅ : finset α).min = none := rfl
@[simp] theorem min_insert {a : α} {s : finset α} :
(insert a s).min = option.lift_or_get min (some a) s.min :=
fold_insert_idem
@[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert
theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min :=
(@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem min_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.min :=
let ⟨a, ha⟩ := exists_mem_of_ne_empty h in min_of_mem ha
theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ :=
⟨λ h, by_contradiction $
λ hs, let ⟨a, ha⟩ := min_of_ne_empty hs in by rw [h] at ha; cases ha,
λ h, h.symm ▸ min_empty⟩
theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s :=
finset.induction_on s (λ _ H, by cases H) $
λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice min_choice (some b) s.min with q q;
rw [min_insert, q] at h,
{ cases h, cases p rfl },
{ exact mem_insert_of_mem (ih h) } }
end
theorem le_min_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b :=
by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
end max_min
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort (s : finset α) : list α := sort r s.1
@[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) :=
sort_sorted _ _
@[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 :=
sort_eq _ _
@[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup :=
(by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s))
@[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s :=
list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s)
@[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
multiset.mem_sort _
end sort
section disjoint
variable [decidable_eq α]
theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl
theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 :=
disjoint_left
theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁))
theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁))
@[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left
@[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right
@[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s :=
by simp only [disjoint_left, mem_singleton, forall_eq]
@[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s :=
disjoint.comm.trans singleton_disjoint
@[simp] theorem disjoint_insert_left {a : α} {s t : finset α} :
disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t :=
by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] theorem disjoint_insert_right {a : α} {s t : finset α} :
disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm]
@[simp] theorem disjoint_union_left {s t u : finset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right {s t u : finset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem card_disjoint_union {s t : finset α} :
disjoint s t → card (s ∪ t) = card s + card t :=
finset.induction_on s (λ _, by simp only [empty_union, card_empty, zero_add]) $ λ a s ha ih H,
have h1 : a ∉ s ∪ t, from λ h, or.elim (mem_union.1 h) ha (disjoint_insert_left.1 H).1,
by rw [insert_union, card_insert_of_not_mem h1, card_insert_of_not_mem ha, ih (disjoint_insert_left.1 H).2, add_right_comm]
end disjoint
theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) :
list.sorted (<) (sort (≤) s) :=
(sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _)
instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩
def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) :=
⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩
@[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} :
a ∈ s.attach_fin h ↔ a.1 ∈ s :=
⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁,
λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩
@[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) :
(s.attach_fin h).card = s.card := multiset.card_pmap _ _ _
section choose
variables (p : α → Prop) [decidable_pred p] (l : finset α)
def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } :=
multiset.choose_x p l.val hp
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
theorem lt_wf {α} [decidable_eq α] : well_founded (@has_lt.lt (finset α) _) :=
have H : subrelation (@has_lt.lt (finset α) _)
(inv_image (<) card),
from λ x y hxy, card_lt_card hxy,
subrelation.wf H $ inv_image.wf _ $ nat.lt_wf
section decidable_linear_order
variables {α} [decidable_linear_order α]
def min' (S : finset α) (H : S ≠ ∅) : α :=
@option.get _ S.min $
let ⟨k, hk⟩ := exists_mem_of_ne_empty H in
let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb]
def max' (S : finset α) (H : S ≠ ∅) : α :=
@option.get _ S.max $
let ⟨k, hk⟩ := exists_mem_of_ne_empty H in
let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb]
variables (S : finset α) (H : S ≠ ∅)
theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min']
theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := le_min_of_mem H2 $ option.get_mem _
theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _
theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max']
theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _
theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _
theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H :=
begin
rcases lt_trichotomy i j with H4 | H4 | H4,
{ have H5 := min'_le S H i H1,
have H6 := le_max' S H j H2,
apply lt_of_le_of_lt H5,
apply lt_of_lt_of_le H4 H6 },
{ cc },
{ have H5 := min'_le S H j H2,
have H6 := le_max' S H i H1,
apply lt_of_le_of_lt H5,
apply lt_of_lt_of_le H4 H6 }
end
end decidable_linear_order
end finset
namespace list
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length :=
congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h
end list
|
a19df92db35c36500b0fed9cbb4d941a48d0793e | 4e0d7c3132ce31edc5829849735dd25db406b144 | /lean/love09_hoare_logic_demo.lean | 34f67273c9c73b245db493d1fa1c95c3bb447760 | [] | no_license | gonzalgu/logical_verification_2020 | a0013a6c22ea254e9f4d245f2948f0f4d44df4bb | 724d0457dff2c3ff10f9ab2170388f4c5e958b75 | refs/heads/master | 1,660,886,374,533 | 1,589,859,641,000 | 1,589,859,641,000 | 256,069,971 | 0 | 0 | null | 1,586,997,430,000 | 1,586,997,429,000 | null | UTF-8 | Lean | false | false | 15,153 | lean | import .love08_operational_semantics_demo
/-! # LoVe Demo 9: Hoare Logic
We review a second way to specify the semantics of a programming language: Hoare
logic. If operational semantics corresponds to an idealized interpreter,
__Hoare logic__ (also called __axiomatic semantics__) corresponds to a verifier.
Hoare logic is particularly convenient to reason about concrete programs. -/
set_option pp.beta true
namespace LoVe
/-! ## First Things First: Formalization Projects
Instead of two of the homeworks, you can do a verification project, worth
20 points. If you choose to do so, please send your lecturer a message (by email
or via Canvas) by the end of the week. For a fully successful project, we expect
about 200 (or more) lines of Lean, including definitions and proofs.
Some ideas for projects follow.
Computer science:
* extended WHILE language with static arrays or other features;
* functional data structures (e.g., balanced trees);
* functional algorithms (e.g., bubble sort, merge sort, Tarjan's algorithm);
* compiler from expressions or imperative programs to, e.g., stack machine;
* type systems (e.g., Benjamin Pierce's __Types and Programming Languages__);
* security properties (e.g., Volpano–Smith-style noninterference analysis);
* theory of first-order terms, including matching, term rewriting;
* automata theory;
* normalization of context-free grammars or regular expressions;
* process algebras and bisimilarity;
* soundness and possibly completeness of proof systems (e.g., Genzen's sequent
calculus, natural deduction, tableaux);
* separation logic;
* verified program using Hoare logic.
Mathematics:
* graphs;
* combinatorics;
* number theory.
Evaluation from 2018–2019:
Q: How did you find the project?
A: Enjoyable.
A: Fun and hard.
A: Good, I think the format was excellent in a way that it gave people the
chance to do challenging exercises and hand them in incomplete.
A: I really really liked it. I think it's a great way of learning—find
something you like, dig in it a little, get stuck, ask for help. I wish I
could do more of that!
A: It was great to have some time to try to work out some stuff you find
interesting yourself.
A: lots of fun actually!!!
A: Very helpful. It gave the opportunity to spend some more time on a
particular aspect of the course.
## Hoare Triples
The basic judgments of Hoare logic are often called __Hoare triples__. They have
the form
`{P} S {Q}`
where `S` is a statement, and `P` and `Q` (called __precondition__ and
__postcondition__) are logical formulas over the state variables.
Intended meaning:
If `P` holds before `S` is executed and the execution terminates normally,
`Q` holds at termination.
This is a __partial correctness__ statement: The program is correct if it
terminates normally (i.e., no run-time error, no infinite loop or divergence).
All of these Hoare triples are valid (with respect to the intended meaning):
`{true} b := 4 {b = 4}`
`{a = 2} b := 2 * a {a = 2 ∧ b = 4}`
`{b ≥ 5} b := b + 1 {b ≥ 6}`
`{false} skip {b = 100}`
`{true} while i ≠ 100 do i := i + 1 {i = 100}`
## Hoare Rules
The following is a complete set of rules for reasoning about WHILE programs:
———————————— Skip
{P} skip {P}
——————————————————— Asn
{Q[a/x]} x := a {Q}
{P} S {R} {R} S' {Q}
—————————————————————— Seq
{P} S; S' {Q}
{I ∧ b} S {Q} {I ∧ ¬b} S' {Q}
——————————————————————————————— If
{I} if b then S else S' {Q}
{P ∧ b} S {P}
————————————————————————— While
{P} while b do S {P ∧ ¬b}
P' → P {P} S {Q} Q → Q'
——————————————————————————— Conseq
{P'} S {Q'}
`Q[a/x]` denotes `Q` with `x` replaced by `a`.
In the `While` rule, `I` is called an __invariant__.
Except for `Conseq`, the rules are syntax-driven: by looking at a program, we
see immediately which rule to apply.
Example derivations:
—————————————————————— Asn —————————————————————— Asn
{a = 2} b := a {b = 2} {b = 2} c := b {c = 2}
——————————————————————————————————————————————————— Seq
{a = 2} b := a; c := b {c = 2}
—————————————————————— Asn
x > 10 → x > 5 {x > 5} y := x {y > 5} y > 5 → y > 0
——————————————————————————————————————————————————————— Conseq
{x > 10} y := x {y > 0}
Various __derived rules__ can be proved to be correct in terms of the standard
rules. For example, we can derive bidirectional rules for `skip`, `:=`, and
`while`:
P → Q
———————————— Skip'
{P} skip {Q}
P → Q[a/x]
—————————————— Asn'
{P} x := a {Q}
{P ∧ b} S {P} P ∧ ¬b → Q
—————————————————————————— While'
{P} while b do S {Q}
## A Semantic Approach to Hoare Logic
We can, and will, define Hoare triples **semantically** in Lean.
We will use predicates on states (`state → Prop`) to represent pre- and
postconditions, following the shallow embedding style. -/
def partial_hoare (P : state → Prop) (S : stmt)
(Q : state → Prop) : Prop :=
∀s t, P s → (S, s) ⟹ t → Q t
notation `{* ` P : 1 ` *} ` S : 1 ` {* ` Q : 1 ` *}` :=
partial_hoare P S Q
namespace partial_hoare
lemma skip_intro {P} :
{* P *} stmt.skip {* P *} :=
begin
intros s t hs hst,
cases hst,
assumption
end
lemma assign_intro (P : state → Prop) {x} {a : state → ℕ} :
{* λs, P (s{x ↦ a s}) *} stmt.assign x a {* P *} :=
begin
intros s t P hst,
cases hst,
assumption
end
lemma seq_intro {P Q R S T} (hS : {* P *} S {* Q *})
(hT : {* Q *} T {* R *}) :
{* P *} S ;; T {* R *} :=
begin
intros s t P hst,
cases hst,
apply hT,
{ apply hS,
{ exact P },
{ assumption } },
{ assumption }
end
lemma ite_intro {b P Q : state → Prop} {S T}
(hS : {* λs, P s ∧ b s *} S {* Q *})
(hT : {* λs, P s ∧ ¬ b s *} T {* Q *}) :
{* P *} stmt.ite b S T {* Q *} :=
begin
intros s t hs hst,
cases hst,
{ apply hS,
exact and.intro hs hst_hcond,
assumption },
{ apply hT,
exact and.intro hs hst_hcond,
assumption }
end
lemma while_intro (P : state → Prop) {b : state → Prop} {S}
(h : {* λs, P s ∧ b s *} S {* P *}) :
{* P *} stmt.while b S {* λs, P s ∧ ¬ b s *} :=
begin
intros s t hs,
generalize hws : (stmt.while b S, s) = ws,
intro hst,
induction hst generalizing s; cases hws,
{ apply hst_ih_hrest hst_t,
{ apply h hst_s; cc },
{ refl } },
{ exact and.intro hs hst_hcond }
end
lemma consequence {P P' Q Q' : state → Prop} {S}
(h : {* P *} S {* Q *}) (hp : ∀s, P' s → P s)
(hq : ∀s, Q s → Q' s) :
{* P' *} S {* Q' *} :=
fix s t,
assume hs : P' s,
assume hst : (S, s) ⟹ t,
show Q' t, from
hq _ (h s t (hp s hs) hst)
lemma tac_style_consequence { P P' Q Q' : state → Prop} {S}
(h : {* P *} S {* Q *}) (hp : ∀s, P' s → P s)
(hq : ∀s, Q s → Q' s) :
{* P' *} S {* Q' *} :=
begin
intros s t hP' hS,
apply hq,
apply h s t,
apply hp,
assumption,
assumption,
end
lemma fwd_style_consequence { P P' Q Q' : state → Prop} {S}
(h : {* P *} S {* Q *}) (hp : ∀s, P' s → P s)
(hq : ∀s, Q s → Q' s) :
{* P' *} S {* Q' *} :=
fix s t,
(λ (hP' : P' s) (hS : (S, s) ⟹ t), hq t (h s t (hp s hP') hS))
lemma consequence_left (P' : state → Prop) {P Q S}
(h : {* P *} S {* Q *}) (hp : ∀s, P' s → P s) :
{* P' *} S {* Q *} :=
consequence h hp (by cc)
lemma consequence_right (Q) {Q' : state → Prop} {P S}
(h : {* P *} S {* Q *}) (hq : ∀s, Q s → Q' s) :
{* P *} S {* Q' *} :=
consequence h (by cc) hq
lemma skip_intro' {P Q : state → Prop} (h : ∀s, P s → Q s) :
{* P *} stmt.skip {* Q *} :=
consequence skip_intro h (by cc)
lemma assign_intro' {P Q : state → Prop} {x} {a : state → ℕ}
(h : ∀s, P s → Q (s{x ↦ a s})):
{* P *} stmt.assign x a {* Q *} :=
consequence (assign_intro Q) h (by cc)
lemma seq_intro' {P Q R S T} (hT : {* Q *} T {* R *})
(hS : {* P *} S {* Q *}) :
{* P *} S ;; T {* R *} :=
seq_intro hS hT
lemma while_intro' {b P Q : state → Prop} {S}
(I : state → Prop)
(hS : {* λs, I s ∧ b s *} S {* I *})
(hP : ∀s, P s → I s)
(hQ : ∀s, ¬ b s → I s → Q s) :
{* P *} stmt.while b S {* Q *} :=
consequence (while_intro I hS) hP (by finish)
/-! `finish` applies a combination of techniques, including normalization of
logical connectives and quantifiers, simplification, congruence closure, and
quantifier instantiation. It either fully succeeds or fails. -/
lemma assign_intro_forward (P) {x a} :
{* P *}
stmt.assign x a
{* λs, ∃n₀, P (s{x ↦ n₀}) ∧ s x = a (s{x ↦ n₀}) *} :=
begin
apply assign_intro',
intros s hP,
apply exists.intro (s x),
simp [*]
end
lemma assign_intro_backward (Q : state → Prop) {x}
{a : state → ℕ} :
{* λs, ∃n', Q (s{x ↦ n'}) ∧ n' = a s *}
stmt.assign x a
{* Q *} :=
begin
apply assign_intro',
intros s hP,
cases hP,
cc
end
end partial_hoare
/-! ## First Program: Exchanging Two Variables -/
def SWAP : stmt :=
stmt.assign "t" (λs, s "a") ;;
stmt.assign "a" (λs, s "b") ;;
stmt.assign "b" (λs, s "t")
lemma SWAP_correct (a₀ b₀ : ℕ) :
{* λs, s "a" = a₀ ∧ s "b" = b₀ *}
SWAP
{* λs, s "a" = b₀ ∧ s "b" = a₀ *} :=
begin
apply partial_hoare.seq_intro',
apply partial_hoare.seq_intro',
apply partial_hoare.assign_intro,
apply partial_hoare.assign_intro,
apply partial_hoare.assign_intro',
simp { contextual := tt }
end
lemma SWAP_correct₂ (a₀ b₀ : ℕ) :
{* λs, s "a" = a₀ ∧ s "b" = b₀ *}
SWAP
{* λs, s "a" = b₀ ∧ s "b" = a₀ *} :=
begin
intros s t hP hstep,
cases hstep,
cases hstep_hS,
cases hstep_hT,
cases hstep_hT_hS,
cases hstep_hT_hT,
finish,
end
/-! ## Second Program: Adding Two Numbers -/
def ADD : stmt :=
stmt.while (λs, s "n" ≠ 0)
(stmt.assign "n" (λs, s "n" - 1) ;;
stmt.assign "m" (λs, s "m" + 1))
lemma ADD_correct (n₀ m₀ : ℕ) :
{* λs, s "n" = n₀ ∧ s "m" = m₀ *}
ADD
{* λs, s "n" = 0 ∧ s "m" = n₀ + m₀ *} :=
partial_hoare.while_intro' (λs, s "n" + s "m" = n₀ + m₀)
begin
apply partial_hoare.seq_intro',
{ apply partial_hoare.assign_intro },
{ apply partial_hoare.assign_intro',
simp,
intros s hnm hnz,
rewrite ←hnm,
cases s "n"; finish }
end
(by simp { contextual := true })
(by simp { contextual := true })
/-! ## A Verification Condition Generator
__Verification condition generators__ (VCGs) are programs that apply Hoare rules
automatically, producing __verification conditions__ that must be proved by the
user. The user must usually also provide strong enough loop invariants, as an
annotation in their programs.
We can use Lean's metaprogramming framework to define a simple VCG.
Hundreds if not thousands of program verification tools are based on these
principles. Often these are based on an extension called separation logic.
VCGs typically work backwards from the postcondition, using backward rules
(rules stated to have an arbitrary `Q` as their postcondition). This works well
because `Asn` is backward. -/
def stmt.while_inv (I b : state → Prop) (S : stmt) : stmt :=
stmt.while b S
namespace partial_hoare
lemma while_inv_intro {b I Q : state → Prop} {S}
(hS : {* λs, I s ∧ b s *} S {* I *})
(hQ : ∀s, ¬ b s → I s → Q s) :
{* I *} stmt.while_inv I b S {* Q *} :=
while_intro' I hS (by cc) hQ
lemma while_inv_intro' {b I P Q : state → Prop} {S}
(hS : {* λs, I s ∧ b s *} S {* I *})
(hP : ∀s, P s → I s) (hQ : ∀s, ¬ b s → I s → Q s) :
{* P *} stmt.while_inv I b S {* Q *} :=
while_intro' I hS hP hQ
end partial_hoare
meta def vcg : tactic unit :=
do
t ← tactic.target,
match t with
| `({* %%P *} %%S {* _ *}) :=
match S with
| `(stmt.skip) :=
tactic.applyc
(if expr.is_mvar P then ``partial_hoare.skip_intro
else ``partial_hoare.skip_intro')
| `(stmt.assign _ _) :=
tactic.applyc
(if expr.is_mvar P then ``partial_hoare.assign_intro
else ``partial_hoare.assign_intro')
| `(stmt.seq _ _) :=
tactic.applyc ``partial_hoare.seq_intro'; vcg
| `(stmt.ite _ _ _) :=
tactic.applyc ``partial_hoare.ite_intro; vcg
| `(stmt.while_inv _ _ _) :=
tactic.applyc
(if expr.is_mvar P then ``partial_hoare.while_inv_intro
else ``partial_hoare.while_inv_intro');
vcg
| _ :=
tactic.fail (to_fmt "cannot analyze " ++ to_fmt S)
end
| _ := pure ()
end
end LoVe
/-! Register `vcg` as a proper tactic: -/
meta def tactic.interactive.vcg : tactic unit :=
LoVe.vcg
namespace LoVe
/-! ## Second Program Revisited: Adding Two Numbers -/
lemma ADD_correct₂ (n₀ m₀ : ℕ) :
{* λs, s "n" = n₀ ∧ s "m" = m₀ *}
ADD
{* λs, s "n" = 0 ∧ s "m" = n₀ + m₀ *} :=
show {* λs, s "n" = n₀ ∧ s "m" = m₀ *}
stmt.while_inv (λs, s "n" + s "m" = n₀ + m₀)
(λs, s "n" ≠ 0)
(stmt.assign "n" (λs, s "n" - 1) ;;
stmt.assign "m" (λs, s "m" + 1))
{* λs, s "n" = 0 ∧ s "m" = n₀ + m₀ *}, from
begin
vcg; simp { contextual := tt },
intros s hnm hnz,
rewrite ←hnm,
cases s "n"; finish
end
/-! ## Hoare Triples for Total Correctness
__Total correctness__ asserts that the program not only is partially correct but
also that it always terminates normally. Hoare triples for total correctness
have the form
[P] S [Q]
Intended meaning:
If the `P` holds before `S` is executed, the execution terminates normally
and `Q` holds in the final state.
For deterministic programs, an equivalent formulation is as follows:
If `P` holds before `S` is executed, there exists a state in which execution
terminates normally and `Q` holds in that state.
Example:
`[i ≤ 100] while i ≠ 100 do i := i + 1 [i = 100]`
In our WHILE language, this only affects while loops, which must now be
annotated by a __variant__ `V` (a natural number that decreases with each
iteration):
[I ∧ b ∧ V = v₀] S [I ∧ V < v₀]
——————————————————————————————— While
[I] while b do S [I ∧ ¬b]
What is the variant in the example above? -/
end LoVe
|
d6266555948752e887ea2c986356076da2b99b0f | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/data/fin.lean | 5536ec94a40800d30afd09043fec6cb8ebb56336 | [
"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 | 73,793 | lean | /-
Copyright (c) 2017 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Keeley Hoek
-/
import data.nat.cast
import data.int.basic
import tactic.localized
import tactic.apply_fun
import order.rel_iso
/-!
# The finite type with `n` elements
`fin n` is the type whose elements are natural numbers smaller than `n`.
This file expands on the development in the core library.
## Main definitions
### Induction principles
* `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`.
* `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted
as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines
`0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element
of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple.
* `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument;
* `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the
`nat`-like base cases of `C 0` and `C (i.succ)`.
* `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument.
### Casts
* `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into;
* `cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`;
* `cast eq` : embed `fin n` into `fin m`, `eq : n = m`;
* `cast_add m` : embed `fin n` into `fin (n+m)`;
* `cast_succ` : embed `fin n` into `fin (n+1)`;
* `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`;
* `pred_above (p : fin n) i` : embed `i : fin (n+1)` into `fin n` by subtracting one if `p < i`;
* `cast_pred` : embed `fin (n + 2)` into `fin (n + 1)` by mapping `last (n + 1)` to `last n`;
* `sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`;
* `add_nat m i` : add `m` on `i` on the right, generalizes `fin.succ`;
* `nat_add n i` adds `n` on `i` on the left;
* `clamp n m` : `min n m` as an element of `fin (m + 1)`;
### Operation on tuples
We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`.
If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal)
to `vector`s.
We define the following operations:
* `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries;
* `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple;
* `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries;
* `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc`
comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order.
* `insert_nth` : insert an element to a tuple at a given position.
* `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied.
### Misc definitions
* `fin.last n` : The greatest value of `fin (n+1)`.
-/
universes u v
open fin nat function
/-- Elimination principle for the empty set `fin 0`, dependent version. -/
def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0
lemma fact.succ.pos {n} : fact (0 < succ n) := ⟨zero_lt_succ _⟩
lemma fact.bit0.pos {n} [h : fact (0 < n)] : fact (0 < bit0 n) :=
⟨nat.zero_lt_bit0 $ ne_of_gt h.1⟩
lemma fact.bit1.pos {n} : fact (0 < bit1 n) :=
⟨nat.zero_lt_bit1 _⟩
lemma fact.pow.pos {p n : ℕ} [h : fact $ 0 < p] : fact (0 < p ^ n) :=
⟨pow_pos h.1 _⟩
localized "attribute [instance] fact.succ.pos" in fin_fact
localized "attribute [instance] fact.bit0.pos" in fin_fact
localized "attribute [instance] fact.bit1.pos" in fin_fact
localized "attribute [instance] fact.pow.pos" in fin_fact
namespace fin
variables {n m : ℕ} {a b : fin n}
instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨subtype.val⟩
lemma pos_iff_nonempty {n : ℕ} : 0 < n ↔ nonempty (fin n) :=
⟨λ h, ⟨⟨0, h⟩⟩, λ ⟨i⟩, lt_of_le_of_lt (nat.zero_le _) i.2⟩
section coe
/-!
### coercions and constructions
-/
@[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a :=
by cases a; refl
@[ext]
lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h
lemma ext_iff (a b : fin n) : a = b ↔ (a : ℕ) = b :=
iff.intro (congr_arg _) fin.eq_of_veq
lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := subtype.coe_injective
lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 :=
⟨veq_of_eq, eq_of_veq⟩
lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 :=
⟨vne_of_ne, ne_of_vne⟩
@[simp] lemma mk_eq_subtype_mk (a : ℕ) (h : a < n) : mk a h = ⟨a, h⟩ := rfl
protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} :
(⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b :=
subtype.mk_eq_mk
lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl
lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k :=
fin.eq_iff_veq a ⟨k, hk⟩
@[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl
lemma mk_coe (i : fin n) : (⟨i, i.property⟩ : fin n) = i :=
fin.eta _ _
lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl
@[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl
/-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element,
then they coincide (in the heq sense). -/
protected lemma heq_fun_iff {α : Sort*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} :
f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) :=
by { induction h, simp [heq_iff_eq, function.funext_iff] }
protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} :
i == j ↔ (i : ℕ) = (j : ℕ) :=
by { induction h, simp [ext_iff] }
lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ :=
⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩),
λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩
lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ :=
⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩
end coe
section order
/-!
### order
-/
lemma is_lt (i : fin n) : (i : ℕ) < n := i.2
lemma is_le (i : fin (n + 1)) : (i : ℕ) ≤ n := le_of_lt_succ i.is_lt
lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl
lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl
lemma mk_lt_of_lt_coe {a : ℕ} (h : a < b) : (⟨a, h.trans b.is_lt⟩ : fin n) < b := h
lemma mk_le_of_le_coe {a : ℕ} (h : a ≤ b) : (⟨a, h.trans_lt b.is_lt⟩ : fin n) ≤ b := h
/-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/
@[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b :=
iff.rfl
/-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/
@[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b :=
iff.rfl
instance {n : ℕ} : linear_order (fin n) :=
{ le := (≤), lt := (<),
decidable_le := fin.decidable_le,
decidable_lt := fin.decidable_lt,
decidable_eq := fin.decidable_eq _,
..linear_order.lift (coe : fin n → ℕ) (@fin.eq_of_veq _) }
/-- The inclusion map `fin n → ℕ` is a relation embedding. -/
def coe_embedding (n) : (fin n) ↪o ℕ :=
⟨⟨coe, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩
/-- The ordering on `fin n` is a well order. -/
instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) :=
(coe_embedding n).is_well_order
/-- Use the ordering on `fin n` for checking recursive definitions.
For example, the following definition is not accepted by the termination checker,
unless we declare the `has_well_founded` instance:
```lean
def factorial {n : ℕ} : fin n → ℕ
| ⟨0, _⟩ := 1
| ⟨i + 1, hi⟩ := (i + 1) * factorial ⟨i, i.lt_succ_self.trans hi⟩
```
-/
instance {n : ℕ} : has_well_founded (fin n) :=
⟨_, measure_wf coe⟩
@[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl
attribute [simp] val_zero
@[simp] lemma val_zero' (n) : (0 : fin (n+1)).val = 0 := rfl
@[simp] lemma mk_zero : (⟨0, nat.succ_pos'⟩ : fin (n + 1)) = (0 : fin _) := rfl
lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1
lemma pos_iff_ne_zero (a : fin (n+1)) : 0 < a ↔ a ≠ 0 :=
begin
split,
{ rintros h rfl, exact lt_irrefl _ h, },
{ rintros h,
apply (@pos_iff_ne_zero _ _ (a : ℕ)).mpr,
cases a,
rintro w,
apply h,
simp at w,
subst w,
refl, },
end
lemma eq_zero_or_eq_succ {n : ℕ} (i : fin (n+1)) : i = 0 ∨ ∃ j : fin n, i = j.succ :=
begin
rcases i with ⟨_|j, h⟩,
{ left, refl, },
{ right, exact ⟨⟨j, nat.lt_of_succ_lt_succ h⟩, rfl⟩, }
end
/-- The greatest value of `fin (n+1)` -/
def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩
@[simp, norm_cast] lemma coe_last (n : ℕ) : (last n : ℕ) = n := rfl
lemma last_val (n : ℕ) : (last n).val = n := rfl
theorem le_last (i : fin (n+1)) : i ≤ last n :=
le_of_lt_succ i.is_lt
instance : bounded_lattice (fin (n + 1)) :=
{ top := last n,
le_top := le_last,
bot := 0,
bot_le := zero_le,
.. fin.linear_order, .. lattice_of_linear_order }
lemma last_pos : (0 : fin (n + 2)) < last (n + 1) :=
by simp [lt_iff_coe_lt_coe]
lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n :=
le_antisymm (le_last i) (not_lt.1 h)
section
variables {α : Type*} [preorder α]
open set
/-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity
map. In this lemma we state that for each `i : fin n` we have `(e i : ℕ) = (i : ℕ)`. -/
@[simp] lemma coe_order_iso_apply (e : fin n ≃o fin m) (i : fin n) : (e i : ℕ) = i :=
begin
rcases i with ⟨i, hi⟩,
rw [subtype.coe_mk],
induction i using nat.strong_induction_on with i h,
refine le_antisymm (forall_lt_iff_le.1 $ λ j hj, _) (forall_lt_iff_le.1 $ λ j hj, _),
{ have := e.symm.lt_iff_lt.2 (mk_lt_of_lt_coe hj),
rw e.symm_apply_apply at this,
convert this,
simpa using h _ this (e.symm _).is_lt },
{ rwa [← h j hj (hj.trans hi), ← lt_iff_coe_lt_coe, e.lt_iff_lt] }
end
instance order_iso_subsingleton : subsingleton (fin n ≃o α) :=
⟨λ e e', by { ext i,
rw [← e.symm.apply_eq_iff_eq, e.symm_apply_apply, ← e'.trans_apply, ext_iff,
coe_order_iso_apply] }⟩
instance order_iso_subsingleton' : subsingleton (α ≃o fin n) :=
order_iso.symm_injective.subsingleton
instance order_iso_unique : unique (fin n ≃o fin n) := unique.mk' _
/-- Two strictly monotone functions from `fin n` are equal provided that their ranges
are equal. -/
lemma strict_mono_unique {f g : fin n → α} (hf : strict_mono f) (hg : strict_mono g)
(h : range f = range g) : f = g :=
have (hf.order_iso f).trans (order_iso.set_congr _ _ h) = hg.order_iso g,
from subsingleton.elim _ _,
congr_arg (function.comp (coe : range g → α)) (funext $ rel_iso.ext_iff.1 this)
/-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/
lemma order_embedding_eq {f g : fin n ↪o α} (h : range f = range g) : f = g :=
rel_embedding.ext $ funext_iff.1 $ strict_mono_unique f.strict_mono g.strict_mono h
end
/-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/
lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} :
strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ :=
begin
split,
{ assume H i hi,
apply H,
exact nat.lt_succ_self _ },
{ assume H,
have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩,
{ assume i j h h',
induction h with k h IH,
{ exact H _ _ },
{ exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } },
assume i j hij,
convert A (i : ℕ) (j : ℕ) hij j.2; ext; simp only [subtype.coe_eta] }
end
end order
section add
/-!
### addition, numerals, and coercion from nat
-/
/-- convert a `ℕ` to `fin n`, provided `n` is positive -/
def of_nat' [h : fact (0 < n)] (i : ℕ) : fin n := ⟨i%n, mod_lt _ h.1⟩
lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl
lemma coe_one' {n : ℕ} : ((1 : fin (n+1)) : ℕ) = 1 % (n+1) := rfl
@[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl
@[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl
@[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl
instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩
section monoid
@[simp] protected lemma add_zero (k : fin (n + 1)) : k + 0 = k :=
by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)]
@[simp] protected lemma zero_add (k : fin (n + 1)) : (0 : fin (n + 1)) + k = k :=
by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)]
instance add_comm_monoid (n : ℕ) : add_comm_monoid (fin (n + 1)) :=
{ add := (+),
add_assoc := by simp [eq_iff_veq, add_def, add_assoc],
zero := 0,
zero_add := fin.zero_add,
add_zero := fin.add_zero,
add_comm := by simp [eq_iff_veq, add_def, add_comm] }
end monoid
lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma coe_add_eq_ite {n : ℕ} (a b : fin n) :
(↑(a + b) : ℕ) = if n ≤ a + b then a + b - n else a + b :=
by rw [fin.coe_add, nat.add_mod_eq_ite,
nat.mod_eq_of_lt (show ↑a < n, from a.2), nat.mod_eq_of_lt (show ↑b < n, from b.2)]
lemma coe_bit0 {n : ℕ} (k : fin n) : ((bit0 k : fin n) : ℕ) = bit0 (k : ℕ) % n :=
by { cases k, refl }
lemma coe_bit1 {n : ℕ} (k : fin (n + 1)) :
((bit1 k : fin (n + 1)) : ℕ) = bit1 (k : ℕ) % (n + 1) :=
begin
cases n, { cases k with k h, cases k, {show _ % _ = _, simp}, cases h with _ h, cases h },
simp [bit1, fin.coe_bit0, fin.coe_add, fin.coe_one],
end
lemma coe_add_one_of_lt {n : ℕ} {i : fin n.succ} (h : i < last _) :
(↑(i + 1) : ℕ) = i + 1 :=
begin
-- First show that `((1 : fin n.succ) : ℕ) = 1`, because `n.succ` is at least 2.
cases n,
{ cases h },
-- Then just unfold the definitions.
rw [fin.coe_add, fin.coe_one, nat.mod_eq_of_lt (nat.succ_lt_succ _)],
exact h
end
@[simp] lemma last_add_one : ∀ n, last n + 1 = 0
| 0 := subsingleton.elim _ _
| (n + 1) := by { ext, rw [coe_add, coe_zero, coe_last, coe_one, nat.mod_self] }
lemma coe_add_one {n : ℕ} (i : fin (n + 1)) :
((i + 1 : fin (n + 1)) : ℕ) = if i = last _ then 0 else i + 1 :=
begin
rcases (le_last i).eq_or_lt with rfl|h,
{ simp },
{ simpa [h.ne] using coe_add_one_of_lt h }
end
section bit
@[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) :
(⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) :=
eq_of_veq (nat.mod_eq_of_lt h).symm
@[simp] lemma mk_bit1 {m n : ℕ} (h : bit1 m < n + 1) :
(⟨bit1 m, h⟩ : fin (n + 1)) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt
((m + m).lt_succ_self.trans h)⟩ : fin _) :=
begin
ext,
simp only [bit1, bit0] at h,
simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h],
end
end bit
@[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl
@[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl
section of_nat_coe
@[simp]
lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a :=
begin
induction a with a ih, { refl },
ext, show (a+1) % (n+1) = subtype.val (a+1 : fin (n+1)),
{ rw [val_add, ← ih, of_nat],
exact add_mod _ _ _ }
end
/-- Converting an in-range number to `fin (n + 1)` produces a result
whose value is the original number. -/
lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) :
((a : fin (n + 1)).val) = a :=
begin
rw ←of_nat_eq_coe,
exact nat.mod_eq_of_lt h
end
/-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results
in the same value. -/
lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a :=
begin
rw fin.eq_iff_veq,
exact coe_val_of_lt a.property
end
/-- Coercing an in-range number to `fin (n + 1)`, and converting back
to `ℕ`, results in that number. -/
lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) :
((a : fin (n + 1)) : ℕ) = a :=
coe_val_of_lt h
/-- Converting a `fin (n + 1)` to `ℕ` and back results in the same
value. -/
@[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a :=
coe_val_eq_self a
lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n :=
by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] }
lemma le_coe_last (i : fin (n + 1)) : i ≤ n :=
by { rw fin.coe_nat_eq_last, exact fin.le_last i }
end of_nat_coe
lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 :=
begin
cases n,
{ exact absurd h (nat.not_lt_zero _) },
{ rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h,
rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h],
exact nat.zero_lt_succ _ }
end
lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0
lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos
@[simp] lemma zero_eq_one_iff : (0 : fin (n + 1)) = 1 ↔ n = 0 :=
begin
split,
{ cases n; intro h,
{ refl },
{ have := zero_ne_one, contradiction } },
{ rintro rfl, refl }
end
@[simp] lemma one_eq_zero_iff : (1 : fin (n + 1)) = 0 ↔ n = 0 :=
by rw [eq_comm, zero_eq_one_iff]
end add
section succ
/-!
### succ and casts into larger fin types
-/
@[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 :=
by cases j; simp [fin.succ]
lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe]
/-- `fin.succ` as an `order_embedding` -/
def succ_embedding (n : ℕ) : fin n ↪o fin (n + 1) :=
order_embedding.of_strict_mono fin.succ $ λ ⟨i, hi⟩ ⟨j, hj⟩ h, succ_lt_succ h
@[simp] lemma coe_succ_embedding : ⇑(succ_embedding n) = fin.succ := rfl
@[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b :=
(succ_embedding n).le_iff_le
@[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b :=
(succ_embedding n).lt_iff_lt
lemma succ_injective (n : ℕ) : injective (@fin.succ n) :=
(succ_embedding n).injective
@[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b :=
(succ_injective n).eq_iff
lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0
| ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (ext_iff _ _).1 heq
@[simp] lemma succ_zero_eq_one : fin.succ (0 : fin (n + 1)) = 1 := rfl
@[simp] lemma succ_one_eq_two : fin.succ (1 : fin (n + 2)) = 2 := rfl
@[simp] lemma succ_mk (n i : ℕ) (h : i < n) : fin.succ ⟨i, h⟩ = ⟨i + 1, nat.succ_lt_succ h⟩ :=
rfl
lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ :=
by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i }
lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ :=
begin
cases n,
{ exact fin_zero_elim a },
{ rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a }
end
lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a)
/-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/
def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩
@[simp] lemma coe_cast_lt (i : fin m) (h : i.1 < n) : (cast_lt i h : ℕ) = i := rfl
@[simp] lemma cast_lt_mk (i n m : ℕ) (hn : i < n) (hm : i < m) : cast_lt ⟨i, hn⟩ hm = ⟨i, hm⟩ := rfl
/-- `cast_le h i` embeds `i` into a larger `fin` type. -/
def cast_le (h : n ≤ m) : fin n ↪o fin m :=
order_embedding.of_strict_mono (λ a, cast_lt a (lt_of_lt_of_le a.2 h)) $ λ a b h, h
@[simp] lemma coe_cast_le (h : n ≤ m) (i : fin n) : (cast_le h i : ℕ) = i := rfl
@[simp] lemma cast_le_mk (i n m : ℕ) (hn : i < n) (h : n ≤ m) :
cast_le h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h⟩ := rfl
@[simp] lemma cast_le_zero {n m : ℕ} (h : n.succ ≤ m.succ) :
cast_le h 0 = 0 :=
by simp [eq_iff_veq]
@[simp] lemma range_cast_le {n k : ℕ} (h : n ≤ k) :
set.range (cast_le h) = {i | (i : ℕ) < n} :=
set.ext (λ x, ⟨λ ⟨y, hy⟩, hy ▸ y.2, λ hx, ⟨⟨x, hx⟩, fin.ext rfl⟩⟩)
@[simp] lemma coe_of_injective_cast_le_symm {n k : ℕ} (h : n ≤ k) (i : fin k) (hi) :
((equiv.of_injective _ (cast_le h).injective).symm ⟨i, hi⟩ : ℕ) = i :=
begin
rw ← coe_cast_le,
exact congr_arg coe (equiv.apply_of_injective_symm _ _ _)
end
@[simp] lemma cast_le_succ {m n : ℕ} (h : (m + 1) ≤ (n + 1)) (i : fin m) :
cast_le h i.succ = (cast_le (nat.succ_le_succ_iff.mp h) i).succ :=
by simp [fin.eq_iff_veq]
/-- `cast eq i` embeds `i` into a equal `fin` type. -/
def cast (eq : n = m) : fin n ≃o fin m :=
{ to_equiv := ⟨cast_le eq.le, cast_le eq.symm.le, λ a, eq_of_veq rfl, λ a, eq_of_veq rfl⟩,
map_rel_iff' := λ a b, iff.rfl }
@[simp] lemma symm_cast (h : n = m) : (cast h).symm = cast h.symm := rfl
lemma coe_cast (h : n = m) (i : fin n) : (cast h i : ℕ) = i := rfl
@[simp] lemma cast_mk (h : n = m) (i : ℕ) (hn : i < n) :
cast h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h.le⟩ := rfl
@[simp] lemma cast_trans {k : ℕ} (h : n = m) (h' : m = k) {i : fin n} :
cast h' (cast h i) = cast (eq.trans h h') i := rfl
@[simp] lemma cast_refl (h : n = n := rfl) : cast h = order_iso.refl (fin n) :=
by { ext, refl }
/-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply
a generic theorem about `cast`. -/
lemma cast_to_equiv (h : n = m) : (cast h).to_equiv = equiv.cast (h ▸ rfl) :=
by { subst h, simp }
/-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply
a generic theorem about `cast`. -/
lemma cast_eq_cast (h : n = m) : (cast h : fin n → fin m) = _root_.cast (h ▸ rfl) :=
by { subst h, ext, simp }
/-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/
def cast_add (m) : fin n ↪o fin (n + m) := cast_le $ nat.le_add_right n m
@[simp] lemma coe_cast_add (m : ℕ) (i : fin n) : (cast_add m i : ℕ) = i := rfl
lemma cast_add_lt {m : ℕ} (n : ℕ) (i : fin m) : (cast_add n i : ℕ) < m := i.2
@[simp] lemma cast_add_mk (m : ℕ) (i : ℕ) (h : i < n) :
cast_add m ⟨i, h⟩ = ⟨i, lt_add_right i n m h⟩ := rfl
/-- embedding `fin n` into `fin (m + n)` sending `i` to `m + i` -/
def cast_add_right (m : ℕ) {n : ℕ} : fin n ↪ fin (m + n) :=
{ to_fun := λ i, ⟨m + i, add_lt_add_left i.2 _⟩,
inj' := λ i j h, fin.ext (by simpa using h) }
@[simp] lemma coe_cast_add_right (m : ℕ) {n : ℕ} (i : fin n) :
(cast_add_right m i : ℕ) = m + i := rfl
lemma le_cast_add_right (m : ℕ) {n : ℕ} (i : fin n) : m ≤ cast_add_right m i :=
nat.le_add_right _ _
/-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/
def cast_succ : fin n ↪o fin (n + 1) := cast_add 1
@[simp] lemma coe_cast_succ (i : fin n) : (i.cast_succ : ℕ) = i := rfl
@[simp] lemma cast_succ_mk (n i : ℕ) (h : i < n) : cast_succ ⟨i, h⟩ = ⟨i, nat.lt.step h⟩ := rfl
lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ :=
lt_iff_coe_lt_coe.2 $ by simp only [coe_cast_succ, coe_succ, nat.lt_succ_self]
lemma le_cast_succ_iff {i : fin (n + 1)} {j : fin n} : i ≤ j.cast_succ ↔ i < j.succ :=
by simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe] using nat.succ_le_succ_iff.symm
@[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl
@[simp] lemma succ_eq_last_succ {n : ℕ} (i : fin n.succ) :
i.succ = last (n + 1) ↔ i = last n :=
by rw [← succ_last, (succ_injective _).eq_iff]
@[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i :=
fin.eq_of_veq rfl
@[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) :
cast_lt (cast_succ a) h = a :=
by cases a; refl
@[simp] lemma cast_succ_lt_cast_succ_iff : a.cast_succ < b.cast_succ ↔ a < b :=
(@cast_succ n).lt_iff_lt
lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) :=
(cast_succ : fin n ↪o _).injective
lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b :=
(cast_succ_injective n).eq_iff
lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt
@[simp] lemma cast_succ_zero : cast_succ (0 : fin (n + 1)) = 0 := rfl
@[simp] lemma cast_succ_one {n : ℕ} : fin.cast_succ (1 : fin (n + 2)) = 1 := rfl
/-- `cast_succ i` is positive when `i` is positive -/
lemma cast_succ_pos {i : fin (n + 1)} (h : 0 < i) : 0 < cast_succ i :=
by simpa [lt_iff_coe_lt_coe] using h
@[simp] lemma cast_succ_eq_zero_iff (a : fin (n + 1)) : a.cast_succ = 0 ↔ a = 0 :=
subtype.ext_iff.trans $ (subtype.ext_iff.trans $ by exact iff.rfl).symm
lemma cast_succ_ne_zero_iff (a : fin (n + 1)) : a.cast_succ ≠ 0 ↔ a ≠ 0 :=
not_iff_not.mpr $ cast_succ_eq_zero_iff a
lemma cast_succ_fin_succ (n : ℕ) (j : fin n) :
cast_succ (fin.succ j) = fin.succ (cast_succ j) :=
by simp [fin.ext_iff]
@[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ :=
begin
ext,
exact coe_val_of_lt (nat.lt.step a.is_lt),
end
@[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ :=
begin
cases n,
{ exact fin_zero_elim a },
{ simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] }
end
lemma lt_succ : a.cast_succ < a.succ :=
by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val }
@[simp] lemma range_cast_succ {n : ℕ} :
set.range (cast_succ : fin n → fin n.succ) = {i | (i : ℕ) < n} :=
range_cast_le _
@[simp] lemma coe_of_injective_cast_succ_symm {n : ℕ} (i : fin n.succ) (hi) :
((equiv.of_injective cast_succ (cast_succ_injective _)).symm ⟨i, hi⟩ : ℕ) = i :=
begin
rw ← coe_cast_succ,
exact congr_arg coe (equiv.apply_of_injective_symm _ _ _)
end
lemma succ_cast_succ {n : ℕ} (i : fin n) :
i.cast_succ.succ = i.succ.cast_succ :=
fin.ext (by simp)
/-- `add_nat m i` adds `m` to `i`, generalizes `fin.succ`. -/
def add_nat (m) : fin n ↪o fin (n + m) :=
order_embedding.of_strict_mono (λ i, ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩) $
λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_right h _
@[simp] lemma coe_add_nat (m : ℕ) (i : fin n) : (add_nat m i : ℕ) = i + m := rfl
/-- `nat_add n i` adds `n` to `i` "on the left". -/
def nat_add (n) {m} : fin m ↪o fin (n + m) :=
order_embedding.of_strict_mono (λ i, ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩) $
λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_left h _
@[simp] lemma coe_nat_add (n : ℕ) {m : ℕ} (i : fin m) : (nat_add n i : ℕ) = n + i := rfl
lemma nat_add_zero {n : ℕ} : fin.nat_add 0 = (fin.cast (zero_add n).symm).to_rel_embedding :=
by { ext, apply zero_add }
end succ
section rec
/-!
### recursion and induction principles
-/
/-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`.
This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple,
and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element
of `n`-tuple. -/
@[elab_as_eliminator] def succ_rec
{C : Π n, fin n → Sort*}
(H0 : Π n, C (succ n) 0)
(Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i
| 0 i := i.elim0
| (succ n) ⟨0, _⟩ := H0 _
| (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩)
/-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`.
This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple,
and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element
of `n`-tuple.
A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/
@[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n)
{C : Π n, fin n → Sort*}
(H0 : Π n, C (succ n) 0)
(Hs : Π n i, C n i → C (succ n) i.succ) : C n i :=
i.succ_rec H0 Hs
@[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) :
@fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n :=
rfl
@[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) :
@fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) :=
by cases i; refl
/--
Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `h0` handles the base case on `C 0`,
and `hs` defines the inductive step using `C i.cast_succ`.
-/
@[elab_as_eliminator] def induction
{C : fin (n + 1) → Sort*}
(h0 : C 0)
(hs : ∀ i : fin n, C i.cast_succ → C i.succ) :
Π (i : fin (n + 1)), C i :=
begin
rintro ⟨i, hi⟩,
induction i with i IH,
{ rwa [fin.mk_zero] },
{ refine hs ⟨i, lt_of_succ_lt_succ hi⟩ _,
exact IH (lt_of_succ_lt hi) }
end
/--
Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `h0` handles the base case on `C 0`,
and `hs` defines the inductive step using `C i.cast_succ`.
A version of `fin.induction` taking `i : fin (n + 1)` as the first argument.
-/
@[elab_as_eliminator] def induction_on (i : fin (n + 1))
{C : fin (n + 1) → Sort*}
(h0 : C 0)
(hs : ∀ i : fin n, C i.cast_succ → C i.succ) : C i :=
induction h0 hs i
/-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and
`i = j.succ`, `j : fin n`. -/
@[elab_as_eliminator] def cases
{C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) :
Π (i : fin (succ n)), C i :=
induction H0 (λ i _, Hs i)
@[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 :=
rfl
@[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) :
@fin.cases n C H0 Hs i.succ = Hs i :=
by cases i; refl
@[simp] theorem cases_succ' {n} {C : fin (succ n) → Sort*} {H0 Hs} {i : ℕ} (h : i + 1 < n + 1) :
@fin.cases n C H0 Hs ⟨i.succ, h⟩ = Hs ⟨i, lt_of_succ_lt_succ h⟩ :=
by cases i; refl
lemma forall_fin_succ {P : fin (n+1) → Prop} :
(∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) :=
⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩
lemma exists_fin_succ {P : fin (n+1) → Prop} :
(∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) :=
⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h,
λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩
/--
Define `C i` by reverse induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `hlast` handles the base case on `C (fin.last n)`,
and `hs` defines the inductive step using `C i.succ`, inducting downwards.
-/
@[elab_as_eliminator]
def reverse_induction {n : ℕ}
{C : fin (n + 1) → Sort*}
(hlast : C (fin.last n))
(hs : ∀ i : fin n, C i.succ → C i.cast_succ) :
Π (i : fin (n + 1)), C i
| i :=
if hi : i = fin.last n
then _root_.cast (by rw hi) hlast
else
let j : fin n := ⟨i, lt_of_le_of_ne (nat.le_of_lt_succ i.2) (λ h, hi (fin.ext h))⟩ in
have wf : n + 1 - j.succ < n + 1 - i, begin
cases i,
rw [nat.sub_lt_sub_left_iff];
simp [*, nat.succ_le_iff],
end,
have hi : i = fin.cast_succ j, from fin.ext rfl,
_root_.cast (by rw hi) (hs _ (reverse_induction j.succ))
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ i : fin (n+1), n + 1 - i)⟩],
dec_tac := `[assumption] }
@[simp] lemma reverse_induction_last {n : ℕ}
{C : fin (n + 1) → Sort*}
(h0 : C (fin.last n))
(hs : ∀ i : fin n, C i.succ → C i.cast_succ) :
(reverse_induction h0 hs (fin.last n) : C (fin.last n)) = h0 :=
by rw [reverse_induction]; simp
@[simp] lemma reverse_induction_cast_succ {n : ℕ}
{C : fin (n + 1) → Sort*}
(h0 : C (fin.last n))
(hs : ∀ i : fin n, C i.succ → C i.cast_succ) (i : fin n):
(reverse_induction h0 hs i.cast_succ : C i.cast_succ) =
hs i (reverse_induction h0 hs i.succ) :=
begin
rw [reverse_induction, dif_neg (ne_of_lt (fin.cast_succ_lt_last i))],
cases i,
refl
end
/-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = fin.last n` and
`i = j.cast_succ`, `j : fin n`. -/
@[elab_as_eliminator, elab_strategy]
def last_cases {n : ℕ} {C : fin (n + 1) → Sort*}
(hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin (n + 1)) : C i :=
reverse_induction hlast (λ i _, hcast i) i
@[simp] lemma last_cases_last {n : ℕ} {C : fin (n + 1) → Sort*}
(hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) :
(fin.last_cases hlast hcast (fin.last n): C (fin.last n)) = hlast :=
reverse_induction_last _ _
@[simp] lemma last_cases_cast_succ {n : ℕ} {C : fin (n + 1) → Sort*}
(hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin n) :
(fin.last_cases hlast hcast (fin.cast_succ i): C (fin.cast_succ i)) = hcast i :=
reverse_induction_cast_succ _ _ _
/-- Define `f : Π i : fin (m + n), C i` by separately handling the cases `i = cast_add n i`,
`j : fin m` and `i = cast_add_right m j`, `j : fin n`. -/
@[elab_as_eliminator, elab_strategy]
def add_cases {m n : ℕ} {C : fin (m + n) → Sort*}
(hleft : Π i, C (cast_add n i))
(hright : Π i, C (cast_add_right m i)) (i : fin (m + n)) : C i :=
if hi : (i : ℕ) < m
then have hi' : i = fin.cast_add _ ⟨i, hi⟩, from fin.ext rfl,
_root_.cast (congr_arg C hi'.symm) (hleft _)
else have hi' : i = fin.cast_add_right m
⟨i - m, show (i : ℕ) - m < n,
from (nat.sub_lt_left_iff_lt_add (le_of_not_gt hi)).2 i.2⟩,
from fin.ext $ by simp [nat.add_sub_cancel' (le_of_not_gt hi)],
_root_.cast (congr_arg C hi'.symm) (hright _)
@[simp] lemma add_cases_left {m n : ℕ} {C : fin (m + n) → Sort*}
(hleft : Π i, C (fin.cast_add n i))
(hright : Π i, C (fin.cast_add_right m i))
(i : fin m) :
(fin.add_cases hleft hright (fin.cast_add n i) : C (fin.cast_add n i)) =
hleft i :=
begin
cases i,
simp only [add_cases, *, dif_pos, coe_mk, cast_eq, cast_add_mk],
refl
end
@[simp] lemma add_cases_right {m n : ℕ} {C : fin (m + n) → Sort*}
(hleft : Π i, C (fin.cast_add n i))
(hright : Π i, C (fin.cast_add_right m i))
(i : fin n) :
(fin.add_cases hleft hright (fin.cast_add_right m i) : C (fin.cast_add_right m i)) =
hright i :=
begin
have : ¬ (cast_add_right m i : ℕ) < m, from not_lt_of_ge (le_cast_add_right _ _),
cases i with i hi,
simp only [add_cases, this, dif_neg, not_false_iff, cast_eq, not_false_iff],
rw [cast_eq_iff_heq],
congr,
simp
end
end rec
section pred
/-!
### pred
-/
@[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 :=
by { cases j, refl }
@[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i
| ⟨0, h⟩ hi := by contradiction
| ⟨n + 1, h⟩ hi := rfl
@[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i :=
by { cases i, refl }
@[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) :
fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ :=
by simp only [ext_iff, coe_pred, coe_mk, nat.add_sub_cancel]
-- This is not a simp lemma by default, because `pred_mk_succ` is nicer when it applies.
lemma pred_mk {n : ℕ} (i : ℕ) (h : i < n + 1) (w) :
fin.pred ⟨i, h⟩ w =
⟨i - 1, by rwa nat.sub_lt_right_iff_lt_add (nat.pos_of_ne_zero (fin.vne_of_ne w))⟩ :=
rfl
@[simp] lemma pred_le_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} :
a.pred ha ≤ b.pred hb ↔ a ≤ b :=
by rw [←succ_le_succ_iff, succ_pred, succ_pred]
@[simp] lemma pred_lt_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} :
a.pred ha < b.pred hb ↔ a < b :=
by rw [←succ_lt_succ_iff, succ_pred, succ_pred]
@[simp] lemma pred_inj :
∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b
| ⟨0, _⟩ b ha hb := by contradiction
| ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction
| ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq]
@[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl
lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) :
pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h :=
begin
rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, nat.add_sub_cancel],
exact add_lt_add_right h 1,
end
/-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/
def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n :=
⟨(i : ℕ) - m, by { rw [nat.sub_lt_right_iff_lt_add h], exact i.is_lt }⟩
@[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m :=
rfl
@[simp] lemma pred_cast_succ_succ (i : fin n) :
pred (cast_succ i.succ) (ne_of_gt (cast_succ_pos i.succ_pos)) = i.cast_succ :=
by simp [eq_iff_veq]
end pred
section add_group
open nat int
/-- Negation on `fin n` -/
instance (n : ℕ) : has_neg (fin n) :=
⟨λ a, ⟨(n - a) % n, nat.mod_lt _ (lt_of_le_of_lt (nat.zero_le _) a.2)⟩⟩
/-- Abelian group structure on `fin (n+1)`. -/
instance (n : ℕ) : add_comm_group (fin (n+1)) :=
{ add_left_neg := λ ⟨a, ha⟩, fin.ext $ trans (nat.mod_add_mod _ _ _) $
by { rw [fin.coe_mk, fin.coe_zero, nat.sub_add_cancel, nat.mod_self], exact le_of_lt ha },
sub_eq_add_neg := λ ⟨a, ha⟩ ⟨b, hb⟩, fin.ext $
show (a + (n + 1 - b)) % (n + 1) = (a + (n + 1 - b) % (n + 1)) % (n + 1), by simp,
sub := fin.sub,
..fin.add_comm_monoid n,
..fin.has_neg n.succ }
protected lemma coe_neg (a : fin n) : ((-a : fin n) : ℕ) = (n - a) % n := rfl
protected lemma coe_sub (a b : fin n) : ((a - b : fin n) : ℕ) = (a + (n - b)) % n :=
by cases a; cases b; refl
end add_group
section succ_above
lemma succ_above_aux (p : fin (n + 1)) :
strict_mono (λ i : fin n, if i.cast_succ < p then i.cast_succ else i.succ) :=
(cast_succ : fin n ↪o _).strict_mono.ite (succ_embedding n).strict_mono
(λ i j hij hj, lt_trans ((cast_succ : fin n ↪o _).lt_iff_lt.2 hij) hj)
(λ i, (cast_succ_lt_succ i).le)
/-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/
def succ_above (p : fin (n + 1)) : fin n ↪o fin (n + 1) :=
order_embedding.of_strict_mono _ p.succ_above_aux
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/
lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) :
p.succ_above i = i.cast_succ :=
by { rw [succ_above], exact if_pos h }
@[simp] lemma succ_above_ne_zero_zero {a : fin (n + 2)} (ha : a ≠ 0) : a.succ_above 0 = 0 :=
begin
rw fin.succ_above_below,
{ refl },
{ exact bot_lt_iff_ne_bot.mpr ha }
end
lemma succ_above_eq_zero_iff {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) :
a.succ_above b = 0 ↔ b = 0 :=
by simp only [←succ_above_ne_zero_zero ha, order_embedding.eq_iff_eq]
lemma succ_above_ne_zero {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0) :
a.succ_above b ≠ 0 :=
mt (succ_above_eq_zero_iff ha).mp hb
/-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/
@[simp] lemma succ_above_zero : ⇑(succ_above (0 : fin (n + 1))) = fin.succ := rfl
/-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/
@[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ :=
by { ext, simp only [succ_above_below, cast_succ_lt_last] }
lemma succ_above_last_apply (i : fin n) : succ_above (fin.last n) i = i.cast_succ :=
by rw succ_above_last
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
embeds `i` by `succ` when the resulting `p < i.succ`. -/
lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) :
p.succ_above i = i.succ :=
by simp [succ_above, h.not_lt]
/-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/
lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ :=
lt_or_ge (cast_succ i) p
/-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/
lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ :=
or.cases_on (succ_above_lt_ge p i)
(λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i)))
/-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater
results in a value that is less than `p`. -/
@[simp] lemma succ_above_lt_iff (p : fin (n + 1)) (i : fin n) :
p.succ_above i < p ↔ i.cast_succ < p :=
begin
refine iff.intro _ _,
{ intro h,
cases succ_above_lt_ge p i with H H,
{ exact H },
{ rw succ_above_above _ _ H at h,
exact lt_trans (cast_succ_lt_succ i) h } },
{ intro h,
rw succ_above_below _ _ h,
exact h }
end
/-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser
results in a value that is greater than `p`. -/
lemma lt_succ_above_iff (p : fin (n + 1)) (i : fin n) : p < p.succ_above i ↔ p ≤ i.cast_succ :=
begin
refine iff.intro _ _,
{ intro h,
cases succ_above_lt_ge p i with H H,
{ rw succ_above_below _ _ H at h,
exact le_of_lt h },
{ exact H } },
{ intro h,
rw succ_above_above _ _ h,
exact lt_of_le_of_lt h (cast_succ_lt_succ i) },
end
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
never results in `p` itself -/
theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p :=
begin
intro eq,
by_cases H : i.cast_succ < p,
{ simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H },
{ simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i }
end
/-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/
lemma succ_above_pos (p : fin (n + 2)) (i : fin (n + 1)) (h : 0 < i) : 0 < p.succ_above i :=
begin
by_cases H : i.cast_succ < p,
{ simpa [succ_above_below _ _ H] using cast_succ_pos h },
{ simpa [succ_above_above _ _ (le_of_not_lt H)] using succ_pos _ },
end
/-- The range of `p.succ_above` is everything except `p`. -/
lemma range_succ_above (p : fin (n + 1)) : set.range (p.succ_above) = { i | i ≠ p } :=
begin
ext,
simp only [set.mem_range, ne.def, set.mem_set_of_eq],
split,
{ rintro ⟨y, rfl⟩,
exact succ_above_ne _ _ },
{ intro h,
cases lt_or_gt_of_ne h with H H,
{ refine ⟨x.cast_lt _, _⟩,
{ exact lt_of_lt_of_le H p.le_last },
{ rw succ_above_below,
{ simp },
{ exact H } } },
{ refine ⟨x.pred _, _⟩,
{ exact (ne_of_lt (lt_of_le_of_lt p.zero_le H)).symm },
{ rw succ_above_above,
{ simp },
{ simpa [le_iff_coe_le_coe] using nat.le_pred_of_lt H } } } }
end
/-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/
lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) :=
(succ_above x).injective
/-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/
lemma succ_above_right_inj {x : fin (n + 1)} :
x.succ_above a = x.succ_above b ↔ a = b :=
succ_above_right_injective.eq_iff
/-- `succ_above` is injective at the pivot -/
lemma succ_above_left_injective : injective (@succ_above n) :=
λ _ _ h, by simpa [range_succ_above] using congr_arg (λ f : fin n ↪o fin (n + 1), (set.range f)ᶜ) h
/-- `succ_above` is injective at the pivot -/
lemma succ_above_left_inj {x y : fin (n + 1)} :
x.succ_above = y.succ_above ↔ x = y :=
succ_above_left_injective.eq_iff
@[simp] lemma zero_succ_above {n : ℕ} (i : fin n) :
(0 : fin (n + 1)).succ_above i = i.succ :=
rfl
@[simp] lemma succ_succ_above_zero {n : ℕ} (i : fin (n + 1)) :
(i.succ).succ_above 0 = 0 :=
succ_above_below _ _ (succ_pos _)
@[simp] lemma succ_succ_above_succ {n : ℕ} (i : fin (n + 1)) (j : fin n) :
(i.succ).succ_above j.succ = (i.succ_above j).succ :=
(lt_or_ge j.cast_succ i).elim
(λ h, have h' : j.succ.cast_succ < i.succ, by simpa [lt_iff_coe_lt_coe] using h,
by { ext, simp [succ_above_below _ _ h, succ_above_below _ _ h'] })
(λ h, have h' : i.succ ≤ j.succ.cast_succ, by simpa [le_iff_coe_le_coe] using h,
by { ext, simp [succ_above_above _ _ h, succ_above_above _ _ h'] })
@[simp] lemma one_succ_above_zero {n : ℕ} :
(1 : fin (n + 2)).succ_above 0 = 0 :=
succ_succ_above_zero 0
/-- By moving `succ` to the outside of this expression, we create opportunities for further
simplification using `succ_above_zero` or `succ_succ_above_zero`. -/
@[simp] lemma succ_succ_above_one {n : ℕ} (i : fin (n + 2)) :
(i.succ).succ_above 1 = (i.succ_above 0).succ :=
succ_succ_above_succ i 0
@[simp] lemma one_succ_above_succ {n : ℕ} (j : fin n) :
(1 : fin (n + 2)).succ_above j.succ = j.succ.succ :=
succ_succ_above_succ 0 j
@[simp] lemma one_succ_above_one {n : ℕ} :
(1 : fin (n + 3)).succ_above 1 = 2 :=
succ_succ_above_succ 0 0
end succ_above
section pred_above
/-- `pred_above p i` embeds `i : fin (n+1)` into `fin n` by subtracting one if `p < i`. -/
def pred_above (p : fin n) (i : fin (n+1)) : fin n :=
if h : p.cast_succ < i then
i.pred (ne_of_lt (lt_of_le_of_lt (zero_le p.cast_succ) h)).symm
else
i.cast_lt (lt_of_le_of_lt (le_of_not_lt h) p.2)
lemma pred_above_right_monotone (p : fin n) : monotone p.pred_above :=
λ a b H,
begin
dsimp [pred_above],
split_ifs with ha hb hb,
all_goals { simp only [le_iff_coe_le_coe, coe_pred], },
{ exact pred_le_pred H, },
{ calc _ ≤ _ : nat.pred_le _
... ≤ _ : H, },
{ simp at ha, exact le_pred_of_lt (lt_of_le_of_lt ha hb), },
{ exact H, },
end
lemma pred_above_left_monotone (i : fin (n + 1)) : monotone (λ p, pred_above p i) :=
λ a b H,
begin
dsimp [pred_above],
split_ifs with ha hb hb,
all_goals { simp only [le_iff_coe_le_coe, coe_pred] },
{ exact pred_le _, },
{ have : b < a := cast_succ_lt_cast_succ_iff.mpr (hb.trans_le (le_of_not_gt ha)),
exact absurd H this.not_le }
end
/-- `cast_pred` embeds `i : fin (n + 2)` into `fin (n + 1)`
by lowering just `last (n + 1)` to `last n`. -/
def cast_pred (i : fin (n + 2)) : fin (n + 1) :=
pred_above (last n) i
@[simp] lemma cast_pred_zero : cast_pred (0 : fin (n + 2)) = 0 := rfl
@[simp] lemma cast_pred_one : cast_pred (1 : fin (n + 2)) = 1 :=
by { cases n, apply subsingleton.elim, refl }
@[simp] theorem pred_above_zero {i : fin (n + 2)} (hi : i ≠ 0) :
pred_above 0 i = i.pred hi :=
begin
dsimp [pred_above],
rw dif_pos,
exact (pos_iff_ne_zero _).mpr hi,
end
@[simp] lemma cast_pred_last : cast_pred (last (n + 1)) = last n :=
by simp [eq_iff_veq, cast_pred, pred_above, cast_succ_lt_last]
@[simp] lemma cast_pred_mk (n i : ℕ) (h : i < n + 1) :
cast_pred ⟨i, lt_succ_of_lt h⟩ = ⟨i, h⟩ :=
begin
have : ¬cast_succ (last n) < ⟨i, lt_succ_of_lt h⟩,
{ simpa [lt_iff_coe_lt_coe] using le_of_lt_succ h },
simp [cast_pred, pred_above, this]
end
lemma pred_above_below (p : fin (n + 1)) (i : fin (n + 2)) (h : i ≤ p.cast_succ) :
p.pred_above i = i.cast_pred :=
begin
have : i ≤ (last n).cast_succ := h.trans p.le_last,
simp [pred_above, cast_pred, h.not_lt, this.not_lt]
end
@[simp] lemma pred_above_last : pred_above (fin.last n) = cast_pred := rfl
lemma pred_above_last_apply (i : fin n) : pred_above (fin.last n) i = i.cast_pred :=
by rw pred_above_last
lemma pred_above_above (p : fin n) (i : fin (n + 1)) (h : p.cast_succ < i) :
p.pred_above i = i.pred (p.cast_succ.zero_le.trans_lt h).ne.symm :=
by simp [pred_above, h]
lemma cast_pred_monotone : monotone (@cast_pred n) :=
pred_above_right_monotone (last _)
/-- Sending `fin (n+1)` to `fin n` by subtracting one from anything above `p`
then back to `fin (n+1)` with a gap around `p` is the identity away from `p`. -/
@[simp] lemma succ_above_pred_above {p : fin n} {i : fin (n + 1)} (h : i ≠ p.cast_succ) :
p.cast_succ.succ_above (p.pred_above i) = i :=
begin
dsimp [pred_above, succ_above],
rcases p with ⟨p, _⟩,
rcases i with ⟨i, _⟩,
cases lt_or_le i p with H H,
{ rw dif_neg, rw if_pos, refl, exact H, simp, apply le_of_lt H, },
{ rw dif_pos, rw if_neg,
swap 3, -- For some reason `simp` doesn't fire fully unless we discharge the third goal.
{ exact lt_of_le_of_ne H (ne.symm h), },
{ simp, },
{ simp only [subtype.mk_eq_mk, ne.def, fin.cast_succ_mk] at h,
simp only [pred, subtype.mk_lt_mk, not_lt],
exact nat.le_pred_of_lt (nat.lt_of_le_and_ne H (ne.symm h)), }, },
end
/-- Sending `fin n` into `fin (n + 1)` with a gap at `p`
then back to `fin n` by subtracting one from anything above `p` is the identity. -/
@[simp] lemma pred_above_succ_above (p : fin n) (i : fin n) :
p.pred_above (p.cast_succ.succ_above i) = i :=
begin
dsimp [pred_above, succ_above],
rcases p with ⟨p, _⟩,
rcases i with ⟨i, _⟩,
split_ifs,
{ rw dif_neg,
{ refl },
{ simp_rw [if_pos h],
simp only [subtype.mk_lt_mk, not_lt],
exact le_of_lt h, }, },
{ rw dif_pos,
{ refl, },
{ simp_rw [if_neg h],
exact lt_succ_iff.mpr (not_lt.mp h), }, },
end
lemma cast_succ_pred_eq_pred_cast_succ {a : fin (n + 1)} (ha : a ≠ 0)
(ha' := a.cast_succ_ne_zero_iff.mpr ha) : (a.pred ha).cast_succ = a.cast_succ.pred ha' :=
by { cases a, refl }
/-- `pred` commutes with `succ_above`. -/
lemma pred_succ_above_pred {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0)
(hk := succ_above_ne_zero ha hb) :
(a.pred ha).succ_above (b.pred hb) = (a.succ_above b).pred hk :=
begin
obtain hbelow | habove := lt_or_le b.cast_succ a, -- `rwa` uses them
{ rw fin.succ_above_below,
{ rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_inj, fin.succ_above_below] },
{ rwa [cast_succ_pred_eq_pred_cast_succ , pred_lt_pred_iff] } },
{ rw fin.succ_above_above,
have : (b.pred hb).succ = b.succ.pred (fin.succ_ne_zero _), by rw [succ_pred, pred_succ],
{ rwa [this, fin.pred_inj, fin.succ_above_above] },
{ rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_le_pred_iff] } }
end
@[simp] theorem cast_pred_cast_succ (i : fin (n + 1)) :
cast_pred i.cast_succ = i :=
by simp [cast_pred, pred_above, le_last]
lemma cast_succ_cast_pred {i : fin (n + 2)} (h : i < last _) : cast_succ i.cast_pred = i :=
begin
rw [cast_pred, pred_above, dif_neg],
{ simp [fin.eq_iff_veq] },
{ exact h.not_le }
end
lemma coe_cast_pred_le_self (i : fin (n + 2)) : (i.cast_pred : ℕ) ≤ i :=
begin
rcases i.le_last.eq_or_lt with rfl|h,
{ simp },
{ rw [cast_pred, pred_above, dif_neg],
{ simp },
{ simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe, lt_succ_iff] using h } }
end
lemma coe_cast_pred_lt_iff {i : fin (n + 2)} : (i.cast_pred : ℕ) < i ↔ i = fin.last _ :=
begin
rcases i.le_last.eq_or_lt with rfl|H,
{ simp },
{ simp only [ne_of_lt H],
rw ←cast_succ_cast_pred H,
simp }
end
lemma lt_last_iff_coe_cast_pred {i : fin (n + 2)} : i < fin.last _ ↔ (i.cast_pred : ℕ) = i :=
begin
rcases i.le_last.eq_or_lt with rfl|H,
{ simp },
{ simp only [H],
rw ←cast_succ_cast_pred H,
simp }
end
lemma forall_iff_succ_above {p : fin (n + 1) → Prop} (i : fin (n + 1)) :
(∀ j, p j) ↔ p i ∧ ∀ j, p (i.succ_above j) :=
⟨λ h, ⟨h _, λ j, h _⟩,
λ h j, if hj : j = i then (hj.symm ▸ h.1) else
begin
cases n,
{ convert h.1 },
{ cases lt_or_gt_of_ne hj with lt gt,
{ rcases j.zero_le.eq_or_lt with rfl|H,
{ convert h.2 0, rw succ_above_below; simp [lt] },
{ have ltl : j < last _ := lt.trans_le i.le_last,
convert h.2 j.cast_pred,
simp [succ_above_below, cast_succ_cast_pred ltl, lt] } },
{ convert h.2 (j.pred (i.zero_le.trans_lt gt).ne.symm),
rw succ_above_above;
simp [le_cast_succ_iff, gt.lt] } }
end⟩
end pred_above
/-- `min n m` as an element of `fin (m + 1)` -/
def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m
@[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m :=
nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _
section tuple
/-!
### Tuples
We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type
`α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant
operations, first about adding or removing elements at the beginning of a tuple.
-/
/-- There is exactly one tuple of size zero. -/
example (α : fin 0 → Sort u) : unique (Π i : fin 0, α i) :=
by apply_instance
@[simp] lemma tuple0_le {α : Π i : fin 0, Type*} [Π i, preorder (α i)] (f g : Π i, α i) : f ≤ g :=
fin_zero_elim
variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ))
(i : fin n) (y : α i.succ) (z : α 0)
/-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/
def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ
lemma tail_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} :
tail (λ k : fin (n+1), q k) = (λ k : fin n, q k.succ) := rfl
/-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/
def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i :=
λ j, fin.cases x p j
@[simp] lemma tail_cons : tail (cons x p) = p :=
by simp [tail, cons]
@[simp] lemma cons_succ : cons x p i.succ = p i :=
by simp [cons]
@[simp] lemma cons_zero : cons x p 0 = x :=
by simp [cons]
/-- Updating a tuple and adding an element at the beginning commute. -/
@[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp [ne.symm (succ_ne_zero i)] },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ],
by_cases h' : j' = i,
{ rw h', simp },
{ have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj],
rw [update_noteq h', update_noteq this, cons_succ] } }
end
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
lemma update_cons_zero : update (cons x p) 0 z = cons z p :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp },
{ simp only [h, update_noteq, ne.def, not_false_iff],
let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ, cons_succ] }
end
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp] lemma cons_self_tail : cons (q 0) (tail q) = q :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, tail, cons_succ] }
end
/-- Updating the first element of a tuple does not change the tail. -/
@[simp] lemma tail_update_zero : tail (update q 0 z) = tail q :=
by { ext j, simp [tail, fin.succ_ne_zero] }
/-- Updating a nonzero element and taking the tail commute. -/
@[simp] lemma tail_update_succ :
tail (update q i.succ y) = update (tail q) i y :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp [tail] },
{ simp [tail, (fin.succ_injective n).ne h, h] }
end
lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) :
g ∘ (cons y q) = cons (g y) (g ∘ q) :=
begin
ext j,
by_cases h : j = 0,
{ rw h, refl },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ, comp_app, cons_succ] }
end
lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) :
g ∘ (tail q) = tail (g ∘ q) :=
by { ext j, simp [tail] }
lemma le_cons [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} :
q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p :=
forall_fin_succ.trans $ and_congr iff.rfl $ forall_congr $ λ j, by simp [tail]
lemma cons_le [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} :
cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q :=
@le_cons _ (λ i, order_dual (α i)) _ x q p
@[simp]
lemma range_cons {α : Type*} {n : ℕ} (x : α) (b : fin n → α) :
set.range (fin.cons x b : fin n.succ → α) = insert x (set.range b) :=
begin
ext y,
simp only [set.mem_range, set.mem_insert_iff],
split,
{ rintros ⟨i, rfl⟩,
refine cases (or.inl (cons_zero _ _)) (λ i, or.inr ⟨i, _⟩) i,
rw cons_succ },
{ rintros (rfl | ⟨i, hi⟩),
{ exact ⟨0, fin.cons_zero _ _⟩ },
{ refine ⟨i.succ, _⟩,
rw [cons_succ, hi] } }
end
/-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce
one of length `o = m + n`. `ho` provides control of definitional equality
for the vector length. -/
def append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α :=
λ i, if h : (i : ℕ) < m
then u ⟨i, h⟩
else v ⟨(i : ℕ) - m, (nat.sub_lt_left_iff_lt_add (le_of_not_lt h)).2 (ho ▸ i.property)⟩
@[simp] lemma fin_append_apply_zero {α : Type*} {o : ℕ} (ho : (o + 1) = (m + 1) + n)
(u : fin (m + 1) → α) (v : fin n → α) :
fin.append ho u v 0 = u 0 := rfl
end tuple
section tuple_right
/-! In the previous section, we have discussed inserting or removing elements on the left of a
tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed
inductively from `fin n` starting from the left, not from the right. This implies that Lean needs
more help to realize that elements belong to the right types, i.e., we need to insert casts at
several places. -/
variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ)
(i : fin n) (y : α i.cast_succ) (z : α (last n))
/-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/
def init (q : Πi, α i) (i : fin n) : α i.cast_succ :=
q i.cast_succ
lemma init_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} :
init (λ k : fin (n+1), q k) = (λ k : fin n, q k.cast_succ) := rfl
/-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from
`cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/
def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i :=
if h : i.val < n
then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h))
else _root_.cast (by rw eq_last_of_not_lt h) x
@[simp] lemma init_snoc : init (snoc p x) = p :=
begin
ext i,
have h' := fin.cast_lt_cast_succ i i.is_lt,
simp [init, snoc, i.is_lt, h'],
convert cast_eq rfl (p i)
end
@[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i :=
begin
have : i.cast_succ.val < n := i.is_lt,
have h' := fin.cast_lt_cast_succ i i.is_lt,
simp [snoc, this, h'],
convert cast_eq rfl (p i)
end
@[simp] lemma snoc_last : snoc p x (last n) = x :=
by { simp [snoc] }
/-- Updating a tuple and adding an element at the end commute. -/
@[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y :=
begin
ext j,
by_cases h : j.val < n,
{ simp only [snoc, h, dif_pos],
by_cases h' : j = cast_succ i,
{ have C1 : α i.cast_succ = α j, by rw h',
have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y,
{ have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp,
convert this,
{ exact h'.symm },
{ exact heq_of_cast_eq (congr_arg α (eq.symm h')) rfl } },
have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)),
by rw [cast_succ_cast_lt, h'],
have E2 : update p i y (cast_lt j h) = _root_.cast C2 y,
{ have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y,
by simp,
convert this,
{ simp [h, h'] },
{ exact heq_of_cast_eq C2 rfl } },
rw [E1, E2],
exact eq_rec_compose _ _ _ },
{ have : ¬(cast_lt j h = i),
by { assume E, apply h', rw [← E, cast_succ_cast_lt] },
simp [h', this, snoc, h] } },
{ rw eq_last_of_not_lt h,
simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] }
end
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, update_noteq, this, snoc] },
{ rw eq_last_of_not_lt h,
simp }
end
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt],
have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _,
rw ← cast_eq rfl (q j),
congr' 1; rw A },
{ rw eq_last_of_not_lt h,
simp }
end
/-- Updating the last element of a tuple does not change the beginning. -/
@[simp] lemma init_update_last : init (update q (last n) z) = init q :=
by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] }
/-- Updating an element and taking the beginning commute. -/
@[simp] lemma init_update_cast_succ :
init (update q i.cast_succ y) = update (init q) i y :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp [init] },
{ simp [init, h] }
end
/-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) :
tail (init q) = init (tail q) :=
by { ext i, simp [tail, init, cast_succ_fin_succ] }
/-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) :
@cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b :=
begin
ext i,
by_cases h : i = 0,
{ rw h, refl },
set j := pred i h with ji,
have : i = j.succ, by rw [ji, succ_pred],
rw [this, cons_succ],
by_cases h' : j.val < n,
{ set k := cast_lt j h' with jk,
have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt],
rw [this, ← cast_succ_fin_succ],
simp },
rw [eq_last_of_not_lt h', succ_last],
simp
end
lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) :
g ∘ (snoc q y) = snoc (g ∘ q) (g y) :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, this, snoc, cast_succ_cast_lt] },
{ rw eq_last_of_not_lt h,
simp }
end
lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) :
g ∘ (init q) = init (g ∘ q) :=
by { ext j, simp [init] }
end tuple_right
section insert_nth
variables {α : fin (n+1) → Type u} {β : Type v}
/-- Insert an element into a tuple at a given position, auxiliary definition.
For the general definition, see `insert_nth`. -/
def insert_nth' {α : fin (n + 2) → Type u} (i : fin (n + 2)) (x : α i)
(p : Π j : fin (n + 1), α (i.succ_above j)) (j : fin (n + 2)) : α j :=
if h : i = j
then _root_.cast (congr_arg α h) x
else if h' : j < i then _root_.cast (congr_arg α $ begin
obtain ⟨k, hk⟩ : ∃ (k : fin (n + 1)), k.cast_succ = j,
{ refine ⟨⟨(j : ℕ), _⟩, _⟩,
{ exact lt_of_lt_of_le h' i.is_le, },
{ simp } },
subst hk,
simp [succ_above_below, h'],
end)
(p j.cast_pred) else _root_.cast (congr_arg α $ begin
have lt : i < j := lt_of_le_of_ne (le_of_not_lt h') h,
have : j ≠ 0 := (ne_of_gt (lt_of_le_of_lt i.zero_le lt)),
rw [←succ_pred j this, ←le_cast_succ_iff] at lt,
simp [pred_above_zero this, succ_above_above _ _ lt]
end) (p (fin.pred_above 0 j))
/-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`,
for `i = fin.last n` see `fin.snoc`. -/
def insert_nth : Π {n : ℕ} {α : fin (n + 1) → Type u} (i : fin (n + 1)) (x : α i)
(p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)), α j
| 0 _ _ x _ _ := _root_.cast (by congr) x
| (n + 1) _ i x p j := insert_nth' i x p j
@[simp] lemma insert_nth_apply_same (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) :
insert_nth i x p i = x :=
by { cases n; simp [insert_nth, insert_nth'] }
@[simp] lemma insert_nth_apply_succ_above (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j))
(j : fin n) :
insert_nth i x p (i.succ_above j) = p j :=
begin
cases n,
{ exact j.elim0 },
simp only [insert_nth, insert_nth', dif_neg (succ_above_ne _ _).symm],
cases succ_above_lt_ge i j with h h,
{ rw dif_pos,
refine eq_of_heq ((cast_heq _ _).trans _),
{ simp [h] },
{ congr,
simp [succ_above_below, h] } },
{ rw dif_neg,
refine eq_of_heq ((cast_heq _ _).trans _),
{ simp [h] },
{ congr,
simp [succ_above_above, h, succ_ne_zero] } }
end
@[simp] lemma insert_nth_comp_succ_above (i : fin (n + 1)) (x : β) (p : fin n → β) :
insert_nth i x p ∘ i.succ_above = p :=
funext $ insert_nth_apply_succ_above i x p
lemma insert_nth_eq_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
i.insert_nth x p = q ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) :=
by simp [funext_iff, forall_iff_succ_above i, eq_comm]
lemma eq_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
q = i.insert_nth x p ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) :=
eq_comm.trans insert_nth_eq_iff
lemma insert_nth_zero (x : α 0) (p : Π j : fin n, α (succ_above 0 j)) :
insert_nth 0 x p = cons x (λ j, _root_.cast (congr_arg α (congr_fun succ_above_zero j)) (p j)) :=
begin
refine insert_nth_eq_iff.2 ⟨by simp, _⟩,
ext j,
convert (cons_succ _ _ _).symm
end
@[simp] lemma insert_nth_zero' (x : β) (p : fin n → β) :
@insert_nth _ (λ _, β) 0 x p = cons x p :=
by simp [insert_nth_zero]
lemma insert_nth_last (x : α (last n)) (p : Π j : fin n, α ((last n).succ_above j)) :
insert_nth (last n) x p =
snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x :=
begin
refine insert_nth_eq_iff.2 ⟨by simp, _⟩,
ext j,
apply eq_of_heq,
transitivity snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x j.cast_succ,
{ rw [snoc_cast_succ], exact (cast_heq _ _).symm },
{ apply congr_arg_heq,
rw [succ_above_last] }
end
@[simp] lemma insert_nth_last' (x : β) (p : fin n → β) :
@insert_nth _ (λ _, β) (last n) x p = snoc p x :=
by simp [insert_nth_last]
variables [Π i, preorder (α i)]
lemma insert_nth_le_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
i.insert_nth x p ≤ q ↔ x ≤ q i ∧ p ≤ (λ j, q (i.succ_above j)) :=
by simp [pi.le_def, forall_iff_succ_above i]
lemma le_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
q ≤ i.insert_nth x p ↔ q i ≤ x ∧ (λ j, q (i.succ_above j)) ≤ p :=
by simp [pi.le_def, forall_iff_succ_above i]
open set
lemma insert_nth_mem_Icc {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)}
{q₁ q₂ : Π j, α j} :
i.insert_nth x p ∈ Icc q₁ q₂ ↔
x ∈ Icc (q₁ i) (q₂ i) ∧ p ∈ Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) :=
by simp only [mem_Icc, insert_nth_le_iff, le_insert_nth_iff, and.assoc, and.left_comm]
lemma preimage_insert_nth_Icc_of_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j}
(hx : x ∈ Icc (q₁ i) (q₂ i)) :
i.insert_nth x ⁻¹' (Icc q₁ q₂) = Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) :=
set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, true_and]
lemma preimage_insert_nth_Icc_of_not_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j}
(hx : x ∉ Icc (q₁ i) (q₂ i)) :
i.insert_nth x ⁻¹' (Icc q₁ q₂) = ∅ :=
set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, false_and, mem_empty_eq]
end insert_nth
section find
/-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied. -/
def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n)
| 0 p _ := none
| (n+1) p _ := by resetI; exact option.cases_on
(@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _)
(if h : p (fin.last n) then some (fin.last n) else none)
(λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2)))
/-- If `find p = some i`, then `p i` holds -/
lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n}
(hi : i ∈ by exactI fin.find p), p i
| 0 p I i hi := option.no_confusion hi
| (n+1) p I i hi := begin
dsimp [find] at hi,
resetI,
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j,
{ rw h at hi,
dsimp at hi,
split_ifs at hi with hl hl,
{ exact option.some_inj.1 hi ▸ hl },
{ exact option.no_confusion hi } },
{ rw h at hi,
rw [← option.some_inj.1 hi],
exact find_spec _ h }
end
/-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/
lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p],
by exactI (find p).is_some ↔ ∃ i, p i
| 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i)
| (n+1) p _ := ⟨λ h, begin
rw [option.is_some_iff_exists] at h,
cases h with i hi,
exactI ⟨i, find_spec _ hi⟩
end, λ ⟨⟨i, hin⟩, hi⟩,
begin
resetI,
dsimp [find],
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j,
{ split_ifs with hl hl,
{ exact option.is_some_some },
{ have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2
⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin)
(λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩,
rw h at this,
exact this } },
{ simp }
end⟩
/-- `find p` returns `none` if and only if `p i` never holds. -/
lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] :
find p = none ↔ ∀ i, ¬ p i :=
by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp
/-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among
the indices where `p` holds. -/
lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n}
(hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j
| 0 p _ i hi j hj hpj := option.no_confusion hi
| (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin
resetI,
dsimp [find] at hi,
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k,
{ rw [h] at hi,
split_ifs at hi with hl hl,
{ have := option.some_inj.1 hi,
subst this,
rw [find_eq_none_iff] at h,
exact h ⟨j, hj⟩ hpj },
{ exact option.no_confusion hi } },
{ rw h at hi,
dsimp at hi,
have := option.some_inj.1 hi,
subst this,
exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj }
end
lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n}
(h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j :=
le_of_not_gt (λ hij, find_min h hij hj)
lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p]
(h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) :
(⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p :=
let ⟨i, hin, hi⟩ := h in
begin
cases hf : find p with f,
{ rw [find_eq_none_iff] at hf,
exact (hf ⟨i, hin⟩ hi).elim },
{ refine option.some_inj.2 (le_antisymm _ _),
{ exact find_min' hf (nat.find_spec h).snd },
{ exact nat.find_min' _ ⟨f.2, by convert find_spec p hf;
exact fin.eta _ _⟩ } }
end
lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} :
i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j :=
⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩,
begin
rintros ⟨hpi, hj⟩,
cases hfp : fin.find p,
{ rw [find_eq_none_iff] at hfp,
exact (hfp _ hpi).elim },
{ exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) }
end⟩
lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} :
fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j :=
mem_find_iff
lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p]
(h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p :=
mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩
end find
@[simp]
lemma coe_of_nat_eq_mod (m n : ℕ) :
((n : fin (succ m)) : ℕ) = n % succ m :=
by rw [← of_nat_eq_coe]; refl
@[simp] lemma coe_of_nat_eq_mod' (m n : ℕ) [I : fact (0 < m)] :
(@fin.of_nat' _ I n : ℕ) = n % m :=
rfl
section mul
/-!
### mul
-/
lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp] protected lemma mul_one (k : fin (n + 1)) : k * 1 = k :=
by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] }
@[simp] protected lemma one_mul (k : fin (n + 1)) : (1 : fin (n + 1)) * k = k :=
by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] }
@[simp] protected lemma mul_zero (k : fin (n + 1)) : k * 0 = 0 :=
by simp [eq_iff_veq, mul_def]
@[simp] protected lemma zero_mul (k : fin (n + 1)) : (0 : fin (n + 1)) * k = 0 :=
by simp [eq_iff_veq, mul_def]
end mul
end fin
|
38737da485f62d10b65f973b0b57d8699ed2a62c | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/group_theory/sylow.lean | 67ffb1a37267bb743ffb1e1a961877dbb242200f | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 12,395 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import group_theory.group_action
import group_theory.quotient_group
import group_theory.order_of_element
import data.zmod.basic
import data.fintype.card
import data.list.rotate
open equiv fintype finset mul_action function
open equiv.perm subgroup list quotient_group
open_locale big_operators
universes u v w
variables {G : Type u} {α : Type v} {β : Type w} [group G]
local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable
namespace mul_action
variables [mul_action G α]
lemma mem_fixed_points_iff_card_orbit_eq_one {a : α}
[fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 :=
begin
rw [fintype.card_eq_one_iff, mem_fixed_points],
split,
{ exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ },
{ assume h x,
rcases h with ⟨⟨z, hz⟩, hz₁⟩,
exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩)
... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm }
end
lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)]
(p : ℕ) {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] :=
calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) :
card_congr (sigma_preimage_equiv (@quotient.mk' _ (orbit_rel G α))).symm
... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _
... ≡ ∑ a : fixed_points G α, 1 [MOD p] :
begin
rw [← zmod.eq_iff_modeq_nat p, sum_nat_cast, sum_nat_cast],
refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1)
(λ _ _ _, mem_univ _)
(λ a₁ a₂ _ _ _ _ h,
subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h)))
(λ b, _)
(λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2];
simp only [quotient.eq']; congr)),
{ refine quotient.induction_on' b (λ b _ hb, _),
have : card (orbit G b) ∣ p ^ n,
{ rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)];
exact card_quotient_dvd_card _ },
rcases (nat.dvd_prime_pow hp).1 this with ⟨k, _, hk⟩,
have hb' :¬ p ^ 1 ∣ p ^ k,
{ rw [pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat,
nat.cast_zero, ← ne.def],
exact eq.mpr (by simp only [quotient.eq']; congr) hb },
have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (pow_dvd_pow p) hb'))),
refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, pow_zero]⟩,
mem_univ _, _, rfl⟩,
rw [nat.cast_one], exact one_ne_zero }
end
... = _ : by simp; refl
end mul_action
lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G)
(t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) =
fintype.card s * fintype.card t :=
by rw [← fintype.card_prod, fintype.card_congr
(preimage_mk_equiv_subgroup_times_set _ _)]
namespace sylow
/-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`,
by consing the the inverse of the product of `v`. -/
def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) :=
v.to_list.prod⁻¹ :: v
lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) :=
λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h)
/-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/
def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) :=
{v | v.to_list.prod = 1}
lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) :
v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl
lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) :
v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) :=
⟨λ (h : v.to_list.prod = 1), ⟨v.tail,
begin
unfold mk_vector_prod_eq_one,
conv {to_rhs, rw ← vector.cons_head_tail v},
suffices : (v.tail.to_list.prod)⁻¹ = v.head,
{ rw this },
rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons,
← vector.to_list_cons, vector.cons_head_tail, h]
end⟩,
λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one,
vector.to_list_cons, list.prod_cons, inv_mul_self]⟩
/-- The rotation action of `zmod n` (viewed as multiplicative group) on
`vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/
def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ)
(m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n :=
⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩
instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] :
mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) :=
{ smul := (rotate_vectors_prod_eq_one G n),
one_smul :=
begin
intro v, apply subtype.eq, apply vector.eq _ _,
show rotate _ (0 : zmod n).val = _, rw zmod.val_zero,
exact rotate_zero v.1.to_list
end,
mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $
show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val),
by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] }
lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n :=
by simp [vector.repeat, vectors_prod_eq_one]
lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] :
(⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈
fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) :=
λ m, subtype.eq $ vector.eq _ _ $
rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G),
show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _
/-- Cauchy's theorem -/
lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime]
(hdvd : p ∣ card G) : ∃ x : G, order_of x = p :=
let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.one_lt⟩ in
have hn : p = n + 1 := nat.succ_sub hp.pos,
have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ),
by rw [set.ext mem_vectors_prod_eq_one_iff,
set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector],
have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1,
by { rw pow_one p, exact zmod.card p },
have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points
(multiplicative (zmod p)) (vectors_prod_eq_one G p) _ _ _ _ _ _ 1 hp hzmod,
have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) :=
calc p ∣ card G ^ 1 : by rwa pow_one
... ∣ card G ^ (n : ℕ) : pow_dvd_pow _ n.2
... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm,
have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)),
by { rw nat.dvd_iff_mod_eq_zero at hdvdcard ⊢, rwa [← hn, hmodeq] at hdvdcard },
have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) :=
fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p, one_mem_vectors_prod_eq_one _⟩,
one_mem_fixed_points_rotate _⟩⟩,
have hlt : 1 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) :=
calc (1 : ℕ) < p : hp.one_lt
... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂,
let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_one_lt_card hlt
⟨_, one_mem_fixed_points_rotate p⟩ in
have hx : x ≠ list.repeat (1 : G) p, from λ h, by simpa [h, vector.repeat] using hx₄,
have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n,
have list.rotate x (n : zmod p).val = x :=
subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p))),
by rwa [zmod.val_cast_nat, ← hx₁, rotate_mod] at this),
let ⟨a, ha⟩ := this in
⟨a, have hx1 : x.prod = 1 := hx₂,
have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl),
have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1,
(hp.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left
(λ h, ha1 (order_of_eq_one_iff.1 h))⟩
open subgroup submonoid is_group_hom mul_action
lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [fintype ((H : set G) : Type u)]
{x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H :=
⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x,
from λ _, ((mem_fixed_points' _).1 hx _),
(inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H),
have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)),
show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv}
)),
λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H),
(mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2
(let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in
have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂,
(inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1
$ by rw hx at hb₂;
simpa [mul_inv_rev, mul_assoc] using hb₂)⟩
def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] :
fixed_points H (quotient H) ≃
quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) :=
@subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _)
(λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm) (by intros; refl)
lemma exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ n ∣ card G), ∃ H : subgroup G, fintype.card H = p ^ n
| 0 := λ _ _, ⟨(⊥ : subgroup G), by convert card_trivial⟩
| (n+1) := λ hp hdvd,
let ⟨H, hH2⟩ := @exists_subgroup_card_pow_prime _ hp
(dvd.trans (pow_dvd_pow _ (nat.le_succ _)) hdvd) in
let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in
have hcard : card (quotient H) = s * p :=
(nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2
⟨⟨1, H.one_mem⟩⟩)).1
(by rwa [← card_eq_card_quotient_mul_card_subgroup, hH2, hs,
pow_succ', mul_assoc, mul_comm p]),
have hm : s * p % p =
card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p :=
card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸
@card_modeq_card_fixed_points _ _ _ _ _ _ _ p _ hp hH2,
have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) :=
nat.dvd_of_mod_eq_zero
(by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm),
let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.group _) _ _ hp hm' in
have hxcard : ∀ {f : fintype (subgroup.gpowers x)}, card (subgroup.gpowers x) = p,
from λ f, by rw [← hx, order_eq_card_gpowers]; congr,
have fintype (subgroup.comap (quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)),
by apply_instance,
have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) :=
⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩,
λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩,
-- begin proof of ∃ H : subgroup G, fintype.card H = p ^ n
⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (quotient_group.mk' _) (gpowers x)),
begin
show card ↥(map H.normalizer.subtype (comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) =
p ^ (n + 1),
suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H))
(gpowers x)) : set (↥(H.normalizer)))) = p^(n+1),
{ convert this },
rw [set.card_image_of_injective
(subgroup.comap (quotient_group.mk' _) (gpowers x) : set (H.normalizer)) subtype.val_injective,
pow_succ', ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers,
← fintype.card_prod],
exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _)
end
⟩
end sylow
|
8e50b89bd4af3351838388b6309c31b819a967a6 | bb31430994044506fa42fd667e2d556327e18dfe | /src/topology/basic.lean | 101947cac86024f575ce7e8bf835be72d49a8e99 | [
"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 | 75,467 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Jeremy Avigad
-/
import order.filter.ultrafilter
import order.filter.partial
import algebra.support
import order.filter.lift
/-!
# Basic theory of topological spaces.
The main definition is the type class `topological space α` which endows a type `α` with a topology.
Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and
`frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has
`x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x`
along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular
the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`.
For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`,
`continuous_at f a` means `f` is continuous at `a`, and global continuity is
`continuous f`. There is also a version of continuity `pcontinuous` for
partially defined functions.
## Notation
* `𝓝 x`: the filter `nhds x` of neighborhoods of a point `x`;
* `𝓟 s`: the principal filter of a set `s`;
* `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`;
* `𝓝[≤] x`: the filter `nhds_within x (set.Iic x)` of left-neighborhoods of `x`;
* `𝓝[≥] x`: the filter `nhds_within x (set.Ici x)` of right-neighborhoods of `x`;
* `𝓝[<] x`: the filter `nhds_within x (set.Iio x)` of punctured left-neighborhoods of `x`;
* `𝓝[>] x`: the filter `nhds_within x (set.Ioi x)` of punctured right-neighborhoods of `x`;
* `𝓝[≠] x`: the filter `nhds_within x {x}ᶜ` of punctured neighborhoods of `x`.
## Implementation notes
Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in
<https://leanprover-community.github.io/theories/topology.html>.
## References
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
## Tags
topological space, interior, closure, frontier, neighborhood, continuity, continuous function
-/
noncomputable theory
open set filter classical
open_locale classical filter
universes u v w
/-!
### Topological spaces
-/
/-- A topology on `α`. -/
@[protect_proj] structure topological_space (α : Type u) :=
(is_open : set α → Prop)
(is_open_univ : is_open univ)
(is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t))
(is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s))
attribute [class] topological_space
/-- A constructor for topologies by specifying the closed sets,
and showing that they satisfy the appropriate conditions. -/
def topological_space.of_closed {α : Type u} (T : set (set α))
(empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) :
topological_space α :=
{ is_open := λ X, Xᶜ ∈ T,
is_open_univ := by simp [empty_mem],
is_open_inter := λ s t hs ht, by simpa only [compl_inter] using union_mem sᶜ hs tᶜ ht,
is_open_sUnion := λ s hs,
by rw set.compl_sUnion; exact sInter_mem (compl '' s)
(λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) }
section topological_space
variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ t : set α} {p p₁ p₂ : α → Prop}
@[ext]
lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g
| ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl
section
variables [topological_space α]
/-- `is_open s` means that `s` is open in the ambient topological space on `α` -/
def is_open (s : set α) : Prop := topological_space.is_open ‹_› s
@[simp]
lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ _
lemma is_open.inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) :=
topological_space.is_open_inter _ s₁ s₂ h₁ h₂
lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) :=
topological_space.is_open_sUnion _ s h
end
lemma topological_space_eq_iff {t t' : topological_space α} :
t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s :=
⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩
lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s :=
rfl
variables [topological_space α]
lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) :=
is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i
lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) :
is_open (⋃i∈s, f i) :=
is_open_Union $ assume i, is_open_Union $ assume hi, h i hi
lemma is_open.union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) :=
by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
@[simp] lemma is_open_empty : is_open (∅ : set α) :=
by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim)
lemma is_open_sInter {s : set (set α)} (hs : s.finite) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) :=
finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $
λ a s has hs ih h, by rw sInter_insert; exact
is_open.inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _)
lemma is_open_bInter {s : set β} {f : β → set α} (hs : s.finite) :
(∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bInter_empty; exact is_open_univ)
(λ a s has hs ih h, by rw bInter_insert; exact
is_open.inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_open_Inter [finite β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) :=
suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa,
is_open_bInter finite_univ (λ i _, h i)
lemma is_open_Inter_prop {p : Prop} {s : p → set α}
(h : ∀ h : p, is_open (s h)) : is_open (Inter s) :=
by by_cases p; simp *
lemma is_open_bInter_finset {s : finset β} {f : β → set α} (h : ∀ i ∈ s, is_open (f i)) :
is_open (⋂ i ∈ s, f i) :=
is_open_bInter (to_finite _) h
lemma is_open_const {p : Prop} : is_open {a : α | p} :=
by_cases
(assume : p, begin simp only [this]; exact is_open_univ end)
(assume : ¬ p, begin simp only [this]; exact is_open_empty end)
lemma is_open.and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} :=
is_open.inter
/-- A set is closed if its complement is open -/
class is_closed (s : set α) : Prop :=
(is_open_compl : is_open sᶜ)
@[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s :=
⟨λ h, ⟨h⟩, λ h, h.is_open_compl⟩
@[simp] lemma is_closed_empty : is_closed (∅ : set α) :=
by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ }
@[simp] lemma is_closed_univ : is_closed (univ : set α) :=
by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty }
lemma is_closed.union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) :=
λ h₁ h₂, by { rw [← is_open_compl_iff] at *, rw compl_union, exact is_open.inter h₁ h₂ }
lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) :=
by simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion
lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) :=
is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i
lemma is_closed_bInter {s : set β} {f : β → set α} (h : ∀ i ∈ s, is_closed (f i)) :
is_closed (⋂ i ∈ s, f i) :=
is_closed_Inter $ λ i, is_closed_Inter $ h i
@[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s :=
by rw [←is_open_compl_iff, compl_compl]
lemma is_open.is_closed_compl {s : set α} (hs : is_open s) : is_closed sᶜ :=
is_closed_compl_iff.2 hs
lemma is_open.sdiff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) :=
is_open.inter h₁ $ is_open_compl_iff.mpr h₂
lemma is_closed.inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) :=
by { rw [← is_open_compl_iff] at *, rw compl_inter, exact is_open.union h₁ h₂ }
lemma is_closed.sdiff {s t : set α} (h₁ : is_closed s) (h₂ : is_open t) : is_closed (s \ t) :=
is_closed.inter h₁ (is_closed_compl_iff.mpr h₂)
lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : s.finite) :
(∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bUnion_empty; exact is_closed_empty)
(λ a s has hs ih h, by rw bUnion_insert; exact
is_closed.union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_closed_Union [finite β] {s : β → set α} (h : ∀ i, is_closed (s i)) :
is_closed (⋃ i, s i) :=
suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i),
by convert this; simp [set.ext_iff],
is_closed_bUnion finite_univ (λ i _, h i)
lemma is_closed_Union_prop {p : Prop} {s : p → set α}
(h : ∀ h : p, is_closed (s h)) : is_closed (Union s) :=
by by_cases p; simp *
lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x})
(hq : is_closed {x | q x}) : is_closed {x | p x → q x} :=
have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or,
by rw [this]; exact is_closed.union (is_closed_compl_iff.mpr hp) hq
lemma is_closed.not : is_closed {a | p a} → is_open {a | ¬ p a} :=
is_open_compl_iff.mpr
/-!
### Interior of a set
-/
/-- The interior of a set `s` is the largest open subset of `s`. -/
def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s}
lemma mem_interior {s : set α} {x : α} :
x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by simp only [interior, mem_sUnion, mem_set_of_eq, exists_prop, and_assoc, and.left_comm]
@[simp] lemma is_open_interior {s : set α} : is_open (interior s) :=
is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁
lemma interior_subset {s : set α} : interior s ⊆ s :=
sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂
lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s :=
subset_sUnion_of_mem ⟨h₂, h₁⟩
lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s :=
subset.antisymm interior_subset (interior_maximal (subset.refl s) h)
lemma interior_eq_iff_is_open {s : set α} : interior s = s ↔ is_open s :=
⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩
lemma subset_interior_iff_is_open {s : set α} : s ⊆ interior s ↔ is_open s :=
by simp only [interior_eq_iff_is_open.symm, subset.antisymm_iff, interior_subset, true_and]
lemma is_open.subset_interior_iff {s t : set α} (h₁ : is_open s) :
s ⊆ interior t ↔ s ⊆ t :=
⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩
lemma subset_interior_iff {s t : set α} : t ⊆ interior s ↔ ∃ U, is_open U ∧ t ⊆ U ∧ U ⊆ s :=
⟨λ h, ⟨interior s, is_open_interior, h, interior_subset⟩,
λ ⟨U, hU, htU, hUs⟩, htU.trans (interior_maximal hUs hU)⟩
@[mono] lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t :=
interior_maximal (subset.trans interior_subset h) is_open_interior
@[simp] lemma interior_empty : interior (∅ : set α) = ∅ :=
is_open_empty.interior_eq
@[simp] lemma interior_univ : interior (univ : set α) = univ :=
is_open_univ.interior_eq
@[simp] lemma interior_eq_univ {s : set α} : interior s = univ ↔ s = univ :=
⟨λ h, univ_subset_iff.mp $ h.symm.trans_le interior_subset, λ h, h.symm ▸ interior_univ⟩
@[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s :=
is_open_interior.interior_eq
@[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t :=
subset.antisymm
(subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t))
(interior_maximal (inter_subset_inter interior_subset interior_subset) $
is_open.inter is_open_interior is_open_interior)
@[simp] lemma finset.interior_Inter {ι : Type*} (s : finset ι) (f : ι → set α) :
interior (⋂ i ∈ s, f i) = ⋂ i ∈ s, interior (f i) :=
begin
classical,
refine s.induction_on (by simp) _,
intros i s h₁ h₂,
simp [h₂],
end
@[simp] lemma interior_Inter {ι : Type*} [finite ι] (f : ι → set α) :
interior (⋂ i, f i) = ⋂ i, interior (f i) :=
by { casesI nonempty_fintype ι, convert finset.univ.interior_Inter f; simp }
lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s)
(h₂ : interior t = ∅) :
interior (s ∪ t) = interior s :=
have interior (s ∪ t) ⊆ s, from
assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩,
classical.by_contradiction $ assume hx₂ : x ∉ s,
have u \ s ⊆ t,
from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂,
have u \ s ⊆ interior t,
by rwa (is_open.sdiff hu₁ h₁).subset_interior_iff,
have u \ s ⊆ ∅,
by rwa h₂ at this,
this ⟨hx₁, hx₂⟩,
subset.antisymm
(interior_maximal this is_open_interior)
(interior_mono $ subset_union_left _ _)
lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by rw ← subset_interior_iff_is_open; simp only [subset_def, mem_interior]
lemma interior_Inter_subset (s : ι → set α) : interior (⋂ i, s i) ⊆ ⋂ i, interior (s i) :=
subset_Inter $ λ i, interior_mono $ Inter_subset _ _
lemma interior_Inter₂_subset (p : ι → Sort*) (s : Π i, p i → set α) :
interior (⋂ i j, s i j) ⊆ ⋂ i j, interior (s i j) :=
(interior_Inter_subset _).trans $ Inter_mono $ λ i, interior_Inter_subset _
lemma interior_sInter_subset (S : set (set α)) : interior (⋂₀ S) ⊆ ⋂ s ∈ S, interior s :=
calc interior (⋂₀ S) = interior (⋂ s ∈ S, s) : by rw sInter_eq_bInter
... ⊆ ⋂ s ∈ S, interior s : interior_Inter₂_subset _ _
/-!
### Closure of a set
-/
/-- The closure of `s` is the smallest closed set containing `s`. -/
def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t}
@[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) :=
is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁
lemma subset_closure {s : set α} : s ⊆ closure s :=
subset_sInter $ assume t ⟨h₁, h₂⟩, h₂
lemma not_mem_of_not_mem_closure {s : set α} {P : α} (hP : P ∉ closure s) : P ∉ s :=
λ h, hP (subset_closure h)
lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t :=
sInter_subset_of_mem ⟨h₂, h₁⟩
lemma disjoint.closure_left {s t : set α} (hd : disjoint s t) (ht : is_open t) :
disjoint (closure s) t :=
disjoint_compl_left.mono_left $ closure_minimal hd.subset_compl_right ht.is_closed_compl
lemma disjoint.closure_right {s t : set α} (hd : disjoint s t) (hs : is_open s) :
disjoint s (closure t) :=
(hd.symm.closure_left hs).symm
lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s :=
subset.antisymm (closure_minimal (subset.refl s) h) subset_closure
lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s :=
closure_minimal (subset.refl _) hs
lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) :
closure s ⊆ t ↔ s ⊆ t :=
⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩
lemma is_closed.mem_iff_closure_subset {s : set α} (hs : is_closed s) {x : α} :
x ∈ s ↔ closure ({x} : set α) ⊆ s :=
(hs.closure_subset_iff.trans set.singleton_subset_iff).symm
@[mono] lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_minimal (subset.trans h subset_closure) is_closed_closure
lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) :=
λ _ _, closure_mono
lemma diff_subset_closure_iff {s t : set α} :
s \ t ⊆ closure t ↔ s ⊆ closure t :=
by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure]
lemma closure_inter_subset_inter_closure (s t : set α) :
closure (s ∩ t) ⊆ closure s ∩ closure t :=
(monotone_closure α).map_inf_le s t
lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s :=
by rw subset.antisymm subset_closure h; exact is_closed_closure
lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s :=
⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩
lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s :=
⟨is_closed_of_closure_subset, is_closed.closure_subset⟩
@[simp] lemma closure_empty : closure (∅ : set α) = ∅ :=
is_closed_empty.closure_eq
@[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ :=
⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩
@[simp] lemma closure_nonempty_iff {s : set α} : (closure s).nonempty ↔ s.nonempty :=
by simp only [nonempty_iff_ne_empty, ne.def, closure_empty_iff]
alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure
@[simp] lemma closure_univ : closure (univ : set α) = univ :=
is_closed_univ.closure_eq
@[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s :=
is_closed_closure.closure_eq
@[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t :=
subset.antisymm
(closure_minimal (union_subset_union subset_closure subset_closure) $
is_closed.union is_closed_closure is_closed_closure)
((monotone_closure α).le_map_sup s t)
@[simp] lemma finset.closure_bUnion {ι : Type*} (s : finset ι) (f : ι → set α) :
closure (⋃ i ∈ s, f i) = ⋃ i ∈ s, closure (f i) :=
begin
classical,
refine s.induction_on (by simp) _,
intros i s h₁ h₂,
simp [h₂],
end
@[simp] lemma closure_Union {ι : Type*} [finite ι] (f : ι → set α) :
closure (⋃ i, f i) = ⋃ i, closure (f i) :=
by { casesI nonempty_fintype ι, convert finset.univ.closure_bUnion f; simp }
lemma interior_subset_closure {s : set α} : interior s ⊆ closure s :=
subset.trans interior_subset subset_closure
lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ :=
begin
rw [interior, closure, compl_sUnion, compl_image_set_of],
simp only [compl_subset_compl, is_open_compl_iff],
end
@[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ :=
by simp [closure_eq_compl_interior_compl]
theorem mem_closure_iff {s : set α} {a : α} :
a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty :=
⟨λ h o oo ao, classical.by_contradiction $ λ os,
have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩,
closure_minimal this (is_closed_compl_iff.2 oo) h ao,
λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc,
let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (h₂ hs)⟩
lemma closure_inter_open_nonempty_iff {s t : set α} (h : is_open t) :
(closure s ∩ t).nonempty ↔ (s ∩ t).nonempty :=
⟨λ ⟨x, hxcs, hxt⟩, inter_comm t s ▸ mem_closure_iff.1 hxcs t h hxt,
λ h, h.mono $ inf_le_inf_right t subset_closure⟩
lemma filter.le_lift'_closure (l : filter α) : l ≤ l.lift' closure :=
le_lift'.2 $ λ s hs, mem_of_superset hs subset_closure
lemma filter.has_basis.lift'_closure {l : filter α} {p : ι → Prop} {s : ι → set α}
(h : l.has_basis p s) :
(l.lift' closure).has_basis p (λ i, closure (s i)) :=
h.lift' (monotone_closure α)
lemma filter.has_basis.lift'_closure_eq_self {l : filter α} {p : ι → Prop} {s : ι → set α}
(h : l.has_basis p s) (hc : ∀ i, p i → is_closed (s i)) :
l.lift' closure = l :=
le_antisymm (h.ge_iff.2 $ λ i hi, (hc i hi).closure_eq ▸ mem_lift' (h.mem_of_mem hi))
l.le_lift'_closure
@[simp] lemma filter.lift'_closure_eq_bot {l : filter α} : l.lift' closure = ⊥ ↔ l = ⊥ :=
⟨λ h, bot_unique $ h ▸ l.le_lift'_closure,
λ h, h.symm ▸ by rw [lift'_bot (monotone_closure _), closure_empty, principal_empty]⟩
/-- A set is dense in a topological space if every point belongs to its closure. -/
def dense (s : set α) : Prop := ∀ x, x ∈ closure s
lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ :=
eq_univ_iff_forall.symm
lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ :=
dense_iff_closure_eq.mp h
lemma interior_eq_empty_iff_dense_compl {s : set α} : interior s = ∅ ↔ dense sᶜ :=
by rw [dense_iff_closure_eq, closure_compl, compl_univ_iff]
lemma dense.interior_compl {s : set α} (h : dense s) : interior sᶜ = ∅ :=
interior_eq_empty_iff_dense_compl.2 $ by rwa compl_compl
/-- The closure of a set `s` is dense if and only if `s` is dense. -/
@[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s :=
by rw [dense, dense, closure_closure]
alias dense_closure ↔ dense.of_closure dense.closure
@[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial
/-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/
lemma dense_iff_inter_open {s : set α} :
dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty :=
begin
split ; intro h,
{ rintros U U_op ⟨x, x_in⟩,
exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in },
{ intro x,
rw mem_closure_iff,
intros U U_op x_in,
exact h U U_op ⟨_, x_in⟩ },
end
alias dense_iff_inter_open ↔ dense.inter_open_nonempty _
lemma dense.exists_mem_open {s : set α} (hs : dense s) {U : set α} (ho : is_open U)
(hne : U.nonempty) :
∃ x ∈ s, x ∈ U :=
let ⟨x, hx⟩ := hs.inter_open_nonempty U ho hne in ⟨x, hx.2, hx.1⟩
lemma dense.nonempty_iff {s : set α} (hs : dense s) :
s.nonempty ↔ nonempty α :=
⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩,
let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩
lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty :=
hs.nonempty_iff.2 h
@[mono]
lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ :=
λ x, closure_mono h (hd x)
/-- Complement to a singleton is dense if and only if the singleton is not an open set. -/
lemma dense_compl_singleton_iff_not_open {x : α} : dense ({x}ᶜ : set α) ↔ ¬is_open ({x} : set α) :=
begin
fsplit,
{ intros hd ho,
exact (hd.inter_open_nonempty _ ho (singleton_nonempty _)).ne_empty (inter_compl_self _) },
{ refine λ ho, dense_iff_inter_open.2 (λ U hU hne, inter_compl_nonempty_iff.2 $ λ hUx, _),
obtain rfl : U = {x}, from eq_singleton_iff_nonempty_unique_mem.2 ⟨hne, hUx⟩,
exact ho hU }
end
/-!
### Frontier of a set
-/
/-- The frontier of a set is the set of points between the closure and interior. -/
def frontier (s : set α) : set α := closure s \ interior s
@[simp] lemma closure_diff_interior (s : set α) : closure s \ interior s = frontier s := rfl
@[simp] lemma closure_diff_frontier (s : set α) : closure s \ frontier s = interior s :=
by rw [frontier, diff_diff_right_self, inter_eq_self_of_subset_right interior_subset_closure]
@[simp] lemma self_diff_frontier (s : set α) : s \ frontier s = interior s :=
by rw [frontier, diff_diff_right, diff_eq_empty.2 subset_closure,
inter_eq_self_of_subset_right interior_subset, empty_union]
lemma frontier_eq_closure_inter_closure {s : set α} :
frontier s = closure s ∩ closure sᶜ :=
by rw [closure_compl, frontier, diff_eq]
lemma frontier_subset_closure {s : set α} : frontier s ⊆ closure s := diff_subset _ _
lemma is_closed.frontier_subset (hs : is_closed s) : frontier s ⊆ s :=
frontier_subset_closure.trans hs.closure_eq.subset
lemma frontier_closure_subset {s : set α} : frontier (closure s) ⊆ frontier s :=
diff_subset_diff closure_closure.subset $ interior_mono subset_closure
lemma frontier_interior_subset {s : set α} : frontier (interior s) ⊆ frontier s :=
diff_subset_diff (closure_mono interior_subset) interior_interior.symm.subset
/-- The complement of a set has the same frontier as the original set. -/
@[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s :=
by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm]
@[simp] lemma frontier_univ : frontier (univ : set α) = ∅ := by simp [frontier]
@[simp] lemma frontier_empty : frontier (∅ : set α) = ∅ := by simp [frontier]
lemma frontier_inter_subset (s t : set α) :
frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) :=
begin
simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union],
convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t),
simp only [inter_distrib_left, inter_distrib_right, inter_assoc],
congr' 2,
apply inter_comm
end
lemma frontier_union_subset (s t : set α) :
frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) :=
by simpa only [frontier_compl, ← compl_union]
using frontier_inter_subset sᶜ tᶜ
lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s :=
by rw [frontier, hs.closure_eq]
lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s :=
by rw [frontier, hs.interior_eq]
lemma is_open.inter_frontier_eq {s : set α} (hs : is_open s) : s ∩ frontier s = ∅ :=
by rw [hs.frontier_eq, inter_diff_self]
/-- The frontier of a set is closed. -/
lemma is_closed_frontier {s : set α} : is_closed (frontier s) :=
by rw frontier_eq_closure_inter_closure; exact is_closed.inter is_closed_closure is_closed_closure
/-- The frontier of a closed set has no interior point. -/
lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ :=
begin
have A : frontier s = s \ interior s, from h.frontier_eq,
have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _),
have C : interior (frontier s) ⊆ frontier s := interior_subset,
have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) :=
subset_inter B (by simpa [A] using C),
rwa [inter_diff_self, subset_empty_iff] at this,
end
lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s :=
(union_diff_cancel interior_subset_closure).symm
lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s :=
(union_diff_cancel' interior_subset subset_closure).symm
lemma disjoint.frontier_left (ht : is_open t) (hd : disjoint s t) : disjoint (frontier s) t :=
subset_compl_iff_disjoint_right.1 $ frontier_subset_closure.trans $ closure_minimal
(disjoint_left.1 hd) $ is_closed_compl_iff.2 ht
lemma disjoint.frontier_right (hs : is_open s) (hd : disjoint s t) : disjoint s (frontier t) :=
(hd.symm.frontier_left hs).symm
lemma frontier_eq_inter_compl_interior {s : set α} :
frontier s = (interior s)ᶜ ∩ (interior (sᶜ))ᶜ :=
by { rw [←frontier_compl, ←closure_compl], refl }
lemma compl_frontier_eq_union_interior {s : set α} :
(frontier s)ᶜ = interior s ∪ interior sᶜ :=
begin
rw frontier_eq_inter_compl_interior,
simp only [compl_inter, compl_compl],
end
/-!
### Neighborhoods
-/
/-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all
neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the
infimum over the principal filters of all open sets containing `a`. -/
@[irreducible] def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s)
localized "notation (name := nhds) `𝓝` := nhds" in topological_space
/-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the
intersection of `s` and a neighborhood of `a`. -/
def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s
localized "notation (name := nhds_within)
`𝓝[` s `] ` x:100 := nhds_within x s" in topological_space
localized "notation (name := nhds_within.ne)
`𝓝[≠] ` x:100 := nhds_within x {x}ᶜ" in topological_space
localized "notation (name := nhds_within.ge)
`𝓝[≥] ` x:100 := nhds_within x (set.Ici x)" in topological_space
localized "notation (name := nhds_within.le)
`𝓝[≤] ` x:100 := nhds_within x (set.Iic x)" in topological_space
localized "notation (name := nhds_within.gt)
`𝓝[>] ` x:100 := nhds_within x (set.Ioi x)" in topological_space
localized "notation (name := nhds_within.lt)
`𝓝[<] ` x:100 := nhds_within x (set.Iio x)" in topological_space
lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := by rw nhds
lemma nhds_def' (a : α) : 𝓝 a = ⨅ (s : set α) (hs : is_open s) (ha : a ∈ s), 𝓟 s :=
by simp only [nhds_def, mem_set_of_eq, and_comm (a ∈ _), infi_and]
/-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'`
for a variant using open neighborhoods instead. -/
lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ s, s) :=
begin
rw nhds_def,
exact has_basis_binfi_principal
(λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open.inter hs ht⟩,
⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩)
⟨univ, ⟨mem_univ a, is_open_univ⟩⟩
end
lemma nhds_basis_closeds (a : α) : (𝓝 a).has_basis (λ s : set α, a ∉ s ∧ is_closed s) compl :=
⟨λ t, (nhds_basis_opens a).mem_iff.trans $ compl_surjective.exists.trans $
by simp only [is_open_compl_iff, mem_compl_iff]⟩
/-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/
lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f :=
by simp [nhds_def]
/-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above
the principal filter of some open set `s` containing `a`. -/
lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f :=
by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf)
lemma mem_nhds_iff {a : α} {s : set α} :
s ∈ 𝓝 a ↔ ∃ t ⊆ s, is_open t ∧ a ∈ t :=
(nhds_basis_opens a).mem_iff.trans
⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩
/-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set
containing `a`. -/
lemma eventually_nhds_iff {a : α} {p : α → Prop} :
(∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t :=
mem_nhds_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq]
lemma map_nhds {a : α} {f : α → β} :
map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) :=
((nhds_basis_opens a).map f).eq_binfi
lemma mem_of_mem_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s :=
λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_iff.1 H in ht hs
/-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/
lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α}
(h : ∀ᶠ y in 𝓝 a, p y) : p a :=
mem_of_mem_nhds h
lemma is_open.mem_nhds {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
s ∈ 𝓝 a :=
mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩
lemma is_open.mem_nhds_iff {a : α} {s : set α} (hs : is_open s) : s ∈ 𝓝 a ↔ a ∈ s :=
⟨mem_of_mem_nhds, λ ha, mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩⟩
lemma is_closed.compl_mem_nhds {a : α} {s : set α} (hs : is_closed s) (ha : a ∉ s) : sᶜ ∈ 𝓝 a :=
hs.is_open_compl.mem_nhds (mem_compl ha)
lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
∀ᶠ x in 𝓝 a, x ∈ s :=
is_open.mem_nhds hs ha
/-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens`
for a variant using open sets around `a` instead. -/
lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) :=
begin
convert nhds_basis_opens a,
ext s,
exact and.congr_left_iff.2 is_open.mem_nhds_iff
end
/-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`:
it contains an open set containing `s`. -/
lemma exists_open_set_nhds {s U : set α} (h : ∀ x ∈ s, U ∈ 𝓝 x) :
∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U :=
begin
have := λ x hx, (nhds_basis_opens x).mem_iff.1 (h x hx),
choose! Z hZ hZU using this, choose hZmem hZo using hZ,
exact ⟨⋃ x ∈ s, Z x, λ x hx, mem_bUnion hx (hZmem x hx), is_open_bUnion hZo, Union₂_subset hZU⟩
end
/-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s:
it contains an open set containing `s`. -/
lemma exists_open_set_nhds' {s U : set α} (h : U ∈ ⨆ x ∈ s, 𝓝 x) :
∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U :=
exists_open_set_nhds (by simpa using h)
/-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close
to `a` this predicate is true in a neighbourhood of `y`. -/
lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) :
∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x :=
let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in
eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩
@[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} :
(∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x :=
⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩
@[simp] lemma frequently_frequently_nhds {p : α → Prop} {a : α} :
(∃ᶠ y in 𝓝 a, ∃ᶠ x in 𝓝 y, p x) ↔ (∃ᶠ x in 𝓝 a, p x) :=
begin
rw ← not_iff_not,
simp_rw not_frequently,
exact eventually_eventually_nhds,
end
@[simp] lemma eventually_mem_nhds {s : set α} {a : α} :
(∀ᶠ x in 𝓝 a, s ∈ 𝓝 x) ↔ s ∈ 𝓝 a :=
eventually_eventually_nhds
@[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds
@[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} :
(∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g :=
eventually_eventually_nhds
lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a :=
h.self_of_nhds
@[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} :
(∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g :=
eventually_eventually_nhds
/-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close
to `a` these functions are equal in a neighbourhood of `y`. -/
lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) :
∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g :=
h.eventually_nhds
/-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have
`f x ≤ g x` in a neighbourhood of `y`. -/
lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) :
∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g :=
h.eventually_nhds
theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) :
(∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) :=
((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp]
theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t)
(l : filter β) :
(∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) :=
all_mem_nhds _ _ (λ s t ssubt h, mem_of_superset h (hf s t ssubt))
theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t, id) _
theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) :=
by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono }
theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) :=
rtendsto_nhds
theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) :=
rtendsto'_nhds
theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} :
tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _
lemma tendsto_at_top_nhds [nonempty β] [semilattice_sup β] {f : β → α} {a : α} :
(tendsto f at_top (𝓝 a)) ↔ ∀ U : set α, a ∈ U → is_open U → ∃ N, ∀ n, N ≤ n → f n ∈ U :=
(at_top_basis.tendsto_iff (nhds_basis_opens a)).trans $
by simp only [and_imp, exists_prop, true_and, mem_Ici, ge_iff_le]
lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) :=
tendsto_nhds.mpr $ assume s hs ha, univ_mem' $ assume _, ha
lemma tendsto_at_top_of_eventually_const {ι : Type*} [semilattice_sup ι] [nonempty ι]
{x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≥ i₀, u i = x) : tendsto u at_top (𝓝 x) :=
tendsto.congr' (eventually_eq.symm (eventually_at_top.mpr ⟨i₀, h⟩)) tendsto_const_nhds
lemma tendsto_at_bot_of_eventually_const {ι : Type*} [semilattice_inf ι] [nonempty ι]
{x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≤ i₀, u i = x) : tendsto u at_bot (𝓝 x) :=
tendsto.congr' (eventually_eq.symm (eventually_at_bot.mpr ⟨i₀, h⟩)) tendsto_const_nhds
lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) :=
assume a s hs, mem_pure.2 $ mem_of_mem_nhds hs
lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) :
tendsto f (pure a) (𝓝 (f a)) :=
(tendsto_pure_pure f a).mono_right (pure_le_nhds _)
lemma order_top.tendsto_at_top_nhds {α : Type*} [partial_order α] [order_top α]
[topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) :=
(tendsto_at_top_pure f).mono_right (pure_le_nhds _)
@[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) :=
ne_bot_of_le (pure_le_nhds a)
/-!
### Cluster points
In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point)
(also known as limit points and accumulation points) of a filter and of a sequence.
-/
/-- A point `x` is a cluster point of a filter `F` if `𝓝 x ⊓ F ≠ ⊥`. Also known as
an accumulation point or a limit point, but beware that terminology varies. This
is *not* the same as asking `𝓝[≠] x ⊓ F ≠ ⊥`. See `mem_closure_iff_cluster_pt` in particular. -/
def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F)
lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h
lemma filter.has_basis.cluster_pt_iff {ιa ιF} {pa : ιa → Prop} {sa : ιa → set α}
{pF : ιF → Prop} {sF : ιF → set α} {F : filter α}
(ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) :
cluster_pt a F ↔ ∀ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty :=
ha.inf_basis_ne_bot_iff hF
lemma cluster_pt_iff {x : α} {F : filter α} :
cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty :=
inf_ne_bot_iff
/-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty
set. See also `mem_closure_iff_cluster_pt`. -/
lemma cluster_pt_principal_iff {x : α} {s : set α} :
cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty :=
inf_principal_ne_bot_iff
lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} :
cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s :=
by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff]
lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f :=
by rwa [cluster_pt, inf_eq_right.mpr H]
lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) :
cluster_pt x f :=
cluster_pt.of_le_nhds H
lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f :=
by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot]
lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) :
cluster_pt x g :=
⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩
lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) :
cluster_pt x f :=
H.mono inf_le_left
lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) :
cluster_pt x g :=
H.mono inf_le_right
lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x :=
⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩
/-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point
of `map u F`. -/
def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F)
lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) :
map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s :=
by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl }
lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ}
{x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) :
map_cluster_pt x F u :=
begin
have := calc
map (u ∘ φ) p = map u (map φ p) : map_map
... ≤ map u F : map_mono h,
have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F,
from le_inf H this,
exact ne_bot_of_le this
end
/--A point `x` is an accumulation point of a filter `F` if `𝓝[≠] x ⊓ F ≠ ⊥`.-/
def acc_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝[≠] x ⊓ F)
lemma acc_iff_cluster (x : α) (F : filter α) : acc_pt x F ↔ cluster_pt x (𝓟 {x}ᶜ ⊓ F) :=
by rw [acc_pt, nhds_within, cluster_pt, inf_assoc]
/-- `x` is an accumulation point of a set `C` iff it is a cluster point of `C ∖ {x}`.-/
lemma acc_principal_iff_cluster (x : α) (C : set α) :
acc_pt x (𝓟 C) ↔ cluster_pt x (𝓟(C \ {x})) :=
by rw [acc_iff_cluster, inf_principal, inter_comm]; refl
/-- `x` is an accumulation point of a set `C` iff every neighborhood
of `x` contains a point of `C` other than `x`. -/
lemma acc_pt_iff_nhds (x : α) (C : set α) : acc_pt x (𝓟 C) ↔ ∀ U ∈ 𝓝 x, ∃ y ∈ U ∩ C, y ≠ x :=
by simp [acc_principal_iff_cluster, cluster_pt_principal_iff, set.nonempty, exists_prop,
and_assoc, and_comm (¬ _ = x)]
/-- `x` is an accumulation point of a set `C` iff
there are points near `x` in `C` and different from `x`.-/
lemma acc_pt_iff_frequently (x : α) (C : set α) : acc_pt x (𝓟 C) ↔ ∃ᶠ y in 𝓝 x, y ≠ x ∧ y ∈ C :=
by simp [acc_principal_iff_cluster, cluster_pt_principal_iff_frequently, and_comm]
/-- If `x` is an accumulation point of `F` and `F ≤ G`, then
`x` is an accumulation point of `D. -/
lemma acc_pt.mono {x : α} {F G : filter α} (h : acc_pt x F) (hFG : F ≤ G) : acc_pt x G :=
⟨ne_bot_of_le_ne_bot h.ne (inf_le_inf_left _ hFG)⟩
/-!
### Interior, closure and frontier in terms of neighborhoods
-/
lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} :=
set.ext $ λ x, by simp only [mem_interior, mem_nhds_iff, mem_set_of_eq]
lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} :=
interior_eq_nhds'.trans $ by simp only [le_principal_iff]
lemma mem_interior_iff_mem_nhds {s : set α} {a : α} :
a ∈ interior s ↔ s ∈ 𝓝 a :=
by rw [interior_eq_nhds', mem_set_of_eq]
@[simp] lemma interior_mem_nhds {s : set α} {a : α} :
interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a :=
⟨λ h, mem_of_superset h interior_subset,
λ h, is_open.mem_nhds is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩
lemma interior_set_of_eq {p : α → Prop} :
interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} :=
interior_eq_nhds'
lemma is_open_set_of_eventually_nhds {p : α → Prop} :
is_open {x | ∀ᶠ y in 𝓝 x, p y} :=
by simp only [← interior_set_of_eq, is_open_interior]
lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x :=
show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s :=
calc is_open s ↔ s ⊆ interior s : subset_interior_iff_is_open.symm
... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a :=
is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff
/-- A set `s` is open iff for every point `x` in `s` and every `y` close to `x`, `y` is in `s`. -/
lemma is_open_iff_eventually {s : set α} : is_open s ↔ ∀ x, x ∈ s → ∀ᶠ y in 𝓝 x, y ∈ s :=
is_open_iff_mem_nhds
theorem is_open_iff_ultrafilter {s : set α} :
is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) :=
by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter]
lemma is_open_singleton_iff_nhds_eq_pure (a : α) :
is_open ({a} : set α) ↔ 𝓝 a = pure a :=
begin
split,
{ intros h,
apply le_antisymm _ (pure_le_nhds a),
rw le_pure_iff,
exact h.mem_nhds (mem_singleton a) },
{ intros h,
simp [is_open_iff_nhds, h] }
end
lemma is_open_singleton_iff_punctured_nhds {α : Type*} [topological_space α] (a : α) :
is_open ({a} : set α) ↔ (𝓝[≠] a) = ⊥ :=
by rw [is_open_singleton_iff_nhds_eq_pure, nhds_within, ← mem_iff_inf_principal_compl,
← le_pure_iff, nhds_ne_bot.le_pure_iff]
lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s :=
by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds,
closure_eq_compl_interior_compl]; refl
alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure
/-- A set `s` is closed iff for every point `x`, if there is a point `y` close to `x` that belongs
to `s` then `x` is in `s`. -/
lemma is_closed_iff_frequently {s : set α} : is_closed s ↔ ∀ x, (∃ᶠ y in 𝓝 x, y ∈ s) → x ∈ s :=
begin
rw ← closure_subset_iff_is_closed,
apply forall_congr (λ x, _),
rw mem_closure_iff_frequently
end
/-- The set of cluster points of a filter is closed. In particular, the set of limit points
of a sequence is closed. -/
lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} :=
begin
simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or],
refine is_closed_Inter (λ p, is_closed.union _ _); apply is_closed_compl_iff.2,
exacts [is_open_set_of_eventually_nhds, is_open_const]
end
theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) :=
mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm
lemma mem_closure_iff_nhds_ne_bot {s : set α} : a ∈ closure s ↔ 𝓝 a ⊓ 𝓟 s ≠ ⊥ :=
mem_closure_iff_cluster_pt.trans ne_bot_iff
lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} :
x ∈ closure s ↔ ne_bot (𝓝[s] x) :=
mem_closure_iff_cluster_pt
/-- If `x` is not an isolated point of a topological space, then `{x}ᶜ` is dense in the whole
space. -/
lemma dense_compl_singleton (x : α) [ne_bot (𝓝[≠] x)] : dense ({x}ᶜ : set α) :=
begin
intro y,
unfreezingI { rcases eq_or_ne y x with rfl|hne },
{ rwa mem_closure_iff_nhds_within_ne_bot },
{ exact subset_closure hne }
end
/-- If `x` is not an isolated point of a topological space, then the closure of `{x}ᶜ` is the whole
space. -/
@[simp] lemma closure_compl_singleton (x : α) [ne_bot (𝓝[≠] x)] :
closure {x}ᶜ = (univ : set α) :=
(dense_compl_singleton x).closure_eq
/-- If `x` is not an isolated point of a topological space, then the interior of `{x}` is empty. -/
@[simp] lemma interior_singleton (x : α) [ne_bot (𝓝[≠] x)] :
interior {x} = (∅ : set α) :=
interior_eq_empty_iff_dense_compl.2 (dense_compl_singleton x)
lemma not_is_open_singleton (x : α) [ne_bot (𝓝[≠] x)] : ¬ is_open ({x} : set α) :=
dense_compl_singleton_iff_not_open.1 (dense_compl_singleton x)
lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} :=
set.ext $ λ x, mem_closure_iff_cluster_pt
theorem mem_closure_iff_nhds {s : set α} {a : α} :
a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty :=
mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff
theorem mem_closure_iff_nhds' {s : set α} {a : α} :
a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t :=
by simp only [mem_closure_iff_nhds, set.inter_nonempty_iff_exists_right,
set_coe.exists, subtype.coe_mk]
theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} :
x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) :=
by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.inter_nonempty_iff_exists_right,
set_coe.exists, subtype.coe_mk]
theorem mem_closure_iff_nhds_basis' {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s)
{t : set α} :
a ∈ closure t ↔ ∀ i, p i → (s i ∩ t).nonempty :=
mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $
by simp only [exists_prop, forall_const]
theorem mem_closure_iff_nhds_basis {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s)
{t : set α} :
a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i :=
(mem_closure_iff_nhds_basis' h).trans $
by simp only [set.nonempty, mem_inter_iff, exists_prop, and_comm]
/-- `x` belongs to the closure of `s` if and only if some ultrafilter
supported on `s` converges to `x`. -/
lemma mem_closure_iff_ultrafilter {s : set α} {x : α} :
x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x :=
by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm]
lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s :=
calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm
... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt]
lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s :=
by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff]
lemma is_closed.interior_union_left {s t : set α} (h : is_closed s) :
interior (s ∪ t) ⊆ s ∪ interior t :=
λ a ⟨u, ⟨⟨hu₁, hu₂⟩, ha⟩⟩, (classical.em (a ∈ s)).imp_right $ λ h, mem_interior.mpr
⟨u ∩ sᶜ, λ x hx, (hu₂ hx.1).resolve_left hx.2, is_open.inter hu₁ is_closed.is_open_compl, ⟨ha, h⟩⟩
lemma is_closed.interior_union_right {s t : set α} (h : is_closed t) :
interior (s ∪ t) ⊆ interior s ∪ t :=
by simpa only [union_comm] using h.interior_union_left
lemma is_open.inter_closure {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) :=
compl_subset_compl.mp $ by simpa only [← interior_compl, compl_inter]
using is_closed.interior_union_left h.is_closed_compl
lemma is_open.closure_inter {s t : set α} (h : is_open t) : closure s ∩ t ⊆ closure (s ∩ t) :=
by simpa only [inter_comm] using h.inter_closure
lemma dense.open_subset_closure_inter {s t : set α} (hs : dense s) (ht : is_open t) :
t ⊆ closure (t ∩ s) :=
calc t = t ∩ closure s : by rw [hs.closure_eq, inter_univ]
... ⊆ closure (t ∩ s) : ht.inter_closure
lemma mem_closure_of_mem_closure_union {s₁ s₂ : set α} {x : α} (h : x ∈ closure (s₁ ∪ s₂))
(h₁ : s₁ᶜ ∈ 𝓝 x) : x ∈ closure s₂ :=
begin
rw mem_closure_iff_nhds_ne_bot at *,
rwa ← calc
𝓝 x ⊓ principal (s₁ ∪ s₂) = 𝓝 x ⊓ (principal s₁ ⊔ principal s₂) : by rw sup_principal
... = (𝓝 x ⊓ principal s₁) ⊔ (𝓝 x ⊓ principal s₂) : inf_sup_left
... = ⊥ ⊔ 𝓝 x ⊓ principal s₂ : by rw inf_principal_eq_bot.mpr h₁
... = 𝓝 x ⊓ principal s₂ : bot_sup_eq
end
/-- The intersection of an open dense set with a dense set is a dense set. -/
lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) :
dense (s ∩ t) :=
λ x, (closure_minimal hso.inter_closure is_closed_closure) $
by simp [hs.closure_eq, ht.closure_eq]
/-- The intersection of a dense set with an open dense set is a dense set. -/
lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) :
dense (s ∩ t) :=
inter_comm t s ▸ ht.inter_of_open_left hs hto
lemma dense.inter_nhds_nonempty {s t : set α} (hs : dense s) {x : α} (ht : t ∈ 𝓝 x) :
(s ∩ t).nonempty :=
let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht in
(hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ λ y hy, ⟨hy.2, hsub hy.1⟩
lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) :=
calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm]
... ⊆ closure ((closure t)ᶜ ∩ s) : (is_open_compl_iff.mpr $ is_closed_closure).inter_closure
... = closure (s \ closure t) : by simp only [diff_eq, inter_comm]
... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure
lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s)
(hs : is_closed s) : a ∈ s :=
hs.closure_subset h.mem_closure
lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s :=
(hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs
lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
[ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s :=
hs.mem_of_frequently_of_tendsto h.frequently hf
lemma mem_closure_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ closure s :=
filter.frequently.mem_closure $ hf.frequently h
lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
[ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s :=
mem_closure_of_frequently_of_tendsto h.frequently hf
/-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter.
Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/
lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β}
{a : α} (h : ∀ x ∉ s, f x = a) :
tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) :=
begin
rw [tendsto_iff_comap, tendsto_iff_comap],
replace h : 𝓟 sᶜ ≤ comap f (𝓝 a),
{ rintros U ⟨t, ht, htU⟩ x hx,
have : f x ∈ t, from (h x hx).symm ▸ mem_of_mem_nhds ht,
exact htU this },
refine ⟨λ h', _, le_trans inf_le_left⟩,
have := sup_le h' h,
rw [sup_inf_right, sup_principal, union_compl_self, principal_univ,
inf_top_eq, sup_le_iff] at this,
exact this.1
end
/-!
### Limits of filters in topological spaces
-/
section lim
/-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/
noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a
/--
If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists.
-/
def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f
/--
If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists.
Note that dot notation `F.Lim` can be used for `F : ultrafilter α`.
-/
def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F
/-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`,
if it exists. -/
noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α :=
Lim (f.map g)
/-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate
this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types
without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify
this instance with any other instance. -/
lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) :=
epsilon_spec h
/-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate
this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types
without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify
this instance with any other instance. -/
lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) :
tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) :=
le_nhds_Lim h
end lim
end topological_space
/-!
### Continuity
-/
section continuous
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables [topological_space α] [topological_space β] [topological_space γ]
open_locale topological_space
/-- A function between topological spaces is continuous if the preimage
of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/
structure continuous (f : α → β) : Prop :=
(is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s))
lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) :=
⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩
lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) :
is_open (f ⁻¹' s) :=
hf.is_open_preimage s h
lemma continuous.congr {f g : α → β} (h : continuous f) (h' : ∀ x, f x = g x) : continuous g :=
by { convert h, ext, rw h' }
/-- A function between topological spaces is continuous at a point `x₀`
if `f x` tends to `f x₀` when `x` tends to `x₀`. -/
def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x))
lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) :
tendsto f (𝓝 x) (𝓝 (f x)) :=
h
lemma continuous_at_def {f : α → β} {x : α} : continuous_at f x ↔ ∀ A ∈ 𝓝 (f x), f ⁻¹' A ∈ 𝓝 x :=
iff.rfl
lemma continuous_at_congr {f g : α → β} {x : α} (h : f =ᶠ[𝓝 x] g) :
continuous_at f x ↔ continuous_at g x :=
by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds]
lemma continuous_at.congr {f g : α → β} {x : α} (hf : continuous_at f x) (h : f =ᶠ[𝓝 x] g) :
continuous_at g x :=
(continuous_at_congr h).1 hf
lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x)
(ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x :=
h ht
lemma eventually_eq_zero_nhds {M₀} [has_zero M₀] {a : α} {f : α → M₀} :
f =ᶠ[𝓝 a] 0 ↔ a ∉ closure (function.support f) :=
by rw [← mem_compl_iff, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl
lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la)
{f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) :
cluster_pt (f x) lb :=
⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩
/-- See also `interior_preimage_subset_preimage_interior`. -/
lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β}
(hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) :=
interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf)
lemma continuous_id : continuous (id : α → α) :=
continuous_def.2 $ assume s h, h
lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) :
continuous (g ∘ f) :=
continuous_def.2 $ assume s h, (h.preimage hg).preimage hf
lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) :=
nat.rec_on n continuous_id (λ n ihn, ihn.comp h)
lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α}
(hg : continuous_at g (f x)) (hf : continuous_at f x) :
continuous_at (g ∘ f) x :=
hg.comp hf
lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) :
tendsto f (𝓝 x) (𝓝 (f x)) :=
((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $
λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩
/-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit.
E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/
lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) :
tendsto f (𝓝 x) (𝓝 y) :=
h ▸ hf.tendsto x
lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) :
continuous_at f x :=
h.tendsto x
lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x :=
⟨continuous.tendsto,
assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)),
continuous_def.2 $
assume s, assume hs : is_open s,
have ∀a, f a ∈ s → s ∈ 𝓝 (f a),
from λ a ha, is_open.mem_nhds hs ha,
show is_open (f ⁻¹' s),
from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩
lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x :=
tendsto_const_nhds
lemma continuous_const {b : β} : continuous (λa:α, b) :=
continuous_iff_continuous_at.mpr $ assume a, continuous_at_const
lemma filter.eventually_eq.continuous_at {x : α} {f : α → β} {y : β} (h : f =ᶠ[𝓝 x] (λ _, y)) :
continuous_at f x :=
(continuous_at_congr h).2 tendsto_const_nhds
lemma continuous_of_const {f : α → β} (h : ∀ x y, f x = f y) : continuous f :=
continuous_iff_continuous_at.mpr $ λ x, filter.eventually_eq.continuous_at $
eventually_of_forall (λ y, h y x)
lemma continuous_at_id {x : α} : continuous_at id x :=
continuous_id.continuous_at
lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) :
continuous_at (f^[n]) x :=
nat.rec_on n continuous_at_id $ λ n ihn,
show continuous_at (f^[n] ∘ f) x,
from continuous_at.comp (hx.symm ▸ ihn) hf
lemma continuous_iff_is_closed {f : α → β} :
continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) :=
⟨assume hf s hs, by simpa using (continuous_def.1 hf sᶜ hs.is_open_compl).is_closed_compl,
assume hf, continuous_def.2 $ assume s,
by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩
lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) :
is_closed (f ⁻¹' s) :=
continuous_iff_is_closed.mp hf s h
lemma mem_closure_image {f : α → β} {x : α} {s : set α} (hf : continuous_at f x)
(hx : x ∈ closure s) : f x ∈ closure (f '' s) :=
mem_closure_of_frequently_of_tendsto
((mem_closure_iff_frequently.1 hx).mono (λ x, mem_image_of_mem _)) hf
lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔
∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) :=
tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x))
lemma continuous_iff_ultrafilter {f : α → β} :
continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) :=
by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter]
lemma continuous.closure_preimage_subset {f : α → β}
(hf : continuous f) (t : set β) :
closure (f ⁻¹' t) ⊆ f ⁻¹' (closure t) :=
begin
rw ← (is_closed_closure.preimage hf).closure_eq,
exact closure_mono (preimage_mono subset_closure),
end
lemma continuous.frontier_preimage_subset
{f : α → β} (hf : continuous f) (t : set β) :
frontier (f ⁻¹' t) ⊆ f ⁻¹' (frontier t) :=
diff_subset_diff (hf.closure_preimage_subset t) (preimage_interior_subset_interior_preimage hf)
/-! ### Continuity and partial functions -/
/-- Continuity of a partial function -/
def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s)
lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom :=
by rw [←pfun.preimage_univ]; exact h _ is_open_univ
lemma pcontinuous_iff' {f : α →. β} :
pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) :=
begin
split,
{ intros h x y h',
simp only [ptendsto'_def, mem_nhds_iff],
rintros s ⟨t, tsubs, opent, yt⟩,
exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ },
intros hf s os,
rw is_open_iff_nhds,
rintros x ⟨y, ys, fxy⟩ t,
rw [mem_principal],
assume h : f.preimage s ⊆ t,
change t ∈ 𝓝 x,
apply mem_of_superset _ h,
have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x,
{ intros s hs,
have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy,
rw ptendsto'_def at this,
exact this s hs },
show f.preimage s ∈ 𝓝 x,
apply h', rw mem_nhds_iff, exact ⟨s, set.subset.refl _, os, ys⟩
end
/-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/
lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t)
(hc : continuous f) : maps_to f (closure s) (closure t) :=
begin
simp only [maps_to, mem_closure_iff_cluster_pt],
exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h)
end
lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) :
f '' closure s ⊆ closure (f '' s) :=
((maps_to_image f s).closure h).image_subset
lemma closure_subset_preimage_closure_image {f : α → β} {s : set α} (h : continuous f) :
closure s ⊆ f ⁻¹' (closure (f '' s)) :=
by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h }
lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α}
(hf : continuous f) (ha : a ∈ closure s) (ht : maps_to f s t) : f a ∈ closure t :=
ht.closure hf ha
/-- If a continuous map `f` maps `s` to a closed set `t`, then it maps `closure s` to `t`. -/
lemma set.maps_to.closure_left {s : set α} {t : set β} {f : α → β} (h : maps_to f s t)
(hc : continuous f) (ht : is_closed t) : maps_to f (closure s) t :=
ht.closure_eq ▸ h.closure hc
/-!
### Function with dense range
-/
section dense_range
variables {κ ι : Type*} (f : κ → β) (g : β → γ)
/-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/
def dense_range := dense (range f)
variables {f}
/-- A surjective map has dense range. -/
lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f :=
λ x, by simp [hf.range_eq]
lemma dense_range_id : dense_range (id : α → α) :=
function.surjective.dense_range function.surjective_id
lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ :=
dense_iff_closure_eq
lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ :=
h.closure_eq
lemma dense.dense_range_coe {s : set α} (h : dense s) : dense_range (coe : s → α) :=
by simpa only [dense_range, subtype.range_coe_subtype]
lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f)
{s : set α} (hs : dense s) :
range f ⊆ closure (f '' s) :=
by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf }
/-- The image of a dense set under a continuous map with dense range is a dense set. -/
lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f)
{s : set α} (hs : dense s) :
dense (f '' s) :=
(hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure
/-- If `f` has dense range and `s` is an open set in the codomain of `f`, then the image of the
preimage of `s` under `f` is dense in `s`. -/
lemma dense_range.subset_closure_image_preimage_of_is_open (hf : dense_range f) {s : set β}
(hs : is_open s) : s ⊆ closure (f '' (f ⁻¹' s)) :=
by { rw image_preimage_eq_inter_range, exact hf.open_subset_closure_inter hs }
/-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense
set. -/
lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f)
{s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) :
dense t :=
(hf'.dense_image hf hs).mono ht.image_subset
/-- Composition of a continuous map with dense range and a function with dense range has dense
range. -/
lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f)
(cg : continuous g) :
dense_range (g ∘ f) :=
by { rw [dense_range, range_comp], exact hg.dense_image cg hf }
lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β :=
range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff
lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ :=
hf.nonempty_iff.mpr h
/-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/
def dense_range.some (hf : dense_range f) (b : β) : κ :=
classical.choice $ hf.nonempty_iff.mpr ⟨b⟩
lemma dense_range.exists_mem_open (hf : dense_range f) {s : set β} (ho : is_open s)
(hs : s.nonempty) :
∃ a, f a ∈ s :=
exists_range_iff.1 $ hf.exists_mem_open ho hs
lemma dense_range.mem_nhds {f : κ → β} (h : dense_range f) {b : β} {U : set β}
(U_in : U ∈ 𝓝 b) : ∃ a, f a ∈ U :=
let ⟨a, ha⟩ := h.exists_mem_open is_open_interior ⟨b, mem_interior_iff_mem_nhds.2 U_in⟩
in ⟨a, interior_subset ha⟩
end dense_range
end continuous
/--
The library contains many lemmas stating that functions/operations are continuous. There are many
ways to formulate the continuity of operations. Some are more convenient than others.
Note: for the most part this note also applies to other properties
(`measurable`, `differentiable`, `continuous_on`, ...).
### The traditional way
As an example, let's look at addition `(+) : M → M → M`. We can state that this is continuous
in different definitionally equal ways (omitting some typing information)
* `continuous (λ p, p.1 + p.2)`;
* `continuous (function.uncurry (+))`;
* `continuous ↿(+)`. (`↿` is notation for recursively uncurrying a function)
However, lemmas with this conclusion are not nice to use in practice because
1. They confuse the elaborator. The following two examples fail, because of limitations in the
elaboration process.
```
variables {M : Type*} [has_add M] [topological_space M] [has_continuous_add M]
example : continuous (λ x : M, x + x) :=
continuous_add.comp _
example : continuous (λ x : M, x + x) :=
continuous_add.comp (continuous_id.prod_mk continuous_id)
```
The second is a valid proof, which is accepted if you write it as
`continuous_add.comp (continuous_id.prod_mk continuous_id : _)`
2. If the operation has more than 2 arguments, they are impractical to use, because in your
application the arguments in the domain might be in a different order or associated differently.
### The convenient way
A much more convenient way to write continuity lemmas is like `continuous.add`:
```
continuous.add {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λ x, f x + g x)
```
The conclusion can be `continuous (f + g)`, which is definitionally equal.
This has the following advantages
* It supports projection notation, so is shorter to write.
* `continuous.add _ _` is recognized correctly by the elaborator and gives useful new goals.
* It works generally, since the domain is a variable.
As an example for an unary operation, we have `continuous.neg`.
```
continuous.neg {f : α → G} (hf : continuous f) : continuous (λ x, -f x)
```
For unary functions, the elaborator is not confused when applying the traditional lemma
(like `continuous_neg`), but it's still convenient to have the short version available (compare
`hf.neg.neg.neg` with `continuous_neg.comp $ continuous_neg.comp $ continuous_neg.comp hf`).
As a harder example, consider an operation of the following type:
```
def strans {x : F} (γ γ' : path x x) (t₀ : I) : path x x
```
The precise definition is not important, only its type.
The correct continuity principle for this operation is something like this:
```
{f : X → F} {γ γ' : ∀ x, path (f x) (f x)} {t₀ s : X → I}
(hγ : continuous ↿γ) (hγ' : continuous ↿γ')
(ht : continuous t₀) (hs : continuous s) :
continuous (λ x, strans (γ x) (γ' x) (t x) (s x))
```
Note that *all* arguments of `strans` are indexed over `X`, even the basepoint `x`, and the last
argument `s` that arises since `path x x` has a coercion to `I → F`. The paths `γ` and `γ'` (which
are unary functions from `I`) become binary functions in the continuity lemma.
### Summary
* Make sure that your continuity lemmas are stated in the most general way, and in a convenient
form. That means that:
- The conclusion has a variable `X` as domain (not something like `Y × Z`);
- Wherever possible, all point arguments `c : Y` are replaced by functions `c : X → Y`;
- All `n`-ary function arguments are replaced by `n+1`-ary functions
(`f : Y → Z` becomes `f : X → Y → Z`);
- All (relevant) arguments have continuity assumptions, and perhaps there are additional
assumptions needed to make the operation continuous;
- The function in the conclusion is fully applied.
* These remarks are mostly about the format of the *conclusion* of a continuity lemma.
In assumptions it's fine to state that a function with more than 1 argument is continuous using
`↿` or `function.uncurry`.
### Functions with discontinuities
In some cases, you want to work with discontinuous functions, and in certain expressions they are
still continuous. For example, consider the fractional part of a number, `fract : ℝ → ℝ`.
In this case, you want to add conditions to when a function involving `fract` is continuous, so you
get something like this: (assumption `hf` could be weakened, but the important thing is the shape
of the conclusion)
```
lemma continuous_on.comp_fract {X Y : Type*} [topological_space X] [topological_space Y]
{f : X → ℝ → Y} {g : X → ℝ} (hf : continuous ↿f) (hg : continuous g) (h : ∀ s, f s 0 = f s 1) :
continuous (λ x, f x (fract (g x)))
```
With `continuous_at` you can be even more precise about what to prove in case of discontinuities,
see e.g. `continuous_at.comp_div_cases`.
-/
library_note "continuity lemma statement"
|
2c98dbf9aace601d720471eaab558d06db4b7ace | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/group/with_one.lean | 4cdb8f471280272db10a9d766b43b173da2eaf46 | [
"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 | 8,751 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johan Commelin
-/
import algebra.ring.basic
import data.equiv.basic
/-!
# Adjoining a zero/one to semigroups and related algebraic structures
This file contains different results about adjoining an element to an algebraic structure which then
behaves like a zero or a one. An example is adjoining a one to a semigroup to obtain a monoid. That
this provides an example of an adjunction is proved in `algebra.category.Mon.adjunctions`.
Another result says that adjoining to a group an element `zero` gives a `group_with_zero`. For more
information about these structures (which are not that standard in informal mathematics, see
`algebra.group_with_zero.basic`)
-/
universes u v w
variable {α : Type u}
/-- Add an extra element `1` to a type -/
@[to_additive "Add an extra element `0` to a type"]
def with_one (α) := option α
namespace with_one
@[to_additive]
instance : monad with_one := option.monad
@[to_additive]
instance : has_one (with_one α) := ⟨none⟩
@[to_additive]
instance : inhabited (with_one α) := ⟨1⟩
@[to_additive]
instance [nonempty α] : nontrivial (with_one α) := option.nontrivial
@[to_additive]
instance : has_coe_t α (with_one α) := ⟨some⟩
@[to_additive]
lemma some_eq_coe {a : α} : (some a : with_one α) = ↑a := rfl
@[simp, to_additive]
lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) :=
option.some_ne_none a
@[simp, to_additive]
lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a :=
coe_ne_one.symm
@[to_additive]
lemma ne_one_iff_exists {x : with_one α} : x ≠ 1 ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
-- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work
-- unless we explicitly define this instance
instance : can_lift (with_one α) α :=
{ coe := coe,
cond := λ a, a ≠ 1,
prf := λ a, ne_one_iff_exists.1 }
@[simp, to_additive]
lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b :=
option.some_inj
attribute [norm_cast] coe_inj with_zero.coe_inj
@[elab_as_eliminator, to_additive]
protected lemma cases_on {P : with_one α → Prop} :
∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x :=
option.cases_on
@[to_additive]
instance [has_mul α] : has_mul (with_one α) :=
{ mul := option.lift_or_get (*) }
@[to_additive]
instance [semigroup α] : monoid (with_one α) :=
{ mul_assoc := (option.lift_or_get_assoc _).1,
one_mul := (option.lift_or_get_is_left_id _).1,
mul_one := (option.lift_or_get_is_right_id _).1,
..with_one.has_one,
..with_one.has_mul }
@[to_additive]
instance [comm_semigroup α] : comm_monoid (with_one α) :=
{ mul_comm := (option.lift_or_get_comm _).1,
..with_one.monoid }
/-- `coe` as a bundled morphism -/
@[to_additive "`coe` as a bundled morphism", simps apply]
def coe_mul_hom [has_mul α] : mul_hom α (with_one α) :=
{ to_fun := coe, map_mul' := λ x y, rfl }
section lift
variables [semigroup α] {β : Type v} [monoid β]
/-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. -/
@[to_additive "Lift an add_semigroup homomorphism `f` to a bundled add_monoid homorphism."]
def lift : mul_hom α β ≃ (with_one α →* β) :=
{ to_fun := λ f,
{ to_fun := λ x, option.cases_on x 1 f,
map_one' := rfl,
map_mul' := λ x y,
with_one.cases_on x (by { rw one_mul, exact (one_mul _).symm }) $ λ x,
with_one.cases_on y (by { rw mul_one, exact (mul_one _).symm }) $ λ y,
f.map_mul x y },
inv_fun := λ F, F.to_mul_hom.comp coe_mul_hom,
left_inv := λ f, mul_hom.ext $ λ x, rfl,
right_inv := λ F, monoid_hom.ext $ λ x, with_one.cases_on x F.map_one.symm $ λ x, rfl }
variables (f : mul_hom α β)
@[simp, to_additive]
lemma lift_coe (x : α) : lift f x = f x := rfl
@[simp, to_additive]
lemma lift_one : lift f 1 = 1 := rfl
@[to_additive]
theorem lift_unique (f : with_one α →* β) : f = lift (f.to_mul_hom.comp coe_mul_hom) :=
(lift.apply_symm_apply f).symm
end lift
section map
variables {β : Type v} [semigroup α] [semigroup β]
/-- Given a multiplicative map from `α → β` returns a monoid homomorphism
from `with_one α` to `with_one β` -/
@[to_additive "Given an additive map from `α → β` returns an add_monoid homomorphism
from `with_zero α` to `with_zero β`"]
def map (f : mul_hom α β) : with_one α →* with_one β :=
lift (coe_mul_hom.comp f)
@[simp, to_additive]
lemma map_id : map (mul_hom.id α) = monoid_hom.id (with_one α) :=
by { ext, cases x; refl }
@[simp, to_additive]
lemma map_comp {γ : Type w} [semigroup γ] (f : mul_hom α β) (g : mul_hom β γ) :
map (g.comp f) = (map g).comp (map f) :=
by { ext, cases x; refl }
end map
attribute [irreducible] with_one
@[simp, norm_cast, to_additive]
lemma coe_mul [has_mul α] (a b : α) : ((a * b : α) : with_one α) = a * b := rfl
end with_one
namespace with_zero
-- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work
-- unless we explicitly define this instance
instance : can_lift (with_zero α) α :=
{ coe := coe,
cond := λ a, a ≠ 0,
prf := λ a, ne_zero_iff_exists.1 }
attribute [to_additive] with_one.can_lift
instance [one : has_one α] : has_one (with_zero α) :=
{ ..one }
@[simp, norm_cast] lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl
instance [has_mul α] : mul_zero_class (with_zero α) :=
{ mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂),
zero_mul := λ a, rfl,
mul_zero := λ a, by cases a; refl,
..with_zero.has_zero }
@[simp, norm_cast] lemma coe_mul {α : Type u} [has_mul α]
{a b : α} : ((a * b : α) : with_zero α) = a * b := rfl
@[simp] lemma zero_mul {α : Type u} [has_mul α]
(a : with_zero α) : 0 * a = 0 := rfl
@[simp] lemma mul_zero {α : Type u} [has_mul α]
(a : with_zero α) : a * 0 = 0 := by cases a; refl
instance [semigroup α] : semigroup (with_zero α) :=
{ mul_assoc := λ a b c, match a, b, c with
| none, _, _ := rfl
| some a, none, _ := rfl
| some a, some b, none := rfl
| some a, some b, some c := congr_arg some (mul_assoc _ _ _)
end,
..with_zero.mul_zero_class }
instance [comm_semigroup α] : comm_semigroup (with_zero α) :=
{ mul_comm := λ a b, match a, b with
| none, _ := (mul_zero _).symm
| some a, none := rfl
| some a, some b := congr_arg some (mul_comm _ _)
end,
..with_zero.semigroup }
instance [monoid α] : monoid_with_zero (with_zero α) :=
{ one_mul := λ a, match a with
| none := rfl
| some a := congr_arg some $ one_mul _
end,
mul_one := λ a, match a with
| none := rfl
| some a := congr_arg some $ mul_one _
end,
..with_zero.mul_zero_class,
..with_zero.has_one,
..with_zero.semigroup }
instance [comm_monoid α] : comm_monoid_with_zero (with_zero α) :=
{ ..with_zero.monoid_with_zero, ..with_zero.comm_semigroup }
/-- Given an inverse operation on `α` there is an inverse operation
on `with_zero α` sending `0` to `0`-/
definition inv [has_inv α] (x : with_zero α) : with_zero α :=
do a ← x, return a⁻¹
instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩
@[simp, norm_cast] lemma coe_inv [has_inv α] (a : α) :
((a⁻¹ : α) : with_zero α) = a⁻¹ := rfl
@[simp] lemma inv_zero [has_inv α] :
(0 : with_zero α)⁻¹ = 0 := rfl
section group
variables [group α]
@[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 :=
show ((1⁻¹ : α) : with_zero α) = 1, by simp
/-- if `G` is a group then `with_zero G` is a group with zero. -/
instance : group_with_zero (with_zero α) :=
{ inv_zero := inv_zero,
mul_inv_cancel := by { intros a ha, lift a to α using ha, norm_cast, apply mul_right_inv },
.. with_zero.monoid_with_zero,
.. with_zero.has_inv,
.. with_zero.nontrivial }
@[norm_cast]
lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl
end group
instance [comm_group α] : comm_group_with_zero (with_zero α) :=
{ .. with_zero.group_with_zero, .. with_zero.comm_monoid_with_zero }
instance [semiring α] : semiring (with_zero α) :=
{ left_distrib := λ a b c, begin
cases a with a, {refl},
cases b with b; cases c with c; try {refl},
exact congr_arg some (left_distrib _ _ _)
end,
right_distrib := λ a b c, begin
cases c with c,
{ change (a + b) * 0 = a * 0 + b * 0, simp },
cases a with a; cases b with b; try {refl},
exact congr_arg some (right_distrib _ _ _)
end,
..with_zero.add_comm_monoid,
..with_zero.mul_zero_class,
..with_zero.monoid_with_zero }
attribute [irreducible] with_zero
end with_zero
|
1f42def54ab12f065b5cde25c54600ffdced60f1 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/measure_theory/simple_func_dense.lean | f7218f1c43ed202340e4e4733ae21228584d85e6 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,472 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import measure_theory.l1_space
/-!
# Density of simple functions
Show that each Borel measurable function can be approximated,
both pointwise and in `L¹` norm, by a sequence of simple functions.
## Main definitions
* `measure_theory.simple_func.nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ ℕ`: the `simple_func` sending
each `x : α` to the point `e k` which is the nearest to `x` among `e 0`, ..., `e N`.
* `measure_theory.simple_func.approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α)
(h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : β →ₛ α` : a simple function that takes values in `s`
and approximates `f`. If `f x ∈ s`, then `measure_theory.simple_func.approx_on f hf s y₀ h₀ n x`
tends to `f x` as `n` tends to `∞`. If `α` is a `normed_group`, `f x - y₀`
is `measure_theory.integrable`, and `f x ∈ s` for a.e. `x`, then
`simple_func.approx_on f hf s y₀ h₀ n` tends to `f` in `L₁`. The main use case is `s = univ`,
`y₀ = 0`.
## Notations
* `α →ₛ β` (local notation): the type of simple functions `α → β`.
-/
open set filter topological_space
open_locale classical topological_space
variables {α β ι E : Type*}
namespace measure_theory
open ennreal emetric
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
variables [measurable_space α] [emetric_space α] [opens_measurable_space α]
/-- `nearest_pt_ind e N x` is the index `k` such that `e k` is the nearest point to `x` among the
points `e 0`, ..., `e N`. If more than one point are at the same distance from `x`, then
`nearest_pt_ind e N x` returns the least of their indexes. -/
noncomputable def nearest_pt_ind (e : ℕ → α) : ℕ → α →ₛ ℕ
| 0 := const α 0
| (N + 1) := piecewise (⋂ k ≤ N, {x | edist (e (N + 1)) x < edist (e k) x})
(is_measurable.Inter $ λ k, is_measurable.Inter_Prop $ λ hk,
is_measurable_lt measurable_edist_right measurable_edist_right)
(const α $ N + 1) (nearest_pt_ind N)
/-- `nearest_pt e N x` is the nearest point to `x` among the points `e 0`, ..., `e N`. If more than
one point are at the same distance from `x`, then `nearest_pt e N x` returns the point with the
least possible index. -/
noncomputable def nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ α :=
(nearest_pt_ind e N).map e
@[simp] lemma nearest_pt_ind_zero (e : ℕ → α) : nearest_pt_ind e 0 = const α 0 := rfl
@[simp] lemma nearest_pt_zero (e : ℕ → α) : nearest_pt e 0 = const α (e 0) := rfl
lemma nearest_pt_ind_succ (e : ℕ → α) (N : ℕ) (x : α) :
nearest_pt_ind e (N + 1) x =
if ∀ k ≤ N, edist (e (N + 1)) x < edist (e k) x
then N + 1 else nearest_pt_ind e N x :=
by { simp only [nearest_pt_ind, coe_piecewise, set.piecewise], congr, simp }
lemma nearest_pt_ind_le (e : ℕ → α) (N : ℕ) (x : α) : nearest_pt_ind e N x ≤ N :=
begin
induction N with N ihN, { simp },
simp only [nearest_pt_ind_succ],
split_ifs,
exacts [le_rfl, ihN.trans N.le_succ]
end
lemma edist_nearest_pt_le (e : ℕ → α) (x : α) {k N : ℕ} (hk : k ≤ N) :
edist (nearest_pt e N x) x ≤ edist (e k) x :=
begin
induction N with N ihN generalizing k,
{ simp [le_zero_iff_eq.1 hk, le_refl] },
{ simp only [nearest_pt, nearest_pt_ind_succ, map_apply],
split_ifs,
{ rcases hk.eq_or_lt with rfl|hk,
exacts [le_rfl, (h k (nat.lt_succ_iff.1 hk)).le] },
{ push_neg at h,
rcases h with ⟨l, hlN, hxl⟩,
rcases hk.eq_or_lt with rfl|hk,
exacts [(ihN hlN).trans hxl, ihN (nat.lt_succ_iff.1 hk)] } }
end
lemma tendsto_nearest_pt {e : ℕ → α} {x : α} (hx : x ∈ closure (range e)) :
tendsto (λ N, nearest_pt e N x) at_top (𝓝 x) :=
begin
refine (at_top_basis.tendsto_iff nhds_basis_eball).2 (λ ε hε, _),
rcases emetric.mem_closure_iff.1 hx ε hε with ⟨_, ⟨N, rfl⟩, hN⟩,
rw [edist_comm] at hN,
exact ⟨N, trivial, λ n hn, (edist_nearest_pt_le e x hn).trans_lt hN⟩
end
variables [measurable_space β] {f : β → α}
/-- Approximate a measurable function by a sequence of simple functions `F n` such that
`F n x ∈ s`. -/
noncomputable def approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α) (h₀ : y₀ ∈ s)
[separable_space s] (n : ℕ) :
β →ₛ α :=
by haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩;
exact comp (nearest_pt (λ k, nat.cases_on k y₀ (coe ∘ dense_seq s) : ℕ → α) n) f hf
@[simp] lemma approx_on_zero {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] (x : β) :
approx_on f hf s y₀ h₀ 0 x = y₀ :=
rfl
lemma approx_on_mem {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] (n : ℕ) (x : β) :
approx_on f hf s y₀ h₀ n x ∈ s :=
begin
haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩,
suffices : ∀ n, (nat.cases_on n y₀ (coe ∘ dense_seq s) : α) ∈ s, { apply this },
rintro (_|n),
exacts [h₀, subtype.mem _]
end
@[simp] lemma approx_on_comp {γ : Type*} [measurable_space γ] {f : β → α} (hf : measurable f)
{g : γ → β} (hg : measurable g) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) :
approx_on (f ∘ g) (hf.comp hg) s y₀ h₀ n = (approx_on f hf s y₀ h₀ n).comp g hg :=
rfl
lemma tendsto_approx_on {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] {x : β} (hx : f x ∈ closure s) :
tendsto (λ n, approx_on f hf s y₀ h₀ n x) at_top (𝓝 $ f x) :=
begin
haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩,
rw [← @subtype.range_coe _ s, ← image_univ, ← dense_seq_dense s] at hx,
simp only [approx_on, coe_comp],
refine tendsto_nearest_pt (closure_minimal _ is_closed_closure hx),
simp only [nat.range_cases_on, closure_union, range_comp coe],
exact subset.trans (image_closure_subset_closure_image continuous_subtype_coe)
(subset_union_right _ _)
end
lemma edist_approx_on_le {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] (x : β) (n : ℕ) :
edist (approx_on f hf s y₀ h₀ n x) (f x) ≤ edist y₀ (f x) :=
begin
dsimp only [approx_on, coe_comp, (∘)],
exact edist_nearest_pt_le _ _ (zero_le _)
end
lemma edist_approx_on_y0_le {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] (x : β) (n : ℕ) :
edist y₀ (approx_on f hf s y₀ h₀ n x) ≤ edist y₀ (f x) + edist y₀ (f x) :=
calc edist y₀ (approx_on f hf s y₀ h₀ n x) ≤
edist y₀ (f x) + edist (approx_on f hf s y₀ h₀ n x) (f x) : edist_triangle_right _ _ _
... ≤ edist y₀ (f x) + edist y₀ (f x) : add_le_add_left (edist_approx_on_le hf h₀ x n) _
variables [measurable_space E] [normed_group E]
lemma norm_approx_on_zero_le [opens_measurable_space E] {f : β → E} (hf : measurable f)
{s : set E} (h₀ : (0 : E) ∈ s) [separable_space s] (x : β) (n : ℕ) :
∥approx_on f hf s 0 h₀ n x∥ ≤ ∥f x∥ + ∥f x∥ :=
begin
have := edist_approx_on_y0_le hf h₀ x n,
simp [edist_comm (0 : E), edist_eq_coe_nnnorm] at this,
exact_mod_cast this,
end
lemma tendsto_approx_on_l1_edist [opens_measurable_space E]
{f : β → E} (hf : measurable f) {s : set E} {y₀ : E} (h₀ : y₀ ∈ s) [separable_space s]
{μ : measure β} (hμ : ∀ᵐ x ∂μ, f x ∈ closure s) (hi : has_finite_integral (λ x, f x - y₀) μ) :
tendsto (λ n, ∫⁻ x, edist (approx_on f hf s y₀ h₀ n x) (f x) ∂μ) at_top (𝓝 0) :=
begin
simp only [has_finite_integral, ← nndist_eq_nnnorm, ← edist_nndist, ← edist_comm y₀] at hi,
have : ∀ n, measurable (λ x, edist (approx_on f hf s y₀ h₀ n x) (f x)) :=
λ n, (approx_on f hf s y₀ h₀ n).measurable_bind (λ y x, edist y (f x))
(λ y, measurable_edist_right.comp hf),
convert tendsto_lintegral_of_dominated_convergence _ this
(λ n, eventually_of_forall $ λ x, edist_approx_on_le hf h₀ x n) hi (hμ.mono $ λ x hx, _),
show tendsto (λ n, edist _ (f x)) at_top (𝓝 $ edist (f x) (f x)),
from (tendsto_approx_on hf h₀ hx).edist tendsto_const_nhds,
simp
end
lemma integrable_approx_on [borel_space E]
{f : β → E} {μ : measure β} (hf : integrable f μ) {s : set E} {y₀ : E} (h₀ : y₀ ∈ s)
[separable_space s] (hi₀ : integrable (λ x, y₀) μ) (n : ℕ) :
integrable (approx_on f hf.1 s y₀ h₀ n) μ :=
begin
refine ⟨(approx_on f hf.1 s y₀ h₀ n).measurable, _⟩,
suffices : integrable (λ x, approx_on f hf.1 s y₀ h₀ n x - y₀) μ,
{ convert this.add' hi₀, ext1 x, simp },
refine ⟨(approx_on f hf.1 s y₀ h₀ n - const β y₀).measurable, _⟩,
have hi := hf.sub' hi₀,
simp only [has_finite_integral, ← nndist_eq_nnnorm, ← edist_nndist, edist_comm _ y₀,
pi.sub_apply] at hi ⊢,
have : measurable (λ x, edist y₀ (f x)) := measurable_edist_right.comp hf.1,
calc ∫⁻ x, edist y₀ (approx_on f hf.1 s y₀ h₀ n x) ∂μ ≤ ∫⁻ x, edist y₀ (f x) + edist y₀ (f x) ∂μ :
measure_theory.lintegral_mono (λ x, edist_approx_on_y0_le hf.1 h₀ x n)
... = ∫⁻ x, edist y₀ (f x) ∂μ + ∫⁻ x, edist y₀ (f x) ∂μ :
measure_theory.lintegral_add this this
... < ⊤ :
add_lt_top.2 ⟨hi, hi⟩
end
lemma tendsto_approx_on_univ_l1_edist [opens_measurable_space E] [second_countable_topology E]
{f : β → E} {μ : measure β} (hf : integrable f μ) :
tendsto (λ n, ∫⁻ x, edist (approx_on f hf.1 univ 0 trivial n x) (f x) ∂μ) at_top (𝓝 0) :=
tendsto_approx_on_l1_edist hf.1 trivial (by simp) (by simpa using hf.2)
lemma integrable_approx_on_univ [borel_space E] [second_countable_topology E]
{f : β → E} {μ : measure β} (hf : integrable f μ) (n : ℕ) :
integrable (approx_on f hf.1 univ 0 trivial n) μ :=
integrable_approx_on hf _ (integrable_zero _ _ _) n
lemma tendsto_approx_on_univ_l1 [borel_space E] [second_countable_topology E]
{f : β → E} {μ : measure β} (hf : integrable f μ) :
tendsto (λ n, l1.of_fun (approx_on f hf.1 univ 0 trivial n) (integrable_approx_on_univ hf n))
at_top (𝓝 $ l1.of_fun f hf) :=
tendsto_iff_edist_tendsto_0.2 $ tendsto_approx_on_univ_l1_edist hf
end simple_func
end measure_theory
|
f15f16e7573f98936f1a014031a4c01852752672 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/normed_space/banach.lean | d79e9f0034c05c7664fb43f36154840360a0852a | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,406 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.metric_space.baire
import Mathlib.analysis.normed_space.operator_norm
import Mathlib.PostPort
universes u_1 u_2 u_3
namespace Mathlib
/-!
# 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.
-/
/--
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. -/
theorem exists_approx_preimage_norm_le {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (f : continuous_linear_map 𝕜 E F) [complete_space F] (surj : function.surjective ⇑f) : ∃ (C : ℝ), ∃ (H : C ≥ 0), ∀ (y : F), ∃ (x : E), dist (coe_fn f x) y ≤ 1 / bit0 1 * norm y ∧ norm x ≤ C * norm y := sorry
/-- 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 {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (f : continuous_linear_map 𝕜 E F) [complete_space F] [complete_space E] (surj : function.surjective ⇑f) : ∃ (C : ℝ), ∃ (H : C > 0), ∀ (y : F), ∃ (x : E), coe_fn f x = y ∧ norm x ≤ C * norm y := sorry
/-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is
open. -/
theorem open_mapping {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (f : continuous_linear_map 𝕜 E F) [complete_space F] [complete_space E] (surj : function.surjective ⇑f) : is_open_map ⇑f := sorry
namespace linear_equiv
/-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/
theorem continuous_symm {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] [complete_space F] [complete_space E] (e : linear_equiv 𝕜 E F) (h : continuous ⇑e) : continuous ⇑(symm e) := sorry
/-- 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 {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] [complete_space F] [complete_space E] (e : linear_equiv 𝕜 E F) (h : continuous ⇑e) : continuous_linear_equiv 𝕜 E F :=
continuous_linear_equiv.mk (mk (to_fun e) sorry sorry (inv_fun e) sorry sorry)
@[simp] theorem coe_fn_to_continuous_linear_equiv_of_continuous {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] [complete_space F] [complete_space E] (e : linear_equiv 𝕜 E F) (h : continuous ⇑e) : ⇑(to_continuous_linear_equiv_of_continuous e h) = ⇑e :=
rfl
@[simp] theorem coe_fn_to_continuous_linear_equiv_of_continuous_symm {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] [complete_space F] [complete_space E] (e : linear_equiv 𝕜 E F) (h : continuous ⇑e) : ⇑(continuous_linear_equiv.symm (to_continuous_linear_equiv_of_continuous e h)) = ⇑(symm e) :=
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. -/
def of_bijective {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] [complete_space F] [complete_space E] (f : continuous_linear_map 𝕜 E F) (hinj : continuous_linear_map.ker f = ⊥) (hsurj : continuous_linear_map.range f = ⊤) : continuous_linear_equiv 𝕜 E F :=
linear_equiv.to_continuous_linear_equiv_of_continuous (linear_equiv.of_bijective (↑f) hinj hsurj) sorry
@[simp] theorem coe_fn_of_bijective {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] [complete_space F] [complete_space E] (f : continuous_linear_map 𝕜 E F) (hinj : continuous_linear_map.ker f = ⊥) (hsurj : continuous_linear_map.range f = ⊤) : ⇑(of_bijective f hinj hsurj) = ⇑f :=
rfl
@[simp] theorem of_bijective_symm_apply_apply {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] [complete_space F] [complete_space E] (f : continuous_linear_map 𝕜 E F) (hinj : continuous_linear_map.ker f = ⊥) (hsurj : continuous_linear_map.range f = ⊤) (x : E) : coe_fn (continuous_linear_equiv.symm (of_bijective f hinj hsurj)) (coe_fn f x) = x :=
symm_apply_apply (of_bijective f hinj hsurj) x
@[simp] theorem of_bijective_apply_symm_apply {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] [complete_space F] [complete_space E] (f : continuous_linear_map 𝕜 E F) (hinj : continuous_linear_map.ker f = ⊥) (hsurj : continuous_linear_map.range f = ⊤) (y : F) : coe_fn f (coe_fn (continuous_linear_equiv.symm (of_bijective f hinj hsurj)) y) = y :=
apply_symm_apply (of_bijective f hinj hsurj) y
|
cbc8ddcb674cb7f125e42fbcc7a7b9da9f13cc6c | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/analysis/convex/caratheodory.lean | 730b1744a1d0698294a13e913a64c3357e5752c6 | [
"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 | 9,627 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Scott Morrison
-/
import analysis.convex.basic
import linear_algebra.finite_dimensional
/-!
# Carathéodory's convexity theorem
This file is devoted to proving Carathéodory's convexity theorem:
The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`.
## Main results:
* `convex_hull_eq_union`: Carathéodory's convexity theorem
## Implementation details
This theorem was formalized as part of the Sphere Eversion project.
## Tags
convex hull, caratheodory
-/
universes u
open set finset finite_dimensional
open_locale big_operators
variables {E : Type u} [add_comm_group E] [vector_space ℝ E] [finite_dimensional ℝ E]
namespace caratheodory
/--
If `x` is in the convex hull of some finset `t` with strictly more than `findim + 1` elements,
then it is in the union of the convex hulls of the finsets `t.erase y` for `y ∈ t`.
-/
lemma mem_convex_hull_erase [decidable_eq E] {t : finset E} (h : findim ℝ E + 1 < t.card)
{x : E} (m : x ∈ convex_hull (↑t : set E)) :
∃ (y : (↑t : set E)), x ∈ convex_hull (↑(t.erase y) : set E) :=
begin
simp only [finset.convex_hull_eq, mem_set_of_eq] at m ⊢,
obtain ⟨f, fpos, fsum, rfl⟩ := m,
obtain ⟨g, gcombo, gsum, gpos⟩ := exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card h,
clear h,
let s := t.filter (λ z : E, 0 < g z),
obtain ⟨i₀, mem, w⟩ : ∃ i₀ ∈ s, ∀ i ∈ s, f i₀ / g i₀ ≤ f i / g i,
{ apply s.exists_min_image (λ z, f z / g z),
obtain ⟨x, hx, hgx⟩ : ∃ x ∈ t, 0 < g x := gpos,
exact ⟨x, mem_filter.mpr ⟨hx, hgx⟩⟩, },
have hg : 0 < g i₀ := by { rw mem_filter at mem, exact mem.2 },
have hi₀ : i₀ ∈ t := filter_subset _ mem,
let k : E → ℝ := λ z, f z - (f i₀ / g i₀) * g z,
have hk : k i₀ = 0 := by field_simp [k, ne_of_gt hg],
have ksum : ∑ e in t.erase i₀, k e = 1,
{ calc ∑ e in t.erase i₀, k e = ∑ e in t, k e :
by conv_rhs { rw [← insert_erase hi₀, sum_insert (not_mem_erase i₀ t), hk, zero_add], }
... = ∑ e in t, (f e - f i₀ / g i₀ * g e) : rfl
... = 1 : by rw [sum_sub_distrib, fsum, ← mul_sum, gsum, mul_zero, sub_zero] },
refine ⟨⟨i₀, hi₀⟩, k, _, ksum, _⟩,
{ simp only [and_imp, sub_nonneg, mem_erase, ne.def, subtype.coe_mk],
intros e hei₀ het,
by_cases hes : e ∈ s,
{ have hge : 0 < g e := by { rw mem_filter at hes, exact hes.2 },
rw ← le_div_iff hge,
exact w _ hes, },
{ calc _ ≤ 0 : mul_nonpos_of_nonneg_of_nonpos _ _ -- prove two goals below
... ≤ f e : fpos e het,
{ apply div_nonneg (fpos i₀ (mem_of_subset (filter_subset t) mem)) (le_of_lt hg) },
{ simpa only [mem_filter, het, true_and, not_lt] using hes }, } },
{ simp only [subtype.coe_mk, center_mass_eq_of_sum_1 _ id ksum, id],
calc ∑ e in t.erase i₀, k e • e = ∑ e in t, k e • e :
by conv_rhs { rw [← insert_erase hi₀, sum_insert (not_mem_erase i₀ t), hk, zero_smul, zero_add], }
... = ∑ e in t, (f e - f i₀ / g i₀ * g e) • e : rfl
... = t.center_mass f id : _,
simp only [sub_smul, mul_smul, sum_sub_distrib, ← smul_sum, gcombo, smul_zero,
sub_zero, center_mass, fsum, inv_one, one_smul, id.def], },
end
/--
The convex hull of a finset `t` with `findim ℝ E + 1 < t.card` is equal to
the union of the convex hulls of the finsets `t.erase x` for `x ∈ t`.
-/
lemma step [decidable_eq E] (t : finset E) (h : findim ℝ E + 1 < t.card) :
convex_hull (↑t : set E) = ⋃ (x : (↑t : set E)), convex_hull ↑(t.erase x) :=
begin
apply set.subset.antisymm,
{ intros x m',
obtain ⟨y, m⟩ := mem_convex_hull_erase h m',
exact mem_Union.2 ⟨y, m⟩, },
{ refine Union_subset _,
intro x,
apply convex_hull_mono,
apply erase_subset, }
end
/--
The convex hull of a finset `t` with `findim ℝ E + 1 < t.card` is contained in
the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ findim ℝ E + 1`.
-/
lemma shrink' (t : finset E) (k : ℕ) (h : t.card = findim ℝ E + 1 + k) :
convex_hull (↑t : set E) ⊆
⋃ (t' : finset E) (w : t' ⊆ t) (b : t'.card ≤ findim ℝ E + 1), convex_hull ↑t' :=
begin
induction k with k ih generalizing t,
{ apply subset_subset_Union t,
apply subset_subset_Union (set.subset.refl _),
exact subset_subset_Union (le_of_eq h) (subset.refl _), },
{ classical,
rw step _ (by { rw h, simp, } : findim ℝ E + 1 < t.card),
apply Union_subset,
intro i,
transitivity,
{ apply ih,
rw [card_erase_of_mem, h, nat.pred_succ],
exact i.2, },
{ apply Union_subset_Union,
intro t',
apply Union_subset_Union_const,
exact λ h, set.subset.trans h (erase_subset _ _), } }
end
/--
The convex hull of any finset `t` is contained in
the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ findim ℝ E + 1`.
-/
lemma shrink (t : finset E) :
convex_hull (↑t : set E) ⊆
⋃ (t' : finset E) (w : t' ⊆ t) (b : t'.card ≤ findim ℝ E + 1), convex_hull ↑t' :=
begin
by_cases h : t.card ≤ findim ℝ E + 1,
{ apply subset_subset_Union t,
apply subset_subset_Union (set.subset.refl _),
exact subset_subset_Union h (set.subset.refl _), },
push_neg at h,
obtain ⟨k, w⟩ := le_iff_exists_add.mp (le_of_lt h), clear h,
exact shrink' _ _ w,
end
end caratheodory
/--
One inclusion of Carathéodory's convexity theorem.
The convex hull of a set `s` in ℝᵈ is contained in
the union of the convex hulls of the (d+1)-tuples in `s`.
-/
lemma convex_hull_subset_union (s : set E) :
convex_hull s ⊆ ⋃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ findim ℝ E + 1), convex_hull ↑t :=
begin
-- First we replace `convex_hull s` with the union of the convex hulls of finite subsets,
rw convex_hull_eq_union_convex_hull_finite_subsets,
-- and prove the inclusion for each of those.
apply Union_subset, intro r,
apply Union_subset, intro h,
-- Second, for each convex hull of a finite subset, we shrink it.
transitivity,
{ apply caratheodory.shrink, },
{ -- After that it's just shuffling unions around.
apply Union_subset, intro t,
apply Union_subset, intro htr,
apply Union_subset, intro ht,
apply set.subset_subset_Union t,
apply set.subset_subset_Union (subset.trans htr h),
exact subset_Union _ ht, },
end
/--
Carathéodory's convexity theorem.
The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`.
-/
theorem convex_hull_eq_union (s : set E) :
convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ findim ℝ E + 1), convex_hull ↑t :=
begin
apply set.subset.antisymm,
{ apply convex_hull_subset_union, },
iterate 3 { convert Union_subset _, intro, },
exact convex_hull_mono ‹_›,
end
/--
A more explicit formulation of Carathéodory's convexity theorem,
writing an element of a convex hull as the center of mass
of an explicit `finset` with cardinality at most `dim + 1`.
-/
theorem eq_center_mass_card_le_dim_succ_of_mem_convex_hull
{s : set E} {x : E} (h : x ∈ convex_hull s) :
∃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ findim ℝ E + 1)
(f : E → ℝ), (∀ y ∈ t, 0 ≤ f y) ∧ t.sum f = 1 ∧ t.center_mass f id = x :=
begin
rw convex_hull_eq_union at h,
simp only [exists_prop, mem_Union] at h,
obtain ⟨t, w, b, m⟩ := h,
refine ⟨t, w, b, _⟩,
rw finset.convex_hull_eq at m,
simpa only [exists_prop] using m,
end
/--
A variation on Carathéodory's convexity theorem,
writing an element of a convex hull as a center of mass
of an explicit `finset` with cardinality at most `dim + 1`,
where all coefficients in the center of mass formula
are strictly positive.
(This is proved using `eq_center_mass_card_le_dim_succ_of_mem_convex_hull`,
and discarding any elements of the set with coefficient zero.)
-/
theorem eq_pos_center_mass_card_le_dim_succ_of_mem_convex_hull
{s : set E} {x : E} (h : x ∈ convex_hull s) :
∃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ findim ℝ E + 1)
(f : E → ℝ), (∀ y ∈ t, 0 < f y) ∧ t.sum f = 1 ∧ t.center_mass f id = x :=
begin
obtain ⟨t, w, b, f, ⟨pos, sum, center⟩⟩ := eq_center_mass_card_le_dim_succ_of_mem_convex_hull h,
let t' := t.filter (λ z, 0 < f z),
have t'sum : t'.sum f = 1,
{ convert sum using 1,
symmetry,
fapply sum_bij_ne_zero (λ z h w, z),
{ intros z m nz,
exact multiset.mem_filter_of_mem m (lt_of_le_of_ne (pos z m) (ne.symm nz)), },
{ intros _ _ _ _ _ _ a, exact a, },
{ intros z m nz,
exact ⟨z, mem_of_subset (filter_subset t) m, nz, rfl⟩, },
{ intros, refl, }, },
refine ⟨t', _, _, f, ⟨_, _, _⟩⟩,
{ exact subset.trans (filter_subset t) w, },
{ exact le_trans (card_le_of_subset (filter_subset t)) b, },
{ exact λ y H, (mem_filter.mp H).right, },
{ exact t'sum, },
{ convert center using 1,
symmetry,
simp only [center_mass, t'sum, sum, inv_one, one_smul, id.def],
fapply sum_bij_ne_zero (λ z h w, z),
{ intros z m nz,
have nz' : f z ≠ 0,
{ intro a, rw a at nz,
simpa using nz, },
exact multiset.mem_filter_of_mem m (lt_of_le_of_ne (pos z m) (ne.symm nz')), },
{ intros _ _ _ _ _ _ a, exact a, },
{ intros z m nz,
exact ⟨z, mem_of_subset (filter_subset t) m, nz, rfl⟩, },
{ intros, refl, }, },
end
|
0a56ad88a9c3b4e7afd47dcf1fc64153777c1498 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/test/algebra-amgm-sum1toneqn-prod1tonleq1.lean | d34f44edc1c6bdd7b42d41e85f90c9b29a99cef0 | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 393 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.real.nnreal
import data.real.basic
import algebra.big_operators.basic
open_locale big_operators
example (a : ℕ → nnreal) (n : ℕ) (h₀ : ∑ x in finset.range n, a x = n ) : ∏ x in finset.range n, a x ≤ 1 :=
begin
sorry
end
|
2bcc7d2adb9b959a41fa977624927230fae37d1b | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/data/nat/sqrt.lean | 32c1d5e773208176043ee2f9abf19e58c075ccb4 | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 6,983 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro
An efficient binary implementation of a (sqrt n) function that
returns s s.t.
s*s ≤ n ≤ s*s + s + s
-/
import data.int.basic
namespace nat
theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b :=
begin
simp [shiftr_eq_div_pow],
apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2,
have := nat.mul_lt_mul_of_pos_left
(dec_trivial : 1 < 4) (nat.pos_of_ne_zero h),
rwa mul_one at this
end
def sqrt_aux : ℕ → ℕ → ℕ → ℕ
| b r n := if b0 : b = 0 then r else
let b' := shiftr b 2 in
have b' < b, from sqrt_aux_dec b0,
match (n - (r + b : ℕ) : ℤ) with
| (n' : ℕ) := sqrt_aux b' (div2 r + b) n'
| _ := sqrt_aux b' (div2 r) n
end
/-- `sqrt n` is the square root of a natural number `n`. If `n` is not a
perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/
def sqrt (n : ℕ) : ℕ :=
match size n with
| 0 := 0
| succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n
end
theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r :=
by rw sqrt_aux; simp
local attribute [simp] sqrt_aux_0
theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) :
sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' :=
by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false];
rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1]
theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) :
sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n :=
begin
rw sqrt_aux; simp only [h, h₂, if_false],
cases int.eq_neg_succ_of_lt_zero
(sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e,
rw [e, sqrt_aux._match_1]
end
private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1)
private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ)
(h₁ : r*r ≤ n)
(m') (hm : shiftr (2^m * 2^m) 2 = m')
(H1 : n < (r + 2^m) * (r + 2^m) →
is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r)))
(H2 : (r + 2^m) * (r + 2^m) ≤ n →
is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) :
is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) :=
begin
have b0 :=
have b0:_, from ne_of_gt (@pos_pow_of_pos 2 m dec_trivial),
nat.mul_ne_zero b0 b0,
have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔
n < (r+2^m)*(r+2^m), {
rw [nat.sub_lt_right_iff_lt_add h₁],
simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc,
add_comm, add_assoc, add_left_comm] },
have re : div2 (2 * r * 2^m) = r * 2^m, {
rw [div2_val, mul_assoc,
nat.mul_div_cancel_left _ (dec_trivial:2>0)] },
cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl,
{ rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl },
{ cases le.dest hl with n' e,
rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)),
hm, re, ← right_distrib],
{ apply H2 hl },
apply eq.symm, apply nat.sub_eq_of_eq_add,
rw [← add_assoc, (_ : r*r + _ = _)],
exact (nat.add_sub_cancel' hl).symm,
simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_assoc] },
end
private lemma sqrt_aux_is_sqrt (n) : ∀ m r,
r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) →
is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r))
| 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl;
intros; simp; [exact ⟨h₁, a⟩, exact ⟨a, h₂⟩]
| (m+1) r h₁ h₂ := begin
apply sqrt_aux_is_sqrt_lemma
(m+1) r n h₁ (2^m * 2^m)
(by simp [shiftr, nat.pow_succ, div2_val, mul_comm, mul_left_comm];
repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial});
intros,
{ have := sqrt_aux_is_sqrt m r h₁ a,
simpa [nat.pow_succ, mul_comm, mul_assoc] },
{ rw [nat.pow_succ, mul_two, ← add_assoc] at h₂,
have := sqrt_aux_is_sqrt m (r + 2^(m+1)) a h₂,
rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m,
by simp [nat.pow_succ, mul_comm, mul_left_comm] }
end
private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) :=
begin
generalize e : size n = s, cases s with s; simp [e, sqrt],
{ rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial },
{ have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _),
simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by {
generalize: div2 s = x,
change bit0 x with x+x,
rw [one_shiftl, pow_add] }] at this,
apply this,
rw [← pow_add, ← mul_two], apply size_le.1,
rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1,
rw [div2_val], apply lt_succ_self }
end
theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n :=
(sqrt_is_sqrt n).left
theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) :=
(sqrt_is_sqrt n).right
theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n :=
by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n)
theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n :=
⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n),
λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $
lt_of_le_of_lt h (lt_succ_sqrt n)⟩
theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n :=
lt_iff_lt_of_le_iff_le le_sqrt
theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n :=
le_trans (le_mul_self _) (sqrt_le n)
theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n :=
le_sqrt.2 (le_trans (sqrt_le _) h)
theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 :=
⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $
by rw [h]; exact dec_trivial,
λ e, e.symm ▸ rfl⟩
theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) :=
⟨λ e, e.symm ▸ sqrt_is_sqrt n,
λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩
theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 :=
le_of_lt_succ $ (@sqrt_lt n 2).1 $
by rw [h]; exact dec_trivial
theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n :=
sqrt_lt.2 $ by
have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h);
rwa [mul_one] at this
theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt
theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n :=
le_antisymm
(le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc];
exact lt_succ_of_le (nat.add_le_add_left h _))
(le_sqrt.2 $ nat.le_add_right _ _)
theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n :=
sqrt_add_eq n (zero_le _)
theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ :=
le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $
le_trans (sqrt_le_add n) $ add_le_add_right
(by refine add_le_add
(mul_le_mul_right _ _) _; exact le_add_right _ 2) _
theorem exists_mul_self (x : ℕ) :
(∃ n, n * n = x) ↔ sqrt x * sqrt x = x :=
⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩
end nat
|
fd0c5dec479b55b04e9e9bb897b20075fed61267 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/group/semiconj.lean | cffbcd589857cd2eea9faec14e18262b5dd34b75 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 6,992 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
Some proofs and docs came from `algebra/commute` (c) Neil Strickland
-/
import algebra.group.units
/-!
# Semiconjugate elements of a semigroup
## Main definitions
We say that `x` is semiconjugate to `y` by `a` (`semiconj_by a x y`), if `a * x = y * a`.
In this file we provide operations on `semiconj_by _ _ _`.
In the names of these operations, we treat `a` as the “left” argument, and both `x` and `y` as
“right” arguments. This way most names in this file agree with the names of the corresponding lemmas
for `commute a b = semiconj_by a b b`. As a side effect, some lemmas have only `_right` version.
Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like
`rw [(h.pow_right 5).eq]` rather than just `rw [h.pow_right 5]`.
This file provides only basic operations (`mul_left`, `mul_right`, `inv_right` etc). Other
operations (`pow_right`, field inverse etc) are in the files that define corresponding notions.
-/
universes u v
/-- `x` is semiconjugate to `y` by `a`, if `a * x = y * a`. -/
@[to_additive add_semiconj_by "`x` is additive semiconjugate to `y` by `a` if `a + x = y + a`"]
def semiconj_by {M : Type u} [has_mul M] (a x y : M) : Prop := a * x = y * a
namespace semiconj_by
/-- Equality behind `semiconj_by a x y`; useful for rewriting. -/
@[to_additive]
protected lemma eq {S : Type u} [has_mul S] {a x y : S} (h : semiconj_by a x y) :
a * x = y * a := h
section semigroup
variables {S : Type u} [semigroup S] {a b x y z x' y' : S}
/-- If `a` semiconjugates `x` to `y` and `x'` to `y'`,
then it semiconjugates `x * x'` to `y * y'`. -/
@[simp, to_additive] lemma mul_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x * x') (y * y') :=
by unfold semiconj_by; assoc_rw [h.eq, h'.eq]
/-- If both `a` and `b` semiconjugate `x` to `y`, then so does `a * b`. -/
@[to_additive]
lemma mul_left (ha : semiconj_by a y z) (hb : semiconj_by b x y) :
semiconj_by (a * b) x z :=
by unfold semiconj_by; assoc_rw [hb.eq, ha.eq, mul_assoc]
/-- The relation “there exists an element that semiconjugates `a` to `b`” on a semigroup
is transitive. -/
@[to_additive "The relation “there exists an element that semiconjugates `a` to `b`” on an additive
semigroup is transitive."]
protected lemma transitive : transitive (λ a b : S, ∃ c, semiconj_by c a b) :=
λ a b c ⟨x, hx⟩ ⟨y, hy⟩, ⟨y * x, hy.mul_left hx⟩
end semigroup
section mul_one_class
variables {M : Type u} [mul_one_class M]
/-- Any element semiconjugates `1` to `1`. -/
@[simp, to_additive]
lemma one_right (a : M) : semiconj_by a 1 1 := by rw [semiconj_by, mul_one, one_mul]
/-- One semiconjugates any element to itself. -/
@[simp, to_additive]
lemma one_left (x : M) : semiconj_by 1 x x := eq.symm $ one_right x
/-- The relation “there exists an element that semiconjugates `a` to `b`” on a monoid (or, more
generally, on ` mul_one_class` type) is reflexive. -/
@[to_additive "The relation “there exists an element that semiconjugates `a` to `b`” on an additive
monoid (or, more generally, on a `add_zero_class` type) is reflexive."]
protected lemma reflexive : reflexive (λ a b : M, ∃ c, semiconj_by c a b) :=
λ a, ⟨1, one_left a⟩
end mul_one_class
section monoid
variables {M : Type u} [monoid M]
/-- If `a` semiconjugates a unit `x` to a unit `y`, then it semiconjugates `x⁻¹` to `y⁻¹`. -/
@[to_additive] lemma units_inv_right {a : M} {x y : Mˣ} (h : semiconj_by a x y) :
semiconj_by a ↑x⁻¹ ↑y⁻¹ :=
calc a * ↑x⁻¹ = ↑y⁻¹ * (y * a) * ↑x⁻¹ : by rw [units.inv_mul_cancel_left]
... = ↑y⁻¹ * a : by rw [← h.eq, mul_assoc, units.mul_inv_cancel_right]
@[simp, to_additive] lemma units_inv_right_iff {a : M} {x y : Mˣ} :
semiconj_by a ↑x⁻¹ ↑y⁻¹ ↔ semiconj_by a x y :=
⟨units_inv_right, units_inv_right⟩
/-- If a unit `a` semiconjugates `x` to `y`, then `a⁻¹` semiconjugates `y` to `x`. -/
@[to_additive] lemma units_inv_symm_left {a : Mˣ} {x y : M} (h : semiconj_by ↑a x y) :
semiconj_by ↑a⁻¹ y x :=
calc ↑a⁻¹ * y = ↑a⁻¹ * (y * a * ↑a⁻¹) : by rw [units.mul_inv_cancel_right]
... = x * ↑a⁻¹ : by rw [← h.eq, ← mul_assoc, units.inv_mul_cancel_left]
@[simp, to_additive] lemma units_inv_symm_left_iff {a : Mˣ} {x y : M} :
semiconj_by ↑a⁻¹ y x ↔ semiconj_by ↑a x y :=
⟨units_inv_symm_left, units_inv_symm_left⟩
@[to_additive] theorem units_coe {a x y : Mˣ} (h : semiconj_by a x y) :
semiconj_by (a : M) x y :=
congr_arg units.val h
@[to_additive] theorem units_of_coe {a x y : Mˣ} (h : semiconj_by (a : M) x y) :
semiconj_by a x y :=
units.ext h
@[simp, to_additive] theorem units_coe_iff {a x y : Mˣ} :
semiconj_by (a : M) x y ↔ semiconj_by a x y :=
⟨units_of_coe, units_coe⟩
@[simp, to_additive]
lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) :=
begin
induction n with n ih,
{ rw [pow_zero, pow_zero], exact semiconj_by.one_right _ },
{ rw [pow_succ, pow_succ],
exact h.mul_right ih }
end
end monoid
section group
variables {G : Type u} [group G] {a x y : G}
@[simp, to_additive] lemma inv_right_iff : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y :=
@units_inv_right_iff G _ a ⟨x, x⁻¹, mul_inv_self x, inv_mul_self x⟩
⟨y, y⁻¹, mul_inv_self y, inv_mul_self y⟩
@[to_additive] lemma inv_right : semiconj_by a x y → semiconj_by a x⁻¹ y⁻¹ :=
inv_right_iff.2
@[simp, to_additive] lemma inv_symm_left_iff : semiconj_by a⁻¹ y x ↔ semiconj_by a x y :=
@units_inv_symm_left_iff G _ ⟨a, a⁻¹, mul_inv_self a, inv_mul_self a⟩ _ _
@[to_additive] lemma inv_symm_left : semiconj_by a x y → semiconj_by a⁻¹ y x :=
inv_symm_left_iff.2
@[to_additive] lemma inv_inv_symm (h : semiconj_by a x y) : semiconj_by a⁻¹ y⁻¹ x⁻¹ :=
h.inv_right.inv_symm_left
-- this is not a simp lemma because it can be deduced from other simp lemmas
@[to_additive] lemma inv_inv_symm_iff : semiconj_by a⁻¹ y⁻¹ x⁻¹ ↔ semiconj_by a x y :=
inv_right_iff.trans inv_symm_left_iff
/-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/
@[to_additive] lemma conj_mk (a x : G) : semiconj_by a x (a * x * a⁻¹) :=
by unfold semiconj_by; rw [mul_assoc, inv_mul_self, mul_one]
end group
end semiconj_by
@[simp, to_additive add_semiconj_by_iff_eq]
lemma semiconj_by_iff_eq {M : Type u} [cancel_comm_monoid M] {a x y : M} :
semiconj_by a x y ↔ x = y :=
⟨λ h, mul_left_cancel (h.trans (mul_comm _ _)), λ h, by rw [h, semiconj_by, mul_comm] ⟩
/-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/
@[to_additive]
lemma units.mk_semiconj_by {M : Type u} [monoid M] (u : Mˣ) (x : M) :
semiconj_by ↑u x (u * x * ↑u⁻¹) :=
by unfold semiconj_by; rw [units.inv_mul_cancel_right]
|
ea599043f61bf3f4532b5ee107874589bc042e95 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Compiler/Main.lean | 5e26afa991ade187fed5fe02a543f91c2d735714 | [
"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,483 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.Decl
import Lean.Compiler.TerminalCases
import Lean.Compiler.CSE
import Lean.Compiler.Stage1
namespace Lean.Compiler
/--
We do not generate code for `declName` if
- Its type is a proposition.
- Its type is a type former.
- It is tagged as `[macroInline]`.
- It is a type class instance.
Remark: we still generate code for declarations tagged as `[inline]`
and `[specialize]` since they can be partially applied.
-/
def shouldGenerateCode (declName : Name) : CoreM Bool := do
if (← isCompIrrelevant |>.run') then return false
if hasMacroInlineAttribute (← getEnv) declName then return false
if (← Meta.isMatcher declName) then return false
-- TODO: check if type class instance
return true
where
isCompIrrelevant : MetaM Bool := do
let info ← getConstInfo declName
Meta.isProp info.type <||> Meta.isTypeFormerType info.type
/--
A checkpoint in code generation to print all declarations in between
compiler passes in order to ease debugging.
The trace can be viewed with `set_option trace.Compiler.step true`.
-/
def checkpoint (step : Name) (decls : Array Decl) (cfg : Check.Config := {}): CoreM Unit := do
trace[Compiler.step] "{step}"
for decl in decls do
withOptions (fun opts => opts.setBool `pp.motives.pi false) do
trace[Compiler.step] "{decl.name} : {decl.type} :=\n{decl.value}"
decl.check cfg
@[export lean_compile_stage1]
def compileStage1Impl (declNames : Array Name) : CoreM (Array Decl) := do
let declNames ← declNames.filterM shouldGenerateCode
if declNames.isEmpty then return #[]
let decls ← declNames.mapM toDecl
checkpoint `init decls { terminalCasesOnly := false }
let decls ← decls.mapM (·.terminalCases)
checkpoint `terminalCases decls
-- Remark: add simplification step here, `cse` is useful after simplification
let decls ← decls.mapM (·.cse)
checkpoint `cse decls
saveStage1Decls decls
return decls
/--
Run the code generation pipeline for all declarations in `declNames`
that fulfill the requirements of `shouldGenerateCode`.
-/
def compile (declNames : Array Name) : CoreM Unit := do profileitM Exception "compiler new" (← getOptions) do
discard <| compileStage1Impl declNames
builtin_initialize
registerTraceClass `Compiler
registerTraceClass `Compiler.step
end Lean.Compiler
|
17b9ed9dddc77fbf5e83a67ff527183d28f31694 | 40c8b73f5a82a3c09e3d1956df44aad9ffd510b7 | /src/section_10_11_12.lean | 9cbf7f91887c31a9a8c2629ca9ee1f1fdd432030 | [] | no_license | lean-forward/cap_set_problem | 343c02d42775eb25b32b6c567d13769fd42dd4ca | 095a2f18f81c551a0053f2e65806de751e438fc4 | refs/heads/master | 1,626,463,115,144 | 1,561,829,195,000 | 1,561,829,195,000 | 178,678,372 | 7 | 1 | null | 1,625,412,745,000 | 1,554,031,306,000 | Lean | UTF-8 | Lean | false | false | 31,360 | lean | /-
Copyright (c) 2018 Sander Dahmen, Johannes Hölzl, Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sander Dahmen, Johannes Hölzl, Robert Y. Lewis
"On large subsets of 𝔽ⁿ_q with no three-term arithmetic progression"
by J. S. Ellenberg and D. Gijswijt
This file establishes the bound on the cardinality of a generalized cap set.
It corresponds to sections 10-12 of our blueprint.
-/
import library section_9
open mv_polynomial
section
parameters
{α : Type} [discrete_field α] [fintype α] -- 𝔽_q: q is cardinality of `α`
(n : ℕ)
def q : ℕ := fintype.card α
lemma q_pos : q > 0 := fintype.card_pos_iff.2 ⟨1⟩
lemma one_le_q : 1 ≤ q := q_pos
lemma one_le_q_real : 1 ≤ (q : ℚ) :=
suffices ↑(1 : ℕ) ≤ (q : ℚ), by simpa,
nat.cast_le.2 one_le_q
/-- Polynomials in α - seen as a vector space -/
@[reducible] def S := mv_polynomial (fin n) α
instance S.module : module α S := by dunfold S; apply_instance
instance S.vector_space : vector_space α S := { .. S.module }
instance fin_q_has_zero : has_zero (fin q) := ⟨⟨0, one_le_q⟩⟩
def M : finset (mv_polynomial (fin n) α):=
(finset.univ.image $ λ f : fin n →₀ fin q, f.map_range fin.val rfl).image (λd : fin n →₀ ℕ, monomial d (1:α))
lemma linear_independent_M : linear_independent α (↑M : set (mv_polynomial (fin n) α)) :=
(mv_polynomial.is_basis_monomials _ _).1.mono $ λ p hp,
let ⟨s, _, hsp⟩ := finset.mem_image.1 hp in
set.mem_range.2 ⟨s, hsp⟩
def fin_map_to_mono_map (f : fin n → fin q) : fin n →₀ ℕ := λ k, (f k).val
def fmtmm : has_coe (fin n → fin q) (fin n →₀ ℕ) := ⟨fin_map_to_mono_map⟩
local attribute [instance] fmtmm
lemma monomial_mem_M (f : fin n → fin q) : monomial ↑f (1 : α) ∈ M :=
begin
apply finset.mem_image.2,
refine ⟨f, _, rfl⟩,
apply finset.mem_image.2,
use [f, finset.mem_univ _], ext, refl
end
@[simp] lemma coe_fin_eq_coe_fin (f g : (fin n → fin q)) : (f : fin n →₀ ℕ) = g ↔ f = g :=
begin
split,
{ intro h,
ext,
apply (fin.ext_iff _ _).2,
apply finsupp.congr_fun h },
{ intro h, rw h }
end
lemma M_spec {x} (hx : x ∈ M) : ∃ s : fin n → fin q, monomial ↑s 1 = x :=
begin
rcases finset.mem_image.1 hx with ⟨d, ⟨hd, hdmon⟩⟩,
have h : ∀ k, d k < q,
{ intro k,
rcases finset.mem_image.1 hd with ⟨l, ⟨hl, hdl⟩⟩,
have hdl' : (finsupp.map_range fin.val (_) l : fin n → ℕ) k = d k, {rw hdl},
rw finsupp.map_range_apply at hdl', rw ←hdl', apply fin.is_lt },
use λ k, ⟨d k, h k⟩,
rw ←hdmon, congr, ext, refl
end
noncomputable def monom_exps (p : (mv_polynomial (fin n) α)) : (fin n → fin q) :=
if hp : p ∈ M then classical.some (M_spec hp) else 0
lemma monom_exps_def {x} (hx : x ∈ M) : monomial ↑(monom_exps x) 1 = x :=
by simpa [hx, monom_exps] using (classical.some_spec (M_spec hx))
lemma monom_exps_inj {x y} (hx : x ∈ M) (hy : y ∈ M) (hxy : monom_exps x = monom_exps y) : x = y :=
have h1 : _, from monom_exps_def hx, have h2 : _, from monom_exps_def hy,
by rw [←h1, ←h2, hxy]
@[simp] lemma monom_exps_monomial (f : fin n → fin q) : monom_exps (monomial f 1) = f :=
by simpa using finsupp.eq_of_single_eq_left (monom_exps_def (monomial_mem_M _)) one_ne_zero
lemma monom_exps_surj (f : fin n → fin q) : ∃ x, x ∈ M ∧ monom_exps x = f :=
⟨monomial f 1, monomial_mem_M _, monom_exps_monomial _⟩
-- do more generally
lemma monomial_total_degree (f : fin n →₀ ℕ) :
mv_polynomial.total_degree (monomial f (1 : α)) = finsupp.sum f (λ _, id) :=
suffices finset.sup {f} (λ (s : fin n →₀ ℕ), finsupp.sum s (λ _, id)) =
finsupp.sum f (λ _, id), by simpa [monomial, finsupp.single, mv_polynomial.total_degree],
by rw finset.sup_singleton
lemma mv_polynomial_eval_eq (p : mv_polynomial (fin n) α) (a : fin n → α) :
p.eval a = p.sum (λi c, c * (i.to_multiset.map $ λn, a n).prod) :=
begin
rw [eval, eval₂],
congr, funext i c, congr,
rw [finsupp.to_multiset_map, finsupp.prod_to_multiset,
finsupp.prod_map_domain_index pow_zero pow_add]
end
lemma eval_add (p : S) (a b : fin n → α) :
p.eval (a + b) = p.sum (λe x, multiset.sum $
e.to_multiset.diagonal.map $ λp, x * ((p.1.map $ λi, a i).prod * (p.2.map $ λi, b i).prod)) :=
by simp [mv_polynomial_eval_eq, multiset.sum_map_mul_left, multiset.prod_map_add]
section
def M' (d : ℚ) := M.filter (λ m, d ≥ mv_polynomial.total_degree m)
end
lemma linear_independent_M' (d) : linear_independent α (↑(M' d) : set (mv_polynomial (fin n) α)) :=
linear_independent_M.mono $ λ x hx, M.filter_subset hx
lemma mem_M_of_mem_M' {x d} (hx : x ∈ M' d) : x ∈ M := (finset.mem_filter.1 hx).1
def S' (d : ℚ) := submodule.span α (↑(M' d) : set (mv_polynomial (fin n) α))
lemma mem_S'_of_mem_M' {d : ℚ} {p} (hp : p ∈ M' d) : p ∈ S' d :=
submodule.mem_span.2 $ λ t hmt, hmt hp
lemma S'_le_restrict_q (d : ℚ) : S' d ≤ mv_polynomial.restrict_degree _ _ (q - 1) :=
submodule.span_le.2 $ assume p hp,
begin
have : p ∈ M := mem_M_of_mem_M' hp,
rcases M_spec this with ⟨s, rfl⟩,
assume s hs n,
rw [finset.mem_coe, mv_polynomial.monomial,
finsupp.support_single_ne_zero zero_ne_one.symm, finset.singleton_eq_singleton,
finset.mem_singleton] at hs,
subst hs,
exact (nat.le_sub_right_iff_add_le one_le_q).2 (s n).2
end
lemma le_floor_to_nat (n : ℕ) (d : ℚ) (hd : 0 ≤ d) :
n ≤ ⌊d⌋.to_nat ↔ (n : ℚ) ≤ d :=
begin
rw [int.to_nat_le_iff, le_floor, ← coe_coe],
rwa [le_floor]
end
lemma S'_le_restrict_d (d : ℚ) (hd : 0 ≤ d):
S' d ≤ mv_polynomial.restrict_total_degree _ _ (⌊d⌋).to_nat :=
submodule.span_le.2 $ assume p hp, (mv_polynomial.mem_restrict_total_degree _ _ _ _).2
begin
have hp := (finset.mem_filter.1 hp).2,
rwa [le_floor_to_nat _ _ hd]
end
parameter (α)
noncomputable def m (d : ℚ) : ℕ := (vector_space.dim α (S' d)).to_nat
parameter {α}
lemma M'_card (d : ℚ) : (M' d).card = m d :=
by rw [m, S', dim_span (linear_independent_M' _), ←cardinal.finset_card, cardinal.to_nat_coe]
section Propostion_11_1
parameters {d : ℚ} (d_nonneg : 0 ≤ d) --(d_upper : d ≤ (fintype.card α) * n)
set_option class.instance_max_depth 200
parameters
{p : S}
(A : finset (fin n → α))
(a b c : α)
(hp : p ∈ S' d)
(habc : a + b + c = 0)
(h : ∀x:fin n → α, x∈A → ∀y∈A, x ≠ y → mv_polynomial.eval (a • x + b • y) p = (0:α))
include habc
lemma a_plus_b : a + b = -c :=
calc a + b = a + b + c + (-c) : by simp
... = -c : by simp [habc]
omit habc
include hp
section
open multiset finsupp
/-- The coefficients `(m₁, m₂) ⊢> ∑ c*X^e ∈ p | m₁ + m₂ = e, c * a ^ |m₁| * b ^ |m₂|` -/
def coeff (a b : α) : (multiset (fin n) × multiset (fin n)) →₀ α :=
p.sum $ λe c, sum $ e.to_multiset.diagonal.map $ λm, single m (c * a ^ card m.1 * b ^ card m.2)
/-- `π x m := Πi∈m, x i` -/
def π (x : fin n → α) (m : multiset (fin n)) : α := prod $ m.map $ λi, x i
def split_left (a b : α) : (multiset (fin n) × multiset (fin n)) →₀ α :=
(coeff a b).filter $ λp, d / 2 > p.1.card
def split_right (a b : α) : (multiset (fin n) × multiset (fin n)) →₀ α :=
((coeff a b).filter (λp:multiset (fin n)×multiset (fin n), ¬ d / 2 > p.1.card)).map_domain prod.swap
lemma mem_coeff_support {a b : α} (m₀ m₁ : multiset (fin n)) (h : (m₀, m₁) ∈ (coeff a b).support) :
of_multiset (m₀ + m₁) ∈ p.support :=
begin
rcases finsupp.mem_support_finset_sum _ h with ⟨f, hf, hfm⟩,
rcases finsupp.mem_support_multiset_sum _ hfm with ⟨e, he, hem⟩, clear hfm,
rcases multiset.mem_map.1 he with ⟨m, hm, rfl⟩, clear he,
rw [mem_support_single] at hem,
rcases hem with ⟨rfl, hb⟩,
rw [mem_diagonal] at hm,
rw [hm],
show equiv_multiset.inv_fun (equiv_multiset.to_fun f) ∈ p.support,
rwa [equiv_multiset.left_inv f]
end
section
include d_nonneg
lemma mem_coeff_support_d {a b : α} (m₀ m₁ : multiset (fin n))
(h : (m₀, m₁) ∈ (coeff a b).support) :
d ≥ (m₀ + m₁).card :=
begin
have : of_multiset (m₀ + m₁) ∈ p.support := mem_coeff_support m₀ m₁ h,
have hp := (mv_polynomial.mem_restrict_total_degree _ _ _ _).1 (S'_le_restrict_d d d_nonneg hp),
rw [le_floor_to_nat _ _ d_nonneg, total_degree_eq] at hp,
refine le_trans (nat.cast_le.2 $ le_trans _ (finset.le_sup this)) hp,
convert le_refl _,
exact finsupp.equiv_multiset.4 _
end
lemma mem_coeff_support_q {a b : α} (m₀ m₁ : multiset (fin n))
(h : (m₀, m₁) ∈ (coeff a b).support) (i : fin n) :
(m₀ + m₁).count i < q :=
begin
have := S'_le_restrict_q _ hp (mem_coeff_support _ _ h),
exact (nat.le_sub_right_iff_add_le one_le_q).1 (this i)
end
lemma split_left_curry_card (a b : α) : (split_left a b).curry.support.card ≤ m (d/2) :=
begin
rw [← M'_card, M'],
refine finset.card_le_card_of_inj_on (λm, monomial (finsupp.of_multiset m) (1:α)) _ _,
{ simp only [finset.mem_filter, finset.mem_image, exists_prop, finset.mem_univ, true_and, M],
assume m hm',
rcases finset.mem_image.1 (finsupp.support_curry _ hm') with ⟨⟨m₀, m₁⟩, hm, rfl⟩, clear hm',
rw [split_left, finsupp.support_filter, finset.mem_filter] at hm,
let f : fin n → fin q := λi, ⟨m₀.count i, lt_of_le_of_lt
(multiset.count_le_of_le _ $ le_add_right _ _) (mem_coeff_support_q _ _ hm.1 i)⟩,
refine ⟨⟨_, ⟨f, rfl⟩, _⟩, _⟩,
{ congr, ext i, refl },
{ rw [monomial_total_degree, ← card_to_multiset],
convert le_of_lt hm.2,
exact finsupp.equiv_multiset.4 _ } },
{ assume m₀ _ m₁ _ eq,
have := (single_eq_single_iff _ _ _ _).1 eq,
simp only [(zero_ne_one : (0:α) ≠ 1).symm, or_false, and_false] at this,
exact (finsupp.equiv_multiset.symm.apply_eq_iff_eq m₀ m₁).1 this.1 }
end
lemma split_right_curry_card (a b : α) : (split_right a b).curry.support.card ≤ m (d/2) :=
begin
rw [← M'_card, M'],
refine finset.card_le_card_of_inj_on (λm, monomial (finsupp.of_multiset m) (1:α)) _ _,
{ simp only [finset.mem_filter, finset.mem_image, exists_prop, finset.mem_univ, true_and, M],
assume m hm',
rcases finset.mem_image.1 (finsupp.support_curry _ hm') with ⟨⟨m₁, m₀⟩, hm'', rfl⟩, clear hm',
rcases finset.mem_image.1 (map_domain_support hm'') with ⟨⟨m₀', m₁'⟩, hm, eq⟩,
cases eq, clear eq, clear hm'',
rw [finsupp.support_filter, finset.mem_filter] at hm,
let f : fin n → fin q := λi, ⟨m₁.count i, lt_of_le_of_lt
(multiset.count_le_of_le _ $ le_add_left _ _) (mem_coeff_support_q _ _ hm.1 i)⟩,
refine ⟨⟨_, ⟨f, rfl⟩, _⟩, _⟩,
{ congr, ext i, refl },
{ rw [monomial_total_degree, ← card_to_multiset],
have d_le : d / 2 ≤ ↑(card m₀) := le_of_not_gt hm.2,
have d_ge : d ≥ card (m₀ + m₁) := mem_coeff_support_d _ _ hm.1,
rw [multiset.card_add, nat.cast_add] at d_ge,
have : d / 2 ≥ ↑(card m₁),
{ refine le_of_not_gt (assume h, _),
have : (card m₀ : ℚ) + card m₁ > d / 2 + d / 2 := add_lt_add_of_le_of_lt d_le h,
rw [add_halves] at this,
exact not_lt_of_ge d_ge this },
convert this,
exact finsupp.equiv_multiset.4 _ } },
{ assume m₀ _ m₁ _ eq,
have := (single_eq_single_iff _ _ _ _).1 eq,
simp only [(zero_ne_one : (0:α) ≠ 1).symm, or_false, and_false] at this,
exact (finsupp.equiv_multiset.symm.apply_eq_iff_eq m₀ m₁).1 this.1 }
end
end
lemma eval_add_eq_split_sum {x y : fin n → α} {a b : α} :
p.eval (a • x + b • y) =
(split_left a b).curry.sum (λm f, π x m * f.sum (λm c, c * π y m)) +
(split_right a b).curry.sum (λm f, π y m * f.sum (λm c, c * π x m)) :=
calc p.eval (a • x + b • y) = (coeff a b).sum (λm c, c * π x m.1 * π y m.2) :
by
rw [coeff, eval_add];
simp [π, finsupp.multiset_sum_sum_index, sum_sum_index, sum_single_index,
add_mul, mul_comm, mul_left_comm, mul_assoc]
... =
(split_left a b).sum (λm c, c * π x m.1 * π y m.2) +
(split_right a b).sum (λm c, c * π x m.2 * π y m.1) :
begin
rw [split_left, split_right, sum_map_domain_index]; simp [- not_lt],
rw [← sum_add_index, filter_pos_add_filter_neg]; simp [add_mul],
simp [add_mul]
end
... =
(split_left a b).curry.sum (λm f, π x m * f.sum (λm c, c * π y m)) +
(split_right a b).curry.sum (λm f, π y m * f.sum (λm c, c * π x m)) :
by
rw [
← (sum_curry_index (split_left a b) (λm₀ m₁ c, c * π x m₀ * π y m₁) _ _),
← (sum_curry_index (split_right a b) (λm₀ m₁ c, c * π x m₁ * π y m₀) _ _)];
simp [finsupp.mul_sum, mul_comm, mul_assoc, mul_left_comm, add_mul];
simp [finsupp.sum, mul_comm, mul_assoc, mul_left_comm]
end
lemma sum_is_matrix_mul_left (a b : α) (x y) :
((split_left a b).curry.sum (λm f, π x m * f.sum (λm c, c * π y m))) =
(split_left a b).curry.sum (λ m f, matrix.vec_mul_vec (λ x : fin n → α, π x m)
(λ y : fin n → α, f.sum (λ m c, c * π y m))) x y :=
begin
rw ←finsupp.sum_matrix _ _ x y,
refl
end
lemma sum_is_matrix_mul_right (a b : α) (x y) :
((split_right a b).curry.sum (λm f, π y m * f.sum (λm c, c * π x m))) =
(split_right a b).curry.sum (λ m f, matrix.vec_mul_vec (λ x : fin n → α, f.sum (λ m c, c * π x m))
(λ y : fin n → α, π y m)) x y :=
begin
rw ←finsupp.sum_matrix _ _ x y,
congr, ext, simp [matrix.vec_mul_vec, mul_comm]
end
lemma vmv_rank (m : multiset (fin n)) (f : multiset (fin n) →₀ α) :
rank (matrix.vec_mul_vec
(λ x : fin n → α, π x m) (λ y : fin n → α, f.sum (λ m c, c * π y m))).to_lin ≤ 1 :=
matrix.rank_vec_mul_vec _ _
def B : matrix {x // x ∈ A} {x // x ∈ A} α
| x y := p.eval (a • x + b • y)
lemma B_entry_eq_sum (i j) : B i j =
(split_left a b).curry.sum (λm f, π i.val m * f.sum (λm c, c * π j.val m)) +
(split_right a b).curry.sum (λm f, π j.val m * f.sum (λm c, c * π i.val m)) :=
eval_add_eq_split_sum
lemma B_entry_eq_sum_matrix (i j) : B i j =
(split_left a b).curry.sum (λ m f, matrix.vec_mul_vec (λ x, π x m)
(λ y, f.sum (λ m c, c * π y m))) i.val j.val +
(split_right a b).curry.sum (λ m f, matrix.vec_mul_vec (λ x, f.sum (λ m c, c * π x m))
(λ y, π y m)) i.val j.val :=
begin
rw [B_entry_eq_sum, sum_is_matrix_mul_left, sum_is_matrix_mul_right]
end
lemma B_eq_sum_matrix : B =
(split_left a b).curry.sum (λ m f, matrix.vec_mul_vec (λ x, π x.val m)
(λ y, f.sum (λ m c, c * π y.val m))) +
(split_right a b).curry.sum (λ m f, matrix.vec_mul_vec (λ x, f.sum (λ m c, c * π x.val m))
(λ y, π y.val m)) :=
begin
ext, rw B_entry_eq_sum_matrix, congr;
{ rw [finsupp.sum_matrix, finsupp.sum_matrix], refl }
end
lemma B_diagonal_card : fintype.card {i : {x // x ∈ A} // p.eval (-c • i.val) ≠ 0} =
(A.filter (λ a, p.eval (-c • a) ≠ 0)).card :=
suffices fintype.card { i // i ∈ A ∧ p.eval (-c • i) ≠ 0} = (A.filter (λ a, p.eval (-c • a) ≠ 0)).card,
begin
rw ←this,
apply fintype.card_congr,
refine {to_fun := λ x, ⟨x.1.1, x.1.2, x.2⟩, inv_fun := λ x, ⟨⟨x.1, x.2.1⟩, x.2.2⟩, ..},
{ simp [function.left_inverse] },
{ simp [function.right_inverse, function.left_inverse] }
end,
fintype.card_of_subtype _ $ λ a, finset.mem_filter
-- strategy: B = Σ Mᵢ + Σ Nᵢ, where there are ≤ m (d/2) i's and rank(Mᵢ), rank(Nᵢ) ≤ 1
include d_nonneg
lemma B_rank_le : (rank B.to_lin) ≤ ↑(2 * m (d/2)) :=
suffices rank B.to_lin ≤ ↑(m (d/2)) + ↑(m (d/2)), by simpa [two_mul],
begin
rw [B_eq_sum_matrix, matrix.to_lin_add],
transitivity,
apply rank_add_le,
apply cardinal.add_le_add;
`[rw [finsupp.sum_matrix_to_lin],
transitivity,
apply rank_finset_sum_le,
rw [←mul_one (m (d/2)), nat.cast_mul, nat.cast_one, ←add_monoid.smul_eq_mul],
transitivity add_monoid.smul _ (1 : cardinal),
{ apply finset.sum_le_card_mul_of_bdd,
intros, apply matrix.rank_vec_mul_vec },
apply add_monoid.smul_le_smul (cardinal.zero_le _)],
apply split_left_curry_card, apply split_right_curry_card
end
include habc h
lemma B_diagonal : B = matrix.diagonal (λ n, p.eval (-c • n.val)) :=
matrix.ext $ λ i j,
if hij : i = j then by rw [B, hij, ←add_smul, a_plus_b]; simp; refl
else begin
rw [B, h],
{ simp [hij] },
{ exact i.2 },
{ exact j.2 },
{ intro h2, apply hij, exact subtype.eq h2 }
end
lemma B_rank_eq :
(rank B.to_lin).to_nat = (A.filter (λa : fin n → α, mv_polynomial.eval (- c • a) p ≠ 0 )).card :=
begin
rw [B_diagonal, matrix.rank_diagonal, ←B_diagonal_card, cardinal.to_nat_coe],
congr -- WHY??
end
theorem proposition_11_1 :
(A.filter (λa : fin n → α, mv_polynomial.eval (- c • a) p ≠ 0 )).card ≤ 2 * m (d / 2) :=
begin
rw ←B_rank_eq,
transitivity,
{ apply cardinal.to_nat_le_of_le _,
apply B_rank_le,
apply cardinal.nat_lt_omega },
{ rw cardinal.to_nat_coe }
end
end Propostion_11_1
-- corresponds to section 12 of Sander's writeup
section Theorem4
set_option class.instance_max_depth 200
parameters {a b c : α} (h_a_ne_zero : c ≠ 0) (h_sum : a + b + c = 0) (h_n_pos : n > 0)
{A : finset (fin n → α)}
(h_A : ∀ x y z ∈ A, a•x + b•y + c•z = (0 : fin n → α) → x = y ∧ x = z)
section
parameters {d : ℚ} (hd : d ≤ (q-1)*n) (d_nonneg : 0 ≤ d) -- q is the cardinality of α
def neg_cA : finset (fin n → α) := A.image (λ z, (-c) • z)
include h_a_ne_zero
lemma map_is_bijective : function.bijective (λ x : fin n → α, -c•x) :=
equiv.bijective $ linear_equiv.to_equiv $ linear_equiv.smul_of_ne_zero (fin n → α) (-c) $
by simp [h_a_ne_zero]
omit h_a_ne_zero
lemma neg_cA_card : neg_cA.card = A.card :=
finset.card_image_of_injective _ map_is_bijective.1
lemma A_card_le_α_card_n : A.card ≤ fintype.card α^n :=
calc A.card ≤ finset.univ.card : finset.card_le_of_subset (finset.subset_univ _)
... = fintype.card (fin n → α) : finset.card_univ
... = fintype.card α^n : by simp
def V : set S := zero_set (S' d) (finset.univ \ neg_cA)
def V' : subspace α S := zero_set_subspace (S' d) (finset.univ \ neg_cA)
lemma p_in_V_vanishes {p : S} : p ∈ V →
∀ {x : fin n → α}, x ∉ neg_cA → p.eval x = 0
| ⟨_, p_spec⟩ _ h_xnmem := p_spec _ $ finset.mem_sdiff.2 ⟨finset.mem_univ _, h_xnmem⟩
lemma V_dim_finite : (vector_space.dim α V') < cardinal.omega :=
zero_set_subspace_dim _ _ (dim_span_of_finset _)
noncomputable def V_dim := (vector_space.dim α V').to_nat
include h_n_pos h_a_ne_zero
lemma diff_card_comp : (finset.univ \ neg_cA).card + A.card = q^n :=
by rw [finset.card_univ_diff, fintype.card_fin_arrow, neg_cA_card,
nat.sub_add_cancel A_card_le_α_card_n]; refl
theorem lemma_12_2 : q^n + V_dim ≥ m d + A.card :=
have V_dim + (finset.univ \ neg_cA).card ≥ m d,
from lemma_9_2 _ _ V_dim_finite,
by linarith [diff_card_comp]
omit h_a_ne_zero
def sup (p : S) : finset (fin n → α) :=
finset.univ.filter $ λ x, mv_polynomial.eval x p ≠ 0
lemma mem_sup_iff {p : S} {x : fin n → α} : x ∈ sup p ↔ p.eval x ≠ 0 :=
by rw [sup, finset.mem_filter, and_iff_right (finset.mem_univ _)]
lemma mem_sup {p : S} {x : fin n → α} : p.eval x ≠ 0 → x ∈ sup p := mem_sup_iff.2
lemma exi_max_sup : ∃ P ∈ V, ∀ P' ∈ V, sup P ⊆ sup P' → sup P = sup P' :=
begin
refine set.finite.exists_maximal_wrt sup _ _ _,
{ refine cardinal.lt_omega_iff_fintype.1 _,
apply cardinal_lt_omega_of_dim_lt_omega V_dim_finite },
exact set.ne_empty_iff_exists_mem.2 ⟨0, V'.zero_mem⟩
end
noncomputable def P := classical.some exi_max_sup
lemma P_V : P ∈ V := have _ := classical.some_spec exi_max_sup, by tauto
lemma P_in_S' : P ∈ S' d := P_V.1
lemma P_spec : ∀ P' ∈ V, sup P ⊆ sup P' → sup P = sup P' :=
have _ := classical.some_spec exi_max_sup, by tauto
noncomputable def P_sig := sup P
lemma eval_ne_zero_of_mem_P_sig {x} (hx : x ∈ P_sig) : P.eval x ≠ 0 :=
(finset.mem_filter.1 hx).2
lemma eval_eq_zero_of_not_mem_neg_cA {x} (hx : x ∉ neg_cA) : P.eval x = 0 :=
P_V.2 _ $ (finset.mem_sdiff.2 ⟨finset.mem_univ _, hx⟩)
def W : set S := zero_set V' P_sig
lemma eval_mem_W_eq_zero_of_not_mem_neg_cA {Q} (hQ : Q ∈ W) {x} (hx : x ∉ neg_cA) : Q.eval x = 0 :=
hQ.1.2 _ $ finset.mem_sdiff.2 ⟨finset.mem_univ _, hx⟩
noncomputable def W_dim := (vector_space.dim α (zero_set_subspace V' P_sig)).to_nat
lemma W_dim_ge : W_dim + P_sig.card ≥ V_dim :=
lemma_9_2 V' P_sig (zero_set_subspace_dim _ _ V_dim_finite)
theorem lemma_12_3 : P_sig.card ≥ V_dim :=
le_of_not_gt $
assume hlt : P_sig.card < V_dim,
have W_dim > 0, by linarith [W_dim_ge],
let ⟨Q, hQW, hQ⟩ := exists_mem_ne_zero_of_dim_pos (cardinal.pos_of_to_nat_pos this) in
have hPQ : ∀ x ∈ P_sig, (P + Q).eval x ≠ 0, from
assume x hxP_sig,
have hxP : P.eval x ≠ 0, from eval_ne_zero_of_mem_P_sig hxP_sig,
have hxQ : Q.eval x = 0, from hQW.2 _ hxP_sig,
by simp [hxP, hxQ],
have hQq : Q ∈ restrict_degree (fin n) α (q - 1) :=
begin
refine S'_le_restrict_q _ _, -- if instantiated with `d` and `hQW.1.1` it doesn't terminate!
exact d,
exact hQW.1.1,
end,
have ∃ y, Q.eval y ≠ 0, from
not_forall.1 $ mt (assume h, Q.eq_zero_of_eval_eq_zero _ _ h hQq) hQ,
let ⟨y, hQy⟩ := this in
have hPsig_y : y ∉ P_sig, from λ h, hQy $ hQW.2 _ h,
have hPy : P.eval y = 0, from by_contradiction $ λ h, hPsig_y (mem_sup h),
have (P + Q).eval y ≠ 0, by simp [hPy, hQy],
have hPQsup_y : y ∈ sup (P + Q), from mem_sup this,
have hxPQ : ∀ x, x ∈ finset.univ \ neg_cA → (P + Q).eval x = 0, from
λ _ hx, by cases finset.mem_sdiff.1 hx with _ hx;
simp [eval_eq_zero_of_not_mem_neg_cA hx, eval_mem_W_eq_zero_of_not_mem_neg_cA hQW hx],
have hmemS' : P + Q ∈ (S' d), from submodule.add_mem _ P_V.1 hQW.1.1,
have hPQV : (P + Q) ∈ V, from ⟨hmemS', hxPQ⟩,
have hSup : P_sig = sup (P + Q), from P_spec _ hPQV $ λ x hx, mem_sup (hPQ _ hx),
hPsig_y $ by rwa ←hSup at hPQsup_y
def A_antidiag : finset ((fin n → α) × (fin n → α)) :=
(A.product A).filter (λ p, p.1 ≠ p.2)
def abS : finset (fin n → α) := A_antidiag.image $ λ p, a•p.1 + b•p.2
include h_A
lemma inter_empty : abS ∩ neg_cA = ∅ :=
begin
apply finset.eq_empty_of_forall_not_mem,
intros x h_xmem,
rcases finset.mem_image.1 (finset.mem_of_mem_inter_left h_xmem) with ⟨⟨l, r⟩, hlr, hx_sum⟩,
rcases finset.mem_image.1 (finset.mem_of_mem_inter_right h_xmem) with ⟨w, hw, hx_w⟩,
cases finset.mem_filter.1 hlr with hp h_lrne,
cases finset.mem_product.1 hp with h_la h_ra,
dsimp at hx_sum,
have : a•l + b•r +c•w = 0, {rw [hx_sum, ←hx_w], simp},
apply h_lrne,
refine (h_A _ _ _ _ _ _ this).left; assumption
end
lemma P_vanishes_off_A_image (x : fin n → α) (h_xmemS : x ∉ neg_cA) :
mv_polynomial.eval x P = 0 :=
p_in_V_vanishes P_V h_xmemS
lemma P_vanishes_on_abS (x : fin n → α) (h_xmemS : x ∈ abS) : mv_polynomial.eval x P = 0 :=
begin
apply P_vanishes_off_A_image,
intro h_xmemimage,
apply finset.not_mem_empty x,
rw ←inter_empty,
apply finset.mem_inter_of_mem; assumption
end
lemma filter_eq : finset.univ.filter (λ x : fin n → α, mv_polynomial.eval x P ≠ 0) =
finset.filter (λ x, mv_polynomial.eval x P ≠ 0) neg_cA :=
finset.ext.2 $ λ x,
⟨ λ h_xmem,
let ⟨_, h_xeval⟩ := finset.mem_filter.1 h_xmem in
finset.mem_filter.2 ⟨have _, from P_vanishes_off_A_image x, by clear_aux_decl; tauto, h_xeval⟩,
λ h_xmem, finset.mem_filter.2 ⟨finset.mem_univ _, (finset.mem_filter.1 h_xmem).2⟩ ⟩
theorem lemma_12_4 : P_sig.card ≤ 2 * m (d/2) :=
have h_P_vanishes' : ∀ x, x ∈ A → ∀ y, y ∈ A → x ≠ y → mv_polynomial.eval (a•x + b•y) P = 0,
begin
intros x hx y hy hxy,
apply P_vanishes_on_abS (a•x + b•y),
apply finset.mem_image.2,
have : (x, y) ∈ A_antidiag, from finset.mem_filter.2 ⟨finset.mem_product.2 ⟨hx, hy⟩, hxy⟩,
apply exists.intro,
existsi this,
refl
end,
have h_bound : _ := proposition_11_1 d_nonneg A a b c P_in_S' h_sum h_P_vanishes',
have h_P_sig_def : P_sig = finset.image (λ z, (-c) • z) (A.filter (λ x, P.eval (-c•x) ≠ 0)), from calc
P_sig = finset.univ.filter (λ x, P.eval x ≠ 0) : rfl
... = finset.filter (λ x, P.eval x ≠ 0) neg_cA : filter_eq
... = finset.image (λ z, (-c) • z) (A.filter (λ x, P.eval (-c•x) ≠ 0)) : finset.image_filter,
have h_P_card : P_sig.card = (A.filter (λ x, P.eval (-c•x) ≠ 0)).card, from calc
P_sig.card = (finset.image (λ z, (-c) • z) (A.filter (λ a, P.eval (-c•a) ≠ 0))).card : by rw h_P_sig_def
... = ((A.filter (λ x, P.eval (-c•x) ≠ 0))).card : finset.card_image_of_injective _ map_is_bijective.1,
by rwa ←h_P_card at h_bound
omit h_A
section
omit h_n_pos
def l125_A : finset (fin n → fin q) := finset.univ
@[reducible] def monom (v : fin n → fin q) : mv_polynomial (fin n) α := monomial v 1
lemma total_degree_monom (v : fin n → fin q) : total_degree (monom v) = fin.sum (v : fin n → ℕ) :=
by simp only [monom, monomial_total_degree, fin_sum_finsupp_sum]; refl
def l125_B := l125_A.filter $ λ v, ↑(total_degree (monom v)) ≤ d
def l125_C := l125_A.filter $ λ v, ↑(total_degree (monom v)) > d
def l125_D := l125_A.filter $ λ v, ↑(total_degree (monom v)) < ((q : ℚ) - 1)*n - d
def l125_E := l125_A.filter $ λ v, ↑(total_degree (monom v)) ≤ ((q : ℚ) - 1)*n - d
lemma monom_exps_M'_card (k : ℚ) : ((M' k).image monom_exps).card = (M' k).card :=
finset.card_image_of_inj_on $
λ v1 hv1 v2 hv2 hv, monom_exps_inj (finset.mem_filter.1 hv1).1 (finset.mem_filter.1 hv2).1 hv
lemma monom_exps_M'_card_m (k : ℚ) : ((M' k).image monom_exps).card = m k :=
by rw [monom_exps_M'_card, M'_card]
lemma B_C_disjoint : disjoint l125_B l125_C :=
λ x hx, by linarith [(finset.mem_filter.1 (finset.mem_of_mem_inter_left hx)).2,
(finset.mem_filter.1 (finset.mem_of_mem_inter_right hx)).2]
lemma B_C_union : l125_B ∪ l125_C = l125_A :=
finset.ext.2 $ λ x,
⟨ λ _, finset.mem_univ _,
λ _, finset.mem_union.2 $
if hx : ↑(total_degree (monom x)) ≤ d then or.inl (finset.mem_filter.2 ⟨finset.mem_univ _, hx⟩)
else or.inr (finset.mem_filter.2 ⟨finset.mem_univ _, lt_of_not_ge hx⟩) ⟩
lemma filter_eq_image (r : ℚ) :
(l125_A.filter $ λ v, ↑(total_degree (monom v)) ≤ r) = (M' r).image monom_exps :=
finset.ext.2 $ λ x,
⟨ λ h, finset.mem_image.2
⟨ monomial x 1, finset.mem_filter.2 ⟨monomial_mem_M _, (finset.mem_filter.1 h).2⟩, by simp ⟩,
λ h, finset.mem_filter.2
⟨ finset.mem_univ _,
let ⟨a, ha, hax⟩ := finset.mem_image.1 h,
ha' := (finset.mem_filter.1 ha).2 in
by rw [←hax, monom, monom_exps_def (mem_M_of_mem_M' ha)]; exact ha' ⟩⟩
lemma le_helper (v : ℕ) : q - (v + 1) < q := nat.sub_lt one_le_q (nat.succ_pos _)
def invol (v : fin n → fin q) : fin n → fin q :=
λ x, ⟨q - (v x + 1), le_helper _⟩
lemma invol_add (v i) : ((invol v) i : ℕ) + v i = q - 1 :=
show q - (↑(v i) + 1) + ↑(v i) = q - 1,
begin
rw ←nat.sub_add_comm,
{ apply nat.sub_eq_of_eq_add,
rw [add_assoc _ 1, nat.add_sub_cancel'],
{ ac_refl },
{ exact one_le_q } },
{ apply nat.succ_le_of_lt,
apply fin.is_lt }
end
-- not sure why it appears like this below
lemma invol_add' (v i) : (⇑(invol v) : fin n → ℕ) i + (⇑v : fin n → ℕ) i = q - 1 :=
invol_add _ _
lemma invol_is_involution (x : fin n → fin q) : invol (invol x) = x :=
funext $ λ i, (fin.ext_iff _ _).2 $
show q - (q - (x i + 1) + 1) = x i,
begin
rw [←nat.sub_sub, ←nat.sub_sub, nat.sub_sub, nat.sub_add_cancel, nat.sub_sub_self],
{ apply le_of_lt, apply fin.is_lt },
{ apply (nat.add_le_to_le_sub _ _).1,
{ rw add_comm, apply fin.is_lt },
{ apply le_of_lt, apply fin.is_lt }}
end
lemma invol_inj : function.injective invol :=
λ v1 v2 hv, by rw [←invol_is_involution v1, ←invol_is_involution v2, hv]
lemma total_degree_invol_eq (v : fin n → fin q) :
↑(total_degree (monom (invol v))) = ((q : ℚ)-1)*n - ↑(total_degree (monom v)) :=
begin
simp only [total_degree_monom],
apply eq_sub_of_add_eq,
rw [←nat.cast_add, fin.sum_add],
simp only [invol_add'],
have qcast: ((q : ℚ) - 1) * n = ↑((q - 1)*n), {simp [nat.cast_sub one_le_q]},
rw [qcast, mul_comm], congr, -- something funny with the casts here
convert fin.sum_const _ _,
simp
end
lemma invol_total_degree (v : fin n → fin q) :
↑(total_degree (monom v)) > d ↔ ↑(total_degree (monom (invol v))) < ((q : ℚ) - 1)*n - d :=
by constructor; { rw total_degree_invol_eq, intro, linarith }
lemma D_eq_C_image_invol : l125_D = l125_C.image invol :=
finset.ext.2 $ λ v,
⟨ λ h, finset.mem_image.2
⟨invol v, finset.mem_filter.2 ⟨finset.mem_univ _,
by rw [invol_total_degree, invol_is_involution];
apply (finset.mem_filter.1 h).2⟩, invol_is_involution _⟩,
λ h, finset.mem_filter.2 ⟨finset.mem_univ _,
begin
rcases finset.mem_image.1 h with ⟨v', hv', hvv'⟩,
rw [←hvv', ←invol_total_degree],
apply (finset.mem_filter.1 hv').2
end⟩⟩
-- this is useful in asymptotics
parameters (α n d)
lemma h_B_card : l125_B.card = m d :=
by rw [l125_B, filter_eq_image, monom_exps_M'_card_m]
parameters {α n d}
include h_n_pos
theorem lemma_12_5 : q^n ≤ m (((q : ℚ) - 1)*n - d) + m d :=
have h_A_card : l125_A.card = q^n, by simp [finset.card_univ, l125_A],
have h_B_card : l125_B.card = m d, by rw [l125_B, filter_eq_image, monom_exps_M'_card_m],
have h_B_C_card : l125_B.card + l125_C.card = l125_A.card,
by rw [←finset.card_disjoint_union B_C_disjoint, B_C_union],
have h_C_D_card : l125_C.card = l125_D.card,
by rw [←finset.card_image_of_injective _ invol_inj, D_eq_C_image_invol],
have h_D_E_card : l125_D.card ≤ l125_E.card, from
finset.card_le_card_of_inj_on id
(λ a ha, finset.mem_filter.2 ⟨finset.mem_univ _, le_of_lt ((finset.mem_filter.1 ha).2)⟩)
(λ _ _ _ _, id),
have h_E_card : l125_E.card = m ((q-1)*n - d), by rw [l125_E, filter_eq_image, monom_exps_M'_card_m],
by linarith
include h_A hd h_a_ne_zero h_sum d_nonneg
theorem lemma_12_6 : A.card ≤ 2 * m (d/2) + m ((q - 1)*n - d) :=
by linarith [lemma_12_2, lemma_12_3, lemma_12_4, lemma_12_5]
end
end
include h_A h_n_pos h_a_ne_zero h_sum
theorem theorem_12_1 : A.card ≤ 3*(m (1/3*((q-1)*n))) :=
begin
set qn := ((q : ℚ) - 1)*n with hqn,
set! d := 2/3*qn with hd,
have : qn ≥ 0, from mul_nonneg (sub_nonneg_of_le one_le_q_real) (nat.cast_nonneg _),
have : d ≤ qn, {linarith},
have h_d2 : d / 2 = 1/3 * qn, {linarith},
have h_qnd : qn - d = 1/3 * qn, {linarith},
have h_l5, from lemma_12_6 this,
rw [h_d2, h_qnd] at h_l5,
convert h_l5 _,
{ ring },
{ apply mul_nonneg,
{ norm_num },
{ assumption } }
end
end Theorem4
end |
b155620d11a0cd1b6d9aa30d426ea4bd494a08bb | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/mv_polynomial/variables.lean | 80227f8c99ec02c43720d3454841070b6c014264 | [
"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 | 23,045 | 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.mv_polynomial.monad
import data.set.disjointed
/-!
# Degrees and variables of polynomials
This file establishes many results about the degree and variable sets of a multivariate polynomial.
The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$
that appears in a monomial in $P$.
The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the
variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a
monomial of $P$.
## Main declarations
* `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets
corresponding to each non-zero monomial in `p`.
For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}`
* `mv_polynomial.vars p` : the finset of variables occurring in `p`.
For example if `p = x⁴y+yz` then `vars p = {x, y, z}`
* `mv_polynomial.degree_of n p : ℕ` : the total degree of `p` with respect to the variable `n`.
For example if `p = x⁴y+yz` then `degree_of y p = 1`.
* `mv_polynomial.total_degree p : ℕ` :
the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`.
For example if `p = x⁴y+yz` then `total_degree p = 5`.
## Notation
As in other polynomial files, we typically use the 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`
+ `r : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ R`
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w
variables {R : Type u} {S : Type v}
namespace mv_polynomial
variables {σ τ : Type*} {r : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
variables [comm_semiring R] {p q : mv_polynomial σ R}
section degrees
/-! ### `degrees` -/
/--
The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset.
(For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.)
-/
def degrees (p : mv_polynomial σ R) : multiset σ :=
p.support.sup (λs:σ →₀ ℕ, s.to_multiset)
lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset :=
finset.sup_le $ assume t h,
begin
have := finsupp.support_single_subset h,
rw [finset.mem_singleton] at this,
rw this
end
lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) :
degrees (monomial s a) = s.to_multiset :=
le_antisymm (degrees_monomial s a) $ finset.le_sup $
by rw [support_monomial, if_neg ha, finset.mem_singleton]
lemma degrees_C (a : R) : degrees (C a : mv_polynomial σ R) = 0 :=
multiset.le_zero.1 $ degrees_monomial _ _
lemma degrees_X' (n : σ) : degrees (X n : mv_polynomial σ R) ≤ {n} :=
le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _
@[simp] lemma degrees_X [nontrivial R] (n : σ) : degrees (X n : mv_polynomial σ R) = {n} :=
(degrees_monomial_eq _ _ one_ne_zero).trans (to_multiset_single _ _)
@[simp] lemma degrees_zero : degrees (0 : mv_polynomial σ R) = 0 :=
by { rw ← C_0, exact degrees_C 0 }
@[simp] lemma degrees_one : degrees (1 : mv_polynomial σ R) = 0 := degrees_C 1
lemma degrees_add (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := finsupp.support_add hb, rw finset.mem_union at this,
cases this,
{ exact le_sup_left_of_le (finset.le_sup this) },
{ exact le_sup_right_of_le (finset.le_sup this) },
end
lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) :
(∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) :=
begin
refine s.induction _ _,
{ simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ },
{ assume i s his ih,
rw [finset.sup_insert, finset.sum_insert his],
exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) }
end
lemma degrees_mul (p q : mv_polynomial σ R) : (p * q).degrees ≤ p.degrees + q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := support_mul p q hb,
simp only [finset.mem_bUnion, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.to_multiset_add],
exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂)
end
lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) :
(∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees :=
begin
refine s.induction _ _,
{ simp only [finset.prod_empty, finset.sum_empty, degrees_one] },
{ assume i s his ih,
rw [finset.prod_insert his, finset.sum_insert his],
exact le_trans (degrees_mul _ _) (add_le_add_left ih _) }
end
lemma degrees_pow (p : mv_polynomial σ R) :
∀(n : ℕ), (p^n).degrees ≤ n •ℕ p.degrees
| 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end
| (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _)
lemma mem_degrees {p : mv_polynomial σ R} {i : σ} :
i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support :=
by simp only [degrees, multiset.mem_sup, ← mem_support_iff,
finsupp.mem_to_multiset, exists_prop]
lemma le_degrees_add {p q : mv_polynomial σ R} (h : p.degrees.disjoint q.degrees) :
p.degrees ≤ (p + q).degrees :=
begin
apply finset.sup_le,
intros d hd,
rw multiset.disjoint_iff_ne at h,
rw multiset.le_iff_count,
intros i,
rw [degrees, multiset.count_sup],
simp only [finsupp.count_to_multiset],
by_cases h0 : d = 0,
{ simp only [h0, zero_le, finsupp.zero_apply], },
{ refine @finset.le_sup _ _ _ (p + q).support _ d _,
rw [mem_support_iff, coeff_add],
suffices : q.coeff d = 0,
{ rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], },
rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0,
obtain ⟨j, hj⟩ := h0,
contrapose! h,
rw mem_support_iff at hd,
refine ⟨j, _, j, _, rfl⟩,
all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } }
end
lemma degrees_add_of_disjoint
{p q : mv_polynomial σ R} (h : multiset.disjoint p.degrees q.degrees) :
(p + q).degrees = p.degrees ∪ q.degrees :=
begin
apply le_antisymm,
{ apply degrees_add },
{ apply multiset.union_le,
{ apply le_degrees_add h },
{ rw add_comm, apply le_degrees_add h.symm } }
end
lemma degrees_map [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) :
(map f p).degrees ⊆ p.degrees :=
begin
dsimp only [degrees],
apply multiset.subset_of_le,
convert finset.sup_subset _ _,
apply mv_polynomial.support_map_subset
end
lemma degrees_rename (f : σ → τ) (φ : mv_polynomial σ R) :
(rename f φ).degrees ⊆ (φ.degrees.map f) :=
begin
intros i,
rw [mem_degrees, multiset.mem_map],
rintro ⟨d, hd, hi⟩,
obtain ⟨x, rfl, hx⟩ := coeff_rename_ne_zero _ _ _ hd,
simp only [map_domain, finsupp.mem_support_iff] at hi,
rw [sum_apply, finsupp.sum] at hi,
contrapose! hi,
rw [finset.sum_eq_zero],
intros j hj,
simp only [exists_prop, mem_degrees] at hi,
specialize hi j ⟨x, hx, hj⟩,
rw [single_apply, if_neg hi],
end
lemma degrees_map_of_injective [comm_semiring S] (p : mv_polynomial σ R)
{f : R →+* S} (hf : injective f) : (map f p).degrees = p.degrees :=
by simp only [degrees, mv_polynomial.support_map_of_injective _ hf]
end degrees
section vars
/-! ### `vars` -/
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : mv_polynomial σ R) : finset σ := p.degrees.to_finset
@[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ :=
by rw [vars, degrees_zero, multiset.to_finset_zero]
@[simp] lemma vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support :=
by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset]
@[simp] lemma vars_C : (C r : mv_polynomial σ R).vars = ∅ :=
by rw [vars, degrees_C, multiset.to_finset_zero]
@[simp] lemma vars_X [nontrivial R] : (X n : mv_polynomial σ R).vars = {n} :=
by rw [X, vars_monomial (@one_ne_zero R _ _), finsupp.support_single_ne_zero (one_ne_zero : 1 ≠ 0)]
lemma mem_vars (i : σ) :
i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support :=
by simp only [vars, multiset.mem_to_finset, mem_degrees, mem_support_iff,
exists_prop]
lemma mem_support_not_mem_vars_zero
{f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) :
x v = 0 :=
begin
rw [vars, multiset.mem_to_finset] at h,
rw ← finsupp.not_mem_support_iff,
contrapose! h,
unfold degrees,
rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H),
rw finset.sup_insert,
simp only [multiset.mem_union, multiset.sup_eq_union],
left,
rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h,
end
lemma vars_add_subset (p q : mv_polynomial σ R) :
(p + q).vars ⊆ p.vars ∪ q.vars :=
begin
intros x hx,
simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢,
simpa using multiset.mem_of_le (degrees_add _ _) hx,
end
lemma vars_add_of_disjoint (h : disjoint p.vars q.vars) :
(p + q).vars = p.vars ∪ q.vars :=
begin
apply finset.subset.antisymm (vars_add_subset p q),
intros x hx,
simp only [vars, multiset.disjoint_to_finset] at h hx ⊢,
rw [degrees_add_of_disjoint h, multiset.to_finset_union],
exact hx
end
section mul
lemma vars_mul (φ ψ : mv_polynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars :=
begin
intro i,
simp only [mem_vars, finset.mem_union],
rintro ⟨d, hd, hi⟩,
rw [mem_support_iff, coeff_mul] at hd,
contrapose! hd, cases hd,
rw finset.sum_eq_zero,
rintro ⟨d₁, d₂⟩ H,
rw finsupp.mem_antidiagonal_support at H,
subst H,
obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support,
{ simpa only [finset.mem_union] using finsupp.support_add hi, },
{ suffices : coeff d₁ φ = 0, by simp [this],
rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, },
{ suffices : coeff d₂ ψ = 0, by simp [this],
rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, },
end
@[simp] lemma vars_one : (1 : mv_polynomial σ R).vars = ∅ :=
vars_C
lemma vars_pow (φ : mv_polynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars :=
begin
induction n with n ih,
{ simp },
{ rw pow_succ,
apply finset.subset.trans (vars_mul _ _),
exact finset.union_subset (finset.subset.refl _) ih }
end
/--
The variables of the product of a family of polynomials
are a subset of the union of the sets of variables of each polynomial.
-/
lemma vars_prod {ι : Type*} {s : finset ι} (f : ι → mv_polynomial σ R) :
(∏ i in s, f i).vars ⊆ s.bUnion (λ i, (f i).vars) :=
begin
apply s.induction_on,
{ simp },
{ intros a s hs hsub,
simp only [hs, finset.bUnion_insert, finset.prod_insert, not_false_iff],
apply finset.subset.trans (vars_mul _ _),
exact finset.union_subset_union (finset.subset.refl _) hsub }
end
section integral_domain
variables {A : Type*} [integral_domain A]
lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars :=
begin
ext1 i,
simp only [mem_vars, exists_prop, mem_support_iff],
apply exists_congr,
intro d,
apply and_congr _ iff.rfl,
rw [coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and],
end
end integral_domain
end mul
section sum
variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ R)
lemma vars_sum_subset :
(∑ i in t, φ i).vars ⊆ finset.bUnion t (λ i, (φ i).vars) :=
begin
apply t.induction_on,
{ simp },
{ intros a s has hsum,
rw [finset.bUnion_insert, finset.sum_insert has],
refine finset.subset.trans (vars_add_subset _ _)
(finset.union_subset_union (finset.subset.refl _) _),
assumption }
end
lemma vars_sum_of_disjoint (h : pairwise $ disjoint on (λ i, (φ i).vars)) :
(∑ i in t, φ i).vars = finset.bUnion t (λ i, (φ i).vars) :=
begin
apply t.induction_on,
{ simp },
{ intros a s has hsum,
rw [finset.bUnion_insert, finset.sum_insert has, vars_add_of_disjoint, hsum],
unfold pairwise on_fun at h,
rw hsum,
simp only [finset.disjoint_iff_ne] at h ⊢,
intros v hv v2 hv2,
rw finset.mem_bUnion at hv2,
rcases hv2 with ⟨i, his, hi⟩,
refine h a i _ _ hv _ hi,
rintro rfl,
contradiction }
end
end sum
section map
variables [comm_semiring S] (f : R →+* S)
variable (p)
lemma vars_map : (map f p).vars ⊆ p.vars :=
by simp [vars, degrees_map]
variable {f}
lemma vars_map_of_injective (hf : injective f) :
(map f p).vars = p.vars :=
by simp [vars, degrees_map_of_injective _ hf]
lemma vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) :
(monomial (finsupp.single i e) r).vars = {i} :=
by rw [vars_monomial hr, finsupp.support_single_ne_zero he]
lemma vars_eq_support_bUnion_support : p.vars = p.support.bUnion finsupp.support :=
by { ext i, rw [mem_vars, finset.mem_bUnion] }
end map
end vars
section degree_of
/-! ### `degree_of` -/
/-- `degree_of n p` gives the highest power of X_n that appears in `p` -/
def degree_of (n : σ) (p : mv_polynomial σ R) : ℕ := p.degrees.count n
end degree_of
section total_degree
/-! ### `total_degree` -/
/-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/
def total_degree (p : mv_polynomial σ R) : ℕ := p.support.sup (λs, s.sum $ λn e, e)
lemma total_degree_eq (p : mv_polynomial σ R) :
p.total_degree = p.support.sup (λm, m.to_multiset.card) :=
begin
rw [total_degree],
congr, funext m,
exact (finsupp.card_to_multiset _).symm
end
lemma total_degree_le_degrees_card (p : mv_polynomial σ R) :
p.total_degree ≤ p.degrees.card :=
begin
rw [total_degree_eq],
exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs)
end
@[simp] lemma total_degree_C (a : R) : (C a : mv_polynomial σ R).total_degree = 0 :=
nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn,
have _ := finsupp.support_single_subset hn,
begin
rw [finset.mem_singleton] at this,
subst this,
exact le_refl _
end
@[simp] lemma total_degree_zero : (0 : mv_polynomial σ R).total_degree = 0 :=
by rw [← C_0]; exact total_degree_C (0 : R)
@[simp] lemma total_degree_one : (1 : mv_polynomial σ R).total_degree = 0 :=
total_degree_C (1 : R)
@[simp] lemma total_degree_X {R} [comm_semiring R] [nontrivial R] (s : σ) :
(X s : mv_polynomial σ R).total_degree = 1 :=
begin
rw [total_degree, support_X],
simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq],
end
lemma total_degree_add (a b : mv_polynomial σ R) :
(a + b).total_degree ≤ max a.total_degree b.total_degree :=
finset.sup_le $ assume n hn,
have _ := finsupp.support_add hn,
begin
rw finset.mem_union at this,
cases this,
{ exact le_max_left_of_le (finset.le_sup this) },
{ exact le_max_right_of_le (finset.le_sup this) }
end
lemma total_degree_mul (a b : mv_polynomial σ R) :
(a * b).total_degree ≤ a.total_degree + b.total_degree :=
finset.sup_le $ assume n hn,
have _ := add_monoid_algebra.support_mul a b hn,
begin
simp only [finset.mem_bUnion, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.sum_add_index],
{ exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) },
{ assume a, refl },
{ assume a b₁ b₂, refl }
end
lemma total_degree_pow (a : mv_polynomial σ R) (n : ℕ) :
(a ^ n).total_degree ≤ n * a.total_degree :=
begin
induction n with n ih,
{ simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] },
rw pow_succ,
calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _
... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _
... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm]
end
lemma total_degree_list_prod :
∀(s : list (mv_polynomial σ R)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum
| [] := by rw [@list.prod_nil (mv_polynomial σ R) _, total_degree_one]; refl
| (p :: ps) :=
begin
rw [@list.prod_cons (mv_polynomial σ R) _, list.map, list.sum_cons],
exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _)
end
lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ R)) :
s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum :=
begin
refine quotient.induction_on s (assume l, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum],
exact total_degree_list_prod l
end
lemma total_degree_finset_prod {ι : Type*}
(s : finset ι) (f : ι → mv_polynomial σ R) :
(s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree :=
begin
refine le_trans (total_degree_multiset_prod _) _,
rw [multiset.map_map],
refl
end
lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ R) (n : ℕ)
(h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) :
∃ i, d i < n :=
begin
contrapose! h,
calc n * fintype.card σ
= ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ]
... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s)
... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl }
... ≤ f.total_degree : finset.le_sup hd,
end
lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ R} {d : σ →₀ ℕ}
(h : f.total_degree < ∑ i in d.support, d i) :
coeff d f = 0 :=
begin
classical,
rw [total_degree, finset.sup_lt_iff] at h,
{ specialize h d, rw mem_support_iff at h,
refine not_not.mp (mt h _), exact lt_irrefl _, },
{ exact lt_of_le_of_lt (nat.zero_le _) h, }
end
lemma total_degree_rename_le (f : σ → τ) (p : mv_polynomial σ R) :
(rename f p).total_degree ≤ p.total_degree :=
finset.sup_le $ assume b,
begin
assume h,
rw rename_eq at h,
have h' := finsupp.map_domain_support h,
rw finset.mem_image at h',
rcases h' with ⟨s, hs, rfl⟩,
rw finsupp.sum_map_domain_index,
exact le_trans (le_refl _) (finset.le_sup hs),
exact assume _, rfl,
exact assume _ _ _, rfl
end
end total_degree
section eval_vars
/-! ### `vars` and `eval` -/
variables [comm_semiring S]
lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S) {g : σ → S}
{p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) :
eval₂_hom f g p = f (constant_coeff p) :=
begin
conv_lhs { rw p.as_sum },
simp only [ring_hom.map_sum, eval₂_hom_monomial],
by_cases h0 : constant_coeff p = 0,
work_on_goal 0
{ rw [h0, f.map_zero, finset.sum_eq_zero],
intros d hd },
work_on_goal 1
{ rw [finset.sum_eq_single (0 : σ →₀ ℕ)],
{ rw [finsupp.prod_zero_index, mul_one],
refl },
intros d hd hd0, },
repeat
{ obtain ⟨i, hi⟩ : d.support.nonempty,
{ rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0,
rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty],
rintro rfl, contradiction },
rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero],
rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)],
rw [mem_vars],
exact ⟨d, hd, hi⟩ },
{ rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0,
intro, contradiction }
end
lemma aeval_eq_constant_coeff_of_vars [algebra R S] {g : σ → S}
{p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) :
aeval g p = algebra_map _ _ (constant_coeff p) :=
eval₂_hom_eq_constant_coeff_of_vars _ hp
lemma eval₂_hom_congr' {f₁ f₂ : R →+* S} {g₁ g₂ : σ → S} {p₁ p₂ : mv_polynomial σ R} :
f₁ = f₂ → (∀ i, i ∈ p₁.vars → i ∈ p₂.vars → g₁ i = g₂ i) → p₁ = p₂ →
eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ :=
begin
rintro rfl h rfl,
rename [p₁ p, f₁ f],
rw p.as_sum,
simp only [ring_hom.map_sum, eval₂_hom_monomial],
apply finset.sum_congr rfl,
intros d hd,
congr' 1,
simp only [finsupp.prod],
apply finset.prod_congr rfl,
intros i hi,
have : i ∈ p.vars, { rw mem_vars, exact ⟨d, hd, hi⟩ },
rw h i this this,
end
lemma vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) :
(bind₁ f φ).vars ⊆ φ.vars.bUnion (λ i, (f i).vars) :=
begin
calc (bind₁ f φ).vars
= (φ.support.sum (λ (x : σ →₀ ℕ), (bind₁ f) (monomial x (coeff x φ)))).vars :
by { rw [← alg_hom.map_sum, ← φ.as_sum], }
... ≤ φ.support.bUnion (λ (i : σ →₀ ℕ), ((bind₁ f) (monomial i (coeff i φ))).vars) :
vars_sum_subset _ _
... = φ.support.bUnion (λ (d : σ →₀ ℕ), (C (coeff d φ) * ∏ i in d.support, f i ^ d i).vars) :
by simp only [bind₁_monomial]
... ≤ φ.support.bUnion (λ (d : σ →₀ ℕ), d.support.bUnion (λ i, (f i).vars)) : _ -- proof below
... ≤ φ.vars.bUnion (λ (i : σ), (f i).vars) : _, -- proof below
{ apply finset.bUnion_mono,
intros d hd,
calc (C (coeff d φ) * ∏ (i : σ) in d.support, f i ^ d i).vars
≤ (C (coeff d φ)).vars ∪ (∏ (i : σ) in d.support, f i ^ d i).vars : vars_mul _ _
... ≤ (∏ (i : σ) in d.support, f i ^ d i).vars :
by simp only [finset.empty_union, vars_C, finset.le_iff_subset, finset.subset.refl]
... ≤ d.support.bUnion (λ (i : σ), (f i ^ d i).vars) : vars_prod _
... ≤ d.support.bUnion (λ (i : σ), (f i).vars) : _,
apply finset.bUnion_mono,
intros i hi,
apply vars_pow, },
{ intro j,
simp_rw finset.mem_bUnion,
rintro ⟨d, hd, ⟨i, hi, hj⟩⟩,
exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ }
end
lemma mem_vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ}
(h : j ∈ (bind₁ f φ).vars) :
∃ (i : σ), i ∈ φ.vars ∧ j ∈ (f i).vars :=
by simpa only [exists_prop, finset.mem_bUnion, mem_support_iff, ne.def] using vars_bind₁ f φ h
lemma vars_rename (f : σ → τ) (φ : mv_polynomial σ R) :
(rename f φ).vars ⊆ (φ.vars.image f) :=
begin
intros i hi,
simp only [vars, exists_prop, multiset.mem_to_finset, finset.mem_image] at hi ⊢,
simpa only [multiset.mem_map] using degrees_rename _ _ hi
end
lemma mem_vars_rename (f : σ → τ) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (rename f φ).vars) :
∃ (i : σ), i ∈ φ.vars ∧ f i = j :=
by simpa only [exists_prop, finset.mem_image] using vars_rename f φ h
end eval_vars
end comm_semiring
end mv_polynomial
|
c3f61855088fcab5da3f8b48226f1d5e9d235fcb | f68ef9a599ec5575db7b285d4960e63c5d464ccc | /Exercises/Lista 7/cap16-LucasMoschen.lean | 06cb17cd3a3e36680b730de2e2dfdf9867bd5d54 | [] | no_license | lucasmoschen/discrete-mathematics | a38d5970cc571b0b9d202bf6a43efeb8ed6f66e3 | 0f1945cc5eb094814c926cd6ae4a8b4c5c579a1e | refs/heads/master | 1,677,111,757,003 | 1,611,500,097,000 | 1,611,500,097,000 | 205,903,359 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,081 | lean | -- Chapter 16
-- Lucas Machado Moschen
-- Exercício 1
import data.set
open function int algebra
section
def f (x : ℤ) : ℤ := x + 3
def g (x : ℤ) : ℤ := -x
def h (x : ℤ) : ℤ := 2 * x + 3
example : injective f :=
assume x1 x2,
assume h1 : x1 + 3 = x2 + 3, -- Lean knows this is the same as f x1 = f x2
show x1 = x2, from eq_of_add_eq_add_right h1
example : surjective f :=
assume y,
have h1 : f (y - 3) = y, from calc
f (y - 3) = (y - 3) + 3 : rfl
... = y : by rw sub_add_cancel,
show ∃ x, f x = y, from exists.intro (y - 3) h1
example (x y : ℤ) (h : 2 * x = 2 * y) : x = y :=
have h1 : 2 ≠ (0 : ℤ), from dec_trivial, -- this tells Lean to figure it out itself
show x = y, from eq_of_mul_eq_mul_left h1 h
example (x : ℤ) : -(-x) = x := neg_neg x
example (A B : Type) (u : A → B) (v : B → A) (h : left_inverse u v) :
∀ x, u (v x) = x :=
h
example (A B : Type) (u : A → B) (v : B → A) (h : left_inverse u v) :
right_inverse v u :=
h
-- fill in the sorry's in the following proofs
example : injective h :=
begin
assume x1 x2,
assume h1,
have h2: 2 ≠ (0 : ℤ), from dec_trivial,
apply eq_of_mul_eq_mul_left h2 (eq_of_add_eq_add_right h1),
end
example : surjective g :=
begin
assume y,
have h: g (-y) = y, from calc
g (-y) = -(-y) : rfl
... = y : by rw neg_neg,
apply exists.intro (-y),
exact h
end
example (A B : Type) (u : A → B) (v1 : B → A) (v2 : B → A)
(h1 : left_inverse v1 u) (h2 : right_inverse v2 u) : v1 = v2 :=
funext
(assume x,
calc
v1 x = v1 (u (v2 x)) : by rw h2
... = v2 x : by rw h1)
end
-- Exercício 2
section
open function set
variables {X Y : Type}
variable f : X → Y
variables A B : set X
example : f '' (A ∪ B) = f '' A ∪ f '' B :=
eq_of_subset_of_subset
(assume y,
assume h1 : y ∈ f '' (A ∪ B),
exists.elim h1 $
assume x h,
have h2 : x ∈ A ∪ B, from h.left,
have h3 : f x = y, from h.right,
or.elim h2
(assume h4 : x ∈ A,
have h5 : y ∈ f '' A, from ⟨x, h4, h3⟩,
show y ∈ f '' A ∪ f '' B, from or.inl h5)
(assume h4 : x ∈ B,
have h5 : y ∈ f '' B, from ⟨x, h4, h3⟩,
show y ∈ f '' A ∪ f '' B, from or.inr h5))
(assume y,
assume h2 : y ∈ f '' A ∪ f '' B,
or.elim h2
(assume h3 : y ∈ f '' A,
exists.elim h3 $
assume x h,
have h4 : x ∈ A, from h.left,
have h5 : f x = y, from h.right,
have h6 : x ∈ A ∪ B, from or.inl h4,
show y ∈ f '' (A ∪ B), from ⟨x, h6, h5⟩)
(assume h3 : y ∈ f '' B,
exists.elim h3 $
assume x h,
have h4 : x ∈ B, from h.left,
have h5 : f x = y, from h.right,
have h6 : x ∈ A ∪ B, from or.inr h4,
show y ∈ f '' (A ∪ B), from ⟨x, h6, h5⟩))
-- remember, x ∈ A ∩ B is the same as x ∈ A ∧ x ∈ B
example (x : X) (h1 : x ∈ A) (h2 : x ∈ B) : x ∈ A ∩ B :=
and.intro h1 h2
example (x : X) (h1 : x ∈ A ∩ B) : x ∈ A :=
and.left h1
-- Fill in the proof below.
-- (It should take about 8 lines.)
example : f '' (A ∩ B) ⊆ f '' A ∩ f '' B :=
assume y,
assume h1 : y ∈ f '' (A ∩ B),
show y ∈ f '' A ∩ f '' B, from
begin
apply and.intro,
cases h1 with x h2,
have h3: x ∈ A ∧ f x = y,
from and.intro (h2.left.left) h2.right,
apply exists.intro x,
exact h3,
cases h1 with x h2,
have h3: x ∈ B ∧ f x = y,
from and.intro (h2.left.right) h2.right,
apply exists.intro x,
exact h3
end
end |
5fae3e93ecdaa3ee8c314f2cca5831e582dcfc61 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/tactic/norm_swap.lean | 3b767dc45bb32aa0c062b39e69fa80f969e76d82 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 2,098 | lean | /-
Copyright (c) 2021 Yakov Pechersky All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import data.equiv.basic
import tactic.norm_fin
/-!
# `norm_swap`
Evaluating `swap x y z` for numerals `x y z` that are `ℕ`, `ℤ`, or `ℚ`, via a `norm_num` plugin.
Terms are passed to `eval`, quickly failing if not of the form `swap x y z`.
The expressions for numerals `x y z` are converted to `nat`, and then compared.
Based on equality of these `nat`s, equality proofs are generated using either
`equiv.swap_apply_left`, `equiv.swap_apply_right`, or `swap_apply_of_ne_of_ne`.
-/
open equiv tactic expr
open norm_num
namespace norm_swap
/--
A `norm_num` plugin for normalizing `equiv.swap a b c`
where `a b c` are numerals of `ℕ`, `ℤ`, `ℚ` or `fin n`.
```
example : equiv.swap 1 2 1 = 2 := by norm_num
```
-/
@[norm_num] meta def eval : expr → tactic (expr × expr) := λ e, do
(swapt, fun_ty, coe_fn_inst, fexpr, c) ← e.match_app_coe_fn
<|> fail "did not get an app coe_fn expr",
guard (fexpr.get_app_fn.const_name = ``equiv.swap) <|> fail "coe_fn not of equiv.swap",
[α, deceq_inst, a, b] ← pure fexpr.get_app_args <|>
fail "swap did not have exactly two args applied",
na ← a.to_rat <|> (do (fa, _) ← norm_fin.eval_fin_num a, fa.to_rat),
nb ← b.to_rat <|> (do (fb, _) ← norm_fin.eval_fin_num b, fb.to_rat),
nc ← c.to_rat <|> (do (fc, _) ← norm_fin.eval_fin_num c, fc.to_rat),
if nc = na then do
p ← mk_mapp `equiv.swap_apply_left [α, deceq_inst, a, b],
pure (b, p)
else if nc = nb then do
p ← mk_mapp `equiv.swap_apply_right [α, deceq_inst, a, b],
pure (a, p)
else do
nic ← mk_instance_cache α,
hca ← (prod.snd <$> prove_ne nic c a nc na) <|>
(do (_, ff, p) ← norm_fin.prove_eq_ne_fin c a, pure p),
hcb ← (prod.snd <$> prove_ne nic c b nc nb) <|>
(do (_, ff, p) ← norm_fin.prove_eq_ne_fin c b, pure p),
p ← mk_mapp `equiv.swap_apply_of_ne_of_ne [α, deceq_inst, a, b, c, hca, hcb],
pure (c, p)
end norm_swap
|
9c237a74b27b43a8015d9952e5cb4ac0ba6d7c50 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/equiv/transfer_instance.lean | f98abda590d767d7436d4335b2af61b233ea6417 | [
"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 | 10,488 | 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
-/
import data.equiv.basic
import algebra.field
import algebra.module
import algebra.algebra.basic
import algebra.group.type_tags
import ring_theory.ideal.basic
/-!
# Transfer algebraic structures across `equiv`s
In this file we prove theorems of the following form: if `β` has a
group structure and `α ≃ β` then `α` has a group structure, and
similarly for monoids, semigroups, rings, integral domains, fields and
so on.
Note that most of these constructions can also be obtained using the `transport` tactic.
## Tags
equiv, group, ring, field, module, algebra
-/
universes u v
variables {α : Type u} {β : Type v}
namespace equiv
section instances
variables (e : α ≃ β)
/-- Transfer `has_one` across an `equiv` -/
@[to_additive "Transfer `has_zero` across an `equiv`"]
protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩
@[to_additive]
lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl
/-- Transfer `has_mul` across an `equiv` -/
@[to_additive "Transfer `has_add` across an `equiv`"]
protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩
@[to_additive]
lemma mul_def [has_mul β] (x y : α) :
@has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl
/-- Transfer `has_inv` across an `equiv` -/
@[to_additive "Transfer `has_neg` across an `equiv`"]
protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩
@[to_additive]
lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl
/-- Transfer `has_scalar` across an `equiv` -/
protected def has_scalar {R : Type*} [has_scalar R β] : has_scalar R α :=
⟨λ r x, e.symm (r • (e x))⟩
lemma smul_def {R : Type*} [has_scalar R β] (r : R) (x : α) :
@has_scalar.smul _ _ (equiv.has_scalar e) r x = e.symm (r • (e x)) := rfl
/--
An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β`
where the multiplicative structure on `α` is
the one obtained by transporting a multiplicative structure on `β` back along `e`.
-/
@[to_additive
"An equivalence `e : α ≃ β` gives a additive equivalence `α ≃+ β`
where the additive structure on `α` is
the one obtained by transporting an additive structure on `β` back along `e`."]
def mul_equiv (e : α ≃ β) [has_mul β] :
by { letI := equiv.has_mul e, exact α ≃* β } :=
begin
introsI,
exact
{ map_mul' := λ x y, by { apply e.symm.injective, simp, refl, },
..e }
end
@[simp, to_additive] lemma mul_equiv_apply (e : α ≃ β) [has_mul β] (a : α) :
(mul_equiv e) a = e a := rfl
@[to_additive] lemma mul_equiv_symm_apply (e : α ≃ β) [has_mul β] (b : β) :
by { letI := equiv.has_mul e, exact (mul_equiv e).symm b = e.symm b } :=
begin
intros, refl,
end
/--
An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β`
where the ring structure on `α` is
the one obtained by transporting a ring structure on `β` back along `e`.
-/
def ring_equiv (e : α ≃ β) [has_add β] [has_mul β] :
by { letI := equiv.has_add e, letI := equiv.has_mul e, exact α ≃+* β } :=
begin
introsI,
exact
{ map_add' := λ x y, by { apply e.symm.injective, simp, refl, },
map_mul' := λ x y, by { apply e.symm.injective, simp, refl, },
..e }
end
@[simp] lemma ring_equiv_apply (e : α ≃ β) [has_add β] [has_mul β] (a : α) :
(ring_equiv e) a = e a := rfl
lemma ring_equiv_symm_apply (e : α ≃ β) [has_add β] [has_mul β] (b : β) :
by { letI := equiv.has_add e, letI := equiv.has_mul e, exact (ring_equiv e).symm b = e.symm b } :=
begin
intros, refl,
end
/-- Transfer `semigroup` across an `equiv` -/
@[to_additive "Transfer `add_semigroup` across an `equiv`"]
protected def semigroup [semigroup β] : semigroup α :=
{ mul_assoc := by simp [mul_def, mul_assoc],
..equiv.has_mul e }
/-- Transfer `comm_semigroup` across an `equiv` -/
@[to_additive "Transfer `add_comm_semigroup` across an `equiv`"]
protected def comm_semigroup [comm_semigroup β] : comm_semigroup α :=
{ mul_comm := by simp [mul_def, mul_comm],
..equiv.semigroup e }
/-- Transfer `monoid` across an `equiv` -/
@[to_additive "Transfer `add_monoid` across an `equiv`"]
protected def monoid [monoid β] : monoid α :=
{ one_mul := by simp [mul_def, one_def],
mul_one := by simp [mul_def, one_def],
..equiv.semigroup e,
..equiv.has_one e }
/-- Transfer `comm_monoid` across an `equiv` -/
@[to_additive "Transfer `add_comm_monoid` across an `equiv`"]
protected def comm_monoid [comm_monoid β] : comm_monoid α :=
{ ..equiv.comm_semigroup e,
..equiv.monoid e }
/-- Transfer `group` across an `equiv` -/
@[to_additive "Transfer `add_group` across an `equiv`"]
protected def group [group β] : group α :=
{ mul_left_inv := by simp [mul_def, inv_def, one_def],
..equiv.monoid e,
..equiv.has_inv e }
/-- Transfer `comm_group` across an `equiv` -/
@[to_additive "Transfer `add_comm_group` across an `equiv`"]
protected def comm_group [comm_group β] : comm_group α :=
{ ..equiv.group e,
..equiv.comm_semigroup e }
/-- Transfer `semiring` across an `equiv` -/
protected def semiring [semiring β] : semiring α :=
{ right_distrib := by simp [mul_def, add_def, add_mul],
left_distrib := by simp [mul_def, add_def, mul_add],
zero_mul := by simp [mul_def, zero_def],
mul_zero := by simp [mul_def, zero_def],
..equiv.has_zero e,
..equiv.has_mul e,
..equiv.has_add e,
..equiv.monoid e,
..equiv.add_comm_monoid e }
/-- Transfer `comm_semiring` across an `equiv` -/
protected def comm_semiring [comm_semiring β] : comm_semiring α :=
{ ..equiv.semiring e,
..equiv.comm_monoid e }
/-- Transfer `ring` across an `equiv` -/
protected def ring [ring β] : ring α :=
{ ..equiv.semiring e,
..equiv.add_comm_group e }
/-- Transfer `comm_ring` across an `equiv` -/
protected def comm_ring [comm_ring β] : comm_ring α :=
{ ..equiv.comm_monoid e,
..equiv.ring e }
/-- Transfer `nonzero` across an `equiv` -/
protected theorem nontrivial [nontrivial β] : nontrivial α :=
let ⟨x, y, h⟩ := exists_pair_ne β in ⟨⟨e.symm x, e.symm y, e.symm.injective.ne h⟩⟩
/-- Transfer `domain` across an `equiv` -/
protected def domain [domain β] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.eq_symm_apply],
..equiv.ring e,
..equiv.nontrivial e }
/-- Transfer `integral_domain` across an `equiv` -/
protected def integral_domain [integral_domain β] : integral_domain α :=
{ ..equiv.domain e,
..equiv.comm_ring e }
/-- Transfer `division_ring` across an `equiv` -/
protected def division_ring [division_ring β] : division_ring α :=
{ inv_mul_cancel := λ _,
by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm];
exact inv_mul_cancel,
mul_inv_cancel := λ _,
by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm];
exact mul_inv_cancel,
inv_zero := by simp [zero_def, inv_def],
..equiv.has_zero e,
..equiv.has_one e,
..equiv.domain e,
..equiv.has_inv e }
/-- Transfer `field` across an `equiv` -/
protected def field [field β] : field α :=
{ ..equiv.integral_domain e,
..equiv.division_ring e }
section R
variables (R : Type*)
include R
section
variables [monoid R]
/-- Transfer `mul_action` across an `equiv` -/
protected def mul_action (e : α ≃ β) [mul_action R β] : mul_action R α :=
{ one_smul := by simp [smul_def],
mul_smul := by simp [smul_def, mul_smul],
..equiv.has_scalar e }
/-- Transfer `distrib_mul_action` across an `equiv` -/
protected def distrib_mul_action (e : α ≃ β) [add_comm_monoid β] :
begin
letI := equiv.add_comm_monoid e,
exact Π [distrib_mul_action R β], distrib_mul_action R α
end :=
begin
intros,
letI := equiv.add_comm_monoid e,
exact (
{ smul_zero := by simp [zero_def, smul_def],
smul_add := by simp [add_def, smul_def, smul_add],
..equiv.mul_action R e } : distrib_mul_action R α)
end
end
section
variables [semiring R]
/-- Transfer `semimodule` across an `equiv` -/
protected def semimodule (e : α ≃ β) [add_comm_monoid β] :
begin
letI := equiv.add_comm_monoid e,
exact Π [semimodule R β], semimodule R α
end :=
begin
introsI,
exact (
{ zero_smul := by simp [zero_def, smul_def],
add_smul := by simp [add_def, smul_def, add_smul],
..equiv.distrib_mul_action R e } : semimodule R α)
end
/--
An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β`
where the `R`-module structure on `α` is
the one obtained by transporting an `R`-module structure on `β` back along `e`.
-/
def linear_equiv (e : α ≃ β) [add_comm_monoid β] [semimodule R β] :
begin
letI := equiv.add_comm_monoid e,
letI := equiv.semimodule R e,
exact α ≃ₗ[R] β
end :=
begin
introsI,
exact
{ map_smul' := λ r x, by { apply e.symm.injective, simp, refl, },
..equiv.add_equiv e }
end
end
section
variables [comm_semiring R]
/-- Transfer `algebra` across an `equiv` -/
protected def algebra (e : α ≃ β) [semiring β] :
begin
letI := equiv.semiring e,
exact Π [algebra R β], algebra R α
end :=
begin
introsI,
fapply ring_hom.to_algebra',
{ exact ((ring_equiv e).symm : β →+* α).comp (algebra_map R β), },
{ intros r x,
simp only [function.comp_app, ring_hom.coe_comp],
have p := ring_equiv_symm_apply e,
dsimp at p,
erw p, clear p,
apply (ring_equiv e).injective,
simp only [(ring_equiv e).map_mul],
simp [algebra.commutes], }
end
/--
An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β`
where the `R`-algebra structure on `α` is
the one obtained by transporting an `R`-algebra structure on `β` back along `e`.
-/
def alg_equiv (e : α ≃ β) [semiring β] [algebra R β] :
begin
letI := equiv.semiring e,
letI := equiv.algebra R e,
exact α ≃ₐ[R] β
end :=
begin
introsI,
exact
{ commutes' := λ r, by { apply e.symm.injective, simp, refl, },
..equiv.ring_equiv e }
end
end
end R
end instances
end equiv
namespace ring_equiv
protected lemma local_ring {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] (e : A ≃+* B) :
local_ring B :=
begin
haveI := e.symm.to_equiv.nontrivial,
refine @local_of_surjective A B _ _ _ _ e e.to_equiv.surjective,
end
end ring_equiv
|
04d998addd182cb837d5e20ffaca22121479ebaa | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/analysis/special_functions/trigonometric.lean | 03f6dcd9c00488f72f9c99bc8d9a252e5119e7bf | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 103,067 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson
-/
import analysis.special_functions.exp_log
import data.set.intervals.infinite
import algebra.quadratic_discriminant
import ring_theory.polynomial.chebyshev.defs
/-!
# Trigonometric functions
## Main definitions
This file contains the following definitions:
* π, arcsin, arccos, arctan
* argument of a complex number
* logarithm on complex numbers
## Main statements
Many basic inequalities on trigonometric functions are established.
The continuity and differentiability of the usual trigonometric functions are proved, and their
derivatives are computed.
* `polynomial.chebyshev₁_complex_cos`: the `n`-th Chebyshev polynomial evaluates on `complex.cos θ`
to the value `n * complex.cos θ`.
## Tags
log, sin, cos, tan, arcsin, arccos, arctan, angle, argument
-/
noncomputable theory
open_locale classical
open set
namespace complex
/-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/
lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x :=
begin
simp only [cos, div_eq_mul_inv],
convert ((((has_deriv_at_id x).neg.mul_const I).cexp.sub
((has_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹,
simp only [function.comp, id],
rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc,
I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm]
end
lemma times_cont_diff_sin {n} : times_cont_diff ℂ n sin :=
(((times_cont_diff_neg.mul times_cont_diff_const).cexp.sub
(times_cont_diff_id.mul times_cont_diff_const).cexp).mul times_cont_diff_const).div_const
lemma differentiable_sin : differentiable ℂ sin :=
λx, (has_deriv_at_sin x).differentiable_at
lemma differentiable_at_sin {x : ℂ} : differentiable_at ℂ sin x :=
differentiable_sin x
@[simp] lemma deriv_sin : deriv sin = cos :=
funext $ λ x, (has_deriv_at_sin x).deriv
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
lemma continuous_on_sin {s : set ℂ} : continuous_on sin s := continuous_sin.continuous_on
lemma measurable_sin : measurable sin := continuous_sin.measurable
/-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/
lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x :=
begin
simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul],
convert (((has_deriv_at_id x).mul_const I).cexp.add
((has_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹,
simp only [function.comp, id],
ring
end
lemma times_cont_diff_cos {n} : times_cont_diff ℂ n cos :=
((times_cont_diff_id.mul times_cont_diff_const).cexp.add
(times_cont_diff_neg.mul times_cont_diff_const).cexp).div_const
lemma differentiable_cos : differentiable ℂ cos :=
λx, (has_deriv_at_cos x).differentiable_at
lemma differentiable_at_cos {x : ℂ} : differentiable_at ℂ cos x :=
differentiable_cos x
lemma deriv_cos {x : ℂ} : deriv cos x = -sin x :=
(has_deriv_at_cos x).deriv
@[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) :=
funext $ λ x, deriv_cos
lemma continuous_cos : continuous cos :=
differentiable_cos.continuous
lemma continuous_on_cos {s : set ℂ} : continuous_on cos s := continuous_cos.continuous_on
lemma measurable_cos : measurable cos := continuous_cos.measurable
/-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `cosh x`. -/
lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x :=
begin
simp only [cosh, div_eq_mul_inv],
convert ((has_deriv_at_exp x).sub (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹,
rw [id, mul_neg_one, neg_neg]
end
lemma times_cont_diff_sinh {n} : times_cont_diff ℂ n sinh :=
(times_cont_diff_exp.sub times_cont_diff_neg.cexp).div_const
lemma differentiable_sinh : differentiable ℂ sinh :=
λx, (has_deriv_at_sinh x).differentiable_at
lemma differentiable_at_sinh {x : ℂ} : differentiable_at ℂ sinh x :=
differentiable_sinh x
@[simp] lemma deriv_sinh : deriv sinh = cosh :=
funext $ λ x, (has_deriv_at_sinh x).deriv
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
/-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `sinh x`. -/
lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x :=
begin
simp only [sinh, div_eq_mul_inv],
convert ((has_deriv_at_exp x).add (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹,
rw [id, mul_neg_one, sub_eq_add_neg]
end
lemma times_cont_diff_cosh {n} : times_cont_diff ℂ n cosh :=
(times_cont_diff_exp.add times_cont_diff_neg.cexp).div_const
lemma differentiable_cosh : differentiable ℂ cosh :=
λx, (has_deriv_at_cosh x).differentiable_at
lemma differentiable_at_cosh {x : ℂ} : differentiable_at ℂ cos x :=
differentiable_cos x
@[simp] lemma deriv_cosh : deriv cosh = sinh :=
funext $ λ x, (has_deriv_at_cosh x).deriv
lemma continuous_cosh : continuous cosh :=
differentiable_cosh.continuous
lemma measurable_cosh : measurable cosh := continuous_cosh.measurable
end complex
section
/-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : ℂ → ℂ` -/
variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ}
/-! #### `complex.cos` -/
lemma measurable.ccos {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.cos (f x)) :=
complex.measurable_cos.comp hf
lemma has_deriv_at.ccos (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x :=
(complex.has_deriv_at_cos (f x)).comp x hf
lemma has_deriv_within_at.ccos (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') s x :=
(complex.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_ccos (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.cos (f x)) s x = - complex.sin (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.ccos.deriv_within hxs
@[simp] lemma deriv_ccos (hc : differentiable_at ℂ f x) :
deriv (λx, complex.cos (f x)) x = - complex.sin (f x) * (deriv f x) :=
hc.has_deriv_at.ccos.deriv
/-! #### `complex.sin` -/
lemma measurable.csin {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.sin (f x)) :=
complex.measurable_sin.comp hf
lemma has_deriv_at.csin (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x :=
(complex.has_deriv_at_sin (f x)).comp x hf
lemma has_deriv_within_at.csin (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') s x :=
(complex.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_csin (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.sin (f x)) s x = complex.cos (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.csin.deriv_within hxs
@[simp] lemma deriv_csin (hc : differentiable_at ℂ f x) :
deriv (λx, complex.sin (f x)) x = complex.cos (f x) * (deriv f x) :=
hc.has_deriv_at.csin.deriv
/-! #### `complex.cosh` -/
lemma measurable.ccosh {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.cosh (f x)) :=
complex.measurable_cosh.comp hf
lemma has_deriv_at.ccosh (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x :=
(complex.has_deriv_at_cosh (f x)).comp x hf
lemma has_deriv_within_at.ccosh (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') s x :=
(complex.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_ccosh (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.cosh (f x)) s x = complex.sinh (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.ccosh.deriv_within hxs
@[simp] lemma deriv_ccosh (hc : differentiable_at ℂ f x) :
deriv (λx, complex.cosh (f x)) x = complex.sinh (f x) * (deriv f x) :=
hc.has_deriv_at.ccosh.deriv
/-! #### `complex.sinh` -/
lemma measurable.csinh {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.sinh (f x)) :=
complex.measurable_sinh.comp hf
lemma has_deriv_at.csinh (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x :=
(complex.has_deriv_at_sinh (f x)).comp x hf
lemma has_deriv_within_at.csinh (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') s x :=
(complex.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_csinh (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.sinh (f x)) s x = complex.cosh (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.csinh.deriv_within hxs
@[simp] lemma deriv_csinh (hc : differentiable_at ℂ f x) :
deriv (λx, complex.sinh (f x)) x = complex.cosh (f x) * (deriv f x) :=
hc.has_deriv_at.csinh.deriv
end
section
/-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : E → ℂ` -/
variables {E : Type*} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ}
{x : E} {s : set E}
/-! #### `complex.cos` -/
lemma has_fderiv_at.ccos (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') x :=
(complex.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.ccos (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') s x :=
(complex.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.ccos (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.cos (f x)) s x :=
hf.has_fderiv_within_at.ccos.differentiable_within_at
@[simp] lemma differentiable_at.ccos (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.cos (f x)) x :=
hc.has_fderiv_at.ccos.differentiable_at
lemma differentiable_on.ccos (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.cos (f x)) s :=
λx h, (hc x h).ccos
@[simp] lemma differentiable.ccos (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.cos (f x)) :=
λx, (hc x).ccos
lemma fderiv_within_ccos (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
fderiv_within ℂ (λx, complex.cos (f x)) s x = - complex.sin (f x) • (fderiv_within ℂ f s x) :=
hf.has_fderiv_within_at.ccos.fderiv_within hxs
@[simp] lemma fderiv_ccos (hc : differentiable_at ℂ f x) :
fderiv ℂ (λx, complex.cos (f x)) x = - complex.sin (f x) • (fderiv ℂ f x) :=
hc.has_fderiv_at.ccos.fderiv
lemma times_cont_diff.ccos {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.cos (f x)) :=
complex.times_cont_diff_cos.comp h
lemma times_cont_diff_at.ccos {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.cos (f x)) x :=
complex.times_cont_diff_cos.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.ccos {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.cos (f x)) s :=
complex.times_cont_diff_cos.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.ccos {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.cos (f x)) s x :=
complex.times_cont_diff_cos.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `complex.sin` -/
lemma has_fderiv_at.csin (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') x :=
(complex.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.csin (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') s x :=
(complex.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.csin (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.sin (f x)) s x :=
hf.has_fderiv_within_at.csin.differentiable_within_at
@[simp] lemma differentiable_at.csin (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.sin (f x)) x :=
hc.has_fderiv_at.csin.differentiable_at
lemma differentiable_on.csin (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.sin (f x)) s :=
λx h, (hc x h).csin
@[simp] lemma differentiable.csin (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.sin (f x)) :=
λx, (hc x).csin
lemma fderiv_within_csin (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
fderiv_within ℂ (λx, complex.sin (f x)) s x = complex.cos (f x) • (fderiv_within ℂ f s x) :=
hf.has_fderiv_within_at.csin.fderiv_within hxs
@[simp] lemma fderiv_csin (hc : differentiable_at ℂ f x) :
fderiv ℂ (λx, complex.sin (f x)) x = complex.cos (f x) • (fderiv ℂ f x) :=
hc.has_fderiv_at.csin.fderiv
lemma times_cont_diff.csin {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.sin (f x)) :=
complex.times_cont_diff_sin.comp h
lemma times_cont_diff_at.csin {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.sin (f x)) x :=
complex.times_cont_diff_sin.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.csin {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.sin (f x)) s :=
complex.times_cont_diff_sin.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.csin {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.sin (f x)) s x :=
complex.times_cont_diff_sin.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `complex.cosh` -/
lemma has_fderiv_at.ccosh (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') x :=
(complex.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.ccosh (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') s x :=
(complex.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.ccosh (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.cosh (f x)) s x :=
hf.has_fderiv_within_at.ccosh.differentiable_within_at
@[simp] lemma differentiable_at.ccosh (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.cosh (f x)) x :=
hc.has_fderiv_at.ccosh.differentiable_at
lemma differentiable_on.ccosh (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.cosh (f x)) s :=
λx h, (hc x h).ccosh
@[simp] lemma differentiable.ccosh (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.cosh (f x)) :=
λx, (hc x).ccosh
lemma fderiv_within_ccosh (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
fderiv_within ℂ (λx, complex.cosh (f x)) s x = complex.sinh (f x) • (fderiv_within ℂ f s x) :=
hf.has_fderiv_within_at.ccosh.fderiv_within hxs
@[simp] lemma fderiv_ccosh (hc : differentiable_at ℂ f x) :
fderiv ℂ (λx, complex.cosh (f x)) x = complex.sinh (f x) • (fderiv ℂ f x) :=
hc.has_fderiv_at.ccosh.fderiv
lemma times_cont_diff.ccosh {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.cosh (f x)) :=
complex.times_cont_diff_cosh.comp h
lemma times_cont_diff_at.ccosh {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.cosh (f x)) x :=
complex.times_cont_diff_cosh.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.ccosh {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.cosh (f x)) s :=
complex.times_cont_diff_cosh.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.ccosh {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.cosh (f x)) s x :=
complex.times_cont_diff_cosh.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `complex.sinh` -/
lemma has_fderiv_at.csinh (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') x :=
(complex.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.csinh (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') s x :=
(complex.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.csinh (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.sinh (f x)) s x :=
hf.has_fderiv_within_at.csinh.differentiable_within_at
@[simp] lemma differentiable_at.csinh (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.sinh (f x)) x :=
hc.has_fderiv_at.csinh.differentiable_at
lemma differentiable_on.csinh (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.sinh (f x)) s :=
λx h, (hc x h).csinh
@[simp] lemma differentiable.csinh (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.sinh (f x)) :=
λx, (hc x).csinh
lemma fderiv_within_csinh (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
fderiv_within ℂ (λx, complex.sinh (f x)) s x = complex.cosh (f x) • (fderiv_within ℂ f s x) :=
hf.has_fderiv_within_at.csinh.fderiv_within hxs
@[simp] lemma fderiv_csinh (hc : differentiable_at ℂ f x) :
fderiv ℂ (λx, complex.sinh (f x)) x = complex.cosh (f x) • (fderiv ℂ f x) :=
hc.has_fderiv_at.csinh.fderiv
lemma times_cont_diff.csinh {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.sinh (f x)) :=
complex.times_cont_diff_sinh.comp h
lemma times_cont_diff_at.csinh {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.sinh (f x)) x :=
complex.times_cont_diff_sinh.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.csinh {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.sinh (f x)) s :=
complex.times_cont_diff_sinh.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.csinh {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.sinh (f x)) s x :=
complex.times_cont_diff_sinh.times_cont_diff_at.comp_times_cont_diff_within_at x hf
end
namespace real
variables {x y z : ℝ}
lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x :=
(complex.has_deriv_at_sin x).real_of_complex
lemma times_cont_diff_sin {n} : times_cont_diff ℝ n sin :=
complex.times_cont_diff_sin.real_of_complex
lemma differentiable_sin : differentiable ℝ sin :=
λx, (has_deriv_at_sin x).differentiable_at
lemma differentiable_at_sin : differentiable_at ℝ sin x :=
differentiable_sin x
@[simp] lemma deriv_sin : deriv sin = cos :=
funext $ λ x, (has_deriv_at_sin x).deriv
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
lemma measurable_sin : measurable sin := continuous_sin.measurable
lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x :=
(complex.has_deriv_at_cos x).real_of_complex
lemma times_cont_diff_cos {n} : times_cont_diff ℝ n cos :=
complex.times_cont_diff_cos.real_of_complex
lemma differentiable_cos : differentiable ℝ cos :=
λx, (has_deriv_at_cos x).differentiable_at
lemma differentiable_at_cos : differentiable_at ℝ cos x :=
differentiable_cos x
lemma deriv_cos : deriv cos x = - sin x :=
(has_deriv_at_cos x).deriv
@[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) :=
funext $ λ _, deriv_cos
lemma continuous_cos : continuous cos :=
differentiable_cos.continuous
lemma continuous_on_cos {s} : continuous_on cos s := continuous_cos.continuous_on
lemma measurable_cos : measurable cos := continuous_cos.measurable
lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x :=
(complex.has_deriv_at_sinh x).real_of_complex
lemma times_cont_diff_sinh {n} : times_cont_diff ℝ n sinh :=
complex.times_cont_diff_sinh.real_of_complex
lemma differentiable_sinh : differentiable ℝ sinh :=
λx, (has_deriv_at_sinh x).differentiable_at
lemma differentiable_at_sinh : differentiable_at ℝ sinh x :=
differentiable_sinh x
@[simp] lemma deriv_sinh : deriv sinh = cosh :=
funext $ λ x, (has_deriv_at_sinh x).deriv
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x :=
(complex.has_deriv_at_cosh x).real_of_complex
lemma times_cont_diff_cosh {n} : times_cont_diff ℝ n cosh :=
complex.times_cont_diff_cosh.real_of_complex
lemma differentiable_cosh : differentiable ℝ cosh :=
λx, (has_deriv_at_cosh x).differentiable_at
lemma differentiable_at_cosh : differentiable_at ℝ cosh x :=
differentiable_cosh x
@[simp] lemma deriv_cosh : deriv cosh = sinh :=
funext $ λ x, (has_deriv_at_cosh x).deriv
lemma continuous_cosh : continuous cosh :=
differentiable_cosh.continuous
lemma measurable_cosh : measurable cosh := continuous_cosh.measurable
/-- `sinh` is strictly monotone. -/
lemma sinh_strict_mono : strict_mono sinh :=
strict_mono_of_deriv_pos differentiable_sinh (by { rw [real.deriv_sinh], exact cosh_pos })
end real
section
/-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : ℝ → ℝ` -/
variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ}
/-! #### `real.cos` -/
lemma measurable.cos {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.cos (f x)) :=
real.measurable_cos.comp hf
lemma has_deriv_at.cos (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x :=
(real.has_deriv_at_cos (f x)).comp x hf
lemma has_deriv_within_at.cos (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.cos (f x)) (- real.sin (f x) * f') s x :=
(real.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_cos (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.cos (f x)) s x = - real.sin (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.cos.deriv_within hxs
@[simp] lemma deriv_cos (hc : differentiable_at ℝ f x) :
deriv (λx, real.cos (f x)) x = - real.sin (f x) * (deriv f x) :=
hc.has_deriv_at.cos.deriv
/-! #### `real.sin` -/
lemma measurable.sin {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.sin (f x)) :=
real.measurable_sin.comp hf
lemma has_deriv_at.sin (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x :=
(real.has_deriv_at_sin (f x)).comp x hf
lemma has_deriv_within_at.sin (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.sin (f x)) (real.cos (f x) * f') s x :=
(real.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_sin (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.sin (f x)) s x = real.cos (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.sin.deriv_within hxs
@[simp] lemma deriv_sin (hc : differentiable_at ℝ f x) :
deriv (λx, real.sin (f x)) x = real.cos (f x) * (deriv f x) :=
hc.has_deriv_at.sin.deriv
/-! #### `real.cosh` -/
lemma measurable.cosh {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.cosh (f x)) :=
real.measurable_cosh.comp hf
lemma has_deriv_at.cosh (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x :=
(real.has_deriv_at_cosh (f x)).comp x hf
lemma has_deriv_within_at.cosh (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') s x :=
(real.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_cosh (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.cosh (f x)) s x = real.sinh (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.cosh.deriv_within hxs
@[simp] lemma deriv_cosh (hc : differentiable_at ℝ f x) :
deriv (λx, real.cosh (f x)) x = real.sinh (f x) * (deriv f x) :=
hc.has_deriv_at.cosh.deriv
/-! #### `real.sinh` -/
lemma measurable.sinh {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.sinh (f x)) :=
real.measurable_sinh.comp hf
lemma has_deriv_at.sinh (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x :=
(real.has_deriv_at_sinh (f x)).comp x hf
lemma has_deriv_within_at.sinh (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') s x :=
(real.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_sinh (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.sinh (f x)) s x = real.cosh (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.sinh.deriv_within hxs
@[simp] lemma deriv_sinh (hc : differentiable_at ℝ f x) :
deriv (λx, real.sinh (f x)) x = real.cosh (f x) * (deriv f x) :=
hc.has_deriv_at.sinh.deriv
end
section
/-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : E → ℝ` -/
variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ}
{x : E} {s : set E}
/-! #### `real.cos` -/
lemma has_fderiv_at.cos (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.cos (f x)) (- real.sin (f x) • f') x :=
(real.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.cos (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.cos (f x)) (- real.sin (f x) • f') s x :=
(real.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.cos (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.cos (f x)) s x :=
hf.has_fderiv_within_at.cos.differentiable_within_at
@[simp] lemma differentiable_at.cos (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.cos (f x)) x :=
hc.has_fderiv_at.cos.differentiable_at
lemma differentiable_on.cos (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.cos (f x)) s :=
λx h, (hc x h).cos
@[simp] lemma differentiable.cos (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.cos (f x)) :=
λx, (hc x).cos
lemma fderiv_within_cos (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.cos (f x)) s x = - real.sin (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.cos.fderiv_within hxs
@[simp] lemma fderiv_cos (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.cos (f x)) x = - real.sin (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.cos.fderiv
lemma times_cont_diff.cos {n} (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.cos (f x)) :=
real.times_cont_diff_cos.comp h
lemma times_cont_diff_at.cos {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.cos (f x)) x :=
real.times_cont_diff_cos.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.cos {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.cos (f x)) s :=
real.times_cont_diff_cos.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.cos {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.cos (f x)) s x :=
real.times_cont_diff_cos.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `real.sin` -/
lemma has_fderiv_at.sin (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.sin (f x)) (real.cos (f x) • f') x :=
(real.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.sin (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.sin (f x)) (real.cos (f x) • f') s x :=
(real.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.sin (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.sin (f x)) s x :=
hf.has_fderiv_within_at.sin.differentiable_within_at
@[simp] lemma differentiable_at.sin (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.sin (f x)) x :=
hc.has_fderiv_at.sin.differentiable_at
lemma differentiable_on.sin (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.sin (f x)) s :=
λx h, (hc x h).sin
@[simp] lemma differentiable.sin (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.sin (f x)) :=
λx, (hc x).sin
lemma fderiv_within_sin (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.sin (f x)) s x = real.cos (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.sin.fderiv_within hxs
@[simp] lemma fderiv_sin (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.sin (f x)) x = real.cos (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.sin.fderiv
lemma times_cont_diff.sin {n} (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.sin (f x)) :=
real.times_cont_diff_sin.comp h
lemma times_cont_diff_at.sin {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.sin (f x)) x :=
real.times_cont_diff_sin.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.sin {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.sin (f x)) s :=
real.times_cont_diff_sin.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.sin {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.sin (f x)) s x :=
real.times_cont_diff_sin.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `real.cosh` -/
lemma has_fderiv_at.cosh (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') x :=
(real.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.cosh (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') s x :=
(real.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.cosh (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.cosh (f x)) s x :=
hf.has_fderiv_within_at.cosh.differentiable_within_at
@[simp] lemma differentiable_at.cosh (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.cosh (f x)) x :=
hc.has_fderiv_at.cosh.differentiable_at
lemma differentiable_on.cosh (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.cosh (f x)) s :=
λx h, (hc x h).cosh
@[simp] lemma differentiable.cosh (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.cosh (f x)) :=
λx, (hc x).cosh
lemma fderiv_within_cosh (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.cosh (f x)) s x = real.sinh (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.cosh.fderiv_within hxs
@[simp] lemma fderiv_cosh (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.cosh (f x)) x = real.sinh (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.cosh.fderiv
lemma times_cont_diff.cosh {n} (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.cosh (f x)) :=
real.times_cont_diff_cosh.comp h
lemma times_cont_diff_at.cosh {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.cosh (f x)) x :=
real.times_cont_diff_cosh.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.cosh {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.cosh (f x)) s :=
real.times_cont_diff_cosh.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.cosh {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.cosh (f x)) s x :=
real.times_cont_diff_cosh.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `real.sinh` -/
lemma has_fderiv_at.sinh (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') x :=
(real.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.sinh (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') s x :=
(real.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.sinh (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.sinh (f x)) s x :=
hf.has_fderiv_within_at.sinh.differentiable_within_at
@[simp] lemma differentiable_at.sinh (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.sinh (f x)) x :=
hc.has_fderiv_at.sinh.differentiable_at
lemma differentiable_on.sinh (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.sinh (f x)) s :=
λx h, (hc x h).sinh
@[simp] lemma differentiable.sinh (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.sinh (f x)) :=
λx, (hc x).sinh
lemma fderiv_within_sinh (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.sinh (f x)) s x = real.cosh (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.sinh.fderiv_within hxs
@[simp] lemma fderiv_sinh (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.sinh (f x)) x = real.cosh (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.sinh.fderiv
lemma times_cont_diff.sinh {n} (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.sinh (f x)) :=
real.times_cont_diff_sinh.comp h
lemma times_cont_diff_at.sinh {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.sinh (f x)) x :=
real.times_cont_diff_sinh.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.sinh {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.sinh (f x)) s :=
real.times_cont_diff_sinh.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.sinh {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.sinh (f x)) s x :=
real.times_cont_diff_sinh.times_cont_diff_at.comp_times_cont_diff_within_at x hf
end
namespace real
lemma exists_cos_eq_zero : 0 ∈ cos '' Icc (1:ℝ) 2 :=
intermediate_value_Icc' (by norm_num) continuous_on_cos
⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩
/-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from
which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/
noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero
localized "notation `π` := real.pi" in real
@[simp] lemma cos_pi_div_two : cos (π / 2) = 0 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).2
lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).1.1
lemma pi_div_two_le_two : π / 2 ≤ 2 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).1.2
lemma two_le_pi : (2 : ℝ) ≤ π :=
(div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1
(by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two)
lemma pi_le_four : π ≤ 4 :=
(div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1
(calc π / 2 ≤ 2 : pi_div_two_le_two
... = 4 / 2 : by norm_num)
lemma pi_pos : 0 < π :=
lt_of_lt_of_le (by norm_num) two_le_pi
lemma pi_ne_zero : pi ≠ 0 :=
ne_of_gt pi_pos
lemma pi_div_two_pos : 0 < π / 2 :=
half_pos pi_pos
lemma two_pi_pos : 0 < 2 * π :=
by linarith [pi_pos]
@[simp] lemma sin_pi : sin π = 0 :=
by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _ _), two_mul, add_div,
sin_add, cos_pi_div_two]; simp
@[simp] lemma cos_pi : cos π = -1 :=
by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _ _), mul_div_assoc,
cos_two_mul, cos_pi_div_two];
simp [bit0, pow_add]
@[simp] lemma sin_two_pi : sin (2 * π) = 0 :=
by simp [two_mul, sin_add]
@[simp] lemma cos_two_pi : cos (2 * π) = 1 :=
by simp [two_mul, cos_add]
lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x :=
by simp [sin_add]
lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x :=
by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi]
lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x :=
by simp [cos_add, cos_two_pi, sin_two_pi]
lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x :=
by simp [sub_eq_add_neg, sin_add]
lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x :=
by simp [cos_add]
lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x :=
by simp [sub_eq_add_neg, cos_add]
lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x :=
if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2
else
have (2 : ℝ) + 2 = 4, from rfl,
have π - x ≤ 2, from sub_le_iff_le_add.2
(le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)),
sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this
lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x :=
match lt_or_eq_of_le h0x with
| or.inl h0x := (lt_or_eq_of_le hxp).elim
(le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x)
(λ hpx, by simp [hpx])
| or.inr h0x := by simp [h0x.symm]
end
lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 :=
neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx)
lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 :=
neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx)
@[simp] lemma sin_pi_div_two : sin (π / 2) = 1 :=
have sin (π / 2) = 1 ∨ sin (π / 2) = -1 :=
by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2),
this.resolve_right
(λ h, (show ¬(0 : ℝ) < -1, by norm_num) $
h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos))
lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x :=
by simp [sin_add]
lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x :=
by simp [sub_eq_add_neg, sin_add]
lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x :=
by simp [sub_eq_add_neg, sin_add]
lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x :=
by simp [cos_add]
lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x :=
by simp [sub_eq_add_neg, cos_add]
lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x :=
by rw [← cos_neg, neg_sub, cos_sub_pi_div_two]
lemma cos_pos_of_mem_Ioo
{x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x :=
sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith)
lemma cos_nonneg_of_mem_Icc
{x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x :=
match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with
| or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_mem_Ioo hx₁ hx₂)
| or.inl hx₁, or.inr hx₂ := by simp [hx₂]
| or.inr hx₁, _ := by simp [hx₁.symm]
end
lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 :=
neg_pos.1 $ cos_pi_sub x ▸
cos_pos_of_mem_Ioo (by linarith) (by linarith)
lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 :=
neg_nonneg.1 $ cos_pi_sub x ▸
cos_nonneg_of_mem_Icc (by linarith) (by linarith)
lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 :=
by induction n; simp [add_mul, sin_add, *]
lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 :=
by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi]
lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 :=
by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi]
lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 :=
by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe,
int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg,
(neg_mul_eq_neg_mul _ _).symm, cos_neg]
lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 :=
by simp [cos_add, sin_add, cos_int_mul_two_pi]
lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) :
sin x = 0 ↔ x = 0 :=
⟨λ h, le_antisymm
(le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $
calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂
... = 0 : h))
(le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $
calc 0 = sin x : h.symm
... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)),
λ h, by simp [h]⟩
lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x :=
⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos))
(sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos))
(by simp [sub_eq_add_neg, sin_add, h, sin_int_mul_pi]))⟩,
λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩
lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 :=
by rw [← mul_self_eq_one_iff, ← sin_sq_add_cos_sq x,
pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self];
exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩
lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x :=
⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in
⟨n / 2, (int.mod_two_eq_zero_or_one n).elim
(λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel
((int.dvd_iff_mod_eq_zero _ _).2 hn0)])
(λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul,
one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn;
rw [← hn, cos_int_mul_two_pi_add_pi] at h;
exact absurd h (by norm_num))⟩,
λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩
lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 :=
⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in
begin
clear _let_match,
subst hn,
rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂,
rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt,
← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁,
exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))),
end,
λ h, by simp [h]⟩
lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π / 2) (hxy : x < y) :
cos y < cos x :=
begin
rw [← sub_lt_zero, cos_sub_cos],
have : 0 < sin ((y + x) / 2),
{ refine sin_pos_of_pos_of_lt_pi _ _; linarith },
have : 0 < sin ((y - x) / 2),
{ refine sin_pos_of_pos_of_lt_pi _ _; linarith },
nlinarith,
end
lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π) (hxy : x < y) :
cos y < cos x :=
match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with
| or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hy hxy
| or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim
(λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos])
... < cos x : cos_pos_of_mem_Ioo (by linarith) hx)
(λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos])
... = cos x : by rw [hx, cos_pi_div_two])
| or.inr hx, or.inl hy := by linarith
| or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub];
apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith)
end
lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π) (hxy : x ≤ y) :
cos y ≤ cos x :=
(lt_or_eq_of_le hxy).elim
(le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hy₂)
(λ h, h ▸ le_refl _)
lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x)
(hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y :=
by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)];
apply cos_lt_cos_of_nonneg_of_le_pi; linarith
lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x)
(hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y :=
(lt_or_eq_of_le hxy).elim
(le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hy₂)
(λ h, h ▸ le_refl _)
lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y)
(hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y :=
match lt_trichotomy x y with
| or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hy₂ h) (by rw hxy; exact lt_irrefl _)
| or.inr (or.inl h) := h
| or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hx₂ h) (by rw hxy; exact lt_irrefl _)
end
lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π)
(hxy : cos x = cos y) : x = y :=
begin
rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy,
refine (sub_right_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy);
linarith
end
lemma exists_sin_eq : Icc (-1:ℝ) 1 ⊆ sin '' Icc (-(π / 2)) (π / 2) :=
by convert intermediate_value_Icc
(le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos))
continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two]
lemma exists_cos_eq : (Icc (-1) 1 : set ℝ) ⊆ cos '' Icc 0 π :=
by convert intermediate_value_Icc' real.pi_pos.le real.continuous_on_cos;
simp only [real.cos_pi, real.cos_zero]
lemma range_cos : range cos = (Icc (-1) 1 : set ℝ) :=
begin
ext,
split,
{ rintros ⟨y, rfl⟩, exact ⟨y.neg_one_le_cos, y.cos_le_one⟩ },
{ rintros h,
rcases real.exists_cos_eq h with ⟨y, -, hy⟩,
exact ⟨y, hy⟩ }
end
lemma range_sin : range sin = (Icc (-1) 1 : set ℝ) :=
begin
ext,
split,
{ rintros ⟨y, rfl⟩, exact ⟨y.neg_one_le_sin, y.sin_le_one⟩ },
{ rintros h,
rcases real.exists_sin_eq h with ⟨y, -, hy⟩,
exact ⟨y, hy⟩ }
end
lemma range_cos_infinite : (range real.cos).infinite :=
by { rw real.range_cos, exact Icc.infinite (by norm_num) }
lemma range_sin_infinite : (range real.sin).infinite :=
by { rw real.range_sin, exact Icc.infinite (by norm_num) }
lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x :=
begin
cases le_or_gt x 1 with h' h',
{ have hx : abs x = x := abs_of_nonneg (le_of_lt h),
have : abs x ≤ 1, rwa [hx],
have := sin_bound this, rw [abs_le] at this,
have := this.2, rw [sub_le_iff_le_add', hx] at this,
apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)),
apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul',
{ rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)),
rw mul_le_mul_right, exact h', apply pow_pos h },
norm_num, norm_num, apply pow_pos h },
exact lt_of_le_of_lt (sin_le_one x) h'
end
/- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6.
note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/
lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x :=
begin
have hx : abs x = x := abs_of_nonneg (le_of_lt h),
have : abs x ≤ 1, rwa [hx],
have := sin_bound this, rw [abs_le] at this,
have := this.1, rw [le_sub_iff_add_le, hx] at this,
refine lt_of_lt_of_le _ this,
rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left,
apply add_lt_of_lt_sub_left,
rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12,
by simp [div_eq_mul_inv, ← mul_sub]; norm_num),
apply mul_lt_mul',
{ rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)),
rw mul_le_mul_right, exact h', apply pow_pos h },
norm_num, norm_num, apply pow_pos h
end
section cos_div_pow_two
variable (x : ℝ)
/-- the series `sqrt_two_add_series x n` is `sqrt(2 + sqrt(2 + ... ))` with `n` square roots,
starting with `x`. We define it here because `cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2`
-/
@[simp] noncomputable def sqrt_two_add_series (x : ℝ) : ℕ → ℝ
| 0 := x
| (n+1) := sqrt (2 + sqrt_two_add_series n)
lemma sqrt_two_add_series_zero : sqrt_two_add_series x 0 = x := by simp
lemma sqrt_two_add_series_one : sqrt_two_add_series 0 1 = sqrt 2 := by simp
lemma sqrt_two_add_series_two : sqrt_two_add_series 0 2 = sqrt (2 + sqrt 2) := by simp
lemma sqrt_two_add_series_zero_nonneg : ∀(n : ℕ), 0 ≤ sqrt_two_add_series 0 n
| 0 := le_refl 0
| (n+1) := sqrt_nonneg _
lemma sqrt_two_add_series_nonneg {x : ℝ} (h : 0 ≤ x) : ∀(n : ℕ), 0 ≤ sqrt_two_add_series x n
| 0 := h
| (n+1) := sqrt_nonneg _
lemma sqrt_two_add_series_lt_two : ∀(n : ℕ), sqrt_two_add_series 0 n < 2
| 0 := by norm_num
| (n+1) :=
begin
refine lt_of_lt_of_le _ (le_of_eq $ sqrt_sqr $ le_of_lt zero_lt_two),
rw [sqrt_two_add_series, sqrt_lt],
apply add_lt_of_lt_sub_left,
apply lt_of_lt_of_le (sqrt_two_add_series_lt_two n),
norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num
end
lemma sqrt_two_add_series_succ (x : ℝ) :
∀(n : ℕ), sqrt_two_add_series x (n+1) = sqrt_two_add_series (sqrt (2 + x)) n
| 0 := rfl
| (n+1) := by rw [sqrt_two_add_series, sqrt_two_add_series_succ, sqrt_two_add_series]
lemma sqrt_two_add_series_monotone_left {x y : ℝ} (h : x ≤ y) :
∀(n : ℕ), sqrt_two_add_series x n ≤ sqrt_two_add_series y n
| 0 := h
| (n+1) :=
begin
rw [sqrt_two_add_series, sqrt_two_add_series],
apply sqrt_le_sqrt, apply add_le_add_left, apply sqrt_two_add_series_monotone_left
end
@[simp] lemma cos_pi_over_two_pow : ∀(n : ℕ), cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2
| 0 := by simp
| (n+1) :=
begin
symmetry, rw [div_eq_iff_mul_eq], symmetry,
rw [sqrt_two_add_series, sqrt_eq_iff_sqr_eq, mul_pow, cos_square, ←mul_div_assoc,
nat.add_succ, pow_succ, mul_div_mul_left, cos_pi_over_two_pow, add_mul],
congr, norm_num,
rw [mul_comm, pow_two, mul_assoc, ←mul_div_assoc, mul_div_cancel_left, ←mul_div_assoc,
mul_div_cancel_left],
norm_num, norm_num, norm_num,
apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num,
apply le_of_lt, apply cos_pos_of_mem_Ioo,
{ transitivity (0 : ℝ), rw neg_lt_zero, apply pi_div_two_pos,
apply div_pos pi_pos, apply pow_pos, norm_num },
apply div_lt_div' (le_refl pi) _ pi_pos _,
refine lt_of_le_of_lt (le_of_eq (pow_one _).symm) _,
apply pow_lt_pow, norm_num, apply nat.succ_lt_succ, apply nat.succ_pos, all_goals {norm_num}
end
lemma sin_square_pi_over_two_pow (n : ℕ) :
sin (pi / 2 ^ (n+1)) ^ 2 = 1 - (sqrt_two_add_series 0 n / 2) ^ 2 :=
by rw [sin_square, cos_pi_over_two_pow]
lemma sin_square_pi_over_two_pow_succ (n : ℕ) :
sin (pi / 2 ^ (n+2)) ^ 2 = 1 / 2 - sqrt_two_add_series 0 n / 4 :=
begin
rw [sin_square_pi_over_two_pow, sqrt_two_add_series, div_pow, sqr_sqrt, add_div, ←sub_sub],
congr, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg,
end
@[simp] lemma sin_pi_over_two_pow_succ (n : ℕ) :
sin (pi / 2 ^ (n+2)) = sqrt (2 - sqrt_two_add_series 0 n) / 2 :=
begin
symmetry, rw [div_eq_iff_mul_eq], symmetry,
rw [sqrt_eq_iff_sqr_eq, mul_pow, sin_square_pi_over_two_pow_succ, sub_mul],
{ congr, norm_num, rw [mul_comm], convert mul_div_cancel' _ _, norm_num, norm_num },
{ rw [sub_nonneg], apply le_of_lt, apply sqrt_two_add_series_lt_two },
apply le_of_lt, apply mul_pos, apply sin_pos_of_pos_of_lt_pi,
{ apply div_pos pi_pos, apply pow_pos, norm_num },
refine lt_of_lt_of_le _ (le_of_eq (div_one _)), rw [div_lt_div_left],
refine lt_of_le_of_lt (le_of_eq (pow_zero 2).symm) _,
apply pow_lt_pow, norm_num, apply nat.succ_pos, apply pi_pos,
apply pow_pos, all_goals {norm_num}
end
@[simp] lemma cos_pi_div_four : cos (pi / 4) = sqrt 2 / 2 :=
by { transitivity cos (pi / 2 ^ 2), congr, norm_num, simp }
@[simp] lemma sin_pi_div_four : sin (pi / 4) = sqrt 2 / 2 :=
by { transitivity sin (pi / 2 ^ 2), congr, norm_num, simp }
@[simp] lemma cos_pi_div_eight : cos (pi / 8) = sqrt (2 + sqrt 2) / 2 :=
by { transitivity cos (pi / 2 ^ 3), congr, norm_num, simp }
@[simp] lemma sin_pi_div_eight : sin (pi / 8) = sqrt (2 - sqrt 2) / 2 :=
by { transitivity sin (pi / 2 ^ 3), congr, norm_num, simp }
@[simp] lemma cos_pi_div_sixteen : cos (pi / 16) = sqrt (2 + sqrt (2 + sqrt 2)) / 2 :=
by { transitivity cos (pi / 2 ^ 4), congr, norm_num, simp }
@[simp] lemma sin_pi_div_sixteen : sin (pi / 16) = sqrt (2 - sqrt (2 + sqrt 2)) / 2 :=
by { transitivity sin (pi / 2 ^ 4), congr, norm_num, simp }
@[simp] lemma cos_pi_div_thirty_two : cos (pi / 32) = sqrt (2 + sqrt (2 + sqrt (2 + sqrt 2))) / 2 :=
by { transitivity cos (pi / 2 ^ 5), congr, norm_num, simp }
@[simp] lemma sin_pi_div_thirty_two : sin (pi / 32) = sqrt (2 - sqrt (2 + sqrt (2 + sqrt 2))) / 2 :=
by { transitivity sin (pi / 2 ^ 5), congr, norm_num, simp }
-- This section is also a convenient location for other explicit values of `sin` and `cos`.
/-- The cosine of `π / 3` is `1 / 2`. -/
@[simp] lemma cos_pi_div_three : cos (π / 3) = 1 / 2 :=
begin
have h₁ : (2 * cos (π / 3) - 1) ^ 2 * (2 * cos (π / 3) + 2) = 0,
{ have : cos (3 * (π / 3)) = cos π := by { congr' 1, ring },
linarith [cos_pi, cos_three_mul (π / 3)] },
cases mul_eq_zero.mp h₁ with h h,
{ linarith [pow_eq_zero h] },
{ have : cos π < cos (π / 3),
{ refine cos_lt_cos_of_nonneg_of_le_pi _ rfl.ge _;
linarith [pi_pos] },
linarith [cos_pi] }
end
/-- The square of the cosine of `π / 6` is `3 / 4` (this is sometimes more convenient than the
result for cosine itself). -/
lemma square_cos_pi_div_six : cos (π / 6) ^ 2 = 3 / 4 :=
begin
have h1 : cos (π / 6) ^ 2 = 1 / 2 + 1 / 2 / 2,
{ convert cos_square (π / 6),
have h2 : 2 * (π / 6) = π / 3 := by cancel_denoms,
rw [h2, cos_pi_div_three] },
rw ← sub_eq_zero at h1 ⊢,
convert h1 using 1,
ring
end
/-- The cosine of `π / 6` is `√3 / 2`. -/
@[simp] lemma cos_pi_div_six : cos (π / 6) = (sqrt 3) / 2 :=
begin
suffices : sqrt 3 = cos (π / 6) * 2,
{ field_simp [(by norm_num : 0 ≠ 2)], exact this.symm },
rw sqrt_eq_iff_sqr_eq,
{ have h1 := (mul_right_inj' (by norm_num : (4:ℝ) ≠ 0)).mpr square_cos_pi_div_six,
rw ← sub_eq_zero at h1 ⊢,
convert h1 using 1,
ring },
{ norm_num },
{ have : 0 < cos (π / 6) := by { apply cos_pos_of_mem_Ioo; linarith [pi_pos] },
linarith },
end
/-- The sine of `π / 6` is `1 / 2`. -/
@[simp] lemma sin_pi_div_six : sin (π / 6) = 1 / 2 :=
begin
rw [← cos_pi_div_two_sub, ← cos_pi_div_three],
congr,
ring
end
/-- The square of the sine of `π / 3` is `3 / 4` (this is sometimes more convenient than the
result for cosine itself). -/
lemma square_sin_pi_div_three : sin (π / 3) ^ 2 = 3 / 4 :=
begin
rw [← cos_pi_div_two_sub, ← square_cos_pi_div_six],
congr,
ring
end
/-- The sine of `π / 3` is `√3 / 2`. -/
@[simp] lemma sin_pi_div_three : sin (π / 3) = (sqrt 3) / 2 :=
begin
rw [← cos_pi_div_two_sub, ← cos_pi_div_six],
congr,
ring
end
end cos_div_pow_two
/-- The type of angles -/
def angle : Type :=
quotient_add_group.quotient (add_subgroup.gmultiples (2 * π))
namespace angle
instance angle.add_comm_group : add_comm_group angle :=
quotient_add_group.add_comm_group _
instance : inhabited angle := ⟨0⟩
instance angle.has_coe : has_coe ℝ angle :=
⟨quotient.mk'⟩
@[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl
@[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl
@[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl
@[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) :=
by rw [sub_eq_add_neg, sub_eq_add_neg, coe_add, coe_neg]
@[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) :
↑((n : ℝ) * x) = n •ℕ (↑x : angle) :=
by simpa using add_monoid_hom.map_nsmul ⟨coe, coe_zero, coe_add⟩ _ _
@[simp, norm_cast] lemma coe_int_mul_eq_gsmul (x : ℝ) (n : ℤ) :
↑((n : ℝ) * x : ℝ) = n •ℤ (↑x : angle) :=
by simpa using add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _
@[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) :=
quotient.sound' ⟨-1, show (-1 : ℤ) •ℤ (2 * π) = _, by rw [neg_one_gsmul, add_zero]⟩
lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k :=
by simp only [quotient_add_group.eq, add_subgroup.gmultiples_eq_closure,
add_subgroup.mem_closure_singleton, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm]
theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ :=
begin
split,
{ intro Hcos,
rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero,
false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos,
rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩,
{ right,
rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _ _), ← sub_eq_iff_eq_add] at hn,
rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc,
coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero] },
{ left,
rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _ _), eq_sub_iff_add_eq] at hn,
rw [← hn, coe_add, mul_assoc,
coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] },
apply_instance, },
{ rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _),
mul_comm π _, sin_int_mul_pi, mul_zero],
rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k,
mul_div_cancel_left _ (@two_ne_zero ℝ _ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] }
end
theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π :=
begin
split,
{ intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin,
cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h,
{ left, rw [coe_sub, coe_sub] at h, exact sub_right_inj.1 h },
right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub,
sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h,
exact h.symm },
{ rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _),
mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul],
have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add,
mul_assoc, mul_comm π _, ←mul_assoc] at H,
rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ (@two_ne_zero ℝ _ _),
cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] }
end
theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ :=
begin
cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc },
cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs },
rw [eq_neg_iff_add_eq_zero, hs] at hc,
cases quotient.exact' hc with n hn, change n •ℤ _ = _ at hn,
rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul,
mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add,
← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn,
have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn,
rw [add_comm, int.add_mul_mod_self] at this,
exact absurd this one_ne_zero
end
end angle
/-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`.
If the argument is not between `-1` and `1` it defaults to `0` -/
noncomputable def arcsin (x : ℝ) : ℝ :=
if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx) else 0
lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 :=
if hx : -1 ≤ x ∧ x ≤ 1
then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.2
else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos
lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x :=
if hx : -1 ≤ x ∧ x ≤ 1
then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.1
else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos)
lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x :=
by rw [arcsin, dif_pos (and.intro hx₁ hx₂)];
exact (classical.some_spec (exists_sin_eq ⟨hx₁, hx₂⟩)).2
lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x :=
sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂
(by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _))
lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1)
(hxy : arcsin x = arcsin y) : x = y :=
by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy]
@[simp] lemma arcsin_zero : arcsin 0 = 0 :=
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(neg_nonpos.2 (le_of_lt pi_div_two_pos))
(le_of_lt pi_div_two_pos)
(by rw [sin_arcsin, sin_zero]; norm_num)
@[simp] lemma arcsin_one : arcsin 1 = π / 2 :=
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(by linarith [pi_pos])
(le_refl _)
(by rw [sin_arcsin, sin_pi_div_two]; norm_num)
@[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x :=
if h : -1 ≤ x ∧ x ≤ 1 then
have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm],
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(neg_le_neg (arcsin_le_pi_div_two _))
(neg_le.1 (neg_pi_div_two_le_arcsin _))
(by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2])
else
have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm],
by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero]
@[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp
lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x :=
if hx₁ : x ≤ 1 then
not_lt.1 (λ h, not_lt.2 hx begin
have := sin_lt_sin_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _) (le_of_lt pi_div_two_pos) h,
rw [real.sin_arcsin, sin_zero] at this; linarith
end)
else by rw [arcsin, dif_neg]; simp [hx₁]
lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 :=
⟨λ h, have sin (arcsin x) = 0, by simp [h],
by rwa [sin_arcsin hx₁ hx₂] at this,
λ h, by simp [h]⟩
lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x :=
lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁))
(ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm))
lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 :=
neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx))
/-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`.
If the argument is not between `-1` and `1` it defaults to `π / 2` -/
noncomputable def arccos (x : ℝ) : ℝ :=
π / 2 - arcsin x
lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl
lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x :=
by simp [sub_eq_add_neg, arccos]
lemma arccos_le_pi (x : ℝ) : arccos x ≤ π :=
by unfold arccos; linarith [neg_pi_div_two_le_arcsin x]
lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x :=
by unfold arccos; linarith [arcsin_le_pi_div_two x]
lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x :=
by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂]
lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x :=
by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp [sub_eq_add_neg]; linarith
lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1)
(hxy : arccos x = arccos y) : x = y :=
arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at *
@[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos]
@[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos]
@[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves]
lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x :=
by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp
lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) :=
cos_nonneg_of_mem_Icc
(neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _)
lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) :=
have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x),
begin
rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))),
pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this,
rw [this, sin_arcsin hx₁ hx₂],
end
lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) :=
by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂]
lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 :=
have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _),
have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁,
by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul,
mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _),
← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)),
abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm];
exact lt_add_one _
lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 :=
(abs_lt.1 (abs_div_sqrt_one_add_lt _)).2
lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) :=
(abs_lt.1 (abs_div_sqrt_one_add_lt _)).1
@[simp] lemma tan_pi_div_four : tan (π / 4) = 1 :=
begin
rw [tan_eq_sin_div_cos, cos_pi_div_four, sin_pi_div_four],
have h : (sqrt 2) / 2 > 0 := by cancel_denoms,
exact div_self (ne_of_gt h),
end
lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x :=
by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith))
(cos_pos_of_mem_Ioo (by linarith) hxp)
lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x :=
match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with
| or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp)
| or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos]
| or.inr hx0, _ := by simp [hx0.symm]
end
lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 :=
neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos]))
lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 :=
neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos]))
lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y < π / 2) (hxy : x < y) :
tan x < tan y :=
begin
rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos],
exact div_lt_div
(sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hy₂) hxy)
(cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) (le_of_lt hxy))
(sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))
(cos_pos_of_mem_Ioo (by linarith) hy₂)
end
lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x)
(hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y :=
match le_total x 0, le_total y 0 with
| or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact
tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0)
(neg_lt.2 hx₁) (neg_lt_neg hxy)
| or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim
(λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁)
... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂)
(λ hy0, by rw [← hy0, tan_zero]; exact
tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁)
| or.inr hx0, or.inl hy0 := by linarith
| or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hy₂ hxy
end
lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2)
(hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y :=
match lt_trichotomy x y with
| or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hy₂ h) (by rw hxy; exact lt_irrefl _)
| or.inr (or.inl h) := h
| or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hx₂ h) (by rw hxy; exact lt_irrefl _)
end
/-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/
noncomputable def arctan (x : ℝ) : ℝ :=
arcsin (x / sqrt (1 + x ^ 2))
lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) :=
sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _))
lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) :=
have h₁ : (0 : ℝ) < 1 + x ^ 2,
from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _),
have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1,
by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _)
(abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)),
by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)),
one_div, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)),
div_pow, pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁),
← mul_right_inj' (ne.symm (ne_of_lt h₁)), mul_sub,
mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))];
simp
lemma tan_arctan (x : ℝ) : tan (arctan x) = x :=
by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one,
mul_div_assoc,
div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))),
mul_one]
lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 :=
lt_of_le_of_ne (arcsin_le_pi_div_two _)
(λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $
by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _))
(le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two])
lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x :=
lt_of_le_of_ne (neg_pi_div_two_le_arcsin _)
(λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $
by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _))
(le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two])
lemma arctan_mem_Ioo (x : ℝ) : arctan x ∈ Ioo (-(π / 2)) (π / 2) :=
⟨neg_pi_div_two_lt_arctan x, arctan_lt_pi_div_two x⟩
lemma tan_surjective : function.surjective tan :=
function.right_inverse.surjective tan_arctan
lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x :=
tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _)
(arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan)
@[simp] lemma arctan_zero : arctan 0 = 0 :=
by simp [arctan]
@[simp] lemma arctan_one : arctan 1 = π / 4 :=
begin
refine tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan 1) (arctan_lt_pi_div_two 1) _ _ _;
linarith [pi_pos, tan_arctan 1, tan_pi_div_four],
end
@[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x :=
by simp [arctan, neg_div]
end real
namespace complex
open_locale real
/-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`,
`sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`,
`arg 0` defaults to `0` -/
noncomputable def arg (x : ℂ) : ℝ :=
if 0 ≤ x.re
then real.arcsin (x.im / x.abs)
else if 0 ≤ x.im
then real.arcsin ((-x).im / x.abs) + π
else real.arcsin ((-x).im / x.abs) - π
lemma arg_le_pi (x : ℂ) : arg x ≤ π :=
if hx₁ : 0 ≤ x.re
then by rw [arg, if_pos hx₁];
exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos))
else
if hx₂ : 0 ≤ x.im
then by rw [arg, if_neg hx₁, if_pos hx₂];
exact le_sub_iff_add_le.1 (by rw sub_self;
exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_nonneg _)))
else by rw [arg, if_neg hx₁, if_neg hx₂];
exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _)
(by linarith [real.pi_pos]))
lemma neg_pi_lt_arg (x : ℂ) : -π < arg x :=
if hx₁ : 0 ≤ x.re
then by rw [arg, if_pos hx₁];
exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _)
else
have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁,
if hx₂ : 0 ≤ x.im
then by rw [arg, if_neg hx₁, if_pos hx₂];
exact sub_lt_iff_lt_add.1
(lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _))
else by rw [arg, if_neg hx₁, if_neg hx₂];
exact lt_sub_iff_add_lt.2 (by rw neg_add_self;
exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂))
(abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2))
lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) :
arg x = arg (-x) + π :=
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos],
by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg]
lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) :
arg x = arg (-x) - π :=
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos],
by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg]
@[simp] lemma arg_zero : arg 0 = 0 :=
by simp [arg, le_refl]
@[simp] lemma arg_one : arg 1 = 0 :=
by simp [arg, zero_le_one]
@[simp] lemma arg_neg_one : arg (-1) = π :=
by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _ _)]
@[simp] lemma arg_I : arg I = π / 2 :=
by simp [arg, le_refl]
@[simp] lemma arg_neg_I : arg (-I) = -(π / 2) :=
by simp [arg, le_refl]
lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs :=
by unfold arg; split_ifs;
simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1
(abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg,
real.sin_neg]
private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs :=
have 0 ≤ 1 - (x.im / abs x) ^ 2,
from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two];
exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _),
by rw [eq_div_iff_mul_eq (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x),
arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1
(abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this,
sub_mul, div_pow, ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)),
one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr]
lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs :=
if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr
else
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr,
if hxi : 0 ≤ x.im
then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr,
by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi,
cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this];
simp [neg_div]
else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)];
simp [sub_eq_add_neg, real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]
lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re :=
begin
by_cases h : x = 0,
{ simp only [h, zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] },
rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h,
div_div_div_cancel_right _ (mt abs_eq_zero.1 h)]
end
lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) :
arg (cos x + sin x * I) = x :=
if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2
then
have hx₄ : 0 ≤ (cos x + sin x * I).re,
by simp; exact real.cos_nonneg_of_mem_Icc hx₃.1 hx₃.2,
by rw [arg, if_pos hx₄];
simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2]
else if hx₄ : x < -(π / 2)
then
have hx₅ : ¬0 ≤ (cos x + sin x * I).re :=
suffices ¬ 0 ≤ real.cos x, by simpa,
not_le.2 $ by rw ← real.cos_neg;
apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith,
have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im :=
suffices real.sin x < 0, by simpa,
by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith,
suffices -π + -real.arcsin (real.sin x) = x,
by rw [arg, if_neg hx₅, if_neg hx₆];
simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re],
by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; try {simp [add_left_comm]}; linarith
else
have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith,
have hx₆ : ¬0 ≤ (cos x + sin x * I).re :=
suffices ¬0 ≤ real.cos x, by simpa,
not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith,
have hx₇ : 0 ≤ (cos x + sin x * I).im :=
suffices 0 ≤ real.sin x, by simpa,
by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith,
suffices π - real.arcsin (real.sin x) = x,
by rw [arg, if_neg hx₆, if_pos hx₇];
simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re],
by rw [← real.sin_pi_sub, real.arcsin_sin]; simp [sub_eq_add_neg]; linarith
lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) :
arg x = arg y ↔ (abs y / abs x : ℂ) * x = y :=
have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx),
have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy),
⟨λ h,
begin
have hcos := congr_arg real.cos h,
rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos,
have hsin := congr_arg real.sin h,
rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin,
apply complex.ext,
{ rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm,
← mul_div_assoc, hcos, mul_div_cancel _ hax] },
{ rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero,
mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] }
end,
λ h,
have hre : abs (y / x) * x.re = y.re,
by rw ← of_real_div at h;
simpa [-of_real_div] using congr_arg re h,
have hre' : abs (x / y) * y.re = x.re,
by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div,
mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul],
have him : abs (y / x) * x.im = y.im,
by rw ← of_real_div at h;
simpa [-of_real_div] using congr_arg im h,
have him' : abs (x / y) * y.im = x.im,
by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div,
mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul],
have hxya : x.im / abs x = y.im / abs y,
by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay],
have hnxya : (-x).im / abs x = (-y).im / abs y,
by rw [neg_im, neg_im, neg_div, neg_div, hxya],
if hxr : 0 ≤ x.re
then
have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr,
by simp [arg, *] at *
else
have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr,
if hxi : 0 ≤ x.im
then
have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi,
by simp [arg, *] at *
else
have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi,
by simp [arg, *] at *⟩
lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x :=
if hx : x = 0 then by simp [hx]
else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $
by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc,
of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul,
div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm),
div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul]
lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y :=
if hy : y = 0 then by simp * at *
else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *,
by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂
lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 :=
by simp [arg, hx]
lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π :=
by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg];
simp [*, le_iff_eq_or_lt, lt_neg]
/-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`.
`log 0 = 0`-/
noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I
lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log]
lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log]
lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x :=
by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx,
← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div,
mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc,
mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im]
lemma range_exp : range exp = {x | x ≠ 0} :=
set.ext $ λ x, ⟨by { rintro ⟨x, rfl⟩, exact exp_ne_zero x }, λ hx, ⟨log x, exp_log hx⟩⟩
lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π)
(hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y :=
by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy;
exact complex.ext
(real.exp_injective $
by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy)
(by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _),
arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy)
lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x :=
exp_inj_of_neg_pi_lt_of_le_pi
(by rw log_im; exact neg_pi_lt_arg _)
(by rw log_im; exact arg_le_pi _)
hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)])
lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x :=
complex.ext
(by rw [log_re, of_real_re, abs_of_nonneg hx])
(by rw [of_real_im, log_im, arg_of_real_of_nonneg hx])
lemma log_of_real_re (x : ℝ) : (log (x : ℂ)).re = real.log x := by simp [log_re]
@[simp] lemma log_zero : log 0 = 0 := by simp [log]
@[simp] lemma log_one : log 1 = 0 := by simp [log]
lemma log_neg_one : log (-1) = π * I := by simp [log]
lemma log_I : log I = π / 2 * I := by simp [log]
lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log]
lemma exists_pow_nat_eq (x : ℂ) {n : ℕ} (hn : 0 < n) : ∃ z, z ^ n = x :=
begin
by_cases hx : x = 0,
{ use 0, simp only [hx, zero_pow_eq_zero, hn] },
{ use exp (log x / n),
rw [← exp_nat_mul, mul_div_cancel', exp_log hx],
exact_mod_cast (nat.pos_iff_ne_zero.mp hn) }
end
lemma exists_eq_mul_self (x : ℂ) : ∃ z, x = z * z :=
begin
obtain ⟨z, rfl⟩ := exists_pow_nat_eq x zero_lt_two,
exact ⟨z, pow_two z⟩
end
lemma two_pi_I_ne_zero : (2 * π * I : ℂ) ≠ 0 :=
by norm_num [real.pi_ne_zero, I_ne_zero]
lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) :=
have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1,
from λ h₁ h₂, begin
rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁,
have := real.exp_pos x.re,
rw ← h₁ at this,
exact absurd this (by norm_num)
end,
calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff]
... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 :
begin
rw exp_eq_exp_re_mul_sin_add_cos,
simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re,
real.exp_ne_zero],
split; finish [real.sin_eq_zero_iff_cos_eq]
end
... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 :
by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff]
... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) :
⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩,
λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩,
by simp [hn]⟩⟩
lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 :=
by rw [exp_sub, div_eq_one_iff_eq (exp_ne_zero _)]
lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) :=
by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add']
@[simp] lemma cos_pi_div_two : cos (π / 2) = 0 :=
calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp
... = 0 : by simp
@[simp] lemma sin_pi_div_two : sin (π / 2) = 1 :=
calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp
... = 1 : by simp
@[simp] lemma sin_pi : sin π = 0 :=
by rw [← of_real_sin, real.sin_pi]; simp
@[simp] lemma cos_pi : cos π = -1 :=
by rw [← of_real_cos, real.cos_pi]; simp
@[simp] lemma sin_two_pi : sin (2 * π) = 0 :=
by simp [two_mul, sin_add]
@[simp] lemma cos_two_pi : cos (2 * π) = 1 :=
by simp [two_mul, cos_add]
lemma sin_add_pi (x : ℂ) : sin (x + π) = -sin x :=
by simp [sin_add]
lemma sin_add_two_pi (x : ℂ) : sin (x + 2 * π) = sin x :=
by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi]
lemma cos_add_two_pi (x : ℂ) : cos (x + 2 * π) = cos x :=
by simp [cos_add, cos_two_pi, sin_two_pi]
lemma sin_pi_sub (x : ℂ) : sin (π - x) = sin x :=
by simp [sub_eq_add_neg, sin_add]
lemma cos_add_pi (x : ℂ) : cos (x + π) = -cos x :=
by simp [cos_add]
lemma cos_pi_sub (x : ℂ) : cos (π - x) = -cos x :=
by simp [sub_eq_add_neg, cos_add]
lemma sin_add_pi_div_two (x : ℂ) : sin (x + π / 2) = cos x :=
by simp [sin_add]
lemma sin_sub_pi_div_two (x : ℂ) : sin (x - π / 2) = -cos x :=
by simp [sub_eq_add_neg, sin_add]
lemma sin_pi_div_two_sub (x : ℂ) : sin (π / 2 - x) = cos x :=
by simp [sub_eq_add_neg, sin_add]
lemma cos_add_pi_div_two (x : ℂ) : cos (x + π / 2) = -sin x :=
by simp [cos_add]
lemma cos_sub_pi_div_two (x : ℂ) : cos (x - π / 2) = sin x :=
by simp [sub_eq_add_neg, cos_add]
lemma cos_pi_div_two_sub (x : ℂ) : cos (π / 2 - x) = sin x :=
by rw [← cos_neg, neg_sub, cos_sub_pi_div_two]
lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 :=
by induction n; simp [add_mul, sin_add, *]
lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 :=
by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi]
lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 :=
by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi]
lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 :=
by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe,
int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg,
(neg_mul_eq_neg_mul _ _).symm, cos_neg]
lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 :=
by simp [cos_add, sin_add, cos_int_mul_two_pi]
lemma exp_pi_mul_I : exp (π * I) = -1 := by { rw exp_mul_I, simp, }
theorem cos_eq_zero_iff {θ : ℂ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 :=
begin
have h : (exp (θ * I) + exp (-θ * I)) / 2 = 0 ↔ exp (2 * θ * I) = -1,
{ rw [@div_eq_iff _ _ (exp (θ * I) + exp (-θ * I)) 2 0 (by norm_num), zero_mul, add_eq_zero_iff_eq_neg,
neg_eq_neg_one_mul (exp (-θ * I)), ← div_eq_iff (exp_ne_zero (-θ * I)), ← exp_sub],
field_simp, ring },
rw [cos, h, ← exp_pi_mul_I, exp_eq_exp_iff_exists_int],
split; simp; intros x h2; use x,
{ field_simp, ring at h2,
rwa [mul_right_comm 2 I θ, mul_right_comm (2*(x:ℂ)+1) I (π:ℂ), mul_left_inj' I_ne_zero,
mul_comm 2 θ] at h2},
{ field_simp at h2, ring,
rw [mul_right_comm 2 I θ, mul_right_comm (2*(x:ℂ)+1) I (π:ℂ), mul_left_inj' I_ne_zero,
mul_comm 2 θ, h2] },
end
theorem cos_ne_zero_iff {θ : ℂ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 :=
by rw [← not_exists, not_iff_not, cos_eq_zero_iff]
theorem sin_eq_zero_iff {θ : ℂ} : sin θ = 0 ↔ ∃ k : ℤ, θ = k * π :=
begin
rw [← complex.cos_sub_pi_div_two, cos_eq_zero_iff],
split,
{ rintros ⟨k, hk⟩,
use k + 1,
field_simp [eq_add_of_sub_eq hk],
ring },
{ rintros ⟨k, rfl⟩,
use k - 1,
field_simp,
ring }
end
theorem sin_ne_zero_iff {θ : ℂ} : sin θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π :=
by rw [← not_exists, not_iff_not, sin_eq_zero_iff]
lemma cos_eq_cos_iff {x y : ℂ} :
cos x = cos y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x :=
calc cos x = cos y ↔ cos x - cos y = 0 : sub_eq_zero.symm
... ↔ -2 * sin((x + y)/2) * sin((x - y)/2) = 0 : by rw cos_sub_cos
... ↔ sin((x + y)/2) = 0 ∨ sin((x - y)/2) = 0 : by { field_simp [(by norm_num : -(2:ℂ) ≠ 0)] }
... ↔ sin((x - y)/2) = 0 ∨ sin((x + y)/2) = 0 : or.comm
... ↔ (∃ k : ℤ, y = 2 * k * π + x) ∨ (∃ k :ℤ, y = 2 * k * π - x) :
begin
apply or_congr;
rw sin_eq_zero_iff;
field_simp [(by norm_num : -(2:ℂ) ≠ 0)],
work_on_goal 0 -- material specific to the left of the `or`, when x ≅ y mod 2π
{ split,
all_goals
{ rintros ⟨k, hk⟩,
refine ⟨-k, eq.symm _⟩ } },
work_on_goal 2 -- material specific to the right of the `or`, when x ≅ -y mod 2π
{ refine exists_congr (λ k, ⟨λ hk, _, λ hk, _⟩) },
all_goals -- joint material for showing two equations differ by a constant
{ rw ← sub_eq_zero at hk ⊢,
convert hk using 1,
try { push_cast },
ring }
end
... ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x : exists_or_distrib.symm
lemma sin_eq_sin_iff {x y : ℂ} :
sin x = sin y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = (2 * k + 1) * π - x :=
begin
rw [←complex.cos_sub_pi_div_two, ←complex.cos_sub_pi_div_two, cos_eq_cos_iff],
simp only [exists_or_distrib],
apply or_congr;
refine exists_congr (λ k, ⟨_, _⟩);
{ intros h,
rw ← sub_eq_zero at ⊢ h,
convert h using 1,
field_simp,
ring },
end
lemma has_deriv_at_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) :
has_deriv_at tan (1 / (cos x)^2) x :=
begin
convert has_deriv_at.div (has_deriv_at_sin x) (has_deriv_at_cos x) (cos_ne_zero_iff.mpr h),
rw ← sin_sq_add_cos_sq x,
ring,
end
lemma differentiable_at_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : differentiable_at ℂ tan x :=
(has_deriv_at_tan h).differentiable_at
@[simp] lemma deriv_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : deriv tan x = 1 / (cos x)^2 :=
(has_deriv_at_tan h).deriv
lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} :=
continuous_on_sin.div continuous_on_cos $ λ x, id
lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) :=
continuous_on_iff_continuous_restrict.1 continuous_on_tan
lemma cos_surjective : function.surjective cos :=
begin
intro x,
obtain ⟨w, hw⟩ : ∃ w, 1 * w * w + (-2 * x) * w + 1 = 0,
{ exact exists_quadratic_eq_zero one_ne_zero (exists_eq_mul_self _) },
have hw' : exp (log w / I * I) = w,
{ rw [div_mul_cancel _ I_ne_zero, exp_log],
rintro rfl,
simpa only [zero_add, one_ne_zero, mul_zero] using hw },
obtain ⟨z, hz⟩ : ∃ z : ℂ, (exp (z * I)) ^ 2 - 2 * x * exp (z * I) + 1 = 0,
{ use log w / I, rw [hw', ← hw], ring },
use z,
delta cos,
rw ← mul_left_inj' (exp_ne_zero (z * I)),
rw [sub_add_eq_add_sub, sub_eq_zero, pow_two, ← exp_add, mul_comm _ x, mul_right_comm] at hz,
field_simp [add_mul, ← exp_add, hz]
end
@[simp] lemma range_cos : range cos = set.univ :=
cos_surjective.range_eq
lemma sin_surjective : function.surjective sin :=
begin
intro x,
rcases cos_surjective x with ⟨z, rfl⟩,
exact ⟨z+π/2, sin_add_pi_div_two z⟩
end
@[simp] lemma range_sin : range sin = set.univ :=
sin_surjective.range_eq
end complex
section chebyshev₁
open polynomial complex
/-- the `n`-th Chebyshev polynomial evaluates on `cos θ` to the value `cos (n * θ)`. -/
lemma chebyshev₁_complex_cos (θ : ℂ) :
∀ n, (chebyshev₁ ℂ n).eval (cos θ) = cos (n * θ)
| 0 := by simp only [chebyshev₁_zero, eval_one, nat.cast_zero, zero_mul, cos_zero]
| 1 := by simp only [eval_X, one_mul, chebyshev₁_one, nat.cast_one]
| (n + 2) :=
begin
simp only [eval_X, eval_one, chebyshev₁_add_two, eval_sub, eval_bit0, nat.cast_succ, eval_mul],
rw [chebyshev₁_complex_cos (n + 1), chebyshev₁_complex_cos n],
have aux : sin θ * sin θ = 1 - cos θ * cos θ,
{ rw ← sin_sq_add_cos_sq θ, ring, },
simp only [nat.cast_add, nat.cast_one, add_mul, cos_add, one_mul, sin_add, mul_assoc, aux],
ring,
end
/-- `cos (n * θ)` is equal to the `n`-th Chebyshev polynomial evaluated on `cos θ`. -/
lemma cos_nat_mul (n : ℕ) (θ : ℂ) :
cos (n * θ) = (chebyshev₁ ℂ n).eval (cos θ) :=
(chebyshev₁_complex_cos θ n).symm
end chebyshev₁
namespace real
open_locale real
theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 :=
begin
rw [← complex.of_real_eq_zero, complex.of_real_cos θ],
convert @complex.cos_eq_zero_iff θ,
norm_cast,
end
theorem cos_ne_zero_iff {θ : ℝ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 :=
by rw [← not_exists, not_iff_not, cos_eq_zero_iff]
lemma cos_eq_cos_iff {x y : ℝ} :
cos x = cos y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x :=
begin
have := @complex.cos_eq_cos_iff x y,
rw [← complex.of_real_cos, ← complex.of_real_cos] at this,
norm_cast at this,
simp [this],
end
lemma sin_eq_sin_iff {x y : ℝ} :
sin x = sin y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = (2 * k + 1) * π - x :=
begin
have := @complex.sin_eq_sin_iff x y,
rw [← complex.of_real_sin, ← complex.of_real_sin] at this,
norm_cast at this,
simp [this],
end
lemma has_deriv_at_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) :
has_deriv_at tan (1 / (cos x)^2) x :=
begin
convert (complex.has_deriv_at_tan (by { convert h, norm_cast } )).real_of_complex,
rw ← complex.of_real_re (1/((cos x)^2)),
simp,
end
lemma differentiable_at_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : differentiable_at ℝ tan x :=
(has_deriv_at_tan h).differentiable_at
@[simp] lemma deriv_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : deriv tan x = 1 / (cos x)^2 :=
(has_deriv_at_tan h).deriv
lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) :=
by simp only [tan_eq_sin_div_cos]; exact
(continuous_sin.comp continuous_subtype_val).mul
(continuous.inv subtype.property
(continuous_cos.comp continuous_subtype_val))
lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} :=
by { rw continuous_on_iff_continuous_restrict, convert continuous_tan }
lemma has_deriv_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) :
has_deriv_at tan (1 / (cos x)^2) x :=
has_deriv_at_tan (cos_ne_zero_iff.mp (ne_of_gt (cos_pos_of_mem_Ioo h.1 h.2)))
lemma differentiable_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) :
differentiable_at ℝ tan x :=
(has_deriv_at_tan_of_mem_Ioo h).differentiable_at
lemma deriv_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) : deriv tan x = 1 / (cos x)^2 :=
(has_deriv_at_tan_of_mem_Ioo h).deriv
lemma continuous_on_tan_Ioo : continuous_on tan (Ioo (-(π/2)) (π/2)) :=
begin
refine continuous_on_tan.mono _,
intros x hx,
simp only [mem_set_of_eq],
exact ne_of_gt (cos_pos_of_mem_Ioo hx.1 hx.2),
end
open filter
open_locale topological_space
lemma tendsto_sin_pi_div_two : tendsto sin (𝓝[Iio (π/2)] (π/2)) (𝓝 1) :=
by { convert continuous_sin.continuous_within_at, simp }
lemma tendsto_cos_pi_div_two : tendsto cos (𝓝[Iio (π/2)] (π/2)) (𝓝[Ioi 0] 0) :=
begin
apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within,
{ convert continuous_cos.continuous_within_at, simp },
{ filter_upwards [Ioo_mem_nhds_within_Iio (right_mem_Ioc.mpr (norm_num.lt_neg_pos
_ _ pi_div_two_pos pi_div_two_pos))] λ x hx, cos_pos_of_mem_Ioo hx.1 hx.2 },
end
lemma tendsto_tan_pi_div_two : tendsto tan (𝓝[Iio (π/2)] (π/2)) at_top :=
begin
convert tendsto_mul_at_top (by norm_num) (tendsto.inv_tendsto_zero tendsto_cos_pi_div_two)
tendsto_sin_pi_div_two,
ext x,
rw tan_eq_sin_div_cos x,
ring,
end
lemma tendsto_sin_neg_pi_div_two : tendsto sin (𝓝[Ioi (-(π/2))] (-(π/2))) (𝓝 (-1)) :=
by { convert continuous_sin.continuous_within_at, simp }
lemma tendsto_cos_neg_pi_div_two : tendsto cos (𝓝[Ioi (-(π/2))] (-(π/2))) (𝓝[Ioi 0] 0) :=
begin
apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within,
{ convert continuous_cos.continuous_within_at, simp },
{ filter_upwards [Ioo_mem_nhds_within_Ioi (set.left_mem_Ico.mpr (norm_num.lt_neg_pos
_ _ pi_div_two_pos pi_div_two_pos))] λ x hx, cos_pos_of_mem_Ioo hx.1 hx.2 },
end
lemma tendsto_tan_neg_pi_div_two : tendsto tan (𝓝[Ioi (-(π/2))] (-(π/2))) at_bot :=
begin
convert tendsto_mul_at_bot (by norm_num) (tendsto.inv_tendsto_zero tendsto_cos_neg_pi_div_two)
tendsto_sin_neg_pi_div_two,
ext x,
rw tan_eq_sin_div_cos x,
ring,
end
/-!
### Continuity and differentiability of arctan
The continuity of `arctan` is difficult to prove due to `arctan` being (indirectly) defined naively
via `classical.some`. The proof therefore uses the general theorem that monotone functions are
homeomorphisms: `homeomorph_of_strict_mono_continuous_Ioo`. We first prove that `tan` (restricted)
is a homeomorphism whose inverse is definitionally equal to `arctan`. The fact that `arctan` is
continuous is then derived from the fact that it is equal to a homeomorphism, and its
differentiability is in turn derived from its continuity using `has_deriv_at.of_local_left_inverse`.
-/
/-- The function `tan`, restricted to the open interval (-π/2, π/2), is a homeomorphism. The inverse
function of that homeomorphism is definitionally equal to `arctan` via `homeomorph.change_inv`. -/
def tan_homeomorph : (Ioo (-(π/2)) (π/2)) ≃ₜ ℝ :=
(homeomorph_of_strict_mono_continuous_Ioo tan (by linarith [pi_div_two_pos])
(λ x y, tan_lt_tan_of_lt_of_lt_pi_div_two) continuous_on_tan_Ioo tendsto_tan_pi_div_two
tendsto_tan_neg_pi_div_two).change_inv (λ x, ⟨arctan x, arctan_mem_Ioo x⟩) tan_arctan
lemma tan_homeomorph_inv_fun_eq_arctan : coe ∘ tan_homeomorph.inv_fun = arctan := rfl
lemma continuous_arctan : continuous arctan :=
continuous_subtype_coe.comp tan_homeomorph.continuous_inv_fun
lemma has_deriv_at_arctan (x : ℝ) : has_deriv_at arctan (1 / (1 + x^2)) x :=
begin
have h1 : 0 < 1 + x^2 := by nlinarith,
have h2 : cos (arctan x) ≠ 0 := by { rw cos_arctan, exact ne_of_gt (one_div_pos.mpr (sqrt_pos.mpr h1)) },
simpa [(cos_arctan x), sqr_sqrt (le_of_lt h1)] using has_deriv_at.of_local_left_inverse
continuous_arctan.continuous_at (has_deriv_at_tan (cos_ne_zero_iff.mp h2))
(one_div_ne_zero (pow_ne_zero 2 h2)) (by {apply eventually_of_forall, exact tan_arctan} ),
end
lemma differentiable_at_arctan (x : ℝ) : differentiable_at ℝ arctan x :=
(has_deriv_at_arctan x).differentiable_at
@[simp] lemma deriv_arctan : deriv arctan = (λ x, 1 / (1 + x^2)) :=
funext $ λ x, (has_deriv_at_arctan x).deriv
end real
section
/-! Register lemmas for the derivatives of the composition of `real.arctan` with a differentiable
function, for standalone use and use with `simp`. -/
variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ}
lemma has_deriv_at.arctan (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.arctan (f x)) ((1 / (1 + (f x)^2)) * f') x :=
(real.has_deriv_at_arctan (f x)).comp x hf
lemma has_deriv_within_at.arctan (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.arctan (f x)) ((1 / (1 + (f x)^2)) * f') s x :=
(real.has_deriv_at_arctan (f x)).comp_has_deriv_within_at x hf
lemma differentiable_within_at.arctan (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.arctan (f x)) s x :=
hf.has_deriv_within_at.arctan.differentiable_within_at
@[simp] lemma differentiable_at.arctan (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λ x, real.arctan (f x)) x :=
hc.has_deriv_at.arctan.differentiable_at
lemma differentiable_on.arctan (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λ x, real.arctan (f x)) s :=
λ x h, (hc x h).arctan
@[simp] lemma differentiable.arctan (hc : differentiable ℝ f) :
differentiable ℝ (λ x, real.arctan (f x)) :=
λ x, (hc x).arctan
lemma deriv_within_arctan (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) :
deriv_within (λ x, real.arctan (f x)) s x = (1 / (1 + (f x)^2)) * (deriv_within f s x) :=
hf.has_deriv_within_at.arctan.deriv_within hxs
@[simp] lemma deriv_arctan (hc : differentiable_at ℝ f x) :
deriv (λ x, real.arctan (f x)) x = (1 / (1 + (f x)^2)) * (deriv f x) :=
hc.has_deriv_at.arctan.deriv
end
|
365734c8350943171b98f23767c4f1eec8478a78 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /library/init/nat.lean | 0cad98f68fee5a1c653031d4545146e03a658628 | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,350 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura
-/
prelude
import init.wf init.tactic init.num
open eq.ops decidable or
notation `ℕ` := nat
namespace nat
protected definition rec_on [reducible] [recursor] [unfold 2]
{C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n :=
nat.rec H₁ H₂ n
protected definition induction_on [recursor]
{C : ℕ → Prop} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n :=
nat.rec H₁ H₂ n
protected definition cases_on [reducible] [recursor] [unfold 2]
{C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C (succ a)) : C n :=
nat.rec H₁ (λ a ih, H₂ a) n
protected definition no_confusion_type [reducible] (P : Type) (v₁ v₂ : ℕ) : Type :=
nat.rec
(nat.rec
(P → P)
(λ a₂ ih, P)
v₂)
(λ a₁ ih, nat.rec
P
(λ a₂ ih, (a₁ = a₂ → P) → P)
v₂)
v₁
protected definition no_confusion [reducible] [unfold 4]
{P : Type} {v₁ v₂ : ℕ} (H : v₁ = v₂) : nat.no_confusion_type P v₁ v₂ :=
eq.rec (λ H₁ : v₁ = v₁, nat.rec (λ h, h) (λ a ih h, h (eq.refl a)) v₁) H H
/- basic definitions on natural numbers -/
inductive le (a : ℕ) : ℕ → Prop :=
| nat_refl : le a a -- use nat_refl to avoid overloading le.refl
| step : Π {b}, le a b → le a (succ b)
definition nat_has_le [instance] [reducible] [priority nat.prio]: has_le nat := has_le.mk nat.le
protected lemma le_refl [refl] : ∀ a : nat, a ≤ a :=
le.nat_refl
protected definition lt [reducible] (n m : ℕ) := succ n ≤ m
definition nat_has_lt [instance] [reducible] [priority nat.prio] : has_lt nat := has_lt.mk nat.lt
definition pred [unfold 1] (a : nat) : nat :=
nat.cases_on a zero (λ a₁, a₁)
-- add is defined in init.num
protected definition sub (a b : nat) : nat :=
nat.rec_on b a (λ b₁, pred)
protected definition mul (a b : nat) : nat :=
nat.rec_on b zero (λ b₁ r, r + a)
definition nat_has_sub [instance] [reducible] [priority nat.prio] : has_sub nat :=
has_sub.mk nat.sub
definition nat_has_mul [instance] [reducible] [priority nat.prio] : has_mul nat :=
has_mul.mk nat.mul
/- properties of ℕ -/
protected definition is_inhabited [instance] : inhabited nat :=
inhabited.mk zero
protected definition has_decidable_eq [instance] [priority nat.prio] : ∀ x y : nat, decidable (x = y)
| has_decidable_eq zero zero := inl rfl
| has_decidable_eq (succ x) zero := inr (by contradiction)
| has_decidable_eq zero (succ y) := inr (by contradiction)
| has_decidable_eq (succ x) (succ y) :=
match has_decidable_eq x y with
| inl xeqy := inl (by rewrite xeqy)
| inr xney := inr (λ h : succ x = succ y, by injection h with xeqy; exact absurd xeqy xney)
end
/- properties of inequality -/
protected theorem le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ !nat.le_refl
theorem le_succ (n : ℕ) : n ≤ succ n := le.step !nat.le_refl
theorem pred_le (n : ℕ) : pred n ≤ n := by cases n;repeat constructor
theorem le_succ_iff_true [simp] (n : ℕ) : n ≤ succ n ↔ true :=
iff_true_intro (le_succ n)
theorem pred_le_iff_true [simp] (n : ℕ) : pred n ≤ n ↔ true :=
iff_true_intro (pred_le n)
protected theorem le_trans {n m k : ℕ} (H1 : n ≤ m) : m ≤ k → n ≤ k :=
le.rec H1 (λp H2, le.step)
theorem le_succ_of_le {n m : ℕ} (H : n ≤ m) : n ≤ succ m := nat.le_trans H !le_succ
theorem le_of_succ_le {n m : ℕ} (H : succ n ≤ m) : n ≤ m := nat.le_trans !le_succ H
protected theorem le_of_lt {n m : ℕ} (H : n < m) : n ≤ m := le_of_succ_le H
theorem succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m :=
le.rec !nat.le_refl (λa b, le.step)
theorem pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m :=
le.rec !nat.le_refl (nat.rec (λa b, b) (λa b c, le.step))
theorem le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m :=
pred_le_pred
theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m :=
nat.cases_on n le.step (λa, succ_le_succ)
theorem not_succ_le_zero (n : ℕ) : ¬succ n ≤ 0 :=
by intro H; cases H
theorem succ_le_zero_iff_false (n : ℕ) : succ n ≤ 0 ↔ false :=
iff_false_intro !not_succ_le_zero
theorem not_succ_le_self : Π {n : ℕ}, ¬succ n ≤ n :=
nat.rec !not_succ_le_zero (λa b c, b (le_of_succ_le_succ c))
theorem succ_le_self_iff_false [simp] (n : ℕ) : succ n ≤ n ↔ false :=
iff_false_intro not_succ_le_self
theorem zero_le : ∀ (n : ℕ), 0 ≤ n :=
nat.rec !nat.le_refl (λa, le.step)
theorem zero_le_iff_true [simp] (n : ℕ) : 0 ≤ n ↔ true :=
iff_true_intro !zero_le
theorem lt.step {n m : ℕ} : n < m → n < succ m := le.step
theorem zero_lt_succ (n : ℕ) : 0 < succ n :=
succ_le_succ !zero_le
theorem zero_lt_succ_iff_true [simp] (n : ℕ) : 0 < succ n ↔ true :=
iff_true_intro (zero_lt_succ n)
protected theorem lt_trans {n m k : ℕ} (H1 : n < m) : m < k → n < k :=
nat.le_trans (le.step H1)
protected theorem lt_of_le_of_lt {n m k : ℕ} (H1 : n ≤ m) : m < k → n < k :=
nat.le_trans (succ_le_succ H1)
protected theorem lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans
protected theorem lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self
theorem lt_self_iff_false (n : ℕ) : n < n ↔ false :=
iff_false_intro (λ H, absurd H (nat.lt_irrefl n))
theorem self_lt_succ (n : ℕ) : n < succ n := !nat.le_refl
theorem self_lt_succ_iff_true [simp] (n : ℕ) : n < succ n ↔ true :=
iff_true_intro (self_lt_succ n)
theorem lt.base (n : ℕ) : n < succ n := !nat.le_refl
theorem le_lt_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m < n) : false :=
!nat.lt_irrefl (nat.lt_of_le_of_lt H1 H2)
protected theorem le_antisymm {n m : ℕ} (H1 : n ≤ m) : m ≤ n → n = m :=
le.cases_on H1 (λa, rfl) (λa b c, absurd (nat.lt_of_le_of_lt b c) !nat.lt_irrefl)
theorem lt_le_antisymm {n m : ℕ} (H1 : n < m) (H2 : m ≤ n) : false :=
le_lt_antisymm H2 H1
protected theorem nat.lt_asymm {n m : ℕ} (H1 : n < m) : ¬ m < n :=
le_lt_antisymm (nat.le_of_lt H1)
theorem not_lt_zero (a : ℕ) : ¬ a < 0 := !not_succ_le_zero
theorem lt_zero_iff_false [simp] (a : ℕ) : a < 0 ↔ false :=
iff_false_intro (not_lt_zero a)
protected theorem eq_or_lt_of_le {a b : ℕ} (H : a ≤ b) : a = b ∨ a < b :=
le.cases_on H (inl rfl) (λn h, inr (succ_le_succ h))
protected theorem le_of_eq_or_lt {a b : ℕ} (H : a = b ∨ a < b) : a ≤ b :=
or.elim H !nat.le_of_eq !nat.le_of_lt
-- less-than is well-founded
definition lt.wf [instance] : well_founded lt :=
well_founded.intro (nat.rec
(!acc.intro (λn H, absurd H (not_lt_zero n)))
(λn IH, !acc.intro (λm H,
elim (nat.eq_or_lt_of_le (le_of_succ_le_succ H))
(λe, eq.substr e IH) (acc.inv IH))))
definition measure {A : Type} : (A → ℕ) → A → A → Prop :=
inv_image lt
definition measure.wf {A : Type} (f : A → ℕ) : well_founded (measure f) :=
inv_image.wf f lt.wf
theorem succ_lt_succ {a b : ℕ} : a < b → succ a < succ b :=
succ_le_succ
theorem lt_of_succ_lt {a b : ℕ} : succ a < b → a < b :=
le_of_succ_le
theorem lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b :=
le_of_succ_le_succ
definition decidable_le [instance] [priority nat.prio] : ∀ a b : nat, decidable (a ≤ b) :=
nat.rec (λm, (decidable.inl !zero_le))
(λn IH m, !nat.cases_on (decidable.inr (not_succ_le_zero n))
(λm, decidable.rec (λH, inl (succ_le_succ H))
(λH, inr (λa, H (le_of_succ_le_succ a))) (IH m)))
definition decidable_lt [instance] [priority nat.prio] : ∀ a b : nat, decidable (a < b) :=
λ a b, decidable_le (succ a) b
protected theorem lt_or_ge (a b : ℕ) : a < b ∨ a ≥ b :=
nat.rec (inr !zero_le) (λn, or.rec
(λh, inl (le_succ_of_le h))
(λh, elim (nat.eq_or_lt_of_le h) (λe, inl (eq.subst e !nat.le_refl)) inr)) b
protected definition lt_ge_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a ≥ b → P) : P :=
by_cases H1 (λh, H2 (elim !nat.lt_or_ge (λa, absurd a h) (λa, a)))
protected definition lt_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P)
(H3 : b < a → P) : P :=
nat.lt_ge_by_cases H1 (λh₁,
nat.lt_ge_by_cases H3 (λh₂, H2 (nat.le_antisymm h₂ h₁)))
protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a :=
nat.lt_by_cases (λH, inl H) (λH, inr (inl H)) (λH, inr (inr H))
protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a :=
or.rec_on (nat.lt_trichotomy a b)
(λ hlt, absurd hlt hnlt)
(λ h, h)
theorem lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b :=
succ_le_succ
theorem lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h
theorem succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h
theorem succ_sub_succ_eq_sub [simp] (a b : ℕ) : succ a - succ b = a - b :=
nat.rec (by esimp) (λ b, congr_arg pred) b
theorem sub_eq_succ_sub_succ (a b : ℕ) : a - b = succ a - succ b :=
eq.symm !succ_sub_succ_eq_sub
theorem zero_sub_eq_zero [simp] (a : ℕ) : 0 - a = 0 :=
nat.rec rfl (λ a, congr_arg pred) a
theorem zero_eq_zero_sub (a : ℕ) : 0 = 0 - a :=
eq.symm !zero_sub_eq_zero
theorem sub_le (a b : ℕ) : a - b ≤ a :=
nat.rec_on b !nat.le_refl (λ b₁, nat.le_trans !pred_le)
theorem sub_le_iff_true [simp] (a b : ℕ) : a - b ≤ a ↔ true :=
iff_true_intro (sub_le a b)
theorem sub_lt {a b : ℕ} (H1 : 0 < a) (H2 : 0 < b) : a - b < a :=
!nat.cases_on (λh, absurd h !nat.lt_irrefl)
(λa h, succ_le_succ (!nat.cases_on (λh, absurd h !nat.lt_irrefl)
(λb c, eq.substr !succ_sub_succ_eq_sub !sub_le) H2)) H1
theorem sub_lt_succ (a b : ℕ) : a - b < succ a :=
lt_succ_of_le !sub_le
theorem sub_lt_succ_iff_true [simp] (a b : ℕ) : a - b < succ a ↔ true :=
iff_true_intro !sub_lt_succ
end nat
|
1712d0e232aa84c15242a8263471ef0ce6a550e4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/calculus/affine_map.lean | 97f2e2a756d3aa5488349acb8de44f63930b602f | [
"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 | 907 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import analysis.normed_space.continuous_affine_map
import analysis.calculus.cont_diff
/-!
# Smooth affine maps
This file contains results about smoothness of affine maps.
## Main definitions:
* `continuous_affine_map.cont_diff`: a continuous affine map is smooth
-/
namespace continuous_affine_map
variables {𝕜 V W : Type*} [nontrivially_normed_field 𝕜]
variables [normed_add_comm_group V] [normed_space 𝕜 V]
variables [normed_add_comm_group W] [normed_space 𝕜 W]
/-- A continuous affine map between normed vector spaces is smooth. -/
lemma cont_diff {n : ℕ∞} (f : V →A[𝕜] W) :
cont_diff 𝕜 n f :=
begin
rw f.decomp,
apply f.cont_linear.cont_diff.add,
simp only,
exact cont_diff_const,
end
end continuous_affine_map
|
192a4a3a5fb057621bd9f11da04c875624d7aa74 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/calculus/formal_multilinear_series.lean | 08490045b8cb5a70d1f41f43790df68b0f6d285d | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 6,952 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.normed_space.multilinear
/-!
# Formal multilinear series
In this file we define `formal_multilinear_series 𝕜 E F` to be a family of `n`-multilinear maps for
all `n`, designed to model the sequence of derivatives of a function. In other files we use this
notion to define `C^n` functions (called `cont_diff` in `mathlib`) and analytic functions.
## Notations
We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with
values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives.
## Tags
multilinear, formal series
-/
noncomputable theory
open set fin
open_locale topological_space
variables {𝕜 𝕜' E F G : Type*}
section
variables [comm_ring 𝕜]
[add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E]
[add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F]
[has_continuous_const_smul 𝕜 F]
[add_comm_group G] [module 𝕜 G] [topological_space G] [topological_add_group G]
[has_continuous_const_smul 𝕜 G]
/-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of
multilinear maps from `E^n` to `F` for all `n`. -/
@[derive add_comm_group, nolint unused_arguments]
def formal_multilinear_series (𝕜 : Type*) (E : Type*) (F : Type*)
[ring 𝕜]
[add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E]
[add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F]
[has_continuous_const_smul 𝕜 F] :=
Π (n : ℕ), (E [×n]→L[𝕜] F)
instance : inhabited (formal_multilinear_series 𝕜 E F) := ⟨0⟩
section module
/- `derive` is not able to find the module structure, probably because Lean is confused by the
dependent types. We register it explicitly. -/
instance : module 𝕜 (formal_multilinear_series 𝕜 E F) :=
begin
letI : Π n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) :=
λ n, by apply_instance,
refine pi.module _ _ _,
end
end module
namespace formal_multilinear_series
/-- Killing the zeroth coefficient in a formal multilinear series -/
def remove_zero (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E F
| 0 := 0
| (n + 1) := p (n + 1)
@[simp] lemma remove_zero_coeff_zero (p : formal_multilinear_series 𝕜 E F) :
p.remove_zero 0 = 0 := rfl
@[simp] lemma remove_zero_coeff_succ (p : formal_multilinear_series 𝕜 E F) (n : ℕ) :
p.remove_zero (n+1) = p (n+1) := rfl
lemma remove_zero_of_pos (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (h : 0 < n) :
p.remove_zero n = p n :=
by { rw ← nat.succ_pred_eq_of_pos h, refl }
/-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal
multilinear series are equal, then the values are also equal. -/
lemma congr (p : formal_multilinear_series 𝕜 E F) {m n : ℕ} {v : fin m → E} {w : fin n → E}
(h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v ⟨i, him⟩ = w ⟨i, hin⟩) :
p m v = p n w :=
by { cases h1, congr' with ⟨i, hi⟩, exact h2 i hi hi }
/-- Composing each term `pₙ` in a formal multilinear series with `(u, ..., u)` where `u` is a fixed
continuous linear map, gives a new formal multilinear series `p.comp_continuous_linear_map u`. -/
def comp_continuous_linear_map (p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) :
formal_multilinear_series 𝕜 E G :=
λ n, (p n).comp_continuous_linear_map (λ (i : fin n), u)
@[simp] lemma comp_continuous_linear_map_apply
(p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) (n : ℕ) (v : fin n → E) :
(p.comp_continuous_linear_map u) n v = p n (u ∘ v) := rfl
variables (𝕜) [comm_ring 𝕜'] [has_scalar 𝕜 𝕜']
variables [module 𝕜' E] [has_continuous_const_smul 𝕜' E] [is_scalar_tower 𝕜 𝕜' E]
variables [module 𝕜' F] [has_continuous_const_smul 𝕜' F] [is_scalar_tower 𝕜 𝕜' F]
/-- Reinterpret a formal `𝕜'`-multilinear series as a formal `𝕜`-multilinear series. -/
@[simp] protected def restrict_scalars (p : formal_multilinear_series 𝕜' E F) :
formal_multilinear_series 𝕜 E F :=
λ n, (p n).restrict_scalars 𝕜
end formal_multilinear_series
end
namespace formal_multilinear_series
variables [nondiscrete_normed_field 𝕜]
[normed_group E] [normed_space 𝕜 E]
[normed_group F] [normed_space 𝕜 F]
[normed_group G] [normed_space 𝕜 G]
variables (p : formal_multilinear_series 𝕜 E F)
/-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms
as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then
`p.shift` is the Taylor series of the derivative of the function. -/
def shift : formal_multilinear_series 𝕜 E (E →L[𝕜] F) :=
λn, (p n.succ).curry_right
/-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This
corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor
series for the function itself. -/
def unshift (q : formal_multilinear_series 𝕜 E (E →L[𝕜] F)) (z : F) :
formal_multilinear_series 𝕜 E F
| 0 := (continuous_multilinear_curry_fin0 𝕜 E F).symm z
| (n + 1) := continuous_multilinear_curry_right_equiv' 𝕜 n E F (q n)
end formal_multilinear_series
namespace continuous_linear_map
variables [comm_ring 𝕜]
[add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E]
[add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F]
[has_continuous_const_smul 𝕜 F]
[add_comm_group G] [module 𝕜 G] [topological_space G] [topological_add_group G]
[has_continuous_const_smul 𝕜 G]
/-- Composing each term `pₙ` in a formal multilinear series with a continuous linear map `f` on the
left gives a new formal multilinear series `f.comp_formal_multilinear_series p` whose general term
is `f ∘ pₙ`. -/
def comp_formal_multilinear_series (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) :
formal_multilinear_series 𝕜 E G :=
λ n, f.comp_continuous_multilinear_map (p n)
@[simp] lemma comp_formal_multilinear_series_apply
(f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) :
(f.comp_formal_multilinear_series p) n = f.comp_continuous_multilinear_map (p n) :=
rfl
lemma comp_formal_multilinear_series_apply'
(f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (v : fin n → E) :
(f.comp_formal_multilinear_series p) n v = f (p n v) :=
rfl
end continuous_linear_map
|
c2232b495c756b2e3d9f776587eef004de1af36f | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/tst16.lean | ebfefd24dd5a4cc1ecb7f9d110285d590a3fd75c | [
"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 | 615 | lean | variable f : Type -> Bool
print forall a b : Type, (f a) = (f b)
variable g : Bool -> Bool -> Bool
print forall (a b : Type) (c : Bool), g c ((f a) = (f b))
print exists (a b : Type) (c : Bool), g c ((f a) = (f b))
print forall (a b : Type) (c : Bool), (g c (f a) = (f b)) -> (f a)
check forall (a b : Type) (c : Bool), g c ((f a) = (f b))
print ∀ (a b : Type) (c : Bool), g c ((f a) = (f b))
print ∀ a b : Type, (f a) = (f b)
print ∃ a b : Type, (f a) = (f b) ∧ (f a)
print ∃ a b : Type, (f a) = (f b) ∨ (f b)
variable a : Bool
print (f a) ∨ (f a)
print (f a) = a ∨ (f a)
print (f a) = a ∧ (f a)
|
a5c247392011c341ab2c099dbb2237e2cf6ded52 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/continued_fractions/terminated_stable.lean | f31d31624322684da893bcca3a7a95fa6beed103 | [] | 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,990 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.continued_fractions.translations
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Stabilisation of gcf Computations Under Termination
## Summary
We show that the continuants and convergents of a gcf stabilise once the gcf terminates.
-/
namespace generalized_continued_fraction
/-- If a gcf terminated at position `n`, it also terminated at `m ≥ n`.-/
theorem terminated_stable {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} {m : ℕ} (n_le_m : n ≤ m) (terminated_at_n : terminated_at g n) : terminated_at g m :=
seq.terminated_stable (s g) n_le_m terminated_at_n
theorem continuants_aux_stable_step_of_terminated {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] (terminated_at_n : terminated_at g n) : continuants_aux g (n + bit0 1) = continuants_aux g (n + 1) := sorry
theorem continuants_aux_stable_of_terminated {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} {m : ℕ} [division_ring K] (succ_n_le_m : n + 1 ≤ m) (terminated_at_n : terminated_at g n) : continuants_aux g m = continuants_aux g (n + 1) := sorry
theorem convergents'_aux_stable_step_of_terminated {K : Type u_1} {n : ℕ} [division_ring K] {s : seq (pair K)} (terminated_at_n : seq.terminated_at s n) : convergents'_aux s (n + 1) = convergents'_aux s n := sorry
theorem convergents'_aux_stable_of_terminated {K : Type u_1} {n : ℕ} {m : ℕ} [division_ring K] {s : seq (pair K)} (n_le_m : n ≤ m) (terminated_at_n : seq.terminated_at s n) : convergents'_aux s m = convergents'_aux s n := sorry
theorem continuants_stable_of_terminated {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} {m : ℕ} [division_ring K] (n_le_m : n ≤ m) (terminated_at_n : terminated_at g n) : continuants g m = continuants g n := sorry
theorem numerators_stable_of_terminated {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} {m : ℕ} [division_ring K] (n_le_m : n ≤ m) (terminated_at_n : terminated_at g n) : numerators g m = numerators g n := sorry
theorem denominators_stable_of_terminated {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} {m : ℕ} [division_ring K] (n_le_m : n ≤ m) (terminated_at_n : terminated_at g n) : denominators g m = denominators g n := sorry
theorem convergents_stable_of_terminated {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} {m : ℕ} [division_ring K] (n_le_m : n ≤ m) (terminated_at_n : terminated_at g n) : convergents g m = convergents g n := sorry
theorem convergents'_stable_of_terminated {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} {m : ℕ} [division_ring K] (n_le_m : n ≤ m) (terminated_at_n : terminated_at g n) : convergents' g m = convergents' g n := sorry
|
a9a49bff8680f3249ac2b91f2a15bc165ea14614 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1030.lean | e333841db671dba6a39d0a621ce27deb877967eb | [
"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 | 338 | lean | def foo: List Unit → Type
| [] => Unit → Unit
| _ :: tl => foo tl
partial def bar: (l: List Unit) → foo l → foo l
| [] , f => λ t => f t
| _ :: tl, f => bar tl f
def bar': (l: List Unit) → foo l → foo l
| [] , f => by simp only [foo] at f; exact (λ t => f t)
| _ :: tl, f => bar' tl f
#eval bar [()] id ()
|
64036d62d90599f1d7ca5933b97d617ec2c460be | b2fe74b11b57d362c13326bc5651244f111fa6f4 | /src/ring_theory/fractional_ideal.lean | dad99f4751e9dafb21be26ef235a0904df846c62 | [
"Apache-2.0"
] | permissive | midfield/mathlib | c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7 | 775edc615ecec631d65b6180dbcc7bc26c3abc26 | refs/heads/master | 1,675,330,551,921 | 1,608,304,514,000 | 1,608,304,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 41,786 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import ring_theory.localization
import ring_theory.noetherian
import ring_theory.principal_ideal_domain
/-!
# Fractional ideals
This file defines fractional ideals of an integral domain and proves basic facts about them.
## Main definitions
Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the
natural ring hom from `R` to `P`.
* `is_fractional` defines which `R`-submodules of `P` are fractional ideals
* `fractional_ideal f` is the type of fractional ideals in `P`
* `has_coe (ideal R) (fractional_ideal f)` instance
* `comm_semiring (fractional_ideal f)` instance:
the typical ideal operations generalized to fractional ideals
* `lattice (fractional_ideal f)` instance
* `map` is the pushforward of a fractional ideal along an algebra morphism
Let `K` be the localization of `R` at `R \ {0}` and `g` the natural ring hom from `R` to `K`.
* `has_div (fractional_ideal g)` instance:
the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined)
## Main statements
* `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone
* `right_inverse_eq` states that `1 / I` is the inverse of `I` if one exists
## Implementation notes
Fractional ideals are considered equal when they contain the same elements,
independent of the denominator `a : R` such that `a I ⊆ R`.
Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`,
instead of having `fractional_ideal` be a structure of which `a` is a field.
Most definitions in this file specialize operations from submodules to fractional ideals,
proving that the result of this operation is fractional if the input is fractional.
Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`,
in order to re-use their respective proof terms.
We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`.
In `ring_theory.localization`, we define a copy of the localization map `f`'s codomain `P`
(`f.codomain`) so that the `R`-algebra instance on `P` can 'know' the map needed to induce
the `R`-algebra structure.
We don't assume that the localization is a field until we need it to define ideal quotients.
When this assumption is needed, we replace `S` with `non_zero_divisors R`, making the localization
a field.
## References
* https://en.wikipedia.org/wiki/Fractional_ideal
## Tags
fractional ideal, fractional ideals, invertible ideal
-/
open localization_map
namespace ring
section defs
variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P]
(f : localization_map S P)
/-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/
def is_fractional (I : submodule R f.codomain) :=
∃ a ∈ S, ∀ b ∈ I, f.is_integer (f.to_map a * b)
/-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`.
More precisely, let `P` be a localization of `R` at some submonoid `S`,
then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`,
such that there is a nonzero `a : R` with `a I ⊆ R`.
-/
def fractional_ideal :=
{I : submodule R f.codomain // is_fractional f I}
end defs
namespace fractional_ideal
open set
open submodule
variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P]
{f : localization_map S P}
instance : has_coe (fractional_ideal f) (submodule R f.codomain) := ⟨λ I, I.val⟩
@[simp] lemma val_eq_coe (I : fractional_ideal f) : I.val = I := rfl
@[simp, norm_cast] lemma coe_mk (I : submodule R f.codomain) (hI : is_fractional f I) :
(subtype.mk I hI : submodule R f.codomain) = I := rfl
instance : has_mem P (fractional_ideal f) := ⟨λ x I, x ∈ (I : submodule R f.codomain)⟩
/-- Fractional ideals are equal if their submodules are equal.
Combined with `submodule.ext` this gives that fractional ideals are equal if
they have the same elements.
-/
@[ext]
lemma ext {I J : fractional_ideal f} : (I : submodule R f.codomain) = J → I = J :=
subtype.ext_iff_val.mpr
lemma ext_iff {I J : fractional_ideal f} : (∀ x, (x ∈ I ↔ x ∈ J)) ↔ I = J :=
⟨ λ h, ext (submodule.ext h), λ h x, h ▸ iff.rfl ⟩
lemma fractional_of_subset_one (I : submodule R f.codomain)
(h : I ≤ (submodule.span R {1})) :
is_fractional f I :=
begin
use [1, S.one_mem],
intros b hb,
rw [f.to_map.map_one, one_mul],
rw ←submodule.one_eq_span at h,
obtain ⟨b', b'_mem, b'_eq_b⟩ := h hb,
rw (show b = f.to_map b', from b'_eq_b.symm),
exact set.mem_range_self b',
end
lemma is_fractional_of_le {I : submodule R f.codomain} {J : fractional_ideal f}
(hIJ : I ≤ J) : is_fractional f I :=
begin
obtain ⟨a, a_mem, ha⟩ := J.2,
use [a, a_mem],
intros b b_mem,
exact ha b (hIJ b_mem)
end
instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal f) :=
⟨ λ I, ⟨f.coe_submodule I, fractional_of_subset_one _ $ λ x ⟨y, hy, h⟩,
submodule.mem_span_singleton.2 ⟨y, by rw ←h; exact mul_one _⟩⟩ ⟩
@[simp, norm_cast] lemma coe_coe_ideal (I : ideal R) :
((I : fractional_ideal f) : submodule R f.codomain) = f.coe_submodule I := rfl
@[simp] lemma mem_coe_ideal {x : f.codomain} {I : ideal R} :
x ∈ (I : fractional_ideal f) ↔ ∃ (x' ∈ I), f.to_map x' = x :=
⟨ λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩,
λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩ ⟩
instance : has_zero (fractional_ideal f) := ⟨(0 : ideal R)⟩
@[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal f) ↔ x = 0 :=
⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩,
have x'_eq_zero : x' = 0 := x'_mem_zero,
by simp [x'_eq_x.symm, x'_eq_zero]),
(λ hx, ⟨0, rfl, by simp [hx]⟩) ⟩
@[simp, norm_cast] lemma coe_zero : ↑(0 : fractional_ideal f) = (⊥ : submodule R f.codomain) :=
submodule.ext $ λ _, mem_zero_iff
@[simp, norm_cast] lemma coe_to_fractional_ideal_bot : ((⊥ : ideal R) : fractional_ideal f) = 0 :=
rfl
@[simp] lemma exists_mem_to_map_eq {x : R} {I : ideal R} (h : S ≤ non_zero_divisors R) :
(∃ x', x' ∈ I ∧ f.to_map x' = f.to_map x) ↔ x ∈ I :=
⟨λ ⟨x', hx', eq⟩, f.injective h eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩
lemma coe_to_fractional_ideal_injective (h : S ≤ non_zero_divisors R) :
function.injective (coe : ideal R → fractional_ideal f) :=
λ I J heq, have
∀ (x : R), f.to_map x ∈ (I : fractional_ideal f) ↔ f.to_map x ∈ (J : fractional_ideal f) :=
λ x, heq ▸ iff.rfl,
ideal.ext (by { simpa only [mem_coe_ideal, exists_prop, exists_mem_to_map_eq h] using this })
lemma coe_to_fractional_ideal_eq_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) :
(I : fractional_ideal f) = 0 ↔ I = (⊥ : ideal R) :=
⟨λ h, coe_to_fractional_ideal_injective hS h,
λ h, by rw [h, coe_to_fractional_ideal_bot]⟩
lemma coe_to_fractional_ideal_ne_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) :
(I : fractional_ideal f) ≠ 0 ↔ I ≠ (⊥ : ideal R) :=
not_iff_not.mpr (coe_to_fractional_ideal_eq_zero hS)
lemma coe_to_submodule_eq_bot {I : fractional_ideal f} :
(I : submodule R f.codomain) = ⊥ ↔ I = 0 :=
⟨λ h, ext (by simp [h]),
λ h, by simp [h] ⟩
lemma coe_to_submodule_ne_bot {I : fractional_ideal f} :
↑I ≠ (⊥ : submodule R f.codomain) ↔ I ≠ 0 :=
not_iff_not.mpr coe_to_submodule_eq_bot
instance : inhabited (fractional_ideal f) := ⟨0⟩
instance : has_one (fractional_ideal f) :=
⟨(1 : ideal R)⟩
lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal f) ↔ ∃ x' : R, f.to_map x' = x :=
iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩)
lemma coe_mem_one (x : R) : f.to_map x ∈ (1 : fractional_ideal f) :=
mem_one_iff.mpr ⟨x, rfl⟩
lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal f) :=
mem_one_iff.mpr ⟨1, f.to_map.map_one⟩
/-- `(1 : fractional_ideal f)` is defined as the R-submodule `f(R) ≤ K`.
However, this is not definitionally equal to `1 : submodule R K`,
which is proved in the actual `simp` lemma `coe_one`. -/
lemma coe_one_eq_coe_submodule_one :
↑(1 : fractional_ideal f) = f.coe_submodule (1 : ideal R) :=
rfl
@[simp, norm_cast] lemma coe_one :
(↑(1 : fractional_ideal f) : submodule R f.codomain) = 1 :=
begin
simp only [coe_one_eq_coe_submodule_one, ideal.one_eq_top],
convert (submodule.one_eq_map_top).symm,
end
section lattice
/-!
### `lattice` section
Defines the order on fractional ideals as inclusion of their underlying sets,
and ports the lattice structure on submodules to fractional ideals.
-/
instance : partial_order (fractional_ideal f) :=
{ le := λ I J, I.1 ≤ J.1,
le_refl := λ I, le_refl I.1,
le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI },
le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK }
lemma le_iff_mem {I J : fractional_ideal f} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) :=
iff.rfl
@[simp] lemma coe_le_coe {I J : fractional_ideal f} :
(I : submodule R f.codomain) ≤ (J : submodule R f.codomain) ↔ I ≤ J :=
iff.rfl
lemma zero_le (I : fractional_ideal f) : 0 ≤ I :=
begin
intros x hx,
convert submodule.zero_mem _,
simpa using hx
end
instance order_bot : order_bot (fractional_ideal f) :=
{ bot := 0,
bot_le := zero_le,
..fractional_ideal.partial_order }
@[simp] lemma bot_eq_zero : (⊥ : fractional_ideal f) = 0 :=
rfl
@[simp] lemma le_zero_iff {I : fractional_ideal f} : I ≤ 0 ↔ I = 0 :=
le_bot_iff
lemma eq_zero_iff {I : fractional_ideal f} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) :=
⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx),
(λ h, le_bot_iff.mp (λ x hx, mem_zero_iff.mpr (h x hx))) ⟩
lemma fractional_sup (I J : fractional_ideal f) : is_fractional f (I.1 ⊔ J.1) :=
begin
rcases I.2 with ⟨aI, haI, hI⟩,
rcases J.2 with ⟨aJ, haJ, hJ⟩,
use aI * aJ,
use S.mul_mem haI haJ,
intros b hb,
rcases mem_sup.mp hb with
⟨bI, hbI, bJ, hbJ, hbIJ⟩,
rw [←hbIJ, mul_add],
apply is_integer_add,
{ rw [mul_comm aI, f.to_map.map_mul, mul_assoc],
apply is_integer_smul (hI bI hbI), },
{ rw [f.to_map.map_mul, mul_assoc],
apply is_integer_smul (hJ bJ hbJ) }
end
lemma fractional_inf (I J : fractional_ideal f) : is_fractional f (I.1 ⊓ J.1) :=
begin
rcases I.2 with ⟨aI, haI, hI⟩,
use aI,
use haI,
intros b hb,
rcases mem_inf.mp hb with ⟨hbI, hbJ⟩,
exact (hI b hbI)
end
instance lattice : lattice (fractional_ideal f) :=
{ inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩,
sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩,
inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left,
inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right,
le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK,
le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left,
le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right,
sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK,
..fractional_ideal.partial_order }
instance : semilattice_sup_bot (fractional_ideal f) :=
{ ..fractional_ideal.order_bot, ..fractional_ideal.lattice }
end lattice
section semiring
instance : has_add (fractional_ideal f) := ⟨(⊔)⟩
@[simp]
lemma sup_eq_add (I J : fractional_ideal f) : I ⊔ J = I + J := rfl
@[simp, norm_cast]
lemma coe_add (I J : fractional_ideal f) : (↑(I + J) : submodule R f.codomain) = I + J := rfl
lemma fractional_mul (I J : fractional_ideal f) : is_fractional f (I.1 * J.1) :=
begin
rcases I with ⟨I, aI, haI, hI⟩,
rcases J with ⟨I, aJ, haJ, hJ⟩,
use aI * aJ,
use S.mul_mem haI haJ,
intros b hb,
apply submodule.mul_induction_on hb,
{ intros m hm n hn,
obtain ⟨n', hn'⟩ := hJ n hn,
rw [f.to_map.map_mul, mul_comm m, ←mul_assoc, mul_assoc _ _ n],
erw ←hn', rw mul_assoc,
apply hI,
exact submodule.smul_mem _ _ hm },
{ rw [mul_zero],
exact ⟨0, f.to_map.map_zero⟩ },
{ intros x y hx hy,
rw [mul_add],
apply is_integer_add hx hy },
{ intros r x hx,
show f.is_integer (_ * (f.to_map r * x)),
rw [←mul_assoc, ←f.to_map.map_mul, mul_comm _ r, f.to_map.map_mul, mul_assoc],
apply is_integer_smul hx },
end
/-- `fractional_ideal.mul` is the product of two fractional ideals,
used to define the `has_mul` instance.
This is only an auxiliary definition: the preferred way of writing `I.mul J` is `I * J`.
Elaborated terms involving `fractional_ideal` tend to grow quite large,
so by making definitions irreducible, we hope to avoid deep unfolds.
-/
@[irreducible]
def mul (I J : fractional_ideal f) : fractional_ideal f :=
⟨I.1 * J.1, fractional_mul I J⟩
local attribute [semireducible] mul
instance : has_mul (fractional_ideal f) := ⟨λ I J, mul I J⟩
@[simp] lemma mul_eq_mul (I J : fractional_ideal f) : mul I J = I * J := rfl
@[simp, norm_cast]
lemma coe_mul (I J : fractional_ideal f) : (↑(I * J) : submodule R f.codomain) = I * J := rfl
lemma mul_left_mono (I : fractional_ideal f) : monotone ((*) I) :=
λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy))
lemma mul_right_mono (I : fractional_ideal f) : monotone (λ J, J * I) :=
λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy)
lemma mul_mem_mul {I J : fractional_ideal f} {i j : f.codomain} (hi : i ∈ I) (hj : j ∈ J) :
i * j ∈ I * J := submodule.mul_mem_mul hi hj
lemma mul_le {I J K : fractional_ideal f} :
I * J ≤ K ↔ (∀ (i ∈ I) (j ∈ J), i * j ∈ K) :=
submodule.mul_le
@[elab_as_eliminator] protected theorem mul_induction_on
{I J : fractional_ideal f}
{C : f.codomain → Prop} {r : f.codomain} (hr : r ∈ I * J)
(hm : ∀ (i ∈ I) (j ∈ J), C (i * j))
(h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y))
(hs : ∀ (r : R) x, C x → C (r • x)) : C r :=
submodule.mul_induction_on hr hm h0 ha hs
instance comm_semiring : comm_semiring (fractional_ideal f) :=
{ add_assoc := λ I J K, sup_assoc,
add_comm := λ I J, sup_comm,
add_zero := λ I, sup_bot_eq,
zero_add := λ I, bot_sup_eq,
mul_assoc := λ I J K, ext (submodule.mul_assoc _ _ _),
mul_comm := λ I J, ext (submodule.mul_comm _ _),
mul_one := λ I, begin
ext,
split; intro h,
{ apply mul_le.mpr _ h,
rintros x hx y ⟨y', y'_mem_R, y'_eq_y⟩,
rw [←y'_eq_y, mul_comm],
exact submodule.smul_mem _ _ hx },
{ have : x * 1 ∈ (I * 1) := mul_mem_mul h one_mem_one,
rwa [mul_one] at this }
end,
one_mul := λ I, begin
ext,
split; intro h,
{ apply mul_le.mpr _ h,
rintros x ⟨x', x'_mem_R, x'_eq_x⟩ y hy,
rw ←x'_eq_x,
exact submodule.smul_mem _ _ hy },
{ have : 1 * x ∈ (1 * I) := mul_mem_mul one_mem_one h,
rwa [one_mul] at this }
end,
mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx
(λ x hx y hy, by simp [mem_zero_iff.mp hy])
rfl
(λ x y hx hy, by simp [hx, hy])
(λ r x hx, by simp [hx])),
zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx
(λ x hx y hy, by simp [mem_zero_iff.mp hx])
rfl
(λ x y hx hy, by simp [hx, hy])
(λ r x hx, by simp [hx])),
left_distrib := λ I J K, ext (mul_add _ _ _),
right_distrib := λ I J K, ext (add_mul _ _ _),
..fractional_ideal.has_zero,
..fractional_ideal.has_add,
..fractional_ideal.has_one,
..fractional_ideal.has_mul }
section order
lemma add_le_add_left {I J : fractional_ideal f} (hIJ : I ≤ J) (J' : fractional_ideal f) :
J' + I ≤ J' + J :=
sup_le_sup_left hIJ J'
lemma mul_le_mul_left {I J : fractional_ideal f} (hIJ : I ≤ J) (J' : fractional_ideal f) :
J' * I ≤ J' * J :=
mul_le.mpr (λ k hk j hj, mul_mem_mul hk (hIJ hj))
lemma le_self_mul_self {I : fractional_ideal f} (hI: 1 ≤ I) : I ≤ I * I :=
begin
convert mul_left_mono I hI,
exact (mul_one I).symm
end
lemma mul_self_le_self {I : fractional_ideal f} (hI: I ≤ 1) : I * I ≤ I :=
begin
convert mul_left_mono I hI,
exact (mul_one I).symm
end
lemma coe_ideal_le_one {I : ideal R} : (I : fractional_ideal f) ≤ 1 :=
λ x hx, let ⟨y, _, hy⟩ := fractional_ideal.mem_coe_ideal.mp hx
in fractional_ideal.mem_one_iff.mpr ⟨y, hy⟩
lemma le_one_iff_exists_coe_ideal {J : fractional_ideal f} :
J ≤ (1 : fractional_ideal f) ↔ ∃ (I : ideal R), ↑I = J :=
begin
split,
{ intro hJ,
refine ⟨⟨{x : R | f.to_map x ∈ J}, _, _, _⟩, _⟩,
{ rw [mem_set_of_eq, ring_hom.map_zero],
exact J.val.zero_mem },
{ intros a b ha hb,
rw [mem_set_of_eq, ring_hom.map_add],
exact J.val.add_mem ha hb },
{ intros c x hx,
rw [smul_eq_mul, mem_set_of_eq, ring_hom.map_mul],
exact J.val.smul_mem c hx },
{ ext x,
split,
{ rintros ⟨y, hy, eq_y⟩,
rwa ← eq_y },
{ intro hx,
obtain ⟨y, eq_x⟩ := fractional_ideal.mem_one_iff.mp (hJ hx),
rw ← eq_x at *,
exact ⟨y, hx, rfl⟩ } } },
{ rintro ⟨I, hI⟩,
rw ← hI,
apply coe_ideal_le_one },
end
end order
variables {P' : Type*} [comm_ring P'] {f' : localization_map S P'}
variables {P'' : Type*} [comm_ring P''] {f'' : localization_map S P''}
lemma fractional_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) :
is_fractional f' (submodule.map g.to_linear_map I.1) :=
begin
rcases I with ⟨I, a, a_nonzero, hI⟩,
use [a, a_nonzero],
intros b hb,
obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb,
obtain ⟨x, hx⟩ := hI b' b'_mem,
use x,
erw [←g.commutes, hx, g.map_smul, hb'],
refl
end
/-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/
def map (g : f.codomain →ₐ[R] f'.codomain) :
fractional_ideal f → fractional_ideal f' :=
λ I, ⟨submodule.map g.to_linear_map I.1, fractional_map g I⟩
@[simp, norm_cast] lemma coe_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) :
↑(map g I) = submodule.map g.to_linear_map I := rfl
@[simp] lemma mem_map {I : fractional_ideal f} {g : f.codomain →ₐ[R] f'.codomain}
{y : f'.codomain} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y :=
submodule.mem_map
variables (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain)
@[simp] lemma map_id : I.map (alg_hom.id _ _) = I :=
ext (submodule.map_id I.1)
@[simp] lemma map_comp (g' : f'.codomain →ₐ[R] f''.codomain) :
I.map (g'.comp g) = (I.map g).map g' :=
ext (submodule.map_comp g.to_linear_map g'.to_linear_map I.1)
@[simp, norm_cast] lemma map_coe_ideal (I : ideal R) :
(I : fractional_ideal f).map g = I :=
begin
ext x,
simp only [coe_coe_ideal, mem_coe_submodule],
split,
{ rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩,
exact ⟨y, hy, (g.commutes y).symm⟩ },
{ rintro ⟨y, hy, rfl⟩,
exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ },
end
@[simp] lemma map_one :
(1 : fractional_ideal f).map g = 1 :=
map_coe_ideal g 1
@[simp] lemma map_zero :
(0 : fractional_ideal f).map g = 0 :=
map_coe_ideal g 0
@[simp] lemma map_add : (I + J).map g = I.map g + J.map g :=
ext (submodule.map_sup _ _ _)
@[simp] lemma map_mul : (I * J).map g = I.map g * J.map g :=
ext (submodule.map_mul _ _ _)
@[simp] lemma map_map_symm (g : f.codomain ≃ₐ[R] f'.codomain) :
(I.map (g : f.codomain →ₐ[R] f'.codomain)).map (g.symm : f'.codomain →ₐ[R] f.codomain) = I :=
by rw [←map_comp, g.symm_comp, map_id]
@[simp] lemma map_symm_map (I : fractional_ideal f') (g : f.codomain ≃ₐ[R] f'.codomain) :
(I.map (g.symm : f'.codomain →ₐ[R] f.codomain)).map (g : f.codomain →ₐ[R] f'.codomain) = I :=
by rw [←map_comp, g.comp_symm, map_id]
/-- If `g` is an equivalence, `map g` is an isomorphism -/
def map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) :
fractional_ideal f ≃+* fractional_ideal f' :=
{ to_fun := map g,
inv_fun := map g.symm,
map_add' := λ I J, map_add I J _,
map_mul' := λ I J, map_mul I J _,
left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] },
right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } }
@[simp] lemma coe_fun_map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) :
⇑(map_equiv g) = map g :=
rfl
@[simp] lemma map_equiv_apply (g : f.codomain ≃ₐ[R] f'.codomain) (I : fractional_ideal f) :
map_equiv g I = map ↑g I := rfl
@[simp] lemma map_equiv_symm (g : f.codomain ≃ₐ[R] f'.codomain) :
(map_equiv g).symm = map_equiv g.symm := rfl
@[simp] lemma map_equiv_refl :
map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal f) :=
ring_equiv.ext (λ x, by simp)
lemma is_fractional_span_iff {s : set f.codomain} :
is_fractional f (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → f.is_integer (f.to_map a * b) :=
⟨ λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩,
λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb
h
(by { rw mul_zero, exact f.is_integer_zero })
(λ x y hx hy, by { rw mul_add, exact is_integer_add hx hy })
(λ s x hx, by { rw algebra.mul_smul_comm, exact is_integer_smul hx }) ⟩ ⟩
lemma is_fractional_of_fg {I : submodule R f.codomain} (hI : I.fg) :
is_fractional f I :=
begin
rcases hI with ⟨I, rfl⟩,
rcases localization_map.exist_integer_multiples_of_finset f I with ⟨⟨s, hs1⟩, hs⟩,
rw is_fractional_span_iff,
exact ⟨s, hs1, hs⟩,
end
/-- `canonical_equiv f f'` is the canonical equivalence between the fractional
ideals in `f.codomain` and in `f'.codomain` -/
@[irreducible]
noncomputable def canonical_equiv (f : localization_map S P) (f' : localization_map S P') :
fractional_ideal f ≃+* fractional_ideal f' :=
map_equiv
{ commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _ _,
..ring_equiv_of_ring_equiv f f' (ring_equiv.refl R)
(by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) }
@[simp] lemma mem_canonical_equiv_apply {I : fractional_ideal f} {x : f'.codomain} :
x ∈ canonical_equiv f f' I ↔
∃ y ∈ I, @localization_map.map _ _ _ _ _ _ _ f (ring_hom.id _) _ (λ ⟨y, hy⟩, hy) _ _ f' y = x :=
begin
rw [canonical_equiv, map_equiv_apply, mem_map],
exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩
end
@[simp] lemma canonical_equiv_symm (f : localization_map S P) (f' : localization_map S P') :
(canonical_equiv f f').symm = canonical_equiv f' f :=
ring_equiv.ext $ λ I, fractional_ideal.ext_iff.mp $ λ x,
by { erw [mem_canonical_equiv_apply, canonical_equiv, map_equiv_symm, map_equiv, mem_map],
exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ }
@[simp] lemma canonical_equiv_flip (f : localization_map S P) (f' : localization_map S P') (I) :
canonical_equiv f f' (canonical_equiv f' f I) = I :=
by rw [←canonical_equiv_symm, ring_equiv.symm_apply_apply]
end semiring
section fraction_map
/-!
### `fraction_map` section
This section concerns fractional ideals in the field of fractions,
i.e. the type `fractional_ideal g` when `g` is a `fraction_map R K`.
-/
variables {K K' : Type*} [field K] [field K'] {g : fraction_map R K} {g' : fraction_map R K'}
variables {I J : fractional_ideal g} (h : g.codomain →ₐ[R] g'.codomain)
/-- Nonzero fractional ideals contain a nonzero integer. -/
lemma exists_ne_zero_mem_is_integer [nontrivial R] (hI : I ≠ 0) :
∃ x ≠ (0 : R), g.to_map x ∈ I :=
begin
obtain ⟨y, y_mem, y_not_mem⟩ := submodule.exists_of_lt (bot_lt_iff_ne_bot.mpr hI),
have y_ne_zero : y ≠ 0 := by simpa using y_not_mem,
obtain ⟨z, ⟨x, hx⟩⟩ := g.exists_integer_multiple y,
refine ⟨x, _, _⟩,
{ rw [ne.def, ← g.to_map_eq_zero_iff, hx],
exact mul_ne_zero (g.to_map_ne_zero_of_mem_non_zero_divisors _) y_ne_zero },
{ rw hx,
exact smul_mem _ _ y_mem }
end
lemma map_ne_zero [nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 :=
begin
obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_is_integer hI,
contrapose! x_ne_zero with map_eq_zero,
refine g'.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr _)),
exact ⟨g.to_map x, hx, h.commutes x⟩,
end
@[simp] lemma map_eq_zero_iff [nontrivial R] : I.map h = 0 ↔ I = 0 :=
⟨imp_of_not_imp_not _ _ (map_ne_zero _),
λ hI, hI.symm ▸ map_zero h⟩
end fraction_map
section quotient
/-!
### `quotient` section
This section defines the ideal quotient of fractional ideals.
In this section we need that each non-zero `y : R` has an inverse in
the localization, i.e. that the localization is a field. We satisfy this
assumption by taking `S = non_zero_divisors R`, `R`'s localization at which
is a field because `R` is a domain.
-/
open_locale classical
variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] {g : fraction_map R₁ K}
instance : nontrivial (fractional_ideal g) :=
⟨⟨0, 1, λ h,
have this : (1 : K) ∈ (0 : fractional_ideal g) :=
by rw ←g.to_map.map_one; convert coe_mem_one _,
one_ne_zero (mem_zero_iff.mp this) ⟩⟩
lemma fractional_div_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) :
is_fractional g (I.1 / J.1) :=
begin
rcases I with ⟨I, aI, haI, hI⟩,
rcases J with ⟨J, aJ, haJ, hJ⟩,
obtain ⟨y, mem_J, not_mem_zero⟩ := exists_of_lt (bot_lt_iff_ne_bot.mpr h),
obtain ⟨y', hy'⟩ := hJ y mem_J,
use (aI * y'),
split,
{ apply (non_zero_divisors R₁).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _),
intro y'_eq_zero,
have : g.to_map aJ * y = 0 := by rw [←hy', y'_eq_zero, g.to_map.map_zero],
obtain aJ_zero | y_zero := mul_eq_zero.mp this,
{ have : aJ = 0 := g.to_map.injective_iff.1 g.injective _ aJ_zero,
have : aJ ≠ 0 := mem_non_zero_divisors_iff_ne_zero.mp haJ,
contradiction },
{ exact not_mem_zero (mem_zero_iff.mpr y_zero) } },
intros b hb,
rw [g.to_map.map_mul, mul_assoc, mul_comm _ b, hy'],
exact hI _ (hb _ (submodule.smul_mem _ aJ mem_J)),
end
noncomputable instance fractional_ideal_has_div :
has_div (fractional_ideal g) :=
⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩
variables {I J : fractional_ideal g} [ J ≠ 0 ]
noncomputable instance : has_inv (fractional_ideal g) := ⟨λ I, 1 / I⟩
lemma inv_eq {I : fractional_ideal g} : I⁻¹ = 1 / I := rfl
@[simp] lemma div_zero {I : fractional_ideal g} :
I / 0 = 0 :=
dif_pos rfl
lemma div_nonzero {I J : fractional_ideal g} (h : J ≠ 0) :
(I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ :=
dif_neg h
lemma inv_zero : (0 : fractional_ideal g)⁻¹ = 0 := div_zero
lemma inv_nonzero {I : fractional_ideal g} (h : I ≠ 0) :
I⁻¹ = ⟨(1 : fractional_ideal g) / I, fractional_div_of_nonzero h⟩ :=
div_nonzero h
@[simp] lemma coe_div {I J : fractional_ideal g} (hJ : J ≠ 0) :
(↑(I / J) : submodule R₁ g.codomain) = ↑I / (↑J : submodule R₁ g.codomain) :=
begin
unfold has_div.div,
simp only [dif_neg hJ, coe_mk, val_eq_coe],
end
lemma mem_div_iff_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) {x} :
x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I :=
by { rw div_nonzero h, exact submodule.mem_div_iff_forall_mul_mem }
lemma mul_one_div_le_one {I : fractional_ideal g} : I * (1 / I) ≤ 1 :=
begin
by_cases hI : I = 0,
{ rw [hI, div_zero, mul_zero],
exact zero_le 1 },
{ rw [← coe_le_coe, coe_mul, coe_div hI, coe_one],
apply submodule.mul_one_div_le_one },
end
lemma le_self_mul_one_div {I : fractional_ideal g} (hI : I ≤ (1 : fractional_ideal g)) :
I ≤ I * (1 / I) :=
begin
by_cases hI_nz : I = 0,
{ rw [hI_nz, div_zero, mul_zero], exact zero_le 0 },
{ rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one],
rw [← coe_le_coe, coe_one] at hI,
exact submodule.le_self_mul_one_div hI },
end
lemma le_div_iff_of_nonzero {I J J' : fractional_ideal g} (hJ' : J' ≠ 0) :
I ≤ J / J' ↔ ∀ (x ∈ I) (y ∈ J'), x * y ∈ J :=
⟨ λ h x hx, (mem_div_iff_of_nonzero hJ').mp (h hx),
λ h x hx, (mem_div_iff_of_nonzero hJ').mpr (h x hx) ⟩
lemma le_div_iff_mul_le {I J J' : fractional_ideal g} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ I * J' ≤ J :=
begin
rw div_nonzero hJ',
convert submodule.le_div_iff_mul_le using 1,
rw [val_eq_coe, val_eq_coe, ←coe_mul],
refl,
end
lemma coe_inv_of_nonzero {I : fractional_ideal g} (h : I ≠ 0) :
(↑I⁻¹ : submodule R₁ g.codomain) = g.coe_submodule 1 / I :=
by { rw inv_nonzero h, refl }
@[simp] lemma div_one {I : fractional_ideal g} : I / 1 = I :=
begin
rw [div_nonzero (@one_ne_zero (fractional_ideal g) _ _)],
ext,
split; intro h,
{ convert mem_div_iff_forall_mul_mem.mp h 1
(g.to_map.map_one ▸ coe_mem_one 1), simp },
{ apply mem_div_iff_forall_mul_mem.mpr,
rintros y ⟨y', _, y_eq_y'⟩,
rw mul_comm,
convert submodule.smul_mem _ y' h,
rw ←y_eq_y',
refl }
end
lemma ne_zero_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : I ≠ 0 :=
λ hI, @zero_ne_one (fractional_ideal g) _ _ (by { convert h, simp [hI], })
/-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/
theorem right_inverse_eq (I J : fractional_ideal g) (h : I * J = 1) :
J = I⁻¹ :=
begin
have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h,
suffices h' : I * (1 / I) = 1,
{ exact (congr_arg units.inv $
@units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) },
apply le_antisymm,
{ apply mul_le.mpr _,
intros x hx y hy,
rw mul_comm,
exact (mem_div_iff_of_nonzero hI).mp hy x hx },
rw ← h,
apply mul_left_mono I,
apply (le_div_iff_of_nonzero hI).mpr _,
intros y hy x hx,
rw mul_comm,
exact mul_mem_mul hx hy
end
theorem mul_inv_cancel_iff {I : fractional_ideal g} :
I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 :=
⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa [←right_inverse_eq I J hJ]⟩
variables {K' : Type*} [field K'] {g' : fraction_map R₁ K'}
@[simp] lemma map_div (I J : fractional_ideal g) (h : g.codomain ≃ₐ[R₁] g'.codomain) :
(I / J).map (h : g.codomain →ₐ[R₁] g'.codomain) = I.map h / J.map h :=
begin
by_cases H : J = 0,
{ rw [H, div_zero, map_zero, div_zero] },
{ ext x,
simp [div_nonzero H, div_nonzero (map_ne_zero _ H), submodule.map_div] }
end
@[simp] lemma map_inv (I : fractional_ideal g) (h : g.codomain ≃ₐ[R₁] g'.codomain) :
(I⁻¹).map (h : g.codomain →ₐ[R₁] g'.codomain) = (I.map h)⁻¹ :=
by rw [inv_eq, map_div, map_one, inv_eq]
end quotient
section principal_ideal_ring
variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] {g : fraction_map R₁ K}
open_locale classical
open submodule submodule.is_principal
lemma is_fractional_span_singleton (x : f.codomain) : is_fractional f (span R {x}) :=
let ⟨a, ha⟩ := f.exists_integer_multiple x in
is_fractional_span_iff.mpr ⟨ a.1, a.2, λ x hx, (mem_singleton_iff.mp hx).symm ▸ ha⟩
/-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/
@[irreducible]
def span_singleton (x : f.codomain) : fractional_ideal f :=
⟨span R {x}, is_fractional_span_singleton x⟩
local attribute [semireducible] span_singleton
@[simp] lemma coe_span_singleton (x : f.codomain) :
(span_singleton x : submodule R f.codomain) = span R {x} := rfl
@[simp] lemma mem_span_singleton {x y : f.codomain} :
x ∈ span_singleton y ↔ ∃ (z : R), z • y = x :=
submodule.mem_span_singleton
lemma mem_span_singleton_self (x : f.codomain) :
x ∈ span_singleton x :=
mem_span_singleton.mpr ⟨1, one_smul _ _⟩
lemma eq_span_singleton_of_principal (I : fractional_ideal f)
[is_principal (I : submodule R f.codomain)] :
I = span_singleton (generator (I : submodule R f.codomain)) :=
ext (span_singleton_generator I.1).symm
lemma is_principal_iff (I : fractional_ideal f) :
is_principal (I : submodule R f.codomain) ↔ ∃ x, I = span_singleton x :=
⟨λ h, ⟨@generator _ _ _ _ _ I.1 h, @eq_span_singleton_of_principal _ _ _ _ _ _ I h⟩,
λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton x)⟩ } ⟩
@[simp] lemma span_singleton_zero : span_singleton (0 : f.codomain) = 0 :=
by { ext, simp [submodule.mem_span_singleton, eq_comm] }
lemma span_singleton_eq_zero_iff {y : f.codomain} : span_singleton y = 0 ↔ y = 0 :=
⟨λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y),
λ h, by simp [h] ⟩
lemma span_singleton_ne_zero_iff {y : f.codomain} : span_singleton y ≠ 0 ↔ y ≠ 0 :=
not_congr span_singleton_eq_zero_iff
@[simp] lemma span_singleton_one : span_singleton (1 : f.codomain) = 1 :=
begin
ext,
refine mem_span_singleton.trans ((exists_congr _).trans mem_one_iff.symm),
intro x',
refine eq.congr (mul_one _) rfl,
end
@[simp]
lemma span_singleton_mul_span_singleton (x y : f.codomain) :
span_singleton x * span_singleton y = span_singleton (x * y) :=
begin
ext,
simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul]
end
@[simp]
lemma coe_ideal_span_singleton (x : R) :
(↑(span R {x} : ideal R) : fractional_ideal f) = span_singleton (f.to_map x) :=
begin
ext y,
refine mem_coe_ideal.trans (iff.trans _ mem_span_singleton.symm),
split,
{ rintros ⟨y', hy', rfl⟩,
obtain ⟨x', rfl⟩ := submodule.mem_span_singleton.mp hy',
use x',
rw [smul_eq_mul, f.to_map.map_mul],
refl },
{ rintros ⟨y', rfl⟩,
exact ⟨y' * x, submodule.mem_span_singleton.mpr ⟨y', rfl⟩, f.to_map.map_mul _ _⟩ }
end
@[simp]
lemma canonical_equiv_span_singleton (f : localization_map S P) {P'} [comm_ring P']
(f' : localization_map S P') (x : f.codomain) :
canonical_equiv f f' (span_singleton x) =
span_singleton (f.map (show ∀ (y : S), ring_hom.id _ y.1 ∈ S, from λ y, y.2) f' x) :=
begin
apply ext_iff.mp,
intro y,
split; intro h,
{ apply mem_span_singleton.mpr,
obtain ⟨x', hx', rfl⟩ := mem_canonical_equiv_apply.mp h,
obtain ⟨z, rfl⟩ := mem_span_singleton.mp hx',
use z,
rw localization_map.map_smul,
refl },
{ apply mem_canonical_equiv_apply.mpr,
obtain ⟨z, rfl⟩ := mem_span_singleton.mp h,
use f.to_map z * x,
use mem_span_singleton.mpr ⟨z, rfl⟩,
rw [ring_hom.map_mul, localization_map.map_eq],
refl }
end
lemma mem_singleton_mul {x y : f.codomain} {I : fractional_ideal f} :
y ∈ span_singleton x * I ↔ ∃ y' ∈ I, y = x * y' :=
begin
split,
{ intro h,
apply fractional_ideal.mul_induction_on h,
{ intros x' hx' y' hy',
obtain ⟨a, ha⟩ := mem_span_singleton.mp hx',
use [a • y', I.1.smul_mem a hy'],
rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] },
{ exact ⟨0, I.1.zero_mem, (mul_zero x).symm⟩ },
{ rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩,
exact ⟨y + y', I.1.add_mem hy hy', (mul_add _ _ _).symm⟩ },
{ rintros r _ ⟨y', hy', rfl⟩,
exact ⟨r • y', I.1.smul_mem r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } },
{ rintros ⟨y', hy', rfl⟩,
exact mul_mem_mul (mem_span_singleton.mpr ⟨1, one_smul _ _⟩) hy' }
end
lemma mul_generator_self_inv (I : fractional_ideal g)
[submodule.is_principal (I : submodule R₁ g.codomain)] (h : I ≠ 0) :
I * span_singleton (generator (I : submodule R₁ g.codomain))⁻¹ = 1 :=
begin
-- Rewrite only the `I` that appears alone.
conv_lhs { congr, rw eq_span_singleton_of_principal I },
rw [span_singleton_mul_span_singleton, mul_inv_cancel, span_singleton_one],
intro generator_I_eq_zero,
apply h,
rw [eq_span_singleton_of_principal I, generator_I_eq_zero, span_singleton_zero]
end
lemma one_div_span_singleton (x : g.codomain) :
1 / span_singleton x = span_singleton (x⁻¹) :=
if h : x = 0 then by simp [h] else (right_inverse_eq _ _ (by simp [h])).symm
@[simp]
lemma span_singleton_inv (x : g.codomain) :
(span_singleton x)⁻¹ = span_singleton (x⁻¹) :=
one_div_span_singleton x
lemma invertible_of_principal (I : fractional_ideal g)
[submodule.is_principal (I : submodule R₁ g.codomain)] (h : I ≠ 0) :
I * I⁻¹ = 1 :=
mul_inv_cancel_iff.mpr
⟨span_singleton (generator (I : submodule R₁ g.codomain))⁻¹, mul_generator_self_inv I h⟩
lemma invertible_iff_generator_nonzero (I : fractional_ideal g)
[submodule.is_principal (I : submodule R₁ g.codomain)] :
I * I⁻¹ = 1 ↔ generator (I : submodule R₁ g.codomain) ≠ 0 :=
begin
split,
{ intros hI hg,
apply ne_zero_of_mul_eq_one _ _ hI,
rw [eq_span_singleton_of_principal I, hg, span_singleton_zero] },
{ intro hg,
apply invertible_of_principal,
rw [eq_span_singleton_of_principal I],
intro hI,
have := mem_span_singleton_self (generator (I : submodule R₁ g.codomain)),
rw [hI, mem_zero_iff] at this,
contradiction }
end
lemma is_principal_inv (I : fractional_ideal g)
[submodule.is_principal (I : submodule R₁ g.codomain)] (h : I ≠ 0) :
submodule.is_principal (I⁻¹).1 :=
I⁻¹.is_principal_iff.mpr ⟨_, (right_inverse_eq _ _ (mul_generator_self_inv I h)).symm⟩
@[simp]
lemma div_span_singleton (J : fractional_ideal g) (d : g.codomain) :
J / span_singleton d = span_singleton (d⁻¹) * J :=
begin
rw ← one_div_span_singleton,
by_cases hd : d = 0,
{ simp only [hd, span_singleton_zero, div_zero, zero_mul] },
have h_spand : span_singleton d ≠ 0 := mt span_singleton_eq_zero_iff.mp hd,
apply le_antisymm,
{ intros x hx,
rw [val_eq_coe, coe_div h_spand, submodule.mem_div_iff_forall_mul_mem] at hx,
specialize hx d (mem_span_singleton_self d),
have h_xd : x = d⁻¹ * (x * d), { field_simp [hd] },
rw [val_eq_coe, coe_mul, one_div_span_singleton, h_xd],
exact submodule.mul_mem_mul (mem_span_singleton_self _) hx },
{ rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_span_singleton,
span_singleton_mul_span_singleton, inv_mul_cancel hd, span_singleton_one, mul_one],
exact le_refl J },
end
lemma exists_eq_span_singleton_mul (I : fractional_ideal g) :
∃ (a : R₁) (aI : ideal R₁), a ≠ 0 ∧ I = span_singleton (g.to_map a)⁻¹ * aI :=
begin
obtain ⟨a_inv, nonzero, ha⟩ := I.2,
have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero,
have map_a_nonzero := mt g.to_map_eq_zero_iff.mp nonzero,
use a_inv,
use (span_singleton (g.to_map a_inv) * I).1.comap g.lin_coe,
split, exact nonzero,
ext,
refine iff.trans _ mem_singleton_mul.symm,
split,
{ intro hx,
obtain ⟨x', hx'⟩ := ha x hx,
refine ⟨g.to_map x', mem_coe_ideal.mpr ⟨x', (mem_singleton_mul.mpr ⟨x, hx, hx'⟩), rfl⟩, _⟩,
erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] },
{ rintros ⟨y, hy, rfl⟩,
obtain ⟨x', hx', rfl⟩ := mem_coe_ideal.mp hy,
obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx',
rw lin_coe_apply at hx',
erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul],
exact hy' }
end
instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] {f : fraction_map R K}
(I : fractional_ideal f) : (I : submodule R f.codomain).is_principal :=
begin
obtain ⟨a, aI, -, ha⟩ := exists_eq_span_singleton_mul I,
use (f.to_map a)⁻¹ * f.to_map (generator aI),
suffices : I = span_singleton ((f.to_map a)⁻¹ * f.to_map (generator aI)),
{ exact congr_arg subtype.val this },
conv_lhs { rw [ha, ←span_singleton_generator aI] },
rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton]
end
end principal_ideal_ring
variables {R₁ : Type*} [integral_domain R₁]
variables {K : Type*} [field K] {g : fraction_map R₁ K}
local attribute [instance] classical.prop_decidable
lemma is_noetherian_zero : is_noetherian R₁ (0 : fractional_ideal g) :=
is_noetherian_submodule.mpr (λ I (hI : I ≤ (0 : fractional_ideal g)),
by { rw coe_zero at hI, rw le_bot_iff.mp hI, exact fg_bot })
lemma is_noetherian_iff {I : fractional_ideal g} :
is_noetherian R₁ I ↔ ∀ J ≤ I, (J : submodule R₁ g.codomain).fg :=
is_noetherian_submodule.trans ⟨λ h J hJ, h _ hJ, λ h J hJ, h ⟨J, is_fractional_of_le hJ⟩ hJ⟩
lemma is_noetherian_coe_to_fractional_ideal [is_noetherian_ring R₁] (I : ideal R₁) :
is_noetherian R₁ (I : fractional_ideal g) :=
begin
rw is_noetherian_iff,
intros J hJ,
obtain ⟨J, rfl⟩ := le_one_iff_exists_coe_ideal.mp (le_trans hJ coe_ideal_le_one),
exact fg_map (is_noetherian.noetherian J),
end
lemma is_noetherian_span_singleton_to_map_inv_mul (x : R₁) {I : fractional_ideal g}
(hI : is_noetherian R₁ I) :
is_noetherian R₁ (span_singleton (g.to_map x)⁻¹ * I : fractional_ideal g) :=
begin
by_cases hx : x = 0,
{ rw [hx, g.to_map.map_zero, _root_.inv_zero, span_singleton_zero, zero_mul],
exact is_noetherian_zero },
have h_gx : g.to_map x ≠ 0,
from mt (g.to_map.injective_iff.mp (fraction_map.injective g) x) hx,
have h_spanx : span_singleton (g.to_map x) ≠ (0 : fractional_ideal g),
from span_singleton_ne_zero_iff.mpr h_gx,
rw is_noetherian_iff at ⊢ hI,
intros J hJ,
rw [← div_span_singleton, le_div_iff_mul_le h_spanx] at hJ,
obtain ⟨s, hs⟩ := hI _ hJ,
use s * {(g.to_map x)⁻¹},
rw [finset.coe_mul, finset.coe_singleton, ← span_mul_span, hs, ← coe_span_singleton, ← coe_mul,
mul_assoc, span_singleton_mul_span_singleton, mul_inv_cancel h_gx,
span_singleton_one, mul_one],
end
/-- Every fractional ideal of a noetherian integral domain is noetherian. -/
lemma is_noetherian [is_noetherian_ring R₁] (I : fractional_ideal g) : is_noetherian R₁ I :=
begin
obtain ⟨d, J, h_nzd, rfl⟩ := exists_eq_span_singleton_mul I,
apply is_noetherian_span_singleton_to_map_inv_mul,
apply is_noetherian_coe_to_fractional_ideal,
end
end fractional_ideal
end ring
|
b1cf3a8500aecd56a13e7d8aaa8ec8ed487301d6 | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /tests/lean/run/indbug2.lean | 1dce9422fdc43c7ed19ee77e46d440ca194e1cb0 | [
"Apache-2.0"
] | permissive | respu/lean | 6582d19a2f2838a28ecd2b3c6f81c32d07b5341d | 8c76419c60b63d0d9f7bc04ebb0b99812d0ec654 | refs/heads/master | 1,610,882,451,231 | 1,427,747,084,000 | 1,427,747,429,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 196 | lean | set_option pp.implicit true
set_option pp.universes true
context
parameter {A : Type}
definition foo : A → A → Type := (λ x y, Type)
inductive bar {a b : A} (f : foo a b) :=
bar2 : bar f
end
|
678f9a73eaa5fdaa59166dad7817dac9ce80b4a6 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Lean/Elab/Deriving/DecEq.lean | 676824da7f5977c84b12c8a99242574e257c112c | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 4,982 | 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.Meta.Transform
import Lean.Meta.Inductive
import Lean.Elab.Deriving.Basic
import Lean.Elab.Deriving.Util
namespace Lean.Elab.Deriving.DecEq
open Lean.Parser.Term
open Meta
def mkDecEqHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do
mkHeader ctx `DecidableEq 2 indVal
def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) (argNames : Array Name) : TermElabM Syntax := do
let discrs ← mkDiscrs header indVal
let alts ← mkAlts
`(match $[$discrs],* with $alts:matchAlt*)
where
mkSameCtorRhs : List (Syntax × Syntax × Bool) → TermElabM Syntax
| [] => `(isTrue rfl)
| (a, b, recField) :: todo => withFreshMacroScope do
let rhs ←
`(if h : $a = $b then
by subst h; exact $(← mkSameCtorRhs todo):term
else
isFalse (by intro n; injection n; apply h _; assumption))
if recField then
-- add local instance for `a = b` using the function being defined `auxFunName`
`(let inst := $(mkIdent auxFunName) $a $b; $rhs)
else
return rhs
mkAlts : TermElabM (Array Syntax) := do
let mut alts := #[]
for ctorName₁ in indVal.ctors do
let ctorInfo ← getConstInfoCtor ctorName₁
for ctorName₂ in indVal.ctors do
let mut patterns := #[]
-- add `_` pattern for indices
for i in [:indVal.numIndices] do
patterns := patterns.push (← `(_))
if ctorName₁ == ctorName₂ then
let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do
let type ← Core.betaReduce type -- we 'beta-reduce' to eliminate "artificial" dependencies
let mut patterns := patterns
let mut ctorArgs1 := #[]
let mut ctorArgs2 := #[]
-- add `_` for inductive parameters, they are inaccessible
for i in [:indVal.numParams] do
ctorArgs1 := ctorArgs1.push (← `(_))
ctorArgs2 := ctorArgs2.push (← `(_))
let mut todo := #[]
for i in [:ctorInfo.numFields] do
let x := xs[indVal.numParams + i]
if type.containsFVar x.fvarId! then
-- If resulting type depends on this field, we don't need to compare
ctorArgs1 := ctorArgs1.push (← `(_))
ctorArgs2 := ctorArgs2.push (← `(_))
else
let a := mkIdent (← mkFreshUserName `a)
let b := mkIdent (← mkFreshUserName `b)
ctorArgs1 := ctorArgs1.push a
ctorArgs2 := ctorArgs2.push b
let recField := (← inferType x).isAppOf indVal.name
todo := todo.push (a, b, recField)
patterns := patterns.push (← `(@$(mkIdent ctorName₁):ident $ctorArgs1:term*))
patterns := patterns.push (← `(@$(mkIdent ctorName₁):ident $ctorArgs2:term*))
let rhs ← mkSameCtorRhs todo.toList
`(matchAltExpr| | $[$patterns:term],* => $rhs:term)
alts := alts.push alt
else if (← compatibleCtors ctorName₁ ctorName₂) then
patterns := patterns ++ #[(← `($(mkIdent ctorName₁) ..)), (← `($(mkIdent ctorName₂) ..))]
let rhs ← `(isFalse (by intro h; injection h))
alts ← alts.push (← `(matchAltExpr| | $[$patterns:term],* => $rhs:term))
return alts
def mkAuxFunction (ctx : Context) : TermElabM Syntax := do
let auxFunName ← ctx.auxFunNames[0]
let indVal ← ctx.typeInfos[0]
let header ← mkDecEqHeader ctx indVal
let mut body ← mkMatch ctx header indVal auxFunName header.argNames
let binders := header.binders
let type ← `(Decidable ($(mkIdent header.targetNames[0]) = $(mkIdent header.targetNames[1])))
`(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : $type:term := $body:term)
def mkDecEqCmds (indVal : InductiveVal) : TermElabM (Array Syntax) := do
let ctx ← mkContext "decEq" indVal.name
let cmds := #[← mkAuxFunction ctx] ++ (← mkInstanceCmds ctx `DecidableEq #[indVal.name] (useAnonCtor := false))
trace[Elab.Deriving.decEq] "\n{cmds}"
return cmds
open Command
def mkDecEqInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if declNames.size != 1 then
return false -- mutually inductive types are not supported yet
else
let indVal ← getConstInfoInduct declNames[0]
if indVal.isNested then
return false -- nested inductive types are not supported yet
else
let cmds ← liftTermElabM none <| mkDecEqCmds indVal
cmds.forM elabCommand
return true
builtin_initialize
registerBuiltinDerivingHandler `DecidableEq mkDecEqInstanceHandler
registerTraceClass `Elab.Deriving.decEq
end Lean.Elab.Deriving.DecEq
|
3e08d1c013c65e5df981dfcf8b3ceefd4a2d02c6 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/group/pointwise.lean | 82e55d4269208897dbdf01c983cc8a02e9fcc41e | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,767 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Alex J. Best
-/
import measure_theory.group.arithmetic
/-!
# Pointwise set operations on `measurable_set`s
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we prove several versions of the following fact: if `s` is a measurable set, then so is
`a • s`. Note that the pointwise product of two measurable sets need not be measurable, so there is
no `measurable_set.mul` etc.
-/
open_locale pointwise
open set
@[to_additive]
lemma measurable_set.const_smul {G α : Type*} [group G] [mul_action G α] [measurable_space G]
[measurable_space α] [has_measurable_smul G α] {s : set α} (hs : measurable_set s) (a : G) :
measurable_set (a • s) :=
begin
rw ← preimage_smul_inv,
exact measurable_const_smul _ hs
end
lemma measurable_set.const_smul_of_ne_zero {G₀ α : Type*} [group_with_zero G₀] [mul_action G₀ α]
[measurable_space G₀] [measurable_space α] [has_measurable_smul G₀ α] {s : set α}
(hs : measurable_set s) {a : G₀} (ha : a ≠ 0) :
measurable_set (a • s) :=
begin
rw ← preimage_smul_inv₀ ha,
exact measurable_const_smul _ hs
end
lemma measurable_set.const_smul₀ {G₀ α : Type*} [group_with_zero G₀] [has_zero α]
[mul_action_with_zero G₀ α] [measurable_space G₀] [measurable_space α] [has_measurable_smul G₀ α]
[measurable_singleton_class α] {s : set α} (hs : measurable_set s) (a : G₀) :
measurable_set (a • s) :=
begin
rcases eq_or_ne a 0 with (rfl|ha),
exacts [(subsingleton_zero_smul_set s).measurable_set, hs.const_smul_of_ne_zero ha]
end
|
ad84c99528c2d1de63491d166907cf34f61ef892 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/topology/uniform_space/uniform_embedding.lean | a1047efadb7c86d779c6f3919396a86af4af5767 | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 20,204 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Sébastien Gouëzel, Patrick Massot
Uniform embeddings of uniform spaces. Extension of uniform continuous functions.
-/
import topology.uniform_space.cauchy
import topology.uniform_space.separation
import topology.dense_embedding
open filter topological_space set classical
open_locale classical
open_locale uniformity topological_space
section
variables {α : Type*} {β : Type*} {γ : Type*}
[uniform_space α] [uniform_space β] [uniform_space γ]
universe u
structure uniform_inducing (f : α → β) : Prop :=
(comap_uniformity : comap (λx:α×α, (f x.1, f x.2)) (𝓤 β) = 𝓤 α)
lemma uniform_inducing.mk' {f : α → β} (h : ∀ s, s ∈ 𝓤 α ↔
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s) : uniform_inducing f :=
⟨by simp [eq_comm, filter.ext_iff, subset_def, h]⟩
lemma uniform_inducing.comp {g : β → γ} (hg : uniform_inducing g)
{f : α → β} (hf : uniform_inducing f) : uniform_inducing (g ∘ f) :=
⟨ by rw [show (λ (x : α × α), ((g ∘ f) x.1, (g ∘ f) x.2)) =
(λ y : β × β, (g y.1, g y.2)) ∘ (λ x : α × α, (f x.1, f x.2)), by ext ; simp,
← filter.comap_comap_comp, hg.1, hf.1]⟩
structure uniform_embedding (f : α → β) extends uniform_inducing f : Prop :=
(inj : function.injective f)
lemma uniform_embedding_subtype_val {p : α → Prop} :
uniform_embedding (subtype.val : subtype p → α) :=
{ comap_uniformity := rfl,
inj := subtype.val_injective }
lemma uniform_embedding_subtype_coe {p : α → Prop} :
uniform_embedding (coe : subtype p → α) :=
uniform_embedding_subtype_val
lemma uniform_embedding_set_inclusion {s t : set α} (hst : s ⊆ t) :
uniform_embedding (inclusion hst) :=
{ comap_uniformity :=
by { erw [uniformity_subtype, uniformity_subtype, comap_comap_comp], congr },
inj := inclusion_injective hst }
lemma uniform_embedding.comp {g : β → γ} (hg : uniform_embedding g)
{f : α → β} (hf : uniform_embedding f) : uniform_embedding (g ∘ f) :=
{ inj := hg.inj.comp hf.inj,
..hg.to_uniform_inducing.comp hf.to_uniform_inducing }
theorem uniform_embedding_def {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ 𝓤 α ↔
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s :=
begin
split,
{ rintro ⟨⟨h⟩, h'⟩,
rw [eq_comm, filter.ext_iff] at h,
simp [*, subset_def] },
{ rintro ⟨h, h'⟩,
refine uniform_embedding.mk ⟨_⟩ h,
rw [eq_comm, filter.ext_iff],
simp [*, subset_def] }
end
theorem uniform_embedding_def' {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ s, s ∈ 𝓤 α →
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s :=
by simp [uniform_embedding_def, uniform_continuous_def]; exact
⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩,
λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s,
λ ⟨t, tu, h⟩, sets_of_superset _ (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩
lemma uniform_inducing.uniform_continuous {f : α → β}
(hf : uniform_inducing f) : uniform_continuous f :=
by simp [uniform_continuous, hf.comap_uniformity.symm, tendsto_comap]
lemma uniform_inducing.uniform_continuous_iff {f : α → β} {g : β → γ} (hg : uniform_inducing g) :
uniform_continuous f ↔ uniform_continuous (g ∘ f) :=
by simp [uniform_continuous, tendsto]; rw [← hg.comap_uniformity, ← map_le_iff_le_comap, filter.map_map]
lemma uniform_inducing.inducing {f : α → β} (h : uniform_inducing f) : inducing f :=
begin
refine ⟨eq_of_nhds_eq_nhds $ assume a, _ ⟩,
rw [nhds_induced, nhds_eq_uniformity, nhds_eq_uniformity, ← h.comap_uniformity,
comap_lift'_eq, comap_lift'_eq2];
{ refl <|> exact monotone_preimage }
end
lemma uniform_inducing.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β']
{e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_inducing e₁) (h₂ : uniform_inducing e₂) :
uniform_inducing (λp:α×β, (e₁ p.1, e₂ p.2)) :=
⟨by simp [(∘), uniformity_prod, h₁.comap_uniformity.symm, h₂.comap_uniformity.symm,
comap_inf, comap_comap_comp]⟩
lemma uniform_inducing.dense_inducing {f : α → β} (h : uniform_inducing f) (hd : dense_range f) :
dense_inducing f :=
{ dense := hd,
induced := h.inducing.induced }
lemma uniform_embedding.embedding {f : α → β} (h : uniform_embedding f) : embedding f :=
{ induced := h.to_uniform_inducing.inducing.induced,
inj := h.inj }
lemma uniform_embedding.dense_embedding {f : α → β} (h : uniform_embedding f) (hd : dense_range f) :
dense_embedding f :=
{ dense := hd,
inj := h.inj,
induced := h.embedding.induced }
lemma closure_image_mem_nhds_of_uniform_inducing
{s : set (α×α)} {e : α → β} (b : β)
(he₁ : uniform_inducing e) (he₂ : dense_inducing e) (hs : s ∈ 𝓤 α) :
∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ 𝓝 b :=
have s ∈ comap (λp:α×α, (e p.1, e p.2)) (𝓤 β),
from he₁.comap_uniformity.symm ▸ hs,
let ⟨t₁, ht₁u, ht₁⟩ := this in
have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁,
let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in
let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in
have preimage e {b' | (b, b') ∈ t₂} ∈ comap e (𝓝 b),
from preimage_mem_comap $ mem_nhds_left b ht₂u,
let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := nonempty_of_mem_sets (he₂.comap_nhds_ne_bot) this in
have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ 𝓤 β →
({y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s}).nonempty,
from assume b' s' hb' hs',
have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ comap e (𝓝 b'),
from preimage_mem_comap $ mem_nhds_left b' $ inter_mem_sets hs' htu,
let ⟨a₂, ha₂s', ha₂t⟩ := nonempty_of_mem_sets (he₂.comap_nhds_ne_bot) this in
have (e a, e a₂) ∈ t₁,
from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t,
have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s},
from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩,
⟨_, this⟩,
have ∀b', (b, b') ∈ t → 𝓝 b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥,
begin
intros b' hb',
rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_ne_bot_iff],
exact assume s, this b' s hb',
exact monotone_inter monotone_preimage monotone_const
end,
have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}),
from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb',
⟨a, (𝓝 b).sets_of_superset (mem_nhds_left b htu) this⟩
lemma uniform_embedding_subtype_emb (p : α → Prop) {e : α → β} (ue : uniform_embedding e)
(de : dense_embedding e) : uniform_embedding (dense_embedding.subtype_emb p e) :=
{ comap_uniformity := by simp [comap_comap_comp, (∘), dense_embedding.subtype_emb,
uniformity_subtype, ue.comap_uniformity.symm],
inj := (de.subtype p).inj }
lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β']
{e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) :
uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) :=
{ inj := h₁.inj.prod h₂.inj,
..h₁.to_uniform_inducing.prod h₂.to_uniform_inducing }
lemma is_complete_of_complete_image {m : α → β} {s : set α} (hm : uniform_inducing m)
(hs : is_complete (m '' s)) : is_complete s :=
begin
intros f hf hfs,
rw le_principal_iff at hfs,
obtain ⟨_, ⟨x, hx, rfl⟩, hyf⟩ : ∃ y ∈ m '' s, map m f ≤ 𝓝 y,
from hs (f.map m) (cauchy_map hm.uniform_continuous hf)
(le_principal_iff.2 (image_mem_map hfs)),
rw [map_le_iff_le_comap, ← nhds_induced, ← hm.inducing.induced] at hyf,
exact ⟨x, hx, hyf⟩
end
/-- A set is complete iff its image under a uniform embedding is complete. -/
lemma is_complete_image_iff {m : α → β} {s : set α} (hm : uniform_embedding m) :
is_complete (m '' s) ↔ is_complete s :=
begin
refine ⟨is_complete_of_complete_image hm.to_uniform_inducing, λ c f hf fs, _⟩,
rw filter.le_principal_iff at fs,
let f' := comap m f,
have cf' : cauchy f',
{ have : comap m f ≠ ⊥,
{ refine comap_ne_bot (λt ht, _),
have A : t ∩ m '' s ∈ f := filter.inter_mem_sets ht fs,
obtain ⟨x, ⟨xt, ⟨y, ys, rfl⟩⟩⟩ : (t ∩ m '' s).nonempty,
from nonempty_of_mem_sets hf.1 A,
exact ⟨y, xt⟩ },
apply cauchy_comap _ hf this,
simp only [hm.comap_uniformity, le_refl] },
have : f' ≤ principal s := by simp [f']; exact
⟨m '' s, by simpa using fs, by simp [preimage_image_eq s hm.inj]⟩,
rcases c f' cf' this with ⟨x, xs, hx⟩,
existsi [m x, mem_image_of_mem m xs],
rw [(uniform_embedding.embedding hm).induced, nhds_induced] at hx,
calc f = map m f' : (map_comap $ filter.mem_sets_of_superset fs $ image_subset_range _ _).symm
... ≤ map m (comap m (𝓝 (m x))) : map_mono hx
... ≤ 𝓝 (m x) : map_comap_le
end
lemma complete_space_iff_is_complete_range {f : α → β} (hf : uniform_embedding f) :
complete_space α ↔ is_complete (range f) :=
by rw [complete_space_iff_is_complete_univ, ← is_complete_image_iff hf, image_univ]
lemma complete_space_congr {e : α ≃ β} (he : uniform_embedding e) :
complete_space α ↔ complete_space β :=
by rw [complete_space_iff_is_complete_range he, e.range_eq_univ,
complete_space_iff_is_complete_univ]
lemma complete_space_coe_iff_is_complete {s : set α} :
complete_space s ↔ is_complete s :=
(complete_space_iff_is_complete_range uniform_embedding_subtype_coe).trans $
by rw [range_coe_subtype]
lemma is_complete.complete_space_coe {s : set α} (hs : is_complete s) :
complete_space s :=
complete_space_coe_iff_is_complete.2 hs
lemma is_closed.complete_space_coe [complete_space α] {s : set α} (hs : is_closed s) :
complete_space s :=
(is_complete_of_is_closed hs).complete_space_coe
lemma complete_space_extension {m : β → α} (hm : uniform_inducing m) (dense : dense_range m)
(h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ 𝓝 x) : complete_space α :=
⟨assume (f : filter α), assume hf : cauchy f,
let
p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s},
g := (𝓤 α).lift (λs, f.lift' (p s))
in
have mp₀ : monotone p,
from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩,
have mp₁ : ∀{s}, monotone (p s),
from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩,
have f ≤ g, from
le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
le_principal_iff.mpr $
mem_sets_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩,
have g ≠ ⊥, from ne_bot_of_le_ne_bot hf.left this,
have comap m g ≠ ⊥, from comap_ne_bot $ assume t ht,
let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in
let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in
let ⟨x, (hx : x ∈ t'')⟩ := nonempty_of_mem_sets hf.left ht'' in
have h₀ : 𝓝 x ⊓ principal (range m) ≠ ⊥,
by simpa [dense_range, closure_eq_nhds] using dense x,
have h₁ : {y | (x, y) ∈ t'} ∈ 𝓝 x ⊓ principal (range m),
from @mem_inf_sets_of_left α (𝓝 x) (principal (range m)) _ $ mem_nhds_left x ht',
have h₂ : range m ∈ 𝓝 x ⊓ principal (range m),
from @mem_inf_sets_of_right α (𝓝 x) (principal (range m)) _ $ subset.refl _,
have {y | (x, y) ∈ t'} ∩ range m ∈ 𝓝 x ⊓ principal (range m),
from @inter_mem_sets α (𝓝 x ⊓ principal (range m)) _ _ h₁ h₂,
let ⟨y, xyt', b, b_eq⟩ := nonempty_of_mem_sets h₀ this in
⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩,
have cauchy g, from
⟨‹g ≠ ⊥›, assume 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 (preimage prod.swap s₁) t ∈ g,
from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht,
have hg₂ : p s₂ t ∈ g,
from mem_lift hs₂ $ @mem_lift' α α f _ t ht,
have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ filter.prod g g,
from @prod_mem_prod α α _ _ g g hg₁ hg₂,
(filter.prod g g).sets_of_superset hg
(assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩,
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.comap m g),
from cauchy_comap (le_of_eq hm.comap_uniformity) ‹cauchy g› (by assumption),
let ⟨x, (hx : map m (filter.comap m g) ≤ 𝓝 x)⟩ := h _ this in
have map m (filter.comap m g) ⊓ 𝓝 x ≠ ⊥,
from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx,
have g ⊓ 𝓝 x ≠ ⊥,
from ne_bot_of_le_ne_bot this (inf_le_inf_right _ (assume s hs, ⟨s, hs, subset.refl _⟩)),
⟨x, calc f ≤ g : by assumption
... ≤ 𝓝 x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩
lemma totally_bounded_preimage {f : α → β} {s : set β} (hf : uniform_embedding f)
(hs : totally_bounded s) : totally_bounded (f ⁻¹' s) :=
λ t ht, begin
rw ← hf.comap_uniformity at ht,
rcases mem_comap_sets.2 ht with ⟨t', ht', ts⟩,
rcases totally_bounded_iff_subset.1
(totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩,
refine ⟨f ⁻¹' c, finite_preimage (hf.inj.inj_on _) hfc, λ x h, _⟩,
have := hct (mem_image_of_mem f h), simp at this ⊢,
rcases this with ⟨z, zc, zt⟩,
rcases cs zc with ⟨y, yc, rfl⟩,
exact ⟨y, zc, ts (by exact zt)⟩
end
end
lemma uniform_embedding_comap {α : Type*} {β : Type*} {f : α → β} [u : uniform_space β]
(hf : function.injective f) : @uniform_embedding α β (uniform_space.comap f u) u f :=
@uniform_embedding.mk _ _ (uniform_space.comap f u) _ _
(@uniform_inducing.mk _ _ (uniform_space.comap f u) _ _ rfl) hf
section uniform_extension
variables {α : Type*} {β : Type*} {γ : Type*}
[uniform_space α] [uniform_space β] [uniform_space γ]
{e : β → α}
(h_e : uniform_inducing e)
(h_dense : dense_range e)
{f : β → γ}
(h_f : uniform_continuous f)
local notation `ψ` := (h_e.dense_inducing h_dense).extend f
lemma uniformly_extend_exists [complete_space γ] (a : α) :
∃c, tendsto f (comap e (𝓝 a)) (𝓝 c) :=
let de := (h_e.dense_inducing h_dense) in
have cauchy (𝓝 a), from cauchy_nhds,
have cauchy (comap e (𝓝 a)), from
cauchy_comap (le_of_eq h_e.comap_uniformity) this de.comap_nhds_ne_bot,
have cauchy (map f (comap e (𝓝 a))), from
cauchy_map h_f this,
complete_space.complete this
lemma uniform_extend_subtype [complete_space γ]
{p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α}
(hf : uniform_continuous (λx:subtype p, f x.val))
(he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e))
(hb : closure (e '' s) ∈ 𝓝 b) (hs : is_closed s) (hp : ∀x∈s, p x) :
∃c, tendsto f (comap e (𝓝 b)) (𝓝 c) :=
have de : dense_embedding e,
from he.dense_embedding hd,
have de' : dense_embedding (dense_embedding.subtype_emb p e),
by exact de.subtype p,
have ue' : uniform_embedding (dense_embedding.subtype_emb p e),
from uniform_embedding_subtype_emb _ he de,
have b ∈ closure (e '' {x | p x}),
from (closure_mono $ monotone_image $ hp) (mem_of_nhds hb),
let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (dense_embedding.subtype_emb p e) (𝓝 ⟨b, this⟩)) (𝓝 c))⟩ :=
uniformly_extend_exists ue'.to_uniform_inducing de'.dense hf _ in
begin
rw [nhds_subtype_eq_comap] at hc,
simp [comap_comap_comp] at hc,
change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (𝓝 b)) (𝓝 c)) at hc,
rw [←comap_comap_comp, tendsto_comap'_iff] at hc,
exact ⟨c, hc⟩,
exact ⟨_, hb, assume x,
begin
change e x ∈ (closure (e '' s)) → x ∈ range subtype.val,
rw [←closure_induced, closure_eq_nhds, mem_set_of_eq, (≠), nhds_induced, ← de.to_dense_inducing.nhds_eq_comap],
change x ∈ {x | 𝓝 x ⊓ principal s ≠ ⊥} → x ∈ range subtype.val,
rw [←closure_eq_nhds, closure_eq_of_is_closed hs],
exact assume hxs, ⟨⟨x, hp x hxs⟩, rfl⟩,
exact de.inj
end⟩
end
variables [separated γ]
lemma uniformly_extend_of_ind (b : β) : ψ (e b) = f b :=
dense_inducing.extend_e_eq _ b (continuous_iff_continuous_at.1 h_f.continuous b)
include h_f
lemma uniformly_extend_spec [complete_space γ] (a : α) :
tendsto f (comap e (𝓝 a)) (𝓝 (ψ a)) :=
let de := (h_e.dense_inducing h_dense) in
begin
by_cases ha : a ∈ range e,
{ rcases ha with ⟨b, rfl⟩,
rw [uniformly_extend_of_ind _ _ h_f, ← de.nhds_eq_comap],
exact h_f.continuous.tendsto _ },
{ simp only [dense_inducing.extend, dif_neg ha],
exact lim_spec (uniformly_extend_exists h_e h_dense h_f _) }
end
lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] : uniform_continuous ψ :=
assume d hd,
let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in
have h_pnt : ∀{a m}, m ∈ 𝓝 a → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s,
from assume a m hm,
have nb : map f (comap e (𝓝 a)) ≠ ⊥,
from map_ne_bot (h_e.dense_inducing h_dense).comap_nhds_ne_bot,
have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ map f (comap e (𝓝 a)),
from inter_mem_sets (image_mem_map $ preimage_mem_comap $ hm)
(uniformly_extend_spec h_e h_dense h_f _ (inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs))),
nonempty_of_mem_sets nb this,
have preimage (λp:β×β, (f p.1, f p.2)) s ∈ 𝓤 β,
from h_f hs,
have preimage (λp:β×β, (f p.1, f p.2)) s ∈ comap (λx:β×β, (e x.1, e x.2)) (𝓤 α),
by rwa [h_e.comap_uniformity.symm] at this,
let ⟨t, ht, ts⟩ := this in
show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ 𝓤 α,
from (𝓤 α).sets_of_superset (interior_mem_uniformity ht) $
assume ⟨x₁, x₂⟩ hx_t,
have 𝓝 (x₁, x₂) ≤ principal (interior t),
from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t,
have interior t ∈ filter.prod (𝓝 x₁) (𝓝 x₂),
by rwa [nhds_prod_eq, le_principal_iff] at this,
let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in
let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in
let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in
have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s,
from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm
... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset
... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts,
have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s,
from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) =
(λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq
... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : monotone_image this
... ⊆ s : image_subset_iff.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
|
106b43e7ce01c6ff9cdc4d4bcdb29a346e2a06f8 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/zorn_auto.lean | e2fbcfb42f68dca474759ea25426eb91e90b1ebc | [] | 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 | 7,366 | 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
Zorn's lemmas.
Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel).
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.set.lattice
import Mathlib.PostPort
universes u u_1 u_2
namespace Mathlib
namespace zorn
/-- A chain is a subset `c` satisfying
`x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ c`. -/
def chain {α : Type u} (r : α → α → Prop) (c : set α) :=
set.pairwise_on c fun (x y : α) => r x y ∨ r y x
theorem chain.total_of_refl {α : Type u} {r : α → α → Prop} [is_refl α r] {c : set α}
(H : chain r c) {x : α} {y : α} (hx : x ∈ c) (hy : y ∈ c) : r x y ∨ r y x :=
dite (x = y) (fun (e : x = y) => Or.inl (e ▸ refl x)) fun (e : ¬x = y) => H x hx y hy e
theorem chain.mono {α : Type u} {r : α → α → Prop} {c : set α} {c' : set α} :
c' ⊆ c → chain r c → chain r c' :=
set.pairwise_on.mono
theorem chain.directed_on {α : Type u} {r : α → α → Prop} [is_refl α r] {c : set α}
(H : chain r c) : directed_on r c :=
sorry
theorem chain_insert {α : Type u} {r : α → α → Prop} {c : set α} {a : α} (hc : chain r c)
(ha : ∀ (b : α), b ∈ c → b ≠ a → r a b ∨ r b a) : chain r (insert a c) :=
sorry
/-- `super_chain c₁ c₂` means that `c₂ is a chain that strictly includes `c₁`. -/
def super_chain {α : Type u} {r : α → α → Prop} (c₁ : set α) (c₂ : set α) := chain r c₂ ∧ c₁ ⊂ c₂
/-- A chain `c` is a maximal chain if there does not exists a chain strictly including `c`. -/
def is_max_chain {α : Type u} {r : α → α → Prop} (c : set α) :=
chain r c ∧ ¬∃ (c' : set α), super_chain c c'
/-- Given a set `c`, if there exists a chain `c'` strictly including `c`, then `succ_chain c`
is one of these chains. Otherwise it is `c`. -/
def succ_chain {α : Type u} {r : α → α → Prop} (c : set α) : set α :=
dite (∃ (c' : set α), chain r c ∧ super_chain c c')
(fun (h : ∃ (c' : set α), chain r c ∧ super_chain c c') => classical.some h)
fun (h : ¬∃ (c' : set α), chain r c ∧ super_chain c c') => c
theorem succ_spec {α : Type u} {r : α → α → Prop} {c : set α}
(h : ∃ (c' : set α), chain r c ∧ super_chain c c') : super_chain c (succ_chain c) :=
sorry
theorem chain_succ {α : Type u} {r : α → α → Prop} {c : set α} (hc : chain r c) :
chain r (succ_chain c) :=
sorry
theorem super_of_not_max {α : Type u} {r : α → α → Prop} {c : set α} (hc₁ : chain r c)
(hc₂ : ¬is_max_chain c) : super_chain c (succ_chain c) :=
sorry
theorem succ_increasing {α : Type u} {r : α → α → Prop} {c : set α} : c ⊆ succ_chain c := sorry
/-- Set of sets reachable from `∅` using `succ_chain` and `⋃₀`. -/
inductive chain_closure {α : Type u} {r : α → α → Prop} : set α → Prop where
| succ : ∀ {s : set α}, chain_closure s → chain_closure (succ_chain s)
| union : ∀ {s : set (set α)}, (∀ (a : set α), a ∈ s → chain_closure a) → chain_closure (⋃₀s)
theorem chain_closure_empty {α : Type u} {r : α → α → Prop} : chain_closure ∅ := sorry
theorem chain_closure_closure {α : Type u} {r : α → α → Prop} : chain_closure (⋃₀chain_closure) :=
chain_closure.union fun (s : set α) (hs : s ∈ chain_closure) => hs
theorem chain_closure_total {α : Type u} {r : α → α → Prop} {c₁ : set α} {c₂ : set α}
(hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ :=
(fun (this : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁) =>
or.imp_right (fun (this : succ_chain c₂ ⊆ c₁) => set.subset.trans succ_increasing this) this)
(chain_closure_succ_total_aux hc₁ hc₂
fun (c₃ : set α) (hc₃ : chain_closure c₃) => chain_closure_succ_total hc₃ hc₂)
theorem chain_closure_succ_fixpoint {α : Type u} {r : α → α → Prop} {c₁ : set α} {c₂ : set α}
(hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ :=
sorry
theorem chain_closure_succ_fixpoint_iff {α : Type u} {r : α → α → Prop} {c : set α}
(hc : chain_closure c) : succ_chain c = c ↔ c = ⋃₀chain_closure :=
sorry
theorem chain_chain_closure {α : Type u} {r : α → α → Prop} {c : set α} (hc : chain_closure c) :
chain r c :=
sorry
/-- `max_chain` is the union of all sets in the chain closure. -/
def max_chain {α : Type u} {r : α → α → Prop} : set α := ⋃₀chain_closure
/-- Hausdorff's maximality principle
There exists a maximal totally ordered subset of `α`.
Note that we do not require `α` to be partially ordered by `r`. -/
theorem max_chain_spec {α : Type u} {r : α → α → Prop} : is_max_chain max_chain := sorry
/-- Zorn's lemma
If every chain has an upper bound, then there is a maximal element -/
theorem exists_maximal_of_chains_bounded {α : Type u} {r : α → α → Prop}
(h : ∀ (c : set α), chain r c → ∃ (ub : α), ∀ (a : α), a ∈ c → r a ub)
(trans : ∀ {a b c : α}, r a b → r b c → r a c) : ∃ (m : α), ∀ (a : α), r m a → r a m :=
sorry
theorem zorn_partial_order {α : Type u} [partial_order α]
(h : ∀ (c : set α), chain LessEq c → ∃ (ub : α), ∀ (a : α), a ∈ c → a ≤ ub) :
∃ (m : α), ∀ (a : α), m ≤ a → a = m :=
sorry
theorem zorn_partial_order₀ {α : Type u} [partial_order α] (s : set α)
(ih :
∀ (c : set α) (H : c ⊆ s),
chain LessEq c →
∀ (y : α) (H : y ∈ c), ∃ (ub : α), ∃ (H : ub ∈ s), ∀ (z : α), z ∈ c → z ≤ ub)
(x : α) (hxs : x ∈ s) : ∃ (m : α), ∃ (H : m ∈ s), x ≤ m ∧ ∀ (z : α), z ∈ s → m ≤ z → z = m :=
sorry
theorem zorn_subset {α : Type u} (S : set (set α))
(h :
∀ (c : set (set α)) (H : c ⊆ S),
chain has_subset.subset c → ∃ (ub : set α), ∃ (H : ub ∈ S), ∀ (s : set α), s ∈ c → s ⊆ ub) :
∃ (m : set α), ∃ (H : m ∈ S), ∀ (a : set α), a ∈ S → m ⊆ a → a = m :=
sorry
theorem zorn_subset₀ {α : Type u} (S : set (set α))
(H :
∀ (c : set (set α)) (H : c ⊆ S),
chain has_subset.subset c →
set.nonempty c → ∃ (ub : set α), ∃ (H : ub ∈ S), ∀ (s : set α), s ∈ c → s ⊆ ub)
(x : set α) (hx : x ∈ S) :
∃ (m : set α), ∃ (H : m ∈ S), x ⊆ m ∧ ∀ (a : set α), a ∈ S → m ⊆ a → a = m :=
sorry
theorem chain.total {α : Type u} [preorder α] {c : set α} (H : chain LessEq c) {x : α} {y : α} :
x ∈ c → y ∈ c → x ≤ y ∨ y ≤ x :=
chain.total_of_refl H
theorem chain.image {α : Type u_1} {β : Type u_2} (r : α → α → Prop) (s : β → β → Prop) (f : α → β)
(h : ∀ (x y : α), r x y → s (f x) (f y)) {c : set α} (hrc : chain r c) : chain s (f '' c) :=
sorry
end zorn
theorem directed_of_chain {α : Type u_1} {β : Type u_2} {r : β → β → Prop} [is_refl β r] {f : α → β}
{c : set α} (h : zorn.chain (f ⁻¹'o r) c) :
directed r fun (x : Subtype fun (a : α) => a ∈ c) => f ↑x :=
sorry
end Mathlib |
a3fdfa6b536e2a139b6f1592a4a4f613bbeaf8dc | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/abelian/injective_resolution.lean | e5fc4068f4dcbd657d15e2e64a435f1dd90ab30c | [
"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 | 12,799 | lean | /-
Copyright (c) 2022 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang, Scott Morrison
-/
import algebra.homology.quasi_iso
import category_theory.preadditive.injective_resolution
import algebra.homology.homotopy_category
/-!
# Main result
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
When the underlying category is abelian:
* `category_theory.InjectiveResolution.desc`: Given `I : InjectiveResolution X` and
`J : InjectiveResolution Y`, any morphism `X ⟶ Y` admits a descent to a chain map
`J.cocomplex ⟶ I.cocomplex`. It is a descent in the sense that `I.ι` intertwines the descent and
the original morphism, see `category_theory.InjectiveResolution.desc_commutes`.
* `category_theory.InjectiveResolution.desc_homotopy`: Any two such descents are homotopic.
* `category_theory.InjectiveResolution.homotopy_equiv`: Any two injective resolutions of the same
object are homotopy equivalent.
* `category_theory.injective_resolutions`: If every object admits an injective resolution, we can
construct a functor `injective_resolutions C : C ⥤ homotopy_category C`.
* `category_theory.exact_f_d`: `f` and `injective.d f` are exact.
* `category_theory.InjectiveResolution.of`: Hence, starting from a monomorphism `X ⟶ J`, where `J`
is injective, we can apply `injective.d` repeatedly to obtain an injective resolution of `X`.
-/
noncomputable theory
open category_theory
open category_theory.limits
universes v u
namespace category_theory
variables {C : Type u} [category.{v} C]
open injective
namespace InjectiveResolution
section
variables [has_zero_morphisms C] [has_zero_object C] [has_equalizers C] [has_images C]
/-- Auxiliary construction for `desc`. -/
def desc_f_zero {Y Z : C} (f : Z ⟶ Y) (I : InjectiveResolution Y) (J : InjectiveResolution Z) :
J.cocomplex.X 0 ⟶ I.cocomplex.X 0 :=
factor_thru (f ≫ I.ι.f 0) (J.ι.f 0)
end
section abelian
variables [abelian C]
/-- Auxiliary construction for `desc`. -/
def desc_f_one {Y Z : C}
(f : Z ⟶ Y) (I : InjectiveResolution Y) (J : InjectiveResolution Z) :
J.cocomplex.X 1 ⟶ I.cocomplex.X 1 :=
exact.desc (desc_f_zero f I J ≫ I.cocomplex.d 0 1) (J.ι.f 0) (J.cocomplex.d 0 1)
(abelian.exact.op _ _ J.exact₀) (by simp [←category.assoc, desc_f_zero])
@[simp] lemma desc_f_one_zero_comm {Y Z : C}
(f : Z ⟶ Y) (I : InjectiveResolution Y) (J : InjectiveResolution Z) :
J.cocomplex.d 0 1 ≫ desc_f_one f I J = desc_f_zero f I J ≫ I.cocomplex.d 0 1 :=
by simp [desc_f_zero, desc_f_one]
/-- Auxiliary construction for `desc`. -/
def desc_f_succ {Y Z : C}
(I : InjectiveResolution Y) (J : InjectiveResolution Z)
(n : ℕ) (g : J.cocomplex.X n ⟶ I.cocomplex.X n) (g' : J.cocomplex.X (n+1) ⟶ I.cocomplex.X (n+1))
(w : J.cocomplex.d n (n+1) ≫ g' = g ≫ I.cocomplex.d n (n+1)) :
Σ' g'' : J.cocomplex.X (n+2) ⟶ I.cocomplex.X (n+2),
J.cocomplex.d (n+1) (n+2) ≫ g'' = g' ≫ I.cocomplex.d (n+1) (n+2) :=
⟨@exact.desc C _ _ _ _ _ _ _ _ _
(g' ≫ I.cocomplex.d (n+1) (n+2))
(J.cocomplex.d n (n+1))
(J.cocomplex.d (n+1) (n+2)) (abelian.exact.op _ _ (J.exact _))
(by simp [←category.assoc, w]), (by simp)⟩
/-- A morphism in `C` descends to a chain map between injective resolutions. -/
def desc {Y Z : C}
(f : Z ⟶ Y) (I : InjectiveResolution Y) (J : InjectiveResolution Z) :
J.cocomplex ⟶ I.cocomplex :=
cochain_complex.mk_hom _ _ (desc_f_zero f _ _) (desc_f_one f _ _)
(desc_f_one_zero_comm f I J).symm
(λ n ⟨g, g', w⟩, ⟨(desc_f_succ I J n g g' w.symm).1, (desc_f_succ I J n g g' w.symm).2.symm⟩)
/-- The resolution maps intertwine the descent of a morphism and that morphism. -/
@[simp, reassoc]
lemma desc_commutes {Y Z : C}
(f : Z ⟶ Y) (I : InjectiveResolution Y) (J : InjectiveResolution Z) :
J.ι ≫ desc f I J = (cochain_complex.single₀ C).map f ≫ I.ι :=
begin
ext n,
rcases n with (_|_|n);
{ dsimp [desc, desc_f_one, desc_f_zero], simp, },
end
-- Now that we've checked this property of the descent,
-- we can seal away the actual definition.
attribute [irreducible] desc
/-- An auxiliary definition for `desc_homotopy_zero`. -/
def desc_homotopy_zero_zero {Y Z : C} {I : InjectiveResolution Y} {J : InjectiveResolution Z}
(f : I.cocomplex ⟶ J.cocomplex)
(comm : I.ι ≫ f = 0) : I.cocomplex.X 1 ⟶ J.cocomplex.X 0 :=
exact.desc (f.f 0) (I.ι.f 0) (I.cocomplex.d 0 1) (abelian.exact.op _ _ I.exact₀)
(congr_fun (congr_arg homological_complex.hom.f comm) 0)
/-- An auxiliary definition for `desc_homotopy_zero`. -/
def desc_homotopy_zero_one {Y Z : C} {I : InjectiveResolution Y} {J : InjectiveResolution Z}
(f : I.cocomplex ⟶ J.cocomplex)
(comm : I.ι ≫ f = (0 : _ ⟶ J.cocomplex)) : I.cocomplex.X 2 ⟶ J.cocomplex.X 1 :=
exact.desc (f.f 1 - desc_homotopy_zero_zero f comm ≫ J.cocomplex.d 0 1)
(I.cocomplex.d 0 1) (I.cocomplex.d 1 2) (abelian.exact.op _ _ (I.exact _))
(by simp [desc_homotopy_zero_zero, ←category.assoc])
/-- An auxiliary definition for `desc_homotopy_zero`. -/
def desc_homotopy_zero_succ {Y Z : C} {I : InjectiveResolution Y} {J : InjectiveResolution Z}
(f : I.cocomplex ⟶ J.cocomplex) (n : ℕ)
(g : I.cocomplex.X (n + 1) ⟶ J.cocomplex.X n)
(g' : I.cocomplex.X (n + 2) ⟶ J.cocomplex.X (n + 1))
(w : f.f (n + 1) = I.cocomplex.d (n+1) (n+2) ≫ g' + g ≫ J.cocomplex.d n (n+1)) :
I.cocomplex.X (n + 3) ⟶ J.cocomplex.X (n + 2) :=
exact.desc (f.f (n+2) - g' ≫ J.cocomplex.d _ _) (I.cocomplex.d (n+1) (n+2))
(I.cocomplex.d (n+2) (n+3)) (abelian.exact.op _ _ (I.exact _))
(by simp [preadditive.comp_sub, ←category.assoc, preadditive.sub_comp,
show I.cocomplex.d (n+1) (n+2) ≫ g' = f.f (n + 1) - g ≫ J.cocomplex.d n (n+1),
by {rw w, simp only [add_sub_cancel] } ])
/-- Any descent of the zero morphism is homotopic to zero. -/
def desc_homotopy_zero {Y Z : C} {I : InjectiveResolution Y} {J : InjectiveResolution Z}
(f : I.cocomplex ⟶ J.cocomplex)
(comm : I.ι ≫ f = 0) :
homotopy f 0 :=
homotopy.mk_coinductive _ (desc_homotopy_zero_zero f comm) (by simp [desc_homotopy_zero_zero])
(desc_homotopy_zero_one f comm) (by simp [desc_homotopy_zero_one])
(λ n ⟨g, g', w⟩, ⟨desc_homotopy_zero_succ f n g g' (by simp only [w, add_comm]),
by simp [desc_homotopy_zero_succ, w]⟩)
/-- Two descents of the same morphism are homotopic. -/
def desc_homotopy {Y Z : C} (f : Y ⟶ Z) {I : InjectiveResolution Y} {J : InjectiveResolution Z}
(g h : I.cocomplex ⟶ J.cocomplex)
(g_comm : I.ι ≫ g = (cochain_complex.single₀ C).map f ≫ J.ι)
(h_comm : I.ι ≫ h = (cochain_complex.single₀ C).map f ≫ J.ι) :
homotopy g h :=
homotopy.equiv_sub_zero.inv_fun (desc_homotopy_zero _ (by simp [g_comm, h_comm]))
/-- The descent of the identity morphism is homotopic to the identity cochain map. -/
def desc_id_homotopy (X : C) (I : InjectiveResolution X) :
homotopy (desc (𝟙 X) I I) (𝟙 I.cocomplex) :=
by apply desc_homotopy (𝟙 X); simp
/-- The descent of a composition is homotopic to the composition of the descents. -/
def desc_comp_homotopy {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
(I : InjectiveResolution X) (J : InjectiveResolution Y) (K : InjectiveResolution Z) :
homotopy (desc (f ≫ g) K I) (desc f J I ≫ desc g K J) :=
by apply desc_homotopy (f ≫ g); simp
-- We don't care about the actual definitions of these homotopies.
attribute [irreducible] desc_homotopy_zero desc_homotopy desc_id_homotopy desc_comp_homotopy
/-- Any two injective resolutions are homotopy equivalent. -/
def homotopy_equiv {X : C} (I J : InjectiveResolution X) :
homotopy_equiv I.cocomplex J.cocomplex :=
{ hom := desc (𝟙 X) J I,
inv := desc (𝟙 X) I J,
homotopy_hom_inv_id := (desc_comp_homotopy (𝟙 X) (𝟙 X) I J I).symm.trans $
by simpa [category.id_comp] using desc_id_homotopy _ _,
homotopy_inv_hom_id := (desc_comp_homotopy (𝟙 X) (𝟙 X) J I J).symm.trans $
by simpa [category.id_comp] using desc_id_homotopy _ _ }
@[simp, reassoc] lemma homotopy_equiv_hom_ι {X : C} (I J : InjectiveResolution X) :
I.ι ≫ (homotopy_equiv I J).hom = J.ι :=
by simp [homotopy_equiv]
@[simp, reassoc] lemma homotopy_equiv_inv_ι {X : C} (I J : InjectiveResolution X) :
J.ι ≫ (homotopy_equiv I J).inv = I.ι :=
by simp [homotopy_equiv]
end abelian
end InjectiveResolution
section
variables [abelian C]
/-- An arbitrarily chosen injective resolution of an object. -/
abbreviation injective_resolution (Z : C) [has_injective_resolution Z] : cochain_complex C ℕ :=
(has_injective_resolution.out Z).some.cocomplex
/-- The cochain map from cochain complex consisting of `Z` supported in degree `0`
back to the arbitrarily chosen injective resolution `injective_resolution Z`. -/
abbreviation injective_resolution.ι (Z : C) [has_injective_resolution Z] :
(cochain_complex.single₀ C).obj Z ⟶ injective_resolution Z :=
(has_injective_resolution.out Z).some.ι
/-- The descent of a morphism to a cochain map between the arbitrarily chosen injective resolutions.
-/
abbreviation injective_resolution.desc {X Y : C} (f : X ⟶ Y)
[has_injective_resolution X] [has_injective_resolution Y] :
injective_resolution X ⟶ injective_resolution Y :=
InjectiveResolution.desc f _ _
variables (C) [has_injective_resolutions C]
/--
Taking injective resolutions is functorial,
if considered with target the homotopy category
(`ℕ`-indexed cochain complexes and chain maps up to homotopy).
-/
def injective_resolutions : C ⥤ homotopy_category C (complex_shape.up ℕ) :=
{ obj := λ X, (homotopy_category.quotient _ _).obj (injective_resolution X),
map := λ X Y f, (homotopy_category.quotient _ _).map (injective_resolution.desc f),
map_id' := λ X, begin
rw ←(homotopy_category.quotient _ _).map_id,
apply homotopy_category.eq_of_homotopy,
apply InjectiveResolution.desc_id_homotopy,
end,
map_comp' := λ X Y Z f g, begin
rw ←(homotopy_category.quotient _ _).map_comp,
apply homotopy_category.eq_of_homotopy,
apply InjectiveResolution.desc_comp_homotopy,
end, }
end
section
variables [abelian C] [enough_injectives C]
lemma exact_f_d {X Y : C} (f : X ⟶ Y) : exact f (d f) :=
(abelian.exact_iff _ _).2 $
⟨by simp, zero_of_comp_mono (ι _) $ by rw [category.assoc, kernel.condition]⟩
end
namespace InjectiveResolution
/-!
Our goal is to define `InjectiveResolution.of Z : InjectiveResolution Z`.
The `0`-th object in this resolution will just be `injective.under Z`,
i.e. an arbitrarily chosen injective object with a map from `Z`.
After that, we build the `n+1`-st object as `injective.syzygies`
applied to the previously constructed morphism,
and the map from the `n`-th object as `injective.d`.
-/
variables [abelian C] [enough_injectives C]
/-- Auxiliary definition for `InjectiveResolution.of`. -/
@[simps]
def of_cocomplex (Z : C) : cochain_complex C ℕ :=
cochain_complex.mk'
(injective.under Z) (injective.syzygies (injective.ι Z)) (injective.d (injective.ι Z))
(λ ⟨X, Y, f⟩, ⟨injective.syzygies f, injective.d f, (exact_f_d f).w⟩)
/--
In any abelian category with enough injectives,
`InjectiveResolution.of Z` constructs an injective resolution of the object `Z`.
-/
@[irreducible] def of (Z : C) : InjectiveResolution Z :=
{ cocomplex := of_cocomplex Z,
ι := cochain_complex.mk_hom _ _ (injective.ι Z) 0
(by { simp only [of_cocomplex_d, eq_self_iff_true, eq_to_hom_refl, category.comp_id,
dite_eq_ite, if_true, comp_zero],
exact (exact_f_d (injective.ι Z)).w, } ) (λ n _, ⟨0, by ext⟩),
injective := by { rintros (_|_|_|n); { apply injective.injective_under, } },
exact₀ := by simpa using exact_f_d (injective.ι Z),
exact := by { rintros (_|n); { simp, apply exact_f_d } },
mono := injective.ι_mono Z }
@[priority 100]
instance (Z : C) : has_injective_resolution Z :=
{ out := ⟨of Z⟩ }
@[priority 100]
instance : has_injective_resolutions C :=
{ out := λ _, infer_instance }
end InjectiveResolution
end category_theory
namespace homological_complex.hom
variables {C : Type u} [category.{v} C] [abelian C]
/-- If `X` is a cochain complex of injective objects and we have a quasi-isomorphism
`f : Y[0] ⟶ X`, then `X` is an injective resolution of `Y.` -/
def homological_complex.hom.from_single₀_InjectiveResolution (X : cochain_complex C ℕ) (Y : C)
(f : (cochain_complex.single₀ C).obj Y ⟶ X) [quasi_iso f]
(H : ∀ n, injective (X.X n)) :
InjectiveResolution Y :=
{ cocomplex := X,
ι := f,
injective := H,
exact₀ := f.from_single₀_exact_f_d_at_zero,
exact := f.from_single₀_exact_at_succ,
mono := f.from_single₀_mono_at_zero }
end homological_complex.hom
|
c7fcbafa142daadff1103c4cd93f7b13dcf3923d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/metric_space/cau_seq_filter.lean | 4acfa430161bc5f7090d9a5a11a0ec8fdbbf8e3f | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,683 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Sébastien Gouëzel
-/
import analysis.normed.field.basic
/-!
# Completeness in terms of `cauchy` filters vs `is_cau_seq` sequences
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we apply `metric.complete_of_cauchy_seq_tendsto` to prove that a `normed_ring`
is complete in terms of `cauchy` filter if and only if it is complete in terms
of `cau_seq` Cauchy sequences.
-/
universes u v
open set filter
open_locale topology classical
variable {β : Type v}
lemma cau_seq.tendsto_limit [normed_ring β] [hn : is_absolute_value (norm : β → ℝ)]
(f : cau_seq β norm) [cau_seq.is_complete β norm] :
tendsto f at_top (𝓝 f.lim) :=
_root_.tendsto_nhds.mpr
begin
intros s os lfs,
suffices : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → f b ∈ s, by simpa using this,
rcases metric.is_open_iff.1 os _ lfs with ⟨ε, ⟨hε, hεs⟩⟩,
cases setoid.symm (cau_seq.equiv_lim f) _ hε with N hN,
existsi N,
intros b hb,
apply hεs,
dsimp [metric.ball], rw [dist_comm, dist_eq_norm],
solve_by_elim
end
variables [normed_field β]
/-
This section shows that if we have a uniform space generated by an absolute value, topological
completeness and Cauchy sequence completeness coincide. The problem is that there isn't
a good notion of "uniform space generated by an absolute value", so right now this is
specific to norm. Furthermore, norm only instantiates is_absolute_value on normed_division_ring.
This needs to be fixed, since it prevents showing that ℤ_[hp] is complete
-/
open metric
lemma cauchy_seq.is_cau_seq {f : ℕ → β} (hf : cauchy_seq f) :
is_cau_seq norm f :=
begin
cases cauchy_iff.1 hf with hf1 hf2,
intros ε hε,
rcases hf2 {x | dist x.1 x.2 < ε} (dist_mem_uniformity hε) with ⟨t, ⟨ht, htsub⟩⟩,
simp at ht, cases ht with N hN,
existsi N,
intros j hj,
rw ←dist_eq_norm,
apply @htsub (f j, f N),
apply set.mk_mem_prod; solve_by_elim [le_refl]
end
lemma cau_seq.cauchy_seq (f : cau_seq β norm) : cauchy_seq f :=
begin
refine cauchy_iff.2 ⟨by apply_instance, λ s hs, _⟩,
rcases mem_uniformity_dist.1 hs with ⟨ε, ⟨hε, hεs⟩⟩,
cases cau_seq.cauchy₂ f hε with N hN,
existsi {n | n ≥ N}.image f,
simp only [exists_prop, mem_at_top_sets, mem_map, mem_image, ge_iff_le, mem_set_of_eq],
split,
{ existsi N, intros b hb, existsi b, simp [hb] },
{ rintros ⟨a, b⟩ ⟨⟨a', ⟨ha'1, ha'2⟩⟩, ⟨b', ⟨hb'1, hb'2⟩⟩⟩,
dsimp at ha'1 ha'2 hb'1 hb'2,
rw [←ha'2, ←hb'2],
apply hεs,
rw dist_eq_norm,
apply hN; assumption }
end
/-- In a normed field, `cau_seq` coincides with the usual notion of Cauchy sequences. -/
lemma cau_seq_iff_cauchy_seq {α : Type u} [normed_field α] {u : ℕ → α} :
is_cau_seq norm u ↔ cauchy_seq u :=
⟨λh, cau_seq.cauchy_seq ⟨u, h⟩,
λh, h.is_cau_seq⟩
/-- A complete normed field is complete as a metric space, as Cauchy sequences converge by
assumption and this suffices to characterize completeness. -/
@[priority 100] -- see Note [lower instance priority]
instance complete_space_of_cau_seq_complete [cau_seq.is_complete β norm] : complete_space β :=
begin
apply complete_of_cauchy_seq_tendsto,
assume u hu,
have C : is_cau_seq norm u := cau_seq_iff_cauchy_seq.2 hu,
existsi cau_seq.lim ⟨u, C⟩,
rw metric.tendsto_at_top,
assume ε εpos,
cases (cau_seq.equiv_lim ⟨u, C⟩) _ εpos with N hN,
existsi N,
simpa [dist_eq_norm] using hN
end
|
43fbe295bacbf92868de406ef4908bc1e0298aae | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/repr_issue.lean | 1e515b5770b29ca0dde3ac49dcf48e2e88ec7af3 | [
"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 | 623 | lean | def foo {m} [Monad m] [MonadExcept String m] [MonadState (Array Nat) m] : m Nat :=
catch (do modify $ fun (a : Array Nat) => a.set! 0 33;
throw "error")
(fun _ => do a ← get; pure $ a.get! 0)
def ex₁ : StateT (Array Nat) (ExceptT String Id) Nat :=
foo
def ex₂ : ExceptT String (StateT (Array Nat) Id) Nat :=
foo
-- The following examples were producing an element of Type `id (Except String Nat)`.
-- Type class resolution was failing to produce an instance for `HasRepr (id (Except String Nat))` because `id` is not transparent.
#eval run ex₁ (mkArray 10 1000)
#eval run ex₂ (mkArray 10 1000)
|
adddeb98d5f7f68f242c9e76c90d72f76fccc876 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/linear_algebra/basis.lean | c560d1cfc33ec54344082d35f90ec2f4e89392e9 | [
"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 | 57,598 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp
-/
import algebra.big_operators.finsupp
import algebra.big_operators.finprod
import data.fintype.big_operators
import linear_algebra.finsupp
import linear_algebra.linear_independent
import linear_algebra.linear_pmap
import linear_algebra.projection
/-!
# Bases
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines bases in a module or vector space.
It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light.
## Main definitions
All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or
vector space and `ι : Type*` is an arbitrary indexing type.
* `basis ι R M` is the type of `ι`-indexed `R`-bases for a module `M`,
represented by a linear equiv `M ≃ₗ[R] ι →₀ R`.
* the basis vectors of a basis `b : basis ι R M` are available as `b i`, where `i : ι`
* `basis.repr` is the isomorphism sending `x : M` to its coordinates `basis.repr x : ι →₀ R`.
The converse, turning this isomorphism into a basis, is called `basis.of_repr`.
* If `ι` is finite, there is a variant of `repr` called `basis.equiv_fun b : M ≃ₗ[R] ι → R`
(saving you from having to work with `finsupp`). The converse, turning this isomorphism into
a basis, is called `basis.of_equiv_fun`.
* `basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the
basis elements `⇑b : ι → M₁`.
* `basis.reindex` uses an equiv to map a basis to a different indexing set.
* `basis.map` uses a linear equiv to map a basis to a different module.
## Main statements
* `basis.mk`: a linear independent set of vectors spanning the whole module determines a basis
* `basis.ext` states that two linear maps are equal if they coincide on a basis.
Similar results are available for linear equivs (if they coincide on the basis vectors),
elements (if their coordinates coincide) and the functions `b.repr` and `⇑b`.
* `basis.of_vector_space` states that every vector space has a basis.
## Implementation notes
We use families instead of sets because it allows us to say that two identical vectors are linearly
dependent. For bases, this is useful as well because we can easily derive ordered bases by using an
ordered index type `ι`.
## Tags
basis, bases
-/
noncomputable theory
universe u
open function set submodule
open_locale big_operators
variables {ι : Type*} {ι' : Type*} {R : Type*} {R₂ : Type*} {K : Type*}
variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*}
section module
variables [semiring R]
variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M']
section
variables (ι) (R) (M)
/-- A `basis ι R M` for a module `M` is the type of `ι`-indexed `R`-bases of `M`.
The basis vectors are available as `coe_fn (b : basis ι R M) : ι → M`.
To turn a linear independent family of vectors spanning `M` into a basis, use `basis.mk`.
They are internally represented as linear equivs `M ≃ₗ[R] (ι →₀ R)`,
available as `basis.repr`.
-/
structure basis := of_repr :: (repr : M ≃ₗ[R] (ι →₀ R))
end
instance unique_basis [subsingleton R] : unique (basis ι R M) :=
⟨⟨⟨default⟩⟩, λ ⟨b⟩, by rw subsingleton.elim b⟩
namespace basis
instance : inhabited (basis ι R (ι →₀ R)) := ⟨basis.of_repr (linear_equiv.refl _ _)⟩
variables (b b₁ : basis ι R M) (i : ι) (c : R) (x : M)
section repr
lemma repr_injective : injective (repr : basis ι R M → M ≃ₗ[R] (ι →₀ R)) :=
λ f g h, by cases f; cases g; congr'
/-- `b i` is the `i`th basis vector. -/
instance fun_like : fun_like (basis ι R M) ι (λ _, M) :=
{ coe := λ b i, b.repr.symm (finsupp.single i 1),
coe_injective' := λ f g h, repr_injective $ linear_equiv.symm_bijective.injective begin
ext x,
rw [←finsupp.sum_single x, map_finsupp_sum, map_finsupp_sum],
congr' with i r,
have := congr_fun h i,
dsimp at this,
rw [←mul_one r, ←finsupp.smul_single', linear_equiv.map_smul, linear_equiv.map_smul, this],
end }
@[simp] lemma coe_of_repr (e : M ≃ₗ[R] (ι →₀ R)) :
⇑(of_repr e) = λ i, e.symm (finsupp.single i 1) :=
rfl
protected lemma injective [nontrivial R] : injective b :=
b.repr.symm.injective.comp (λ _ _, (finsupp.single_left_inj (one_ne_zero : (1 : R) ≠ 0)).mp)
lemma repr_symm_single_one : b.repr.symm (finsupp.single i 1) = b i := rfl
lemma repr_symm_single : b.repr.symm (finsupp.single i c) = c • b i :=
calc b.repr.symm (finsupp.single i c)
= b.repr.symm (c • finsupp.single i 1) : by rw [finsupp.smul_single', mul_one]
... = c • b i : by rw [linear_equiv.map_smul, repr_symm_single_one]
@[simp] lemma repr_self : b.repr (b i) = finsupp.single i 1 :=
linear_equiv.apply_symm_apply _ _
lemma repr_self_apply (j) [decidable (i = j)] :
b.repr (b i) j = if i = j then 1 else 0 :=
by rw [repr_self, finsupp.single_apply]
@[simp] lemma repr_symm_apply (v) : b.repr.symm v = finsupp.total ι M R b v :=
calc b.repr.symm v = b.repr.symm (v.sum finsupp.single) : by simp
... = ∑ i in v.support, b.repr.symm (finsupp.single i (v i)) :
by rw [finsupp.sum, linear_equiv.map_sum]
... = finsupp.total ι M R b v :
by simp [repr_symm_single, finsupp.total_apply, finsupp.sum]
@[simp] lemma coe_repr_symm : ↑b.repr.symm = finsupp.total ι M R b :=
linear_map.ext (λ v, b.repr_symm_apply v)
@[simp] lemma repr_total (v) : b.repr (finsupp.total _ _ _ b v) = v :=
by { rw ← b.coe_repr_symm, exact b.repr.apply_symm_apply v }
@[simp] lemma total_repr : finsupp.total _ _ _ b (b.repr x) = x :=
by { rw ← b.coe_repr_symm, exact b.repr.symm_apply_apply x }
lemma repr_range : (b.repr : M →ₗ[R] (ι →₀ R)).range = finsupp.supported R R univ :=
by rw [linear_equiv.range, finsupp.supported_univ]
lemma mem_span_repr_support {ι : Type*} (b : basis ι R M) (m : M) :
m ∈ span R (b '' (b.repr m).support) :=
(finsupp.mem_span_image_iff_total _).2 ⟨b.repr m, (by simp [finsupp.mem_supported_support])⟩
lemma repr_support_subset_of_mem_span {ι : Type*}
(b : basis ι R M) (s : set ι) {m : M} (hm : m ∈ span R (b '' s)) : ↑(b.repr m).support ⊆ s :=
begin
rcases (finsupp.mem_span_image_iff_total _).1 hm with ⟨l, hl, hlm⟩,
rwa [←hlm, repr_total, ←finsupp.mem_supported R l]
end
end repr
section coord
/-- `b.coord i` is the linear function giving the `i`'th coordinate of a vector
with respect to the basis `b`.
`b.coord i` is an element of the dual space. In particular, for
finite-dimensional spaces it is the `ι`th basis vector of the dual space.
-/
@[simps]
def coord : M →ₗ[R] R := (finsupp.lapply i) ∘ₗ ↑b.repr
lemma forall_coord_eq_zero_iff {x : M} :
(∀ i, b.coord i x = 0) ↔ x = 0 :=
iff.trans
(by simp only [b.coord_apply, finsupp.ext_iff, finsupp.zero_apply])
b.repr.map_eq_zero_iff
/-- The sum of the coordinates of an element `m : M` with respect to a basis. -/
noncomputable def sum_coords : M →ₗ[R] R :=
finsupp.lsum ℕ (λ i, linear_map.id) ∘ₗ (b.repr : M →ₗ[R] ι →₀ R)
@[simp] lemma coe_sum_coords : (b.sum_coords : M → R) = λ m, (b.repr m).sum (λ i, id) :=
rfl
lemma coe_sum_coords_eq_finsum : (b.sum_coords : M → R) = λ m, ∑ᶠ i, b.coord i m :=
begin
ext m,
simp only [basis.sum_coords, basis.coord, finsupp.lapply_apply, linear_map.id_coe,
linear_equiv.coe_coe, function.comp_app, finsupp.coe_lsum, linear_map.coe_comp,
finsum_eq_sum _ (b.repr m).finite_support, finsupp.sum, finset.finite_to_set_to_finset,
id.def, finsupp.fun_support_eq],
end
@[simp] lemma coe_sum_coords_of_fintype [fintype ι] : (b.sum_coords : M → R) = ∑ i, b.coord i :=
begin
ext m,
simp only [sum_coords, finsupp.sum_fintype, linear_map.id_coe, linear_equiv.coe_coe, coord_apply,
id.def, fintype.sum_apply, implies_true_iff, eq_self_iff_true, finsupp.coe_lsum,
linear_map.coe_comp],
end
@[simp] lemma sum_coords_self_apply : b.sum_coords (b i) = 1 :=
by simp only [basis.sum_coords, linear_map.id_coe, linear_equiv.coe_coe, id.def, basis.repr_self,
function.comp_app, finsupp.coe_lsum, linear_map.coe_comp, finsupp.sum_single_index]
lemma dvd_coord_smul (i : ι) (m : M) (r : R) : r ∣ b.coord i (r • m) :=
⟨b.coord i m, by simp⟩
lemma coord_repr_symm (b : basis ι R M) (i : ι) (f : ι →₀ R) :
b.coord i (b.repr.symm f) = f i :=
by simp only [repr_symm_apply, coord_apply, repr_total]
end coord
section ext
variables {R₁ : Type*} [semiring R₁] {σ : R →+* R₁} {σ' : R₁ →+* R}
variables [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ]
variables {M₁ : Type*} [add_comm_monoid M₁] [module R₁ M₁]
/-- Two linear maps are equal if they are equal on basis vectors. -/
theorem ext {f₁ f₂ : M →ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ :=
by { ext x,
rw [← b.total_repr x, finsupp.total_apply, finsupp.sum],
simp only [linear_map.map_sum, linear_map.map_smulₛₗ, h] }
include σ'
/-- Two linear equivs are equal if they are equal on basis vectors. -/
theorem ext' {f₁ f₂ : M ≃ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ :=
by { ext x,
rw [← b.total_repr x, finsupp.total_apply, finsupp.sum],
simp only [linear_equiv.map_sum, linear_equiv.map_smulₛₗ, h] }
omit σ'
/-- Two elements are equal iff their coordinates are equal. -/
lemma ext_elem_iff {x y : M} :
x = y ↔ (∀ i, b.repr x i = b.repr y i) :=
by simp only [← finsupp.ext_iff, embedding_like.apply_eq_iff_eq]
alias ext_elem_iff ↔ _ _root_.basis.ext_elem
lemma repr_eq_iff {b : basis ι R M} {f : M →ₗ[R] ι →₀ R} :
↑b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 :=
⟨λ h i, h ▸ b.repr_self i,
λ h, b.ext (λ i, (b.repr_self i).trans (h i).symm)⟩
lemma repr_eq_iff' {b : basis ι R M} {f : M ≃ₗ[R] ι →₀ R} :
b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 :=
⟨λ h i, h ▸ b.repr_self i,
λ h, b.ext' (λ i, (b.repr_self i).trans (h i).symm)⟩
lemma apply_eq_iff {b : basis ι R M} {x : M} {i : ι} :
b i = x ↔ b.repr x = finsupp.single i 1 :=
⟨λ h, h ▸ b.repr_self i,
λ h, b.repr.injective ((b.repr_self i).trans h.symm)⟩
/-- An unbundled version of `repr_eq_iff` -/
lemma repr_apply_eq (f : M → ι → R)
(hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x)
(f_eq : ∀ i, f (b i) = finsupp.single i 1) (x : M) (i : ι) :
b.repr x i = f x i :=
begin
let f_i : M →ₗ[R] R :=
{ to_fun := λ x, f x i,
map_add' := λ _ _, by rw [hadd, pi.add_apply],
map_smul' := λ _ _, by { simp [hsmul, pi.smul_apply] } },
have : (finsupp.lapply i) ∘ₗ ↑b.repr = f_i,
{ refine b.ext (λ j, _),
show b.repr (b j) i = f (b j) i,
rw [b.repr_self, f_eq] },
calc b.repr x i = f_i x : by { rw ← this, refl }
... = f x i : rfl
end
/-- Two bases are equal if they assign the same coordinates. -/
lemma eq_of_repr_eq_repr {b₁ b₂ : basis ι R M} (h : ∀ x i, b₁.repr x i = b₂.repr x i) : b₁ = b₂ :=
repr_injective $ by { ext, apply h }
/-- Two bases are equal if their basis vectors are the same. -/
@[ext] lemma eq_of_apply_eq {b₁ b₂ : basis ι R M} : (∀ i, b₁ i = b₂ i) → b₁ = b₂ := fun_like.ext _ _
end ext
section map
variables (f : M ≃ₗ[R] M')
/-- Apply the linear equivalence `f` to the basis vectors. -/
@[simps] protected def map : basis ι R M' :=
of_repr (f.symm.trans b.repr)
@[simp] lemma map_apply (i) : b.map f i = f (b i) := rfl
end map
section map_coeffs
variables {R' : Type*} [semiring R'] [module R' M] (f : R ≃+* R') (h : ∀ c (x : M), f c • x = c • x)
include f h b
local attribute [instance] has_smul.comp.is_scalar_tower
/-- If `R` and `R'` are isomorphic rings that act identically on a module `M`,
then a basis for `M` as `R`-module is also a basis for `M` as `R'`-module.
See also `basis.algebra_map_coeffs` for the case where `f` is equal to `algebra_map`.
-/
@[simps {simp_rhs := tt}]
def map_coeffs : basis ι R' M :=
begin
letI : module R' R := module.comp_hom R (↑f.symm : R' →+* R),
haveI : is_scalar_tower R' R M :=
{ smul_assoc := λ x y z, begin dsimp [(•)], rw [mul_smul, ←h, f.apply_symm_apply], end },
exact (of_repr $ (b.repr.restrict_scalars R').trans $
finsupp.map_range.linear_equiv (module.comp_hom.to_linear_equiv f.symm).symm )
end
lemma map_coeffs_apply (i : ι) : b.map_coeffs f h i = b i :=
apply_eq_iff.mpr $ by simp [f.to_add_equiv_eq_coe]
@[simp] lemma coe_map_coeffs : (b.map_coeffs f h : ι → M) = b :=
funext $ b.map_coeffs_apply f h
end map_coeffs
section reindex
variables (b' : basis ι' R M')
variables (e : ι ≃ ι')
/-- `b.reindex (e : ι ≃ ι')` is a basis indexed by `ι'` -/
def reindex : basis ι' R M :=
basis.of_repr (b.repr.trans (finsupp.dom_lcongr e))
lemma reindex_apply (i' : ι') : b.reindex e i' = b (e.symm i') :=
show (b.repr.trans (finsupp.dom_lcongr e)).symm (finsupp.single i' 1) =
b.repr.symm (finsupp.single (e.symm i') 1),
by rw [linear_equiv.symm_trans_apply, finsupp.dom_lcongr_symm, finsupp.dom_lcongr_single]
@[simp] lemma coe_reindex : (b.reindex e : ι' → M) = b ∘ e.symm :=
funext (b.reindex_apply e)
lemma repr_reindex_apply (i' : ι') : (b.reindex e).repr x i' = b.repr x (e.symm i') :=
show (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (b.repr x) i' = _, by simp
@[simp] lemma repr_reindex : (b.reindex e).repr x = (b.repr x).map_domain e :=
fun_like.ext _ _ $ by simp [repr_reindex_apply]
@[simp] lemma reindex_refl : b.reindex (equiv.refl ι) = b :=
eq_of_apply_eq $ λ i, by simp
/-- `simp` can prove this as `basis.coe_reindex` + `equiv_like.range_comp` -/
lemma range_reindex : set.range (b.reindex e) = set.range b :=
by rw [coe_reindex, equiv_like.range_comp]
@[simp] lemma sum_coords_reindex : (b.reindex e).sum_coords = b.sum_coords :=
begin
ext x,
simp only [coe_sum_coords, repr_reindex],
exact finsupp.sum_map_domain_index (λ _, rfl) (λ _ _ _, rfl),
end
/-- `b.reindex_range` is a basis indexed by `range b`, the basis vectors themselves. -/
def reindex_range : basis (range b) R M :=
by haveI := classical.dec (nontrivial R); exact
if h : nontrivial R then
by letI := h; exact b.reindex (equiv.of_injective b (basis.injective b))
else
by letI : subsingleton R := not_nontrivial_iff_subsingleton.mp h; exact
basis.of_repr (module.subsingleton_equiv R M (range b))
lemma reindex_range_self (i : ι) (h := set.mem_range_self i) :
b.reindex_range ⟨b i, h⟩ = b i :=
begin
by_cases htr : nontrivial R,
{ letI := htr,
simp [htr, reindex_range, reindex_apply, equiv.apply_of_injective_symm b.injective,
subtype.coe_mk] },
{ letI : subsingleton R := not_nontrivial_iff_subsingleton.mp htr,
letI := module.subsingleton R M,
simp [reindex_range] }
end
lemma reindex_range_repr_self (i : ι) :
b.reindex_range.repr (b i) = finsupp.single ⟨b i, mem_range_self i⟩ 1 :=
calc b.reindex_range.repr (b i) = b.reindex_range.repr (b.reindex_range ⟨b i, mem_range_self i⟩) :
congr_arg _ (b.reindex_range_self _ _).symm
... = finsupp.single ⟨b i, mem_range_self i⟩ 1 : b.reindex_range.repr_self _
@[simp] lemma reindex_range_apply (x : range b) : b.reindex_range x = x :=
by { rcases x with ⟨bi, ⟨i, rfl⟩⟩, exact b.reindex_range_self i, }
lemma reindex_range_repr' (x : M) {bi : M} {i : ι} (h : b i = bi) :
b.reindex_range.repr x ⟨bi, ⟨i, h⟩⟩ = b.repr x i :=
begin
nontriviality,
subst h,
refine (b.repr_apply_eq (λ x i, b.reindex_range.repr x ⟨b i, _⟩) _ _ _ x i).symm,
{ intros x y,
ext i,
simp only [pi.add_apply, linear_equiv.map_add, finsupp.coe_add] },
{ intros c x,
ext i,
simp only [pi.smul_apply, linear_equiv.map_smul, finsupp.coe_smul] },
{ intros i,
ext j,
simp only [reindex_range_repr_self],
refine @finsupp.single_apply_left _ _ _ _ (λ i, (⟨b i, _⟩ : set.range b)) _ _ _ _,
exact λ i j h, b.injective (subtype.mk.inj h) }
end
@[simp] lemma reindex_range_repr (x : M) (i : ι) (h := set.mem_range_self i) :
b.reindex_range.repr x ⟨b i, h⟩ = b.repr x i :=
b.reindex_range_repr' _ rfl
section fintype
variables [fintype ι] [decidable_eq M]
/-- `b.reindex_finset_range` is a basis indexed by `finset.univ.image b`,
the finite set of basis vectors themselves. -/
def reindex_finset_range : basis (finset.univ.image b) R M :=
b.reindex_range.reindex ((equiv.refl M).subtype_equiv (by simp))
lemma reindex_finset_range_self (i : ι) (h := finset.mem_image_of_mem b (finset.mem_univ i)) :
b.reindex_finset_range ⟨b i, h⟩ = b i :=
by { rw [reindex_finset_range, reindex_apply, reindex_range_apply], refl }
@[simp] lemma reindex_finset_range_apply (x : finset.univ.image b) :
b.reindex_finset_range x = x :=
by { rcases x with ⟨bi, hbi⟩, rcases finset.mem_image.mp hbi with ⟨i, -, rfl⟩,
exact b.reindex_finset_range_self i }
lemma reindex_finset_range_repr_self (i : ι) :
b.reindex_finset_range.repr (b i) =
finsupp.single ⟨b i, finset.mem_image_of_mem b (finset.mem_univ i)⟩ 1 :=
begin
ext ⟨bi, hbi⟩,
rw [reindex_finset_range, repr_reindex, finsupp.map_domain_equiv_apply, reindex_range_repr_self],
convert finsupp.single_apply_left ((equiv.refl M).subtype_equiv _).symm.injective _ _ _,
refl
end
@[simp] lemma reindex_finset_range_repr (x : M) (i : ι)
(h := finset.mem_image_of_mem b (finset.mem_univ i)) :
b.reindex_finset_range.repr x ⟨b i, h⟩ = b.repr x i :=
by simp [reindex_finset_range]
end fintype
end reindex
protected lemma linear_independent : linear_independent R b :=
linear_independent_iff.mpr $ λ l hl,
calc l = b.repr (finsupp.total _ _ _ b l) : (b.repr_total l).symm
... = 0 : by rw [hl, linear_equiv.map_zero]
protected lemma ne_zero [nontrivial R] (i) : b i ≠ 0 :=
b.linear_independent.ne_zero i
protected lemma mem_span (x : M) : x ∈ span R (range b) :=
by { rw [← b.total_repr x, finsupp.total_apply, finsupp.sum],
exact submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (submodule.subset_span ⟨i, rfl⟩)) }
protected lemma span_eq : span R (range b) = ⊤ :=
eq_top_iff.mpr $ λ x _, b.mem_span x
lemma index_nonempty (b : basis ι R M) [nontrivial M] : nonempty ι :=
begin
obtain ⟨x, y, ne⟩ : ∃ (x y : M), x ≠ y := nontrivial.exists_pair_ne,
obtain ⟨i, _⟩ := not_forall.mp (mt b.ext_elem_iff.2 ne),
exact ⟨i⟩
end
/-- If the submodule `P` has a basis, `x ∈ P` iff it is a linear combination of basis vectors. -/
lemma mem_submodule_iff {P : submodule R M} (b : basis ι R P) {x : M} :
x ∈ P ↔ ∃ (c : ι →₀ R), x = finsupp.sum c (λ i x, x • b i) :=
begin
conv_lhs { rw [← P.range_subtype, ← submodule.map_top, ← b.span_eq, submodule.map_span,
← set.range_comp, ← finsupp.range_total] },
simpa only [@eq_comm _ x],
end
section constr
variables (S : Type*) [semiring S] [module S M']
variables [smul_comm_class R S M']
/-- Construct a linear map given the value at the basis.
This definition is parameterized over an extra `semiring S`,
such that `smul_comm_class R S M'` holds.
If `R` is commutative, you can set `S := R`; if `R` is not commutative,
you can recover an `add_equiv` by setting `S := ℕ`.
See library note [bundled maps over different rings].
-/
def constr : (ι → M') ≃ₗ[S] (M →ₗ[R] M') :=
{ to_fun := λ f, (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f) ∘ₗ ↑b.repr,
inv_fun := λ f i, f (b i),
left_inv := λ f, by { ext, simp },
right_inv := λ f, by { refine b.ext (λ i, _), simp },
map_add' := λ f g, by { refine b.ext (λ i, _), simp },
map_smul' := λ c f, by { refine b.ext (λ i, _), simp } }
theorem constr_def (f : ι → M') :
b.constr S f = (finsupp.total M' M' R id) ∘ₗ ((finsupp.lmap_domain R R f) ∘ₗ ↑b.repr) :=
rfl
theorem constr_apply (f : ι → M') (x : M) :
b.constr S f x = (b.repr x).sum (λ b a, a • f b) :=
by { simp only [constr_def, linear_map.comp_apply, finsupp.lmap_domain_apply, finsupp.total_apply],
rw finsupp.sum_map_domain_index; simp [add_smul] }
@[simp] lemma constr_basis (f : ι → M') (i : ι) :
(b.constr S f : M → M') (b i) = f i :=
by simp [basis.constr_apply, b.repr_self]
lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'}
(h : ∀i, g i = f (b i)) : b.constr S g = f :=
b.ext $ λ i, (b.constr_basis S g i).trans (h i)
lemma constr_self (f : M →ₗ[R] M') : b.constr S (λ i, f (b i)) = f :=
b.constr_eq S $ λ x, rfl
lemma constr_range [nonempty ι] {f : ι → M'} :
(b.constr S f).range = span R (range f) :=
by rw [b.constr_def S f, linear_map.range_comp, linear_map.range_comp, linear_equiv.range,
← finsupp.supported_univ, finsupp.lmap_domain_supported, ←set.image_univ,
← finsupp.span_image_eq_map_total, set.image_id]
@[simp]
lemma constr_comp (f : M' →ₗ[R] M') (v : ι → M') :
b.constr S (f ∘ v) = f.comp (b.constr S v) :=
b.ext (λ i, by simp only [basis.constr_basis, linear_map.comp_apply])
end constr
section equiv
variables (b' : basis ι' R M') (e : ι ≃ ι')
variables [add_comm_monoid M''] [module R M'']
/-- If `b` is a basis for `M` and `b'` a basis for `M'`, and the index types are equivalent,
`b.equiv b' e` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `b' (e i)`. -/
protected def equiv : M ≃ₗ[R] M' :=
b.repr.trans (b'.reindex e.symm).repr.symm
@[simp] lemma equiv_apply : b.equiv b' e (b i) = b' (e i) :=
by simp [basis.equiv]
@[simp] lemma equiv_refl :
b.equiv b (equiv.refl ι) = linear_equiv.refl R M :=
b.ext' (λ i, by simp)
@[simp] lemma equiv_symm : (b.equiv b' e).symm = b'.equiv b e.symm :=
b'.ext' $ λ i, (b.equiv b' e).injective (by simp)
@[simp] lemma equiv_trans {ι'' : Type*} (b'' : basis ι'' R M'')
(e : ι ≃ ι') (e' : ι' ≃ ι'') :
(b.equiv b' e).trans (b'.equiv b'' e') = b.equiv b'' (e.trans e') :=
b.ext' (λ i, by simp)
@[simp]
lemma map_equiv (b : basis ι R M) (b' : basis ι' R M') (e : ι ≃ ι') :
b.map (b.equiv b' e) = b'.reindex e.symm :=
by { ext i, simp }
end equiv
section prod
variables (b' : basis ι' R M')
/-- `basis.prod` maps a `ι`-indexed basis for `M` and a `ι'`-indexed basis for `M'`
to a `ι ⊕ ι'`-index basis for `M × M'`.
For the specific case of `R × R`, see also `basis.fin_two_prod`. -/
protected def prod : basis (ι ⊕ ι') R (M × M') :=
of_repr ((b.repr.prod b'.repr).trans (finsupp.sum_finsupp_lequiv_prod_finsupp R).symm)
@[simp]
lemma prod_repr_inl (x) (i) : (b.prod b').repr x (sum.inl i) = b.repr x.1 i := rfl
@[simp]
lemma prod_repr_inr (x) (i) : (b.prod b').repr x (sum.inr i) = b'.repr x.2 i := rfl
lemma prod_apply_inl_fst (i) :
(b.prod b' (sum.inl i)).1 = b i :=
b.repr.injective $ by
{ ext j,
simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm,
linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self,
equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp],
apply finsupp.single_apply_left sum.inl_injective }
lemma prod_apply_inr_fst (i) :
(b.prod b' (sum.inr i)).1 = 0 :=
b.repr.injective $ by
{ ext i,
simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm,
linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self,
equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero,
finsupp.zero_apply],
apply finsupp.single_eq_of_ne sum.inr_ne_inl }
lemma prod_apply_inl_snd (i) :
(b.prod b' (sum.inl i)).2 = 0 :=
b'.repr.injective $ by
{ ext j,
simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm,
linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self,
equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero,
finsupp.zero_apply],
apply finsupp.single_eq_of_ne sum.inl_ne_inr }
lemma prod_apply_inr_snd (i) :
(b.prod b' (sum.inr i)).2 = b' i :=
b'.repr.injective $ by
{ ext i,
simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm,
linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self,
equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp],
apply finsupp.single_apply_left sum.inr_injective }
@[simp]
lemma prod_apply (i) :
b.prod b' i = sum.elim (linear_map.inl R M M' ∘ b) (linear_map.inr R M M' ∘ b') i :=
by { ext; cases i; simp only [prod_apply_inl_fst, sum.elim_inl, linear_map.inl_apply,
prod_apply_inr_fst, sum.elim_inr, linear_map.inr_apply,
prod_apply_inl_snd, prod_apply_inr_snd, comp_app] }
end prod
section no_zero_smul_divisors
-- Can't be an instance because the basis can't be inferred.
protected lemma no_zero_smul_divisors [no_zero_divisors R] (b : basis ι R M) :
no_zero_smul_divisors R M :=
⟨λ c x hcx, or_iff_not_imp_right.mpr (λ hx, begin
rw [← b.total_repr x, ← linear_map.map_smul] at hcx,
have := linear_independent_iff.mp b.linear_independent (c • b.repr x) hcx,
rw smul_eq_zero at this,
exact this.resolve_right (λ hr, hx (b.repr.map_eq_zero_iff.mp hr))
end)⟩
protected lemma smul_eq_zero [no_zero_divisors R] (b : basis ι R M) {c : R} {x : M} :
c • x = 0 ↔ c = 0 ∨ x = 0 :=
@smul_eq_zero _ _ _ _ _ b.no_zero_smul_divisors _ _
lemma _root_.eq_bot_of_rank_eq_zero [no_zero_divisors R] (b : basis ι R M) (N : submodule R M)
(rank_eq : ∀ {m : ℕ} (v : fin m → N),
linear_independent R (coe ∘ v : fin m → M) → m = 0) :
N = ⊥ :=
begin
rw submodule.eq_bot_iff,
intros x hx,
contrapose! rank_eq with x_ne,
refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩,
rw fintype.linear_independent_iff,
rintros g sum_eq i,
cases i,
simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, finset.univ_unique,
function.comp_const, finset.sum_singleton] at sum_eq,
convert (b.smul_eq_zero.mp sum_eq).resolve_right x_ne
end
end no_zero_smul_divisors
section singleton
/-- `basis.singleton ι R` is the basis sending the unique element of `ι` to `1 : R`. -/
protected def singleton (ι R : Type*) [unique ι] [semiring R] :
basis ι R R :=
of_repr
{ to_fun := λ x, finsupp.single default x,
inv_fun := λ f, f default,
left_inv := λ x, by simp,
right_inv := λ f, finsupp.unique_ext (by simp),
map_add' := λ x y, by simp,
map_smul' := λ c x, by simp }
@[simp] lemma singleton_apply (ι R : Type*) [unique ι] [semiring R] (i) :
basis.singleton ι R i = 1 :=
apply_eq_iff.mpr (by simp [basis.singleton])
@[simp] lemma singleton_repr (ι R : Type*) [unique ι] [semiring R] (x i) :
(basis.singleton ι R).repr x i = x :=
by simp [basis.singleton, unique.eq_default i]
lemma basis_singleton_iff
{R M : Type*} [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M]
(ι : Type*) [unique ι] :
nonempty (basis ι R M) ↔ ∃ x ≠ 0, ∀ y : M, ∃ r : R, r • x = y :=
begin
fsplit,
{ rintro ⟨b⟩,
refine ⟨b default, b.linear_independent.ne_zero _, _⟩,
simpa [span_singleton_eq_top_iff, set.range_unique] using b.span_eq },
{ rintro ⟨x, nz, w⟩,
refine ⟨of_repr $ linear_equiv.symm
{ to_fun := λ f, f default • x,
inv_fun := λ y, finsupp.single default (w y).some,
left_inv := λ f, finsupp.unique_ext _,
right_inv := λ y, _,
map_add' := λ y z, _,
map_smul' := λ c y, _ }⟩,
{ rw [finsupp.add_apply, add_smul] },
{ rw [finsupp.smul_apply, smul_assoc], simp },
{ refine smul_left_injective _ nz _,
simp only [finsupp.single_eq_same],
exact (w (f default • x)).some_spec },
{ simp only [finsupp.single_eq_same],
exact (w y).some_spec } }
end
end singleton
section empty
variables (M)
/-- If `M` is a subsingleton and `ι` is empty, this is the unique `ι`-indexed basis for `M`. -/
protected def empty [subsingleton M] [is_empty ι] : basis ι R M :=
of_repr 0
instance empty_unique [subsingleton M] [is_empty ι] : unique (basis ι R M) :=
{ default := basis.empty M, uniq := λ ⟨x⟩, congr_arg of_repr $ subsingleton.elim _ _ }
end empty
end basis
section fintype
open basis
open fintype
variables [fintype ι] (b : basis ι R M)
/-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`.
-/
def basis.equiv_fun : M ≃ₗ[R] (ι → R) :=
linear_equiv.trans b.repr
({ to_fun := coe_fn,
map_add' := finsupp.coe_add,
map_smul' := finsupp.coe_smul,
..finsupp.equiv_fun_on_finite } : (ι →₀ R) ≃ₗ[R] (ι → R))
/-- A module over a finite ring that admits a finite basis is finite. -/
def module.fintype_of_fintype (b : basis ι R M) [fintype R] : fintype M :=
by haveI := classical.dec_eq ι; exact
fintype.of_equiv _ b.equiv_fun.to_equiv.symm
theorem module.card_fintype (b : basis ι R M) [fintype R] [fintype M] :
card M = (card R) ^ (card ι) :=
by classical; exact
calc card M = card (ι → R) : card_congr b.equiv_fun.to_equiv
... = card R ^ card ι : card_fun
/-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps
a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/
@[simp] lemma basis.equiv_fun_symm_apply (x : ι → R) :
b.equiv_fun.symm x = ∑ i, x i • b i :=
by simp [basis.equiv_fun, finsupp.total_apply, finsupp.sum_fintype]
@[simp]
lemma basis.equiv_fun_apply (u : M) : b.equiv_fun u = b.repr u := rfl
@[simp] lemma basis.map_equiv_fun (f : M ≃ₗ[R] M') :
(b.map f).equiv_fun = f.symm.trans b.equiv_fun :=
rfl
lemma basis.sum_equiv_fun (u : M) : ∑ i, b.equiv_fun u i • b i = u :=
begin
conv_rhs { rw ← b.total_repr u },
simp [finsupp.total_apply, finsupp.sum_fintype, b.equiv_fun_apply]
end
lemma basis.sum_repr (u : M) : ∑ i, b.repr u i • b i = u :=
b.sum_equiv_fun u
@[simp]
lemma basis.equiv_fun_self [decidable_eq ι] (i j : ι) :
b.equiv_fun (b i) j = if i = j then 1 else 0 :=
by { rw [b.equiv_fun_apply, b.repr_self_apply] }
lemma basis.repr_sum_self (c : ι → R) : ⇑(b.repr (∑ i, c i • b i)) = c :=
begin
ext j,
simp only [map_sum, linear_equiv.map_smul, repr_self, finsupp.smul_single, smul_eq_mul,
mul_one, finset.sum_apply'],
rw [finset.sum_eq_single j, finsupp.single_eq_same],
{ rintros i - hi, exact finsupp.single_eq_of_ne hi },
{ intros, have := finset.mem_univ j, contradiction }
end
/-- Define a basis by mapping each vector `x : M` to its coordinates `e x : ι → R`,
as long as `ι` is finite. -/
def basis.of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : basis ι R M :=
basis.of_repr $ e.trans $ linear_equiv.symm $ finsupp.linear_equiv_fun_on_finite R R ι
@[simp] lemma basis.of_equiv_fun_repr_apply (e : M ≃ₗ[R] (ι → R)) (x : M) (i : ι) :
(basis.of_equiv_fun e).repr x i = e x i := rfl
@[simp] lemma basis.coe_of_equiv_fun [decidable_eq ι] (e : M ≃ₗ[R] (ι → R)) :
(basis.of_equiv_fun e : ι → M) = λ i, e.symm (function.update 0 i 1) :=
funext $ λ i, e.injective $ funext $ λ j,
by simp [basis.of_equiv_fun, ←finsupp.single_eq_pi_single, finsupp.single_eq_update]
@[simp] lemma basis.of_equiv_fun_equiv_fun
(v : basis ι R M) : basis.of_equiv_fun v.equiv_fun = v :=
begin
classical,
ext j,
simp only [basis.equiv_fun_symm_apply, basis.coe_of_equiv_fun],
simp_rw [function.update_apply, ite_smul],
simp only [finset.mem_univ, if_true, pi.zero_apply, one_smul, finset.sum_ite_eq', zero_smul],
end
variables (S : Type*) [semiring S] [module S M']
variables [smul_comm_class R S M']
@[simp] theorem basis.constr_apply_fintype (f : ι → M') (x : M) :
(b.constr S f : M → M') x = ∑ i, (b.equiv_fun x i) • f i :=
by simp [b.constr_apply, b.equiv_fun_apply, finsupp.sum_fintype]
/-- If the submodule `P` has a finite basis,
`x ∈ P` iff it is a linear combination of basis vectors. -/
lemma basis.mem_submodule_iff' {P : submodule R M} (b : basis ι R P) {x : M} :
x ∈ P ↔ ∃ (c : ι → R), x = ∑ i, c i • b i :=
b.mem_submodule_iff.trans $ finsupp.equiv_fun_on_finite.exists_congr_left.trans $ exists_congr $
λ c, by simp [finsupp.sum_fintype]
lemma basis.coord_equiv_fun_symm (i : ι) (f : ι → R) : b.coord i (b.equiv_fun.symm f) = f i :=
b.coord_repr_symm i (finsupp.equiv_fun_on_finite.symm f)
end fintype
end module
section comm_semiring
namespace basis
variables [comm_semiring R]
variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M']
variables (b : basis ι R M) (b' : basis ι' R M')
/-- If `b` is a basis for `M` and `b'` a basis for `M'`,
and `f`, `g` form a bijection between the basis vectors,
`b.equiv' b' f g hf hg hgf hfg` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `f (b i)`.
-/
def equiv' (f : M → M') (g : M' → M)
(hf : ∀ i, f (b i) ∈ range b') (hg : ∀ i, g (b' i) ∈ range b)
(hgf : ∀i, g (f (b i)) = b i) (hfg : ∀i, f (g (b' i)) = b' i) :
M ≃ₗ[R] M' :=
{ inv_fun := b'.constr R (g ∘ b'),
left_inv :=
have (b'.constr R (g ∘ b')).comp (b.constr R (f ∘ b)) = linear_map.id,
from (b.ext $ λ i, exists.elim (hf i)
(λ i' hi', by rw [linear_map.comp_apply, b.constr_basis, function.comp_apply, ← hi',
b'.constr_basis, function.comp_apply, hi', hgf, linear_map.id_apply])),
λ x, congr_arg (λ (h : M →ₗ[R] M), h x) this,
right_inv :=
have (b.constr R (f ∘ b)).comp (b'.constr R (g ∘ b')) = linear_map.id,
from (b'.ext $ λ i, exists.elim (hg i)
(λ i' hi', by rw [linear_map.comp_apply, b'.constr_basis, function.comp_apply, ← hi',
b.constr_basis, function.comp_apply, hi', hfg, linear_map.id_apply])),
λ x, congr_arg (λ (h : M' →ₗ[R] M'), h x) this,
.. b.constr R (f ∘ b) }
@[simp] lemma equiv'_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι) :
b.equiv' b' f g hf hg hgf hfg (b i) = f (b i) :=
b.constr_basis R _ _
@[simp] lemma equiv'_symm_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι') :
(b.equiv' b' f g hf hg hgf hfg).symm (b' i) = g (b' i) :=
b'.constr_basis R _ _
lemma sum_repr_mul_repr {ι'} [fintype ι'] (b' : basis ι' R M) (x : M) (i : ι) :
∑ (j : ι'), b.repr (b' j) i * b'.repr x j = b.repr x i :=
begin
conv_rhs { rw [← b'.sum_repr x] },
simp_rw [linear_equiv.map_sum, linear_equiv.map_smul, finset.sum_apply'],
refine finset.sum_congr rfl (λ j _, _),
rw [finsupp.smul_apply, smul_eq_mul, mul_comm]
end
end basis
end comm_semiring
section module
open linear_map
variables {v : ι → M}
variables [ring R] [comm_ring R₂] [add_comm_group M] [add_comm_group M'] [add_comm_group M'']
variables [module R M] [module R₂ M] [module R M'] [module R M'']
variables {c d : R} {x y : M}
variables (b : basis ι R M)
namespace basis
/--
Any basis is a maximal linear independent set.
-/
lemma maximal [nontrivial R] (b : basis ι R M) : b.linear_independent.maximal :=
λ w hi h,
begin
-- If `range w` is strictly bigger than `range b`,
apply le_antisymm h,
-- then choose some `x ∈ range w \ range b`,
intros x p,
by_contradiction q,
-- and write it in terms of the basis.
have e := b.total_repr x,
-- This then expresses `x` as a linear combination
-- of elements of `w` which are in the range of `b`,
let u : ι ↪ w := ⟨λ i, ⟨b i, h ⟨i, rfl⟩⟩, λ i i' r,
b.injective (by simpa only [subtype.mk_eq_mk] using r)⟩,
have r : ∀ i, b i = u i := λ i, rfl,
simp_rw [finsupp.total_apply, r] at e,
change (b.repr x).sum (λ (i : ι) (a : R), (λ (x : w) (r : R), r • (x : M)) (u i) a) =
((⟨x, p⟩ : w) : M) at e,
rw [←finsupp.sum_emb_domain, ←finsupp.total_apply] at e,
-- Now we can contradict the linear independence of `hi`
refine hi.total_ne_of_not_mem_support _ _ e,
simp only [finset.mem_map, finsupp.support_emb_domain],
rintro ⟨j, -, W⟩,
simp only [embedding.coe_fn_mk, subtype.mk_eq_mk, ←r] at W,
apply q ⟨j, W⟩,
end
section mk
variables (hli : linear_independent R v) (hsp : ⊤ ≤ span R (range v))
/-- A linear independent family of vectors spanning the whole module is a basis. -/
protected noncomputable def mk : basis ι R M :=
basis.of_repr
{ inv_fun := finsupp.total _ _ _ v,
left_inv := λ x, hli.total_repr ⟨x, _⟩,
right_inv := λ x, hli.repr_eq rfl,
.. hli.repr.comp (linear_map.id.cod_restrict _ (λ h, hsp submodule.mem_top)) }
@[simp] lemma mk_repr :
(basis.mk hli hsp).repr x = hli.repr ⟨x, hsp submodule.mem_top⟩ :=
rfl
lemma mk_apply (i : ι) : basis.mk hli hsp i = v i :=
show finsupp.total _ _ _ v _ = v i, by simp
@[simp] lemma coe_mk : ⇑(basis.mk hli hsp) = v :=
funext (mk_apply _ _)
variables {hli hsp}
/-- Given a basis, the `i`th element of the dual basis evaluates to 1 on the `i`th element of the
basis. -/
lemma mk_coord_apply_eq (i : ι) :
(basis.mk hli hsp).coord i (v i) = 1 :=
show hli.repr ⟨v i, submodule.subset_span (mem_range_self i)⟩ i = 1,
by simp [hli.repr_eq_single i]
/-- Given a basis, the `i`th element of the dual basis evaluates to 0 on the `j`th element of the
basis if `j ≠ i`. -/
lemma mk_coord_apply_ne {i j : ι} (h : j ≠ i) :
(basis.mk hli hsp).coord i (v j) = 0 :=
show hli.repr ⟨v j, submodule.subset_span (mem_range_self j)⟩ i = 0,
by simp [hli.repr_eq_single j, h]
/-- Given a basis, the `i`th element of the dual basis evaluates to the Kronecker delta on the
`j`th element of the basis. -/
lemma mk_coord_apply [decidable_eq ι] {i j : ι} :
(basis.mk hli hsp).coord i (v j) = if j = i then 1 else 0 :=
begin
cases eq_or_ne j i,
{ simp only [h, if_true, eq_self_iff_true, mk_coord_apply_eq i], },
{ simp only [h, if_false, mk_coord_apply_ne h], },
end
end mk
section span
variables (hli : linear_independent R v)
/-- A linear independent family of vectors is a basis for their span. -/
protected noncomputable def span : basis ι R (span R (range v)) :=
basis.mk (linear_independent_span hli) $
begin
intros x _,
have h₁ : (coe : span R (range v) → M) '' set.range (λ i, subtype.mk (v i) _) = range v,
{ rw ← set.range_comp,
refl },
have h₂ : map (submodule.subtype (span R (range v)))
(span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v),
{ rw [← span_image, submodule.coe_subtype, h₁] },
have h₃ : (x : M) ∈ map (submodule.subtype (span R (range v)))
(span R (set.range (λ i, subtype.mk (v i) _))),
{ rw h₂, apply subtype.mem x },
rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩,
have h_x_eq_y : x = y,
{ rw [subtype.ext_iff, ← hy₂], simp },
rwa h_x_eq_y
end
protected lemma span_apply (i : ι) : (basis.span hli i : M) = v i :=
congr_arg (coe : span R (range v) → M) $ basis.mk_apply (linear_independent_span hli) _ i
end span
lemma group_smul_span_eq_top
{G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M]
[is_scalar_tower G R M] {v : ι → M} (hv : submodule.span R (set.range v) = ⊤) {w : ι → G} :
submodule.span R (set.range (w • v)) = ⊤ :=
begin
rw eq_top_iff,
intros j hj,
rw ← hv at hj,
rw submodule.mem_span at hj ⊢,
refine λ p hp, hj p (λ u hu, _),
obtain ⟨i, rfl⟩ := hu,
have : ((w i)⁻¹ • 1 : R) • w i • v i ∈ p := p.smul_mem ((w i)⁻¹ • 1 : R) (hp ⟨i, rfl⟩),
rwa [smul_one_smul, inv_smul_smul] at this,
end
/-- Given a basis `v` and a map `w` such that for all `i`, `w i` are elements of a group,
`group_smul` provides the basis corresponding to `w • v`. -/
def group_smul {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M]
[is_scalar_tower G R M] [smul_comm_class G R M] (v : basis ι R M) (w : ι → G) :
basis ι R M :=
@basis.mk ι R M (w • v) _ _ _
(v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq).ge
lemma group_smul_apply {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M]
[is_scalar_tower G R M] [smul_comm_class G R M] {v : basis ι R M} {w : ι → G} (i : ι) :
v.group_smul w i = (w • v : ι → M) i :=
mk_apply
(v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq).ge i
lemma units_smul_span_eq_top {v : ι → M} (hv : submodule.span R (set.range v) = ⊤)
{w : ι → Rˣ} : submodule.span R (set.range (w • v)) = ⊤ :=
group_smul_span_eq_top hv
/-- Given a basis `v` and a map `w` such that for all `i`, `w i` is a unit, `smul_of_is_unit`
provides the basis corresponding to `w • v`. -/
def units_smul (v : basis ι R M) (w : ι → Rˣ) :
basis ι R M :=
@basis.mk ι R M (w • v) _ _ _
(v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq).ge
lemma units_smul_apply {v : basis ι R M} {w : ι → Rˣ} (i : ι) :
v.units_smul w i = w i • v i :=
mk_apply
(v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq).ge i
@[simp] lemma coord_units_smul (e : basis ι R₂ M) (w : ι → R₂ˣ) (i : ι) :
(e.units_smul w).coord i = (w i)⁻¹ • e.coord i :=
begin
classical,
apply e.ext,
intros j,
transitivity ((e.units_smul w).coord i) ((w j)⁻¹ • (e.units_smul w) j),
{ congr,
simp [basis.units_smul, ← mul_smul], },
simp only [basis.coord_apply, linear_map.smul_apply, basis.repr_self, units.smul_def,
smul_hom_class.map_smul, finsupp.single_apply],
split_ifs with h h,
{ simp [h] },
{ simp }
end
@[simp] lemma repr_units_smul (e : basis ι R₂ M) (w : ι → R₂ˣ) (v : M) (i : ι) :
(e.units_smul w).repr v i = (w i)⁻¹ • e.repr v i :=
congr_arg (λ f : M →ₗ[R₂] R₂, f v) (e.coord_units_smul w i)
/-- A version of `smul_of_units` that uses `is_unit`. -/
def is_unit_smul (v : basis ι R M) {w : ι → R} (hw : ∀ i, is_unit (w i)):
basis ι R M :=
units_smul v (λ i, (hw i).unit)
lemma is_unit_smul_apply {v : basis ι R M} {w : ι → R} (hw : ∀ i, is_unit (w i)) (i : ι) :
v.is_unit_smul hw i = w i • v i :=
units_smul_apply i
section fin
/-- Let `b` be a basis for a submodule `N` of `M`. If `y : M` is linear independent of `N`
and `y` and `N` together span the whole of `M`, then there is a basis for `M`
whose basis vectors are given by `fin.cons y b`. -/
noncomputable def mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N)
(hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0)
(hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) :
basis (fin (n + 1)) R M :=
have span_b : submodule.span R (set.range (N.subtype ∘ b)) = N,
{ rw [set.range_comp, submodule.span_image, b.span_eq, submodule.map_subtype_top] },
@basis.mk _ _ _ (fin.cons y (N.subtype ∘ b) : fin (n + 1) → M) _ _ _
((b.linear_independent.map' N.subtype (submodule.ker_subtype _)) .fin_cons' _ _ $
by { rintros c ⟨x, hx⟩ hc, rw span_b at hx, exact hli c x hx hc })
(λ x _, by { rw [fin.range_cons, submodule.mem_span_insert', span_b], exact hsp x })
@[simp] lemma coe_mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N)
(hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0)
(hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) :
(mk_fin_cons y b hli hsp : fin (n + 1) → M) = fin.cons y (coe ∘ b) :=
coe_mk _ _
/-- Let `b` be a basis for a submodule `N ≤ O`. If `y ∈ O` is linear independent of `N`
and `y` and `N` together span the whole of `O`, then there is a basis for `O`
whose basis vectors are given by `fin.cons y b`. -/
noncomputable def mk_fin_cons_of_le {n : ℕ} {N O : submodule R M}
(y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O)
(hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0)
(hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) :
basis (fin (n + 1)) R O :=
mk_fin_cons ⟨y, yO⟩ (b.map (submodule.comap_subtype_equiv_of_le hNO).symm)
(λ c x hc hx, hli c x (submodule.mem_comap.mp hc) (congr_arg coe hx))
(λ z, hsp z z.2)
@[simp] lemma coe_mk_fin_cons_of_le {n : ℕ} {N O : submodule R M}
(y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O)
(hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0)
(hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) :
(mk_fin_cons_of_le y yO b hNO hli hsp : fin (n + 1) → O) =
fin.cons ⟨y, yO⟩ (submodule.of_le hNO ∘ b) :=
coe_mk_fin_cons _ _ _ _
/-- The basis of `R × R` given by the two vectors `(1, 0)` and `(0, 1)`. -/
protected def fin_two_prod (R : Type*) [semiring R] : basis (fin 2) R (R × R) :=
basis.of_equiv_fun (linear_equiv.fin_two_arrow R R).symm
@[simp] lemma fin_two_prod_zero (R : Type*) [semiring R] : basis.fin_two_prod R 0 = (1, 0) :=
by simp [basis.fin_two_prod]
@[simp] lemma fin_two_prod_one (R : Type*) [semiring R] : basis.fin_two_prod R 1 = (0, 1) :=
by simp [basis.fin_two_prod]
@[simp] lemma coe_fin_two_prod_repr {R : Type*} [semiring R] (x : R × R) :
⇑((basis.fin_two_prod R).repr x) = ![x.fst, x.snd] :=
rfl
end fin
end basis
end module
section induction
variables [ring R] [is_domain R]
variables [add_comm_group M] [module R M] {b : ι → M}
/-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent
element to a submodule. -/
def submodule.induction_on_rank_aux (b : basis ι R M) (P : submodule R M → Sort*)
(ih : ∀ (N : submodule R M),
(∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N)
(n : ℕ) (N : submodule R M)
(rank_le : ∀ {m : ℕ} (v : fin m → N),
linear_independent R (coe ∘ v : fin m → M) → m ≤ n) :
P N :=
begin
haveI : decidable_eq M := classical.dec_eq M,
have Pbot : P ⊥,
{ apply ih,
intros N N_le x x_mem x_ortho,
exfalso,
simpa using x_ortho 1 0 N.zero_mem },
induction n with n rank_ih generalizing N,
{ suffices : N = ⊥,
{ rwa this },
apply eq_bot_of_rank_eq_zero b _ (λ m v hv, le_zero_iff.mp (rank_le v hv)) },
apply ih,
intros N' N'_le x x_mem x_ortho,
apply rank_ih,
intros m v hli,
refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _),
convert hli.fin_cons' x _ _,
{ ext i, refine fin.cases _ _ i; simp },
{ intros c y hcy,
refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy,
rintros _ ⟨z, rfl⟩,
exact (v z).2 }
end
end induction
section division_ring
variables [division_ring K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V']
variables {v : ι → V} {s t : set V} {x y z : V}
include K
open submodule
namespace basis
section exists_basis
/-- If `s` is a linear independent set of vectors, we can extend it to a basis. -/
noncomputable def extend (hs : linear_independent K (coe : s → V)) :
basis _ K V :=
basis.mk
(@linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ (hs.linear_independent_extend _))
(set_like.coe_subset_coe.mp $ by simpa using hs.subset_span_extend (subset_univ s))
lemma extend_apply_self (hs : linear_independent K (coe : s → V))
(x : hs.extend _) :
basis.extend hs x = x :=
basis.mk_apply _ _ _
@[simp] lemma coe_extend (hs : linear_independent K (coe : s → V)) :
⇑(basis.extend hs) = coe :=
funext (extend_apply_self hs)
lemma range_extend (hs : linear_independent K (coe : s → V)) :
range (basis.extend hs) = hs.extend (subset_univ _) :=
by rw [coe_extend, subtype.range_coe_subtype, set_of_mem_eq]
/-- If `v` is a linear independent family of vectors, extend it to a basis indexed by a sum type. -/
noncomputable def sum_extend (hs : linear_independent K v) :
basis (ι ⊕ _) K V :=
let s := set.range v,
e : ι ≃ s := equiv.of_injective v hs.injective,
b := hs.to_subtype_range.extend (subset_univ (set.range v)) in
(basis.extend hs.to_subtype_range).reindex $ equiv.symm $
calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _)
... ≃ b :
by haveI := classical.dec_pred (∈ s); exact
equiv.set.sum_diff_subset (hs.to_subtype_range.subset_extend _)
lemma subset_extend {s : set V} (hs : linear_independent K (coe : s → V)) :
s ⊆ hs.extend (set.subset_univ _) :=
hs.subset_extend _
section
variables (K V)
/-- A set used to index `basis.of_vector_space`. -/
noncomputable def of_vector_space_index : set V :=
(linear_independent_empty K V).extend (subset_univ _)
/-- Each vector space has a basis. -/
noncomputable def of_vector_space : basis (of_vector_space_index K V) K V :=
basis.extend (linear_independent_empty K V)
lemma of_vector_space_apply_self (x : of_vector_space_index K V) :
of_vector_space K V x = x :=
basis.mk_apply _ _ _
@[simp] lemma coe_of_vector_space :
⇑(of_vector_space K V) = coe :=
funext (λ x, of_vector_space_apply_self K V x)
lemma of_vector_space_index.linear_independent :
linear_independent K (coe : of_vector_space_index K V → V) :=
by { convert (of_vector_space K V).linear_independent, ext x, rw of_vector_space_apply_self }
lemma range_of_vector_space :
range (of_vector_space K V) = of_vector_space_index K V :=
range_extend _
lemma exists_basis : ∃ s : set V, nonempty (basis s K V) :=
⟨of_vector_space_index K V, ⟨of_vector_space K V⟩⟩
end
end exists_basis
end basis
open fintype
variables (K V)
theorem vector_space.card_fintype [fintype K] [fintype V] :
∃ n : ℕ, card V = (card K) ^ n :=
by classical; exact
⟨card (basis.of_vector_space_index K V), module.card_fintype (basis.of_vector_space K V)⟩
section atoms_of_submodule_lattice
variables {K V}
/-- For a module over a division ring, the span of a nonzero element is an atom of the
lattice of submodules. -/
lemma nonzero_span_atom (v : V) (hv : v ≠ 0) : is_atom (span K {v} : submodule K V) :=
begin
split,
{ rw submodule.ne_bot_iff, exact ⟨v, ⟨mem_span_singleton_self v, hv⟩⟩ },
{ intros T hT, by_contra, apply hT.2,
change (span K {v}) ≤ T,
simp_rw [span_singleton_le_iff_mem, ← ne.def, submodule.ne_bot_iff] at *,
rcases h with ⟨s, ⟨hs, hz⟩⟩,
cases (mem_span_singleton.1 (hT.1 hs)) with a ha,
have h : a ≠ 0, by { intro h, rw [h, zero_smul] at ha, exact hz ha.symm },
apply_fun (λ x, a⁻¹ • x) at ha,
simp_rw [← mul_smul, inv_mul_cancel h, one_smul, ha] at *, exact smul_mem T _ hs},
end
/-- The atoms of the lattice of submodules of a module over a division ring are the
submodules equal to the span of a nonzero element of the module. -/
lemma atom_iff_nonzero_span (W : submodule K V) :
is_atom W ↔ ∃ (v : V) (hv : v ≠ 0), W = span K {v} :=
begin
refine ⟨λ h, _, λ h, _ ⟩,
{ cases h with hbot h,
rcases ((submodule.ne_bot_iff W).1 hbot) with ⟨v, ⟨hW, hv⟩⟩,
refine ⟨v, ⟨hv, _⟩⟩,
by_contra heq,
specialize h (span K {v}),
rw [span_singleton_eq_bot, lt_iff_le_and_ne] at h,
exact hv (h ⟨(span_singleton_le_iff_mem v W).2 hW, ne.symm heq⟩) },
{ rcases h with ⟨v, ⟨hv, rfl⟩⟩, exact nonzero_span_atom v hv },
end
/-- The lattice of submodules of a module over a division ring is atomistic. -/
instance : is_atomistic (submodule K V) :=
{ eq_Sup_atoms :=
begin
intro W,
use {T : submodule K V | ∃ (v : V) (hv : v ∈ W) (hz : v ≠ 0), T = span K {v}},
refine ⟨submodule_eq_Sup_le_nonzero_spans W, _⟩,
rintros _ ⟨w, ⟨_, ⟨hw, rfl⟩⟩⟩, exact nonzero_span_atom w hw
end }
end atoms_of_submodule_lattice
variables {K V}
lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V')
(hf_inj : f.ker = ⊥) : ∃g:V' →ₗ[K] V, g.comp f = linear_map.id :=
begin
let B := basis.of_vector_space_index K V,
let hB := basis.of_vector_space K V,
have hB₀ : _ := hB.linear_independent.to_subtype_range,
have : linear_independent K (λ x, x : f '' B → V'),
{ have h₁ : linear_independent K (λ (x : ↥(⇑f '' range (basis.of_vector_space _ _))), ↑x) :=
@linear_independent.image_subtype _ _ _ _ _ _ _ _ _ f hB₀
(show disjoint _ _, by simp [hf_inj]),
rwa [basis.range_of_vector_space K V] at h₁ },
let C := this.extend (subset_univ _),
have BC := this.subset_extend (subset_univ _),
let hC := basis.extend this,
haveI : inhabited V := ⟨0⟩,
refine ⟨hC.constr ℕ (C.restrict (inv_fun f)), hB.ext (λ b, _)⟩,
rw image_subset_iff at BC,
have fb_eq : f b = hC ⟨f b, BC b.2⟩,
{ change f b = basis.extend this _,
rw [basis.extend_apply_self, subtype.coe_mk] },
dsimp [hB],
rw [basis.of_vector_space_apply_self, fb_eq, hC.constr_basis],
exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _
end
lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q :=
let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
instance module.submodule.complemented_lattice : complemented_lattice (submodule K V) :=
⟨submodule.exists_is_compl⟩
lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V')
(hf_surj : f.range = ⊤) : ∃g:V' →ₗ[K] V, f.comp g = linear_map.id :=
begin
let C := basis.of_vector_space_index K V',
let hC := basis.of_vector_space K V',
haveI : inhabited V := ⟨0⟩,
use hC.constr ℕ (C.restrict (inv_fun f)),
refine hC.ext (λ c, _),
rw [linear_map.comp_apply, hC.constr_basis],
simp [right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c]
end
/-- Any linear map `f : p →ₗ[K] V'` defined on a subspace `p` can be extended to the whole
space. -/
lemma linear_map.exists_extend {p : submodule K V} (f : p →ₗ[K] V') :
∃ g : V →ₗ[K] V', g.comp p.subtype = f :=
let ⟨g, hg⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in
⟨f.comp g, by rw [linear_map.comp_assoc, hg, f.comp_id]⟩
open submodule linear_map
/-- If `p < ⊤` is a subspace of a vector space `V`, then there exists a nonzero linear map
`f : V →ₗ[K] K` such that `p ≤ ker f`. -/
lemma submodule.exists_le_ker_of_lt_top (p : submodule K V) (hp : p < ⊤) :
∃ f ≠ (0 : V →ₗ[K] K), p ≤ ker f :=
begin
rcases set_like.exists_of_lt hp with ⟨v, -, hpv⟩, clear hp,
rcases (linear_pmap.sup_span_singleton ⟨p, 0⟩ v (1 : K) hpv).to_fun.exists_extend with ⟨f, hf⟩,
refine ⟨f, _, _⟩,
{ rintro rfl, rw [linear_map.zero_comp] at hf,
have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv 0 p.zero_mem 1,
simpa using (linear_map.congr_fun hf _).trans this },
{ refine λ x hx, mem_ker.2 _,
have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv x hx 0,
simpa using (linear_map.congr_fun hf _).trans this }
end
theorem quotient_prod_linear_equiv (p : submodule K V) :
nonempty (((V ⧸ p) × p) ≃ₗ[K] V) :=
let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $
((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans
(prod_equiv_of_is_compl q p hq.symm)
end division_ring
section restrict_scalars
variables {S : Type*} [comm_ring R] [ring S] [nontrivial S] [add_comm_group M]
variables [algebra R S] [module S M] [module R M]
variables [is_scalar_tower R S M] [no_zero_smul_divisors R S] (b : basis ι S M)
variables (R)
open submodule
/-- Let `b` be a `S`-basis of `M`. Let `R` be a comm_ring such that `algebra R S` with no zero
smul divisors, then the submodule of `M` spanned by `b` over `R` admits `b` as a `R`-basis. -/
noncomputable def basis.restrict_scalars : basis ι R (span R (set.range b)) :=
basis.span (b.linear_independent.restrict_scalars (smul_left_injective R one_ne_zero))
@[simp]
lemma basis.restrict_scalars_apply (i : ι) : (b.restrict_scalars R i : M) = b i :=
by simp only [basis.restrict_scalars, basis.span_apply]
@[simp]
lemma basis.restrict_scalars_repr_apply (m : span R (set.range b)) (i : ι) :
algebra_map R S ((b.restrict_scalars R).repr m i) = b.repr m i :=
begin
suffices : finsupp.map_range.linear_map (algebra.linear_map R S) ∘ₗ
(b.restrict_scalars R).repr.to_linear_map
= ((b.repr : M →ₗ[S] (ι →₀ S)).restrict_scalars R).dom_restrict _,
{ exact finsupp.congr_fun (linear_map.congr_fun this m) i, },
refine basis.ext (b.restrict_scalars R) (λ _, _),
simp only [linear_map.coe_comp, linear_equiv.coe_to_linear_map, function.comp_app, map_one,
basis.repr_self, finsupp.map_range.linear_map_apply, finsupp.map_range_single,
algebra.linear_map_apply, linear_map.dom_restrict_apply, linear_equiv.coe_coe,
basis.restrict_scalars_apply, linear_map.coe_restrict_scalars_eq_coe],
end
/-- Let `b` be a `S`-basis of `M`. Then `m : M` lies in the `R`-module spanned by `b` iff all the
coordinates of `m` on the basis `b` are in `R` (see `basis.mem_span` for the case `R = S`). -/
lemma basis.mem_span_iff_repr_mem (m : M) :
m ∈ span R (set.range b) ↔ ∀ i, b.repr m i ∈ set.range (algebra_map R S) :=
begin
refine ⟨λ hm i, ⟨(b.restrict_scalars R).repr ⟨m, hm⟩ i,
(b.restrict_scalars_repr_apply R ⟨m, hm⟩ i)⟩, λ h, _⟩,
rw [← b.total_repr m, finsupp.total_apply S _],
refine sum_mem (λ i _, _),
obtain ⟨_, h⟩ := h i,
simp_rw [← h, algebra_map_smul],
exact smul_mem _ _ (subset_span (set.mem_range_self i)),
end
end restrict_scalars
|
64314e39d2407d315d96d72b1a9f488d5ca26f3f | 3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a | /src/combinatorics/simplicial_complex/boundary.lean | 40dabe665e9d7c8b705f26f5364aea502108bdf5 | [] | no_license | mmasdeu/brouwerfixedpoint | 684d712c982c6a8b258b4e2c6b2eab923f2f1289 | 548270f79ecf12d7e20a256806ccb9fcf57b87e2 | refs/heads/main | 1,690,539,793,996 | 1,631,801,831,000 | 1,631,801,831,000 | 368,139,809 | 4 | 3 | null | 1,624,453,250,000 | 1,621,246,034,000 | Lean | UTF-8 | Lean | false | false | 12,767 | 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 combinatorics.simplicial_complex.link
import combinatorics.simplicial_complex.subdivision
namespace affine
open set
variables {m n : ℕ} {E : Type*} [normed_group E] [normed_space ℝ E] {S : simplicial_complex E}
{X Y : finset E} {A : set (finset E)} [semilattice_inf_bot (finset E)] [decidable_eq E]
def simplicial_complex.on_boundary (S : simplicial_complex E) (X : finset E) :
Prop :=
∃ (Z ∈ S.faces), X ⊂ Z ∧ ∀ {Z'}, Z' ∈ S.faces → X ⊂ Z' → Z = Z'
def simplicial_complex.boundary (S : simplicial_complex E) :
simplicial_complex E :=
simplicial_complex.of_surcomplex
{X | ∃ Y ∈ S.faces, X ⊆ Y ∧ S.on_boundary Y}
(λ X ⟨Y, hY, hXY, _⟩, S.down_closed hY hXY)
(λ X W ⟨Y, hY, hXY, Z⟩ hWX, ⟨Y, hY, subset.trans hWX hXY, Z⟩)
lemma boundary_empty (hS : S.faces = ∅) :
S.boundary.faces = ∅ :=
begin
unfold simplicial_complex.boundary,
simp,
rw hS,
simp,
end
lemma boundary_singleton_empty (hS : S.faces = {∅}) :
S.boundary.faces = ∅ :=
begin
ext X,
unfold simplicial_complex.boundary simplicial_complex.on_boundary,
simp,
rw hS,
rintro _ (rfl : _ = ∅) XY Y (rfl : _ = ∅) t,
apply (t.2 (empty_subset _)).elim,
end
lemma boundary_subset :
S.boundary.faces ⊆ S.faces :=
λ X ⟨Y, hY, hXY, _⟩, S.down_closed hY hXY
lemma mem_boundary_iff_subset_unique_facet :
X ∈ S.boundary.faces ↔ ∃ {Y Z}, Y ∈ S.faces ∧ Z ∈ S.facets ∧ X ⊆ Y ∧ Y ⊂ Z ∧
∀ {Z'}, Z' ∈ S.faces → Y ⊂ Z' → Z = Z' :=
begin
split,
{ rintro ⟨Y, hY, hXY, Z, hZ, hYZ, hZunique⟩,
suffices hZ' : Z ∈ S.facets,
{ exact ⟨Y, Z, hY, hZ', hXY, hYZ, (λ Z', hZunique)⟩ },
use hZ,
rintro Z' hZ' hZZ',
exact hZunique hZ' ⟨finset.subset.trans hYZ.1 hZZ',
(λ hZ'Y, hYZ.2 (finset.subset.trans hZZ' hZ'Y))⟩ },
{ rintro ⟨Y, Z, hY, hZ, hXY, hYZ, hZunique⟩,
refine ⟨Y, hY, hXY, Z, hZ.1, hYZ, λ Z', hZunique⟩ }
end
lemma facets_disjoint_boundary :
disjoint S.facets S.boundary.faces :=
begin
rintro X ⟨⟨hX, hXunique⟩, ⟨Y, hY, hXY, Z, hZ, hYZ, hZunique⟩⟩,
apply hYZ.2,
rw ← hXunique hZ (subset.trans hXY hYZ.1),
exact hXY,
end
lemma boundary_facet_iff :
X ∈ S.boundary.facets ↔ S.on_boundary X :=
begin
split,
{ rintro ⟨⟨Y, hY, XY, Z, hZ, hYZ, hZunique⟩, hXmax⟩,
refine ⟨Z, hZ, finset.ssubset_of_subset_of_ssubset XY hYZ, λ Z', _⟩,
have hX' : Y ∈ S.boundary.faces,
{ refine ⟨_, hY, subset.refl _, _, hZ, hYZ, λ Z', hZunique⟩ },
have hXX' := hXmax hX' XY,
subst hXX',
apply hZunique },
{ rintro ⟨Y, hY, hXY, hYunique⟩,
refine ⟨⟨X, S.down_closed hY hXY.1, subset.refl _, _, hY, hXY, λ Y', hYunique⟩, _⟩,
rintro V ⟨W, hW, hVW, Z, hZ, hWZ, hZunique⟩ hXV,
apply finset.subset.antisymm hXV,
classical,
by_contra hVX,
have := hYunique (S.down_closed hW hVW) ⟨hXV, hVX⟩,
subst this,
have := hYunique hZ ⟨subset.trans hXV (subset.trans hVW hWZ.1),
λ hZX, hWZ.2 (subset.trans hZX (subset.trans hXV hVW))⟩,
subst this,
exact hWZ.2 hVW,
}
end
lemma boundary_facet_iff' :
X ∈ S.boundary.facets ↔ ∃ {Y}, Y ∈ S.facets ∧ X ⊂ Y ∧ ∀ {Y'}, Y' ∈ S.faces → X ⊂ Y' → Y = Y' :=
begin
rw boundary_facet_iff,
split,
{ rintro ⟨Y, hY, hXY, hYunique⟩,
have hY' : Y ∈ S.facets,
{ use hY,
rintro Y' hY' hYY',
exact hYunique hY' (finset.ssubset_of_ssubset_of_subset hXY hYY'),
},
exact ⟨Y, hY', hXY, (λ Y', hYunique)⟩ },
{ rintro ⟨Y, hY, hXY, hYunique⟩,
exact ⟨Y, hY.1, hXY, (λ Y', hYunique)⟩ }
end
lemma pure_boundary_of_pure (hS : S.pure_of n) :
S.boundary.pure_of (n - 1) :=
begin
rintro X hX,
obtain ⟨Y, hY, hXY, hYunique⟩ := boundary_facet_iff'.1 hX,
cases n,
{ apply nat.eq_zero_of_le_zero,
have hYcard : Y.card = 0 := hS hY,
rw ←hYcard,
exact le_of_lt (finset.card_lt_card hXY) },
have hYcard : Y.card = n.succ := hS hY,
have hXcard : X.card ≤ n,
{ have := finset.card_lt_card hXY,
rw hYcard at this,
exact nat.le_of_lt_succ this },
have : n - X.card + X.card ≤ Y.card,
{ rw [hS hY, nat.sub_add_cancel hXcard, nat.succ_eq_add_one],
linarith },
obtain ⟨W, hXW, hWY, hWcard⟩ := finset.exists_intermediate_set (n - X.card) this hXY.1,
rw nat.sub_add_cancel hXcard at hWcard,
have hW : W ∈ S.boundary.faces,
{ have hYW : ¬Y ⊆ W,
{ have hWYcard : W.card < Y.card,
{ rw [hWcard, hS hY, nat.succ_eq_add_one],
linarith },rintro hYW,
have : n.succ = n := by rw [← hS hY, ← hWcard,
finset.eq_of_subset_of_card_le hYW (le_of_lt hWYcard)],
exact nat.succ_ne_self n this },
refine ⟨W, S.down_closed (facets_subset hY) hWY, subset.refl W, Y, hY.1, ⟨hWY, hYW⟩, _⟩,
rintro Z hZ hWZ,
exact hYunique hZ ⟨subset.trans hXW hWZ.1, (λ hZX, hWZ.2 (finset.subset.trans hZX hXW))⟩ },
rw [nat.succ_sub_one, ←hWcard, hX.2 hW hXW],
end
lemma boundary_link :
S.boundary.link A = (S.link A).boundary :=
begin
ext V,
split,
{
rintro ⟨hVdisj, W, X, hW, ⟨Y, Z, hY, hZ, hXY, hYZ, hZunique⟩, hVX, hWX⟩,
use V,
split,
{
sorry
/-split,
exact (λ U hU, hVdisj hU),
exact ⟨W, Z, hW, facets_subset hZ, subset.trans hVX (subset.trans hXY hYZ.1),
subset.trans hWX (subset.trans hXY hYZ.1)⟩,-/
},
{
/-use subset.refl V,
use Z,
split,
{
sorry --waiting for link_facet_iff. May make this lemma require more assumptions
},
use ⟨finset.subset.trans hVX (finset.subset.trans hXY hYZ.1),
(λ hZV, hYZ.2 (finset.subset.trans hZV (finset.subset.trans hVX hXY)))⟩,
rintro U ⟨hUdisj, T, R, hT, hR, hUR, hTR⟩ hVU,
apply hZunique (S.down_closed hR hUR),-/
sorry
}
},
{
sorry
}
end
lemma boundary_boundary [finite_dimensional ℝ E] (hS : S.pure_of n) (hS' : ∀ {X}, X ∈ S.faces →
(X : finset E).card = n - 1 → equiv {Y | Y ∈ S.faces ∧ X ⊆ Y} (fin 2)) :
S.boundary.boundary.faces = ∅ :=
begin
rw ← facets_empty_iff_faces_empty,
apply eq_empty_of_subset_empty,
rintro V hV,
obtain ⟨W, hW, hVW, hWunique⟩ := boundary_facet_iff'.1 hV,
obtain ⟨X, hX, hXV, hXunique⟩ := boundary_facet_iff'.1 hW,
sorry
end
lemma boundary_mono {S₁ S₂ : simplicial_complex E} (hS : S₁ ≤ S₂) :
S₁.boundary ≤ S₂.boundary :=
begin
/-cases S₂.faces.eq_empty_or_nonempty with hS₂empty hS₂nonempty,
{
rw hS₂empty,
},
rw subdivision_iff_partition at ⊢ hS,-/
have hspace : S₁.boundary.space = S₂.boundary.space,
{
sorry
},
/-rw subdivision_iff_partition,
split,
{
sorry
},
use le_of_eq hspace,
rintro X₂ ⟨Y₂, Z₂, hY₂, hZ₂, hX₂Y₂, hY₂Z₂, hZ₂max⟩,
obtain ⟨hempty, hspace, hpartition⟩ := subdivision_iff_partition.1 hS,
obtain ⟨F, hF, hX₂F⟩ := hpartition (S₂.down_closed hY₂ hX₂Y₂),
use F, rw and.comm, use hX₂F,
rintro X₁ hX₁,-/
use hspace,
rintro X₁ ⟨Y₁, hY₁, hX₁Y₁, Z₁, hZ₁, hY₁Z₁, hZ₁max⟩,
cases X₁.eq_empty_or_nonempty with hX₁empty hX₁nonempty,
{
sorry},
obtain ⟨X₂, hX₂, hX₁X₂⟩ := (subdivision_iff_combi_interiors_subset_combi_interiors.1 hS).2
(S₁.down_closed hY₁ hX₁Y₁),
obtain ⟨Y₂, hY₂, hY₁Y₂⟩ := (subdivision_iff_combi_interiors_subset_combi_interiors.1 hS).2 hY₁,
obtain ⟨Z₂, hZ₂, hZ₁Z₂⟩ := (subdivision_iff_combi_interiors_subset_combi_interiors.1 hS).2 hZ₁,
obtain ⟨x, hxX₁⟩ := id hX₁nonempty,
refine ⟨X₂, ⟨Y₂, hY₂, _, Z₂, hZ₂, ⟨_, _⟩⟩,
convex_hull_subset_convex_hull_of_combi_interior_subset_combi_interior
(S₁.indep (S₁.down_closed hY₁ hX₁Y₁)) (S₂.indep hX₂) hX₁X₂⟩,
{ apply subset_of_combi_interior_inter_convex_hull_nonempty hX₂ hY₂,
obtain ⟨x, hxX₁⟩ := nonempty_combi_interior_of_nonempty (S₁.indep (S₁.down_closed hY₁ hX₁Y₁))
hX₁nonempty,
use [x, hX₁X₂ hxX₁],
apply convex_hull_subset_convex_hull_of_combi_interior_subset_combi_interior (S₁.indep hY₁)
(S₂.indep hY₂) hY₁Y₂,
exact convex_hull_mono hX₁Y₁ hxX₁.1 },
{ obtain ⟨y, hyY₁⟩ := nonempty_combi_interior_of_nonempty (S₁.indep hY₁) ⟨x, hX₁Y₁ hxX₁⟩,
split,
{ apply subset_of_combi_interior_inter_convex_hull_nonempty hY₂ hZ₂,
use [y, hY₁Y₂ hyY₁],
apply convex_hull_subset_convex_hull_of_combi_interior_subset_combi_interior (S₁.indep hZ₁)
(S₂.indep hZ₂) hZ₁Z₂,
exact convex_hull_mono hY₁Z₁.1 hyY₁.1 },
{ rintro hZ₂Y₂,
suffices hY₂Z₂ : ¬Y₂ ⊆ Z₂,
{ apply (hY₁Y₂ hyY₁).2,
rw mem_combi_frontier_iff,
use [Z₂, ⟨hZ₂Y₂, hY₂Z₂⟩],
apply convex_hull_subset_convex_hull_of_combi_interior_subset_combi_interior (S₁.indep hZ₁)
(S₂.indep hZ₂) hZ₁Z₂,
exact convex_hull_mono hY₁Z₁.1 hyY₁.1 },
rintro hY₂Z₂,
have := finset.subset.antisymm hY₂Z₂ hZ₂Y₂,
subst this,
suffices h : Y₁.card = Y₂.card,
{ have := finset.card_lt_card hY₁Z₁,
have := card_le_of_convex_hull_subset (S₁.indep hZ₁)
(convex_hull_subset_convex_hull_of_combi_interior_subset_combi_interior (S₁.indep hZ₁)
(S₂.indep hY₂) hZ₁Z₂),
linarith },
sorry
},
},
{
rintro Z' hZ' hY₂Z',
suffices hZ₁Z' : combi_interior Z₁ ⊆ combi_interior Z',
{
obtain ⟨z, hzZ₁⟩ := nonempty_combi_interior_of_nonempty (S₁.indep hZ₁) ⟨x, hY₁Z₁.1 (hX₁Y₁ hxX₁)⟩,
exact disjoint_interiors hZ₂ hZ' (hZ₁Z₂ hzZ₁) (hZ₁Z' hzZ₁),
},
sorry
}
end
--other attempt using subdivision_iff_partition
lemma boundary_mono' {S₁ S₂ : simplicial_complex E} (hS : S₁ ≤ S₂) :
S₁.boundary ≤ S₂.boundary :=
begin
rw subdivision_iff_partition,
obtain ⟨hempty, hspace, hpartition⟩ := subdivision_iff_partition.1 hS,
split,
sorry,
split,
sorry,
rintro X₂ hX₂,--rintro X₂ ⟨Y₂, hY₂, hX₂Y₂, Z₂, hZ₂, hY₂Z₂, hZ₂max⟩,
obtain ⟨F, hF, hXF⟩ := hpartition (boundary_subset hX₂),--obtain ⟨F, hF, hXF⟩ := hpartition (S₂.down_closed hY₂ hX₂Y₂),
use F,
rw and.comm,
use hXF,
rintro X₁ hX₁,
have hX₁X₂ : combi_interior X₁ ⊆ combi_interior X₂,
{ rw hXF,
exact subset_bUnion_of_mem hX₁ },
sorry
end
/--
A m-simplex is on the boundary of a full dimensional complex iff it belongs to exactly one cell.
Dull?
-/
lemma boundary_subcell_iff_one_surface (hS : S.full_dimensional) (hXcard : X.card = finite_dimensional.finrank ℝ E) :
X ∈ S.boundary.faces ↔ nat.card {Y | Y ∈ S.faces ∧ X ⊂ Y} = 1 :=
-- It's probably a bad idea to use `nat.card` since it's incredibly underdeveloped for doing
-- actual maths in
-- Does this lemma need you to assume locally finite (at X)? If so, the set you care about is a
-- subset of the set we know is finite, so we can convert to a finset and use normal card
begin
split,
{
rintro ⟨Y, hY, hXY, Z, hZ, hYZ, hZunique⟩,
have : X = Y,
{
sorry
},
sorry--rw nat.card_eq_fintype_card,
},
-- have aux_lemma : ∀ {a b : E}, a ≠ b → a ∉ X → b ∉ X → X ∪ {a} ∈ S.faces → X ∪ {b} ∈ S.faces →
-- ∃ w : E → ℝ, w a < 0 ∧ ∑ y in X ∪ {a}, w y = 1 ∧ (X ∪ {a}).center_mass w id = b,
-- {
-- sorry
-- },
sorry
end
/--
A m-simplex is not on the boundary of a full dimensional complex iff it belongs to exactly two
cells.
-/
lemma not_boundary_subcell_iff_two_surfaces (hS : S.full_dimensional) (hXcard : X.card = finite_dimensional.finrank ℝ E) :
X ∉ S.boundary.faces ↔ nat.card {Y | Y ∈ S.faces ∧ X ⊂ Y} = 2 :=
-- It's probably a bad idea to use `nat.card` since it's incredibly underdeveloped for doing
-- actual maths in
-- Does this lemma need you to assume locally finite (at X)? If so, the set you care about is a
-- subset of the set we know is finite, so we can convert to a finset and use normal card
begin
-- have aux_lemma : ∀ {a b : E}, a ≠ b → a ∉ X → b ∉ X → X ∪ {a} ∈ S.faces → X ∪ {b} ∈ S.faces →
-- ∃ w : E → ℝ, w a < 0 ∧ ∑ y in X ∪ {a}, w y = 1 ∧ (X ∪ {a}).center_mass w id = b,
-- {
-- sorry
-- },
sorry
end
end affine
|
454db86cfaa8276126edcb17f1d6280686b13659 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/analysis/normed_space/ball_action.lean | be948c62c24dff30fa519eba9a44c341db650a49 | [
"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 | 8,127 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Heather Macbeth
-/
import analysis.normed.field.unit_ball
import analysis.normed_space.basic
/-!
# Multiplicative actions of/on balls and spheres
Let `E` be a normed vector space over a normed field `𝕜`. In this file we define the following
multiplicative actions.
- The closed unit ball in `𝕜` acts on open balls and closed balls centered at `0` in `E`.
- The unit sphere in `𝕜` acts on open balls, closed balls, and spheres centered at `0` in `E`.
-/
open metric set
variables {𝕜 𝕜' E : Type*} [normed_field 𝕜] [normed_field 𝕜']
[seminormed_add_comm_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] {r : ℝ}
section closed_ball
instance mul_action_closed_ball_ball : mul_action (closed_ball (0 : 𝕜) 1) (ball (0 : E) r) :=
{ smul := λ c x, ⟨(c : 𝕜) • x, mem_ball_zero_iff.2 $
by simpa only [norm_smul, one_mul]
using mul_lt_mul' (mem_closed_ball_zero_iff.1 c.2) (mem_ball_zero_iff.1 x.2)
(norm_nonneg _) one_pos⟩,
one_smul := λ x, subtype.ext $ one_smul 𝕜 _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_closed_ball_ball :
has_continuous_smul (closed_ball (0 : 𝕜) 1) (ball (0 : E) r) :=
⟨continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).smul
(continuous_subtype_val.comp continuous_snd)⟩
instance mul_action_closed_ball_closed_ball :
mul_action (closed_ball (0 : 𝕜) 1) (closed_ball (0 : E) r) :=
{ smul := λ c x, ⟨(c : 𝕜) • x, mem_closed_ball_zero_iff.2 $
by simpa only [norm_smul, one_mul]
using mul_le_mul (mem_closed_ball_zero_iff.1 c.2) (mem_closed_ball_zero_iff.1 x.2)
(norm_nonneg _) zero_le_one⟩,
one_smul := λ x, subtype.ext $ one_smul 𝕜 _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_closed_ball_closed_ball :
has_continuous_smul (closed_ball (0 : 𝕜) 1) (closed_ball (0 : E) r) :=
⟨continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).smul
(continuous_subtype_val.comp continuous_snd)⟩
end closed_ball
section sphere
instance mul_action_sphere_ball : mul_action (sphere (0 : 𝕜) 1) (ball (0 : E) r) :=
{ smul := λ c x, inclusion sphere_subset_closed_ball c • x,
one_smul := λ x, subtype.ext $ one_smul _ _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_sphere_ball :
has_continuous_smul (sphere (0 : 𝕜) 1) (ball (0 : E) r) :=
⟨continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).smul
(continuous_subtype_val.comp continuous_snd)⟩
instance mul_action_sphere_closed_ball : mul_action (sphere (0 : 𝕜) 1) (closed_ball (0 : E) r) :=
{ smul := λ c x, inclusion sphere_subset_closed_ball c • x,
one_smul := λ x, subtype.ext $ one_smul _ _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_sphere_closed_ball :
has_continuous_smul (sphere (0 : 𝕜) 1) (closed_ball (0 : E) r) :=
⟨continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).smul
(continuous_subtype_val.comp continuous_snd)⟩
instance mul_action_sphere_sphere : mul_action (sphere (0 : 𝕜) 1) (sphere (0 : E) r) :=
{ smul := λ c x, ⟨(c : 𝕜) • x, mem_sphere_zero_iff_norm.2 $
by rw [norm_smul, mem_sphere_zero_iff_norm.1 c.coe_prop, mem_sphere_zero_iff_norm.1 x.coe_prop,
one_mul]⟩,
one_smul := λ x, subtype.ext $ one_smul _ _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_sphere_sphere :
has_continuous_smul (sphere (0 : 𝕜) 1) (sphere (0 : E) r) :=
⟨continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).smul
(continuous_subtype_val.comp continuous_snd)⟩
end sphere
section is_scalar_tower
variables [normed_algebra 𝕜 𝕜'] [is_scalar_tower 𝕜 𝕜' E]
instance is_scalar_tower_closed_ball_closed_ball_closed_ball :
is_scalar_tower (closed_ball (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_closed_ball_closed_ball_ball :
is_scalar_tower (closed_ball (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_closed_ball_closed_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_closed_ball_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_sphere_closed_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_sphere_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_sphere_sphere :
is_scalar_tower (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (sphere (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_ball_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (ball (0 : 𝕜') 1) (ball (0 : 𝕜') 1) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : 𝕜')⟩
instance is_scalar_tower_closed_ball_ball_ball :
is_scalar_tower (closed_ball (0 : 𝕜) 1) (ball (0 : 𝕜') 1) (ball (0 : 𝕜') 1) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : 𝕜')⟩
end is_scalar_tower
section smul_comm_class
variables [smul_comm_class 𝕜 𝕜' E]
instance smul_comm_class_closed_ball_closed_ball_closed_ball :
smul_comm_class (closed_ball (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_closed_ball_closed_ball_ball :
smul_comm_class (closed_ball (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_closed_ball_closed_ball :
smul_comm_class (sphere (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_closed_ball_ball :
smul_comm_class (sphere (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_ball_ball [normed_algebra 𝕜 𝕜'] :
smul_comm_class (sphere (0 : 𝕜) 1) (ball (0 : 𝕜') 1) (ball (0 : 𝕜') 1) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : 𝕜')⟩
instance smul_comm_class_sphere_sphere_closed_ball :
smul_comm_class (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_sphere_ball :
smul_comm_class (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_sphere_sphere :
smul_comm_class (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (sphere (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
end smul_comm_class
variables (𝕜) [char_zero 𝕜]
lemma ne_neg_of_mem_sphere {r : ℝ} (hr : r ≠ 0) (x : sphere (0:E) r) : x ≠ - x :=
λ h, ne_zero_of_mem_sphere hr x ((self_eq_neg 𝕜 _).mp (by { conv_lhs {rw h}, simp }))
lemma ne_neg_of_mem_unit_sphere (x : sphere (0:E) 1) : x ≠ - x :=
ne_neg_of_mem_sphere 𝕜 one_ne_zero x
|
c765926c67533648aa30812825bc14ba87738db9 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/ring_quot.lean | cbafee5e87a3f734a1d40c7b8bd87765c3687619 | [] | 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,195 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.algebra.basic
import Mathlib.ring_theory.ideal.basic
import Mathlib.PostPort
universes u₁ u₂ u₃ u₄
namespace Mathlib
/-!
# Quotients of non-commutative rings
Unfortunately, ideals have only been developed in the commutative case as `ideal`,
and it's not immediately clear how one should formalise ideals in the non-commutative case.
In this file, we directly define the quotient of a semiring by any relation,
by building a bigger relation that represents the ideal generated by that relation.
We prove the universal properties of the quotient,
and recommend avoiding relying on the actual definition!
Since everything runs in parallel for quotients of `R`-algebras, we do that case at the same time.
-/
namespace ring_quot
/--
Given an arbitrary relation `r` on a ring, we strengthen it to a relation `rel r`,
such that the equivalence relation generated by `rel r` has `x ~ y` if and only if
`x - y` is in the ideal generated by elements `a - b` such that `r a b`.
-/
inductive rel {R : Type u₁} [semiring R] (r : R → R → Prop) : R → R → Prop
where
| of : ∀ {x y : R}, r x y → rel r x y
| add_left : ∀ {a b c : R}, rel r a b → rel r (a + c) (b + c)
| mul_left : ∀ {a b c : R}, rel r a b → rel r (a * c) (b * c)
| mul_right : ∀ {a b c : R}, rel r b c → rel r (a * b) (a * c)
theorem rel.add_right {R : Type u₁} [semiring R] {r : R → R → Prop} {a : R} {b : R} {c : R} (h : rel r b c) : rel r (a + b) (a + c) :=
eq.mpr (id (Eq._oldrec (Eq.refl (rel r (a + b) (a + c))) (add_comm a b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (rel r (b + a) (a + c))) (add_comm a c))) (rel.add_left h))
theorem rel.neg {R : Type u₁} [ring R] {r : R → R → Prop} {a : R} {b : R} (h : rel r a b) : rel r (-a) (-b) := sorry
theorem rel.smul {S : Type u₂} [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] {r : A → A → Prop} (k : S) {a : A} {b : A} (h : rel r a b) : rel r (k • a) (k • b) := sorry
end ring_quot
/-- The quotient of a ring by an arbitrary relation. -/
def ring_quot {R : Type u₁} [semiring R] (r : R → R → Prop) :=
Quot sorry
namespace ring_quot
protected instance semiring {R : Type u₁} [semiring R] (r : R → R → Prop) : semiring (ring_quot r) :=
semiring.mk (quot.map₂ Add.add rel.add_right rel.add_left) sorry (Quot.mk (rel r) 0) sorry sorry sorry
(quot.map₂ Mul.mul rel.mul_right rel.mul_left) sorry (Quot.mk (rel r) 1) sorry sorry sorry sorry sorry sorry
protected instance ring {R : Type u₁} [ring R] (r : R → R → Prop) : ring (ring_quot r) :=
ring.mk semiring.add sorry semiring.zero sorry sorry (quot.map (fun (a : R) => -a) rel.neg)
(add_comm_group.sub._default semiring.add sorry semiring.zero sorry sorry (quot.map (fun (a : R) => -a) rel.neg))
sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry
protected instance comm_semiring {R : Type u₁} [comm_semiring R] (r : R → R → Prop) : comm_semiring (ring_quot r) :=
comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry semiring.mul sorry semiring.one sorry sorry sorry
sorry sorry sorry sorry
protected instance comm_ring {R : Type u₁} [comm_ring R] (r : R → R → Prop) : comm_ring (ring_quot r) :=
comm_ring.mk comm_semiring.add sorry comm_semiring.zero sorry sorry ring.neg ring.sub sorry sorry comm_semiring.mul
sorry comm_semiring.one sorry sorry sorry sorry sorry
protected instance algebra {S : Type u₂} [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] (s : A → A → Prop) : algebra S (ring_quot s) :=
algebra.mk (ring_hom.mk (fun (r : S) => Quot.mk (rel s) (coe_fn (algebra_map S A) r)) sorry sorry sorry sorry) sorry
sorry
protected instance inhabited {R : Type u₁} [semiring R] (r : R → R → Prop) : Inhabited (ring_quot r) :=
{ default := 0 }
/--
The quotient map from a ring to its quotient, as a homomorphism of rings.
-/
def mk_ring_hom {R : Type u₁} [semiring R] (r : R → R → Prop) : R →+* ring_quot r :=
ring_hom.mk (Quot.mk (rel r)) sorry sorry sorry sorry
theorem mk_ring_hom_rel {R : Type u₁} [semiring R] {r : R → R → Prop} {x : R} {y : R} (w : r x y) : coe_fn (mk_ring_hom r) x = coe_fn (mk_ring_hom r) y :=
quot.sound (rel.of w)
theorem mk_ring_hom_surjective {R : Type u₁} [semiring R] (r : R → R → Prop) : function.surjective ⇑(mk_ring_hom r) := sorry
theorem ring_quot_ext {R : Type u₁} [semiring R] {T : Type u₄} [semiring T] {r : R → R → Prop} (f : ring_quot r →+* T) (g : ring_quot r →+* T) (w : ring_hom.comp f (mk_ring_hom r) = ring_hom.comp g (mk_ring_hom r)) : f = g := sorry
/--
Any ring homomorphism `f : R →+* T` which respects a relation `r : R → R → Prop`
factors uniquely through a morphism `ring_quot r →+* T`.
-/
def lift {R : Type u₁} [semiring R] {T : Type u₄} [semiring T] {r : R → R → Prop} : (Subtype fun (f : R →+* T) => ∀ {x y : R}, r x y → coe_fn f x = coe_fn f y) ≃ (ring_quot r →+* T) :=
equiv.mk
(fun (f' : Subtype fun (f : R →+* T) => ∀ {x y : R}, r x y → coe_fn f x = coe_fn f y) =>
let f : R →+* T := ↑f';
ring_hom.mk (Quot.lift ⇑f sorry) (ring_hom.map_one f) sorry (ring_hom.map_zero f) sorry)
(fun (F : ring_quot r →+* T) => { val := ring_hom.comp F (mk_ring_hom r), property := sorry }) sorry sorry
@[simp] theorem lift_mk_ring_hom_apply {R : Type u₁} [semiring R] {T : Type u₄} [semiring T] (f : R →+* T) {r : R → R → Prop} (w : ∀ {x y : R}, r x y → coe_fn f x = coe_fn f y) (x : R) : coe_fn (coe_fn lift { val := f, property := w }) (coe_fn (mk_ring_hom r) x) = coe_fn f x :=
rfl
-- note this is essentially `lift.symm_apply_eq.mp h`
theorem lift_unique {R : Type u₁} [semiring R] {T : Type u₄} [semiring T] (f : R →+* T) {r : R → R → Prop} (w : ∀ {x y : R}, r x y → coe_fn f x = coe_fn f y) (g : ring_quot r →+* T) (h : ring_hom.comp g (mk_ring_hom r) = f) : g = coe_fn lift { val := f, property := w } := sorry
theorem eq_lift_comp_mk_ring_hom {R : Type u₁} [semiring R] {T : Type u₄} [semiring T] {r : R → R → Prop} (f : ring_quot r →+* T) : f =
coe_fn lift
{ val := ring_hom.comp f (mk_ring_hom r),
property :=
fun (x y : R) (h : r x y) =>
id
(eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn f (coe_fn (mk_ring_hom r) x) = coe_fn f (coe_fn (mk_ring_hom r) y)))
(mk_ring_hom_rel h)))
(Eq.refl (coe_fn f (coe_fn (mk_ring_hom r) y)))) } :=
Eq.symm (equiv.apply_symm_apply lift f)
/-!
We now verify that in the case of a commutative ring, the `ring_quot` construction
agrees with the quotient by the appropriate ideal.
-/
/-- The universal ring homomorphism from `ring_quot r` to `(ideal.of_rel r).quotient`. -/
def ring_quot_to_ideal_quotient {B : Type u₁} [comm_ring B] (r : B → B → Prop) : ring_quot r →+* ideal.quotient (ideal.of_rel r) :=
coe_fn lift { val := ideal.quotient.mk (ideal.of_rel r), property := sorry }
@[simp] theorem ring_quot_to_ideal_quotient_apply {B : Type u₁} [comm_ring B] (r : B → B → Prop) (x : B) : coe_fn (ring_quot_to_ideal_quotient r) (coe_fn (mk_ring_hom r) x) = coe_fn (ideal.quotient.mk (ideal.of_rel r)) x :=
rfl
/-- The universal ring homomorphism from `(ideal.of_rel r).quotient` to `ring_quot r`. -/
def ideal_quotient_to_ring_quot {B : Type u₁} [comm_ring B] (r : B → B → Prop) : ideal.quotient (ideal.of_rel r) →+* ring_quot r :=
ideal.quotient.lift (ideal.of_rel r) (mk_ring_hom r) sorry
@[simp] theorem ideal_quotient_to_ring_quot_apply {B : Type u₁} [comm_ring B] (r : B → B → Prop) (x : B) : coe_fn (ideal_quotient_to_ring_quot r) (coe_fn (ideal.quotient.mk (ideal.of_rel r)) x) = coe_fn (mk_ring_hom r) x :=
rfl
/--
The ring equivalence between `ring_quot r` and `(ideal.of_rel r).quotient`
-/
def ring_quot_equiv_ideal_quotient {B : Type u₁} [comm_ring B] (r : B → B → Prop) : ring_quot r ≃+* ideal.quotient (ideal.of_rel r) :=
ring_equiv.of_hom_inv (ring_quot_to_ideal_quotient r) (ideal_quotient_to_ring_quot r) sorry sorry
/-- Transfer a star_ring instance through a quotient, if the quotient is invariant to `star` -/
def star_ring {R : Type u₁} [semiring R] [star_ring R] (r : R → R → Prop) (hr : ∀ {a b : R}, r a b → r (star a) (star b)) : star_ring (ring_quot r) :=
star_ring.mk sorry
/--
The quotient map from an `S`-algebra to its quotient, as a homomorphism of `S`-algebras.
-/
def mk_alg_hom (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] (s : A → A → Prop) : alg_hom S A (ring_quot s) :=
alg_hom.mk (ring_hom.to_fun (mk_ring_hom s)) sorry sorry sorry sorry sorry
@[simp] theorem mk_alg_hom_coe (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] (s : A → A → Prop) : ↑(mk_alg_hom S s) = mk_ring_hom s :=
rfl
theorem mk_alg_hom_rel (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] {s : A → A → Prop} {x : A} {y : A} (w : s x y) : coe_fn (mk_alg_hom S s) x = coe_fn (mk_alg_hom S s) y :=
quot.sound (rel.of w)
theorem mk_alg_hom_surjective (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] (s : A → A → Prop) : function.surjective ⇑(mk_alg_hom S s) := sorry
theorem ring_quot_ext' (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] {B : Type u₄} [semiring B] [algebra S B] {s : A → A → Prop} (f : alg_hom S (ring_quot s) B) (g : alg_hom S (ring_quot s) B) (w : alg_hom.comp f (mk_alg_hom S s) = alg_hom.comp g (mk_alg_hom S s)) : f = g := sorry
/--
Any `S`-algebra homomorphism `f : A →ₐ[S] B` which respects a relation `s : A → A → Prop`
factors uniquely through a morphism `ring_quot s →ₐ[S] B`.
-/
def lift_alg_hom (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] {B : Type u₄} [semiring B] [algebra S B] {s : A → A → Prop} : (Subtype fun (f : alg_hom S A B) => ∀ {x y : A}, s x y → coe_fn f x = coe_fn f y) ≃ alg_hom S (ring_quot s) B :=
equiv.mk
(fun (f' : Subtype fun (f : alg_hom S A B) => ∀ {x y : A}, s x y → coe_fn f x = coe_fn f y) =>
let f : alg_hom S A B := ↑f';
alg_hom.mk (Quot.lift ⇑f sorry) (alg_hom.map_one f) sorry (alg_hom.map_zero f) sorry sorry)
(fun (F : alg_hom S (ring_quot s) B) => { val := alg_hom.comp F (mk_alg_hom S s), property := sorry }) sorry sorry
@[simp] theorem lift_alg_hom_mk_alg_hom_apply (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] {B : Type u₄} [semiring B] [algebra S B] (f : alg_hom S A B) {s : A → A → Prop} (w : ∀ {x y : A}, s x y → coe_fn f x = coe_fn f y) (x : A) : coe_fn (coe_fn (lift_alg_hom S) { val := f, property := w }) (coe_fn (mk_alg_hom S s) x) = coe_fn f x :=
rfl
-- note this is essentially `(lift_alg_hom S).symm_apply_eq.mp h`
theorem lift_alg_hom_unique (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] {B : Type u₄} [semiring B] [algebra S B] (f : alg_hom S A B) {s : A → A → Prop} (w : ∀ {x y : A}, s x y → coe_fn f x = coe_fn f y) (g : alg_hom S (ring_quot s) B) (h : alg_hom.comp g (mk_alg_hom S s) = f) : g = coe_fn (lift_alg_hom S) { val := f, property := w } := sorry
theorem eq_lift_alg_hom_comp_mk_alg_hom (S : Type u₂) [comm_semiring S] {A : Type u₃} [semiring A] [algebra S A] {B : Type u₄} [semiring B] [algebra S B] {s : A → A → Prop} (f : alg_hom S (ring_quot s) B) : f =
coe_fn (lift_alg_hom S)
{ val := alg_hom.comp f (mk_alg_hom S s),
property :=
fun (x y : A) (h : s x y) =>
id
(eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn f (coe_fn (mk_alg_hom S s) x) = coe_fn f (coe_fn (mk_alg_hom S s) y)))
(mk_alg_hom_rel S h)))
(Eq.refl (coe_fn f (coe_fn (mk_alg_hom S s) y)))) } :=
Eq.symm (equiv.apply_symm_apply (lift_alg_hom S) f)
|
9d3d78273299ca42abdbcf4ca360903c2d39bf08 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/lie/nilpotent.lean | 7187a88462f1b5d0a48d7445851b5917c9083ab8 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 17,787 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.solvable
import algebra.lie.quotient
import linear_algebra.eigenspace
import ring_theory.nilpotent
/-!
# Nilpotent Lie algebras
Like groups, Lie algebras admit a natural concept of nilpotency. More generally, any Lie module
carries a natural concept of nilpotency. We define these here via the lower central series.
## Main definitions
* `lie_module.lower_central_series`
* `lie_module.is_nilpotent`
## Tags
lie algebra, lower central series, nilpotent
-/
universes u v w w₁ w₂
section nilpotent_modules
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (k : ℕ) (N : lie_submodule R L M)
namespace lie_submodule
/-- A generalisation of the lower central series. The zeroth term is a specified Lie submodule of
a Lie module. In the case when we specify the top ideal `⊤` of the Lie algebra, regarded as a Lie
module over itself, we get the usual lower central series of a Lie algebra.
It can be more convenient to work with this generalisation when considering the lower central series
of a Lie submodule, regarded as a Lie module in its own right, since it provides a type-theoretic
expression of the fact that the terms of the Lie submodule's lower central series are also Lie
submodules of the enclosing Lie module.
See also `lie_module.lower_central_series_eq_lcs_comap` and
`lie_module.lower_central_series_map_eq_lcs` below. -/
def lcs : lie_submodule R L M → lie_submodule R L M := (λ N, ⁅(⊤ : lie_ideal R L), N⁆)^[k]
@[simp] lemma lcs_zero (N : lie_submodule R L M) : N.lcs 0 = N := rfl
@[simp] lemma lcs_succ : N.lcs (k + 1) = ⁅(⊤ : lie_ideal R L), N.lcs k⁆ :=
function.iterate_succ_apply' (λ N', ⁅⊤, N'⁆) k N
end lie_submodule
namespace lie_module
variables (R L M)
/-- The lower central series of Lie submodules of a Lie module. -/
def lower_central_series : lie_submodule R L M := (⊤ : lie_submodule R L M).lcs k
@[simp] lemma lower_central_series_zero : lower_central_series R L M 0 = ⊤ := rfl
@[simp] lemma lower_central_series_succ :
lower_central_series R L M (k + 1) = ⁅(⊤ : lie_ideal R L), lower_central_series R L M k⁆ :=
(⊤ : lie_submodule R L M).lcs_succ k
end lie_module
namespace lie_submodule
open lie_module
variables {R L M}
lemma lcs_le_self : N.lcs k ≤ N :=
begin
induction k with k ih,
{ simp, },
{ simp only [lcs_succ],
exact (lie_submodule.mono_lie_right _ _ ⊤ ih).trans (N.lie_le_right ⊤), },
end
lemma lower_central_series_eq_lcs_comap :
lower_central_series R L N k = (N.lcs k).comap N.incl :=
begin
induction k with k ih,
{ simp, },
{ simp only [lcs_succ, lower_central_series_succ] at ⊢ ih,
have : N.lcs k ≤ N.incl.range,
{ rw N.range_incl,
apply lcs_le_self, },
rw [ih, lie_submodule.comap_bracket_eq _ _ N.incl N.ker_incl this], },
end
lemma lower_central_series_map_eq_lcs :
(lower_central_series R L N k).map N.incl = N.lcs k :=
begin
rw [lower_central_series_eq_lcs_comap, lie_submodule.map_comap_incl, inf_eq_right],
apply lcs_le_self,
end
end lie_submodule
namespace lie_module
variables (R L M)
lemma antitone_lower_central_series : antitone $ lower_central_series R L M :=
begin
intros l k,
induction k with k ih generalizing l;
intros h,
{ exact (le_zero_iff.mp h).symm ▸ le_rfl, },
{ rcases nat.of_le_succ h with hk | hk,
{ rw lower_central_series_succ,
exact (lie_submodule.mono_lie_right _ _ ⊤ (ih hk)).trans (lie_submodule.lie_le_right _ _), },
{ exact hk.symm ▸ le_rfl, }, },
end
lemma trivial_iff_lower_central_eq_bot : is_trivial L M ↔ lower_central_series R L M 1 = ⊥ :=
begin
split; intros h,
{ erw [eq_bot_iff, lie_submodule.lie_span_le], rintros m ⟨x, n, hn⟩, rw [← hn, h.trivial], simp,},
{ rw lie_submodule.eq_bot_iff at h, apply is_trivial.mk, intros x m, apply h,
apply lie_submodule.subset_lie_span, use [x, m], refl, },
end
lemma iterate_to_endomorphism_mem_lower_central_series (x : L) (m : M) (k : ℕ) :
(to_endomorphism R L M x)^[k] m ∈ lower_central_series R L M k :=
begin
induction k with k ih,
{ simp only [function.iterate_zero], },
{ simp only [lower_central_series_succ, function.comp_app, function.iterate_succ',
to_endomorphism_apply_apply],
exact lie_submodule.lie_mem_lie _ _ (lie_submodule.mem_top x) ih, },
end
variables {R L M}
lemma map_lower_central_series_le
{M₂ : Type w₁} [add_comm_group M₂] [module R M₂] [lie_ring_module L M₂] [lie_module R L M₂]
(k : ℕ) (f : M →ₗ⁅R,L⁆ M₂) :
lie_submodule.map f (lower_central_series R L M k) ≤ lower_central_series R L M₂ k :=
begin
induction k with k ih,
{ simp only [lie_module.lower_central_series_zero, le_top], },
{ simp only [lie_module.lower_central_series_succ, lie_submodule.map_bracket_eq],
exact lie_submodule.mono_lie_right _ _ ⊤ ih, },
end
variables (R L M)
open lie_algebra
lemma derived_series_le_lower_central_series (k : ℕ) :
derived_series R L k ≤ lower_central_series R L L k :=
begin
induction k with k h,
{ rw [derived_series_def, derived_series_of_ideal_zero, lower_central_series_zero],
exact le_rfl, },
{ have h' : derived_series R L k ≤ ⊤, { by simp only [le_top], },
rw [derived_series_def, derived_series_of_ideal_succ, lower_central_series_succ],
exact lie_submodule.mono_lie _ _ _ _ h' h, },
end
/-- A Lie module is nilpotent if its lower central series reaches 0 (in a finite number of
steps). -/
class is_nilpotent : Prop :=
(nilpotent : ∃ k, lower_central_series R L M k = ⊥)
@[priority 100]
instance trivial_is_nilpotent [is_trivial L M] : is_nilpotent R L M :=
⟨by { use 1, change ⁅⊤, ⊤⁆ = ⊥, simp, }⟩
lemma nilpotent_endo_of_nilpotent_module [hM : is_nilpotent R L M] :
∃ (k : ℕ), ∀ (x : L), (to_endomorphism R L M x)^k = 0 :=
begin
unfreezingI { obtain ⟨k, hM⟩ := hM, },
use k,
intros x, ext m,
rw [linear_map.pow_apply, linear_map.zero_apply, ← @lie_submodule.mem_bot R L M, ← hM],
exact iterate_to_endomorphism_mem_lower_central_series R L M x m k,
end
/-- For a nilpotent Lie module, the weight space of the 0 weight is the whole module.
This result will be used downstream to show that weight spaces are Lie submodules, at which time
it will be possible to state it in the language of weight spaces. -/
lemma infi_max_gen_zero_eigenspace_eq_top_of_nilpotent [is_nilpotent R L M] :
(⨅ (x : L), (to_endomorphism R L M x).maximal_generalized_eigenspace 0) = ⊤ :=
begin
ext m,
simp only [module.End.mem_maximal_generalized_eigenspace, submodule.mem_top, sub_zero, iff_true,
zero_smul, submodule.mem_infi],
intros x,
obtain ⟨k, hk⟩ := nilpotent_endo_of_nilpotent_module R L M,
use k, rw hk,
exact linear_map.zero_apply m,
end
/-- If the quotient of a Lie module `M` by a Lie submodule on which the Lie algebra acts trivially
is nilpotent then `M` is nilpotent.
This is essentially the Lie module equivalent of the fact that a central
extension of nilpotent Lie algebras is nilpotent. See `lie_algebra.nilpotent_of_nilpotent_quotient`
below for the corresponding result for Lie algebras. -/
lemma nilpotent_of_nilpotent_quotient {N : lie_submodule R L M}
(h₁ : N ≤ max_triv_submodule R L M) (h₂ : is_nilpotent R L (M ⧸ N)) : is_nilpotent R L M :=
begin
unfreezingI { obtain ⟨k, hk⟩ := h₂, },
use k+1,
simp only [lower_central_series_succ],
suffices : lower_central_series R L M k ≤ N,
{ replace this := lie_submodule.mono_lie_right _ _ ⊤ (le_trans this h₁),
rwa [ideal_oper_max_triv_submodule_eq_bot, le_bot_iff] at this, },
rw [← lie_submodule.quotient.map_mk'_eq_bot_le, ← le_bot_iff, ← hk],
exact map_lower_central_series_le k (lie_submodule.quotient.mk' N),
end
/-- Given a nilpotent Lie module `M` with lower central series `M = C₀ ≥ C₁ ≥ ⋯ ≥ Cₖ = ⊥`, this is
the natural number `k` (the number of inclusions).
For a non-nilpotent module, we use the junk value 0. -/
noncomputable def nilpotency_length : ℕ :=
Inf { k | lower_central_series R L M k = ⊥ }
lemma nilpotency_length_eq_zero_iff [is_nilpotent R L M] :
nilpotency_length R L M = 0 ↔ subsingleton M :=
begin
let s := { k | lower_central_series R L M k = ⊥ },
have hs : s.nonempty,
{ unfreezingI { obtain ⟨k, hk⟩ := (by apply_instance : is_nilpotent R L M), },
exact ⟨k, hk⟩, },
change Inf s = 0 ↔ _,
rw [← lie_submodule.subsingleton_iff R L M, ← subsingleton_iff_bot_eq_top,
← lower_central_series_zero, @eq_comm (lie_submodule R L M)],
refine ⟨λ h, h ▸ nat.Inf_mem hs, λ h, _⟩,
rw nat.Inf_eq_zero,
exact or.inl h,
end
lemma nilpotency_length_eq_succ_iff (k : ℕ) :
nilpotency_length R L M = k + 1 ↔
lower_central_series R L M (k + 1) = ⊥ ∧ lower_central_series R L M k ≠ ⊥ :=
begin
let s := { k | lower_central_series R L M k = ⊥ },
change Inf s = k + 1 ↔ k + 1 ∈ s ∧ k ∉ s,
have hs : ∀ k₁ k₂, k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s,
{ rintros k₁ k₂ h₁₂ (h₁ : lower_central_series R L M k₁ = ⊥),
exact eq_bot_iff.mpr (h₁ ▸ antitone_lower_central_series R L M h₁₂), },
exact nat.Inf_upward_closed_eq_succ_iff hs k,
end
/-- Given a non-trivial nilpotent Lie module `M` with lower central series
`M = C₀ ≥ C₁ ≥ ⋯ ≥ Cₖ = ⊥`, this is the `k-1`th term in the lower central series (the last
non-trivial term).
For a trivial or non-nilpotent module, this is the bottom submodule, `⊥`. -/
noncomputable def lower_central_series_last : lie_submodule R L M :=
match nilpotency_length R L M with
| 0 := ⊥
| k + 1 := lower_central_series R L M k
end
lemma lower_central_series_last_le_max_triv :
lower_central_series_last R L M ≤ max_triv_submodule R L M :=
begin
rw lower_central_series_last,
cases h : nilpotency_length R L M with k,
{ exact bot_le, },
{ rw le_max_triv_iff_bracket_eq_bot,
rw [nilpotency_length_eq_succ_iff, lower_central_series_succ] at h,
exact h.1, },
end
lemma nontrivial_lower_central_series_last [nontrivial M] [is_nilpotent R L M] :
nontrivial (lower_central_series_last R L M) :=
begin
rw [lie_submodule.nontrivial_iff_ne_bot, lower_central_series_last],
cases h : nilpotency_length R L M,
{ rw [nilpotency_length_eq_zero_iff, ← not_nontrivial_iff_subsingleton] at h,
contradiction, },
{ rw nilpotency_length_eq_succ_iff at h,
exact h.2, },
end
lemma nontrivial_max_triv_of_is_nilpotent [nontrivial M] [is_nilpotent R L M] :
nontrivial (max_triv_submodule R L M) :=
set.nontrivial_mono
(lower_central_series_last_le_max_triv R L M)
(nontrivial_lower_central_series_last R L M)
end lie_module
end nilpotent_modules
@[priority 100]
instance lie_algebra.is_solvable_of_is_nilpotent (R : Type u) (L : Type v)
[comm_ring R] [lie_ring L] [lie_algebra R L] [hL : lie_module.is_nilpotent R L L] :
lie_algebra.is_solvable R L :=
begin
obtain ⟨k, h⟩ : ∃ k, lie_module.lower_central_series R L L k = ⊥ := hL.nilpotent,
use k, rw ← le_bot_iff at h ⊢,
exact le_trans (lie_module.derived_series_le_lower_central_series R L k) h,
end
section nilpotent_algebras
variables (R : Type u) (L : Type v) (L' : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
/-- We say a Lie algebra is nilpotent when it is nilpotent as a Lie module over itself via the
adjoint representation. -/
abbreviation lie_algebra.is_nilpotent (R : Type u) (L : Type v)
[comm_ring R] [lie_ring L] [lie_algebra R L] : Prop :=
lie_module.is_nilpotent R L L
open lie_algebra
lemma lie_algebra.nilpotent_ad_of_nilpotent_algebra [is_nilpotent R L] :
∃ (k : ℕ), ∀ (x : L), (ad R L x)^k = 0 :=
lie_module.nilpotent_endo_of_nilpotent_module R L L
/-- See also `lie_algebra.zero_root_space_eq_top_of_nilpotent`. -/
lemma lie_algebra.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent [is_nilpotent R L] :
(⨅ (x : L), (ad R L x).maximal_generalized_eigenspace 0) = ⊤ :=
lie_module.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L L
-- TODO Generalise the below to Lie modules if / when we define morphisms, equivs of Lie modules
-- covering a Lie algebra morphism of (possibly different) Lie algebras.
variables {R L L'}
open lie_module (lower_central_series)
/-- Given an ideal `I` of a Lie algebra `L`, the lower central series of `L ⧸ I` is the same
whether we regard `L ⧸ I` as an `L` module or an `L ⧸ I` module.
TODO: This result obviously generalises but the generalisation requires the missing definition of
morphisms between Lie modules over different Lie algebras. -/
lemma coe_lower_central_series_ideal_quot_eq {I : lie_ideal R L} (k : ℕ) :
(lower_central_series R L (L ⧸ I) k : submodule R (L ⧸ I)) =
lower_central_series R (L ⧸ I) (L ⧸ I) k :=
begin
induction k with k ih,
{ simp only [lie_submodule.top_coe_submodule, lie_module.lower_central_series_zero], },
{ simp only [lie_module.lower_central_series_succ, lie_submodule.lie_ideal_oper_eq_linear_span],
congr,
ext x,
split,
{ rintros ⟨⟨y, -⟩, ⟨z, hz⟩, rfl : ⁅y, z⁆ = x⟩,
erw [← lie_submodule.mem_coe_submodule, ih, lie_submodule.mem_coe_submodule] at hz,
exact ⟨⟨lie_submodule.quotient.mk y, submodule.mem_top⟩, ⟨z, hz⟩, rfl⟩, },
{ rintros ⟨⟨⟨y⟩, -⟩, ⟨z, hz⟩, rfl : ⁅y, z⁆ = x⟩,
erw [← lie_submodule.mem_coe_submodule, ← ih, lie_submodule.mem_coe_submodule] at hz,
exact ⟨⟨y, submodule.mem_top⟩, ⟨z, hz⟩, rfl⟩, }, },
end
/-- A central extension of nilpotent Lie algebras is nilpotent. -/
lemma lie_algebra.nilpotent_of_nilpotent_quotient {I : lie_ideal R L}
(h₁ : I ≤ center R L) (h₂ : is_nilpotent R (L ⧸ I)) : is_nilpotent R L :=
begin
suffices : lie_module.is_nilpotent R L (L ⧸ I),
{ exact lie_module.nilpotent_of_nilpotent_quotient R L L h₁ this, },
unfreezingI { obtain ⟨k, hk⟩ := h₂, },
use k,
simp [← lie_submodule.coe_to_submodule_eq_iff, coe_lower_central_series_ideal_quot_eq, hk],
end
lemma lie_algebra.non_trivial_center_of_is_nilpotent [nontrivial L] [is_nilpotent R L] :
nontrivial $ center R L :=
lie_module.nontrivial_max_triv_of_is_nilpotent R L L
lemma lie_ideal.map_lower_central_series_le (k : ℕ) {f : L →ₗ⁅R⁆ L'} :
lie_ideal.map f (lower_central_series R L L k) ≤ lower_central_series R L' L' k :=
begin
induction k with k ih,
{ simp only [lie_module.lower_central_series_zero, le_top], },
{ simp only [lie_module.lower_central_series_succ],
exact le_trans (lie_ideal.map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ le_top ih), },
end
lemma lie_ideal.lower_central_series_map_eq (k : ℕ) {f : L →ₗ⁅R⁆ L'}
(h : function.surjective f) :
lie_ideal.map f (lower_central_series R L L k) = lower_central_series R L' L' k :=
begin
have h' : (⊤ : lie_ideal R L).map f = ⊤,
{ rw ←f.ideal_range_eq_map,
exact f.ideal_range_eq_top_of_surjective h, },
induction k with k ih,
{ simp only [lie_module.lower_central_series_zero], exact h', },
{ simp only [lie_module.lower_central_series_succ, lie_ideal.map_bracket_eq f h, ih, h'], },
end
lemma function.injective.lie_algebra_is_nilpotent [h₁ : is_nilpotent R L'] {f : L →ₗ⁅R⁆ L'}
(h₂ : function.injective f) : is_nilpotent R L :=
{ nilpotent :=
begin
obtain ⟨k, hk⟩ := id h₁,
use k,
apply lie_ideal.bot_of_map_eq_bot h₂, rw [eq_bot_iff, ← hk],
apply lie_ideal.map_lower_central_series_le,
end, }
lemma function.surjective.lie_algebra_is_nilpotent [h₁ : is_nilpotent R L] {f : L →ₗ⁅R⁆ L'}
(h₂ : function.surjective f) : is_nilpotent R L' :=
{ nilpotent :=
begin
obtain ⟨k, hk⟩ := id h₁,
use k,
rw [← lie_ideal.lower_central_series_map_eq k h₂, hk],
simp only [lie_ideal.map_eq_bot_iff, bot_le],
end, }
lemma lie_equiv.nilpotent_iff_equiv_nilpotent (e : L ≃ₗ⁅R⁆ L') :
is_nilpotent R L ↔ is_nilpotent R L' :=
begin
split; introsI h,
{ exact e.symm.injective.lie_algebra_is_nilpotent, },
{ exact e.injective.lie_algebra_is_nilpotent, },
end
instance [h : lie_algebra.is_nilpotent R L] : lie_algebra.is_nilpotent R (⊤ : lie_subalgebra R L) :=
lie_subalgebra.top_equiv_self.nilpotent_iff_equiv_nilpotent.mpr h
end nilpotent_algebras
section of_associative
variables (R : Type u) {A : Type v} [comm_ring R] [ring A] [algebra R A]
lemma lie_algebra.ad_nilpotent_of_nilpotent {a : A} (h : is_nilpotent a) :
is_nilpotent (lie_algebra.ad R A a) :=
begin
rw lie_algebra.ad_eq_lmul_left_sub_lmul_right,
have hl : is_nilpotent (algebra.lmul_left R a), { rwa algebra.is_nilpotent_lmul_left_iff, },
have hr : is_nilpotent (algebra.lmul_right R a), { rwa algebra.is_nilpotent_lmul_right_iff, },
exact (algebra.commute_lmul_left_right R a a).is_nilpotent_sub hl hr,
end
variables {R}
lemma lie_subalgebra.is_nilpotent_ad_of_is_nilpotent_ad {L : Type v} [lie_ring L] [lie_algebra R L]
(K : lie_subalgebra R L) {x : K} (h : is_nilpotent (lie_algebra.ad R L ↑x)) :
is_nilpotent (lie_algebra.ad R K x) :=
begin
obtain ⟨n, hn⟩ := h,
use n,
exact linear_map.submodule_pow_eq_zero_of_pow_eq_zero (K.ad_comp_incl_eq x) hn,
end
lemma lie_algebra.is_nilpotent_ad_of_is_nilpotent {L : lie_subalgebra R A} {x : L}
(h : is_nilpotent (x : A)) : is_nilpotent (lie_algebra.ad R L x) :=
L.is_nilpotent_ad_of_is_nilpotent_ad $ lie_algebra.ad_nilpotent_of_nilpotent R h
end of_associative
|
5c0351e0ac439aef8869da5fdfebce1f1dcb55ec | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/smt/array_auto.lean | 9f42e3b09351d0415ed71807102456c1ad6b1be2 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,082 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
universes u v
namespace Mathlib
namespace smt
def array (α : Type u) (β : Type v) := α → β
def select {α : Type u} {β : Type v} (a : array α β) (i : α) : β := a i
theorem arrayext {α : Type u} {β : Type v} (a₁ : array α β) (a₂ : array α β) :
(∀ (i : α), select a₁ i = select a₂ i) → a₁ = a₂ :=
funext
def store {α : Type u} {β : Type v} [DecidableEq α] (a : array α β) (i : α) (v : β) : array α β :=
fun (j : α) => ite (j = i) v (select a j)
@[simp] theorem select_store {α : Type u} {β : Type v} [DecidableEq α] (a : array α β) (i : α)
(v : β) : select (store a i v) i = v :=
sorry
@[simp] theorem select_store_ne {α : Type u} {β : Type v} [DecidableEq α] (a : array α β) (i : α)
(j : α) (v : β) : j ≠ i → select (store a i v) j = select a j :=
sorry
end Mathlib |
7dc7d559c19092793077f9e7c7d9bb3366c80118 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/ring_theory/polynomial/cyclotomic/eval.lean | 06eff72e88654c92aa94d6f4c9bbdfd834e0fc1d | [
"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 | 16,001 | lean | /-
Copyright (c) 2021 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez
-/
import ring_theory.polynomial.cyclotomic.basic
import tactic.by_contra
import topology.algebra.polynomial
import number_theory.padics.padic_val
import analysis.complex.arg
/-!
# Evaluating cyclotomic polynomials
This file states some results about evaluating cyclotomic polynomials in various different ways.
## Main definitions
* `polynomial.eval(₂)_one_cyclotomic_prime(_pow)`: `eval 1 (cyclotomic p^k R) = p`.
* `polynomial.eval_one_cyclotomic_not_prime_pow`: Otherwise, `eval 1 (cyclotomic n R) = 1`.
* `polynomial.cyclotomic_pos` : `∀ x, 0 < eval x (cyclotomic n R)` if `2 < n`.
-/
namespace polynomial
open finset nat
open_locale big_operators
@[simp] lemma eval_one_cyclotomic_prime {R : Type*} [comm_ring R] {p : ℕ} [hn : fact p.prime] :
eval 1 (cyclotomic p R) = p :=
by simp only [cyclotomic_eq_geom_sum hn.out, eval_X, one_pow, finset.sum_const, eval_pow,
eval_finset_sum, finset.card_range, smul_one_eq_coe]
@[simp] lemma eval₂_one_cyclotomic_prime {R S : Type*} [comm_ring R] [semiring S] (f : R →+* S)
{p : ℕ} [fact p.prime] : eval₂ f 1 (cyclotomic p R) = p :=
by simp
@[simp] lemma eval_one_cyclotomic_prime_pow {R : Type*} [comm_ring R] {p : ℕ} (k : ℕ)
[hn : fact p.prime] : eval 1 (cyclotomic (p ^ (k + 1)) R) = p :=
by simp only [cyclotomic_prime_pow_eq_geom_sum hn.out, eval_X, one_pow, finset.sum_const,
eval_pow, eval_finset_sum, finset.card_range, smul_one_eq_coe]
@[simp] lemma eval₂_one_cyclotomic_prime_pow {R S : Type*} [comm_ring R] [semiring S] (f : R →+* S)
{p : ℕ} (k : ℕ) [fact p.prime] : eval₂ f 1 (cyclotomic (p ^ (k + 1)) R) = p :=
by simp
private lemma cyclotomic_neg_one_pos {n : ℕ} (hn : 2 < n) {R} [linear_ordered_comm_ring R] :
0 < eval (-1 : R) (cyclotomic n R) :=
begin
haveI := ne_zero.of_gt hn,
rw [←map_cyclotomic_int, ←int.cast_one, ←int.cast_neg, eval_int_cast_map,
int.coe_cast_ring_hom, int.cast_pos],
suffices : 0 < eval ↑(-1 : ℤ) (cyclotomic n ℝ),
{ rw [←map_cyclotomic_int n ℝ, eval_int_cast_map, int.coe_cast_ring_hom] at this,
exact_mod_cast this },
simp only [int.cast_one, int.cast_neg],
have h0 := cyclotomic_coeff_zero ℝ hn.le,
rw coeff_zero_eq_eval_zero at h0,
by_contra' hx,
have := intermediate_value_univ (-1) 0 (cyclotomic n ℝ).continuous,
obtain ⟨y, hy : is_root _ y⟩ := this (show (0 : ℝ) ∈ set.Icc _ _, by simpa [h0] using hx),
rw is_root_cyclotomic_iff at hy,
rw hy.eq_order_of at hn,
exact hn.not_le linear_ordered_ring.order_of_le_two,
end
lemma cyclotomic_pos {n : ℕ} (hn : 2 < n) {R} [linear_ordered_comm_ring R] (x : R) :
0 < eval x (cyclotomic n R) :=
begin
induction n using nat.strong_induction_on with n ih,
have hn' : 0 < n := pos_of_gt hn,
have hn'' : 1 < n := one_lt_two.trans hn,
dsimp at ih,
have := prod_cyclotomic_eq_geom_sum hn' R,
apply_fun eval x at this,
rw [divisors_eq_proper_divisors_insert_self_of_pos hn', finset.insert_sdiff_of_not_mem,
finset.prod_insert, eval_mul, eval_geom_sum] at this,
rotate,
{ simp only [lt_self_iff_false, finset.mem_sdiff, not_false_iff, mem_proper_divisors, and_false,
false_and]},
{ simpa only [finset.mem_singleton] using hn''.ne' },
rcases lt_trichotomy 0 (∑ i in finset.range n, x ^ i) with h | h | h,
{ apply pos_of_mul_pos_left,
{ rwa this },
rw eval_prod,
refine finset.prod_nonneg (λ i hi, _),
simp only [finset.mem_sdiff, mem_proper_divisors, finset.mem_singleton] at hi,
rw geom_sum_pos_iff hn'' at h,
cases h with hk hx,
{ refine (ih _ hi.1.2 (nat.two_lt_of_ne _ hi.2 _)).le; rintro rfl,
{ exact hn'.ne' (zero_dvd_iff.mp hi.1.1) },
{ exact even_iff_not_odd.mp (even_iff_two_dvd.mpr hi.1.1) hk } },
{ rcases eq_or_ne i 2 with rfl | hk,
{ simpa only [eval_X, eval_one, cyclotomic_two, eval_add] using hx.le },
refine (ih _ hi.1.2 (nat.two_lt_of_ne _ hi.2 hk)).le,
rintro rfl,
exact (hn'.ne' $ zero_dvd_iff.mp hi.1.1) } },
{ rw [eq_comm, geom_sum_eq_zero_iff_neg_one hn''] at h,
exact h.1.symm ▸ cyclotomic_neg_one_pos hn },
{ apply pos_of_mul_neg_left,
{ rwa this },
rw [geom_sum_neg_iff hn''] at h,
have h2 : {2} ⊆ n.proper_divisors \ {1},
{ rw [finset.singleton_subset_iff, finset.mem_sdiff, mem_proper_divisors,
finset.not_mem_singleton],
exact ⟨⟨even_iff_two_dvd.mp h.1, hn⟩, (nat.one_lt_bit0 one_ne_zero).ne'⟩ },
rw [eval_prod, ←finset.prod_sdiff h2, finset.prod_singleton]; try { apply_instance },
apply mul_nonpos_of_nonneg_of_nonpos,
{ refine finset.prod_nonneg (λ i hi, le_of_lt _),
simp only [finset.mem_sdiff, mem_proper_divisors, finset.mem_singleton] at hi,
refine ih _ hi.1.1.2 (nat.two_lt_of_ne _ hi.1.2 hi.2),
rintro rfl,
rw zero_dvd_iff at hi,
exact hn'.ne' hi.1.1.1 },
{ simpa only [eval_X, eval_one, cyclotomic_two, eval_add] using h.right.le } }
end
lemma cyclotomic_pos_and_nonneg (n : ℕ) {R} [linear_ordered_comm_ring R] (x : R) :
(1 < x → 0 < eval x (cyclotomic n R)) ∧ (1 ≤ x → 0 ≤ eval x (cyclotomic n R)) :=
begin
rcases n with _ | _ | _ | n;
simp only [cyclotomic_zero, cyclotomic_one, cyclotomic_two, succ_eq_add_one,
eval_X, eval_one, eval_add, eval_sub, sub_nonneg, sub_pos,
zero_lt_one, zero_le_one, implies_true_iff, imp_self, and_self],
{ split; intro; linarith, },
{ have : 2 < n + 3 := dec_trivial,
split; intro; [skip, apply le_of_lt]; apply cyclotomic_pos this, },
end
/-- Cyclotomic polynomials are always positive on inputs larger than one.
Similar to `cyclotomic_pos` but with the condition on the input rather than index of the
cyclotomic polynomial. -/
lemma cyclotomic_pos' (n : ℕ) {R} [linear_ordered_comm_ring R] {x : R} (hx : 1 < x) :
0 < eval x (cyclotomic n R) :=
(cyclotomic_pos_and_nonneg n x).1 hx
/-- Cyclotomic polynomials are always nonnegative on inputs one or more. -/
lemma cyclotomic_nonneg (n : ℕ) {R} [linear_ordered_comm_ring R] {x : R} (hx : 1 ≤ x) :
0 ≤ eval x (cyclotomic n R) :=
(cyclotomic_pos_and_nonneg n x).2 hx
lemma eval_one_cyclotomic_not_prime_pow {R : Type*} [ring R] {n : ℕ}
(h : ∀ {p : ℕ}, p.prime → ∀ k : ℕ, p ^ k ≠ n) : eval 1 (cyclotomic n R) = 1 :=
begin
rcases n.eq_zero_or_pos with rfl | hn',
{ simp },
have hn : 1 < n := one_lt_iff_ne_zero_and_ne_one.mpr ⟨hn'.ne', (h nat.prime_two 0).symm⟩,
suffices : eval 1 (cyclotomic n ℤ) = 1 ∨ eval 1 (cyclotomic n ℤ) = -1,
{ cases this with h h,
{ have := eval_int_cast_map (int.cast_ring_hom R) (cyclotomic n ℤ) 1,
simpa only [map_cyclotomic, int.cast_one, h, ring_hom.eq_int_cast] using this },
{ exfalso,
linarith [cyclotomic_nonneg n (le_refl (1 : ℤ))] }, },
rw [←int.nat_abs_eq_nat_abs_iff, int.nat_abs_one, nat.eq_one_iff_not_exists_prime_dvd],
intros p hp hpe,
haveI := fact.mk hp,
have hpn : p ∣ n,
{ apply hpe.trans,
nth_rewrite 1 ←int.nat_abs_of_nat n,
rw [int.nat_abs_dvd_iff_dvd, ←one_geom_sum, ←eval_geom_sum, ←prod_cyclotomic_eq_geom_sum hn'],
apply eval_dvd,
apply finset.dvd_prod_of_mem,
simpa using and.intro hn'.ne' hn.ne' },
have := prod_cyclotomic_eq_geom_sum hn' ℤ,
apply_fun eval 1 at this,
rw [eval_geom_sum, one_geom_sum, eval_prod, eq_comm,
←finset.prod_sdiff $ range_pow_padic_val_nat_subset_divisors' p, finset.prod_image] at this,
simp_rw [eval_one_cyclotomic_prime_pow, finset.prod_const, finset.card_range, mul_comm] at this,
rw [←finset.prod_sdiff $ show {n} ⊆ _, from _] at this,
any_goals {apply_instance},
swap,
{ simp only [not_exists, true_and, exists_prop, dvd_rfl, finset.mem_image, finset.mem_range,
finset.mem_singleton, finset.singleton_subset_iff, finset.mem_sdiff, nat.mem_divisors, not_and],
exact ⟨⟨hn'.ne', hn.ne'⟩, λ t _, h hp _⟩ },
rw [←int.nat_abs_of_nat p, int.nat_abs_dvd_iff_dvd] at hpe,
obtain ⟨t, ht⟩ := hpe,
rw [finset.prod_singleton, ht, mul_left_comm, mul_comm, ←mul_assoc, mul_assoc] at this,
have : (p ^ (padic_val_nat p n) * p : ℤ) ∣ n := ⟨_, this⟩,
simp only [←pow_succ', ←int.nat_abs_dvd_iff_dvd, int.nat_abs_of_nat, int.nat_abs_pow] at this,
exact pow_succ_padic_val_nat_not_dvd hn' this,
{ rintro x - y - hxy,
apply nat.succ_injective,
exact nat.pow_right_injective hp.two_le hxy }
end
lemma sub_one_pow_totient_lt_cyclotomic_eval {n : ℕ} {q : ℝ} (hn' : 2 ≤ n) (hq' : 1 < q) :
(q - 1) ^ totient n < (cyclotomic n ℝ).eval q :=
begin
have hn : 0 < n := pos_of_gt hn',
have hq := zero_lt_one.trans hq',
have hfor : ∀ ζ' ∈ primitive_roots n ℂ, q - 1 ≤ ∥↑q - ζ'∥,
{ intros ζ' hζ',
rw mem_primitive_roots hn at hζ',
convert norm_sub_norm_le (↑q) ζ',
{ rw [complex.norm_real, real.norm_of_nonneg hq.le], },
{ rw [hζ'.norm'_eq_one hn.ne'] } },
let ζ := complex.exp (2 * ↑real.pi * complex.I / ↑n),
have hζ : is_primitive_root ζ n := complex.is_primitive_root_exp n hn.ne',
have hex : ∃ ζ' ∈ primitive_roots n ℂ, q - 1 < ∥↑q - ζ'∥,
{ refine ⟨ζ, (mem_primitive_roots hn).mpr hζ, _⟩,
suffices : ¬ same_ray ℝ (q : ℂ) ζ,
{ convert lt_norm_sub_of_not_same_ray this;
simp [real.norm_of_nonneg hq.le, hζ.norm'_eq_one hn.ne'] },
rw complex.same_ray_iff,
push_neg,
refine ⟨by exact_mod_cast hq.ne', hζ.ne_zero hn.ne', _⟩,
rw [complex.arg_of_real_of_nonneg hq.le, ne.def, eq_comm, hζ.arg_eq_zero_iff hn.ne'],
clear_value ζ,
rintro rfl,
linarith [hζ.unique is_primitive_root.one] },
have : ¬eval ↑q (cyclotomic n ℂ) = 0,
{ erw cyclotomic.eval_apply q n (algebra_map ℝ ℂ),
simpa using (cyclotomic_pos' n hq').ne' },
suffices : (units.mk0 (real.to_nnreal (q - 1)) (by simp [hq'])) ^ totient n
< units.mk0 (∥(cyclotomic n ℂ).eval q∥₊) (by simp [this]),
{ simp only [←units.coe_lt_coe, units.coe_pow, units.coe_mk0, ← nnreal.coe_lt_coe, hq'.le,
real.to_nnreal_lt_to_nnreal_iff_of_nonneg, coe_nnnorm, complex.norm_eq_abs,
nnreal.coe_pow, real.coe_to_nnreal', max_eq_left, sub_nonneg] at this,
convert this,
erw [(cyclotomic.eval_apply q n (algebra_map ℝ ℂ)), eq_comm],
simp [cyclotomic_nonneg n hq'.le], },
simp only [cyclotomic_eq_prod_X_sub_primitive_roots hζ, eval_prod, eval_C,
eval_X, eval_sub, nnnorm_prod, units.mk0_prod],
convert finset.prod_lt_prod' _ _,
swap, { exact λ _, units.mk0 (real.to_nnreal (q - 1)) (by simp [hq']) },
{ simp [complex.card_primitive_roots] },
{ simp only [subtype.coe_mk, finset.mem_attach, forall_true_left, subtype.forall,
←units.coe_le_coe, ← nnreal.coe_le_coe, complex.abs_nonneg, hq'.le, units.coe_mk0,
real.coe_to_nnreal', coe_nnnorm, complex.norm_eq_abs, max_le_iff, tsub_le_iff_right],
intros x hx,
simpa using hfor x hx, },
{ simp only [subtype.coe_mk, finset.mem_attach, exists_true_left, subtype.exists,
← nnreal.coe_lt_coe, ← units.coe_lt_coe, units.coe_mk0 _, coe_nnnorm],
simpa [hq'.le] using hex, },
end
lemma cyclotomic_eval_lt_sub_one_pow_totient {n : ℕ} {q : ℝ} (hn' : 3 ≤ n) (hq' : 1 < q) :
(cyclotomic n ℝ).eval q < (q + 1) ^ totient n :=
begin
have hn : 0 < n := pos_of_gt hn',
have hq := zero_lt_one.trans hq',
have hfor : ∀ ζ' ∈ primitive_roots n ℂ, ∥↑q - ζ'∥ ≤ q + 1,
{ intros ζ' hζ',
rw mem_primitive_roots hn at hζ',
convert norm_sub_le (↑q) ζ',
{ rw [complex.norm_real, real.norm_of_nonneg (zero_le_one.trans_lt hq').le], },
{ rw [hζ'.norm'_eq_one hn.ne'] }, },
let ζ := complex.exp (2 * ↑real.pi * complex.I / ↑n),
have hζ : is_primitive_root ζ n := complex.is_primitive_root_exp n hn.ne',
have hex : ∃ ζ' ∈ primitive_roots n ℂ, ∥↑q - ζ'∥ < q + 1,
{ refine ⟨ζ, (mem_primitive_roots hn).mpr hζ, _⟩,
suffices : ¬ same_ray ℝ (q : ℂ) (-ζ),
{ convert norm_add_lt_of_not_same_ray this;
simp [real.norm_of_nonneg hq.le, hζ.norm'_eq_one hn.ne', -complex.norm_eq_abs] },
rw complex.same_ray_iff,
push_neg,
refine ⟨by exact_mod_cast hq.ne', neg_ne_zero.mpr $ hζ.ne_zero hn.ne', _⟩,
rw [complex.arg_of_real_of_nonneg hq.le, ne.def, eq_comm],
intro h,
rw [complex.arg_eq_zero_iff, complex.neg_re, neg_nonneg, complex.neg_im, neg_eq_zero] at h,
have hζ₀ : ζ ≠ 0,
{ clear_value ζ,
rintro rfl,
exact hn.ne' (hζ.unique is_primitive_root.zero) },
have : ζ.re < 0 ∧ ζ.im = 0 := ⟨h.1.lt_of_ne _, h.2⟩,
rw [←complex.arg_eq_pi_iff, hζ.arg_eq_pi_iff hn.ne'] at this,
rw this at hζ,
linarith [hζ.unique $ is_primitive_root.neg_one 0 two_ne_zero.symm],
{ contrapose! hζ₀,
ext; simp [hζ₀, h.2] } },
have : ¬eval ↑q (cyclotomic n ℂ) = 0,
{ erw cyclotomic.eval_apply q n (algebra_map ℝ ℂ),
simp only [complex.coe_algebra_map, complex.of_real_eq_zero],
exact (cyclotomic_pos' n hq').ne.symm, },
suffices : units.mk0 (∥(cyclotomic n ℂ).eval q∥₊) (by simp [this])
< (units.mk0 (real.to_nnreal (q + 1)) (by simp; linarith)) ^ totient n,
{ simp only [←units.coe_lt_coe, units.coe_pow, units.coe_mk0, ← nnreal.coe_lt_coe, hq'.le,
real.to_nnreal_lt_to_nnreal_iff_of_nonneg, coe_nnnorm, complex.norm_eq_abs,
nnreal.coe_pow, real.coe_to_nnreal', max_eq_left, sub_nonneg] at this,
convert this,
{ erw [(cyclotomic.eval_apply q n (algebra_map ℝ ℂ)), eq_comm],
simp [cyclotomic_nonneg n hq'.le] },
rw [eq_comm, max_eq_left_iff],
linarith },
simp only [cyclotomic_eq_prod_X_sub_primitive_roots hζ, eval_prod, eval_C,
eval_X, eval_sub, nnnorm_prod, units.mk0_prod],
convert finset.prod_lt_prod' _ _,
swap, { exact λ _, units.mk0 (real.to_nnreal (q + 1)) (by simp; linarith only [hq']) },
{ simp [complex.card_primitive_roots], },
{ simp only [subtype.coe_mk, finset.mem_attach, forall_true_left, subtype.forall,
←units.coe_le_coe, ← nnreal.coe_le_coe, complex.abs_nonneg, hq'.le, units.coe_mk0,
real.coe_to_nnreal, coe_nnnorm, complex.norm_eq_abs, max_le_iff],
intros x hx,
have : complex.abs _ ≤ _ := hfor x hx,
simp [this], },
{ simp only [subtype.coe_mk, finset.mem_attach, exists_true_left, subtype.exists,
← nnreal.coe_lt_coe, ← units.coe_lt_coe, units.coe_mk0 _, coe_nnnorm],
obtain ⟨ζ, hζ, hhζ : complex.abs _ < _⟩ := hex,
exact ⟨ζ, hζ, by simp [hhζ]⟩ },
end
lemma sub_one_lt_nat_abs_cyclotomic_eval {n : ℕ} {q : ℕ} (hn' : 1 < n) (hq' : q ≠ 1) :
q - 1 < ((cyclotomic n ℤ).eval ↑q).nat_abs :=
begin
rcases q with _ | _ | q,
iterate 2
{ rw [pos_iff_ne_zero, ne.def, int.nat_abs_eq_zero],
intro h,
have := degree_eq_one_of_irreducible_of_root (cyclotomic.irreducible (pos_of_gt hn')) h,
rw [degree_cyclotomic, with_top.coe_eq_one, totient_eq_one_iff] at this,
rcases this with rfl|rfl; simpa using h },
suffices : (q.succ : ℝ) < (eval (↑q + 1 + 1) (cyclotomic n ℤ)).nat_abs,
{ exact_mod_cast this },
calc _ ≤ ((q + 2 - 1) ^ n.totient : ℝ) : _
... < _ : _,
{ norm_num,
convert pow_mono (by simp : 1 ≤ (q : ℝ) + 1) (totient_pos (pos_of_gt hn') : 1 ≤ n.totient),
{ simp },
{ ring }, },
convert sub_one_pow_totient_lt_cyclotomic_eval (show 2 ≤ n, by linarith)
(show (1 : ℝ) < q + 2, by {norm_cast, linarith}),
norm_cast,
erw cyclotomic.eval_apply (q + 2 : ℤ) n (algebra_map ℤ ℝ),
simp only [int.coe_nat_succ, ring_hom.eq_int_cast],
norm_cast,
rw [int.coe_nat_abs_eq_normalize, int.normalize_of_nonneg],
simp only [int.coe_nat_succ],
exact cyclotomic_nonneg n (by linarith),
end
end polynomial
|
9c10643566dd91c2ae8f38c684c19c1968ffc199 | 2f2aa789c57653a0a047d209e0401875a9427cfc | /src/submissions/practice_2.lean | a231845a780e08624915823fbbd51facb9959824 | [] | no_license | AlexFetea/cs2120f21 | dc288aa4a907b116555758b7f63c37aa14f952ae | a2cf406a33e66aac2287341b1c3e9954db9b36ab | refs/heads/main | 1,693,910,053,038 | 1,636,678,382,000 | 1,636,678,382,000 | 399,946,831 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,168 | lean | /-
Prove the following simple logical conjectures.
Give a formal and an English proof of each one.
Your English language proofs should be complete
in the sense that they identify all the axioms
and/or theorems that you use.
-/
example : true := true.intro
example : false := _ -- trick question? why?
--Their is no intro rule for false.
example : ∀ (P : Prop), P ∨ P ↔ P :=
begin
assume P,
apply iff.intro _ _,
-- forward
assume prop,
apply or.elim prop,
-- left disjunct is true
assume p,
exact p,
-- right disjunct is true
assume p,
exact p,
-- backwards
assume p,
exact or.intro_left P p,
end
/- For problem 1, we start by using the introduction
rule for if and only if, giving us two different
propositions. We use the elimination rule to show
that P ∨ P implies P. Next we use the introduction
rule to show that P implies P ∨ P-/
example : ∀ (P : Prop), P ∧ P ↔ P :=
begin
assume P,
apply iff.intro _ _,
assume prop,
apply and.elim prop,
assume p,
assume p,
exact p,
assume prop,
apply and.intro _ _,
apply prop,
apply prop,
end
/- For problem 2, we start by using the introduction
rule for if and only if, giving us two different
propositions. We use the elimination rule to show
that P ∧ P implies P. Next we use the introduction
rule to show that P implies P ∧ P-/
example : ∀ (P Q : Prop), P ∨ Q ↔ Q ∨ P :=
begin
assume P Q,
apply iff.intro _ _,
assume prop,
apply or.elim prop,
assume p,
apply or.intro_right,
exact p,
assume q,
apply or.intro_left,
exact q,
assume prop,
apply or.elim prop,
assume p,
apply or.intro_right,
exact p,
assume q,
apply or.intro_left,
exact q,
end
/- For problem 3, we start by using the introduction
rule for if and only if, giving us two different
propositions. We use the elimination rule giving us
the propositions P → Q ∨ P and Q → Q ∨ P. We use the
intro rule for or to prove the first proposition, and
then use it again to prove the second proposition. To
solve backwards, we first apply the elimination rule
for or, giving us Q → P ∨ Q and P → P ∨ Q, and then we
apply the intro rule for or to both propositions-/
example : ∀ (P Q : Prop), P ∧ Q ↔ Q ∧ P :=
begin
assume P Q,
apply iff.intro _ _,
assume prop,
apply and.elim prop,
assume p,
assume q,
apply and.intro _ _,
exact q,
exact p,
assume prop,
apply and.elim prop,
assume q,
assume p,
apply and.intro _ _,
exact p,
exact q,
end
/- For problem 4, we start by using the introduction
rule for if and only if. We then apply the elimination
rule for and, giving us P → Q → Q ∧ P. We then apply
the intro rule for and. Solving backwords, we apply the
elimination rule for and, giving us Q → P → P ∧ Q. We
then use the introduction rule for and.-/
example : ∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) :=
begin
assume P Q R,
apply iff.intro _ _,
assume prop,
apply and.elim prop,
assume p,
assume prop2,
apply or.elim prop2,
assume q,
apply or.intro_left,
apply and.intro _ _,
exact p,
exact q,
assume r,
apply or.intro_right,
apply and.intro _ _,
exact p,
exact r,
assume prop,
apply or.elim prop,
assume prop2,
apply and.elim prop2,
assume p,
assume q,
apply and.intro _ _,
exact p,
apply or.intro_left,
exact q,
assume prop3,
apply and.elim prop3,
assume p,
assume r,
apply and.intro _ _,
exact p,
apply or.intro_right,
exact r,
end
/- For problem 5, we start by using the introduction
rule for if and only if. We then apply the elimination
rule for and, giving us P → Q ∨ R → P ∧ Q ∨ P ∧ R. We
then apply the elimination rule for or, giving us
Q → P ∧ Q ∨ P ∧ R and R → P ∧ Q ∨ P ∧ R. intro rule for
and. We then apply the introrule for or, followed by the
intro rule for and, solving the firstproposition. We
apply the intro rule for or, followed by the intro rule
for and again, solving the seond propositions. Solving
backwords, we apply the elimination rule for or, then the
elimination rule for and, giving us the proposition
P → Q → P ∧ (Q ∨ R). We then apply the intro rule for and
and the intro rule for or, solving the proposition. Next,
we apply the elimination rule for and, giving us the
proposition P → R → P ∧ (Q ∨ R). We finally apply the intro
rule for and, then the intro rule for or. -/
example : ∀ (P Q R : Prop), P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) :=
begin
assume P Q R,
apply iff.intro _ _,
assume prop,
apply or.elim prop,
assume p,
apply and.intro,
apply or.intro_left,
exact p,
apply or.intro_left,
exact p,
assume prop2,
apply and.elim prop2,
assume q,
assume r,
apply and.intro,
apply or.intro_right,
exact q,
apply or.intro_right,
exact r,
assume prop,
have pq :(P ∨ Q) := and.elim_left prop,
have pr :(P ∨ R) := and.elim_right prop,
apply or.elim pq,
assume p,
apply or.intro_left,
exact p,
assume q,
apply or.elim pr,
assume p,
apply or.intro_left,
exact p,
assume r,
apply or.intro_right,
apply and.intro,
exact q,
exact r,
end
/- For problem 6, we start by using the introduction
rule for if and only if. We then apply the elimination
rule for and, giving us P → (P ∨ Q) ∧ (P ∨ R). We then
apply the intro rule for and to serperate the left and
right statements. Each statement is then proven with the
intro rule for or. We use the eliminiation rule for or
to get Q → R → (P ∨ Q) ∧ (P ∨ R). We then apply the intro
rule for and, to seperate the statements. We then apply
the intro rule for or to each of these statements.
Solving backwords, we let pq represent the left half of
proposition using the elimination rule, and pr to
represent the right have. using the elimination rule for
or on pq we are left with the statement P → P ∨ Q ∧ R. We
can then apply the intro rule for or to seperate the two
statements, followed by the intro rule for and to solve
the statement on the right.-/
example : ∀ (P Q : Prop), P ∧ (P ∨ Q) ↔ P :=
begin
assume P Q,
apply iff.intro _ _,
assume prop,
apply and.elim prop,
assume p,
assume prop2,
exact p,
assume p,
apply and.intro _ _,
exact p,
apply or.intro_left,
exact p,
end
/- For problem 7, we start by using the introduction
rule for if and only if. We then apply the elimination
rule for and, giving us P ∧ (P ∨ Q) → P. We then
apply the elimination rule for and to serperate the left and
right statements. We then use the intro rule for and to
the left half of the proposition, and then apply the intro
rule for or to solve the right half.-/
example : ∀ (P Q : Prop), P ∨ (P ∧ Q) ↔ P :=
begin
assume P Q,
apply iff.intro _ _,
assume prop,
apply or.elim prop,
assume p,
exact p,
assume prop2,
apply and.elim prop2,
assume p,
assume q,
exact p,
assume p,
apply or.intro_left,
exact p,
end
/- For problem 8, we start by using the introduction
rule for if and only if. We then apply the elimination
rule for or, giving us P ∧ (P ∨ Q) → P. We then
apply the elimination rule for and to serperate the left and
right statements. We then apply the elimination rule for and
to seperate teh left and right statements. We finally apply
the intro rule for or to solve the proposition.-/
example : ∀ (P : Prop), P ∨ true ↔ true :=
begin
assume P,
apply iff.intro,
assume prop,
exact true.intro,
assume t,
apply or.intro_right,
exact t,
end
/- For problem 8, we start by using the introduction
rule for if and only if. We use the intro rule for
true to prov the first proposition. We use the intro
rule for or to prove the statement or the right hand
side true.-/
example : ∀ (P : Prop), P ∨ false ↔ P :=
begin
assume P,
apply iff.intro,
assume prop,
apply or.elim prop,
assume p,
exact p,
apply false.elim,
assume p,
apply or.intro_left,
exact p,
end
/- For problem 9, we start by using the introduction
rule for if and only if. We then apply the elimination
rule for or. We then apply the elimination rule for
false, proving one of the statements. We finally apply
the intro rule for or, proving the left hand side.-/
example : ∀ (P : Prop), P ∧ true ↔ P :=
begin
assume P,
apply iff.intro,
assume prop,
apply and.elim prop,
assume p,
assume t,
exact p,
assume p,
apply and.intro,
exact p,
exact true.intro,
end
/- For problem 10, we start by using the introduction
rule for if and only if. We then apply the elimination
rule for and to solve the first proposition. We then use
the introduction rule for and followed by the introduction
rule for true to solve the second proposition.-/
example : ∀ (P : Prop), P ∧ false ↔ false :=
begin
assume P,
apply iff.intro,
assume prop,
apply and.elim prop,
assume p,
assume f,
exact f,
apply false.elim,
end
/- For problem 11, we start by using the introduction
rule for if and only if. We then apply the elimination
rule for and to solve the first proposition. We then use
the elimination rule for flase to solve the second
proposition.-/
|
ddfd8728265663eb6e78c5ca111666bd48f0ece5 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/number_theory/legendre_symbol/mul_character.lean | 3c7903e9736f3e7d21a6f74eab2bf36c381e73af | [
"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 | 17,565 | lean | /-
Copyright (c) 2022 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Stoll
-/
import algebra.char_p.basic
import algebra.euclidean_domain.instances
import algebra.group.conj_finite
/-!
# Multiplicative characters of finite rings and fields
Let `R` and `R'` be a commutative rings.
A *multiplicative character* of `R` with values in `R'` is a morphism of
monoids from the multiplicative monoid of `R` into that of `R'`
that sends non-units to zero.
We use the namespace `mul_char` for the definitions and results.
## Main results
We show that the multiplicative characters form a group (if `R'` is commutative);
see `mul_char.comm_group`. We also provide an equivalence with the
homomorphisms `Rˣ →* R'ˣ`; see `mul_char.equiv_to_unit_hom`.
We define a multiplicative character to be *quadratic* if its values
are among `0`, `1` and `-1`, and we prove some properties of quadratic characters.
Finally, we show that the sum of all values of a nontrivial multiplicative
character vanishes; see `mul_char.is_nontrivial.sum_eq_zero`.
## Tags
multiplicative character
-/
section definition_and_group
/-!
### Definitions related to multiplicative characters
Even though the intended use is when domain and target of the characters
are commutative rings, we define them in the more general setting when
the domain is a commutative monoid and the target is a commutative monoid
with zero. (We need a zero in the target, since non-units are supposed
to map to zero.)
In this setting, there is an equivalence between multiplicative characters
`R → R'` and group homomorphisms `Rˣ → R'ˣ`, and the multiplicative characters
have a natural structure as a commutative group.
-/
universes u v
section defi
-- The domain of our multiplicative characters
variables (R : Type u) [comm_monoid R]
-- The target
variables (R' : Type v) [comm_monoid_with_zero R']
/-- Define a structure for multiplicative characters.
A multiplicative character from a commutative monoid `R` to a commutative monoid with zero `R'`
is a homomorphism of (multiplicative) monoids that sends non-units to zero. -/
structure mul_char extends monoid_hom R R' :=
(map_nonunit' : ∀ a : R, ¬ is_unit a → to_fun a = 0)
/-- This is the corresponding extension of `monoid_hom_class`. -/
class mul_char_class (F : Type*) (R R' : out_param $ Type*) [comm_monoid R]
[comm_monoid_with_zero R']
extends monoid_hom_class F R R' :=
(map_nonunit : ∀ (χ : F) {a : R} (ha : ¬ is_unit a), χ a = 0)
attribute [simp] mul_char_class.map_nonunit
end defi
section group
namespace mul_char
-- The domain of our multiplicative characters
variables {R : Type u} [comm_monoid R]
-- The target
variables {R' : Type v} [comm_monoid_with_zero R']
instance coe_to_fun : has_coe_to_fun (mul_char R R') (λ _, R → R') :=
⟨λ χ, χ.to_fun⟩
/-- See note [custom simps projection] -/
protected def simps.apply (χ : mul_char R R') : R → R' := χ
initialize_simps_projections mul_char (to_monoid_hom_to_fun → apply, -to_monoid_hom)
section trivial
variables (R R')
/-- The trivial multiplicative character. It takes the value `0` on non-units and
the value `1` on units. -/
@[simps]
noncomputable
def trivial : mul_char R R' :=
{ to_fun := by { classical, exact λ x, if is_unit x then 1 else 0 },
map_nonunit' := by { intros a ha, simp only [ha, if_false], },
map_one' := by simp only [is_unit_one, if_true],
map_mul' := by { intros x y,
simp only [is_unit.mul_iff, boole_mul],
split_ifs; tauto, } }
end trivial
@[simp]
lemma coe_coe (χ : mul_char R R') : (χ.to_monoid_hom : R → R') = χ := rfl
@[simp]
lemma to_fun_eq_coe (χ : mul_char R R') : χ.to_fun = χ := rfl
@[simp]
lemma coe_mk (f : R →* R') (hf) : (mul_char.mk f hf : R → R') = f := rfl
/-- Extensionality. See `ext` below for the version that will actually be used. -/
lemma ext' {χ χ' : mul_char R R'} (h : ∀ a, χ a = χ' a) : χ = χ' :=
begin
cases χ,
cases χ',
congr,
exact monoid_hom.ext h,
end
instance : mul_char_class (mul_char R R') R R' :=
{ coe := λ χ, χ.to_monoid_hom.to_fun,
coe_injective' := λ f g h, ext' (λ a, congr_fun h a),
map_mul := λ χ, χ.map_mul',
map_one := λ χ, χ.map_one',
map_nonunit := λ χ, χ.map_nonunit', }
lemma map_nonunit (χ : mul_char R R') {a : R} (ha : ¬ is_unit a) : χ a = 0 :=
χ.map_nonunit' a ha
/-- Extensionality. Since `mul_char`s always take the value zero on non-units, it is sufficient
to compare the values on units. -/
@[ext]
lemma ext {χ χ' : mul_char R R'} (h : ∀ a : Rˣ, χ a = χ' a) : χ = χ' :=
begin
apply ext',
intro a,
by_cases ha : is_unit a,
{ exact h ha.unit, },
{ rw [map_nonunit χ ha, map_nonunit χ' ha], },
end
lemma ext_iff {χ χ' : mul_char R R'} : χ = χ' ↔ ∀ a : Rˣ, χ a = χ' a :=
⟨by { rintro rfl a, refl }, ext⟩
/-!
### Equivalence of multiplicative characters with homomorphisms on units
We show that restriction / extension by zero gives an equivalence
between `mul_char R R'` and `Rˣ →* R'ˣ`.
-/
/-- Turn a `mul_char` into a homomorphism between the unit groups. -/
def to_unit_hom (χ : mul_char R R') : Rˣ →* R'ˣ := units.map χ
lemma coe_to_unit_hom (χ : mul_char R R') (a : Rˣ) :
↑(χ.to_unit_hom a) = χ a :=
rfl
/-- Turn a homomorphism between unit groups into a `mul_char`. -/
noncomputable
def of_unit_hom (f : Rˣ →* R'ˣ) : mul_char R R' :=
{ to_fun := by { classical, exact λ x, if hx : is_unit x then f hx.unit else 0 },
map_one' := by { have h1 : (is_unit_one.unit : Rˣ) = 1 := units.eq_iff.mp rfl,
simp only [h1, dif_pos, units.coe_eq_one, map_one, is_unit_one], },
map_mul' :=
begin
intros x y,
by_cases hx : is_unit x,
{ simp only [hx, is_unit.mul_iff, true_and, dif_pos],
by_cases hy : is_unit y,
{ simp only [hy, dif_pos],
have hm : (is_unit.mul_iff.mpr ⟨hx, hy⟩).unit = hx.unit * hy.unit := units.eq_iff.mp rfl,
rw [hm, map_mul],
norm_cast, },
{ simp only [hy, not_false_iff, dif_neg, mul_zero], }, },
{ simp only [hx, is_unit.mul_iff, false_and, not_false_iff, dif_neg, zero_mul], },
end ,
map_nonunit' := by { intros a ha, simp only [ha, not_false_iff, dif_neg], }, }
lemma of_unit_hom_coe (f : Rˣ →* R'ˣ) (a : Rˣ) :
of_unit_hom f ↑a = f a :=
by simp [of_unit_hom]
/-- The equivalence between multiplicative characters and homomorphisms of unit groups. -/
noncomputable
def equiv_to_unit_hom : mul_char R R' ≃ (Rˣ →* R'ˣ) :=
{ to_fun := to_unit_hom,
inv_fun := of_unit_hom,
left_inv :=
by { intro χ, ext x, rw [of_unit_hom_coe, coe_to_unit_hom] },
right_inv :=
by { intro f, ext x, rw [coe_to_unit_hom, of_unit_hom_coe], } }
@[simp]
lemma to_unit_hom_eq (χ : mul_char R R') : to_unit_hom χ = equiv_to_unit_hom χ := rfl
@[simp]
lemma of_unit_hom_eq (χ : Rˣ →* R'ˣ) : of_unit_hom χ = equiv_to_unit_hom.symm χ := rfl
@[simp]
lemma coe_equiv_to_unit_hom (χ : mul_char R R') (a : Rˣ) :
↑(equiv_to_unit_hom χ a) = χ a :=
coe_to_unit_hom χ a
@[simp]
lemma equiv_unit_hom_symm_coe (f : Rˣ →* R'ˣ) (a : Rˣ) :
equiv_to_unit_hom.symm f ↑a = f a :=
of_unit_hom_coe f a
/-!
### Commutative group structure on multiplicative characters
The multiplicative characters `R → R'` form a commutative group.
-/
protected
lemma map_one (χ : mul_char R R') : χ (1 : R) = 1 :=
χ.map_one'
/-- If the domain has a zero (and is nontrivial), then `χ 0 = 0`. -/
protected
lemma map_zero {R : Type u} [comm_monoid_with_zero R] [nontrivial R] (χ : mul_char R R') :
χ (0 : R) = 0 :=
by rw [map_nonunit χ not_is_unit_zero]
/-- If the domain is a ring `R`, then `χ (ring_char R) = 0`. -/
lemma map_ring_char {R : Type u} [comm_ring R] [nontrivial R] (χ : mul_char R R') :
χ (ring_char R) = 0 :=
by rw [ring_char.nat.cast_ring_char, χ.map_zero]
noncomputable
instance has_one : has_one (mul_char R R') := ⟨trivial R R'⟩
noncomputable
instance inhabited : inhabited (mul_char R R') := ⟨1⟩
/-- Evaluation of the trivial character -/
@[simp]
lemma one_apply_coe (a : Rˣ) : (1 : mul_char R R') a = 1 :=
dif_pos a.is_unit
/-- Multiplication of multiplicative characters. (This needs the target to be commutative.) -/
def mul (χ χ' : mul_char R R') : mul_char R R' :=
{ to_fun := χ * χ',
map_nonunit' := λ a ha, by simp [map_nonunit χ ha],
..χ.to_monoid_hom * χ'.to_monoid_hom }
instance has_mul : has_mul (mul_char R R') := ⟨mul⟩
lemma mul_apply (χ χ' : mul_char R R') (a : R) : (χ * χ') a = χ a * χ' a := rfl
@[simp]
lemma coe_to_fun_mul (χ χ' : mul_char R R') : ⇑(χ * χ') = χ * χ' := rfl
protected
lemma one_mul (χ : mul_char R R') : (1 : mul_char R R') * χ = χ := by { ext, simp }
protected
lemma mul_one (χ : mul_char R R') : χ * 1 = χ := by { ext, simp }
/-- The inverse of a multiplicative character. We define it as `inverse ∘ χ`. -/
noncomputable
def inv (χ : mul_char R R') : mul_char R R' :=
{ to_fun := λ a, monoid_with_zero.inverse (χ a),
map_nonunit' := λ a ha, by simp [map_nonunit _ ha],
..monoid_with_zero.inverse.to_monoid_hom.comp χ.to_monoid_hom }
noncomputable
instance has_inv : has_inv (mul_char R R') := ⟨inv⟩
/-- The inverse of a multiplicative character `χ`, applied to `a`, is the inverse of `χ a`. -/
lemma inv_apply_eq_inv (χ : mul_char R R') (a : R) :
χ⁻¹ a = ring.inverse (χ a) :=
eq.refl $ inv χ a
/-- The inverse of a multiplicative character `χ`, applied to `a`, is the inverse of `χ a`.
Variant when the target is a field -/
lemma inv_apply_eq_inv' {R' : Type v} [field R'] (χ : mul_char R R') (a : R) :
χ⁻¹ a = (χ a)⁻¹ :=
(inv_apply_eq_inv χ a).trans $ ring.inverse_eq_inv (χ a)
/-- When the domain has a zero, then the inverse of a multiplicative character `χ`,
applied to `a`, is `χ` applied to the inverse of `a`. -/
lemma inv_apply {R : Type u} [comm_monoid_with_zero R] (χ : mul_char R R') (a : R) :
χ⁻¹ a = χ (ring.inverse a) :=
begin
by_cases ha : is_unit a,
{ rw [inv_apply_eq_inv],
have h := is_unit.map χ ha,
apply_fun ((*) (χ a)) using is_unit.mul_right_injective h,
rw [ring.mul_inverse_cancel _ h, ← map_mul, ring.mul_inverse_cancel _ ha, mul_char.map_one], },
{ revert ha, nontriviality R, intro ha, -- `nontriviality R` by itself doesn't do it
rw [map_nonunit _ ha, ring.inverse_non_unit a ha, mul_char.map_zero χ], },
end
/-- When the domain has a zero, then the inverse of a multiplicative character `χ`,
applied to `a`, is `χ` applied to the inverse of `a`. -/
lemma inv_apply' {R : Type u} [field R] (χ : mul_char R R') (a : R) : χ⁻¹ a = χ a⁻¹ :=
(inv_apply χ a).trans $ congr_arg _ (ring.inverse_eq_inv a)
/-- The product of a character with its inverse is the trivial character. -/
@[simp]
lemma inv_mul (χ : mul_char R R') : χ⁻¹ * χ = 1 :=
begin
ext x,
rw [coe_to_fun_mul, pi.mul_apply, inv_apply_eq_inv,
ring.inverse_mul_cancel _ (is_unit.map _ x.is_unit), one_apply_coe],
end
/-- The commutative group structure on `mul_char R R'`. -/
noncomputable
instance comm_group : comm_group (mul_char R R') :=
{ one := 1,
mul := (*),
inv := has_inv.inv,
mul_left_inv := inv_mul,
mul_assoc := by { intros χ₁ χ₂ χ₃, ext a, simp [mul_assoc], },
mul_comm := by { intros χ₁ χ₂, ext a, simp [mul_comm], },
one_mul := one_mul,
mul_one := mul_one, }
/-- If `a` is a unit and `n : ℕ`, then `(χ ^ n) a = (χ a) ^ n`. -/
lemma pow_apply_coe (χ : mul_char R R') (n : ℕ) (a : Rˣ) :
(χ ^ n) a = (χ a) ^ n :=
begin
induction n with n ih,
{ rw [pow_zero, pow_zero, one_apply_coe], },
{ rw [pow_succ, pow_succ, mul_apply, ih], },
end
/-- If `n` is positive, then `(χ ^ n) a = (χ a) ^ n`. -/
lemma pow_apply' (χ : mul_char R R') {n : ℕ} (hn : 0 < n) (a : R) :
(χ ^ n) a = (χ a) ^ n :=
begin
by_cases ha : is_unit a,
{ exact pow_apply_coe χ n ha.unit, },
{ rw [map_nonunit (χ ^ n) ha, map_nonunit χ ha, zero_pow hn], },
end
end mul_char
end group
end definition_and_group
/-!
### Properties of multiplicative characters
We introduce the properties of being nontrivial or quadratic and prove
some basic facts about them.
We now assume that domain and target are commutative rings.
-/
section properties
namespace mul_char
universes u v w
variables {R : Type u} [comm_ring R] {R' : Type v} [comm_ring R'] {R'' : Type w} [comm_ring R'']
/-- A multiplicative character is *nontrivial* if it takes a value `≠ 1` on a unit. -/
def is_nontrivial (χ : mul_char R R') : Prop := ∃ a : Rˣ, χ a ≠ 1
/-- A multiplicative character is nontrivial iff it is not the trivial character. -/
lemma is_nontrivial_iff (χ : mul_char R R') : χ.is_nontrivial ↔ χ ≠ 1 :=
by simp only [is_nontrivial, ne.def, ext_iff, not_forall, one_apply_coe]
/-- A multiplicative character is *quadratic* if it takes only the values `0`, `1`, `-1`. -/
def is_quadratic (χ : mul_char R R') : Prop := ∀ a, χ a = 0 ∨ χ a = 1 ∨ χ a = -1
/-- If two values of quadratic characters with target `ℤ` agree after coercion into a ring
of characteristic not `2`, then they agree in `ℤ`. -/
lemma is_quadratic.eq_of_eq_coe {χ : mul_char R ℤ} (hχ : is_quadratic χ)
{χ' : mul_char R' ℤ} (hχ' : is_quadratic χ') [nontrivial R''] (hR'' : ring_char R'' ≠ 2)
{a : R} {a' : R'} (h : (χ a : R'') = χ' a') :
χ a = χ' a' :=
int.cast_inj_on_of_ring_char_ne_two hR'' (hχ a) (hχ' a') h
/-- We can post-compose a multiplicative character with a ring homomorphism. -/
@[simps]
def ring_hom_comp (χ : mul_char R R') (f : R' →+* R'') : mul_char R R'' :=
{ to_fun := λ a, f (χ a),
map_nonunit' := λ a ha, by simp only [map_nonunit χ ha, map_zero],
..f.to_monoid_hom.comp χ.to_monoid_hom }
/-- Composition with an injective ring homomorphism preserves nontriviality. -/
lemma is_nontrivial.comp {χ : mul_char R R'} (hχ : χ.is_nontrivial)
{f : R' →+* R''} (hf : function.injective f) :
(χ.ring_hom_comp f).is_nontrivial :=
begin
obtain ⟨a, ha⟩ := hχ,
use a,
rw [ring_hom_comp_apply, ← ring_hom.map_one f],
exact λ h, ha (hf h),
end
/-- Composition with a ring homomorphism preserves the property of being a quadratic character. -/
lemma is_quadratic.comp {χ : mul_char R R'} (hχ : χ.is_quadratic) (f : R' →+* R'') :
(χ.ring_hom_comp f).is_quadratic :=
begin
intro a,
rcases hχ a with (ha | ha | ha);
simp [ha],
end
/-- The inverse of a quadratic character is itself. → -/
lemma is_quadratic.inv {χ : mul_char R R'} (hχ : χ.is_quadratic) : χ⁻¹ = χ :=
begin
ext x,
rw [inv_apply_eq_inv],
rcases hχ x with h₀ | h₁ | h₂,
{ rw [h₀, ring.inverse_zero], },
{ rw [h₁, ring.inverse_one], },
{ rw [h₂, (by norm_cast : (-1 : R') = (-1 : R'ˣ)), ring.inverse_unit (-1 : R'ˣ)],
refl, },
end
/-- The square of a quadratic character is the trivial character. -/
lemma is_quadratic.sq_eq_one {χ : mul_char R R'} (hχ : χ.is_quadratic) : χ ^ 2 = 1 :=
begin
convert mul_left_inv _,
rw [pow_two, hχ.inv],
end
/-- The `p`th power of a quadratic character is itself, when `p` is the (prime) characteristic
of the target ring. -/
lemma is_quadratic.pow_char {χ : mul_char R R'} (hχ : χ.is_quadratic)
(p : ℕ) [hp : fact p.prime] [char_p R' p] :
χ ^ p = χ :=
begin
ext x,
rw [pow_apply_coe],
rcases hχ x with (hx | hx | hx); rw hx,
{ rw [zero_pow (fact.out p.prime).pos], },
{ rw [one_pow], },
{ exact char_p.neg_one_pow_char R' p, },
end
/-- The `n`th power of a quadratic character is the trivial character, when `n` is even. -/
lemma is_quadratic.pow_even {χ : mul_char R R'} (hχ : χ.is_quadratic) {n : ℕ} (hn : even n) :
χ ^ n = 1 :=
begin
obtain ⟨n, rfl⟩ := even_iff_two_dvd.mp hn,
rw [pow_mul, hχ.sq_eq_one, one_pow]
end
/-- The `n`th power of a quadratic character is itself, when `n` is odd. -/
lemma is_quadratic.pow_odd {χ : mul_char R R'} (hχ : χ.is_quadratic) {n : ℕ} (hn : odd n) :
χ ^ n = χ :=
begin
obtain ⟨n, rfl⟩ := hn,
rw [pow_add, pow_one, hχ.pow_even (even_two_mul _), one_mul]
end
open_locale big_operators
/-- The sum over all values of a nontrivial multiplicative character on a finite ring is zero
(when the target is a domain). -/
lemma is_nontrivial.sum_eq_zero [fintype R] [is_domain R'] {χ : mul_char R R'}
(hχ : χ.is_nontrivial) :
∑ a, χ a = 0 :=
begin
rcases hχ with ⟨b, hb⟩,
refine eq_zero_of_mul_eq_self_left hb _,
simp only [finset.mul_sum, ← map_mul],
exact fintype.sum_bijective _ (units.mul_left_bijective b) _ _ (λ x, rfl)
end
/-- The sum over all values of the trivial multiplicative character on a finite ring is
the cardinality of its unit group. -/
lemma sum_one_eq_card_units [fintype R] [decidable_eq R] :
∑ a, (1 : mul_char R R') a = fintype.card Rˣ :=
begin
calc ∑ a, (1 : mul_char R R') a
= ∑ a : R, if is_unit a then 1 else 0 : finset.sum_congr rfl (λ a _, _)
... = ((finset.univ : finset R).filter is_unit).card : finset.sum_boole
... = (finset.univ.map (⟨(coe : Rˣ → R), units.ext⟩)).card : _
... = fintype.card Rˣ : congr_arg _ (finset.card_map _),
{ split_ifs with h h,
{ exact one_apply_coe h.unit },
{ exact map_nonunit _ h } },
{ congr,
ext a,
simp only [finset.mem_filter, finset.mem_univ, true_and, finset.mem_map,
function.embedding.coe_fn_mk, exists_true_left, is_unit], },
end
end mul_char
end properties
|
f7b3d3f0262513cf1249773bba63f3f9d57ac07e | 6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b | /stage0/src/Lean/Server/FileWorker.lean | 3b112ae911478e0b3ed1598972e301dc5ad84ca0 | [
"Apache-2.0"
] | permissive | pbrinkmeier/lean4 | d31991fd64095e64490cb7157bcc6803f9c48af4 | 32fd82efc2eaf1232299e930ec16624b370eac39 | refs/heads/master | 1,681,364,001,662 | 1,618,425,427,000 | 1,618,425,427,000 | 358,314,562 | 0 | 0 | Apache-2.0 | 1,618,504,558,000 | 1,618,501,999,000 | null | UTF-8 | Lean | false | false | 36,347 | 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 Init.System.IO
import Std.Data.RBMap
import Lean.Environment
import Lean.PrettyPrinter
import Lean.DeclarationRange
import Lean.Data.Lsp
import Lean.Data.Json.FromToJson
import Lean.Server.Snapshots
import Lean.Server.Utils
import Lean.Server.AsyncList
import Lean.Server.InfoUtils
import Lean.Server.Completion
/-!
For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`.
This module implements per-file worker processes.
File processing and requests+notifications against a file should be concurrent for two reasons:
- By the LSP standard, requests should be cancellable.
- Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework,
elaboration can be extremely slow and even not halt in some cases. Users should be able to
work with the file while this is happening, e.g. make new changes to the file or send requests.
To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to
the elaboration of one command. When the elaboration of one command is done, the next task is spawned.
On didChange notifications, we search for the task in which the change occured. If we stumble across
a task that has not yet finished before finding the task we're looking for, we terminate it
and start the elaboration there, otherwise we start the elaboration at the task where the change occured.
Requests iterate over tasks until they find the command that they need to answer the request.
In order to not block the main thread, this is done in a request task.
If a task that the request task waits for is terminated, a change occured somewhere before the
command that the request is looking for and the request sends a "content changed" error.
-/
namespace Lean.Server.FileWorker
open Lsp
open IO
open Snapshots
open Lean.Parser.Command
open Std (RBMap RBMap.empty)
open JsonRpc
section Utils
private def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit :=
IO.eprintln s!"[{s.beginPos}, {s.endPos}]: `{text.source.extract s.beginPos (s.endPos-1)}`"
inductive ElabTaskError where
| aborted
| eof
| ioError (e : IO.Error)
instance : Coe IO.Error ElabTaskError := ⟨ElabTaskError.ioError⟩
structure CancelToken where
ref : IO.Ref Bool
deriving Inhabited
namespace CancelToken
def new : IO CancelToken :=
CancelToken.mk <$> IO.mkRef false
def check [MonadExceptOf ElabTaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do
let c ← tk.ref.get
if c then
throw ElabTaskError.aborted
def set (tk : CancelToken) : IO Unit :=
tk.ref.set true
end CancelToken
/-- A document editable in the sense that we track the environment
and parser state after each command so that edits can be applied
without recompiling code appearing earlier in the file. -/
structure EditableDocument where
meta : DocumentMeta
/- The first snapshot is that after the header. -/
headerSnap : Snapshot
/- Subsequent snapshots occur after each command. -/
cmdSnaps : AsyncList ElabTaskError Snapshot
cancelTk : CancelToken
deriving Inhabited
end Utils
/- Asynchronous snapshot elaboration. -/
section Elab
def publishDiagnostics (m : DocumentMeta) (diagnostics : Array Lsp.Diagnostic) (hOut : FS.Stream) : IO Unit :=
hOut.writeLspNotification {
method := "textDocument/publishDiagnostics"
param := {
uri := m.uri
version? := m.version
diagnostics := diagnostics
: PublishDiagnosticsParams
}
}
def publishMessages (m : DocumentMeta) (msgLog : MessageLog) (hOut : FS.Stream) : IO Unit := do
let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text)
publishDiagnostics m diagnostics.toArray hOut
/-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/
private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream)
: ExceptT ElabTaskError IO Snapshot := do
cancelTk.check
let maybeSnap ← compileNextCmd m.text.source parentSnap
-- TODO(MH): check for interrupt with increased precision
cancelTk.check
match maybeSnap with
| Sum.inl snap =>
/- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones
while prefering newer versions over old ones. The former is necessary because we do
not explicitly clear older diagnostics, while the latter is necessary because we do
not guarantee that diagnostics are emitted in order. Specifically, it may happen that
we interrupted this elaboration task right at this point and a newer elaboration task
emits diagnostics, after which we emit old diagnostics because we did not yet detect
the interrupt. Explicitly clearing diagnostics is difficult for a similar reason,
because we cannot guarantee that no further diagnostics are emitted after clearing
them. -/
publishMessages m (snap.msgLog.add {
fileName := "<ignored>"
pos := m.text.toPosition snap.endPos
severity := MessageSeverity.information
data := "processing..."
}) hOut
snap
| Sum.inr msgLog =>
publishMessages m msgLog hOut
throw ElabTaskError.eof
/-- Elaborates all commands after `initSnap`, emitting the diagnostics into `hOut`. -/
def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream)
(initial : Bool) :
IO (AsyncList ElabTaskError Snapshot) := do
if initial && initSnap.msgLog.hasErrors then
-- treat header processing errors as fatal so users aren't swamped with followup errors
AsyncList.nil
else
AsyncList.unfoldAsync (nextCmdSnap m . cancelTk hOut) initSnap
end Elab
-- Pending requests are tracked so they can be cancelled
abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) (fun a b => Decidable.decide (a < b))
structure ServerContext where
hIn : FS.Stream
hOut : FS.Stream
hLog : FS.Stream
srcSearchPath : SearchPath
docRef : IO.Ref EditableDocument
pendingRequestsRef : IO.Ref PendingRequestMap
abbrev ServerM := ReaderT ServerContext IO
/- Worker initialization sequence. -/
section Initialization
/-- Use `leanpkg print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`.
Compilation progress is reported to `hOut` via LSP notifications. Return the search path for
source files. -/
partial def leanpkgSetupSearchPath (leanpkgPath : String) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do
let leanpkgProc ← Process.spawn {
stdin := Process.Stdio.null
stdout := Process.Stdio.piped
stderr := Process.Stdio.piped
cmd := leanpkgPath
args := #["print-paths"] ++ imports.map (toString ·.module)
}
-- progress notification: report latest stderr line
let rec processStderr (acc : String) : IO String := do
let line ← leanpkgProc.stderr.getLine
if line == "" then
return acc
else
publishDiagnostics m #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }] hOut
processStderr (acc ++ line)
let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated
let stdout := String.trim (← leanpkgProc.stdout.readToEnd)
let stderr ← IO.ofExcept stderr.get
if (← leanpkgProc.wait) == 0 then
match stdout.split (· == '\n') with
| [""] => pure [] -- e.g. no leanpkg.toml
| [leanPath, leanSrcPath] => let sp ← getBuiltinSearchPath
let sp ← addSearchPathFromEnv sp
let sp ← parseSearchPath leanPath sp
searchPathRef.set sp
let srcPath := parseSearchPath leanSrcPath
srcPath.mapM realPathNormalized
| _ => throw <| IO.userError s!"unexpected output from `leanpkg print-paths`:\n{stdout}\nstderr:\n{stderr}"
else
throw <| IO.userError s!"`leanpkg print-paths` failed:\n{stdout}\nstderr:\n{stderr}"
def compileHeader (m : DocumentMeta) (hOut : FS.Stream) : IO (Snapshot × SearchPath) := do
let opts := {} -- TODO
let inputCtx := Parser.mkInputContext m.text.source "<input>"
let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx
let leanpkgPath ← match ← IO.getEnv "LEAN_SYSROOT" with
| some path => s!"{path}/bin/leanpkg{System.FilePath.exeSuffix}"
| _ => s!"{← appDir}/leanpkg{System.FilePath.exeSuffix}"
let mut srcSearchPath := [s!"{← appDir}/../lib/lean/src"]
if let some p := (← IO.getEnv "LEAN_SRC_PATH") then
srcSearchPath := srcSearchPath ++ parseSearchPath p
let (headerEnv, msgLog) ← try
-- NOTE: leanpkg does not exist in stage 0 (yet?)
if (← fileExists leanpkgPath) then
let pkgSearchPath ← leanpkgSetupSearchPath leanpkgPath m (Lean.Elab.headerToImports headerStx).toArray hOut
srcSearchPath := srcSearchPath ++ pkgSearchPath
Elab.processHeader headerStx opts msgLog inputCtx
catch e => -- should be from `leanpkg print-paths`
let msgs := MessageLog.empty.add { fileName := "<ignored>", pos := ⟨0, 0⟩, data := e.toString }
publishMessages m msgs hOut
pure (← mkEmptyEnvironment, msgs)
let cmdState := Elab.Command.mkState headerEnv msgLog opts
let cmdState := { cmdState with infoState.enabled := true, scopes := [{ header := "", opts := opts }] }
let headerSnap := {
beginPos := 0
stx := headerStx
mpState := headerParserState
cmdState := cmdState
}
return (headerSnap, srcSearchPath)
def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream)
: IO ServerContext := do
/- NOTE(WN): `toFileMap` marks line beginnings as immediately following
"\n", which should be enough to handle both LF and CRLF correctly.
This is because LSP always refers to characters by (line, column),
so if we get the line number correct it shouldn't matter that there
is a CR there. -/
let (headerSnap, srcSearchPath) ← compileHeader meta o
let cancelTk ← CancelToken.new
let cmdSnaps ← unfoldCmdSnaps meta headerSnap cancelTk o (initial := true)
let doc : EditableDocument := ⟨meta, headerSnap, cmdSnaps, cancelTk⟩
return {
hIn := i
hOut := o
hLog := e
srcSearchPath := srcSearchPath
docRef := ←IO.mkRef doc
pendingRequestsRef := ←IO.mkRef RBMap.empty
}
end Initialization
section Updates
def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : ServerM Unit := do
(←read).pendingRequestsRef.modify map
/-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source,
updates editable doc state. -/
def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : ServerM Unit := do
-- The watchdog only restarts the file worker when the syntax tree of the header changes.
-- If e.g. a newline is deleted, it will not restart this file worker, but we still
-- need to reparse the header so that the offsets are correct.
let st ← read
let oldDoc ← st.docRef.get
let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap
if newHeaderSnap.stx != oldDoc.headerSnap.stx then
throwServerError "Internal server error: header changed but worker wasn't restarted."
let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix
match e? with
-- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks
-- do not show up in `snapshots` of an EditableDocument.
| some ElabTaskError.aborted =>
throwServerError "Internal server error: elab task was aborted while still in use."
| some (ElabTaskError.ioError ioError) => throw ioError
| _ => -- No error or EOF
oldDoc.cancelTk.set
-- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only
-- when really necessary, we could do a whitespace-aware `Syntax` comparison instead.
let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos)
if validSnaps.length = 0 then
let cancelTk ← CancelToken.new
let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.hOut (initial := true)
st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩
else
/- When at least one valid non-header snap exists, it may happen that a change does not fall
within the syntactic range of that last snap but still modifies it by appending tokens.
We check for this here. We do not currently handle crazy grammars in which an appended
token can merge two or more previous commands into one. To do so would require reparsing
the entire file. -/
let mut lastSnap := validSnaps.getLast!
let preLastSnap :=
if validSnaps.length ≥ 2
then validSnaps.get! (validSnaps.length - 2)
else newHeaderSnap
let newLastStx ← parseNextCmd newMeta.text.source preLastSnap
if newLastStx != lastSnap.stx then
validSnaps ← validSnaps.dropLast
lastSnap ← preLastSnap
let cancelTk ← CancelToken.new
let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk st.hOut (initial := false)
let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps
st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩
end Updates
/- Notifications are handled in the main thread. They may change global worker state
such as the current file contents. -/
section NotificationHandling
def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do
let docId := p.textDocument
let changes := p.contentChanges
let oldDoc ← (←read).docRef.get
let some newVersion ← pure docId.version?
| throwServerError "Expected version number"
if newVersion ≤ oldDoc.meta.version then
-- TODO(WN): This happens on restart sometimes.
IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}"
else if ¬ changes.isEmpty then
let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text
updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff
def handleCancelRequest (p : CancelParams) : ServerM Unit := do
updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id)
end NotificationHandling
/- Request handlers are given by `Task`s executed asynchronously. They may be cancelled at any time,
so they should check the cancellation token when possible to handle this cooperatively. Any exceptions
thrown in a handler will be reported to the client as LSP error responses. -/
section RequestHandling
structure RequestError where
code : ErrorCode
message : String
namespace RequestError
def fileChanged : RequestError :=
{ code := ErrorCode.contentModified
message := "File changed." }
end RequestError
-- TODO(WN): the type is too complicated
abbrev RequestM α := ServerM $ Task $ Except IO.Error $ Except RequestError α
def mapTask (t : Task α) (f : α → ExceptT RequestError ServerM β) : RequestM β := fun st =>
(IO.mapTask · t) fun a => f a st
/-- Create a task which waits for a snapshot matching `p`, handles various errors,
and if a matching snapshot was found executes `x` with it. If not found, the task
executes `notFoundX`. -/
def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool)
(notFoundX : ExceptT RequestError ServerM β)
(x : Snapshot → ExceptT RequestError ServerM β)
: ServerM (Task (Except IO.Error (Except RequestError β))) := do
let findTask ← doc.cmdSnaps.waitFind? p
mapTask findTask fun
| Except.error ElabTaskError.aborted =>
throwThe RequestError RequestError.fileChanged
| Except.error (ElabTaskError.ioError e) =>
throwThe IO.Error e
| Except.error ElabTaskError.eof => notFoundX
| Except.ok none => notFoundX
| Except.ok (some snap) => x snap
/- Requests that need data from a certain command should traverse the snapshots
by successively getting the next task, meaning that we might need to wait for elaboration.
When that happens, the request should send a "content changed" error to the user
(this way, the server doesn't get bogged down in requests for an old state of the document).
Requests need to manually check for whether their task has been cancelled, so that they
can reply with a RequestCancelled error. -/
partial def handleCompletion (p : CompletionParams) :
ServerM (Task (Except IO.Error (Except RequestError CompletionList))) := do
let st ← read
let doc ← st.docRef.get
let text := doc.meta.text
let pos := text.lspPosToUtf8Pos p.position
-- dbg_trace ">> handleCompletion invoked {pos}"
withWaitFindSnap doc (fun s => s.endPos > pos)
(notFoundX := pure { items := #[], isIncomplete := true }) fun snap => do
for infoTree in snap.cmdState.infoState.trees do
-- for (ctx, info) in infoTree.getCompletionInfos do
-- dbg_trace "{← info.format ctx}"
if let some r ← Completion.find? doc.meta.text pos infoTree then
return r
return { items := #[ ], isIncomplete := true }
open Elab in
partial def handleHover (p : HoverParams)
: ServerM (Task (Except IO.Error (Except RequestError (Option Hover)))) := do
let st ← read
let doc ← st.docRef.get
let text := doc.meta.text
let mkHover (s : String) (f : String.Pos) (t : String.Pos) : Hover :=
{ contents := { kind := MarkupKind.markdown
value := s }
range? := some { start := text.utf8PosToLspPos f
«end» := text.utf8PosToLspPos t } }
let hoverPos := text.lspPosToUtf8Pos p.position
withWaitFindSnap doc (fun s => s.endPos > hoverPos)
(notFoundX := pure none) fun snap => do
for t in snap.cmdState.infoState.trees do
if let some (ci, i) := t.hoverableInfoAt? hoverPos then
if let some hoverFmt ← i.fmtHover? ci then
return some <| mkHover (toString hoverFmt) i.pos?.get! i.tailPos?.get!
return none
open Elab in
partial def handleDefinition (goToType? : Bool) (p : TextDocumentPositionParams)
: ServerM (Task (Except IO.Error (Except RequestError (Array LocationLink)))) := do
let st ← read
let doc ← st.docRef.get
let text := doc.meta.text
let hoverPos := text.lspPosToUtf8Pos p.position
withWaitFindSnap doc (fun s => s.endPos > hoverPos)
(notFoundX := pure #[]) fun snap => do
for t in snap.cmdState.infoState.trees do
if let some (ci, Info.ofTermInfo i) := t.hoverableInfoAt? hoverPos then
let mut expr := i.expr
if goToType? then
expr ← ci.runMetaM i.lctx do
Meta.instantiateMVars (← Meta.inferType expr)
if let some n := expr.constName? then
let mod? ← ci.runMetaM i.lctx <| findModuleOf? n
let modUri? ← match mod? with
| some modName =>
let modFname? ← st.srcSearchPath.findWithExt ".lean" modName
pure <| modFname?.map toFileUri
| none => pure <| some doc.meta.uri
let ranges? ← ci.runMetaM i.lctx <| findDeclarationRanges? n
if let (some ranges, some modUri) := (ranges?, modUri?) then
let declRangeToLspRange (r : DeclarationRange) : Lsp.Range :=
{ start := ⟨r.pos.line - 1, r.charUtf16⟩
«end» := ⟨r.endPos.line - 1, r.endCharUtf16⟩ }
let ll : LocationLink := {
originSelectionRange? := some ⟨text.utf8PosToLspPos i.stx.getPos?.get!,
text.utf8PosToLspPos i.stx.getTailPos?.get!⟩
targetUri := modUri
targetRange := declRangeToLspRange ranges.range
targetSelectionRange := declRangeToLspRange ranges.selectionRange
}
return #[ll]
return #[]
open Elab in
partial def handlePlainGoal (p : PlainGoalParams)
: ServerM (Task (Except IO.Error (Except RequestError (Option PlainGoal)))) := do
let st ← read
let doc ← st.docRef.get
let text := doc.meta.text
let hoverPos := text.lspPosToUtf8Pos p.position
withWaitFindSnap doc (fun s => s.endPos > hoverPos)
(notFoundX := return none) fun snap => do
for t in snap.cmdState.infoState.trees do
if let rs@(_ :: _) := t.goalsAt? hoverPos then
let goals ← List.join <$> rs.mapM fun { ctxInfo := ci, tacticInfo := ti, useAfter := useAfter } =>
let ci := if useAfter then { ci with mctx := ti.mctxAfter } else { ci with mctx := ti.mctxBefore }
let goals := if useAfter then ti.goalsAfter else ti.goalsBefore
ci.runMetaM {} <| goals.mapM (fun g => Meta.withPPInaccessibleNames (Meta.ppGoal g))
let md :=
if goals.isEmpty then
"no goals"
else
let goals := goals.map fun goal => s!"```lean
{goal}
```"
String.intercalate "\n---\n" goals
return some { goals := goals.map toString |>.toArray, rendered := md }
return none
def rangeOfSyntax (text : FileMap) (stx : Syntax) : Range :=
⟨text.utf8PosToLspPos <| stx.getPos?.get!,
text.utf8PosToLspPos <| stx.getTailPos?.get!⟩
partial def handleDocumentHighlight (p : DocumentHighlightParams) :
ServerM (Task (Except IO.Error (Except RequestError (Array DocumentHighlight)))) := do
let doc ← (← read).docRef.get
let text := doc.meta.text
let pos := text.lspPosToUtf8Pos p.position
let rec highlightReturn? (doRange? : Option Range) : Syntax → Option DocumentHighlight
| stx@`(doElem|return%$i $e) =>
if stx.getPos?.get! <= pos && pos < stx.getTailPos?.get! then
some { range := doRange?.getD (rangeOfSyntax text i), kind? := DocumentHighlightKind.text }
else
highlightReturn? doRange? e
| `(do%$i $elems) => highlightReturn? (rangeOfSyntax text i) elems
| stx => stx.getArgs.findSome? (highlightReturn? doRange?)
withWaitFindSnap doc (fun s => s.endPos > pos)
(notFoundX := pure #[]) fun snap => do
if let some hi := highlightReturn? none snap.stx then
return #[hi]
return #[]
partial def handleDocumentSymbol (p : DocumentSymbolParams) :
ServerM (Task (Except IO.Error (Except RequestError DocumentSymbolResult))) := do
let st ← read
asTask do
let doc ← st.docRef.get
let ⟨cmdSnaps, e?⟩ ← doc.cmdSnaps.updateFinishedPrefix
let mut stxs := cmdSnaps.finishedPrefix.map Snapshot.stx
match e? with
| some ElabTaskError.aborted =>
return Except.error RequestError.fileChanged
| some _ => pure () -- TODO(WN): what to do on ioError?
| none =>
let lastSnap := cmdSnaps.finishedPrefix.getLastD doc.headerSnap
stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList
let (syms, _) := toDocumentSymbols doc.meta.text stxs
return Except.ok { syms := syms.toArray }
where
toDocumentSymbols (text : FileMap)
| [] => ([], [])
| stx::stxs => match stx with
| `(namespace $id) => sectionLikeToDocumentSymbols text stx stxs (id.getId.toString) SymbolKind.namespace id
| `(section $(id)?) => sectionLikeToDocumentSymbols text stx stxs ((·.getId.toString) <$> id |>.getD "<section>") SymbolKind.namespace (id.getD stx)
| `(end $(id)?) => ([], stx::stxs)
| _ =>
let (syms, stxs') := toDocumentSymbols text stxs
if stx.isOfKind ``Lean.Parser.Command.declaration then
let (name, selection) := match stx with
| `($dm:declModifiers $ak:attrKind instance $[$np:namedPrio]? $[$id:ident$[.{$ls,*}]?]? $sig:declSig $val) =>
((·.getId.toString) <$> id |>.getD s!"instance {sig.reprint.getD ""}", id.getD sig)
| _ => match stx[1][1] with
| `(declId|$id:ident$[.{$ls,*}]?) => (id.getId.toString, id)
| _ => (stx[1][0].isIdOrAtom?.getD "<unknown>", stx[1][0])
(DocumentSymbol.mk {
name := name
kind := SymbolKind.method
range := rangeOfSyntax text stx
selectionRange := rangeOfSyntax text selection
} :: syms, stxs')
else
(syms, stxs')
sectionLikeToDocumentSymbols (text : FileMap) (stx : Syntax) (stxs : List Syntax) (name : String) (kind : SymbolKind) (selection : Syntax) :=
let (syms, stxs') := toDocumentSymbols text stxs
-- discard `end`
let (syms', stxs'') := toDocumentSymbols text (stxs'.drop 1)
let endStx := match stxs' with
| endStx::_ => endStx
| [] => (stx::stxs').getLast!
(DocumentSymbol.mk {
name := name
kind := kind
range := ⟨(rangeOfSyntax text stx).start, (rangeOfSyntax text endStx).«end»⟩
selectionRange := rangeOfSyntax text selection
children? := syms.toArray
} :: syms', stxs'')
def noHighlightKinds : Array SyntaxNodeKind := #[
-- usually have special highlighting by the client
``Lean.Parser.Term.sorry,
``Lean.Parser.Term.type,
``Lean.Parser.Term.prop,
-- not really keywords
`antiquotName,
``Lean.Parser.Command.docComment]
structure SemanticTokensContext where
beginPos : String.Pos
endPos : String.Pos
text : FileMap
infoState : Elab.InfoState
structure SemanticTokensState where
data : Array Nat
lastLspPos : Lsp.Position
partial def handleSemanticTokens (beginPos endPos : String.Pos) :
ServerM (Task (Except IO.Error (Except RequestError SemanticTokens))) := do
let st ← read
let doc ← st.docRef.get
let text := doc.meta.text
let t ← doc.cmdSnaps.waitAll (·.beginPos < endPos)
IO.mapTask (t := t) fun (snaps, _) =>
StateT.run' (s := { data := #[], lastLspPos := ⟨0, 0⟩ : SemanticTokensState }) do
for s in snaps do
if s.endPos <= beginPos then
continue
ReaderT.run (r := SemanticTokensContext.mk beginPos endPos text s.cmdState.infoState) <|
go s.stx
return Except.ok { data := (← get).data }
where
go (stx : Syntax) := do
match stx with
| `($e.$id:ident) => go e; addToken id SemanticTokenType.property
-- indistinguishable from next pattern
--| `(level|$id:ident) => addToken id SemanticTokenType.variable
| `($id:ident) => highlightId id
| _ =>
if !noHighlightKinds.contains stx.getKind then
highlightKeyword stx
if stx.isOfKind choiceKind then
go stx[0]
else
stx.getArgs.forM go
highlightId (stx : Syntax) : ReaderT SemanticTokensContext (StateT SemanticTokensState IO) _ := do
if let (some pos, some tailPos) := (stx.getPos?, stx.getTailPos?) then
for t in (← read).infoState.trees do
for ti in t.deepestNodes (fun
| _, i@(Elab.Info.ofTermInfo ti) => match i.pos? with
| some ipos => if pos <= ipos && ipos < tailPos then some ti else none
| _ => none
| _, _ => none) do
match ti.expr with
| Expr.fvar .. => addToken ti.stx SemanticTokenType.variable
| _ => if ti.stx.getPos?.get! > pos then addToken ti.stx SemanticTokenType.property
highlightKeyword stx := do
if let Syntax.atom info val := stx then
if val.bsize > 0 && val[0].isAlpha then
addToken stx SemanticTokenType.keyword
addToken stx type := do
let ⟨beginPos, endPos, text, _⟩ ← read
if let (some pos, some tailPos) := (stx.getPos?, stx.getTailPos?) then
if beginPos <= pos && pos < endPos then
let lspPos := (← get).lastLspPos
let lspPos' := text.utf8PosToLspPos pos
let deltaLine := lspPos'.line - lspPos.line
let deltaStart := lspPos'.character - (if lspPos'.line == lspPos.line then lspPos.character else 0)
let length := (text.utf8PosToLspPos tailPos).character - lspPos'.character
let tokenType := type.toNat
let tokenModifiers := 0
modify fun st => {
data := st.data ++ #[deltaLine, deltaStart, length, tokenType, tokenModifiers]
lastLspPos := lspPos'
}
def handleSemanticTokensFull (p : SemanticTokensParams) :
ServerM (Task (Except IO.Error (Except RequestError SemanticTokens))) := do
handleSemanticTokens 0 (1 <<< 16)
def handleSemanticTokensRange (p : SemanticTokensRangeParams) :
ServerM (Task (Except IO.Error (Except RequestError SemanticTokens))) := do
let st ← read
let doc ← st.docRef.get
let text := doc.meta.text
let beginPos := text.lspPosToUtf8Pos p.range.start
let endPos := text.lspPosToUtf8Pos p.range.end
handleSemanticTokens beginPos endPos
partial def handleWaitForDiagnostics (p : WaitForDiagnosticsParams)
: ServerM (Task (Except IO.Error (Except RequestError WaitForDiagnostics))) := do
let st ← read
let rec waitLoop : IO EditableDocument := do
let doc ← st.docRef.get
if p.version ≤ doc.meta.version then
return doc
else
IO.sleep 50
waitLoop
let t ← IO.asTask waitLoop
let t ← IO.bindTask t fun
| Except.error e => unreachable!
| Except.ok doc => do
let t₁ ← doc.cmdSnaps.waitAll
return t₁.map fun _ => Except.ok WaitForDiagnostics.mk
return t.map fun _ => Except.ok <| Except.ok WaitForDiagnostics.mk
end RequestHandling
section MessageHandling
def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=
match fromJson? params with
| some parsed => pure parsed
| none => throwServerError s!"Got param with wrong structure: {params.compress}"
def handleNotification (method : String) (params : Json) : ServerM Unit := do
let handle := fun paramType [FromJson paramType] (handler : paramType → ServerM Unit) =>
parseParams paramType params >>= handler
match method with
| "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange
| "$/cancelRequest" => handle CancelParams handleCancelRequest
| _ => throwServerError s!"Got unsupported notification method: {method}"
def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit))
: ServerM Unit := do
updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask)
def handleRequest (id : RequestID) (method : String) (params : Json)
: ServerM Unit := do
let handle := fun paramType [FromJson paramType] respType [ToJson respType]
(handler : paramType → RequestM respType) => do
let st ← read
let p ← parseParams paramType params
let t ← handler p
let t₁ ← (IO.mapTask · t) fun
| Except.ok (Except.ok resp) =>
st.hOut.writeLspResponse ⟨id, resp⟩
| Except.ok (Except.error e) =>
st.hOut.writeLspResponseError { id := id, code := e.code, message := e.message }
| Except.error e =>
st.hOut.writeLspResponseError { id := id, code := ErrorCode.internalError, message := toString e }
queueRequest id t₁
match method with
| "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParams WaitForDiagnostics handleWaitForDiagnostics
| "textDocument/completion" => handle CompletionParams CompletionList handleCompletion
| "textDocument/hover" => handle HoverParams (Option Hover) handleHover
| "textDocument/declaration" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := false)
| "textDocument/definition" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := false)
| "textDocument/typeDefinition" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := true)
| "textDocument/documentHighlight" => handle DocumentHighlightParams DocumentHighlightResult handleDocumentHighlight
| "textDocument/documentSymbol" => handle DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol
| "textDocument/semanticTokens/full" => handle SemanticTokensParams SemanticTokens handleSemanticTokensFull
| "textDocument/semanticTokens/range" => handle SemanticTokensRangeParams SemanticTokens handleSemanticTokensRange
| "$/lean/plainGoal" => handle PlainGoalParams (Option PlainGoal) handlePlainGoal
| _ => throwServerError s!"Got unsupported request: {method}"
end MessageHandling
section MainLoop
partial def mainLoop : ServerM Unit := do
let st ← read
let msg ← st.hIn.readLspMessage
let pendingRequests ← st.pendingRequestsRef.get
let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit))
: ServerM PendingRequestMap := do
if (←hasFinished task) then
/- Handler tasks are constructed so that the only possible errors here
are failures of writing a response into the stream. -/
if let Except.error e := task.get then
throwServerError s!"Failed responding to request {id}: {e}"
acc.erase id
else acc
let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests
st.pendingRequestsRef.set pendingRequests
match msg with
| Message.request id method (some params) =>
handleRequest id method (toJson params)
mainLoop
| Message.notification "exit" none =>
let doc ← st.docRef.get
doc.cancelTk.set
return ()
| Message.notification method (some params) =>
handleNotification method (toJson params)
mainLoop
| _ => throwServerError "Got invalid JSON-RPC message"
end MainLoop
def initAndRunWorker (i o e : FS.Stream) : IO UInt32 := do
let i ← maybeTee "fwIn.txt" false i
let o ← maybeTee "fwOut.txt" true o
-- TODO(WN): act in accordance with InitializeParams
let _ ← i.readLspRequestAs "initialize" InitializeParams
let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams
let doc := param.textDocument
let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩
let e ← e.withPrefix s!"[{param.textDocument.uri}] "
let _ ← IO.setStderr e
try
let ctx ← initializeWorker meta i o e
ReaderT.run (r := ctx) mainLoop
return 0
catch e =>
IO.eprintln e
publishDiagnostics meta #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }] o
return 1
@[export lean_server_worker_main]
def workerMain : IO UInt32 := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
try
initAndRunWorker i o e
catch err =>
e.putStrLn s!"worker initialization error: {err}"
return (1 : UInt32)
end Lean.Server.FileWorker
|
f55e042652a40313bd87e3e12109e760642dca6c | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/lua6.lean | 5f3bc1e5dca211088e612aa1bc14be055afc06ff | [
"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 | 327 | lean | import Int.
variable x : Int
set_option pp::notation false
(*
print(get_options())
*)
check x + 2
(*
o = get_options()
o = o:update(name('lean', 'pp', 'notation'), true)
set_options(o)
print(get_options())
*)
check x + 2
(*
set_option(name('lean', 'pp', 'notation'), false)
print(get_options())
*)
variable y : Int
check x + y
|
264ecc84fd01d56cfbc2b13cedba449803cd44aa | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/data/nat/parity.lean | 057815b1e1f381289efd5dd40736b385864aba28 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 2,714 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The `even` predicate on the natural numbers.
-/
import .modeq
namespace nat
@[simp] theorem mod_two_ne_one {n : nat} : ¬ n % 2 = 1 ↔ n % 2 = 0 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
@[simp] theorem mod_two_ne_zero {n : nat} : ¬ n % 2 = 0 ↔ n % 2 = 1 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
def even (n : nat) : Prop := 2 ∣ n
theorem even_iff {n : nat} : even n ↔ n % 2 = 0 :=
⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩
instance : decidable_pred even :=
λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm
run_cmd mk_simp_attr `parity_simps
@[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩
@[simp] theorem not_even_one : ¬ even 1 :=
by rw even_iff; apply one_ne_zero
@[simp] theorem even_bit0 (n : nat) : even (bit0 n) :=
⟨n, by rw [bit0, two_mul]⟩
@[parity_simps] theorem even_add {m n : nat} : even (m + n) ↔ (even m ↔ even n) :=
begin
cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂;
simp [even_iff, h₁, h₂],
{ exact @modeq.modeq_add _ _ 0 _ 0 h₁ h₂ },
{ exact @modeq.modeq_add _ _ 0 _ 1 h₁ h₂ },
{ exact @modeq.modeq_add _ _ 1 _ 0 h₁ h₂ },
exact @modeq.modeq_add _ _ 1 _ 1 h₁ h₂
end
@[simp] theorem not_even_bit1 (n : nat) : ¬ even (bit1 n) :=
by simp [bit1] with parity_simps
@[parity_simps] theorem even_sub {m n : nat} (h : m ≥ n) : even (m - n) ↔ (even m ↔ even n) :=
begin
conv { to_rhs, rw [←nat.sub_add_cancel h, even_add] },
by_cases h : even n; simp [h]
end
@[parity_simps] theorem even_succ {n : nat} : even (succ n) ↔ ¬ even n :=
by rw [succ_eq_add_one, even_add]; simp [not_even_one]
@[parity_simps] theorem even_mul {m n : nat} : even (m * n) ↔ even m ∨ even n :=
begin
cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂;
simp [even_iff, h₁, h₂],
{ exact @modeq.modeq_mul _ _ 0 _ 0 h₁ h₂ },
{ exact @modeq.modeq_mul _ _ 0 _ 1 h₁ h₂ },
{ exact @modeq.modeq_mul _ _ 1 _ 0 h₁ h₂ },
exact @modeq.modeq_mul _ _ 1 _ 1 h₁ h₂
end
@[parity_simps] theorem even_pow {m n : nat} : even (m^n) ↔ even m ∧ n ≠ 0 :=
by { induction n with n ih; simp [*, pow_succ, even_mul], tauto }
-- Here are examples of how `parity_simps` can be used with `nat`.
example (m n : nat) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) :=
by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps
example : ¬ even 25394535 :=
by simp
end nat
|
489337df08446e96b2664b41a03135dfd212cf85 | bce603343785d07c32cb8b35950aba0b4d9415ae | /lean3/src/cryptomorphism.lean | d8112c7e0515b9f055225934fd06554f7721f577 | [] | no_license | fpvandoorn/cryptomorphism | db00cf0b12c8fd561a6200eee6a6ff2a023f1228 | d486419ecced54de3db759dae81110be44b7c28b | refs/heads/master | 1,693,198,883,854 | 1,636,562,038,000 | 1,636,562,038,000 | 363,219,330 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,323 | lean | import tactic
/-!
A start on detecting cryptomorphic structures.
Proposed algorithm when the data fields are the same:
* Look at the bijection of the data fields where the structures have the most axioms in common
* Try to prove the remaining axioms of each structure from the axioms of the other field.
To do:
Support `extends` keyword (with and without `old_structure_cmd` option)
-/
open tactic native
universe variable u
namespace list
variables {α β γ δ ε ζ : Type*}
def zip_with3 (f : α → β → γ → δ) : list α → list β → list γ → list δ
| (x::xs) (y::ys) (z::zs) := f x y z :: zip_with3 xs ys zs
| _ _ _ := []
def zip_with4 (f : α → β → γ → δ → ε) : list α → list β → list γ → list δ → list ε
| (x::xs) (y::ys) (z::zs) (u::us) := f x y z u :: zip_with4 xs ys zs us
| _ _ _ _ := []
def zip_with5 (f : α → β → γ → δ → ε → ζ) : list α → list β → list γ → list δ → list ε → list ζ
| (x::xs) (y::ys) (z::zs) (u::us) (v::vs) := f x y z u v :: zip_with5 xs ys zs us vs
| _ _ _ _ _ := []
end list
meta instance : inhabited declaration :=
⟨declaration.ax name.anonymous [] (expr.sort level.zero)⟩
@[derive inhabited]
meta structure field_data : Type :=
(local_constant : expr)
(type : expr)
(depends : name_set)
(is_prop : bool)
open format
meta instance : has_to_format field_data :=
⟨λ ⟨a, b, c, d⟩, group (nest 1 (to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt "," ++ line ++ to_fmt c ++ to_fmt "," ++ line ++ to_fmt d ++ to_fmt "⟩"))⟩
meta instance : has_to_tactic_format field_data :=
⟨λ ⟨a, b, c, d⟩, (λ x, group (nest 1 (to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ x ++ to_fmt "," ++ line ++ to_fmt c ++ to_fmt "," ++ line ++ to_fmt d ++ to_fmt "⟩"))) <$> pp b⟩
namespace name
/-- Update the last component of a name -/
def update_suffix (f : string → string) : name → name
| (mk_string s n) := mk_string (f s) n
| n := n
end name
namespace expr
/-- Replace `nm args` for `nm` in `nms` by the expression in the `name_map`. -/
meta def replace_const (e : expr) (nms : name_map expr) (args : list expr) : expr :=
e.replace $ λ subterm n,
let data := nms.find subterm.get_app_fn.const_name in
if data.is_some && (subterm.get_app_args = args) then data.iget else none
/-- Returns the pretty names of all local constants in an expression. -/
meta def list_local_const_pretty_names (e : expr) : name_set :=
e.fold mk_name_set
(λ e' _ es, if e'.is_local_constant then es.insert e'.local_pp_name else es)
end expr
namespace name_set
/-- Erase a list of names from a name_set -/
meta def erase_list (ns : name_set) (nms : list name) : name_set :=
nms.foldl name_set.erase ns
end name_set
/-- `is_in e l` tests whether `e` is definitionally equal to an expression in `l`. -/
meta def is_in : expr → list expr → tactic bool
| e [] := return ff
| e (t :: ts) := (is_def_eq e t >> return tt) <|> is_in e ts
/-- like `assert h t`, but without swapping goals. -/
meta def add_to_context (h : name) (t : expr) : tactic expr :=
do assert_core h t, swap, e ← intro h, return e
-- /-- Get field data, with types of fields instantiated by `args` -/
-- meta def get_field_data (nm : name) (args : list expr) : tactic $ list field_data := retrieve $ do
-- e ← get_env,
-- fields ← e.structure_fields_full nm,
-- axiom_fields ← fields.mmap $ λ nm, mk_const nm >>= is_proof,
-- types ← fields.mmap $ λ nm, (e.get nm).to_option.iget.type.drop_pis args,
-- let depends := types.map $ λ tp, tp.list_names_with_prefix nm,
-- return $ fields.zip_with4 field_data.mk types depends axiom_fields
/-- Add fields to context, and returns data -/
meta def add_fields_to_context (nm : name) (pref : name) (args : list expr) :
tactic $ list field_data := do
e ← get_env,
d ← e.get nm,
guard $ e.is_structure nm,
e_str ← mk_app nm args,
cls ← add_to_context pref e_str,
[(_, field_exprs)] ← cases cls,
fields ← return $ field_exprs.map expr.local_pp_name,
axiom_fields ← field_exprs.mmap is_proof,
types ← field_exprs.mmap infer_type,
let depends := types.map $ λ tp, tp.list_local_const_pretty_names,
return $ field_exprs.zip_with4 field_data.mk types depends axiom_fields
-- for testing
meta def trivial_mapping (fields1 fields2 : list field_data) : tactic $ list (name × expr) := do
let data_fields := fields1.filter $ λ info, !info.is_prop,
mapping ← data_fields.mmap $ λ info, prod.mk info.local_constant.local_uniq_name <$>
get_local (info.local_constant.local_pp_name.update_suffix $ λ s, "h2" ++ s.popn 2) <|> fail "Not all data fields occur in the second class.",
return mapping
-- todo
meta def all_mappings (fields1 fields2 : list field_data) : tactic $ list $ list (name × expr) := do
let data_fields1 := fields1.filter $ λ info, !info.is_prop,
let data_fields2 := fields2.filter $ λ info, !info.is_prop,
failed
/-- Find which axioms in fields1 also occur in fields2 under the renaming `mapping`. -/
meta def matching_axioms (fields1 fields2 : list field_data) (mapping : list (name × expr)) :
tactic $ list field_data := do
let prop_fields := fields1.filter $ λ info, info.is_prop,
let types2 : list expr := fields2.filter_map $ λ info, if info.is_prop then info.type else none,
matches ← prop_fields.mfilter $ λ info, is_in (info.type.instantiate_locals mapping) types2,
return matches
/-- The tactic we use to automatically prove axioms. -/
meta def current_automation : tactic unit :=
tidy >> (done <|> tactic.interactive.finish [] none)
/-- Tries to prove `e` in the local context, returns tt if successful. -/
meta def try_to_prove (e : expr) : tactic bool := retrieve $ do
assert `h e,
succeeds $ focus1 $ current_automation >> done
/-- Tests whether nm1 is a subclass of nm1. Currently the data fields must have the same name for
this tactic to work. -/
meta def is_subclass (nm1 nm2 : name) (show_state := ff) : tactic unit :=
(if show_state then id else retrieve : tactic unit → tactic unit) $ do
M ← add_to_context `M (expr.sort $ (level.param `u).succ),
info1 ← add_fields_to_context nm1 `h1 [M],
info2 ← add_fields_to_context nm2 `h2 [M],
mapping ← trivial_mapping info1 info2,
n ← matching_axioms info1 info2 mapping,
let n_uniqs := n.map $ λ info, info.local_constant.local_uniq_name,
let todo := info1.filter $ λ info, info.is_prop ∧ info.local_constant.local_uniq_name ∉ n_uniqs,
if todo.length = 0 then
trace!"{nm1} is a trivial subclass of {nm2}: {nm2} has all the fields that {nm1} has." else do
-- trace $ todo.map $ λ info, info.local_constant.local_pp_name,
cannot_prove ← todo.mfilter $ λ info, bnot <$> try_to_prove (info.type.instantiate_locals mapping),
-- trace $ cannot_prove.map $ λ info, info.local_constant.local_pp_name,
if cannot_prove.length = 0 then
trace!"{nm1} is a subclass of {nm2}: {nm2} has all the data fields of {nm1}, and all the axioms of {nm1} can be proven from the axioms of {nm2}."
else
trace!"Cannot prove the following axioms of {nm1} from the axioms of {nm2}:
{cannot_prove.map $ λ info, info.local_constant.local_pp_name.update_suffix $ λ s, s.popn 3}."
-- run_cmd retrieve $ do
-- e ← get_env,
-- M ← add_to_context `M (expr.sort $ (level.param `u).succ),
-- let nm := `comm_monoid1,
-- info1 ← add_fields_to_context `comm_monoid1 `h1 [M],
-- info2 ← add_fields_to_context `comm_monoid2 `h2 [M],
-- map ← trivial_mapping info1 info2,
-- n ← matching_axioms info1 info2 map,
-- trace n.length,
-- trace map,
-- -- d ← get_decl nm,
-- -- guard $ e.is_structure nm,
-- -- (args, _) ← open_pis d.type,
-- -- e_str ← mk_app nm args,
-- -- cls ← add_to_context `h e_str,
-- -- let args := args ++ [cls],
-- -- field_info ← get_field_data nm args,
-- -- guard $ field_info.all $ λ info, info.is_prop || info.depends.empty, -- no dependent data fields
-- -- data_locals ← field_info.mmap $ λ info, cond info.is_prop (return none) $
-- -- (λ x, some (info.field_name, x)) <$> add_to_context info.field_name.last info.type, -- use assertv?
-- -- let data_replacements : name_map expr :=
-- -- rb_map.of_list data_locals.reduce_option,
-- -- let reduced_types := field_info.filter_map $ λ info, cond info.is_prop
-- -- (some $ (info.field_name, info.type.replace_const data_replacements args)) none,
-- -- reduced_types.mmap (λ x, type_check x.2), -- sanity check
-- -- axiom_locals ← reduced_types.mmap $ λ e, add_to_context e.1.last e.2,
-- -- trace reduced_types,
-- -- -- trace $ types,
-- -- trace_state,
-- -- trace field_info,
-- -- trace data_locals,
-- -- trace axiom_locals,
-- -- cases cls,
-- -- trace_state,
-- -- trace $ types.map expr.to_string,
-- -- trace depends,
-- skip
/-! We define two notions of commutative monoids, the first is right-unital and the second is both left-unital and right-unital. -/
class comm_monoid1 (M : Type*) :=
(mul : M → M → M)
(mul_assoc : ∀ x y z, mul (mul x y) z = mul x (mul y z))
(mul_comm : ∀ x y, mul x y = mul y x)
(one : M)
(mul_one : ∀ x, mul x one = x)
class comm_monoid2 (M : Type*) :=
(mul : M → M → M)
(mul_assoc : ∀ x y z, mul (mul x y) z = mul x (mul y z))
(mul_comm : ∀ x y, mul x y = mul y x)
(one : M)
(mul_one : ∀ x, mul x one = x)
(one_mul : ∀ x, mul one x = x)
run_cmd is_subclass `comm_monoid1 `comm_monoid2
/- Output: comm_monoid1 is a trivial subclass of comm_monoid2: comm_monoid2 has all the fields that comm_monoid1 has. -/
run_cmd is_subclass `comm_monoid2 `comm_monoid1
/- Output: comm_monoid2 is a subclass of comm_monoid1: comm_monoid1 has all the data fields of comm_monoid2, and all the axioms of comm_monoid2 can be proven from the axioms of comm_monoid1. -/
/-! As a sanity check: we cannot prove commutativity on an arbitrary monoid. -/
class my_monoid (M : Type*) :=
(mul : M → M → M)
(mul_assoc : ∀ x y z, mul (mul x y) z = mul x (mul y z))
(one : M)
(mul_one : ∀ x, mul x one = x)
run_cmd is_subclass `comm_monoid1 `my_monoid
/- Output: Cannot prove the following axioms of comm_monoid1 from the axioms of my_monoid:
[mul_comm]. -/
|
71cb97522dd6727baedd8453cab626b4835f366b | 27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4 | /stage0/src/Lean/Meta/Basic.lean | 2f45148f05f54411b06d4eb097cd6f8476ca4edb | [
"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 | joehendrix/lean4 | 0d1486945f7ca9fe225070374338f4f7e74bab03 | 1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f | refs/heads/master | 1,640,573,727,861 | 1,639,662,710,000 | 1,639,665,515,000 | 198,893,504 | 0 | 0 | Apache-2.0 | 1,564,084,645,000 | 1,564,084,644,000 | null | UTF-8 | Lean | false | false | 56,277 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.LOption
import Lean.Environment
import Lean.Class
import Lean.ReducibilityAttrs
import Lean.Util.Trace
import Lean.Util.RecDepth
import Lean.Util.PPExt
import Lean.Util.ReplaceExpr
import Lean.Util.OccursCheck
import Lean.Util.MonadBacktrack
import Lean.Compiler.InlineAttrs
import Lean.Meta.TransparencyMode
import Lean.Meta.DiscrTreeTypes
import Lean.Eval
import Lean.CoreM
/-
This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.
1- Weak head normal form computation with support for metavariables and transparency modes.
2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).
3- Type inference.
4- Type class resolution.
They are packed into the MetaM monad.
-/
namespace Lean.Meta
builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck
structure Config where
foApprox : Bool := false
ctxApprox : Bool := false
quasiPatternApprox : Bool := false
/-- When `constApprox` is set to true,
we solve `?m t =?= c` using
`?m := fun _ => c`
when `?m t` is not a higher-order pattern and `c` is not an application as -/
constApprox : Bool := false
/--
When the following flag is set,
`isDefEq` throws the exeption `Exeption.isDefEqStuck`
whenever it encounters a constraint `?m ... =?= t` where
`?m` is read only.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`. -/
isDefEqStuckEx : Bool := false
transparency : TransparencyMode := TransparencyMode.default
/-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/
zetaNonDep : Bool := true
/-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/
trackZeta : Bool := false
unificationHints : Bool := true
/-- Enables proof irrelevance at `isDefEq` -/
proofIrrelevance : Bool := true
/-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make
sure typing constraints resolved during elaboration should not "fill" holes that are supposed to be filled using tactics.
However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill
named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify
the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because
this last unification step is not really part of the term elaboration. -/
assignSyntheticOpaque : Bool := false
/-- When `ignoreLevelDepth` is `false`, only universe level metavariables with depth == metavariable context depth
can be assigned.
We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few
cases. Recall that universe levels are often ignored by users, they may not even be aware they exist.
We still use this restriction for regular metavariables. See discussion at the beginning of `MetavarContext.lean`.
We claim it is reasonable to ignore this restriction for universe metavariables because their values are often
contrained by the terms is instances and simp theorems.
TODO: we should delete this configuration option and the method `isReadOnlyLevelMVar` after we have more tests.
-/
ignoreLevelMVarDepth : Bool := true
/-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/
offsetCnstrs : Bool := true
/-- Enable/Disable support for eta-structures. -/
etaStruct : Bool := true
structure ParamInfo where
binderInfo : BinderInfo := BinderInfo.default
hasFwdDeps : Bool := false
backDeps : Array Nat := #[]
deriving Inhabited
def ParamInfo.isImplicit (p : ParamInfo) : Bool :=
p.binderInfo == BinderInfo.implicit
def ParamInfo.isInstImplicit (p : ParamInfo) : Bool :=
p.binderInfo == BinderInfo.instImplicit
def ParamInfo.isStrictImplicit (p : ParamInfo) : Bool :=
p.binderInfo == BinderInfo.strictImplicit
def ParamInfo.isExplicit (p : ParamInfo) : Bool :=
p.binderInfo == BinderInfo.default || p.binderInfo == BinderInfo.auxDecl
structure FunInfo where
paramInfo : Array ParamInfo := #[]
resultDeps : Array Nat := #[]
structure InfoCacheKey where
transparency : TransparencyMode
expr : Expr
nargs? : Option Nat
deriving Inhabited, BEq
namespace InfoCacheKey
instance : Hashable InfoCacheKey :=
⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩
end InfoCacheKey
open Std (PersistentArray PersistentHashMap)
abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr)
abbrev InferTypeCache := PersistentExprStructMap Expr
abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo
abbrev WhnfCache := PersistentExprStructMap Expr
/- A set of pairs. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache).
We should also investigate the impact on memory consumption. -/
abbrev DefEqCache := PersistentHashMap (Expr × Expr) Unit
structure Cache where
inferType : InferTypeCache := {}
funInfo : FunInfoCache := {}
synthInstance : SynthInstanceCache := {}
whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default`
whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all`
defEqDefault : DefEqCache := {}
defEqAll : DefEqCache := {}
deriving Inhabited
/--
"Context" for a postponed universe constraint.
`lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created.
-/
structure DefEqContext where
lhs : Expr
rhs : Expr
lctx : LocalContext
localInstances : LocalInstances
/--
Auxiliary structure for representing postponed universe constraints.
Remark: the fields `ref` and `rootDefEq?` are used for error message generation only.
Remark: we may consider improving the error message generation in the future.
-/
structure PostponedEntry where
ref : Syntax -- We save the `ref` at entry creation time
lhs : Level
rhs : Level
ctx? : Option DefEqContext -- Context for the surrounding `isDefEq` call when entry was created
deriving Inhabited
structure State where
mctx : MetavarContext := {}
cache : Cache := {}
/- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/
zetaFVarIds : FVarIdSet := {}
postponed : PersistentArray PostponedEntry := {}
deriving Inhabited
structure SavedState where
core : Core.State
meta : State
deriving Inhabited
structure Context where
config : Config := {}
lctx : LocalContext := {}
localInstances : LocalInstances := #[]
/-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/
defEqCtx? : Option DefEqContext := none
/--
Track the number of nested `synthPending` invocations. Nested invocations can happen
when the type class resolution invokes `synthPending`.
Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`.
We will add a configuration option if necessary. -/
synthPendingDepth : Nat := 0
abbrev MetaM := ReaderT Context $ StateRefT State CoreM
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind }
instance : Inhabited (MetaM α) where
default := fun _ _ => arbitrary
instance : MonadLCtx MetaM where
getLCtx := return (← read).lctx
instance : MonadMCtx MetaM where
getMCtx := return (← get).mctx
modifyMCtx f := modify fun s => { s with mctx := f s.mctx }
instance : AddMessageContext MetaM where
addMessageContext := addMessageContextFull
protected def saveState : MetaM SavedState :=
return { core := (← getThe Core.State), meta := (← get) }
/-- Restore backtrackable parts of the state. -/
def SavedState.restore (b : SavedState) : MetaM Unit := do
Core.restore b.core
modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed }
instance : MonadBacktrack SavedState MetaM where
saveState := Meta.saveState
restoreState s := s.restore
@[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) :=
x ctx |>.run s
@[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α :=
Prod.fst <$> x.run ctx s
@[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do
let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore
pure (a, sCore, s)
instance [MetaEval α] : MetaEval (MetaM α) :=
⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩
protected def throwIsDefEqStuck : MetaM α :=
throw <| Exception.internal isDefEqStuckExceptionId
builtin_initialize
registerTraceClass `Meta
registerTraceClass `Meta.debug
@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α :=
liftM x
@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α :=
controlAt MetaM fun runInBase => f <| runInBase x
@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α :=
controlAt MetaM fun runInBase => f fun b => runInBase <| k b
@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α :=
controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c
section Methods
variable [MonadControlT MetaM n] [Monad n]
@[inline] def modifyCache (f : Cache → Cache) : MetaM Unit :=
modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩
@[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit :=
modifyCache fun ⟨ic, c1, c2, c3, c4, c5, c6⟩ => ⟨f ic, c1, c2, c3, c4, c5, c6⟩
def getLocalInstances : MetaM LocalInstances :=
return (← read).localInstances
def getConfig : MetaM Config :=
return (← read).config
def setMCtx (mctx : MetavarContext) : MetaM Unit :=
modify fun s => { s with mctx := mctx }
def resetZetaFVarIds : MetaM Unit :=
modify fun s => { s with zetaFVarIds := {} }
def getZetaFVarIds : MetaM FVarIdSet :=
return (← get).zetaFVarIds
def getPostponed : MetaM (PersistentArray PostponedEntry) :=
return (← get).postponed
def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := postponed }
@[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := f s.postponed }
/- WARNING: The following 4 constants are a hack for simulating forward declarations.
They are defined later using the `export` attribute. This is hackish because we
have to hard-code the true arity of these definitions here, and make sure the C names match.
We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/
@[extern 6 "lean_whnf"] constant whnf : Expr → MetaM Expr
@[extern 6 "lean_infer_type"] constant inferType : Expr → MetaM Expr
@[extern 7 "lean_is_expr_def_eq"] constant isExprDefEqAux : Expr → Expr → MetaM Bool
@[extern 7 "lean_is_level_def_eq"] constant isLevelDefEqAux : Level → Level → MetaM Bool
@[extern 6 "lean_synth_pending"] protected constant synthPending : MVarId → MetaM Bool
def whnfForall (e : Expr) : MetaM Expr := do
let e' ← whnf e
if e'.isForall then pure e' else pure e
-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`
protected def withIncRecDepth (x : n α) : n α :=
mapMetaM (withIncRecDepth (m := MetaM)) x
private def mkFreshExprMVarAtCore
(mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do
modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;
return mkMVar mvarId
def mkFreshExprMVarAt
(lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
mkFreshExprMVarAtCore (← mkFreshMVarId) lctx localInsts type kind userName numScopeArgs
def mkFreshLevelMVar : MetaM Level := do
let mvarId ← mkFreshMVarId
modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;
return mkLevelMVar mvarId
private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do
mkFreshExprMVarAt (← getLCtx) (← getLocalInstances) type kind userName
private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarCore type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous
mkFreshExprMVarCore type kind userName
def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
mkFreshExprMVarImpl type? kind userName
def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do
let u ← mkFreshLevelMVar
mkFreshExprMVar (mkSort u) kind userName
/- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create
the metavar using this method. -/
private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
mkFreshExprMVarAtCore mvarId (← getLCtx) (← getLocalInstances) type kind userName numScopeArgs
def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarWithIdCore mvarId type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVar (mkSort u)
mkFreshExprMVarWithIdCore mvarId type kind userName
def mkFreshLevelMVars (num : Nat) : MetaM (List Level) :=
num.foldM (init := []) fun _ us =>
return (← mkFreshLevelMVar)::us
def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) :=
mkFreshLevelMVars info.numLevelParams
def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do
let info ← getConstInfo declName
return mkConst declName (← mkFreshLevelMVarsFor info)
def getTransparency : MetaM TransparencyMode :=
return (← getConfig).transparency
def shouldReduceAll : MetaM Bool :=
return (← getTransparency) == TransparencyMode.all
def shouldReduceReducibleOnly : MetaM Bool :=
return (← getTransparency) == TransparencyMode.reducible
def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do
match (← getMCtx).findDecl? mvarId with
| some d => pure d
| none => throwError "unknown metavariable '?{mvarId.name}'"
def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=
modifyMCtx fun mctx => mctx.setMVarKind mvarId kind
/- Update the type of the given metavariable. This function assumes the new type is
definitionally equal to the current one -/
def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do
modifyMCtx fun mctx => mctx.setMVarType mvarId type
def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do
return (← getMVarDecl mvarId).depth != (← getMCtx).depth
def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvarId
match mvarDecl.kind with
| MetavarKind.syntheticOpaque => return !(← getConfig).assignSyntheticOpaque
| _ => return mvarDecl.depth != (← getMCtx).depth
def getLevelMVarDepth (mvarId : MVarId) : MetaM Nat := do
match (← getMCtx).findLevelDepth? mvarId with
| some depth => return depth
| _ => throwError "unknown universe metavariable '?{mvarId.name}'"
def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do
if (← getConfig).ignoreLevelMVarDepth then
return false
else
return (← getLevelMVarDepth mvarId) != (← getMCtx).depth
def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=
modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName
def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isExprAssigned mvarId
def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) :=
return (← getMCtx).getExprAssignment? mvarId
/-- Return true if `e` contains `mvarId` directly or indirectly -/
def occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool :=
return (← getMCtx).occursCheck mvarId e
def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit :=
modifyMCtx fun mctx => mctx.assignExpr mvarId val
def isDelayedAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isDelayedAssigned mvarId
def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) :=
return (← getMCtx).getDelayedAssignment? mvarId
def hasAssignableMVar (e : Expr) : MetaM Bool :=
return (← getMCtx).hasAssignableMVar e
def throwUnknownFVar (fvarId : FVarId) : MetaM α :=
throwError "unknown free variable '{mkFVar fvarId}'"
def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=
return (← getLCtx).find? fvarId
def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do
match (← getLCtx).find? fvarId with
| some d => pure d
| none => throwUnknownFVar fvarId
def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=
getLocalDecl fvar.fvarId!
def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do
match (← getLCtx).findFromUserName? userName with
| some d => pure d
| none => throwError "unknown local declaration '{userName}'"
def instantiateLevelMVars (u : Level) : MetaM Level :=
MetavarContext.instantiateLevelMVars u
def instantiateMVars (e : Expr) : MetaM Expr :=
(MetavarContext.instantiateExprMVars e).run
def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl :=
match localDecl with
| LocalDecl.cdecl idx id n type bi =>
return LocalDecl.cdecl idx id n (← instantiateMVars type) bi
| LocalDecl.ldecl idx id n type val nonDep =>
return LocalDecl.ldecl idx id n (← instantiateMVars type) (← instantiateMVars val) nonDep
@[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do
match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with
| EStateM.Result.ok e newS => do
setNGen newS.ngen;
setMCtx newS.mctx;
pure e
| EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do
setMCtx newS.mctx;
setNGen newS.ngen;
throwError "failed to create binder due to failure when reverting variable dependencies"
def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr :=
liftMkBindingM <| MetavarContext.abstractRange e n xs
def abstract (e : Expr) (xs : Array Expr) : MetaM Expr :=
abstractRange e xs.size xs
def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly
def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly
def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) : MetaM Expr :=
mkLambdaFVars xs e (usedLetOnly := usedLetOnly)
def mkArrow (d b : Expr) : MetaM Expr :=
return Lean.mkForall (← mkFreshUserName `x) BinderInfo.default d b
/-- `fun _ : Unit => a` -/
def mkFunUnit (a : Expr) : MetaM Expr :=
return Lean.mkLambda (← mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder
@[inline] def withConfig (f : Config → Config) : n α → n α :=
mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })
@[inline] def withTrackingZeta (x : n α) : n α :=
withConfig (fun cfg => { cfg with trackZeta := true }) x
@[inline] def withoutProofIrrelevance (x : n α) : n α :=
withConfig (fun cfg => { cfg with proofIrrelevance := false }) x
@[inline] def withTransparency (mode : TransparencyMode) : n α → n α :=
mapMetaM <| withConfig (fun config => { config with transparency := mode })
@[inline] def withDefault (x : n α) : n α :=
withTransparency TransparencyMode.default x
@[inline] def withReducible (x : n α) : n α :=
withTransparency TransparencyMode.reducible x
@[inline] def withReducibleAndInstances (x : n α) : n α :=
withTransparency TransparencyMode.instances x
@[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α :=
withConfig
(fun config =>
let oldMode := config.transparency
let mode := if oldMode.lt mode then mode else oldMode
{ config with transparency := mode })
x
/-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/
@[inline] def withAssignableSyntheticOpaque (x : n α) : n α :=
withConfig (fun config => { config with assignSyntheticOpaque := true }) x
/-- Save cache, execute `x`, restore cache -/
@[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do
let savedCache := (← get).cache
try x finally modify fun s => { s with cache := savedCache }
@[inline] def savingCache : n α → n α :=
mapMetaM savingCacheImpl
def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
if (← shouldReduceAll) then
return some info
else
return none
private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
match (← getTransparency) with
| TransparencyMode.all => return some info
| TransparencyMode.default => return some info
| _ =>
if (← isReducible info.name) then
return some info
else
return none
/- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.
This method is only used to implement `isClassQuickConst?`.
It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and
`constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/
private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do
match (← getEnv).find? constName with
| some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info
| some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info
| some info => pure (some info)
| none => throwUnknownConstant constName
private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do
if isClass (← getEnv) constName then
pure (LOption.some constName)
else
match (← getConstTemp? constName) with
| some _ => pure LOption.undef
| none => pure LOption.none
private partial def isClassQuick? : Expr → MetaM (LOption Name)
| Expr.bvar .. => pure LOption.none
| Expr.lit .. => pure LOption.none
| Expr.fvar .. => pure LOption.none
| Expr.sort .. => pure LOption.none
| Expr.lam .. => pure LOption.none
| Expr.letE .. => pure LOption.undef
| Expr.proj .. => pure LOption.undef
| Expr.forallE _ _ b _ => isClassQuick? b
| Expr.mdata _ e _ => isClassQuick? e
| Expr.const n _ _ => isClassQuickConst? n
| Expr.mvar mvarId _ => do
match (← getExprMVarAssignment? mvarId) with
| some val => isClassQuick? val
| none => pure LOption.none
| Expr.app f _ _ =>
match f.getAppFn with
| Expr.const n .. => isClassQuickConst? n
| Expr.lam .. => pure LOption.undef
| _ => pure LOption.none
def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do
let savedSythInstance := (← get).cache.synthInstance
modifyCache fun c => { c with synthInstance := {} }
pure savedSythInstance
def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit :=
modifyCache fun c => { c with synthInstance := cache }
@[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do
let savedSythInstance ← saveAndResetSynthInstanceCache
try x finally restoreSynthInstanceCache savedSythInstance
/-- Reset `synthInstance` cache, execute `x`, and restore cache -/
@[inline] def resettingSynthInstanceCache : n α → n α :=
mapMetaM resettingSynthInstanceCacheImpl
@[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α :=
if b then resettingSynthInstanceCache x else x
private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do
let localDecl ← getFVarLocalDecl fvar
/- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/
match localDecl.binderInfo with
| BinderInfo.auxDecl => k
| _ =>
resettingSynthInstanceCache <|
withReader
(fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } })
k
/-- Add entry `{ className := className, fvar := fvar }` to localInstances,
and then execute continuation `k`.
It resets the type class cache using `resettingSynthInstanceCache`. -/
def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α :=
mapMetaM <| withNewLocalInstanceImp className fvar
private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=
match maxFVars? with
| some maxFVars => fvars.size < maxFVars
| none => true
mutual
/--
`withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances
using free variables `fvars[j] ... fvars.back`, and execute `k`.
- `isClassExpensive` is defined later.
- The type class chache is reset whenever a new local instance is found.
- `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.
Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/
private partial def withNewLocalInstancesImp
(fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do
if h : i < fvars.size then
let fvar := fvars.get ⟨i, h⟩
let decl ← getFVarLocalDecl fvar
match (← isClassQuick? decl.type) with
| LOption.none => withNewLocalInstancesImp fvars (i+1) k
| LOption.undef =>
match (← isClassExpensive? decl.type) with
| none => withNewLocalInstancesImp fvars (i+1) k
| some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k
| LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k
else
k
/--
`forallTelescopeAuxAux lctx fvars j type`
Remarks:
- `lctx` is the `MetaM` local context extended with declarations for `fvars`.
- `type` is the type we are computing the telescope for. It contains only
dangling bound variables in the range `[j, fvars.size)`
- if `reducing? == true` and `type` is not `forallE`, we use `whnf`.
- when `type` is not a `forallE` nor it can't be reduced to one, we
excute the continuation `k`.
Here is an example that demonstrates the `reducing?`.
Suppose we have
```
abbrev StateM s a := s -> Prod a s
```
Now, assume we are trying to build the telescope for
```
forall (x : Nat), StateM Int Bool
```
if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.
if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`
if `maxFVars?` is `some max`, then we interrupt the telescope construction
when `fvars.size == max`
-/
private partial def forallTelescopeReducingAuxAux
(reducing : Bool) (maxFVars? : Option Nat)
(type : Expr)
(k : Array Expr → Expr → MetaM α) : MetaM α := do
let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do
match type with
| Expr.forallE n d b c =>
if fvarsSizeLtMaxFVars fvars maxFVars? then
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshFVarId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
let fvars := fvars.push fvar
process lctx fvars j b
else
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars type
| _ =>
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then
let newType ← whnf type
if newType.isForall then
process lctx fvars fvars.size newType
else
k fvars type
else
k fvars type
process (← getLCtx) #[] 0 type
private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do
match maxFVars? with
| some 0 => k #[] type
| _ => do
let newType ← whnf type
if newType.isForall then
forallTelescopeReducingAuxAux true maxFVars? newType k
else
k #[] type
private partial def isClassExpensive? : Expr → MetaM (Option Name)
| type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants.
forallTelescopeReducingAux type none fun xs type => do
let env ← getEnv
match type.getAppFn with
| Expr.const c _ _ => do
if isClass env c then
return some c
else
-- make sure abbreviations are unfolded
match (← whnf type).getAppFn with
| Expr.const c _ _ => return if isClass env c then some c else none
| _ => return none
| _ => return none
private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do
match (← isClassQuick? type) with
| LOption.none => pure none
| LOption.some c => pure (some c)
| LOption.undef => isClassExpensive? type
end
def isClass? (type : Expr) : MetaM (Option Name) :=
try isClassImp? type catch _ => pure none
private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM <| withNewLocalInstancesImp fvars j
partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM <| withNewLocalInstancesImpAux fvars j
@[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k
/--
Given `type` of the form `forall xs, A`, execute `k xs A`.
This combinator will declare local declarations, create free variables for them,
execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/
def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeImp type k) k
private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type (maxFVars? := none) k
/--
Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,
it reduces `A` and continues bulding the telescope if it is a `forall`. -/
def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeReducingImp type k) k
private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type maxFVars? k
/--
Similar to `forallTelescopeReducing`, stops constructing the telescope when
it reaches size `maxFVars`. -/
def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k
private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do
process consumeLet (← getLCtx) #[] 0 e
where
process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do
match consumeLet, e with
| _, Expr.lam n d b c =>
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshFVarId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
process consumeLet lctx (fvars.push fvar) j b
| true, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars
let v := v.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshFVarId
let lctx := lctx.mkLetDecl fvarId n t v
let fvar := mkFVar fvarId
process true lctx (fvars.push fvar) j b
| _, e =>
let e := e.instantiateRevRange j fvars.size fvars
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars e
/-- Similar to `forallTelescope` but for lambda and let expressions. -/
def lambdaLetTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type true k) k
/-- Similar to `forallTelescope` but for lambda expressions. -/
def lambdaTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type false k) k
/-- Return the parameter names for the givel global declaration. -/
def getParamNames (declName : Name) : MetaM (Array Name) := do
forallTelescopeReducing (← getConstInfo declName).type fun xs _ => do
xs.mapM fun x => do
let localDecl ← getLocalDecl x.fvarId!
pure localDecl.userName
-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.
private partial def forallMetaTelescopeReducingAux
(e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) :=
process #[] #[] 0 e
where
process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
if maxMVars?.isEqSome mvars.size then
let type := type.instantiateRevRange j mvars.size mvars;
return (mvars, bis, type)
else
match type with
| Expr.forallE n d b c =>
let d := d.instantiateRevRange j mvars.size mvars
let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind
let mvar ← mkFreshExprMVar d k n
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
| _ =>
let type := type.instantiateRevRange j mvars.size mvars;
if reducing then do
let newType ← whnf type;
if newType.isForall then
process mvars bis mvars.size newType
else
return (mvars, bis, type)
else
return (mvars, bis, type)
/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/
def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind
/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/
def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind
/-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/
def forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind)
/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/
partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) :=
process #[] #[] 0 e
where
process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
let type := type.instantiateRevRange j mvars.size mvars
pure (mvars, bis, type)
if maxMVars?.isEqSome mvars.size then
finalize ()
else
match type with
| Expr.lam n d b c =>
let d := d.instantiateRevRange j mvars.size mvars
let mvar ← mkFreshExprMVar d
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
| _ => finalize ()
private def withNewFVar (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do
match (← isClass? fvarType) with
| none => k fvar
| some c => withNewLocalInstance c fvar <| k fvar
private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshFVarId
let ctx ← read
let lctx := ctx.lctx.mkLocalDecl fvarId n type bi
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLocalDeclImp name bi type k) k
def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α :=
withLocalDecl name BinderInfo.default type k
partial def withLocalDecls
[Inhabited α]
(declInfos : Array (Name × BinderInfo × (Array Expr → n Expr)))
(k : (xs : Array Expr) → n α)
: n α :=
loop #[]
where
loop [Inhabited α] (acc : Array Expr) : n α := do
if acc.size < declInfos.size then
let (name, bi, typeCtor) := declInfos[acc.size]
withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x)
else
k acc
def withLocalDeclsD [Inhabited α] (declInfos : Array (Name × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α :=
withLocalDecls
(declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k
private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do
let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) =>
lctx.setBinderInfo fvarId bi
withReader (fun ctx => { ctx with lctx := lctx }) k
def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α :=
mapMetaM (fun k => withNewBinderInfosImp bs k) k
private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshFVarId
let ctx ← read
let lctx := ctx.lctx.mkLetDecl fvarId n type val
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLetDeclImp name type val k) k
private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do
let ctx ← read
let numLocalInstances := ctx.localInstances.size
let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx
withReader (fun ctx => { ctx with lctx := lctx }) do
let newLocalInsts ← decls.foldlM
(fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do {
match (← isClass? decl.type) with
| none => pure newlocalInsts
| some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _))
ctx.localInstances;
if newLocalInsts.size == numLocalInstances then
k
else
resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k
def withExistingLocalDecls (decls : List LocalDecl) : n α → n α :=
mapMetaM <| withExistingLocalDeclsImp decls
private def withNewMCtxDepthImp (x : MetaM α) : MetaM α := do
let saved ← get
modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} }
try
x
finally
modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed }
/--
Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,
and restore saved data. -/
def withNewMCtxDepth : n α → n α :=
mapMetaM withNewMCtxDepthImp
private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do
let localInstsCurr ← getLocalInstances
withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do
if localInsts == localInstsCurr then
x
else
resettingSynthInstanceCache x
def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α :=
mapMetaM <| withLocalContextImp lctx localInsts
private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do
let mvarDecl ← getMVarDecl mvarId
withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x
/--
Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.
The type class resolution cache is flushed when executing `x` if its `LocalInstances` are
different from the current ones. -/
def withMVarContext (mvarId : MVarId) : n α → n α :=
mapMetaM <| withMVarContextImp mvarId
private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do
let mctx' ← getMCtx
setMCtx mctx
try x finally setMCtx mctx'
def withMCtx (mctx : MetavarContext) : n α → n α :=
mapMetaM <| withMCtxImp mctx
@[inline] private def approxDefEqImp (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x
/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/
@[inline] def approxDefEq : n α → n α :=
mapMetaM approxDefEqImp
@[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x
/--
Similar to `approxDefEq`, but uses all available approximations.
We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.
For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.
Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved
as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to
solve `[Pure (fun _ => IO Bool)]` -/
@[inline] def fullApproxDefEq : n α → n α :=
mapMetaM fullApproxDefEqImp
def normalizeLevel (u : Level) : MetaM Level := do
let u ← instantiateLevelMVars u
pure u.normalize
def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do
modifyMCtx fun mctx => mctx.assignLevel mvarId u
def whnfR (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.reducible <| whnf e
def whnfD (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.default <| whnf e
def whnfI (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.instances <| whnf e
def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do
let env ← getEnv
match Compiler.setInlineAttribute env declName kind with
| Except.ok env => setEnv env
| Except.error msg => throwError msg
private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
match (← whnf e) with
| Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateForall, too many parameters"
else
pure e
/- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/
def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateForallAux ps 0 e
private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
match (← whnf e) with
| Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateLambda, too many parameters"
else
pure e
/- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.
It uses `whnf` to reduce `e` if it is not a lambda -/
def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateLambdaAux ps 0 e
/-- Return true iff `e` depends on the free variable `fvarId` -/
def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool :=
return (← getMCtx).exprDependsOn e fvarId
/-- Return true iff `e` depends on a free variable `x` s.t. `p x` -/
def dependsOnPred (e : Expr) (p : FVarId → Bool) : MetaM Bool :=
return (← getMCtx).findExprDependsOn e p
/-- Return true iff the local declaration `localDecl` depends on a free variable `x` s.t. `p x` -/
def localDeclDependsOnPred (localDecl : LocalDecl) (p : FVarId → Bool) : MetaM Bool := do
return (← getMCtx).findLocalDeclDependsOn localDecl p
def ppExpr (e : Expr) : MetaM Format := do
let ctxCore ← readThe Core.Context
Lean.ppExpr { env := (← getEnv), mctx := (← getMCtx), lctx := (← getLCtx), opts := (← getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e
@[inline] protected def orElse (x : MetaM α) (y : Unit → MetaM α) : MetaM α := do
let s ← saveState
try x catch _ => s.restore; y ()
instance : OrElse (MetaM α) := ⟨Meta.orElse⟩
instance : Alternative MetaM where
failure := fun {α} => throwError "failed"
orElse := Meta.orElse
@[inline] private def orelseMergeErrorsImp (x y : MetaM α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do
let env ← getEnv
let mctx ← getMCtx
try
x
catch ex =>
setEnv env
setMCtx mctx
match ex with
| Exception.error ref₁ m₁ =>
try
y
catch
| Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂)
| ex => throw ex
| ex => throw ex
/--
Similar to `orelse`, but merge errors. Note that internal errors are not caught.
The default `mergeRef` uses the `ref` (position information) for the first message.
The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/
@[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do
controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg
/-- Execute `x`, and apply `f` to the produced error message -/
def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do
try
x
catch
| Exception.error ref msg => throw <| Exception.error ref <| f msg
| ex => throw ex
@[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α :=
controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f
/--
Sort free variables using an order `x < y` iff `x` was defined before `y`.
If a free variable is not in the local context, we use their id. -/
def sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do
let lctx ← getLCtx
return fvarIds.qsort fun fvarId₁ fvarId₂ =>
match lctx.find? fvarId₁, lctx.find? fvarId₂ with
| some d₁, some d₂ => d₁.index < d₂.index
| some _, none => false
| none, some _ => true
| none, none => Name.quickLt fvarId₁.name fvarId₂.name
end Methods
def isInductivePredicate (declName : Name) : MetaM Bool := do
match (← getEnv).find? declName with
| some (ConstantInfo.inductInfo { type := type, ..}) =>
forallTelescopeReducing type fun _ type => do
match (← whnfD type) with
| Expr.sort u .. => return u == levelZero
| _ => return false
| _ => return false
/- -/
def isListLevelDefEqAux : List Level → List Level → MetaM Bool
| [], [] => return true
| u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs
| _, _ => return false
private def getNumPostponed : MetaM Nat := do
return (← getPostponed).size
def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do
let ps ← getPostponed
setPostponed {}
return ps
/-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/
private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr :=
e.replace fun
| Expr.const _ us _ => if us.any p then some (e.setPPUniverses true) else none
| Expr.sort u _ => if p u then some (e.setPPUniverses true) else none
| _ => none
private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do
match entry.ctx? with
| none =>
return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}"
| some ctx =>
withLCtx ctx.lctx ctx.localInstances do
let s := entry.lhs.collectMVars entry.rhs.collectMVars
/- `p u` is true if it contains a universe metavariable in `s` -/
let p (u : Level) := u.any fun | Level.mvar m _ => s.contains m | _ => false
let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p
let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p
try
addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}"
catch _ =>
addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}"
def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do
mkLeveErrorMessageCore "stuck at solving universe constraint" entry
def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do
mkLeveErrorMessageCore "failed to solve universe constraint" entry
private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool :=
traceCtx `Meta.isLevelDefEq.postponed.step do
let ps ← getResetPostponed
for p in ps do
unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do
if exceptionOnFailure then
throwError (← mkLevelErrorMessage p)
else
return false
return true
partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do
if (← getNumPostponed) == 0 then
return true
else
traceCtx `Meta.isLevelDefEq.postponed do
let rec loop : MetaM Bool := do
let numPostponed ← getNumPostponed
if numPostponed == 0 then
return true
else
trace[Meta.isLevelDefEq.postponed] "processing #{numPostponed} postponed is-def-eq level constraints"
if !(← processPostponedStep exceptionOnFailure) then
return false
else
let numPostponed' ← getNumPostponed
if numPostponed' == 0 then
return true
else if numPostponed' < numPostponed then
loop
else
trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints"
return mayPostpone
loop
/--
`checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`.
We keep the modifications only if `processPostponed` return true and `x` returned `true`.
If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning.
We currently try to postpone universe constraints as much as possible, even when by postponing them we
are not sure whether `x` really succeeded or not.
-/
@[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do
let s ← saveState
let postponed ← getResetPostponed
try
if (← x) then
if (← processPostponed mayPostpone) then
let newPostponed ← getPostponed
setPostponed (postponed ++ newPostponed)
return true
else
s.restore
return false
else
s.restore
return false
catch ex =>
s.restore
throw ex
def isLevelDefEq (u v : Level) : MetaM Bool :=
traceCtx `Meta.isLevelDefEq do
let b ← checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v
trace[Meta.isLevelDefEq] "{u} =?= {v} ... {if b then "success" else "failure"}"
return b
def isExprDefEq (t s : Expr) : MetaM Bool :=
traceCtx `Meta.isDefEq <| withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do
let b ← checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s
trace[Meta.isDefEq] "{t} =?= {s} ... {if b then "success" else "failure"}"
return b
abbrev isDefEq (t s : Expr) : MetaM Bool :=
isExprDefEq t s
def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do
try isExprDefEq a b catch _ => return false
abbrev isDefEqGuarded (t s : Expr) : MetaM Bool :=
isExprDefEqGuarded t s
def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool :=
approxDefEq <| isDefEq t s
end Meta
builtin_initialize
registerTraceClass `Meta.isLevelDefEq.postponed
export Meta (MetaM)
end Lean
|
44f0899dc6fd054bdf021912269d265eb3179492 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/topology/uniform_space/completion.lean | e0a312a649c0a122ce4a8723f6eb659d7973d4ee | [
"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 | 23,412 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import topology.uniform_space.abstract_completion
/-!
# Hausdorff completions of uniform spaces
The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces
into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism
(ie. uniformly continuous map) `coe : α → completion α` which solves the universal
mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`.
It means any uniformly continuous `f : α → β` gives rise to a unique morphism
`completion.extension f : completion α → β` such that `f = completion.extension f ∘ coe`.
Actually `completion.extension f` is defined for all maps from `α` to `β` but it has the desired
properties only if `f` is uniformly continuous.
Beware that `coe` is not injective if `α` is not Hausdorff. But its image is always
dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense.
For every uniform spaces `α` and `β`, it turns `f : α → β` into a morphism
`completion.map f : completion α → completion β`
such that
`coe ∘ f = (completion.map f) ∘ coe`
provided `f` is uniformly continuous. This construction is compatible with composition.
In this file we introduce the following concepts:
* `Cauchy α` the uniform completion of the uniform space `α` (using Cauchy filters). These are not
minimal filters.
* `completion α := quotient (separation_setoid (Cauchy α))` the Hausdorff completion.
## References
This formalization is mostly based on
N. Bourbaki: General Topology
I. M. James: Topologies and Uniformities
From a slightly different perspective in order to reuse material in topology.uniform_space.basic.
-/
noncomputable theory
open filter set
universes u v w x
open_locale uniformity classical topological_space filter
/-- 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 α]
variables {β : Type v} {γ : Type w}
variables [uniform_space β] [uniform_space γ]
def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) :=
{p | s ∈ p.1.val ×ᶠ p.2.val }
lemma monotone_gen : monotone gen :=
monotone_set_of $ assume p, @monotone_mem_sets (α×α) (p.1.val ×ᶠ p.2.val)
private lemma symm_gen : map prod.swap ((𝓤 α).lift' gen) ≤ (𝓤 α).lift' gen :=
calc map prod.swap ((𝓤 α).lift' gen) =
(𝓤 α).lift' (λs:set (α×α), {p | s ∈ p.2.val ×ᶠ p.1.val }) :
begin
delta gen,
simp [map_lift'_eq, monotone_set_of, monotone_mem_sets,
function.comp, image_swap_eq_preimage_swap, -subtype.val_eq_coe]
end
... ≤ (𝓤 α).lift' gen :
uniformity_lift_le_swap
(monotone_principal.comp (monotone_set_of $ assume p,
@monotone_mem_sets (α×α) (p.2.val ×ᶠ p.1.val)))
begin
have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val),
simp [function.comp, h, -subtype.val_eq_coe],
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 α)) :=
assume ⟨f, g⟩ ⟨h, h₁, h₂⟩,
let ⟨t₁, (ht₁ : t₁ ∈ f.val), t₂, (ht₂ : t₂ ∈ h.val), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ :=
mem_prod_iff.mp h₁ in
let ⟨t₃, (ht₃ : t₃ ∈ h.val), t₄, (ht₄ : t₄ ∈ g.val), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ :=
mem_prod_iff.mp h₂ in
have t₂ ∩ t₃ ∈ h.val,
from inter_mem_sets ht₂ ht₃,
let ⟨x, xt₂, xt₃⟩ :=
h.property.left.nonempty_of_mem this in
(f.val ×ᶠ g.val).sets_of_superset
(prod_mem_prod ht₁ ht₄)
(assume ⟨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 :
((𝓤 α).lift' gen).lift' (λs, comp_rel s s) ≤ (𝓤 α).lift' gen :=
calc ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) =
(𝓤 α).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
... ≤ (𝓤 α).lift' (λs, gen $ comp_rel s s) :
lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel
... = ((𝓤 α).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
... ≤ (𝓤 α).lift' gen : lift'_mono comp_le_uniformity (le_refl _)
instance : uniform_space (Cauchy α) :=
uniform_space.of_core
{ uniformity := (𝓤 α).lift' gen,
refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b),
a_eq_b ▸ a.property.right hs,
symm := symm_gen,
comp := comp_gen }
theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} :
s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, gen t ⊆ s :=
mem_lift'_sets monotone_gen
theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} :
s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, ∀ f g : Cauchy α, t ∈ f.1 ×ᶠ g.1 → (f, g) ∈ s :=
mem_uniformity.trans $ bex_congr $ λ t h, prod.forall
/-- Embedding of `α` into its completion `Cauchy α` -/
def pure_cauchy (a : α) : Cauchy α :=
⟨pure a, cauchy_pure⟩
lemma uniform_inducing_pure_cauchy : uniform_inducing (pure_cauchy : α → Cauchy α) :=
⟨have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id,
from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩,
by simp [preimage, gen, pure_cauchy, prod_principal_principal],
calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ((𝓤 α).lift' gen)
= (𝓤 α).lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) :
comap_lift'_eq monotone_gen
... = 𝓤 α : by simp [this]⟩
lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) :=
{ inj := assume a₁ a₂ h, pure_injective $ subtype.ext_iff_val.1 h,
..uniform_inducing_pure_cauchy }
lemma dense_range_pure_cauchy : dense_range pure_cauchy :=
assume f,
have h_ex : ∀ s ∈ 𝓤 (Cauchy α), ∃y:α, (f, pure_cauchy y) ∈ s, from
assume s hs,
let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in
let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in
have t' ∈ f.val ×ᶠ f.val,
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)⟩ := f.property.left.nonempty_of_mem ht in
have t'' ∈ f.val ×ᶠ pure x,
from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'},
h $ mk_mem_prod hx hx,
assume ⟨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 only [closure_eq_cluster_pts, cluster_pt, nhds_eq_uniformity, lift'_inf_principal_eq,
set.inter_comm _ (range pure_cauchy), mem_set_of_eq],
exact (lift'_ne_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr
(assume s hs,
let ⟨y, hy⟩ := h_ex s hs in
have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s},
from ⟨mem_range_self y, hy⟩,
⟨_, this⟩)
end
lemma dense_inducing_pure_cauchy : dense_inducing pure_cauchy :=
uniform_inducing_pure_cauchy.dense_inducing dense_range_pure_cauchy
lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy :=
uniform_embedding_pure_cauchy.dense_embedding dense_range_pure_cauchy
lemma nonempty_Cauchy_iff : nonempty (Cauchy α) ↔ nonempty α :=
begin
split ; rintro ⟨c⟩,
{ have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.to_dense_inducing.closure_range c,
obtain ⟨_, ⟨_, a, _⟩⟩ := mem_closure_iff.1 this _ is_open_univ trivial,
exact ⟨a⟩ },
{ exact ⟨pure_cauchy c⟩ }
end
section
set_option eqn_compiler.zeta true
instance : complete_space (Cauchy α) :=
complete_space_extension
uniform_inducing_pure_cauchy
dense_range_pure_cauchy $
assume f hf,
let f' : Cauchy α := ⟨f, hf⟩ in
have map pure_cauchy f ≤ (𝓤 $ Cauchy α).lift' (preimage (prod.mk f')),
from le_lift' $ assume s hs,
let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets 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 assume x hx, (f ×ᶠ pure x).sets_of_superset (prod_mem_prod ht' hx) h,
f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂),
⟨f', by simp [nhds_eq_uniformity]; assumption⟩
end
instance [inhabited α] : inhabited (Cauchy α) :=
⟨pure_cauchy $ default α⟩
instance [h : nonempty α] : nonempty (Cauchy α) :=
h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a
section extend
def extend (f : α → β) : (Cauchy α → β) :=
if uniform_continuous f then
dense_inducing_pure_cauchy.extend f
else
λ x, f (classical.inhabited_of_nonempty $ nonempty_Cauchy_iff.1 ⟨x⟩).default
variables [separated_space β]
lemma extend_pure_cauchy {f : α → β} (hf : uniform_continuous f) (a : α) :
extend f (pure_cauchy a) = f a :=
begin
rw [extend, if_pos hf],
exact uniformly_extend_of_ind uniform_inducing_pure_cauchy dense_range_pure_cauchy hf _
end
variables [_root_.complete_space β]
lemma uniform_continuous_extend {f : α → β} : uniform_continuous (extend f) :=
begin
by_cases hf : uniform_continuous f,
{ rw [extend, if_pos hf],
exact uniform_continuous_uniformly_extend uniform_inducing_pure_cauchy
dense_range_pure_cauchy hf },
{ rw [extend, if_neg hf],
exact uniform_continuous_of_const (assume a b, by congr) }
end
end extend
end
theorem Cauchy_eq
{α : Type*} [inhabited α] [uniform_space α] [complete_space α] [separated_space α] {f g : Cauchy α} :
Lim f.1 = Lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy α) :=
begin
split,
{ intros e s hs,
rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩,
apply ts,
rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩,
refine mem_prod_iff.2
⟨_, f.2.le_nhds_Lim (mem_nhds_right (Lim f.1) du),
_, g.2.le_nhds_Lim (mem_nhds_left (Lim g.1) du), λ x h, _⟩,
cases x with a b, cases h with h₁ h₂,
rw ← e at h₂,
exact dt ⟨_, h₁, h₂⟩ },
{ intros H,
refine separated_def.1 (by apply_instance) _ _ (λ t tu, _),
rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩,
refine H {p | (Lim p.1.1, Lim p.2.1) ∈ t}
(Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩),
rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩,
have limc : ∀ (f : Cauchy α) (x ∈ f.1), Lim f.1 ∈ closure x,
{ intros f x xf,
rw closure_eq_cluster_pts,
exact ne_bot_of_le_ne_bot f.2.1
(le_inf f.2.le_nhds_Lim (le_principal_iff.2 xf)) },
have := dc.closure_subset_iff.2 h,
rw closure_prod_eq at this,
refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption }
end
section
local attribute [instance] uniform_space.separation_setoid
lemma separated_pure_cauchy_injective {α : Type*} [uniform_space α] [s : separated_space α] :
function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h :=
separated_def.1 s _ _ $ assume s hs,
let ⟨t, ht, hts⟩ :=
by rw [← (@uniform_embedding_pure_cauchy α _).comap_uniformity, filter.mem_comap_sets] at hs; exact hs in
have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht,
@hts (a, b) this
end
end Cauchy
local attribute [instance] uniform_space.separation_setoid
open Cauchy set
namespace uniform_space
variables (α : Type*) [uniform_space α]
variables {β : Type*} [uniform_space β]
variables {γ : Type*} [uniform_space γ]
instance complete_space_separation [h : complete_space α] :
complete_space (quotient (separation_setoid α)) :=
⟨assume f, assume hf : cauchy f,
have cauchy (f.comap (λx, ⟦x⟧)), from
hf.comap' comap_quotient_le_uniformity $
hf.left.comap_of_surj $ assume b, quotient.exists_rep _,
let ⟨x, (hx : f.comap (λx, ⟦x⟧) ≤ 𝓝 x)⟩ := complete_space.complete this in
⟨⟦x⟧, calc f = map (λx, ⟦x⟧) (f.comap (λx, ⟦x⟧)) :
(map_comap $ univ_mem_sets' $ assume b, quotient.exists_rep _).symm
... ≤ map (λx, ⟦x⟧) (𝓝 x) : map_mono hx
... ≤ _ : continuous_iff_continuous_at.mp uniform_continuous_quotient_mk.continuous _⟩⟩
/-- Hausdorff completion of `α` -/
def completion := quotient (separation_setoid $ Cauchy α)
namespace completion
instance [inhabited α] : inhabited (completion α) :=
by unfold completion; apply_instance
@[priority 50]
instance : uniform_space (completion α) := by dunfold completion ; apply_instance
instance : complete_space (completion α) := by dunfold completion ; apply_instance
instance : separated_space (completion α) := by dunfold completion ; apply_instance
instance : regular_space (completion α) := separated_regular
/-- Automatic coercion from `α` to its completion. Not always injective. -/
instance : has_coe_t α (completion α) := ⟨quotient.mk ∘ pure_cauchy⟩ -- note [use has_coe_t]
protected lemma coe_eq : (coe : α → completion α) = quotient.mk ∘ pure_cauchy := rfl
lemma comap_coe_eq_uniformity :
(𝓤 _).comap (λ(p:α×α), ((p.1 : completion α), (p.2 : completion α))) = 𝓤 α :=
begin
have : (λx:α×α, ((x.1 : completion α), (x.2 : completion α))) =
(λx:(Cauchy α)×(Cauchy α), (⟦x.1⟧, ⟦x.2⟧)) ∘ (λx:α×α, (pure_cauchy x.1, pure_cauchy x.2)),
{ ext ⟨a, b⟩; simp; refl },
rw [this, ← filter.comap_comap],
change filter.comap _ (filter.comap _ (𝓤 $ quotient $ separation_setoid $ Cauchy α)) = 𝓤 α,
rw [comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.comap_uniformity]
end
lemma uniform_inducing_coe : uniform_inducing (coe : α → completion α) :=
⟨comap_coe_eq_uniformity α⟩
variables {α}
lemma dense_range_coe : dense_range (coe : α → completion α) :=
dense_range_pure_cauchy.quotient
variables (α)
def cpkg {α : Type*} [uniform_space α] : abstract_completion α :=
{ space := completion α,
coe := coe,
uniform_struct := by apply_instance,
complete := by apply_instance,
separation := by apply_instance,
uniform_inducing := completion.uniform_inducing_coe α,
dense := completion.dense_range_coe }
instance abstract_completion.inhabited : inhabited (abstract_completion α) :=
⟨cpkg⟩
local attribute [instance]
abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation
lemma nonempty_completion_iff : nonempty (completion α) ↔ nonempty α :=
cpkg.dense.nonempty_iff.symm
lemma uniform_continuous_coe : uniform_continuous (coe : α → completion α) :=
cpkg.uniform_continuous_coe
lemma continuous_coe : continuous (coe : α → completion α) :=
cpkg.continuous_coe
lemma uniform_embedding_coe [separated_space α] : uniform_embedding (coe : α → completion α) :=
{ comap_uniformity := comap_coe_eq_uniformity α,
inj := separated_pure_cauchy_injective }
variable {α}
lemma dense_inducing_coe : dense_inducing (coe : α → completion α) :=
{ dense := dense_range_coe,
..(uniform_inducing_coe α).inducing }
open topological_space
instance separable_space_completion [separable_space α] : separable_space (completion α) :=
completion.dense_inducing_coe.separable_space
lemma dense_embedding_coe [separated_space α]: dense_embedding (coe : α → completion α) :=
{ inj := separated_pure_cauchy_injective,
..dense_inducing_coe }
lemma dense_range_coe₂ :
dense_range (λx:α × β, ((x.1 : completion α), (x.2 : completion β))) :=
dense_range_coe.prod_map dense_range_coe
lemma dense_range_coe₃ :
dense_range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ)))) :=
dense_range_coe.prod_map dense_range_coe₂
@[elab_as_eliminator]
lemma induction_on {p : completion α → Prop}
(a : completion α) (hp : is_closed {a | p a}) (ih : ∀a:α, p a) : p a :=
is_closed_property dense_range_coe hp ih a
@[elab_as_eliminator]
lemma induction_on₂ {p : completion α → completion β → Prop}
(a : completion α) (b : completion β)
(hp : is_closed {x : completion α × completion β | p x.1 x.2})
(ih : ∀(a:α) (b:β), p a b) : p a b :=
have ∀x : completion α × completion β, p x.1 x.2, from
is_closed_property dense_range_coe₂ hp $ assume ⟨a, b⟩, ih a b,
this (a, b)
@[elab_as_eliminator]
lemma induction_on₃ {p : completion α → completion β → completion γ → Prop}
(a : completion α) (b : completion β) (c : completion γ)
(hp : is_closed {x : completion α × completion β × completion γ | p x.1 x.2.1 x.2.2})
(ih : ∀(a:α) (b:β) (c:γ), p a b c) : p a b c :=
have ∀x : completion α × completion β × completion γ, p x.1 x.2.1 x.2.2, from
is_closed_property dense_range_coe₃ hp $ assume ⟨a, b, c⟩, ih a b c,
this (a, b, c)
lemma ext [t2_space β] {f g : completion α → β} (hf : continuous f) (hg : continuous g)
(h : ∀a:α, f a = g a) : f = g :=
cpkg.funext hf hg h
section extension
variables {f : α → β}
/-- "Extension" to the completion. It is defined for any map `f` but
returns an arbitrary constant value if `f` is not uniformly continuous -/
protected def extension (f : α → β) : completion α → β :=
cpkg.extend f
variables [separated_space β]
@[simp] lemma extension_coe (hf : uniform_continuous f) (a : α) : (completion.extension f) a = f a :=
cpkg.extend_coe hf a
variables [complete_space β]
lemma uniform_continuous_extension : uniform_continuous (completion.extension f) :=
cpkg.uniform_continuous_extend
lemma continuous_extension : continuous (completion.extension f) :=
cpkg.continuous_extend
lemma extension_unique (hf : uniform_continuous f) {g : completion α → β} (hg : uniform_continuous g)
(h : ∀ a : α, f a = g (a : completion α)) : completion.extension f = g :=
cpkg.extend_unique hf hg h
@[simp] lemma extension_comp_coe {f : completion α → β} (hf : uniform_continuous f) :
completion.extension (f ∘ coe) = f :=
cpkg.extend_comp_coe hf
end extension
section map
variables {f : α → β}
/-- Completion functor acting on morphisms -/
protected def map (f : α → β) : completion α → completion β :=
cpkg.map cpkg f
lemma uniform_continuous_map : uniform_continuous (completion.map f) :=
cpkg.uniform_continuous_map cpkg f
lemma continuous_map : continuous (completion.map f) :=
cpkg.continuous_map cpkg f
@[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : (completion.map f) a = f a :=
cpkg.map_coe cpkg hf a
lemma map_unique {f : α → β} {g : completion α → completion β}
(hg : uniform_continuous g) (h : ∀a:α, ↑(f a) = g a) : completion.map f = g :=
cpkg.map_unique cpkg hg h
@[simp] lemma map_id : completion.map (@id α) = id :=
cpkg.map_id
lemma extension_map [complete_space γ] [separated_space γ] {f : β → γ} {g : α → β}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
completion.extension f ∘ completion.map g = completion.extension (f ∘ g) :=
completion.ext (continuous_extension.comp continuous_map) continuous_extension $
by intro a; simp only [hg, hf, hf.comp hg, (∘), map_coe, extension_coe]
lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) :
completion.map g ∘ completion.map f = completion.map (g ∘ f) :=
extension_map ((uniform_continuous_coe _).comp hg) hf
end map
/- In this section we construct isomorphisms between the completion of a uniform space and the
completion of its separation quotient -/
section separation_quotient_completion
def completion_separation_quotient_equiv (α : Type u) [uniform_space α] :
completion (separation_quotient α) ≃ completion α :=
begin
refine ⟨completion.extension (separation_quotient.lift (coe : α → completion α)),
completion.map quotient.mk, _, _⟩,
{ assume a,
refine induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _,
rintros ⟨a⟩,
show completion.map quotient.mk (completion.extension (separation_quotient.lift coe) ↑⟦a⟧) = ↑⟦a⟧,
rw [extension_coe (separation_quotient.uniform_continuous_lift _),
separation_quotient.lift_mk (uniform_continuous_coe α),
completion.map_coe uniform_continuous_quotient_mk] ; apply_instance },
{ assume a,
refine completion.induction_on a (is_closed_eq (continuous_extension.comp continuous_map) continuous_id) _,
assume a,
rw [map_coe uniform_continuous_quotient_mk,
extension_coe (separation_quotient.uniform_continuous_lift _),
separation_quotient.lift_mk (uniform_continuous_coe α) _] ; apply_instance }
end
lemma uniform_continuous_completion_separation_quotient_equiv :
uniform_continuous ⇑(completion_separation_quotient_equiv α) :=
uniform_continuous_extension
lemma uniform_continuous_completion_separation_quotient_equiv_symm :
uniform_continuous ⇑(completion_separation_quotient_equiv α).symm :=
uniform_continuous_map
end separation_quotient_completion
section extension₂
variables (f : α → β → γ)
open function
protected def extension₂ (f : α → β → γ) : completion α → completion β → γ :=
cpkg.extend₂ cpkg f
variables [separated_space γ] {f}
@[simp] lemma extension₂_coe_coe (hf : uniform_continuous₂ f) (a : α) (b : β) :
completion.extension₂ f a b = f a b :=
cpkg.extension₂_coe_coe cpkg hf a b
variables [complete_space γ] (f)
lemma uniform_continuous_extension₂ : uniform_continuous₂ (completion.extension₂ f) :=
cpkg.uniform_continuous_extension₂ cpkg f
end extension₂
section map₂
open function
protected def map₂ (f : α → β → γ) : completion α → completion β → completion γ :=
cpkg.map₂ cpkg cpkg f
lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous₂ (completion.map₂ f) :=
cpkg.uniform_continuous_map₂ cpkg cpkg f
lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ}
{a : δ → completion α} {b : δ → completion β} (ha : continuous a) (hb : continuous b) :
continuous (λd:δ, completion.map₂ f (a d) (b d)) :=
cpkg.continuous_map₂ cpkg cpkg ha hb
lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous₂ f) :
completion.map₂ f (a : completion α) (b : completion β) = f a b :=
cpkg.map₂_coe_coe cpkg cpkg a b f hf
end map₂
end completion
end uniform_space
|
e941b0b2f178c0ba1c16ff5e606bdb4f000654b5 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/rbtree/min_max.lean | f206f16178fd5629215a49bebda2417d4fda9301 | [
"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 | 3,709 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import data.rbtree.basic
universe u
namespace rbnode
variables {α : Type u} {lt : α → α → Prop}
lemma mem_of_min_eq (lt : α → α → Prop) [is_irrefl α lt] {a : α} {t : rbnode α} :
t.min = some a → mem lt a t :=
begin
induction t,
{ intros, contradiction },
all_goals {
cases t_lchild; simp [rbnode.min]; intro h,
{ subst t_val, simp [mem, irrefl_of lt a] },
all_goals { rw [mem], simp [t_ih_lchild h] } }
end
lemma mem_of_max_eq (lt : α → α → Prop) [is_irrefl α lt] {a : α} {t : rbnode α} :
t.max = some a → mem lt a t :=
begin
induction t,
{ intros, contradiction },
all_goals {
cases t_rchild; simp [rbnode.max]; intro h,
{ subst t_val, simp [mem, irrefl_of lt a] },
all_goals { rw [mem], simp [t_ih_rchild h] } }
end
variables [is_strict_weak_order α lt]
lemma eq_leaf_of_min_eq_none {t : rbnode α} : t.min = none → t = leaf :=
begin
induction t,
{ intros, refl },
all_goals {
cases t_lchild; simp [rbnode.min, false_implies_iff]; intro h,
all_goals { have := t_ih_lchild h, contradiction } }
end
lemma eq_leaf_of_max_eq_none {t : rbnode α} : t.max = none → t = leaf :=
begin
induction t,
{ intros, refl },
all_goals {
cases t_rchild; simp [rbnode.max, false_implies_iff]; intro h,
all_goals { have := t_ih_rchild h, contradiction } }
end
lemma min_is_minimal {a : α} {t : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → t.min = some a → ∀ {b}, mem lt b t → a ≈[lt] b ∨ lt a b :=
begin
classical,
induction t,
{ simp [strict_weak_order.equiv], intros _ _ hs hmin b, contradiction },
all_goals {
cases t_lchild; intros lo hi hs hmin b hmem,
{ simp [rbnode.min] at hmin, subst t_val,
simp [mem] at hmem, cases hmem with heqv hmem,
{ left, exact heqv.swap },
{ have := lt_of_mem_right hs (by constructor) hmem,
right, assumption } },
all_goals {
have hs' := hs,
cases hs, simp [rbnode.min] at hmin,
rw [mem] at hmem, blast_disjs,
{ exact t_ih_lchild hs_hs₁ hmin hmem },
{ have hmm := mem_of_min_eq lt hmin,
have a_lt_val := lt_of_mem_left hs' (by constructor) hmm,
have a_lt_b := lt_of_lt_of_incomp a_lt_val hmem.swap,
right, assumption },
{ have hmm := mem_of_min_eq lt hmin,
have a_lt_b := lt_of_mem_left_right hs' (by constructor) hmm hmem,
right, assumption } } }
end
lemma max_is_maximal {a : α} {t : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → t.max = some a → ∀ {b}, mem lt b t → a ≈[lt] b ∨ lt b a :=
begin
classical,
induction t,
{ simp [strict_weak_order.equiv], intros _ _ hs hmax b, contradiction },
all_goals {
cases t_rchild; intros lo hi hs hmax b hmem,
{ simp [rbnode.max] at hmax, subst t_val,
simp [mem] at hmem, cases hmem with hmem heqv,
{ have := lt_of_mem_left hs (by constructor) hmem,
right, assumption },
{ left, exact heqv.swap } },
all_goals {
have hs' := hs,
cases hs, simp [rbnode.max] at hmax,
rw [mem] at hmem, blast_disjs,
{ have hmm := mem_of_max_eq lt hmax,
have a_lt_b := lt_of_mem_left_right hs' (by constructor) hmem hmm,
right, assumption },
{ have hmm := mem_of_max_eq lt hmax,
have val_lt_a := lt_of_mem_right hs' (by constructor) hmm,
have a_lt_b := lt_of_incomp_of_lt hmem val_lt_a,
right, assumption },
{ exact t_ih_rchild hs_hs₂ hmax hmem } } }
end
end rbnode
|
4561e759c3addc588541799b1aee7e2479f92c5e | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/ring/prod.lean | 9d8d565cce61b7c77d85c4cc52e2a1aa5048ccc6 | [
"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 | 4,527 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Chris Hughes, Mario Carneiro, Yury Kudryashov
-/
import algebra.group.prod
import algebra.ring.basic
import data.equiv.ring
/-!
# Semiring, ring etc structures on `R × S`
In this file we define two-binop (`semiring`, `ring` etc) structures on `R × S`. We also prove
trivial `simp` lemmas, and define the following operations on `ring_hom`s:
* `fst R S : R × S →+* R`, `snd R S : R × S →+* R`: projections `prod.fst` and `prod.snd`
as `ring_hom`s;
* `f.prod g : `R →+* S × T`: sends `x` to `(f x, g x)`;
* `f.prod_map g : `R × S → R' × S'`: `prod.map f g` as a `ring_hom`,
sends `(x, y)` to `(f x, g y)`.
-/
variables {R : Type*} {R' : Type*} {S : Type*} {S' : Type*} {T : Type*} {T' : Type*}
namespace prod
/-- Product of two semirings is a semiring. -/
instance [semiring R] [semiring S] : semiring (R × S) :=
{ zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩,
mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩,
left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩,
right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩,
.. prod.add_comm_monoid, .. prod.monoid }
/-- Product of two commutative semirings is a commutative semiring. -/
instance [comm_semiring R] [comm_semiring S] : comm_semiring (R × S) :=
{ .. prod.semiring, .. prod.comm_monoid }
/-- Product of two rings is a ring. -/
instance [ring R] [ring S] : ring (R × S) :=
{ .. prod.add_comm_group, .. prod.semiring }
/-- Product of two commutative rings is a commutative ring. -/
instance [comm_ring R] [comm_ring S] : comm_ring (R × S) :=
{ .. prod.ring, .. prod.comm_monoid }
end prod
namespace ring_hom
variables (R S) [semiring R] [semiring S]
/-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `R`.-/
def fst : R × S →+* R := { to_fun := prod.fst, .. monoid_hom.fst R S, .. add_monoid_hom.fst R S }
/-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `S`.-/
def snd : R × S →+* S := { to_fun := prod.snd, .. monoid_hom.snd R S, .. add_monoid_hom.snd R S }
variables {R S}
@[simp] lemma coe_fst : ⇑(fst R S) = prod.fst := rfl
@[simp] lemma coe_snd : ⇑(snd R S) = prod.snd := rfl
section prod
variables [semiring T] (f : R →+* S) (g : R →+* T)
/-- Combine two ring homomorphisms `f : R →+* S`, `g : R →+* T` into `f.prod g : R →+* S × T`
given by `(f.prod g) x = (f x, g x)` -/
protected def prod (f : R →+* S) (g : R →+* T) : R →+* S × T :=
{ to_fun := λ x, (f x, g x),
.. monoid_hom.prod (f : R →* S) (g : R →* T), .. add_monoid_hom.prod (f : R →+ S) (g : R →+ T) }
@[simp] lemma prod_apply (x) : f.prod g x = (f x, g x) := rfl
@[simp] lemma fst_comp_prod : (fst S T).comp (f.prod g) = f :=
ext $ λ x, rfl
@[simp] lemma snd_comp_prod : (snd S T).comp (f.prod g) = g :=
ext $ λ x, rfl
lemma prod_unique (f : R →+* S × T) :
((fst S T).comp f).prod ((snd S T).comp f) = f :=
ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta]
end prod
section prod_map
variables [semiring R'] [semiring S'] [semiring T] (f : R →+* R') (g : S →+* S')
/-- `prod.map` as a `ring_hom`. -/
def prod_map : R × S →* R' × S' := (f.comp (fst R S)).prod (g.comp (snd R S))
lemma prod_map_def : prod_map f g = (f.comp (fst R S)).prod (g.comp (snd R S)) := rfl
@[simp]
lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl
lemma prod_comp_prod_map (f : T →* R) (g : T →* S) (f' : R →* R') (g' : S →* S') :
(f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) :=
rfl
end prod_map
end ring_hom
namespace ring_equiv
variables {R S} [semiring R] [semiring S]
/-- Swapping components as an equivalence of (semi)rings. -/
def prod_comm : R × S ≃+* S × R :=
{ ..add_equiv.prod_comm, ..mul_equiv.prod_comm }
@[simp] lemma coe_prod_comm : ⇑(prod_comm : R × S ≃+* S × R) = prod.swap := rfl
@[simp] lemma coe_prod_comm_symm : ⇑((prod_comm : R × S ≃+* S × R).symm) = prod.swap := rfl
@[simp] lemma fst_comp_coe_prod_comm :
(ring_hom.fst S R).comp ↑(prod_comm : R × S ≃+* S × R) = ring_hom.snd R S :=
ring_hom.ext $ λ _, rfl
@[simp] lemma snd_comp_coe_prod_comm :
(ring_hom.snd S R).comp ↑(prod_comm : R × S ≃+* S × R) = ring_hom.fst R S :=
ring_hom.ext $ λ _, rfl
end ring_equiv
|
992a9ae9e8de7f33340a672f5f3506037391f3cf | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/linear_algebra/lagrange.lean | 867eb7c814b32d849b3970eb4dc58e0dfbf8b60c | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 6,971 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kenny Lau.
-/
import ring_theory.polynomial algebra.big_operators
/-!
# Lagrange interpolation
## Main definitions
* `lagrange.basis s x` where `s : finset F` and `x : F`: the Lagrange basis polynomial
that evaluates to `1` at `x` and `0` at other elements of `s`.
* `lagrange.interpolate s f` where `s : finset F` and `f : s → F`: the Lagrange interpolant
that evaluates to `f x` at `x` for `x ∈ s`.
-/
noncomputable theory
open_locale big_operators classical
universe u
namespace lagrange
variables {F : Type u} [decidable_eq F] [field F] (s : finset F)
variables {F' : Type u} [field F'] (s' : finset F')
open polynomial
/-- Lagrange basis polynomials that evaluate to 1 at `x` and 0 at other elements of `s`. -/
def basis (x : F) : polynomial F :=
∏ y in s.erase x, C (x - y)⁻¹ * (X - C y)
@[simp] theorem basis_empty (x : F) : basis ∅ x = 1 :=
rfl
@[simp] theorem eval_basis_self (x : F) : (basis s x).eval x = 1 :=
begin
rw [basis, ← (s.erase x).prod_hom (eval x), finset.prod_eq_one],
intros y hy, simp_rw [eval_mul, eval_sub, eval_C, eval_X],
exact inv_mul_cancel (sub_ne_zero_of_ne (finset.ne_of_mem_erase hy).symm)
end
@[simp] theorem eval_basis_ne (x y : F) (h1 : y ∈ s) (h2 : y ≠ x) : (basis s x).eval y = 0 :=
begin
rw [basis, ← (s.erase x).prod_hom (eval y), finset.prod_eq_zero (finset.mem_erase.2 ⟨h2, h1⟩)],
simp_rw [eval_mul, eval_sub, eval_C, eval_X, sub_self, mul_zero]
end
theorem eval_basis (x y : F) (h : y ∈ s) : (basis s x).eval y = if y = x then 1 else 0 :=
by { split_ifs with H, { subst H, apply eval_basis_self }, { exact eval_basis_ne s x y h H } }
@[simp] theorem nat_degree_basis (x : F) (hx : x ∈ s) : (basis s x).nat_degree = s.card - 1 :=
begin
unfold basis, generalize hsx : s.erase x = sx,
have : x ∉ sx := hsx ▸ finset.not_mem_erase x s,
rw [← finset.insert_erase hx, hsx, finset.card_insert_of_not_mem this, nat.add_sub_cancel],
clear hx hsx s, revert this, apply sx.induction_on,
{ intros hx, rw [finset.prod_empty, nat_degree_one], refl },
{ intros y s hys ih hx, rw [finset.mem_insert, not_or_distrib] at hx,
have h1 : C (x - y)⁻¹ ≠ C 0 := λ h, hx.1 (eq_of_sub_eq_zero $ inv_eq_zero.1 $ C_inj.1 h),
have h2 : X ^ 1 - C y ≠ 0 := by convert X_pow_sub_C_ne_zero zero_lt_one y,
rw C_0 at h1, rw pow_one at h2,
rw [finset.prod_insert hys, nat_degree_mul_eq (mul_ne_zero h1 h2), ih hx.2,
finset.card_insert_of_not_mem hys, nat_degree_mul_eq h1 h2,
nat_degree_C, zero_add, nat_degree, degree_X_sub_C, add_comm], refl,
rw [ne, finset.prod_eq_zero_iff], rintro ⟨z, hzs, hz⟩,
rw mul_eq_zero at hz, cases hz with hz hz,
{ rw [← C_0, C_inj, inv_eq_zero, sub_eq_zero] at hz, exact hx.2 (hz.symm ▸ hzs) },
{ rw ← pow_one (X : polynomial F) at hz, exact X_pow_sub_C_ne_zero zero_lt_one _ hz } }
end
variables (f : (↑s : set F) → F)
/-- Lagrange interpolation: given a finset `s` and a function `f : s → F`,
`interpolate s f` is the unique polynomial of degree `< s.card`
that takes value `f x` on all `x` in `s`. -/
def interpolate : polynomial F :=
∑ x in s.attach, C (f x) * basis s x
@[simp] theorem interpolate_empty (f) : interpolate (∅ : finset F) f = 0 :=
rfl
@[simp] theorem eval_interpolate (x) (H : x ∈ s) : eval x (interpolate s f) = f ⟨x, H⟩ :=
begin
rw [interpolate, ← finset.sum_hom _ (eval x), finset.sum_eq_single (⟨x, H⟩ : { x // x ∈ s })],
{ rw [eval_mul, eval_C, subtype.coe_mk, eval_basis_self, mul_one] },
{ rintros ⟨y, hy⟩ _ hyx, rw [eval_mul, subtype.coe_mk, eval_basis_ne s y x H, mul_zero],
{ rintros rfl, exact hyx rfl } },
{ intro h, exact absurd (finset.mem_attach _ _) h }
end
theorem degree_interpolate_lt : (interpolate s f).degree < s.card :=
if H : s = ∅ then by { subst H, rw [interpolate_empty, degree_zero], exact with_bot.bot_lt_coe _ }
else lt_of_le_of_lt (degree_sum_le _ _) $ (finset.sup_lt_iff $ with_bot.bot_lt_coe s.card).2 $ λ b _,
calc (C (f b) * basis s b).degree
≤ (C (f b)).degree + (basis s b).degree : degree_mul_le _ _
... ≤ 0 + (basis s b).degree : add_le_add_right degree_C_le _
... = (basis s b).degree : zero_add _
... ≤ (basis s b).nat_degree : degree_le_nat_degree
... = (s.card - 1 : ℕ) : by { rw nat_degree_basis s b b.2 }
... < s.card : with_bot.coe_lt_coe.2 (nat.pred_lt $ mt finset.card_eq_zero.1 H)
/-- Linear version of `interpolate`. -/
def linterpolate : ((↑s : set F) → F) →ₗ[F] polynomial F :=
{ to_fun := interpolate s,
map_add' := λ f g, by { simp_rw [interpolate, ← finset.sum_add_distrib, ← add_mul, ← C_add],
refl },
map_smul' := λ c f, by { simp_rw [interpolate, finset.smul_sum, C_mul', smul_smul], refl } }
@[simp] lemma interpolate_add (f g) : interpolate s (f + g) = interpolate s f + interpolate s g :=
(linterpolate s).map_add f g
@[simp] lemma interpolate_zero : interpolate s 0 = 0 :=
(linterpolate s).map_zero
@[simp] lemma interpolate_neg (f) : interpolate s (-f) = -interpolate s f :=
(linterpolate s).map_neg f
@[simp] lemma interpolate_sub (f g) : interpolate s (f - g) = interpolate s f - interpolate s g :=
(linterpolate s).map_sub f g
@[simp] lemma interpolate_smul (c : F) (f) : interpolate s (c • f) = c • interpolate s f :=
(linterpolate s).map_smul c f
theorem eq_zero_of_eval_eq_zero {f : polynomial F'} (hf1 : f.degree < s'.card)
(hf2 : ∀ x ∈ s', f.eval x = 0) : f = 0 :=
by_contradiction $ λ hf3, not_le_of_lt hf1 $
calc (s'.card : with_bot ℕ)
≤ f.roots.card : with_bot.coe_le_coe.2 $ finset.card_le_of_subset $ λ x hx,
(mem_roots hf3).2 $ hf2 x hx
... ≤ f.degree : card_roots hf3
theorem eq_of_eval_eq {f g : polynomial F'} (hf : f.degree < s'.card) (hg : g.degree < s'.card)
(hfg : ∀ x ∈ s', f.eval x = g.eval x) : f = g :=
eq_of_sub_eq_zero $ eq_zero_of_eval_eq_zero s'
(lt_of_le_of_lt (degree_sub_le f g) $ max_lt hf hg)
(λ x hx, by rw [eval_sub, hfg x hx, sub_self])
theorem eq_interpolate (f : polynomial F) (hf : f.degree < s.card) :
interpolate s (λ x, f.eval x) = f :=
eq_of_eval_eq s (degree_interpolate_lt s _) hf $ λ x hx, eval_interpolate s _ x hx
/-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials
of degree less than `s.card`. -/
def fun_equiv_degree_lt : degree_lt F s.card ≃ₗ[F] ((↑s : set F) → F) :=
{ to_fun := λ f x, f.1.eval x,
map_add' := λ f g, funext $ λ x, eval_add,
map_smul' := λ c f, funext $ λ x, by { rw [pi.smul_apply, smul_eq_mul, ← @eval_C F c _ x,
← eval_mul, eval_C, C_mul'], refl },
inv_fun := λ f, ⟨interpolate s f, mem_degree_lt.2 $ degree_interpolate_lt s f⟩,
left_inv := λ f, subtype.eq $ eq_interpolate s f $ mem_degree_lt.1 f.2,
right_inv := λ f, funext $ λ ⟨x, hx⟩, eval_interpolate s f x hx }
end lagrange
|
a04f3b94712ce929eb2f01fcc810c6c974bc64cf | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Elab/Do.lean | 9160cd89a9126d44e941a78872b7ab16617af756 | [
"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",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 72,652 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Term
import Lean.Elab.BindersUtil
import Lean.Elab.PatternVar
import Lean.Elab.Quotation.Util
import Lean.Parser.Do
-- HACK: avoid code explosion until heuristics are improved
set_option compiler.reuse false
namespace Lean.Elab.Term
open Lean.Parser.Term
open Meta
open TSyntax.Compat
private def getDoSeqElems (doSeq : Syntax) : List Syntax :=
if doSeq.getKind == ``Parser.Term.doSeqBracketed then
doSeq[1].getArgs.toList.map fun arg => arg[0]
else if doSeq.getKind == ``Parser.Term.doSeqIndent then
doSeq[0].getArgs.toList.map fun arg => arg[0]
else
[]
private def getDoSeq (doStx : Syntax) : Syntax :=
doStx[1]
@[builtin_term_elab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>
throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression"
/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/
private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=
k == ``Parser.Term.do ||
k == ``Parser.Term.doSeqIndent ||
k == ``Parser.Term.doSeqBracketed ||
k == ``Parser.Term.termReturn ||
k == ``Parser.Term.termUnless ||
k == ``Parser.Term.termTry ||
k == ``Parser.Term.termFor
/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/
private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=
let k := letDeclArg.getKind
if k == ``Parser.Term.letPatDecl then
false
else if k == ``Parser.Term.letEqnsDecl then
true
else if k == ``Parser.Term.letIdDecl then
-- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> letIdBinder)) >> optType
let binders := letDeclArg[1]
binders.getNumArgs > 0
else
false
/-- Return `true` if the given `letDecl` contains binders. -/
private def letDeclHasBinders (letDecl : Syntax) : Bool :=
letDeclArgHasBinders letDecl[0]
/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/
private def liftMethodForbiddenBinder (stx : Syntax) : Bool :=
let k := stx.getKind
if k == ``Parser.Term.fun || k == ``Parser.Term.matchAlts ||
k == ``Parser.Term.doLetRec || k == ``Parser.Term.letrec then
-- It is never ok to lift over this kind of binder
true
-- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not
else if k == ``Parser.Term.let then
letDeclHasBinders stx[1]
else if k == ``Parser.Term.doLet then
letDeclHasBinders stx[2]
else if k == ``Parser.Term.doLetArrow then
letDeclArgHasBinders stx[2]
else
false
private partial def hasLiftMethod : Syntax → Bool
| Syntax.node _ k args =>
if liftMethodDelimiter k then false
-- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a
-- bit slower
else if k == ``Parser.Term.liftMethod then true
else args.any hasLiftMethod
| _ => false
structure ExtractMonadResult where
m : Expr
returnType : Expr
expectedType : Expr
private def mkUnknownMonadResult : MetaM ExtractMonadResult := do
let u ← mkFreshLevelMVar
let v ← mkFreshLevelMVar
let m ← mkFreshExprMVar (← mkArrow (mkSort (mkLevelSucc u)) (mkSort (mkLevelSucc v)))
let returnType ← mkFreshExprMVar (mkSort (mkLevelSucc u))
return { m, returnType, expectedType := mkApp m returnType }
private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do
let some expectedType := expectedType? | mkUnknownMonadResult
let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do
let .app m returnType := type | return none
try
let bindInstType ← mkAppM ``Bind #[m]
discard <| Meta.synthInstance bindInstType
return some { m, returnType, expectedType }
catch _ =>
return none
let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match (← extractStep? type) with
| some r => return r
| none =>
let typeNew ← whnfCore type
if typeNew != type then
extract? typeNew
else
if typeNew.getAppFn.isMVar then
mkUnknownMonadResult
else match (← unfoldDefinition? typeNew) with
| some typeNew => extract? typeNew
| none => return none
match (← extract? expectedType) with
| some r => return r
| none => throwError "invalid `do` notation, expected type is not a monad application{indentExpr expectedType}\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad."
namespace Do
abbrev Var := Syntax -- TODO: should be `Ident`
/-- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/
structure Alt (σ : Type) where
ref : Syntax
vars : Array Var
patterns : Syntax
rhs : σ
deriving Inhabited
/--
Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`).
We convert `Code` into a `Syntax` term representing the:
- `do`-block, or
- the visitor argument for the `forIn` combinator.
We say the following constructors are terminals:
- `break`: for interrupting a `for x in s`
- `continue`: for interrupting the current iteration of a `for x in s`
- `return e`: for returning `e` as the result for the whole `do` computation block
- `action a`: for executing action `a` as a terminal
- `ite`: if-then-else
- `match`: pattern matching
- `jmp` a goto to a join-point
We say the terminals `break`, `continue`, `action`, and `return` are "exit points"
Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:
```
def f (x : Nat) : IO Unit := do
if x == 0 then
return ()
IO.println "hello"
```
Executing `#eval f 0` will not print "hello". Now, consider
```
def g (x : Nat) : IO Unit := do
if x == 0 then
pure ()
IO.println "hello"
```
The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`.
- `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).
The field `stx` is the actual `doElem`,
`vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.
`vars` is an array since we have declarations such as `let (a, b) := s`.
- `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).
- `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.
- `seq a k` executes action `a`, ignores its result, and then executes `k`.
We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.
A code block `C` is well-formed if
- For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and
`ps.size == as.size` -/
inductive Code where
| decl (xs : Array Var) (doElem : Syntax) (k : Code)
| reassign (xs : Array Var) (doElem : Syntax) (k : Code)
/-- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/
| joinpoint (name : Name) (params : Array (Var × Bool)) (body : Code) (k : Code)
| seq (action : Syntax) (k : Code)
| action (action : Syntax)
| break (ref : Syntax)
| continue (ref : Syntax)
| return (ref : Syntax) (val : Syntax)
/-- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/
| ite (ref : Syntax) (h? : Option Var) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)
| match (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt Code))
| jmp (ref : Syntax) (jpName : Name) (args : Array Syntax)
deriving Inhabited
def Code.getRef? : Code → Option Syntax
| .decl _ doElem _ => doElem
| .reassign _ doElem _ => doElem
| .joinpoint .. => none
| .seq a _ => a
| .action a => a
| .break ref => ref
| .continue ref => ref
| .return ref _ => ref
| .ite ref .. => ref
| .match ref .. => ref
| .jmp ref .. => ref
abbrev VarSet := RBMap Name Syntax Name.cmp
/-- A code block, and the collection of variables updated by it. -/
structure CodeBlock where
code : Code
uvars : VarSet := {} -- set of variables updated by `code`
private def varSetToArray (s : VarSet) : Array Var :=
s.fold (fun xs _ x => xs.push x) #[]
private def varsToMessageData (vars : Array Var) : MessageData :=
MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.getId.simpMacroScopes)) " "
partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=
let us := MessageData.ofList <| (varSetToArray codeBlock.uvars).toList.map MessageData.ofSyntax
let rec loop : Code → MessageData
| .decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}"
| .reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}"
| .joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}"
| .seq e k => m!"{e}\n{loop k}"
| .action e => e
| .ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}"
| .jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}"
| .break _ => m!"break {us}"
| .continue _ => m!"continue {us}"
| .return _ v => m!"return {v} {us}"
| .match _ _ ds _ alts =>
m!"match {ds} with"
++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}"
loop codeBlock.code
/-- Return true if the give code contains an exit point that satisfies `p` -/
partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool :=
let rec loop : Code → Bool
| .decl _ _ k => loop k
| .reassign _ _ k => loop k
| .joinpoint _ _ b k => loop b || loop k
| .seq _ k => loop k
| .ite _ _ _ _ t e => loop t || loop e
| .match _ _ _ _ alts => alts.any (loop ·.rhs)
| .jmp .. => false
| c => p c
loop c
def hasExitPoint (c : Code) : Bool :=
hasExitPointPred c fun _ => true
def hasReturn (c : Code) : Bool :=
hasExitPointPred c fun
| .return .. => true
| _ => false
def hasTerminalAction (c : Code) : Bool :=
hasExitPointPred c fun
| .action _ => true
| _ => false
def hasBreakContinue (c : Code) : Bool :=
hasExitPointPred c fun
| .break _ => true
| .continue _ => true
| _ => false
def hasBreakContinueReturn (c : Code) : Bool :=
hasExitPointPred c fun
| .break _ => true
| .continue _ => true
| .return _ _ => true
| _ => false
def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do
let y ← `(y)
let doElem ← `(doElem| let y ← $e:term)
-- Add elaboration hint for producing sane error message
let y ← `(ensure_expected_type% "type mismatch, result value" $y)
let k ← mkCont y
return .decl #[y] doElem k
/-- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/
partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Var) : MacroM Code :=
let rec loop : Code → MacroM Code
| .decl xs stx k => return .decl xs stx (← loop k)
| .reassign xs stx k => return .reassign xs stx (← loop k)
| .joinpoint n ps b k => return .joinpoint n ps (← loop b) (← loop k)
| .seq e k => return .seq e (← loop k)
| .ite ref x? h c t e => return .ite ref x? h c (← loop t) (← loop e)
| .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) })
| .action e => mkAuxDeclFor e fun y =>
let ref := e
-- We jump to `jp` with xs **and** y
let jmpArgs := xs.push y
return Code.jmp ref jp jmpArgs
| c => return c
loop code
structure JPDecl where
name : Name
params : Array (Var × Bool)
body : Code
def attachJP (jpDecl : JPDecl) (k : Code) : Code :=
Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k
def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=
jpDecls.foldr attachJP k
def mkFreshJP (ps : Array (Var × Bool)) (body : Code) : TermElabM JPDecl := do
let ps ← if ps.isEmpty then
let y ← `(y)
pure #[(y.raw, false)]
else
pure ps
-- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by
-- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`
-- We will remove this hack when we re-implement the compiler frontend in Lean.
let name ← mkFreshUserName `__do_jp
pure { name := name, params := ps, body := body }
def addFreshJP (ps : Array (Var × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do
let jp ← mkFreshJP ps body
modify fun (jps : Array JPDecl) => jps.push jp
pure jp.name
def insertVars (rs : VarSet) (xs : Array Var) : VarSet :=
xs.foldl (fun rs x => rs.insert x.getId x) rs
def eraseVars (rs : VarSet) (xs : Array Var) : VarSet :=
xs.foldl (·.erase ·.getId) rs
def eraseOptVar (rs : VarSet) (x? : Option Var) : VarSet :=
match x? with
| none => rs
| some x => rs.insert x.getId x
/-- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/
def mkSimpleJmp (ref : Syntax) (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := varSetToArray rs
let jp ← addFreshJP (xs.map fun x => (x, true)) c
if xs.isEmpty then
let unit ← ``(Unit.unit)
return Code.jmp ref jp #[unit]
else
return Code.jmp ref jp xs
/-- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.
The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`
is a fresh variable created by this method. -/
def mkJmp (ref : Syntax) (rs : VarSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := varSetToArray rs
let args := xs.push val
let yFresh ← withRef ref `(y)
let ps := xs.map fun x => (x, true)
let ps := ps.push (yFresh, false)
let jpBody ← liftMacroM <| mkJPBody yFresh
let jp ← addFreshJP ps jpBody
return Code.jmp ref jp args
/-- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/
partial def pullExitPointsAux (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code :=
match c with
| .decl xs stx k => return .decl xs stx (← pullExitPointsAux (eraseVars rs xs) k)
| .reassign xs stx k => return .reassign xs stx (← pullExitPointsAux (insertVars rs xs) k)
| .joinpoint j ps b k => return .joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k)
| .seq e k => return .seq e (← pullExitPointsAux rs k)
| .ite ref x? o c t e => return .ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e)
| .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })
| .jmp .. => return c
| .break ref => mkSimpleJmp ref rs (.break ref)
| .continue ref => mkSimpleJmp ref rs (.continue ref)
| .return ref val => mkJmp ref rs val (fun y => return .return ref y)
| .action e =>
-- We use `mkAuxDeclFor` because `e` is not pure.
mkAuxDeclFor e fun y =>
let ref := e
mkJmp ref rs y (fun yFresh => return .action (← ``(Pure.pure $yFresh)))
/--
Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.
When a new variable is not already in the collection, but is shadowed by some declaration in `c`,
we create auxiliary join points to make sure we preserve the semantics of the code block.
Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it
with the reassignment `x := x + 1`. We first use `pullExitPoints` to create
```
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
and then we add the reassignment
```
x := x + 1
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
Note that we created a fresh variable `x!1` to avoid accidental name capture.
As another example, consider
```
print x;
let x := 10
y := y + 1;
return x;
```
We transform it into
```
let jp (y x!1) := return x!1;
print x;
let x := 10
y := y + 1;
jmp jp y x
```
and then we add the reassignment as in the previous example.
We need to include `y` in the jump, because each exit point is implicitly returning the set of
update variables.
We implement the method as follows. Let `us` be `c.uvars`, then
1- for each `return _ y` in `c`, we create a join point
`let j (us y!1) := return y!1`
and replace the `return _ y` with `jmp us y`
2- for each `break`, we create a join point
`let j (us) := break`
and replace the `break` with `jmp us`.
3- Same as 2 for `continue`.
-/
def pullExitPoints (c : Code) : TermElabM Code := do
if hasExitPoint c then
let (c, jpDecls) ← (pullExitPointsAux {} c).run #[]
return attachJPs jpDecls c
else
return c
partial def extendUpdatedVarsAux (c : Code) (ws : VarSet) : TermElabM Code :=
let rec update (c : Code) : TermElabM Code := do
match c with
| .joinpoint j ps b k => return .joinpoint j ps (← update b) (← update k)
| .seq e k => return .seq e (← update k)
| .match ref g ds t alts =>
if alts.any fun alt => alt.vars.any fun x => ws.contains x.getId then
-- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`
pullExitPoints c
else
return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) })
| .ite ref none o c t e => return .ite ref none o c (← update t) (← update e)
| .ite ref (some h) o cond t e =>
if ws.contains h.getId then
-- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`
pullExitPoints c
else
return Code.ite ref (some h) o cond (← update t) (← update e)
| .reassign xs stx k => return .reassign xs stx (← update k)
| .decl xs stx k => do
if xs.any fun x => ws.contains x.getId then
-- One the declared variables is shadowing a variable in `ws`
pullExitPoints c
else
return .decl xs stx (← update k)
| c => return c
update c
/--
Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.
We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.
See discussion at `pullExitPoints`.
-/
partial def extendUpdatedVars (c : CodeBlock) (ws : VarSet) : TermElabM CodeBlock := do
if ws.any fun x _ => !c.uvars.contains x then
-- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)
pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws }
else
pure { c with uvars := ws }
private def union (s₁ s₂ : VarSet) : VarSet :=
s₁.fold (·.insert ·) s₂
/--
Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables.
Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`.
We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws`
-/
def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do
let ws := union c₁.uvars c₂.uvars
let c₁ ← extendUpdatedVars c₁ ws
let c₂ ← extendUpdatedVars c₂ ws
pure (c₁, c₂)
/--
Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`.
We remove `x` from the collection of updated varibles.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `let (x, y) := t`
-/
def mkVarDeclCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : CodeBlock := {
code := Code.decl xs stx c.code,
uvars := eraseVars c.uvars xs
}
/--
Extending code blocks with reassignments: `x : t := v` and `x : t ← v`.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `(x, y) ← t`
-/
def mkReassignCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do
let us := c.uvars
let ws := insertVars us xs
-- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.
-- See discussion at `pullExitPoints`
let code ← if xs.any fun x => !us.contains x.getId then extendUpdatedVarsAux c.code ws else pure c.code
pure { code := .reassign xs stx code, uvars := ws }
def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := .seq action c.code }
def mkTerminalAction (action : Syntax) : CodeBlock :=
{ code := .action action }
def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=
{ code := .return ref val }
def mkBreak (ref : Syntax) : CodeBlock :=
{ code := .break ref }
def mkContinue (ref : Syntax) : CodeBlock :=
{ code := .continue ref }
def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do
let x? := optIdent.getOptional?
let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch
return {
code := .ite ref x? optIdent cond thenBranch.code elseBranch.code,
uvars := thenBranch.uvars,
}
private def mkUnit : MacroM Syntax :=
``((⟨⟩ : PUnit))
private def mkPureUnit : MacroM Syntax :=
``(pure PUnit.unit)
def mkPureUnitAction : MacroM CodeBlock := do
return mkTerminalAction (← mkPureUnit)
def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do
let thenBranch ← mkPureUnitAction
return { c with code := .ite (← getRef) none mkNullNode cond thenBranch.code c.code }
def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do
-- nary version of homogenize
let ws := alts.foldl (union · ·.rhs.uvars) {}
let alts ← alts.mapM fun alt => do
let rhs ← extendUpdatedVars alt.rhs ws
return { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }
return { code := .match ref genParam discrs optMotive alts, uvars := ws }
/-- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.
This method assumes `terminal` is a terminal -/
def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Var) (k : CodeBlock) : TermElabM CodeBlock := do
unless hasTerminalAction terminal.code do
throwErrorAt kRef "`do` element is unreachable"
let (terminal, k) ← homogenize terminal k
let xs := varSetToArray k.uvars
let y ← match y? with | some y => pure y | none => `(y)
let ps := xs.map fun x => (x, true)
let ps := ps.push (y, false)
let jpDecl ← mkFreshJP ps k.code
let jp := jpDecl.name
let terminal ← liftMacroM <| convertTerminalActionIntoJmp terminal.code jp xs
return { code := attachJP jpDecl terminal, uvars := k.uvars }
def getLetIdDeclVar (letIdDecl : Syntax) : Var :=
letIdDecl[0]
-- support both regular and syntax match
def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Var) :=
getPatternVars pattern <|>
Quotation.getPatternVars pattern
def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Var) :=
getPatternsVars patterns <|>
Quotation.getPatternsVars patterns
def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Var) := do
let pattern := letPatDecl[0]
getPatternVarsEx pattern
def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Var :=
letEqnsDecl[0]
def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Var) := do
let arg := letDecl[0]
if arg.getKind == ``Parser.Term.letIdDecl then
return #[getLetIdDeclVar arg]
else if arg.getKind == ``Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == ``Parser.Term.letEqnsDecl then
return #[getLetEqnsDeclVar arg]
else
throwError "unexpected kind of let declaration"
def getDoLetVars (doLet : Syntax) : TermElabM (Array Var) :=
-- leading_parser "let " >> optional "mut " >> letDecl
getLetDeclVars doLet[2]
def getHaveIdLhsVar (optIdent : Syntax) : TermElabM Var :=
if optIdent.isNone then
`(this)
else
pure optIdent[0]
def getDoHaveVars (doHave : Syntax) : TermElabM (Array Var) := do
-- doHave := leading_parser "have " >> Term.haveDecl
-- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl
let arg := doHave[1][0]
if arg.getKind == ``Parser.Term.haveIdDecl then
-- haveIdDecl := leading_parser atomic (haveIdLhs >> " := ") >> termParser
-- haveIdLhs := optional (ident >> many (ppSpace >> letIdBinder)) >> optType
return #[← getHaveIdLhsVar arg[0]]
else if arg.getKind == ``Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == ``Parser.Term.haveEqnsDecl then
-- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts
return #[← getHaveIdLhsVar arg[0]]
else
throwError "unexpected kind of have declaration"
def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Var) := do
-- letRecDecls is an array of `(group (optional attributes >> letDecl))`
let letRecDecls := doLetRec[1][0].getSepArgs
let letDecls := letRecDecls.map fun p => p[2]
let mut allVars := #[]
for letDecl in letDecls do
let vars ← getLetDeclVars letDecl
allVars := allVars ++ vars
return allVars
-- ident >> optType >> leftArrow >> termParser
def getDoIdDeclVar (doIdDecl : Syntax) : Var :=
doIdDecl[0]
-- termParser >> leftArrow >> termParser >> optional (" | " >> termParser)
def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Var) := do
let pattern := doPatDecl[0]
getPatternVarsEx pattern
-- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Var) := do
let decl := doLetArrow[2]
if decl.getKind == ``Parser.Term.doIdDecl then
return #[getDoIdDeclVar decl]
else if decl.getKind == ``Parser.Term.doPatDecl then
getDoPatDeclVars decl
else
throwError "unexpected kind of `do` declaration"
def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Var) := do
let arg := doReassign[0]
if arg.getKind == ``Parser.Term.letIdDecl then
return #[getLetIdDeclVar arg]
else if arg.getKind == ``Parser.Term.letPatDecl then
getLetPatDeclVars arg
else
throwError "unexpected kind of reassignment"
def mkDoSeq (doElems : Array Syntax) : Syntax :=
mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode <| doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]
/--
If the given syntax is a `doIf`, return an equivalent `doIf` that has an `else` but no `else if`s or `if let`s. -/
private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with
| `(doElem|if $_:doIfProp then $_ else $_) => pure none
| `(doElem|if $cond:doIfCond then $t $[else if $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do
let mut e := e?.getD (← `(doSeq|pure PUnit.unit))
let mut eIsSeq := true
for (cond, t) in Array.zip (conds.reverse.push cond) (ts.reverse.push t) do
e ← if eIsSeq then pure e else `(doSeq|$e:doElem)
e ← match cond with
| `(doIfCond|let $pat := $d) => `(doElem| match $d:term with | $pat:term => $t | _ => $e)
| `(doIfCond|let $pat ← $d) => `(doElem| match ← $d with | $pat:term => $t | _ => $e)
| `(doIfCond|$cond:doIfProp) => `(doElem| if $cond:doIfProp then $t else $e)
| _ => `(doElem| if $(Syntax.missing) then $t else $e)
eIsSeq := false
return some e
| _ => pure none
structure DoIfView where
ref : Syntax
optIdent : Syntax
cond : Syntax
thenBranch : Syntax
elseBranch : Syntax
/-- This method assumes `expandDoIf?` is not applicable. -/
private def mkDoIfView (doIf : Syntax) : DoIfView := {
ref := doIf
optIdent := doIf[1][0]
cond := doIf[1][1]
thenBranch := doIf[3]
elseBranch := doIf[5][1]
}
/--
We use `MProd` instead of `Prod` to group values when expanding the
`do` notation. `MProd` is a universe monomorphic product.
The motivation is to generate simpler universe constraints in code
that was not written by the user.
Note that we are not restricting the macro power since the
`Bind.bind` combinator already forces values computed by monadic
actions to be in the same universe.
-/
private def mkTuple (elems : Array Syntax) : MacroM Syntax := do
if elems.size == 0 then
mkUnit
else if elems.size == 1 then
return elems[0]!
else
elems.extract 0 (elems.size - 1) |>.foldrM (init := elems.back) fun elem tuple =>
``(MProd.mk $elem $tuple)
/-- Return `some action` if `doElem` is a `doExpr <action>`-/
def isDoExpr? (doElem : Syntax) : Option Syntax :=
if doElem.getKind == ``Parser.Term.doExpr then
some doElem[0]
else
none
/--
Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term
```
let a_1 := x.1
let x := x.2
let a_2 := x.1
let x := x.2
...
let a_n := x.1
let a_{n+1} := x.2
body
```
Special cases
- `uvars := #[]` => `body`
- `uvars := #[a]` => `let a := x; body`
We use this method when expanding the `for-in` notation.
-/
private def destructTuple (uvars : Array Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do
if uvars.size == 0 then
return body
else if uvars.size == 1 then
`(let $(uvars[0]!):ident := $x; $body)
else
destruct uvars.toList x body
where
destruct (as : List Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do
match as with
| [a, b] => `(let $a:ident := $x.1; let $b:ident := $x.2; $body)
| a :: as => withFreshMacroScope do
let rest ← destruct as (← `(x)) body
`(let $a:ident := $x.1; let x := $x.2; $rest)
| _ => unreachable!
/-!
The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.
We use this method to convert
1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of
`CodeBlock` never contains `break` nor `continue`. Moreover, the collection
of updated variables is not packed into the result.
Thus, we have two kinds of exit points
- `Code.action e` which is converted into `e`
- `Code.return _ e` which is converted into `pure e`
We use `Kind.regular` for this case.
2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate
a `Syntax` term representing a function for the `xs.forIn` combinator.
a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term
has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type
of the tuple of variables reassigned by `b`.
We use `Kind.forInWithReturn` for this case
b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated
`Syntax` term has type `m (ForInStep σ)`.
We use `Kind.forIn` for this case.
3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).
The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`,
`Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.
For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`,
**and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and
`σ` is the type of the tuple of reassigned variables.
The type `DoResult α β σ` is usedf for code blocks that exit with
`Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values.
We don't use `DoResult α β σ` for all cases because:
a) The elaborator would not be able to infer all type parameters without extra annotations. For example,
if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`.
b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),
but we don't want to consider "unreachable" cases.
We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.
When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,
and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.
- `a`: `Kind.regular`, type `m (α × σ)`
- `r`: `Kind.regular`, type `m (α × σ)`
Note that the code that pattern matches on the result will behave differently in this case.
It produces `return a` for this case, and `pure a` for the previous one.
- `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)`
- `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)`
- `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
- `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
Again the code that pattern matches on the result will behave differently in this case and
the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for
this case, and `pure a` for the previous case.
- `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)`
Here is the recipe for adding new combinators with nested `do`s.
Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α`
1- Convert `doSeq` into `codeBlock : CodeBlock`
2- Create term `term` using `mkNestedTerm code m uvars a r bc` where
`code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,
`m` is a `Syntax` representing the Monad, and
`a` is true if `code` contains `Code.action _`,
`r` is true if `code` contains `Code.return _ _`,
`bc` is true if `code` contains `Code.break _` or `Code.continue _`.
Remark: for combinators such as `repeat` that take a single `doSeq`, all
arguments, but `m`, are extracted from `codeBlock`.
3- Create the term `repeat $term`
4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`
-/
/--
Helper method for annotating `term` with the raw syntax `ref`.
We use this method to implement finer-grained term infos for `do`-blocks.
We use `withRef term` to make sure the synthetic position for the `with_annotate_term` is equal
to the one for `term`. This is important for producing error messages when there is a type mismatch.
Consider the following example:
```
opaque f : IO Nat
def g : IO String := do
f
```
There is at type mismatch at `f`, but it is detected when elaborating the expanded term
containing the `with_annotate_term .. f`. The current `getRef` when this `annotate` is invoked
is not necessarily `f`. Actually, it is the whole `do`-block. By using `withRef` we ensure
the synthetic position for the `with_annotate_term ..` is equal to `term`.
Recall that synthetic positions are used when generating error messages.
-/
def annotate [Monad m] [MonadRef m] [MonadQuotation m] (ref : Syntax) (term : Syntax) : m Syntax :=
withRef term <| `(with_annotate_term $ref $term)
namespace ToTerm
inductive Kind where
| regular
| forIn
| forInWithReturn
| nestedBC
| nestedPR
| nestedSBC
| nestedPRBC
instance : Inhabited Kind := ⟨Kind.regular⟩
def Kind.isRegular : Kind → Bool
| .regular => true
| _ => false
structure Context where
/-- Syntax to reference the monad associated with the do notation. -/
m : Syntax
/-- Syntax to reference the result of the monadic computation performed by the do notation. -/
returnType : Syntax
uvars : Array Var
kind : Kind
abbrev M := ReaderT Context MacroM
def mkUVarTuple : M Syntax := do
let ctx ← read
mkTuple ctx.uvars
def returnToTerm (val : Syntax) : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| .regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))
| .forIn => ``(Pure.pure (ForInStep.done $u))
| .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))
| .nestedBC => unreachable!
| .nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u))
| .nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u))
| .nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u))
def continueToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| .regular => unreachable!
| .forIn => ``(Pure.pure (ForInStep.yield $u))
| .forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))
| .nestedBC => ``(Pure.pure (DoResultBC.«continue» $u))
| .nestedPR => unreachable!
| .nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u))
| .nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u))
def breakToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| .regular => unreachable!
| .forIn => ``(Pure.pure (ForInStep.done $u))
| .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))
| .nestedBC => ``(Pure.pure (DoResultBC.«break» $u))
| .nestedPR => unreachable!
| .nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u))
| .nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u))
def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| .regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))
| .forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))
| .forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))
| .nestedBC => unreachable!
| .nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u)))
| .nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u)))
| .nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u)))
def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
if action.getKind == ``Parser.Term.doDbgTrace then
let msg := action[1]
`(dbg_trace $msg; $k)
else if action.getKind == ``Parser.Term.doAssert then
let cond := action[1]
`(assert! $cond; $k)
else
let action ← withRef action ``(($action : $((←read).m) PUnit))
``(Bind.bind $action (fun (_ : PUnit) => $k))
def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do
let kind := decl.getKind
if kind == ``Parser.Term.doLet then
let letDecl := decl[2]
`(let $letDecl:letDecl; $k)
else if kind == ``Parser.Term.doLetRec then
let letRecToken := decl[0]
let letRecDecls := decl[1]
return mkNode ``Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]
else if kind == ``Parser.Term.doLetArrow then
let arg := decl[2]
if arg.getKind == ``Parser.Term.doIdDecl then
let id := arg[0]
let type := expandOptType id arg[1]
let doElem := arg[3]
-- `doElem` must be a `doExpr action`. See `doLetArrowToCode`
match isDoExpr? doElem with
| some action =>
let action ← withRef action `(($action : $((← read).m) $type))
``(Bind.bind $action (fun ($id:ident : $type) => $k))
| none => Macro.throwErrorAt decl "unexpected kind of `do` declaration"
else
Macro.throwErrorAt decl "unexpected kind of `do` declaration"
else if kind == ``Parser.Term.doHave then
-- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser`
let args := decl.getArgs
let args := args ++ #[mkNullNode /- optional ';' -/, k]
return mkNode `Lean.Parser.Term.«have» args
else
Macro.throwErrorAt decl "unexpected kind of `do` declaration"
def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do
match reassign with
| `(doElem| $x:ident := $rhs) => `(let $x:ident := ensure_type_of% $x $(quote "invalid reassignment, value") $rhs; $k)
| `(doElem| $e:term := $rhs) => `(let $e:term := ensure_type_of% $e $(quote "invalid reassignment, value") $rhs; $k)
| _ =>
-- Note that `doReassignArrow` is expanded by `doReassignArrowToCode
Macro.throwErrorAt reassign "unexpected kind of `do` reassignment"
def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do
if optIdent.isNone then
``(if $cond then $thenBranch else $elseBranch)
else
let h := optIdent[0]
``(if $h:ident : $cond then $thenBranch else $elseBranch)
def mkJoinPoint (j : Name) (ps : Array (Syntax × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do
let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $id) else `(_)
let ps := ps.map (·.1)
/-
We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.
By elaborating `$k` first, we "learn" more about `$body`'s type.
For example, consider the following example `do` expression
```
def f (x : Nat) : IO Unit := do
if x > 0 then
IO.println "x is not zero" -- Error is here
IO.mkRef true
```
it is expanded into
```
def f (x : Nat) : IO Unit := do
let jp (u : Unit) : IO _ :=
IO.mkRef true;
if x > 0 then
IO.println "not zero"
jp ()
else
jp ()
```
If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`.
Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`.
Then, we get the expected type mismatch error at `IO.mkRef true`. -/
`(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k)
def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=
Syntax.mkApp (mkIdentFrom ref j) args
partial def toTerm (c : Code) : M Syntax := do
let term ← go c
if let some ref := c.getRef? then
annotate ref term
else
return term
where
go (c : Code) : M Syntax := do
match c with
| .return ref val => withRef ref <| returnToTerm val
| .continue ref => withRef ref continueToTerm
| .break ref => withRef ref breakToTerm
| .action e => actionTerminalToTerm e
| .joinpoint j ps b k => mkJoinPoint j ps (← toTerm b) (← toTerm k)
| .jmp ref j args => return mkJmp ref j args
| .decl _ stx k => declToTerm stx (← toTerm k)
| .reassign _ stx k => reassignToTerm stx (← toTerm k)
| .seq stx k => seqToTerm stx (← toTerm k)
| .ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e)
| .match ref genParam discrs optMotive alts =>
let mut termAlts := #[]
for alt in alts do
let rhs ← toTerm alt.rhs
let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", mkNullNode #[alt.patterns], mkAtomFrom alt.ref "=>", rhs]
termAlts := termAlts.push termAlt
let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]
return mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, optMotive, discrs, mkAtomFrom ref "with", termMatchAlts]
def run (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var := #[]) (kind := Kind.regular) : MacroM Syntax :=
toTerm code { m, returnType, kind, uvars }
/-- Given
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
generate Kind. See comment at the beginning of the `ToTerm` namespace. -/
def mkNestedKind (a r bc : Bool) : Kind :=
match a, r, bc with
| true, false, false => .regular
| false, true, false => .regular
| false, false, true => .nestedBC
| true, true, false => .nestedPR
| true, false, true => .nestedSBC
| false, true, true => .nestedSBC
| true, true, true => .nestedPRBC
| false, false, false => unreachable!
def mkNestedTerm (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM Syntax := do
ToTerm.run code m returnType uvars (mkNestedKind a r bc)
/-- Given a term `term` produced by `ToTerm.run`, pattern match on its result.
See comment at the beginning of the `ToTerm` namespace.
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
The result is a sequence of `doElem` -/
def matchNestedTermResult (term : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM (List Syntax) := do
let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)
let u ← mkTuple uvars
match a, r, bc with
| true, false, false =>
if uvars.isEmpty then
return toDoElems (← `(do $term:term))
else
return toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1))
| false, true, false =>
if uvars.isEmpty then
return toDoElems (← `(do let r ← $term:term; return r))
else
return toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1))
| false, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| .break u => $u:term := u; break
| .continue u => $u:term := u; continue)
| true, true, false => toDoElems <$>
`(do let r ← $term:term;
match r with
| .pure a u => $u:term := u; pure a
| .return b u => $u:term := u; return b)
| true, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| .pureReturn a u => $u:term := u; pure a
| .break u => $u:term := u; break
| .continue u => $u:term := u; continue)
| false, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| .pureReturn a u => $u:term := u; return a
| .break u => $u:term := u; break
| .continue u => $u:term := u; continue)
| true, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| .pure a u => $u:term := u; pure a
| .return a u => $u:term := u; return a
| .break u => $u:term := u; break
| .continue u => $u:term := u; continue)
| false, false, false => unreachable!
end ToTerm
def isMutableLet (doElem : Syntax) : Bool :=
let kind := doElem.getKind
(kind == ``doLetArrow || kind == ``doLet || kind == ``doLetElse)
&&
!doElem[1].isNone
namespace ToCodeBlock
structure Context where
ref : Syntax
/-- Syntax representing the monad associated with the do notation. -/
m : Syntax
/-- Syntax to reference the result of the monadic computation performed by the do notation. -/
returnType : Syntax
mutableVars : VarSet := {}
insideFor : Bool := false
abbrev M := ReaderT Context TermElabM
def withNewMutableVars {α} (newVars : Array Var) (mutable : Bool) (x : M α) : M α :=
withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x
def checkReassignable (xs : Array Var) : M Unit := do
let throwInvalidReassignment (x : Name) : M Unit :=
throwError "`{x.simpMacroScopes}` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intent to mutate but define `{x.simpMacroScopes}`, consider using `let {x.simpMacroScopes}` instead"
let ctx ← read
for x in xs do
unless ctx.mutableVars.contains x.getId do
throwInvalidReassignment x.getId
def checkNotShadowingMutable (xs : Array Var) : M Unit := do
let throwInvalidShadowing (x : Name) : M Unit :=
throwError "mutable variable `{x.simpMacroScopes}` cannot be shadowed"
let ctx ← read
for x in xs do
if ctx.mutableVars.contains x.getId then
withRef x <| throwInvalidShadowing x.getId
def withFor {α} (x : M α) : M α :=
withReader (fun ctx => { ctx with insideFor := true }) x
structure ToForInTermResult where
uvars : Array Var
term : Syntax
def mkForInBody (_ : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do
let ctx ← read
let uvars := forInBody.uvars
let uvars := varSetToArray uvars
let term ← liftMacroM <| ToTerm.run forInBody.code ctx.m ctx.returnType uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)
return ⟨uvars, term⟩
def ensureInsideFor : M Unit :=
unless (← read).insideFor do
throwError "invalid `do` element, it must be inside `for`"
def ensureEOS (doElems : List Syntax) : M Unit :=
unless doElems.isEmpty do
throwError "must be last element in a `do` sequence"
variable (baseId : Name) in
private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax
| stx@(Syntax.node i k args) =>
if k == choiceKind then do
-- choice node: check that lifts are consistent
let alts ← stx.getArgs.mapM (expandLiftMethodAux inQuot inBinder · |>.run [])
let (_, lifts) := alts[0]!
unless alts.all (·.2 == lifts) do
throwErrorAt stx "cannot lift `(<- ...)` over inconsistent syntax variants, consider lifting out the binding manually"
modify (· ++ lifts)
return .node i k (alts.map (·.1))
else if liftMethodDelimiter k then
return stx
else if k == ``Parser.Term.liftMethod && !inQuot then withFreshMacroScope do
if inBinder then
throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`"
let term := args[1]!
let term ← expandLiftMethodAux inQuot inBinder term
-- keep name deterministic across choice branches
let id ← mkIdentFromRef (.num baseId (← get).length)
let auxDoElem : Syntax ← `(doElem| let $id:ident ← $term:term)
modify fun s => s ++ [auxDoElem]
return id
else do
let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot
let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx)
let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)
return Syntax.node i k args
| stx => return stx
def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do
if !hasLiftMethod doElem then
return ([], doElem)
else
let baseId ← withFreshMacroScope (MonadQuotation.addMacroScope `__do_lift)
let (doElem, doElemsNew) ← (expandLiftMethodAux baseId false false doElem).run []
return (doElemsNew, doElem)
def checkLetArrowRHS (doElem : Syntax) : M Unit := do
let kind := doElem.getKind
if kind == ``Parser.Term.doLetArrow ||
kind == ``Parser.Term.doLet ||
kind == ``Parser.Term.doLetRec ||
kind == ``Parser.Term.doHave ||
kind == ``Parser.Term.doReassign ||
kind == ``Parser.Term.doReassignArrow then
throwErrorAt doElem "invalid kind of value `{kind}` in an assignment"
/-- Generate `CodeBlock` for `doReturn` which is of the form
```
"return " >> optional termParser
```
`doElems` is only used for sanity checking. -/
def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do
ensureEOS doElems
let argOpt := doReturn[1]
let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]
return mkReturn (← getRef) arg
structure Catch where
x : Syntax
optType : Syntax
codeBlock : CodeBlock
def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : VarSet :=
let ws := tryCode.uvars
let ws := catches.foldl (init := ws) fun ws alt => union alt.codeBlock.uvars ws
let ws := match finallyCode? with
| none => ws
| some c => union c.uvars ws
ws
def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool :=
p tryCode.code ||
catches.any (fun «catch» => p «catch».codeBlock.code) ||
match finallyCode? with
| none => false
| some finallyCode => p finallyCode.code
mutual
/-- "Concatenate" `c` with `doSeqToCode doElems` -/
partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=
match doElems with
| [] => pure c
| nextDoElem :: _ => do
let k ← doSeqToCode doElems
let ref := nextDoElem
concat c ref none k
/-- Generate `CodeBlock` for `doLetArrow; doElems`
`doLetArrow` is of the form
```
"let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
```
where
```
def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser
def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doSeq)
```
-/
partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let decl := doLetArrow[2]
if decl.getKind == ``Parser.Term.doIdDecl then
let y := decl[0]
checkNotShadowingMutable #[y]
let doElem := decl[3]
let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)
match isDoExpr? doElem with
| some _ => return mkVarDeclCore #[y] doLetArrow k
| none =>
checkLetArrowRHS doElem
let c ← doSeqToCode [doElem]
match doElems with
| [] => pure c
| kRef::_ => concat c kRef y k
else if decl.getKind == ``Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ← if isMutableLet doLetArrow then
`(do let%$doLetArrow __discr ← $doElem; let%$doLetArrow mut $pattern:term := __discr)
else
`(do let%$doLetArrow __discr ← $doElem; let%$doLetArrow $pattern:term := __discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
let contSeq ← if isMutableLet doLetArrow then
let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var)
pure (vars ++ doElems.toArray)
else
pure doElems.toArray
let contSeq := mkDoSeq contSeq
let elseSeq := optElse[1]
let auxDo ← `(do let%$doLetArrow __discr ← $doElem; match%$doLetArrow __discr with | $pattern:term => $contSeq | _ => $elseSeq)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
throwError "unexpected kind of `do` declaration"
partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do
-- "let " >> optional "mut " >> termParser >> " := " >> termParser >> checkColGt >> " | " >> doSeq
let pattern := doLetElse[2]
let val := doLetElse[4]
let elseSeq := doLetElse[6]
let contSeq ← if isMutableLet doLetElse then
let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var)
pure (vars ++ doElems.toArray)
else
pure doElems.toArray
let contSeq := mkDoSeq contSeq
let auxDo ← `(do let __discr := $val; match __discr with | $pattern:term => $contSeq | _ => $elseSeq)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
/-- Generate `CodeBlock` for `doReassignArrow; doElems`
`doReassignArrow` is of the form
```
(doIdDecl <|> doPatDecl)
```
-/
partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let decl := doReassignArrow[0]
if decl.getKind == ``Parser.Term.doIdDecl then
let doElem := decl[3]
let y := decl[0]
let auxDo ← `(do let r ← $doElem; $y:ident := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else if decl.getKind == ``Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ← `(do let __discr ← $doElem; $pattern:term := __discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported"
else
throwError "unexpected kind of `do` reassignment"
/-- Generate `CodeBlock` for `doIf; doElems`
`doIf` is of the form
```
"if " >> optIdent >> termParser >> " then " >> doSeq
>> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq))
>> optional (" else " >> doSeq)
``` -/
partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do
let view := mkDoIfView doIf
let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch)
let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch)
let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch
concatWith ite doElems
/-- Generate `CodeBlock` for `doUnless; doElems`
`doUnless` is of the form
```
"unless " >> termParser >> "do " >> doSeq
``` -/
partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do
let cond := doUnless[1]
let doSeq := doUnless[3]
let body ← doSeqToCode (getDoSeqElems doSeq)
let unlessCode ← liftMacroM <| mkUnless cond body
concatWith unlessCode doElems
/-- Generate `CodeBlock` for `doFor; doElems`
`doFor` is of the form
```
def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser
def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq
```
-/
partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do
let doForDecls := doFor[1].getSepArgs
if doForDecls.size > 1 then
/-
Expand
```
for x in xs, y in ys do
body
```
into
```
let s := toStream ys
for x in xs do
match Stream.next? s with
| none => break
| some (y, s') =>
s := s'
body
```
-/
-- Extract second element
let doForDecl := doForDecls[1]!
unless doForDecl[0].isNone do
throwErrorAt doForDecl[0] "the proof annotation here has not been implemented yet"
let y := doForDecl[1]
let ys := doForDecl[3]
let doForDecls := doForDecls.eraseIdx 1
let body := doFor[3]
withFreshMacroScope do
/- Recall that `@` (explicit) disables `coeAtOutParam`.
We used `@` at `Stream` functions to make sure `resultIsOutParamSupport` is not used. -/
let toStreamApp ← withRef ys `(@toStream _ _ _ $ys)
let auxDo ←
`(do let mut s := $toStreamApp:term
for $doForDecls:doForDecl,* do
match @Stream.next? _ _ _ s with
| none => break
| some ($y, s') =>
s := s'
do $body)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else withRef doFor do
let h? := if doForDecls[0]![0].isNone then none else some doForDecls[0]![0][0]
let x := doForDecls[0]![1]
withRef x <| checkNotShadowingMutable (← getPatternVarsEx x)
let xs := doForDecls[0]![3]
let forElems := getDoSeqElems doFor[3]
let forInBodyCodeBlock ← withFor (doSeqToCode forElems)
let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock
let ctx ← read
-- semantic no-op that replaces the `uvars`' position information (which all point inside the loop)
-- with that of the respective mutable declarations outside the loop, which allows the language
-- server to identify them as conceptually identical variables
let uvars := uvars.map fun v => ctx.mutableVars.findD v.getId v
let uvarsTuple ← liftMacroM do mkTuple uvars
if hasReturn forInBodyCodeBlock.code then
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let optType ← `(Option $((← read).returnType))
let forInTerm ← if let some h := h? then
annotate doFor
(← `(for_in'% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x $h (r : MProd $optType _) => let r := r.2; $forInBody))
else
annotate doFor
(← `(for_in% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x (r : MProd $optType _) => let r := r.2; $forInBody))
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r.2;
match r.1 with
| none => Pure.pure (ensure_expected_type% "type mismatch, `for`" PUnit.unit)
| some a => return ensure_expected_type% "type mismatch, `for`" a)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← if let some h := h? then
annotate doFor (← `(for_in'% $(xs) $uvarsTuple fun $x $h r => $forInBody))
else
annotate doFor (← `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody))
if doElems.isEmpty then
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r;
Pure.pure (ensure_expected_type% "type mismatch, `for`" PUnit.unit))
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
/-- Generate `CodeBlock` for `doMatch; doElems` -/
partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doMatch
let genParam := doMatch[1]
let optMotive := doMatch[2]
let discrs := doMatch[3]
let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`
let matchAlts ← matchAlts.foldlM (init := #[]) fun result matchAlt => return result ++ (← liftMacroM <| expandMatchAlt matchAlt)
let alts ← matchAlts.mapM fun matchAlt => do
let patterns := matchAlt[1][0]
let vars ← getPatternsVarsEx patterns.getSepArgs
withRef patterns <| checkNotShadowingMutable vars
let rhs := matchAlt[3]
let rhs ← doSeqToCode (getDoSeqElems rhs)
pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }
let matchCode ← mkMatch ref genParam discrs optMotive alts
concatWith matchCode doElems
/--
Generate `CodeBlock` for `doTry; doElems`
```
def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally
def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq
def doCatchMatch := leading_parser "catch " >> doMatchAlts
def doFinally := leading_parser "finally " >> doSeq
```
-/
partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do
let tryCode ← doSeqToCode (getDoSeqElems doTry[1])
let optFinally := doTry[3]
let catches ← doTry[2].getArgs.mapM fun catchStx : Syntax => do
if catchStx.getKind == ``Parser.Term.doCatch then
let x := catchStx[1]
if x.isIdent then
withRef x <| checkNotShadowingMutable #[x]
let optType := catchStx[2]
let c ← doSeqToCode (getDoSeqElems catchStx[4])
return { x := x, optType := optType, codeBlock := c : Catch }
else if catchStx.getKind == ``Parser.Term.doCatchMatch then
let matchAlts := catchStx[1]
let x ← `(ex)
let auxDo ← `(do match ex with $matchAlts)
let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo))
return { x := x, codeBlock := c, optType := mkNullNode : Catch }
else
throwError "unexpected kind of `catch`"
let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])
if catches.isEmpty && finallyCode?.isNone then
throwError "invalid `try`, it must have a `catch` or `finally`"
let ctx ← read
let ws := getTryCatchUpdatedVars tryCode catches finallyCode?
let uvars := varSetToArray ws
let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction
let r := tryCatchPred tryCode catches finallyCode? hasReturn
let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue
let toTerm (codeBlock : CodeBlock) : M Syntax := do
let codeBlock ← liftM $ extendUpdatedVars codeBlock ws
liftMacroM <| ToTerm.mkNestedTerm codeBlock.code ctx.m ctx.returnType uvars a r bc
let term ← toTerm tryCode
let term ← catches.foldlM (init := term) fun term «catch» => do
let catchTerm ← toTerm «catch».codeBlock
if catch.optType.isNone then
annotate doTry (← ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)))
else
let type := «catch».optType[1]
annotate doTry (← ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm)))
let term ← match finallyCode? with
| none => pure term
| some finallyCode => withRef optFinally do
unless finallyCode.uvars.isEmpty do
throwError "`finally` currently does not support reassignments"
if hasBreakContinueReturn finallyCode.code then
throwError "`finally` currently does `return`, `break`, nor `continue`"
let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m ctx.returnType {} ToTerm.Kind.regular
annotate doTry (← ``(tryFinally $term $finallyTerm))
let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc
doSeqToCode (doElemsNew ++ doElems)
partial def doSeqToCode : List Syntax → M CodeBlock
| [] => do liftMacroM mkPureUnitAction
| doElem::doElems => withIncRecDepth <| withRef doElem do
checkMaxHeartbeats "`do`-expander"
match (← liftMacroM <| expandMacro? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
match (← liftMacroM <| expandDoIf? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
let (liftedDoElems, doElem) ← expandLiftMethod doElem
if !liftedDoElems.isEmpty then
doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)
else
let ref := doElem
let k := doElem.getKind
if k == ``Parser.Term.doLet then
let vars ← getDoLetVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)
else if k == ``Parser.Term.doHave then
let vars ← getDoHaveVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> (doSeqToCode doElems)
else if k == ``Parser.Term.doLetRec then
let vars ← getDoLetRecVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> (doSeqToCode doElems)
else if k == ``Parser.Term.doReassign then
let vars ← getDoReassignVars doElem
checkReassignable vars
let k ← doSeqToCode doElems
mkReassignCore vars doElem k
else if k == ``Parser.Term.doLetArrow then
doLetArrowToCode doElem doElems
else if k == ``Parser.Term.doLetElse then
doLetElseToCode doElem doElems
else if k == ``Parser.Term.doReassignArrow then
doReassignArrowToCode doElem doElems
else if k == ``Parser.Term.doIf then
doIfToCode doElem doElems
else if k == ``Parser.Term.doUnless then
doUnlessToCode doElem doElems
else if k == ``Parser.Term.doFor then withFreshMacroScope do
doForToCode doElem doElems
else if k == ``Parser.Term.doMatch then
doMatchToCode doElem doElems
else if k == ``Parser.Term.doTry then
doTryToCode doElem doElems
else if k == ``Parser.Term.doBreak then
ensureInsideFor
ensureEOS doElems
return mkBreak ref
else if k == ``Parser.Term.doContinue then
ensureInsideFor
ensureEOS doElems
return mkContinue ref
else if k == ``Parser.Term.doReturn then
doReturnToCode doElem doElems
else if k == ``Parser.Term.doDbgTrace then
return mkSeq doElem (← doSeqToCode doElems)
else if k == ``Parser.Term.doAssert then
return mkSeq doElem (← doSeqToCode doElems)
else if k == ``Parser.Term.doNested then
let nestedDoSeq := doElem[1]
doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)
else if k == ``Parser.Term.doExpr then
let term := doElem[0]
if doElems.isEmpty then
return mkTerminalAction term
else
return mkSeq term (← doSeqToCode doElems)
else
throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}"
end
def run (doStx : Syntax) (m : Syntax) (returnType : Syntax) : TermElabM CodeBlock :=
(doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m, returnType }
end ToCodeBlock
@[builtin_term_elab «do»] def elabDo : TermElab := fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?
let bindInfo ← extractBind expectedType?
let m ← Term.exprToSyntax bindInfo.m
let returnType ← Term.exprToSyntax bindInfo.returnType
let codeBlock ← ToCodeBlock.run stx m returnType
let stxNew ← liftMacroM <| ToTerm.run codeBlock.code m returnType
trace[Elab.do] stxNew
withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType
end Do
builtin_initialize registerTraceClass `Elab.do
private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do
let stx := stx.setKind newKind
withRef stx `(do $stx:doElem)
@[builtin_macro Lean.Parser.Term.termFor]
def expandTermFor : Macro := toDoElem ``Parser.Term.doFor
@[builtin_macro Lean.Parser.Term.termTry]
def expandTermTry : Macro := toDoElem ``Parser.Term.doTry
@[builtin_macro Lean.Parser.Term.termUnless]
def expandTermUnless : Macro := toDoElem ``Parser.Term.doUnless
@[builtin_macro Lean.Parser.Term.termReturn]
def expandTermReturn : Macro := toDoElem ``Parser.Term.doReturn
end Lean.Elab.Term
|
a47758c68986e0f01b313864e0ac0054392f1bf6 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/name_resolution_at_tactic_execution_time.lean | 09f1d26ad12f675779c24e736fc8eb6e8023de1b | [
"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 | 250 | lean | structure Foo : Type := (foo : ℕ)
open Foo
set_option pp.all true
example (P : Prop) : P → P
| foo := by exact foo
example (P : Prop) : P → P
| bla :=
begin
rename bla foo,
exact foo
end
example (f : Foo) : nat :=
by exact foo f
|
d099423b2df931077a67d6129417a0e7c98031c8 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Util/Recognizers.lean | cd9bd45a2affde026ec3934c321b478a6b24dcac | [
"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 | 1,879 | 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
-/
prelude
import Init.Lean.Expr
namespace Lean
namespace Expr
@[inline] def app1? (e : Expr) (fName : Name) : Option Expr :=
if e.isAppOfArity fName 1 then
some $ e.appArg!
else
none
@[inline] def app2? (e : Expr) (fName : Name) : Option (Expr × Expr) :=
if e.isAppOfArity fName 2 then
some $ (e.appFn!.appArg!, e.appArg!)
else
none
@[inline] def app3? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr) :=
if e.isAppOfArity fName 3 then
some $ (e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg!)
else
none
@[inline] def app4? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr × Expr) :=
if e.isAppOfArity fName 4 then
some $ (e.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg!)
else
none
@[inline] def eq? (p : Expr) : Option (Expr × Expr × Expr) :=
p.app3? `Eq
@[inline] def iff? (p : Expr) : Option (Expr × Expr) :=
p.app2? `Iff
@[inline] def heq? (p : Expr) : Option (Expr × Expr × Expr × Expr) :=
p.app4? `HEq
@[inline] def arrow? : Expr → Option (Expr × Expr)
| Expr.forallE _ α β _ => if β.hasLooseBVars then none else some (α, β)
| _ => none
partial def listLitAux : Expr → List Expr → Option (List Expr)
| e, acc =>
if e.isAppOfArity `List.nil 1 then
some acc.reverse
else if e.isAppOfArity `List.cons 3 then
listLitAux e.appArg! (e.appFn!.appArg! :: acc)
else
none
def listLit? (e : Expr) : Option (List Expr) :=
listLitAux e []
def arrayLit? (e : Expr) : Option (List Expr) :=
match e.app2? `List.toArray with
| some (_, e) => e.listLit?
| none => none
/-- Recognize `α × β` -/
def prod? (e : Expr) : Option (Expr × Expr) :=
e.app2? `Prod
end Expr
end Lean
|
559530dba2a045355792b2e2b40a5c8769c82721 | 367134ba5a65885e863bdc4507601606690974c1 | /src/set_theory/surreal.lean | 74aac995ddfd8756716629397622b39a133de1f2 | [
"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 | 15,126 | lean | /-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Scott Morrison
-/
import set_theory.pgame
/-!
# Surreal numbers
The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games.
A pregame is `numeric` if all the Left options are strictly smaller than all the Right options, and
all those options are themselves numeric. In terms of combinatorial games, the numeric games have
"frozen"; you can only make your position worse by playing, and Left is some definite "number" of
moves ahead (or behind) Right.
A surreal number is an equivalence class of numeric pregames.
In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else
besides!) but we do not yet have a complete development.
## Order properties
Surreal numbers inherit the relations `≤` and `<` from games, and these relations satisfy the axioms
of a partial order (recall that `x < y ↔ x ≤ y ∧ ¬ y ≤ x` did not hold for games).
## Algebraic operations
At this point, we have defined addition and negation (from pregames), and shown that surreals form
an additive semigroup. It would be very little work to finish showing that the surreals form an
ordered commutative group.
We define the operations of multiplication and inverse on surreals, but do not yet establish any of
the necessary properties to show the surreals form an ordered field.
## Embeddings
It would be nice projects to define the group homomorphism `surreal → game`, and also `ℤ → surreal`,
and then the homomorphic inclusion of the dyadic rationals into surreals, and finally
via dyadic Dedekind cuts the homomorphic inclusion of the reals into the surreals.
One can also map all the ordinals into the surreals!
## References
* [Conway, *On numbers and games*][conway2001]
-/
universes u
namespace pgame
/-! Multiplicative operations can be defined at the level of pre-games, but as
they are only useful on surreal numbers, we define them here. -/
/-- The product of `x = {xL | xR}` and `y = {yL | yR}` is
`{xL*y + x*yL - xL*yL, xR*y + x*yR - xR*yR | xL*y + x*yR - xL*yR, x*yL + xR*y - xR*yL }`. -/
def mul (x y : pgame) : pgame :=
begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
have y := mk yl yr yL yR,
refine ⟨xl × yl ⊕ xr × yr, xl × yr ⊕ xr × yl, _, _⟩; rintro (⟨i, j⟩ | ⟨i, j⟩),
{ exact IHxl i y + IHyl j - IHxl i (yL j) },
{ exact IHxr i y + IHyr j - IHxr i (yR j) },
{ exact IHxl i y + IHyr j - IHxl i (yR j) },
{ exact IHxr i y + IHyl j - IHxr i (yL j) }
end
instance : has_mul pgame := ⟨mul⟩
/-- Because the two halves of the definition of `inv` produce more elements
of each side, we have to define the two families inductively.
This is the indexing set for the function, and `inv_val` is the function part. -/
inductive inv_ty (l r : Type u) : bool → Type u
| zero : inv_ty ff
| left₁ : r → inv_ty ff → inv_ty ff
| left₂ : l → inv_ty tt → inv_ty ff
| right₁ : l → inv_ty ff → inv_ty tt
| right₂ : r → inv_ty tt → inv_ty tt
/-- Because the two halves of the definition of `inv` produce more elements
of each side, we have to define the two families inductively.
This is the function part, defined by recursion on `inv_ty`. -/
def inv_val {l r} (L : l → pgame) (R : r → pgame)
(IHl : l → pgame) (IHr : r → pgame) : ∀ {b}, inv_ty l r b → pgame
| _ inv_ty.zero := 0
| _ (inv_ty.left₁ i j) := (1 + (R i - mk l r L R) * inv_val j) * IHr i
| _ (inv_ty.left₂ i j) := (1 + (L i - mk l r L R) * inv_val j) * IHl i
| _ (inv_ty.right₁ i j) := (1 + (L i - mk l r L R) * inv_val j) * IHl i
| _ (inv_ty.right₂ i j) := (1 + (R i - mk l r L R) * inv_val j) * IHr i
/-- The inverse of a positive surreal number `x = {L | R}` is
given by `x⁻¹ = {0,
(1 + (R - x) * x⁻¹L) * R, (1 + (L - x) * x⁻¹R) * L |
(1 + (L - x) * x⁻¹L) * L, (1 + (R - x) * x⁻¹R) * R}`.
Because the two halves `x⁻¹L, x⁻¹R` of `x⁻¹` are used in their own
definition, the sets and elements are inductively generated. -/
def inv' : pgame → pgame
| ⟨l, r, L, R⟩ :=
let l' := {i // 0 < L i},
L' : l' → pgame := λ i, L i.1,
IHl' : l' → pgame := λ i, inv' (L i.1),
IHr := λ i, inv' (R i) in
⟨inv_ty l' r ff, inv_ty l' r tt,
inv_val L' R IHl' IHr, inv_val L' R IHl' IHr⟩
/-- The inverse of a surreal number in terms of the inverse on positive surreals. -/
noncomputable def inv (x : pgame) : pgame :=
by classical; exact
if x = 0 then 0 else if 0 < x then inv' x else inv' (-x)
noncomputable instance : has_inv pgame := ⟨inv⟩
noncomputable instance : has_div pgame := ⟨λ x y, x * y⁻¹⟩
/-- A pre-game is numeric if everything in the L set is less than everything in the R set,
and all the elements of L and R are also numeric. -/
def numeric : pgame → Prop
| ⟨l, r, L, R⟩ :=
(∀ i j, L i < R j) ∧ (∀ i, numeric (L i)) ∧ (∀ i, numeric (R i))
lemma numeric.move_left {x : pgame} (o : numeric x) (i : x.left_moves) :
numeric (x.move_left i) :=
begin
cases x with xl xr xL xR,
exact o.2.1 i,
end
lemma numeric.move_right {x : pgame} (o : numeric x) (j : x.right_moves) :
numeric (x.move_right j) :=
begin
cases x with xl xr xL xR,
exact o.2.2 j,
end
@[elab_as_eliminator]
theorem numeric_rec {C : pgame → Prop}
(H : ∀ l r (L : l → pgame) (R : r → pgame),
(∀ i j, L i < R j) → (∀ i, numeric (L i)) → (∀ i, numeric (R i)) →
(∀ i, C (L i)) → (∀ i, C (R i)) → C ⟨l, r, L, R⟩) :
∀ x, numeric x → C x
| ⟨l, r, L, R⟩ ⟨h, hl, hr⟩ :=
H _ _ _ _ h hl hr (λ i, numeric_rec _ (hl i)) (λ i, numeric_rec _ (hr i))
theorem lt_asymm {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y → ¬ y < x :=
begin
refine numeric_rec (λ xl xr xL xR hx oxl oxr IHxl IHxr, _) x ox y oy,
refine numeric_rec (λ yl yr yL yR hy oyl oyr IHyl IHyr, _),
rw [mk_lt_mk, mk_lt_mk], rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩),
{ exact IHxl _ _ (oyl _) (lt_of_le_mk h₁) (lt_of_le_mk h₂) },
{ exact not_lt.2 (le_trans h₂ h₁) (hy _ _) },
{ exact not_lt.2 (le_trans h₁ h₂) (hx _ _) },
{ exact IHxr _ _ (oyr _) (lt_of_mk_le h₁) (lt_of_mk_le h₂) },
end
theorem le_of_lt {x y : pgame} (ox : numeric x) (oy : numeric y) (h : x < y) : x ≤ y :=
not_lt.1 (lt_asymm ox oy h)
/-- On numeric pre-games, `<` and `≤` satisfy the axioms of a partial order (even though they
don't on all pre-games). -/
theorem lt_iff_le_not_le {x y : pgame} (ox : numeric x) (oy : numeric y) :
x < y ↔ x ≤ y ∧ ¬ y ≤ x :=
⟨λ h, ⟨le_of_lt ox oy h, not_le.2 h⟩, λ h, not_le.1 h.2⟩
theorem numeric_zero : numeric 0 :=
⟨by rintros ⟨⟩ ⟨⟩, ⟨by rintros ⟨⟩, by rintros ⟨⟩⟩⟩
theorem numeric_one : numeric 1 :=
⟨by rintros ⟨⟩ ⟨⟩, ⟨λ x, numeric_zero, by rintros ⟨⟩⟩⟩
theorem numeric_neg : Π {x : pgame} (o : numeric x), numeric (-x)
| ⟨l, r, L, R⟩ o :=
⟨λ j i, lt_iff_neg_gt.1 (o.1 i j),
⟨λ j, numeric_neg (o.2.2 j), λ i, numeric_neg (o.2.1 i)⟩⟩
theorem numeric.move_left_lt {x : pgame.{u}} (o : numeric x) (i : x.left_moves) :
x.move_left i < x :=
begin
rw lt_def_le,
left,
use i,
end
theorem numeric.move_left_le {x : pgame} (o : numeric x) (i : x.left_moves) :
x.move_left i ≤ x :=
le_of_lt (o.move_left i) o (o.move_left_lt i)
theorem numeric.lt_move_right {x : pgame} (o : numeric x) (j : x.right_moves) :
x < x.move_right j :=
begin
rw lt_def_le,
right,
use j,
end
theorem numeric.le_move_right {x : pgame} (o : numeric x) (j : x.right_moves) :
x ≤ x.move_right j :=
le_of_lt o (o.move_right j) (o.lt_move_right j)
theorem add_lt_add
{w x y z : pgame.{u}} (ow : numeric w) (ox : numeric x) (oy : numeric y) (oz : numeric z)
(hwx : w < x) (hyz : y < z) : w + y < x + z :=
begin
rw lt_def_le at *,
rcases hwx with ⟨ix, hix⟩|⟨jw, hjw⟩;
rcases hyz with ⟨iz, hiz⟩|⟨jy, hjy⟩,
{ left,
use (left_moves_add x z).symm (sum.inl ix),
simp only [add_move_left_inl],
calc w + y ≤ move_left x ix + y : add_le_add_right hix
... ≤ move_left x ix + move_left z iz : add_le_add_left hiz
... ≤ move_left x ix + z : add_le_add_left (oz.move_left_le iz) },
{ left,
use (left_moves_add x z).symm (sum.inl ix),
simp only [add_move_left_inl],
calc w + y ≤ move_left x ix + y : add_le_add_right hix
... ≤ move_left x ix + move_right y jy : add_le_add_left (oy.le_move_right jy)
... ≤ move_left x ix + z : add_le_add_left hjy },
{ right,
use (right_moves_add w y).symm (sum.inl jw),
simp only [add_move_right_inl],
calc move_right w jw + y ≤ x + y : add_le_add_right hjw
... ≤ x + move_left z iz : add_le_add_left hiz
... ≤ x + z : add_le_add_left (oz.move_left_le iz), },
{ right,
use (right_moves_add w y).symm (sum.inl jw),
simp only [add_move_right_inl],
calc move_right w jw + y ≤ x + y : add_le_add_right hjw
... ≤ x + move_right y jy : add_le_add_left (oy.le_move_right jy)
... ≤ x + z : add_le_add_left hjy, },
end
theorem numeric_add : Π {x y : pgame} (ox : numeric x) (oy : numeric y), numeric (x + y)
| ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ox oy :=
⟨begin
rintros (ix|iy) (jx|jy),
{ show xL ix + ⟨yl, yr, yL, yR⟩ < xR jx + ⟨yl, yr, yL, yR⟩,
exact add_lt_add_right (ox.1 ix jx), },
{ show xL ix + ⟨yl, yr, yL, yR⟩ < ⟨xl, xr, xL, xR⟩ + yR jy,
apply add_lt_add (ox.move_left ix) ox oy (oy.move_right jy),
apply ox.move_left_lt,
apply oy.lt_move_right },
{ -- show ⟨xl, xr, xL, xR⟩ + yL iy < xR jx + ⟨yl, yr, yL, yR⟩, -- fails?
apply add_lt_add ox (ox.move_right jx) (oy.move_left iy) oy,
apply ox.lt_move_right,
apply oy.move_left_lt, },
{ -- show ⟨xl, xr, xL, xR⟩ + yL iy < ⟨xl, xr, xL, xR⟩ + yR jy, -- fails?
exact @add_lt_add_left ⟨xl, xr, xL, xR⟩ _ _ (oy.1 iy jy), }
end,
begin
split,
{ rintros (ix|iy),
{ apply numeric_add (ox.move_left ix) oy, },
{ apply numeric_add ox (oy.move_left iy), }, },
{ rintros (jx|jy),
{ apply numeric_add (ox.move_right jx) oy, },
{ apply numeric_add ox (oy.move_right jy), }, },
end⟩
using_well_founded { dec_tac := pgame_wf_tac }
-- TODO prove
-- theorem numeric_nat (n : ℕ) : numeric n := sorry
-- theorem numeric_omega : numeric omega := sorry
end pgame
/-- The equivalence on numeric pre-games. -/
def surreal.equiv (x y : {x // pgame.numeric x}) : Prop := x.1.equiv y.1
local infix ` ≈ ` := surreal.equiv
instance surreal.setoid : setoid {x // pgame.numeric x} :=
⟨λ x y, x.1.equiv y.1,
λ x, pgame.equiv_refl _,
λ x y, pgame.equiv_symm,
λ x y z, pgame.equiv_trans⟩
/-- The type of surreal numbers. These are the numeric pre-games quotiented
by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient,
the order becomes a total order. -/
def surreal := quotient surreal.setoid
namespace surreal
open pgame
/-- Construct a surreal number from a numeric pre-game. -/
def mk (x : pgame) (h : x.numeric) : surreal := quotient.mk ⟨x, h⟩
instance : has_zero surreal :=
{ zero := ⟦⟨0, numeric_zero⟩⟧ }
instance : has_one surreal :=
{ one := ⟦⟨1, numeric_one⟩⟧ }
instance : inhabited surreal := ⟨0⟩
/-- Lift an equivalence-respecting function on pre-games to surreals. -/
def lift {α} (f : ∀ x, numeric x → α)
(H : ∀ {x y} (hx : numeric x) (hy : numeric y), x.equiv y → f x hx = f y hy) : surreal → α :=
quotient.lift (λ x : {x // numeric x}, f x.1 x.2) (λ x y, H x.2 y.2)
/-- Lift a binary equivalence-respecting function on pre-games to surreals. -/
def lift₂ {α} (f : ∀ x y, numeric x → numeric y → α)
(H : ∀ {x₁ y₁ x₂ y₂} (ox₁ : numeric x₁) (oy₁ : numeric y₁) (ox₂ : numeric x₂) (oy₂ : numeric y₂),
x₁.equiv x₂ → y₁.equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) : surreal → surreal → α :=
lift (λ x ox, lift (λ y oy, f x y ox oy) (λ y₁ y₂ oy₁ oy₂ h, H _ _ _ _ (equiv_refl _) h))
(λ x₁ x₂ ox₁ ox₂ h, funext $ quotient.ind $ by exact λ ⟨y, oy⟩, H _ _ _ _ h (equiv_refl _))
/-- The relation `x ≤ y` on surreals. -/
def le : surreal → surreal → Prop :=
lift₂ (λ x y _ _, x ≤ y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (le_congr hx hy))
/-- The relation `x < y` on surreals. -/
def lt : surreal → surreal → Prop :=
lift₂ (λ x y _ _, x < y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (lt_congr hx hy))
theorem not_le : ∀ {x y : surreal}, ¬ le x y ↔ lt y x :=
by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; exact not_le
instance : preorder surreal :=
{ le := le,
lt := lt,
le_refl := by rintro ⟨⟨x, ox⟩⟩; exact le_refl _,
le_trans := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩ ⟨⟨z, oz⟩⟩; exact le_trans,
lt_iff_le_not_le := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; exact lt_iff_le_not_le ox oy }
instance : partial_order surreal :=
{ le_antisymm := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩ h₁ h₂; exact quot.sound ⟨h₁, h₂⟩,
..surreal.preorder }
noncomputable instance : linear_order surreal :=
{ le_total := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; classical; exact
or_iff_not_imp_left.2 (λ h, le_of_lt oy ox (pgame.not_le.1 h)),
decidable_le := classical.dec_rel _,
..surreal.partial_order }
/-- Addition on surreals is inherited from pre-game addition:
the sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
def add : surreal → surreal → surreal :=
surreal.lift₂
(λ (x y : pgame) (ox) (oy), ⟦⟨x + y, numeric_add ox oy⟩⟧)
(λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, quot.sound (pgame.add_congr hx hy))
instance : has_add surreal := ⟨add⟩
theorem add_assoc : ∀ (x y z : surreal), (x + y) + z = x + (y + z) :=
begin
rintros ⟨x⟩ ⟨y⟩ ⟨z⟩,
apply quot.sound,
exact add_assoc_equiv,
end
instance : add_semigroup surreal :=
{ add_assoc := add_assoc,
..(by apply_instance : has_add surreal) }
-- We conclude with some ideas for further work on surreals; these would make fun projects.
-- TODO construct the remaining instances:
-- add_monoid, add_group, add_comm_semigroup, add_comm_group, ordered_add_comm_group,
-- as per the instances for `game`
-- TODO define the inclusion of groups `surreal → game`
-- TODO define the dyadic rationals, and show they map into the surreals via the formula
-- m / 2^n ↦ { (m-1) / 2^n | (m+1) / 2^n }
-- TODO show this is a group homomorphism, and injective
-- TODO map the reals into the surreals, using dyadic Dedekind cuts
-- TODO show this is a group homomorphism, and injective
-- TODO define the field structure on the surreals
-- TODO show the maps from the dyadic rationals and from the reals into the surreals are multiplicative
end surreal
|
2e4c295845a1e6ed8a4d8c186ee47c29e5ab96fd | 0ddf2dd8409bcb923d11603846800bd9699616ea | /chapter7.lean | f18f3cde02bbb47d0247c6d33fecc228f1db9f84 | [] | no_license | tounaishouta/Lean | 0cbaaa9340e7f8f884504ea170243e07a54f0566 | 1d75311f5506ca2bfd8b7ccec0b7d70c3319d555 | refs/heads/master | 1,610,229,383,935 | 1,459,950,226,000 | 1,459,950,226,000 | 50,836,185 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,034 | lean | import standard
namespace sec7_1
definition sub2 : ℕ → ℕ
| sub2 0 := 0
| sub2 1 := 0
| sub2 (a + 2) := a
eval sub2 0
eval sub2 1
eval sub2 2
eval sub2 3
eval sub2 4
eval sub2 5
inductive bool : Type :=
| ff : bool
| tt : bool
open sec7_1.bool
definition bnot : bool → bool
| bnot ff := tt
| bnot tt := ff
theorem bnot_bnot : ∀ b : bool, bnot (bnot b) = b
| bnot_bnot tt := rfl
| bnot_bnot ff := rfl
inductive nat : Type :=
| zero : nat
| succ : nat → nat
open nat
notation `ℕ` := nat
definition add : ℕ → ℕ → ℕ
| add n zero := n
| add n (succ m) := succ (n + m)
theorem add_zero (n : ℕ) : n + zero = n := rfl
theorem add_succ (n m : ℕ) : n + succ m = succ (n + m) := rfl
theorem add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k)
| add_assoc n m 0 :=
calc (n + m) + 0
= n + m : add_zero
... = n + (m + 0) : {add_zero m}
| add_assoc n m (succ k) :=
calc (n + m) + succ k
= succ ((n + m) + k) : add_succ
... = succ (n + (m + k)) : add_assoc
... = n + succ (m + k) : add_succ
... = n + (m + succ k) : add_succ
theorem zero_add : ∀ n : ℕ, zero + n = n
| zero_add 0 := rfl
| zero_add (succ n) :=
calc 0 + succ n
= succ (0 + n) : add_succ
... = succ n : {zero_add n}
theorem succ_add : ∀ n m : ℕ, succ n + m = succ (n + m)
| succ_add n 0 :=
calc succ n + 0
= succ n : add_zero
...= succ (n + 0) : add_zero
| succ_add n (succ m) :=
calc succ n + succ m
= succ (succ n + m) : add_succ
...= succ (succ (n + m)) : succ_add
...= succ (n + succ m) : add_succ
theorem add_comm : ∀ n m : ℕ, n + m = m + n
| add_comm n 0 :=
calc n + 0
= n : add_zero
...= 0 + n : zero_add
| add_comm n (succ m) :=
calc n + (succ m)
= succ (n + m) : add_succ
...= succ (m + n) : add_comm
...= succ m + n : succ_add
end sec7_1
namespace sec7_2
end sec7_2
namespace sec7_3
open list
definition map {A B : Type} : (A → B) → list A → list B
| map f nil := nil
| map f (h :: t) := f h :: map f t
open nat
eval map succ []
eval map succ [3, 8, 4]
open prod
definition zip {A B : Type} : list A → list B → list (A × B)
| zip nil _ := nil
| zip _ nil := nil
| zip (h1 :: t1) (h2 :: t2) := (h1, h2) :: zip t1 t2
eval (zip [3, 8, 4] [2, 9, 7, 5] : list (ℕ × ℕ))
eval (zip [4, 5] [8] : list (ℕ × ℕ))
definition unzip {A B : Type} : list (A × B) → list A × list B
| unzip nil := (nil, nil)
| unzip ((h1, h2) :: t) :=
match unzip t with
(t1, t2) := (h1 :: t1, h2 :: t2)
end
eval (unzip [(4, 7), (6, 8), (5, 2)] : list ℕ × list ℕ)
/-
definition diag {A : Type} : list (list A) → list A
| diag nil := nil
| diag (nil :: _) := nil
| diag ((h :: _) :: t) := h :: diag (map tail t)
-/
end sec7_3
namespace sec7_4
open nat
definition f : ℕ → ℕ → ℕ
| f 0 0 := 0
| f 0 _ := 1
| f _ 0 := 2
| f _ _ := arbitrary ℕ
print f
print arbitrary
end sec7_4
namespace sec7_5
end sec7_5
|
ab04f268d9342acd0aacbd9b2bfab306823fe9a4 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Elab/ComputedFields.lean | 0f8299e38ddb5c6ffeb70d79626e4af5c1143d39 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 9,617 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean.Meta.Constructions
import Lean.Compiler.ImplementedByAttr
import Lean.Elab.PreDefinition.WF.Eqns
/-!
# Computed fields
Inductives can have computed fields which are recursive functions whose value
is stored in the constructors, and can be accessed in constant time.
```lean
inductive Exp
| hole
| app (x y : Exp)
with
f : Exp → Nat
| .hole => 42
| .app x y => f x + f y
-- `Exp.f x` runs in constant time, even if `x` is a dag-like value
```
This file implements the computed fields feature by simulating it via
`implementedBy`. The main function is `setComputedFields`.
-/
namespace Lean.Elab.ComputedFields
open Meta
builtin_initialize computedFieldAttr : TagAttribute ←
registerTagAttribute `computedField "Marks a function as a computed field of an inductive" fun _ => do
unless (← getOptions).getBool `elaboratingComputedFields do
throwError "The @[computedField] attribute can only be used in the with-block of an inductive"
def mkUnsafeCastTo (expectedType : Expr) (e : Expr) : MetaM Expr :=
mkAppOptM ``unsafeCast #[none, expectedType, e]
def isScalarField (ctor : Name) : CoreM Bool :=
return (← getConstInfoCtor ctor).numFields == 0 -- TODO
structure Context extends InductiveVal where
lparams : List Level
params : Array Expr
compFields : Array Name
compFieldVars : Array Expr
indices : Array Expr
val : Expr
abbrev M := ReaderT Context MetaM
-- TODO: doesn't work if match contains patterns like `.app (.app a b) c`
def getComputedFieldValue (computedField : Name) (ctorTerm : Expr) : MetaM Expr := do
let ctorName := ctorTerm.getAppFn.constName!
let ind ← getConstInfoInduct (← getConstInfoCtor ctorName).induct
let val ← mkAppOptM computedField (mkArray (ind.numParams+ind.numIndices) none ++ #[some ctorTerm])
let val ←
if let some wfEqn := WF.eqnInfoExt.find? (← getEnv) computedField then
pure <| mkAppN (wfEqn.value.instantiateLevelParams wfEqn.levelParams val.getAppFn.constLevels!) val.getAppArgs
else
unfoldDefinition val
let val ← whnfHeadPred val (return ctorTerm.occurs ·)
if !ctorTerm.occurs val then return val
throwError "computed field {computedField} does not reduce for constructor {ctorName}"
def validateComputedFields : M Unit := do
let {compFieldVars, indices, val ..} ← read
for cf in compFieldVars do
let ty ← inferType cf
if ty.containsFVar val.fvarId! then
throwError "computed field {cf}'s type must not depend on value{indentExpr ty}"
if indices.any (ty.containsFVar ·.fvarId!) then
throwError "computed field {cf}'s type must not depend on indices{indentExpr ty}"
def mkImplType : M Unit := do
let {name, isUnsafe, type, ctors, levelParams, numParams, lparams, params, compFieldVars, ..} ← read
addDecl <| .inductDecl levelParams numParams
(isUnsafe := isUnsafe) -- Note: inlining is disabled with unsafe inductives
[{ name := name ++ `_impl, type,
ctors := ← ctors.mapM fun ctor => do
forallTelescope (← inferType (mkAppN (mkConst ctor lparams) params)) fun fields retTy => do
let retTy := mkAppN (mkConst (name ++ `_impl) lparams) retTy.getAppArgs
let type ← mkForallFVars (params ++ (if ← isScalarField ctor then #[] else compFieldVars) ++ fields) retTy
return { name := ctor ++ `_impl, type } }]
def overrideCasesOn : M Unit := do
let {name, numIndices, ctors, lparams, params, compFieldVars, ..} ← read
let casesOn ← getConstInfoDefn (mkCasesOnName name)
mkCasesOn (name ++ `_impl)
let value ←
forallTelescope (← instantiateForall casesOn.type params) fun xs constMotive => do
let (indices, major, minors) := (xs[1:numIndices+1].toArray,
xs[numIndices+1]!, xs[numIndices+2:].toArray)
let majorImplTy := mkAppN (mkConst (name ++ `_impl) lparams) (params ++ indices)
mkLambdaFVars (params ++ xs) <|
mkAppN (mkConst (mkCasesOnName (name ++ `_impl))
(casesOn.levelParams.map mkLevelParam)) <|
params ++
#[← withLocalDeclD `a majorImplTy fun majorImpl => do
withLetDecl `m (← inferType constMotive) constMotive fun m => do
mkLambdaFVars (#[m] ++ indices ++ #[majorImpl]) m] ++
indices ++ #[← mkUnsafeCastTo majorImplTy major] ++
(← (minors.zip ctors.toArray).mapM fun (minor, ctor) => do
forallTelescope (← inferType minor) fun args _ => do
mkLambdaFVars ((if ← isScalarField ctor then #[] else compFieldVars) ++ args)
(← mkUnsafeCastTo constMotive (mkAppN minor args)))
let nameOverride := mkCasesOnName name ++ `_override
addDecl <| .defnDecl { casesOn with
name := nameOverride
all := [nameOverride]
value
hints := .opaque
safety := .unsafe
}
setInlineAttribute (mkCasesOnName name ++ `_override)
setImplementedBy (mkCasesOnName name) (mkCasesOnName name ++ `_override)
def overrideConstructors : M Unit := do
let {ctors, levelParams, lparams, params, compFields, ..} ← read
for ctor in ctors do
forallTelescope (← inferType (mkAppN (mkConst ctor lparams) params)) fun fields retTy => do
let ctorTerm := mkAppN (mkConst ctor lparams) (params ++ fields)
let computedFieldVals ← if ← isScalarField ctor then pure #[] else
compFields.mapM (getComputedFieldValue · ctorTerm)
addDecl <| .defnDecl {
name := ctor ++ `_override
levelParams
type := ← inferType (mkConst ctor lparams)
value := ← mkLambdaFVars (params ++ fields) <| ← mkUnsafeCastTo retTy <|
mkAppN (mkConst (ctor ++ `_impl) lparams) (params ++ computedFieldVals ++ fields)
hints := .opaque
safety := .unsafe
}
setImplementedBy ctor (ctor ++ `_override)
if ← isScalarField ctor then setInlineAttribute (ctor ++ `_override)
def overrideComputedFields : M Unit := do
let {name, levelParams, ctors, compFields, compFieldVars, lparams, params, indices, val ..} ← read
withLocalDeclD `x (mkAppN (mkConst (name ++ `_impl) lparams) (params ++ indices)) fun xImpl => do
for cfn in compFields, cf in compFieldVars do
if isExtern (← getEnv) cfn then
compileDecls [cfn]
continue
let cases ← ctors.toArray.mapM fun ctor => do
forallTelescope (← inferType (mkAppN (mkConst ctor lparams) params)) fun fields _ => do
if ← isScalarField ctor then
mkLambdaFVars fields <|
← getComputedFieldValue cfn (mkAppN (mkConst ctor lparams) (params ++ fields))
else
mkLambdaFVars (compFieldVars ++ fields) cf
addDecl <| .defnDecl {
name := cfn ++ `_override
levelParams
type := ← mkForallFVars (params ++ indices ++ #[val]) (← inferType cf)
value := ← mkLambdaFVars (params ++ indices ++ #[val]) <|
← mkAppOptM (mkCasesOnName (name ++ `_impl))
((params ++ #[← mkLambdaFVars (indices.push xImpl) (← inferType cf)] ++ indices ++
#[← mkUnsafeCastTo (← inferType xImpl) val] ++ cases).map some)
safety := .unsafe
hints := .opaque
}
setImplementedBy cfn (cfn ++ `_override)
def mkComputedFieldOverrides (declName : Name) (compFields : Array Name) : MetaM Unit := do
let ind ← getConstInfoInduct declName
if ind.ctors.length < 2 then
throwError "computed fields require at least two constructors"
let lparams := ind.levelParams.map mkLevelParam
forallTelescope ind.type fun paramsIndices _ => do
withLocalDeclD `x (mkAppN (mkConst ind.name lparams) paramsIndices) fun val => do
let params := paramsIndices[:ind.numParams].toArray
let indices := paramsIndices[ind.numParams:].toArray
let compFieldVars := compFields.map fun fieldDeclName =>
(fieldDeclName.updatePrefix .anonymous,
fun _ => do inferType (← mkAppM fieldDeclName (params ++ indices ++ #[val])))
withLocalDeclsD compFieldVars fun compFieldVars => do
let ctx := { ind with lparams, params, compFields, compFieldVars, indices, val }
ReaderT.run (r := ctx) do
validateComputedFields
mkImplType
overrideCasesOn
overrideConstructors
overrideComputedFields
/--
Sets the computed fields for a block of mutual inductives,
adding the implementation via `implementedBy`.
The `computedFields` argument contains a pair
for every inductive in the mutual block,
consisting of the name of the inductive
and the names of the associated computed fields.
-/
def setComputedFields (computedFields : Array (Name × Array Name)) : MetaM Unit := do
for (indName, computedFieldNames) in computedFields do
for computedFieldName in computedFieldNames do
unless computedFieldAttr.hasTag (← getEnv) computedFieldName do
logError m!"'{computedFieldName}' must be tagged with @[computedField]"
mkComputedFieldOverrides indName computedFieldNames
-- Once all the implementedBy infrastructure is set up, compile everything.
compileDecls <| computedFields.toList.map fun (indName, _) =>
mkCasesOnName indName ++ `_override
let mut toCompile := #[]
for (declName, computedFields) in computedFields do
let ind ← getConstInfoInduct declName
for ctor in ind.ctors do
toCompile := toCompile.push (ctor ++ `_override)
for fieldName in computedFields do
unless isExtern (← getEnv) fieldName do
toCompile := toCompile.push <| fieldName ++ `_override
compileDecls toCompile.toList
|
ab60aa4cb3bf1b51b13b3db6cdc653449a7e839e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Load/Config.lean | d3f5a2d61ca7d48f49674e8804fdf35eedfcb87d | [
"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 | 995 | lean | /-
Copyright (c) 2022 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lean.Data.Name
import Lean.Data.Options
import Lake.Config.Env
import Lake.Util.Log
namespace Lake
open System Lean
/-- The default name of the Lake configuration file (i.e., `lakefile.lean`). -/
def defaultConfigFile : FilePath := "lakefile.lean"
/-- Context for loading a Lake configuration. -/
structure LoadConfig where
/-- The Lake environment of the load process. -/
env : Lake.Env
/-- The root directory of the loaded package (and its workspace). -/
rootDir : FilePath
/-- The Lean file with the package's Lake configuration (e.g., `lakefile.lean`) -/
configFile : FilePath := rootDir / defaultConfigFile
/-- A set of key-value Lake configuration options (i.e., `-K` settings). -/
configOpts : NameMap String := {}
/-- The Lean options with which to elaborate the configuration file. -/
leanOpts : Options := {}
|
3db56bc85172c52df77db9667b04c83a02f4dd92 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /10_Structures_and_Records.org.10.lean | bc3844410a46c4a2ae108baf94dc827a02b4047d | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 126 | lean | import standard
structure my_struct :=
mk :: (A : Type) (B : Type) (a : A) (b : B)
check {| my_struct, a := 10, b := true |}
|
ecbe0497c5c6f47e47f38164ed10024b6b1fa3f5 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/dfinsupp/order.lean | 63b93b84c8129dc00e0dcadc164f7c306e61dfb0 | [
"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 | 8,068 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.dfinsupp.basic
/-!
# Pointwise order on finitely supported dependent functions
This file lifts order structures on the `α i` to `Π₀ i, α i`.
## Main declarations
* `dfinsupp.order_embedding_to_fun`: The order embedding from finitely supported dependent functions
to functions.
## TODO
Add `is_well_order (Π₀ i, α i) (<)`.
-/
open_locale big_operators
open finset
variables {ι : Type*} {α : ι → Type*}
namespace dfinsupp
/-! ### Order structures -/
section has_zero
variables (α) [Π i, has_zero (α i)]
section has_le
variables [Π i, has_le (α i)]
instance : has_le (Π₀ i, α i) := ⟨λ f g, ∀ i, f i ≤ g i⟩
variables {α}
lemma le_def {f g : Π₀ i, α i} : f ≤ g ↔ ∀ i, f i ≤ g i := iff.rfl
/-- The order on `dfinsupp`s over a partial order embeds into the order on functions -/
def order_embedding_to_fun : (Π₀ i, α i) ↪o Π i, α i :=
{ to_fun := λ f, f,
inj' := λ f g h, dfinsupp.ext $ λ i, by { dsimp at h, rw h },
map_rel_iff' := λ a b, (@le_def _ _ _ _ a b).symm }
@[simp] lemma order_embedding_to_fun_apply {f : Π₀ i, α i} {i : ι} :
order_embedding_to_fun f i = f i := rfl
end has_le
section preorder
variables [Π i, preorder (α i)]
instance : preorder (Π₀ i, α i) :=
{ le_refl := λ f i, le_rfl,
le_trans := λ f g h hfg hgh i, (hfg i).trans (hgh i),
.. dfinsupp.has_le α }
lemma coe_fn_mono : monotone (coe_fn : (Π₀ i, α i) → Π i, α i) := λ f g, le_def.1
end preorder
instance [Π i, partial_order (α i)] : partial_order (Π₀ i, α i) :=
{ le_antisymm := λ f g hfg hgf, ext $ λ i, (hfg i).antisymm (hgf i),
.. dfinsupp.preorder α}
instance [Π i, semilattice_inf (α i)] : semilattice_inf (Π₀ i, α i) :=
{ inf := zip_with (λ _, (⊓)) (λ _, inf_idem),
inf_le_left := λ f g i, by { rw zip_with_apply, exact inf_le_left },
inf_le_right := λ f g i, by { rw zip_with_apply, exact inf_le_right },
le_inf := λ f g h hf hg i, by { rw zip_with_apply, exact le_inf (hf i) (hg i) },
..dfinsupp.partial_order α }
@[simp] lemma inf_apply [Π i, semilattice_inf (α i)] (f g : Π₀ i, α i) (i : ι) :
(f ⊓ g) i = f i ⊓ g i :=
zip_with_apply _ _ _ _ _
instance [Π i, semilattice_sup (α i)] : semilattice_sup (Π₀ i, α i) :=
{ sup := zip_with (λ _, (⊔)) (λ _, sup_idem),
le_sup_left := λ f g i, by { rw zip_with_apply, exact le_sup_left },
le_sup_right := λ f g i, by { rw zip_with_apply, exact le_sup_right },
sup_le := λ f g h hf hg i, by { rw zip_with_apply, exact sup_le (hf i) (hg i) },
..dfinsupp.partial_order α }
@[simp] lemma sup_apply [Π i, semilattice_sup (α i)] (f g : Π₀ i, α i) (i : ι) :
(f ⊔ g) i = f i ⊔ g i :=
zip_with_apply _ _ _ _ _
instance lattice [Π i, lattice (α i)] : lattice (Π₀ i, α i) :=
{ .. dfinsupp.semilattice_inf α, .. dfinsupp.semilattice_sup α }
end has_zero
/-! ### Algebraic order structures -/
instance (α : ι → Type*) [Π i, ordered_add_comm_monoid (α i)] :
ordered_add_comm_monoid (Π₀ i, α i) :=
{ add_le_add_left := λ a b h c i,
by { rw [add_apply, add_apply], exact add_le_add_left (h i) (c i) },
.. dfinsupp.add_comm_monoid, .. dfinsupp.partial_order α }
instance (α : ι → Type*) [Π i, ordered_cancel_add_comm_monoid (α i)] :
ordered_cancel_add_comm_monoid (Π₀ i, α i) :=
{ le_of_add_le_add_left := λ f g h H i, begin
specialize H i,
rw [add_apply, add_apply] at H,
exact le_of_add_le_add_left H,
end,
add_left_cancel := λ f g h H, ext $ λ i, begin
refine add_left_cancel _,
exact f i,
rw [←add_apply, ←add_apply, H],
end,
.. dfinsupp.ordered_add_comm_monoid α }
instance [Π i, ordered_add_comm_monoid (α i)] [Π i, contravariant_class (α i) (α i) (+) (≤)] :
contravariant_class (Π₀ i, α i) (Π₀ i, α i) (+) (≤) :=
⟨λ f g h H i, by { specialize H i, rw [add_apply, add_apply] at H, exact le_of_add_le_add_left H }⟩
section canonically_ordered_add_monoid
variables (α) [Π i, canonically_ordered_add_monoid (α i)]
instance : order_bot (Π₀ i, α i) :=
{ bot := 0,
bot_le := by simp only [le_def, coe_zero, pi.zero_apply, implies_true_iff, zero_le] }
variables {α}
protected lemma bot_eq_zero : (⊥ : Π₀ i, α i) = 0 := rfl
@[simp] lemma add_eq_zero_iff (f g : Π₀ i, α i) : f + g = 0 ↔ f = 0 ∧ g = 0 :=
by simp [ext_iff, forall_and_distrib]
section le
variables [decidable_eq ι] [Π i (x : α i), decidable (x ≠ 0)] {f g : Π₀ i, α i} {s : finset ι}
lemma le_iff' (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i :=
⟨λ h s hs, h s,
λ h s, if H : s ∈ f.support then h s (hf H) else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩
lemma le_iff : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i := le_iff' $ subset.refl _
variables (α)
instance decidable_le [Π i, decidable_rel (@has_le.le (α i) _)] :
decidable_rel (@has_le.le (Π₀ i, α i) _) :=
λ f g, decidable_of_iff _ le_iff.symm
variables {α}
@[simp] lemma single_le_iff {i : ι} {a : α i} : single i a ≤ f ↔ a ≤ f i :=
(le_iff' support_single_subset).trans $ by simp
end le
variables (α) [Π i, has_sub (α i)] [Π i, has_ordered_sub (α i)] {f g : Π₀ i, α i} {i : ι}
{a b : α i}
/-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an
additive group. -/
instance tsub : has_sub (Π₀ i, α i) := ⟨zip_with (λ i m n, m - n) (λ i, tsub_self 0)⟩
variables {α}
lemma tsub_apply (f g : Π₀ i, α i) (i : ι) : (f - g) i = f i - g i := zip_with_apply _ _ _ _ _
@[simp] lemma coe_tsub (f g : Π₀ i, α i) : ⇑(f - g) = f - g := by { ext i, exact tsub_apply f g i }
variables (α)
instance : has_ordered_sub (Π₀ i, α i) :=
⟨λ n m k, forall_congr $ λ i, by { rw [add_apply, tsub_apply], exact tsub_le_iff_right }⟩
instance : canonically_ordered_add_monoid (Π₀ i, α i) :=
{ le_iff_exists_add := λ f g, begin
refine ⟨λ h, ⟨g - f, _⟩, _⟩,
{ ext i,
rw [add_apply, tsub_apply],
exact (add_tsub_cancel_of_le $ h i).symm },
{ rintro ⟨g, rfl⟩ i,
rw add_apply,
exact self_le_add_right (f i) (g i) }
end,
.. dfinsupp.order_bot α,
.. dfinsupp.ordered_add_comm_monoid α }
variables {α} [decidable_eq ι]
@[simp] lemma single_tsub : single i (a - b) = single i a - single i b :=
begin
ext j,
obtain rfl | h := eq_or_ne i j,
{ rw [tsub_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, tsub_self] }
end
variables [Π i (x : α i), decidable (x ≠ 0)]
lemma support_tsub : (f - g).support ⊆ f.support :=
by simp only [subset_iff, tsub_eq_zero_iff_le, mem_support_iff, ne.def, coe_tsub, pi.sub_apply,
not_imp_not, zero_le, implies_true_iff] {contextual := tt}
lemma subset_support_tsub : f.support \ g.support ⊆ (f - g).support :=
by simp [subset_iff] {contextual := tt}
end canonically_ordered_add_monoid
section canonically_linear_ordered_add_monoid
variables [Π i, canonically_linear_ordered_add_monoid (α i)] [decidable_eq ι] {f g : Π₀ i, α i}
@[simp] lemma support_inf : (f ⊓ g).support = f.support ∩ g.support :=
begin
ext,
simp only [inf_apply, mem_support_iff, ne.def,
finset.mem_union, finset.mem_filter, finset.mem_inter],
simp only [inf_eq_min, ←nonpos_iff_eq_zero, min_le_iff, not_or_distrib],
end
@[simp] lemma support_sup : (f ⊔ g).support = f.support ∪ g.support :=
begin
ext,
simp only [finset.mem_union, mem_support_iff, sup_apply, ne.def, ←bot_eq_zero],
rw [_root_.sup_eq_bot_iff, not_and_distrib],
end
lemma disjoint_iff : disjoint f g ↔ disjoint f.support g.support :=
begin
rw [disjoint_iff, disjoint_iff, dfinsupp.bot_eq_zero, ← dfinsupp.support_eq_empty,
dfinsupp.support_inf],
refl,
end
end canonically_linear_ordered_add_monoid
end dfinsupp
|
8f915f8122f09cf9ccf1cdb64be076437a4c4acf | 695574baef97a204f68217f2dfede8512fd91ff8 | /src/main.lean | ae4af2b905518a28dd36682f3bf8e9f7a99e367e | [] | no_license | JasonKYi/stone-weierstrass | ba463bedc758c4993e922afcc8cf8895a9257bd4 | 390affd1415cf393da55866b82fdf68747dee7a2 | refs/heads/master | 1,680,089,697,789 | 1,617,652,603,000 | 1,617,652,603,000 | 266,203,243 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,842 | lean | import topology.bounded_continuous_function
import assumptions
noncomputable theory
open set classical
local attribute [instance] prop_decidable
variables {X : Type*} [metric_space X] [compact_space X]
-- We adopt the notation of bounded countinuous function from mathlib
local infixr ` →ᵇ ` : 25 := bounded_continuous_function
lemma closure₂_of_univ :
closure₂ (@univ (X →ᵇ ℝ)) = univ :=
begin
ext f, split; intro hf,
{ exact mem_univ f },
{ left, refine ⟨f, f, hf, hf, or.inl _⟩,
unfold has_sup.sup,
ext, simpa }
end
/- The first lemma we need states that:
f ∈ closure₂ M₀ ↔
∀ x, y ∈ X, ∀ ε > 0, ∃ f' ∈ closure₀ M₀, such that
|f(x) - f'(x)| < ε and |f(y) - f'(y)| < ε -/
/- The forward direction is trivial -/
lemma dense_at_points_in_closure
{M₀ : set (X →ᵇ ℝ)} {f : X →ᵇ ℝ} (h : f ∈ closure₂ M₀) :
∀ ε > 0, ∀ x y : X, ∃ (g : X →ᵇ ℝ) (H : g ∈ closure₀ M₀),
abs (f x - g x) < ε ∧ abs (f y - g y) < ε :=
begin
rcases h with ⟨g, h, hg, hh, h⟩; intros ε hε x y,
{ cases h with hlub hglb,
exact ⟨g ⊔ h, ⟨g, h, hg, hh, or.inl rfl⟩, by simpa [hlub, hε]⟩,
exact ⟨g ⊓ h, ⟨g, h, hg, hh, or.inr rfl⟩, by simpa [hglb, hε]⟩ },
{ rcases h with ⟨F, hF, hlim⟩,
cases hlim ε hε with N hN,
exact ⟨F N, hF N, by simp [hN N (le_refl N)]⟩ }
end
/- To prove the reverse we fix x ∈ X and vary y.
Since X is a compact space, We an use Heine-Borel on the entire space.
This is the lemma we'll use: compact.elim_finite_subcover -/
/- So let us fix x ∈ X and given y ∈ X write the function g satisfying
h : abs (f(x) - g(x)) < ε ∧ abs (f(y) - g(y)) < ε, f_y (the existence
of which is guarenteed by our hypothesis), we define
S(y) := {z ∈ X | f(z) - f_y(z) < ε}
It's obvious that y ∈ S(y) by h.right so
X ⊆ ⋃ (y : X) S(y) ⇒ X = ⋃ (y : X) S(y)
Now as X is compact, there is a finite subcover of X so there exists
points in X, y₁, ⋯, yₙ, such that
X = U i ∈ {1, ⋯, n}, S(yᵢ).
So now, by letting g_x := ⊔ i, f_yᵢ, we have ∀ z ∈ X,
g_x(z) ≥ f_yₖ(z) > f(z) - ε
for some k ∈ {1, ⋯, n}.
Now we will define T(x) := {z ∈ X | g_x(z) < f(z) + ε}.
As ∀ yᵢ, f_yᵢ(x) < f(x) + ε by h.left, so is g_x(x) < f(x) + ε.
Thus, x ∈ T(x) and X ⊆ ⋃ (x : X) T(x) and again as X is compact, there
is x₁, ⋯, xₘ, such that
X = U i ∈ {1, ⋯, m}, S(xᵢ).
So, by letting h := ⊓ i, g_xᵢ, we have ∀ z ∈ X, h(z) ≤ g_xₖ(z) < f(z) + ε.
Now, as g_xᵢ(z) > f(z) - ε, for all i, so is h(z) > f(z) - ε and hence
there is a function in closure₀ M₀ thats arbitarily close to f.
-/
/- Given x ∈ X, we create a function thats greater than f(z) - ε at all z while
smaller than f(x) + ε. -/
lemma has_bcf_gt {M₀ : set (X →ᵇ ℝ)} {f : X →ᵇ ℝ}
(h : ∀ ε > 0, ∀ x y : X, ∃ (g : X →ᵇ ℝ)
(H : g ∈ closure₀ M₀), abs (f x - g x) < ε ∧ abs (f y - g y) < ε) :
∀ ε > 0, ∀ x : X, ∃ (g : X →ᵇ ℝ)
(H : g ∈ closure₀ M₀), ∀ z : X, f z - ε < g z ∧ g x < f x + ε :=
begin
intros ε hε x, choose g hg₀ hg₁ using h ε (by {norm_cast, exact hε}) x,
let S : X → set X := λ y, {z | f z - g y z < ε},
cases compact.elim_finite_subcover _inst_2.1 S
(is_open_aux_set₀ (by norm_cast; exact hε)) _ with I hI,
{ let p := I.sup g,
refine ⟨p, finset_sup_mem_closure₀ hg₀,
λ z, ⟨_, finset_sup_lt (λ i hi, by linarith [(abs_lt.1 (hg₁ i).1).1])⟩⟩,
suffices : ∃ i ∈ I, f z - ε < g i z,
rcases this with ⟨i, hi₀, hi₁⟩,
exact lt_of_lt_of_le hi₁ (le_finset_sup g i hi₀ z),
have : z ∈ ⋃ (i : X) (H : i ∈ I), S i, exact hI (by trivial),
cases mem_Union.1 this with i hi, cases mem_Union.1 hi with hi hz,
rw mem_set_of_eq at hz, exact ⟨i, hi, by linarith⟩ },
{ intros y hy, exact mem_Union.2 ⟨y, (abs_lt.1 (hg₁ y).2).2⟩ }
end
/- We again use the same method obtaining a function arbitarily close to f -/
lemma has_bcf_close {M₀ : set (X →ᵇ ℝ)} {f : X →ᵇ ℝ}
(h : ∀ ε > 0, ∀ x y : X, ∃ (g : X →ᵇ ℝ)
(H : g ∈ closure₀ M₀), abs (f x - g x) < ε ∧ abs (f y - g y) < ε) :
∀ (ε : ℝ) (hε : 0 < ε), ∃ (g : X →ᵇ ℝ)
(H : g ∈ closure₀ M₀), ∀ z : X, abs (f z - g z) < ε :=
begin
intros ε hε, choose g hg₀ hg₁ using has_bcf_gt h ε hε,
let S : X → set X := λ x, {z | g x z < f z + ε},
cases compact.elim_finite_subcover _inst_2.1 S (is_open_aux_set₁ hε) _ with I hI,
{ let p := I.inf g, refine ⟨p, finset_inf_mem_closure₀ hg₀, λ z, _⟩,
rw abs_lt, refine ⟨_, _⟩,
{ rw neg_lt_sub_iff_lt_add,
suffices : ∃ i ∈ I, g i z < f z + ε,
rcases this with ⟨i, hi₀, hi₁⟩,
refine lt_of_le_of_lt (finset_inf_le g i hi₀ z) hi₁,
have : z ∈ ⋃ (i : X) (H : i ∈ I), S i, refine hI (by trivial),
cases mem_Union.1 this with i hi, cases mem_Union.1 hi with hi hz,
refine ⟨i, hi, hz⟩ },
{ suffices : ∀ i ∈ I, f z - ε < g i z,
exact sub_lt.2 (lt_finset_inf this),
intros i hi, exact (hg₁ i z).1 } },
{ intros x hx, exact mem_Union.2 ⟨x, (hg₁ x x).2⟩ }
end
/- With that we conclude that there is some sequence of functions in closure₀ M₀
that is uniformly convergent towards f -/
lemma in_closure₂_of_dense_at_points {M₀ : set (X →ᵇ ℝ)} {f : X →ᵇ ℝ}
(h : ∀ ε > 0, ∀ x y : X, ∃ (g : X →ᵇ ℝ)
(H : g ∈ closure₀ M₀), abs (f x - g x) < ε ∧ abs (f y - g y) < ε) :
f ∈ closure₂ M₀ := or.inr $
begin
choose F hF₀ hF₁ using λ (n : ℕ),
has_bcf_close h (1 / (n + 1)) (nat.one_div_pos_of_nat),
refine ⟨F, hF₀, λ ε hε, _⟩,
cases exists_nat_gt (1 / ε) with N hN,
refine ⟨N, λ n hn x, lt_of_lt_of_le (hF₁ n x) $
one_div_le_of_one_div_le_of_pos hε $ le_trans (le_of_lt hN) _⟩,
norm_cast, exact le_add_right hn,
end
/- Finally, we can conclude that f can be constructed from M₀ using inf, sup
and uniform convergence iff. for all pairs of points in X, (x, y), there is
some sequence of functions in M₀ that converges pointwise to f(x) and f(y) at
x and y. -/
theorem in_closure₂_iff_dense_at_points {M₀ : set (X →ᵇ ℝ)} {f : X →ᵇ ℝ} :
f ∈ closure₂ M₀ ↔ ∀ ε > 0, ∀ x y : X,
∃ (g : X →ᵇ ℝ) (H : g ∈ closure₀ M₀), abs (f x - g x) < ε ∧ abs (f y - g y) < ε :=
⟨λ h, dense_at_points_in_closure h, λ h, in_closure₂_of_dense_at_points h⟩
/- From this, a corollaries can be deduced immediately:
- If ∀ x, y ∈ X, a, b ∈ ℝ, ∃ f ∈ M₀, f(x) = a, f(y) = b, then
closure₂ M₀ = M (= @univ X →ᵇ ℝ)
where M is the set of all bounded continuous functions from X to ℝ. -/
/- Due to reasons commented from above, we will now consider pairs of points in
X rather than functions.
We define M₀' : X → X → ℝ × ℝ : x, y ↦ {(f(x), f(y)) | f ∈ M₀};
(α, β) ⊔ (γ, δ) := (max α γ, max β δ);
and (α, β) ⊓ (γ, δ) := (min α γ, min β δ).
We also define a closure with respect to this inf, sup and limits of
sequences in ℝ². -/
lemma le_closure' {S : set (ℝ × ℝ)} : S ⊆ closure' S :=
begin
intros x hx, left, refine ⟨x, x, hx, hx, or.inl _⟩,
unfold has_sup.sup,
unfold semilattice_sup.sup,
unfold lattice.sup,
simp
end
lemma zero_mem_of_subalgebra {M₀' : subalgebra ℝ (X →ᵇ ℝ)} :
(0 : X →ᵇ ℝ) ∈ M₀'.carrier := M₀'.2.1.1.1
lemma one_mem_of_subalgebra {M₀' : subalgebra ℝ (X →ᵇ ℝ)} :
(1 : X →ᵇ ℝ) ∈ M₀'.carrier := M₀'.2.2.1
lemma neg_mem_of_subalgebra {M₀' : subalgebra ℝ (X →ᵇ ℝ)} :
∀ f ∈ M₀'.carrier, -f ∈ M₀'.carrier := M₀'.2.1.2
lemma add_mem_of_subalgebra {M₀' : subalgebra ℝ (X →ᵇ ℝ)} :
∀ f g ∈ M₀'.carrier, f + g ∈ M₀'.carrier := M₀'.2.1.1.2
lemma mul_mem_of_subalgebra {M₀' : subalgebra ℝ (X →ᵇ ℝ)} :
∀ f g ∈ M₀'.carrier, f * g ∈ M₀'.carrier := M₀'.2.2.2
lemma zero_mem_of_boundary_points {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
{x y} (hc : closure₀ M₀'.carrier = M₀'.carrier) :
(0 : ℝ × ℝ) ∈ boundary_points (closure₂ M₀'.carrier) x y :=
begin
refine ⟨(0 : X →ᵇ ℝ), _, _⟩,
apply closure_le_seq₁, rw hc,
exact zero_mem_of_subalgebra,
refl
end
lemma one_mem_of_boundary_points {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
{x y} (hc : closure₀ M₀'.carrier = M₀'.carrier) :
(1 : ℝ × ℝ) ∈ boundary_points (closure₂ M₀'.carrier) x y :=
begin
refine ⟨(1 : X →ᵇ ℝ), _, _⟩,
apply closure_le_seq₁, rw hc,
exact one_mem_of_subalgebra,
refl
end
/- neg_mem is a bit trickier since we need to show that closure₂
is closed under neg (note that we are not assuming closure₂ M₀ is
a subalgebra). To prove this we construct an uniformly convergent sequence
of functions in M₀ that converges to -f. -/
lemma neg_mem_of_boundary_points {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
{x y} (hc : closure₀ M₀'.carrier = M₀'.carrier) :
∀ β ∈ boundary_points (closure₂ M₀'.carrier) x y,
-β ∈ boundary_points (closure₂ M₀'.carrier) x y :=
begin
intros β hβ, rcases hβ with ⟨f, hf₀, hf₁⟩,
refine ⟨-f, _, _⟩,
cases hf₀,
{ rcases hf₀ with ⟨g, h, hg, hh, hgh⟩,
cases hgh; left,
refine ⟨-g, -h, neg_mem_of_subalgebra g hg, neg_mem_of_subalgebra h hh, _⟩,
right, exact neg_inf_eq_sup.1 hgh,
refine ⟨-g, -h, neg_mem_of_subalgebra g hg, neg_mem_of_subalgebra h hh, _⟩,
left, exact neg_sup_eq_inf.1 hgh },
{ rcases hf₀ with ⟨F, hF₀, hF₁⟩,
right,
refine ⟨λ n, -F n, λ i, _, _⟩,
rw hc at *, exact neg_mem_of_subalgebra (F i) (hF₀ i),
exact neg_unif_converges_to hF₁ },
rw ←hf₁, refl
end
/- It is a similar story for add_mem and mul_mem. These requires
- if λ n, F n ⟶ f and λ n, G n ⟶ g, then λ n, F n + G n ⟶ f + g
- if λ n, F n ⟶ f and λ n, G n ⟶ g, then λ n, F n * G n ⟶ f * g
respectively (both of which are standar results so).
-/
lemma add_mem_of_boundary_points {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
{x y} (hc : closure₀ M₀'.carrier = M₀'.carrier) :
∀ β γ ∈ boundary_points (closure₂ M₀'.carrier) x y,
β + γ ∈ boundary_points (closure₂ M₀'.carrier) x y := sorry
lemma mul_mem_of_boundary_points {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
{x y} (hc : closure₀ M₀'.carrier = M₀'.carrier) :
∀ β γ ∈ boundary_points (closure₂ M₀'.carrier) x y,
β * γ ∈ boundary_points (closure₂ M₀'.carrier) x y := sorry
/- The boundary points of a closed subalgebra of (X →ᵇ ℝ) over ℝ
form a subring. -/
lemma is_subring_boundary_points {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
{x y} (hc : closure₀ M₀'.carrier = M₀'.carrier) :
is_subring (boundary_points (closure₂ M₀'.carrier) x y) :=
{ zero_mem := zero_mem_of_boundary_points hc,
add_mem := add_mem_of_boundary_points hc,
neg_mem := neg_mem_of_boundary_points hc,
one_mem := one_mem_of_boundary_points hc,
mul_mem := mul_mem_of_boundary_points hc }
lemma boundary_points_range_le {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
{x y} (hc : closure₀ M₀'.carrier = M₀'.carrier) :
range (algebra_map ℝ (ℝ × ℝ)) ≤ boundary_points (closure₂ M₀'.carrier) x y :=
begin
intros z hz, cases mem_range.1 hz with r hr,
refine ⟨r • 1, _, _⟩,
apply closure_le_seq₁, rw hc,
exact subalgebra_closed_under_smul' r one_mem_of_subalgebra,
suffices : (r, r) = z,
simpa [show ∀ x, (1 : X →ᵇ ℝ) x = 1, by intro z; refl],
rw ←hr, refl
end
/- With that, we can construct a subalgebra of ℝ² with underlying
set being boundary_points (closure₂ M₀'.carrier) x y-/
def subalgebra_of_boundary_points {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
(x y) (hc : closure₀ M₀'.carrier = M₀'.carrier) :
subalgebra ℝ (ℝ × ℝ) :=
{ carrier := boundary_points (closure₂ M₀'.carrier) x y,
subring := is_subring_boundary_points hc,
range_le' := boundary_points_range_le hc}
lemma in_closure'_of_in_closoure₂ {M₀' : subalgebra ℝ (X →ᵇ ℝ)} {f : X →ᵇ ℝ}
(h : f ∈ closure₂ M₀'.carrier) (hc : closure₀ M₀'.carrier = M₀'.carrier) :
∀ x y : X, x ≠ y → (f x, f y) ∈ closure' (boundary_points M₀'.carrier x y) :=
begin
intros x y hxy, right,
rw in_closure₂_iff_dense_at_points at h,
choose F hF₀ hF₁ using λ (n : ℕ),
h (1 / (n + 1)) (nat.one_div_pos_of_nat) x y,
refine ⟨λ n, (F n x, F n y), λ n, ⟨F n, hc ▸ hF₀ n, rfl⟩, λ ε hε, _⟩,
cases exists_nat_gt (1 / ε) with N hN,
refine ⟨N, λ n hn, _⟩,
suffices : abs (F n x - f x) < ε ∧ abs (F n y - f y) < ε,
unfold dist, simp [this],
split; rw abs_sub;
try { refine lt_of_lt_of_le (hF₁ n).1 _ <|> refine lt_of_lt_of_le (hF₁ n).2 _ };
refine one_div_le_of_one_div_le_of_pos hε (le_trans (le_of_lt hN) _);
norm_cast; exact le_add_right hn
end
lemma bcf_pair_sup_eq_bcf_sup_pair {u v : X →ᵇ ℝ} {x y} :
(u x, u y) ⊔ (v x, v y) = ((u ⊔ v) x, (u ⊔ v) y) := rfl
lemma bcf_pair_inf_eq_bcf_inf_pair {u v : X →ᵇ ℝ} {x y} :
(u x, u y) ⊓ (v x, v y) = ((u ⊓ v) x, (u ⊓ v) y) := rfl
lemma one_mapsto_one {x} : (1 : X →ᵇ ℝ) x = 1 := rfl
lemma in_closure₂_of_in_closure' {M₀' : subalgebra ℝ (X →ᵇ ℝ)} {f : X →ᵇ ℝ}
(hc : closure₀ M₀'.carrier = M₀'.carrier)
(h : ∀ x y : X, x ≠ y → (f x, f y) ∈ closure' (boundary_points M₀'.carrier x y)) :
f ∈ closure₂ M₀'.carrier :=
begin
rw in_closure₂_iff_dense_at_points,
intros ε hε x y,
cases em (x = y) with hxy hxy,
have : (f x, f x) ∈ closure' (boundary_points M₀'.carrier x y),
refine le_closure' ⟨(f x) • 1, _⟩,
refine ⟨subalgebra_closed_under_smul' (f x) one_mem_of_subalgebra, _⟩,
rw ←hxy, simp [one_mapsto_one],
cases this with h' h',
{ rcases h' with ⟨r, t, ⟨u, hu₀, hu₁⟩, ⟨v, hv₀, hv₁⟩, hrt⟩,
cases hrt, rw hc,
{ refine ⟨u ⊔ v, (hc ▸ closure₀_closed_with_sup) hu₀ hv₀, _⟩,
rw [←hu₁, ←hv₁, bcf_pair_sup_eq_bcf_sup_pair] at hrt,
rw [(prod.mk.inj hrt).1, (prod.mk.inj hrt).2, hxy], simpa },
{ refine ⟨u ⊓ v, closure₀_closed_with_inf _ _, _⟩;
try { rw hc, assumption },
rw [←hu₁, ←hv₁, bcf_pair_inf_eq_bcf_inf_pair] at hrt,
rw [(prod.mk.inj hrt).1, (prod.mk.inj hrt).2, hxy], simpa } },
{ rcases h' with ⟨s, hs₀, hs₁⟩,
cases hs₁ ε hε with N hN,
rcases hs₀ N with ⟨g, hg₀, hg₁⟩,
refine ⟨g, _, _⟩, rw hc, assumption,
have := hN N (le_refl N),
rw ←hg₁ at this, unfold dist at this, simp at this,
split; rw [abs_sub]; simp only [this],
convert this.2, rwa hxy },
cases h x y hxy with h' h',
{ rcases h' with ⟨r, t, ⟨u, hu₀, hu₁⟩, ⟨v, hv₀, hv₁⟩, hrt⟩,
cases hrt, rw hc,
{ refine ⟨u ⊔ v, (hc ▸ closure₀_closed_with_sup) hu₀ hv₀, _⟩,
rw [←hu₁, ←hv₁, bcf_pair_sup_eq_bcf_sup_pair] at hrt,
rw [(prod.mk.inj hrt).1, (prod.mk.inj hrt).2], simpa },
{ refine ⟨u ⊓ v, closure₀_closed_with_inf _ _, _⟩;
try { rw hc, assumption },
rw [←hu₁, ←hv₁, bcf_pair_inf_eq_bcf_inf_pair] at hrt,
rw [(prod.mk.inj hrt).1, (prod.mk.inj hrt).2], simpa } },
{ rcases h' with ⟨s, hs₀, hs₁⟩,
cases hs₁ ε hε with N hN,
rcases hs₀ N with ⟨g, hg₀, hg₁⟩,
refine ⟨g, _, _⟩, rw hc, assumption,
have := hN N (le_refl N),
rw ←hg₁ at this, unfold dist at this, simp at this,
split; rw abs_sub; simp only [this] }
end
lemma in_closure₂_iff_in_closure' {M₀' : subalgebra ℝ (X →ᵇ ℝ)} {f : X →ᵇ ℝ}
(hc : closure₀ M₀'.carrier = M₀'.carrier) :
f ∈ closure₂ M₀'.carrier ↔
∀ x y : X, x ≠ y → (f x, f y) ∈ closure' (boundary_points M₀'.carrier x y) :=
⟨λ h, in_closure'_of_in_closoure₂ h hc, λ h, in_closure₂_of_in_closure' hc h⟩
/- With this, we can formulate the relation between M₀ and M₀'(x, y) formally, i.e.
if M₀, M₁ ⊆ M,
hM : M₀ = closure₂ M₀ and M₁ = closure₂ M₁
hb : ∀ x, y ∈ X, M₀*(x, y) = M₁*(x, y)
then M₀ = M₁. -/
lemma boundary_points_eq_of_eq (M₀' M₁' : subalgebra ℝ (X →ᵇ ℝ))
(h : M₀'.carrier = M₁'.carrier) :
∀ x y : X, x ≠ y → boundary_points M₀'.carrier x y = boundary_points M₁'.carrier x y :=
λ _ _ _, by rw h
lemma closure₀_eq_of_closure₂_eq {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
(h : closure₂ M₀'.carrier = M₀'.carrier) :
closure₀ M₀'.carrier = M₀'.carrier := sorry
lemma eq_of_boundary_points_eq (M₀' M₁' : subalgebra ℝ (X →ᵇ ℝ))
(h : ∀ x y : X, x ≠ y → boundary_points M₀'.carrier x y = boundary_points M₁'.carrier x y)
(hM₀ : M₀'.carrier = closure₂ M₀'.carrier)
(hM₁ : M₁'.carrier = closure₂ M₁'.carrier) : M₀'.carrier = M₁'.carrier :=
begin
ext f, split; intro hf;
{ try {rw hM₀ <|> rw hM₁}, try {rw hM₀ at hf <|> rw hM₁ at hf},
try { rw in_closure₂_iff_in_closure' (closure₀_eq_of_closure₂_eq hM₁.symm),
rw in_closure₂_iff_in_closure' (closure₀_eq_of_closure₂_eq hM₀.symm) at hf },
try { rw in_closure₂_iff_in_closure' (closure₀_eq_of_closure₂_eq hM₁.symm) at hf,
rw in_closure₂_iff_in_closure' (closure₀_eq_of_closure₂_eq hM₀.symm) },
intros x y hxy, try {rw ←h x y <|> rw h x y},
exact hf x y hxy, assumption }
end
theorem eq_iff_boundary_points_eq (M₀' M₁' : subalgebra ℝ (X →ᵇ ℝ))
(hM₀ : M₀'.carrier = closure₂ M₀'.carrier)
(hM₁ : M₁'.carrier = closure₂ M₁'.carrier) :
M₀'.carrier = M₁'.carrier ↔
∀ x y : X, x ≠ y → boundary_points M₀'.carrier x y = boundary_points M₁'.carrier x y :=
⟨λ h, boundary_points_eq_of_eq _ _ h, λ h, eq_of_boundary_points_eq _ _ h hM₀ hM₁⟩
/- Now that we've reformulated the problem such that it considers points in ℝ²
rather than all bounded continuous functions, the question now becomes,
under what condition, is the boundary points of closure₂ M₀ equal to ℝ². -/
lemma closure₂_subalgebra_carrier {M₀' : subalgebra ℝ (X →ᵇ ℝ)} :
(closure₂_subalgebra M₀').carrier = closure₂ M₀'.carrier := rfl
lemma univ_subalgebra_carrier :
(univ_subalgebra.carrier : set (X →ᵇ ℝ)) = univ := rfl
theorem func_dense_iff_boundary_points_dense (M₀' : subalgebra ℝ (X →ᵇ ℝ)) :
closure₂ M₀'.carrier = univ ↔
∀ x y, x ≠ y → boundary_points (closure₂ M₀'.carrier) x y = univ :=
begin
have := eq_iff_boundary_points_eq (closure₂_subalgebra M₀') univ_subalgebra
(closure₂_of_closure₂ M₀'.carrier).symm (closure₂_of_univ).symm,
rw [closure₂_subalgebra_carrier, univ_subalgebra_carrier] at this,
split,
{ intros h x y hxy,
rw this at h, rw (h x y),
exact boundary_points_of_univ x y,
assumption },
{ intro h, rw this, intros x y hxy, rw h x y,
exact (boundary_points_of_univ x y).symm,
assumption }
end
/- Now that we have proved that given a closed subalgebra of X →ᵇ ℝ over
ℝ - M₀', boundary_points (closure₂ M₀'.carrier) x y form a subalgebra of
ℝ², we can use this fact in combination of our theorem from ralgebra.lean
concluding boundary_points (closure₂ M₀'.carrier) x y must be
{(0, 0)} ∨ {p | ∃ x : ℝ, p = (x, 0)} ∨
{p | ∃ y : ℝ, p = (0, y)} ∨ {p | ∃ z : ℝ, p = (z, z)} ∨ ℝ²
Now due to `one_mem_of_boundary_points`, we eliminate our possiblities to
{p | ∃ z : ℝ, p = (z, z)} ∨ ℝ², the first of which is not possible if
we have seperate points. -/
/- (Weierstrass-Stone's Theorem)
Let M₀ be a subalgebra of (X →ᵇ ℝ) that's closed (M₂ = closure₀ M₀)
and seperate points. Then closure₂ M₀ = univ. -/
theorem weierstrass_stone {M₀' : subalgebra ℝ (X →ᵇ ℝ)}
(hc : closure₀ M₀'.carrier = M₀'.carrier)
(hsep : has_seperate_points M₀'.carrier) :
closure₂ M₀'.carrier = univ :=
begin
rw func_dense_iff_boundary_points_dense,
intros x y hxy,
cases subalgebra_of_R2 (subalgebra_of_boundary_points x y hc),
{ suffices : ((1, 1) : ℝ × ℝ) ∈ (subalgebra_of_boundary_points x y hc).carrier,
exfalso, rw [h, mem_singleton_iff] at this,
replace this := congr_arg prod.fst this, simp at this, assumption,
exact one_mem_of_boundary_points hc },
cases h,
{ suffices : ((1, 1) : ℝ × ℝ) ∈ (subalgebra_of_boundary_points x y hc).carrier,
exfalso, rw h at this, cases this with r hr,
simp at hr, assumption,
exact one_mem_of_boundary_points hc },
cases h,
{ suffices : ((1, 1) : ℝ × ℝ) ∈ (subalgebra_of_boundary_points x y hc).carrier,
exfalso, rw h at this, cases this with r hr,
simp at hr, assumption,
exact one_mem_of_boundary_points hc },
cases h,
{ rcases hsep x y hxy with ⟨f, hf₀, hf₁⟩,
suffices : ((f x, f y) : ℝ × ℝ) ∈ (subalgebra_of_boundary_points x y hc).carrier,
exfalso, rw h at this, cases this with r hr,
apply hf₁, replace this : f x = r := congr_arg prod.fst hr,
rw this, simp [show f y = r, by exact congr_arg prod.snd hr],
refine ⟨f, _, rfl⟩, apply closure_le_seq₁, rwa hc },
{ exact h }
end |
ba1d2f36fa2f1432d90a67ebcac3a3c54ad7b6f0 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /library/init/meta/converter.lean | 3a2454480bbbe13c5ec76d375e47e7839be3e727 | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,992 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
Converter monad for building simplifiers.
-/
prelude
import init.meta.tactic init.meta.simp_tactic
import init.meta.congr_lemma init.meta.match_tactic
open tactic
meta structure conv_result (α : Type) :=
(val : α) (rhs : expr) (proof : option expr)
meta def conv (α : Type) : Type :=
name → expr → tactic (conv_result α)
namespace conv
meta def lhs : conv expr :=
λ r e, return ⟨e, e, none⟩
meta def change (new_p : pexpr) : conv unit :=
λ r e, do
new_e ← to_expr new_p,
unify e new_e,
return ⟨(), new_e, none⟩
protected meta def pure {α : Type} : α → conv α :=
λ a r e, return ⟨a, e, none⟩
private meta def join_proofs (r : name) (o₁ o₂ : option expr) : tactic (option expr) :=
match o₁, o₂ with
| none, _ := return o₂
| _, none := return o₁
| some p₁, some p₂ := do
env ← get_env,
match env.trans_for r with
| some trans := do pr ← mk_app trans [p₁, p₂], return $ some pr
| none := fail $ "converter failed, relation '" ++ r.to_string ++ "' is not transitive"
end
end
protected meta def seq {α β : Type} (c₁ : conv (α → β)) (c₂ : conv α) : conv β :=
λ r e, do
⟨fn, e₁, pr₁⟩ ← c₁ r e,
⟨a, e₂, pr₂⟩ ← c₂ r e₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨fn a, e₂, pr⟩
protected meta def fail {α : Type} : conv α :=
λ r e, failed
protected meta def orelse {α : Type} (c₁ : conv α) (c₂ : conv α) : conv α :=
λ r e, c₁ r e <|> c₂ r e
protected meta def map {α β : Type} (f : α → β) (c : conv α) : conv β :=
λ r e, do
⟨a, e₁, pr⟩ ← c r e,
return ⟨f a, e₁, pr⟩
protected meta def bind {α β : Type} (c₁ : conv α) (c₂ : α → conv β) : conv β :=
λ r e, do
⟨a, e₁, pr₁⟩ ← c₁ r e,
⟨b, e₂, pr₂⟩ ← c₂ a r e₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨b, e₂, pr⟩
meta instance : monad conv :=
{ map := @conv.map,
pure := @conv.pure,
bind := @conv.bind,
id_map := undefined, pure_bind := undefined, bind_assoc := undefined,
bind_pure_comp_eq_map := undefined, bind_map_eq_seq := undefined }
meta instance : alternative conv :=
{ conv.monad with
failure := @conv.fail,
orelse := @conv.orelse }
meta def whnf (md : transparency := reducible) : conv unit :=
λ r e, do n ← tactic.whnf e md, return ⟨(), n, none⟩
meta def dsimp : conv unit :=
λ r e, do s ← simp_lemmas.mk_default, n ← s.dsimplify e, return ⟨(), n, none⟩
meta def try (c : conv unit) : conv unit :=
c <|> return ()
meta def tryb (c : conv unit) : conv bool :=
(c >> return tt) <|> return ff
meta def trace {α : Type} [has_to_tactic_format α] (a : α) : conv unit :=
λ r e, tactic.trace a >> return ⟨(), e, none⟩
meta def trace_lhs : conv unit :=
lhs >>= trace
meta def apply_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit :=
λ r e, do
(new_e, pr) ← s.rewrite prove r e,
return ⟨(), new_e, some pr⟩
meta def apply_lemmas (s : simp_lemmas) : conv unit :=
apply_lemmas_core s failed
/- αdapter for using iff-lemmas as eq-lemmas -/
meta def apply_propext_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit :=
λ r e, do
guard (r = `eq),
(new_e, pr) ← s.rewrite prove `iff e,
new_pr ← mk_app `propext [pr],
return ⟨(), new_e, some new_pr⟩
meta def apply_propext_lemmas (s : simp_lemmas) : conv unit :=
apply_propext_lemmas_core s failed
private meta def mk_refl_proof (r : name) (e : expr) : tactic expr :=
do env ← get_env,
match (environment.refl_for env r) with
| (some refl) := do pr ← mk_app refl [e], return pr
| none := fail $ "converter failed, relation '" ++ r.to_string ++ "' is not reflexive"
end
meta def to_tactic (c : conv unit) : name → expr → tactic (expr × expr) :=
λ r e, do
⟨u, e₁, o⟩ ← c r e,
match o with
| none := do p ← mk_refl_proof r e, return (e₁, p)
| some p := return (e₁, p)
end
meta def lift_tactic {α : Type} (t : tactic α) : conv α :=
λ r e, do a ← t, return ⟨a, e, none⟩
meta def apply_simp_set (attr_name : name) : conv unit :=
lift_tactic (get_user_simp_lemmas attr_name) >>= apply_lemmas
meta def apply_propext_simp_set (attr_name : name) : conv unit :=
lift_tactic (get_user_simp_lemmas attr_name) >>= apply_propext_lemmas
meta def skip : conv unit :=
return ()
meta def repeat : conv unit → conv unit
| c r lhs :=
(do
⟨_, rhs₁, pr₁⟩ ← c r lhs,
guard (¬ lhs =ₐ rhs₁),
⟨_, rhs₂, pr₂⟩ ← repeat c r rhs₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨(), rhs₂, pr⟩)
<|> return ⟨(), lhs, none⟩
meta def first {α : Type} : list (conv α) → conv α
| [] := conv.fail
| (c::cs) := c <|> first cs
meta def match_pattern (p : pattern) : conv unit :=
λ r e, tactic.match_pattern p e >> return ⟨(), e, none⟩
meta def mk_match_expr (p : pexpr) : tactic (conv unit) :=
do new_p ← pexpr_to_pattern p,
return (λ r e, tactic.match_pattern new_p e >> return ⟨(), e, none⟩)
meta def match_expr (p : pexpr) : conv unit :=
λ r e, do
new_p ← pexpr_to_pattern p,
tactic.match_pattern new_p e >> return ⟨(), e, none⟩
meta def funext (c : conv unit) : conv unit :=
λ r lhs, do
guard (r = `eq),
(expr.lam n bi d b) ← return lhs,
let aux_type := expr.pi n bi d (expr.const `true []),
(result, _) ← solve_aux aux_type $ do {
x ← intro1,
c_result ← c r (b.instantiate_var x),
let rhs := expr.lam n bi d (c_result.rhs.abstract x),
match c_result.proof : _ → tactic (conv_result unit) with
| some pr := do
let aux_pr := expr.lam n bi d (pr.abstract x),
new_pr ← mk_app `funext [lhs, rhs, aux_pr],
return ⟨(), rhs, some new_pr⟩
| none := return ⟨(), rhs, none⟩
end },
return result
meta def congr_core (c_f c_a : conv unit) : conv unit :=
λ r lhs, do
guard (r = `eq),
(expr.app f a) ← return lhs,
f_type ← infer_type f >>= tactic.whnf,
guard (f_type.is_arrow),
⟨(), new_f, of⟩ ← try c_f r f,
⟨(), new_a, oa⟩ ← try c_a r a,
rhs ← return $ new_f new_a,
match of, oa with
| none, none :=
return ⟨(), rhs, none⟩
| none, some pr_a := do
pr ← mk_app `congr_arg [a, new_a, f, pr_a],
return ⟨(), new_f new_a, some pr⟩
| some pr_f, none := do
pr ← mk_app `congr_fun [f, new_f, pr_f, a],
return ⟨(), rhs, some pr⟩
| some pr_f, some pr_a := do
pr ← mk_app `congr [f, new_f, a, new_a, pr_f, pr_a],
return ⟨(), rhs, some pr⟩
end
meta def congr (c : conv unit) : conv unit :=
congr_core c c
meta def bottom_up (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, failed)
(λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt))
r e,
return ⟨(), new_e, some pr⟩
meta def top_down (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def find (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e,
(do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff))
<|>
return ((), e, none, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def find_pattern (pat : pattern) (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, do
matched ← (tactic.match_pattern pat e >> return tt) <|> return ff,
if matched
then do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff)
else return ((), e, none, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def findp : pexpr → conv unit → conv unit :=
λ p c r e, do
pat ← pexpr_to_pattern p,
find_pattern pat c r e
meta def conversion (c : conv unit) : tactic unit :=
do (r, lhs, rhs) ← (target_lhs_rhs <|> fail "conversion failed, target is not of the form 'lhs R rhs'"),
(new_lhs, pr) ← to_tactic c r lhs,
(unify new_lhs rhs <|>
do new_lhs_fmt ← pp new_lhs,
rhs_fmt ← pp rhs,
fail (to_fmt "conversion failed, expected" ++
rhs_fmt.indent 4 ++ format.line ++ "provided" ++
new_lhs_fmt.indent 4)),
exact pr
end conv
|
edf5b34bc264aa432f3adedc523889ccffb31bfe | 5df84495ec6c281df6d26411cc20aac5c941e745 | /src/formal_ml/pac_bounds.lean | b5ffeadd887ad919aff2b5a83be8ed9525f11db9 | [
"Apache-2.0"
] | permissive | eric-wieser/formal-ml | e278df5a8df78aa3947bc8376650419e1b2b0a14 | 630011d19fdd9539c8d6493a69fe70af5d193590 | refs/heads/master | 1,681,491,589,256 | 1,612,642,743,000 | 1,612,642,743,000 | 360,114,136 | 0 | 0 | Apache-2.0 | 1,618,998,189,000 | 1,618,998,188,000 | null | UTF-8 | Lean | false | false | 15,769 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import measure_theory.measurable_space
import measure_theory.measure_space
import measure_theory.outer_measure
import measure_theory.lebesgue_measure
import measure_theory.integration
import measure_theory.borel_space
import data.set.countable
import formal_ml.measurable_space
import formal_ml.probability_space
import formal_ml.real_random_variable
import data.complex.exponential
import formal_ml.ennreal
import formal_ml.nnreal
import formal_ml.sum
import formal_ml.exp_bound
import formal_ml.classical
structure PAC_problem :=
(Ω:Type*) -- Underlying outcome type
(p:probability_space Ω) -- underlying probability space
(β:Type*) -- instance type
(Mβ:measurable_space β) -- Measurable space for the instances
(γ:Type*) -- label type
(Mγ:measurable_space γ) -- Measurable space for the labels
(HMEγ:has_measurable_equality Mγ) -- Measurable equality for the labels
(Eγ:encodable γ) -- Encodable labels is very useful
(Di:Type*) -- example index type
(FDi:fintype Di) -- number of examples are finite
(EDi:encodable Di) -- example index is encodable
-- see trunc_encodable_of_fintype
(Hi:Type*) -- hypothesis index type
(FHi:fintype Hi) -- number of examples are finite
(EHi:encodable Hi) -- hypothesis index is encodable
-- see trunc_encodable_of_fintype
(H:Hi → (Mβ →ₘ Mγ)) -- hypothesis space
(D:Di → (p →ᵣ (Mβ ×ₘ Mγ))) -- example distribution
(IID:random_variables_IID D) -- examples are IID
(has_example:inhabited Di) -- there exists an example
--example_instance P j is the jth instance (the features of an example)
def example_instance (P:PAC_problem)
(j:P.Di):random_variable P.p P.Mβ :=
(mf_fst) ∘r (P.D j)
--the measurable space on the examples.
def PAC_problem.Mβγ (P:PAC_problem):
measurable_space (P.β × P.γ) := P.Mβ ×ₘ P.Mγ
/-
rv_label_eq X Y is the event that X and Y are equal, where X and Y are labels.
-/
def rv_label_eq (P:PAC_problem)
(X Y:random_variable P.p P.Mγ):event P.p :=
@random_variable_eq P.Ω P.p P.γ P.Mγ P.HMEγ X Y
/-
rv_label_ne X Y is the event that X and Y are not equal, where X and Y are labels.
-/
def rv_label_ne (P:PAC_problem)
(X Y:random_variable P.p P.Mγ):event P.p :=
@random_variable_ne P.Ω P.p P.γ P.Mγ P.HMEγ X Y
/-
example_label P j is the label of the jth example.
-/
def example_label (P:PAC_problem)
(j:P.Di):P.p →ᵣ P.Mγ :=
mf_snd ∘r (P.D j)
/-
example_classification P i j is the classification by the ith hypothesis of the jth example.
-/
def example_classification (P:PAC_problem)
(i:P.Hi) (j:P.Di):P.p →ᵣ P.Mγ :=
(P.H i) ∘r (example_instance P j)
/-
example_correct P i j is whether the ith hypothesis is correct on the jth example.
-/
def example_correct (P:PAC_problem)
(i:P.Hi) (j:P.Di):event P.p :=
rv_label_eq P (example_classification P i j) (example_label P j)
/-
example_error P i j is whether the ith hypothesis made a mistake on the jth example.
-/
def example_error (P:PAC_problem)
(i:P.Hi) (j:P.Di):event P.p :=
rv_label_ne P (example_classification P i j) (example_label P j)
/-
num_examples P is the number of examples in the problem.
This is defined as the cardinality of the index type of the examples.
-/
def num_examples (P:PAC_problem):nat
:= @fintype.card P.Di P.FDi
/-
The number of examples is the number of elements of type P.Di.
P.FDi.elems is the set of all elements in P.Di, and P.FDi.elems.card is the cardinality of
P.FDi.elems.
-/
lemma num_examples_eq_finset_card (P:PAC_problem):
num_examples P = P.FDi.elems.card :=
begin
refl,
end
/-
The number of examples do not equal zero.
-/
lemma num_examples_ne_zero (P:PAC_problem):
num_examples P ≠ 0 :=
begin
unfold num_examples,
apply @card_ne_zero_of_inhabited P.Di P.has_example P.FDi,
end
/-
The number of hypotheses.
-/
def num_hypotheses (P:PAC_problem):nat
:= @fintype.card P.Hi P.FHi
/-
The number of errors on the training set, divided by the size of the training set.
training_error P i = (∑ (j:P.Di), (example_error P i j))/(num_exmaples P)
TODO: replace with average_indicator.
-/
noncomputable def training_error (P:PAC_problem)
(i:P.Hi):P.p →ᵣ (borel nnreal) :=
average_identifier (example_error P i) P.FDi
-- (count_finset_rv P.FDi.elems (example_error P i)) * (to_nnreal_rv ((num_examples P):nnreal)⁻¹)
/-
The expected test error.
The test error is equal to the expected training error. Because we have not defined a generating
process for examples, we use this as the definition.
-/
noncomputable def test_error (P:PAC_problem)
(i:P.Hi):ennreal := E[training_error P i]
/-
fake_hypothesis P ε i is the event that hypothesis i has zero training error, but has
test error > ε.
-/
noncomputable def fake_hypothesis (P:PAC_problem) (ε:nnreal)
(i:P.Hi):event P.p :=
((training_error P i) =ᵣ 0) ∧ (event_const (test_error P i > ε))
/-
The event that all hypotheses with training error zero have test error ≤ ε.
-/
noncomputable def approximately_correct_event (P:PAC_problem)
(ε:nnreal):event P.p :=
enot (eany_fintype P.FHi (fake_hypothesis P ε))
def probably_approximately_correct (P:PAC_problem)
(ε:nnreal) (δ:nnreal):Prop :=
1 - δ ≤ Pr[approximately_correct_event P ε]
lemma enot_example_correct_eq_example_error
(P:PAC_problem) (i:P.Hi) (j:P.Di):enot (example_correct P i j) = (example_error P i j) :=
begin
apply event.eq,
unfold example_error example_correct rv_label_ne rv_label_eq,
refl,
end
lemma enot_example_error_eq_example_correct
(P:PAC_problem) (i:P.Hi) (j:P.Di):enot (example_error P i j) = (example_correct P i j) :=
begin
rw ← enot_example_correct_eq_example_error,
simp,
end
lemma example_correct_iff_not_example_error
(P:PAC_problem) (i:P.Hi) (j:P.Di) (ω:P.Ω): ω ∉ (example_error P i j).val ↔
ω ∈ (example_correct P i j).val :=
begin
rw ← enot_example_error_eq_example_correct,
simp,
end
lemma example_error_IID (P:PAC_problem) (i:P.Hi):
@events_IID P.Ω P.Di P.p (example_error P i) :=
begin
/-
To prove that the errors of a particular hypothesis are IID, we must use an alternate
formulation of the example_error events. Specifically, instead of constructing a hierarchy
of random variables, we must make a leap from the established IID random variable
(the data), construct another IID random variable (the product of
the classification and the label), and show that the set of all label/classification pairs
that aren't equal are a measurable set (because has_measurable_eq Mγ).
The indexed set of events of each IID random variable being in a measurable set is IID,
so the result holds.
Note that while this proof looks a little long, most of the proof is just unwrapping
the traditional and internal definitions of example error, and then using simp to show that
they are equal on all outcomes.
-/
let Y:(P.Mβ ×ₘ P.Mγ)→ₘ (P.Mγ ×ₘ P.Mγ) := prod_measurable_fun ((P.H i) ∘m (mf_fst)) (mf_snd),
begin
let S:@measurable_setB _ (P.Mγ ×ₘ P.Mγ) := @measurable_setB_ne P.γ P.Mγ P.HMEγ,
begin
have A1:@random_variables_IID P.Ω P.p P.Di (P.γ × P.γ) (P.Mγ ×ₘ P.Mγ)
(λ j:P.Di, Y ∘r (P.D j) ),
{
apply compose_IID,
apply P.IID,
},
have A2:@events_IID P.Ω P.Di P.p (λ j:P.Di, @rv_event P.Ω P.p _ (P.Mγ ×ₘ P.Mγ) (Y ∘r (P.D j)) S),
{
apply rv_event_IID,
apply A1,
},
have A3: (λ j:P.Di, @rv_event P.Ω P.p _ (P.Mγ ×ₘ P.Mγ) (Y ∘r (P.D j)) S) = example_error P i,
{
apply funext,
intro j,
apply event.eq,
unfold example_error example_label example_classification rv_label_ne example_instance,
refl,
},
rw ← A3,
exact A2,
end
end
end
lemma example_correct_IID (P:PAC_problem) (i:P.Hi):
@events_IID P.Ω P.Di P.p (example_correct P i) :=
begin
/-
Similar to example_error_IID. Theoretically, we could prove it from example_error_IID.
However, it is easier for now to prove it from first principles.
-/
let Y:(P.Mβ ×ₘ P.Mγ)→ₘ (P.Mγ ×ₘ P.Mγ) := prod_measurable_fun ((P.H i) ∘m (mf_fst)) (mf_snd),
begin
let S:@measurable_setB _ (P.Mγ ×ₘ P.Mγ) := {
val := {x:P.γ × P.γ|x.fst = x.snd},
property := P.HMEγ.measurable_set_eq,
},
begin
have A1:@random_variables_IID P.Ω P.p P.Di (P.γ × P.γ) (P.Mγ ×ₘ P.Mγ)
(λ j:P.Di, Y ∘r (P.D j) ),
{
apply compose_IID,
apply P.IID,
},
have A2:@events_IID P.Ω P.Di P.p (λ j:P.Di, @rv_event P.Ω P.p _ (P.Mγ ×ₘ P.Mγ) (Y ∘r (P.D j)) S),
{
apply rv_event_IID,
apply A1,
},
have A3: (λ j:P.Di, @rv_event P.Ω P.p _ (P.Mγ ×ₘ P.Mγ) (Y ∘r (P.D j)) S) = example_correct P i,
{
apply funext,
intro j,
apply event.eq,
unfold example_correct example_label example_classification rv_label_eq example_instance,
refl,
},
rw ← A3,
exact A2,
end
end
end
lemma example_error_identical (P:PAC_problem) (i:P.Hi) (j j':P.Di):
Pr[example_error P i j] = Pr[example_error P i j'] :=
begin
have A1:@events_IID P.Ω P.Di P.p (example_error P i),
{
apply example_error_IID,
},
unfold events_IID at A1,
cases A1 with A2 A3,
apply A3,
end
--set_option pp.all true
--set_option pp.coercions true
lemma test_error_training_mistake (P:PAC_problem) (i:P.Hi) (j:P.Di):
(Pr[example_error P i j]:ennreal) = (test_error P i) :=
begin
have A1:E[(count_finset_rv P.FDi.elems (example_error P i)) *
(to_nnreal_rv ((num_examples P):nnreal)⁻¹)]=(test_error P i),
{
unfold test_error,
refl,
},
have A2:(test_error P i)=E[(count_finset_rv P.FDi.elems (example_error P i))]
* ((num_examples P):ennreal)⁻¹,
{
rw ← A1,
rw scalar_expected_value,
rw ennreal.coe_inv,
have A2A:(((num_examples P):nnreal)⁻¹:ennreal)=((num_examples P):ennreal)⁻¹,
{
simp,
},
rw A2A,
simp,
apply num_examples_ne_zero,
},
have A3:E[(count_finset_rv P.FDi.elems (example_error P i))]=
P.FDi.elems.sum (λ k, Pr[(example_error P i k)]),
{
apply linear_count_finset_rv,
},
have A4:∀ k, (λ k, (Pr[(example_error P i k)]:ennreal)) k = (Pr[(example_error P i j)]:ennreal),
{
intro k,
simp,
apply (example_error_identical P i _ j),
},
have A5:E[(count_finset_rv P.FDi.elems (example_error P i))]=
P.FDi.elems.card * (Pr[(example_error P i j)]:ennreal),
{
rw A3,
apply finset_sum_const,
apply A4,
},
have A6:E[(count_finset_rv P.FDi.elems (example_error P i))]=
(num_examples P) * (Pr[(example_error P i j)]:ennreal),
{
rw A5,
rw num_examples_eq_finset_card,
},
rw A6 at A2,
rw mul_comm at A2,
rw ← mul_assoc at A2,
have A7:((num_examples P):ennreal)⁻¹ * ((num_examples P):ennreal) = 1,
{
rw mul_comm,
apply ennreal.mul_inv_cancel,
{
simp,
apply (@num_examples_ne_zero P),
},
{
simp,
}
},
rw A7 at A2,
simp at A2,
symmetry,
exact A2,
end
lemma test_error_training_mistake2 (P:PAC_problem) (i:P.Hi) (j:P.Di):
Pr[example_error P i j] = (test_error P i).to_nnreal :=
begin
symmetry,
apply ennreal_coe_eq_lift,
rw test_error_training_mistake,
end
lemma example_correct_prob (P:PAC_problem) (i:P.Hi) (j:P.Di):
Pr[example_correct P i j] = 1 - (test_error P i).to_nnreal :=
begin
rw ← enot_example_error_eq_example_correct,
rw ← Pr_one_minus_eq_not,
rw test_error_training_mistake2,
end
lemma test_error_ne_top (P:PAC_problem) (i:P.Hi):
(test_error P i) ≠ ⊤ :=
begin
rw ← test_error_training_mistake,
simp,
apply P.has_example.default,
end
/-
event_IID_pow :
∀ {α : Type u_1} [Mα : measurable_space α] {p : probability_measure α} {β : Type u_2} [F : fintype β]
[I : inhabited β] {γ : Type u_3} [Mγ : measurable_space γ] (A : β → event p) (S : finset β),
events_IID A → Pr[eall_finset S A] = Pr[A (inhabited.default β)] ^ finset.card S
-/
--sorry
set_option pp.implicit true
lemma training_error_zero_prob (P:PAC_problem) (i:P.Hi):
Pr[training_error P i =ᵣ 0] =
(Pr[(example_correct P i P.has_example.default)])^(num_examples P) :=
begin
unfold training_error,
rw @Pr_average_identifier_eq_zero P.Di P.Ω P.p (example_error P i) P.FDi P.has_example.default,
rw ← enot_example_correct_eq_example_error,
rw Pr_one_minus_not_eq,
rw num_examples_eq_finset_card,
unfold fintype.card,
refl,
apply example_error_IID,
end
lemma fake_hypothesis_prob (P:PAC_problem)
(ε:nnreal) (i:P.Hi):Pr[fake_hypothesis P ε i]≤(1-ε)^(num_examples P) :=
begin
unfold fake_hypothesis,
have A1:decidable (test_error P i ≤ ↑ε),
{
apply linear_order.decidable_le,
},
cases A1,
{
apply le_trans,
apply Pr_eand_le_left,
--Note: this could be <.
have B1:↑ε ≤ test_error P i,
{
apply le_of_not_le A1,
},
have B2:ε ≤ (test_error P i).to_nnreal,
{
apply ennreal_le_to_nnreal_of_ennreal_le_of_ne_top,
apply test_error_ne_top,
exact B1,
},
rw training_error_zero_prob,
rw example_correct_prob,
apply nnreal_pow_mono,
apply nnreal_sub_le_sub_of_le,
--ε ≤ (test_error P i).to_nnreal
exact B2,
},
{
apply le_trans,
apply Pr_eand_le_right,
rw Pr_event_const_false,
{
simp,
},
{
rw ← le_iff_not_gt,
exact A1,
},
},
end
lemma fake_hypothesis_prob2 (P:PAC_problem)
(ε:nnreal) (i:P.Hi):
Pr[fake_hypothesis P ε i] ≤ nnreal.exp (- ε * (num_examples P)) :=
begin
apply le_trans,
apply fake_hypothesis_prob,
apply nnreal_exp_bound2,
end
lemma eany_fake_hypothesis_prob (P:PAC_problem)
(ε:nnreal):
Pr[ eany_fintype P.FHi (fake_hypothesis P ε)] ≤ (num_hypotheses P) * nnreal.exp (- ε * (num_examples P)) :=
begin
apply eany_fintype_bound2,
intro,
apply fake_hypothesis_prob2,
end
lemma pac_bound (P:PAC_problem)
(ε:nnreal):
(1:nnreal) - (num_hypotheses P) * nnreal.exp (-(ε:real) * (num_examples P:real)) ≤
Pr[approximately_correct_event P ε] :=
begin
have A1:Pr[approximately_correct_event P ε] = 1 - Pr[eany_fintype P.FHi (fake_hypothesis P ε)],
{
symmetry,
unfold approximately_correct_event,
apply Pr_one_minus_eq_not (eany_fintype P.FHi (fake_hypothesis P ε)),
},
rw A1,
apply nnreal_sub_le_left,
have A2:Pr[ eany_fintype P.FHi (fake_hypothesis P ε)]
≤ (num_hypotheses P) * nnreal.exp (- ε * (num_examples P)),
{
apply eany_fake_hypothesis_prob,
},
apply A2,
end
lemma pac_bound2 (P:PAC_problem) (ε:nnreal):
probably_approximately_correct P ε
((num_hypotheses P) * nnreal.exp (-ε * (num_examples P))) :=
begin
unfold probably_approximately_correct,
apply pac_bound,
end
|
bba536af8e0f6b403d352643885615fe42335c93 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Tactic/Location.lean | 6e9134d16e5e5ee1fb4d99fa3dc2d86512ff5a13 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 2,301 | 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.Tactic.Basic
import Lean.Elab.Tactic.ElabTerm
namespace Lean.Elab.Tactic
/-- Denotes a set of locations where a tactic should be applied for the main goal. See also `withLocation`. -/
inductive Location where
/-- Apply the tactic everywhere. -/
| wildcard
/-- `hypotheses` are hypothesis names in the main goal that the tactic should be applied to.
If `type` is true, then the tactic should also be applied to the target type. -/
| targets (hypotheses : Array Syntax) (type : Bool)
/-
Recall that
```
syntax locationWildcard := "*"
syntax locationHyp := (colGt term:max)+ ("⊢" <|> "|-")?
syntax location := withPosition("at " locationWildcard <|> locationHyp)
```
-/
def expandLocation (stx : Syntax) : Location :=
let arg := stx[1]
if arg.getKind == ``Parser.Tactic.locationWildcard then
Location.wildcard
else
Location.targets arg[0].getArgs (!arg[1].isNone)
def expandOptLocation (stx : Syntax) : Location :=
if stx.isNone then
Location.targets #[] true
else
expandLocation stx[0]
open Meta
/-- Runs the given `atLocal` and `atTarget` methods on each of the locations selected by the given `loc`.
If any of the selected tactic applications fail, it will call `failed` with the main goal mvar.
-/
def withLocation (loc : Location) (atLocal : FVarId → TacticM Unit) (atTarget : TacticM Unit) (failed : MVarId → TacticM Unit) : TacticM Unit := do
match loc with
| Location.targets hyps type =>
hyps.forM fun hyp => withMainContext do
let fvarId ← getFVarId hyp
atLocal fvarId
if type then
atTarget
| Location.wildcard =>
let worked ← tryTactic <| withMainContext <| atTarget
withMainContext do
let mut worked := worked
-- We must traverse backwards because the given `atLocal` may use the revert/intro idiom
for fvarId in (← getLCtx).getFVarIds.reverse do
if (← fvarId.getDecl).isImplementationDetail then
continue
worked := worked || (← tryTactic <| withMainContext <| atLocal fvarId)
unless worked do
failed (← getMainGoal)
end Lean.Elab.Tactic
|
7df3f516926f70f0bd7979a415fa48a668ac8453 | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/algebra/big_operators/nat_antidiagonal.lean | 07df0107953849b922a6fb54740433c4ce513898 | [
"Apache-2.0"
] | permissive | spolu/mathlib | bacf18c3d2a561d00ecdc9413187729dd1f705ed | 480c92cdfe1cf3c2d083abded87e82162e8814f4 | refs/heads/master | 1,671,684,094,325 | 1,600,736,045,000 | 1,600,736,045,000 | 297,564,749 | 1 | 0 | null | 1,600,758,368,000 | 1,600,758,367,000 | null | UTF-8 | Lean | false | false | 1,034 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import data.finset.nat_antidiagonal
import algebra.big_operators.basic
/-!
# Big operators for `nat_antidiagonal`
This file contains theorems relevant to big operators over `finset.nat.antidiagonal`.
-/
open_locale big_operators
variables {α : Type*} [add_comm_monoid α]
namespace finset
namespace nat
lemma sum_antidiagonal_succ {n : ℕ} {f : ℕ × ℕ → α} :
(antidiagonal (n + 1)).sum f = f (0, n + 1) + ((antidiagonal n).map
(function.embedding.prod_map ⟨nat.succ, nat.succ_injective⟩ (function.embedding.refl _))).sum f :=
begin
rw [antidiagonal_succ, sum_insert],
intro con, rcases mem_map.1 con with ⟨⟨a,b⟩, ⟨h1, h2⟩⟩,
simp only [prod.mk.inj_iff, function.embedding.coe_fn_mk, function.embedding.refl_apply,
function.embedding.coe_prod_map, prod.map_mk] at h2,
apply nat.succ_ne_zero a h2.1,
end
end nat
end finset
|
41c58771d26b0b7a8f7d6ada9b90708bb6d271cf | c777c32c8e484e195053731103c5e52af26a25d1 | /src/order/category/FinBoolAlg.lean | 5082fe335a6ed5e5ada53ec40db2ba86a928a576 | [
"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 | 3,925 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.fintype.powerset
import order.category.BoolAlg
import order.category.FinBddDistLat
import order.hom.complete_lattice
/-!
# The category of finite boolean algebras
This file defines `FinBoolAlg`, the category of finite boolean algebras.
## TODO
Birkhoff's representation for finite Boolean algebras.
`Fintype_to_FinBoolAlg_op.left_op ⋙ FinBoolAlg.dual ≅ Fintype_to_FinBoolAlg_op.left_op`
`FinBoolAlg` is essentially small.
-/
universes u
open category_theory order_dual opposite
/-- The category of finite boolean algebras with bounded lattice morphisms. -/
structure FinBoolAlg :=
(to_BoolAlg : BoolAlg)
[is_fintype : fintype to_BoolAlg]
namespace FinBoolAlg
instance : has_coe_to_sort FinBoolAlg Type* := ⟨λ X, X.to_BoolAlg⟩
instance (X : FinBoolAlg) : boolean_algebra X := X.to_BoolAlg.str
attribute [instance] FinBoolAlg.is_fintype
@[simp] lemma coe_to_BoolAlg (X : FinBoolAlg) : ↥X.to_BoolAlg = ↥X := rfl
/-- Construct a bundled `FinBoolAlg` from `boolean_algebra` + `fintype`. -/
def of (α : Type*) [boolean_algebra α] [fintype α] : FinBoolAlg := ⟨⟨α⟩⟩
@[simp] lemma coe_of (α : Type*) [boolean_algebra α] [fintype α] : ↥(of α) = α := rfl
instance : inhabited FinBoolAlg := ⟨of punit⟩
instance large_category : large_category FinBoolAlg :=
induced_category.category FinBoolAlg.to_BoolAlg
instance concrete_category : concrete_category FinBoolAlg :=
induced_category.concrete_category FinBoolAlg.to_BoolAlg
instance has_forget_to_BoolAlg : has_forget₂ FinBoolAlg BoolAlg :=
induced_category.has_forget₂ FinBoolAlg.to_BoolAlg
instance has_forget_to_FinBddDistLat : has_forget₂ FinBoolAlg FinBddDistLat :=
{ forget₂ := { obj := λ X, FinBddDistLat.of X, map := λ X Y f, f },
forget_comp := rfl }
instance forget_to_BoolAlg_full : full (forget₂ FinBoolAlg BoolAlg) := induced_category.full _
instance forget_to_BoolAlg_faithful : faithful (forget₂ FinBoolAlg BoolAlg) :=
induced_category.faithful _
@[simps] instance has_forget_to_FinPartOrd : has_forget₂ FinBoolAlg FinPartOrd :=
{ forget₂ := { obj := λ X, FinPartOrd.of X, map := λ X Y f,
show order_hom X Y, from ↑(show bounded_lattice_hom X Y, from f) } }
instance forget_to_FinPartOrd_faithful : faithful (forget₂ FinBoolAlg FinPartOrd) :=
⟨λ X Y f g h, by { have := congr_arg (coe_fn : _ → X → Y) h, exact fun_like.coe_injective this }⟩
/-- Constructs an equivalence between finite Boolean algebras from an order isomorphism between
them. -/
@[simps] def iso.mk {α β : FinBoolAlg.{u}} (e : α ≃o β) : α ≅ β :=
{ hom := (e : bounded_lattice_hom α β),
inv := (e.symm : bounded_lattice_hom β α),
hom_inv_id' := by { ext, exact e.symm_apply_apply _ },
inv_hom_id' := by { ext, exact e.apply_symm_apply _ } }
/-- `order_dual` as a functor. -/
@[simps] def dual : FinBoolAlg ⥤ FinBoolAlg :=
{ obj := λ X, of Xᵒᵈ, map := λ X Y, bounded_lattice_hom.dual }
/-- The equivalence between `FinBoolAlg` and itself induced by `order_dual` both ways. -/
@[simps functor inverse] def dual_equiv : FinBoolAlg ≌ FinBoolAlg :=
equivalence.mk dual dual
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
end FinBoolAlg
lemma FinBoolAlg_dual_comp_forget_to_FinBddDistLat :
FinBoolAlg.dual ⋙ forget₂ FinBoolAlg FinBddDistLat =
forget₂ FinBoolAlg FinBddDistLat ⋙ FinBddDistLat.dual := rfl
/-- The powerset functor. `set` as a functor. -/
@[simps] def Fintype_to_FinBoolAlg_op : Fintype ⥤ FinBoolAlgᵒᵖ :=
{ obj := λ X, op $ FinBoolAlg.of (set X),
map := λ X Y f, quiver.hom.op $
(complete_lattice_hom.set_preimage f : bounded_lattice_hom (set Y) (set X)) }
|
9964ab43743c9185497f8eb084ec5baf69a89b6f | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20170116_POPL/native/hello.lean | 20b486b671bad1bbb23588d65e89487514dc8278 | [
"Apache-2.0"
] | permissive | leanprover/presentations | dd031a05bcb12c8855676c77e52ed84246bd889a | 3ce2d132d299409f1de269fa8e95afa1333d644e | refs/heads/master | 1,688,703,388,796 | 1,686,838,383,000 | 1,687,465,742,000 | 29,750,158 | 12 | 9 | Apache-2.0 | 1,540,211,670,000 | 1,422,042,683,000 | Lean | UTF-8 | Lean | false | false | 103 | lean | import system.io
set_option native.binary "hello"
def main : io unit :=
put_str_ln "Hello Lean!"
|
ff3977de9f08617527536116e69e09dfd97db799 | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/algebra/category/precategory.hlean | da5f6d23130ab0243dd5893c6e01b868363b5cf5 | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 12,538 | 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 types.trunc types.pi arity
open eq is_trunc pi equiv
namespace category
/-
Just as in Coq-HoTT we add two redundant fields to precategories: assoc' and id_id.
The first is to make (Cᵒᵖ)ᵒᵖ = C definitionally when C is a constructor.
The second is to ensure that the functor from the terminal category 1 ⇒ Cᵒᵖ is
opposite to the functor 1 ⇒ C.
-/
structure precategory [class] (ob : Type) : Type :=
mk' ::
(hom : ob → ob → Type)
(comp : Π⦃a b c : ob⦄, hom b c → hom a b → hom a c)
(ID : Π (a : ob), hom a a)
(assoc : Π ⦃a b c d : ob⦄ (h : hom c d) (g : hom b c) (f : hom a b),
comp h (comp g f) = comp (comp h g) f)
(assoc' : Π ⦃a b c d : ob⦄ (h : hom c d) (g : hom b c) (f : hom a b),
comp (comp h g) f = comp h (comp g f))
(id_left : Π ⦃a b : ob⦄ (f : hom a b), comp !ID f = f)
(id_right : Π ⦃a b : ob⦄ (f : hom a b), comp f !ID = f)
(id_id : Π (a : ob), comp !ID !ID = ID a)
(is_set_hom : Π(a b : ob), is_set (hom a b))
attribute precategory.is_set_hom [instance]
infixr ∘ := precategory.comp
-- input ⟶ using \--> (this is a different arrow than \-> (→))
infixl [parsing_only] ` ⟶ `:60 := precategory.hom
namespace hom
infixl ` ⟶ `:60 := precategory.hom -- if you open this namespace, hom a b is printed as a ⟶ b
end hom
abbreviation hom [unfold 2] := @precategory.hom
abbreviation comp [unfold 2] := @precategory.comp
abbreviation ID [unfold 2] := @precategory.ID
abbreviation assoc [unfold 2] := @precategory.assoc
abbreviation assoc' [unfold 2] := @precategory.assoc'
abbreviation id_left [unfold 2] := @precategory.id_left
abbreviation id_right [unfold 2] := @precategory.id_right
abbreviation id_id [unfold 2] := @precategory.id_id
abbreviation is_set_hom [unfold 2] := @precategory.is_set_hom
definition is_prop_hom_eq {ob : Type} [C : precategory ob] {x y : ob} (f g : x ⟶ y)
: is_prop (f = g) :=
_
-- the constructor you want to use in practice
protected definition precategory.mk [constructor] {ob : Type} (hom : ob → ob → Type)
[set : Π (a b : ob), is_set (hom a b)]
(comp : Π ⦃a b c : ob⦄, hom b c → hom a b → hom a c) (ID : Π (a : ob), hom a a)
(ass : Π ⦃a b c d : ob⦄ (h : hom c d) (g : hom b c) (f : hom a b),
comp h (comp g f) = comp (comp h g) f)
(idl : Π ⦃a b : ob⦄ (f : hom a b), comp (ID b) f = f)
(idr : Π ⦃a b : ob⦄ (f : hom a b), comp f (ID a) = f) : precategory ob :=
precategory.mk' hom comp ID ass (λa b c d h g f, !ass⁻¹) idl idr (λa, !idl) set
section basic_lemmas
variables {ob : Type} [C : precategory ob]
variables {a b c d : ob} {h : c ⟶ d} {g g' : hom b c} {f f' : hom a b} {i : a ⟶ a}
include C
definition id [reducible] [unfold 2] := ID a
definition id_leftright (f : hom a b) : id ∘ f ∘ id = f := !id_left ⬝ !id_right
definition comp_id_eq_id_comp (f : hom a b) : f ∘ id = id ∘ f := !id_right ⬝ !id_left⁻¹
definition id_comp_eq_comp_id (f : hom a b) : id ∘ f = f ∘ id := !id_left ⬝ !id_right⁻¹
definition hom_whisker_left (g : b ⟶ c) (p : f = f') : g ∘ f = g ∘ f' :=
ap (λx, g ∘ x) p
definition hom_whisker_right (g : c ⟶ a) (p : f = f') : f ∘ g = f' ∘ g :=
ap (λx, x ∘ g) p
/- many variants of hom_pathover are defined in .iso and .functor.basic -/
definition left_id_unique (H : Π{b} {f : hom b a}, i ∘ f = f) : i = id :=
calc i = i ∘ id : by rewrite id_right
... = id : by rewrite H
definition right_id_unique (H : Π{b} {f : hom a b}, f ∘ i = f) : i = id :=
calc i = id ∘ i : by rewrite id_left
... = id : by rewrite H
definition homset [reducible] [constructor] (x y : ob) : Set :=
Set.mk (hom x y) _
definition comp2 (p : g = g') (q : f = f') : g ∘ f = g' ∘ f' :=
ap011 (λg f, comp g f) p q
infix ` ∘2 `:79 := comp2
end basic_lemmas
section squares
parameters {ob : Type} [C : precategory ob]
local infixl ` ⟶ `:25 := @precategory.hom ob C
local infixr ∘ := @precategory.comp ob C _ _ _
definition compose_squares {xa xb xc ya yb yc : ob}
{xg : xb ⟶ xc} {xf : xa ⟶ xb} {yg : yb ⟶ yc} {yf : ya ⟶ yb}
{wa : xa ⟶ ya} {wb : xb ⟶ yb} {wc : xc ⟶ yc}
(xyab : wb ∘ xf = yf ∘ wa) (xybc : wc ∘ xg = yg ∘ wb)
: wc ∘ (xg ∘ xf) = (yg ∘ yf) ∘ wa :=
calc
wc ∘ (xg ∘ xf) = (wc ∘ xg) ∘ xf : by rewrite assoc
... = (yg ∘ wb) ∘ xf : by rewrite xybc
... = yg ∘ (wb ∘ xf) : by rewrite assoc
... = yg ∘ (yf ∘ wa) : by rewrite xyab
... = (yg ∘ yf) ∘ wa : by rewrite assoc
definition compose_squares_2x2 {xa xb xc ya yb yc za zb zc : ob}
{xg : xb ⟶ xc} {xf : xa ⟶ xb} {yg : yb ⟶ yc} {yf : ya ⟶ yb} {zg : zb ⟶ zc} {zf : za ⟶ zb}
{va : ya ⟶ za} {vb : yb ⟶ zb} {vc : yc ⟶ zc} {wa : xa ⟶ ya} {wb : xb ⟶ yb} {wc : xc ⟶ yc}
(xyab : wb ∘ xf = yf ∘ wa) (xybc : wc ∘ xg = yg ∘ wb)
(yzab : vb ∘ yf = zf ∘ va) (yzbc : vc ∘ yg = zg ∘ vb)
: (vc ∘ wc) ∘ (xg ∘ xf) = (zg ∘ zf) ∘ (va ∘ wa) :=
calc
(vc ∘ wc) ∘ (xg ∘ xf) = vc ∘ (wc ∘ (xg ∘ xf)) : by rewrite (assoc vc wc _)
... = vc ∘ ((yg ∘ yf) ∘ wa) : by rewrite (compose_squares xyab xybc)
... = (vc ∘ (yg ∘ yf)) ∘ wa : by rewrite assoc
... = ((zg ∘ zf) ∘ va) ∘ wa : by rewrite (compose_squares yzab yzbc)
... = (zg ∘ zf) ∘ (va ∘ wa) : by rewrite assoc
definition square_precompose {xa xb xc yb yc : ob}
{xg : xb ⟶ xc} {yg : yb ⟶ yc} {wb : xb ⟶ yb} {wc : xc ⟶ yc}
(H : wc ∘ xg = yg ∘ wb) (xf : xa ⟶ xb) : wc ∘ xg ∘ xf = yg ∘ wb ∘ xf :=
calc
wc ∘ xg ∘ xf = (wc ∘ xg) ∘ xf : by rewrite assoc
... = (yg ∘ wb) ∘ xf : by rewrite H
... = yg ∘ wb ∘ xf : by rewrite assoc
definition square_postcompose {xb xc yb yc yd : ob}
{xg : xb ⟶ xc} {yg : yb ⟶ yc} {wb : xb ⟶ yb} {wc : xc ⟶ yc}
(H : wc ∘ xg = yg ∘ wb) (yh : yc ⟶ yd) : (yh ∘ wc) ∘ xg = (yh ∘ yg) ∘ wb :=
calc
(yh ∘ wc) ∘ xg = yh ∘ wc ∘ xg : by rewrite assoc
... = yh ∘ yg ∘ wb : by rewrite H
... = (yh ∘ yg) ∘ wb : by rewrite assoc
definition square_prepostcompose {xa xb xc yb yc yd : ob}
{xg : xb ⟶ xc} {yg : yb ⟶ yc} {wb : xb ⟶ yb} {wc : xc ⟶ yc}
(H : wc ∘ xg = yg ∘ wb) (yh : yc ⟶ yd) (xf : xa ⟶ xb)
: (yh ∘ wc) ∘ (xg ∘ xf) = (yh ∘ yg) ∘ (wb ∘ xf) :=
square_precompose (square_postcompose H yh) xf
end squares
structure Precategory : Type :=
(carrier : Type)
(struct : precategory carrier)
definition precategory.Mk [reducible] [constructor] {ob} (C) : Precategory := Precategory.mk ob C
definition precategory.MK [reducible] [constructor] (a b c d e f g h) : Precategory :=
Precategory.mk a (@precategory.mk a b c d e f g h)
abbreviation carrier [unfold 1] := @Precategory.carrier
attribute Precategory.carrier [coercion]
attribute Precategory.struct [instance] [priority 10000] [coercion]
-- definition precategory.carrier [coercion] [reducible] := Precategory.carrier
-- definition precategory.struct [instance] [coercion] := Precategory.struct
notation g ` ∘[`:60 C:0 `] `:0 f:60 :=
@comp (Precategory.carrier C) (Precategory.struct C) _ _ _ g f
-- TODO: make this left associative
definition Precategory.eta (C : Precategory) : Precategory.mk C C = C :=
Precategory.rec (λob c, idp) C
/-Characterization of paths between precategories-/
-- introduction tule for paths between precategories
definition precategory_eq {ob : Type}
{C D : precategory ob}
(p : Π{a b}, @hom ob C a b = @hom ob D a b)
(q : Πa b c g f, cast p (@comp ob C a b c g f) = @comp ob D a b c (cast p g) (cast p f))
: C = D :=
begin
induction C with hom1 c1 ID1 a b il ir, induction D with hom2 c2 ID2 a' b' il' ir',
esimp at *,
revert q, eapply homotopy2.rec_on @p, esimp, clear p, intro p q, induction p,
esimp at *,
have H : c1 = c2,
begin apply eq_of_homotopy3, intros, apply eq_of_homotopy2, intros, apply q end,
induction H,
have K : ID1 = ID2,
begin apply eq_of_homotopy, intro a, exact !ir'⁻¹ ⬝ !il end,
induction K,
apply ap0111111 (precategory.mk' hom1 c1 ID1): apply is_prop.elim
end
definition precategory_eq_of_equiv {ob : Type}
{C D : precategory ob}
(p : Π⦃a b⦄, @hom ob C a b ≃ @hom ob D a b)
(q : Π{a b c} g f, p (@comp ob C a b c g f) = @comp ob D a b c (p g) (p f))
: C = D :=
begin
fapply precategory_eq,
{ intro a b, exact ua !@p},
{ intros, refine !cast_ua ⬝ !q ⬝ _, apply ap011 !@comp !cast_ua⁻¹ !cast_ua⁻¹},
end
/- if we need to prove properties about precategory_eq, it might be easier with the following proof:
begin
induction C with hom1 comp1 ID1, induction D with hom2 comp2 ID2, esimp at *,
have H : Σ(s : hom1 = hom2), (λa b, equiv_of_eq (apd100 s a b)) = p,
begin
fconstructor,
{ apply eq_of_homotopy2, intros, apply ua, apply p},
{ apply eq_of_homotopy2, intros, rewrite [to_right_inv !eq_equiv_homotopy2, equiv_of_eq_ua]}
end,
induction H with H1 H2, induction H1, esimp at H2,
have K : (λa b, equiv.refl) = p,
begin refine _ ⬝ H2, apply eq_of_homotopy2, intros, exact !equiv_of_eq_refl⁻¹ end,
induction K, clear H2,
esimp at *,
have H : comp1 = comp2,
begin apply eq_of_homotopy3, intros, apply eq_of_homotopy2, intros, apply q end,
have K : ID1 = ID2,
begin apply eq_of_homotopy, intros, apply r end,
induction H, induction K,
apply ap0111111 (precategory.mk' hom1 comp1 ID1): apply is_prop.elim
end
-/
definition Precategory_eq {C D : Precategory}
(p : carrier C = carrier D)
(q : Π{a b : C}, a ⟶ b = cast p a ⟶ cast p b)
(r : Π{a b c : C} (g : b ⟶ c) (f : a ⟶ b), cast q (g ∘ f) = cast q g ∘ cast q f)
: C = D :=
begin
induction C with X C, induction D with Y D, esimp at *, induction p,
esimp at *,
apply ap (Precategory.mk X),
apply precategory_eq @q @r
end
definition Precategory_eq_of_equiv {C D : Precategory}
(p : carrier C ≃ carrier D)
(q : Π⦃a b : C⦄, a ⟶ b ≃ p a ⟶ p b)
(r : Π{a b c : C} (g : b ⟶ c) (f : a ⟶ b), q (g ∘ f) = q g ∘ q f)
: C = D :=
begin
induction C with X C, induction D with Y D, esimp at *,
revert q r, eapply equiv.rec_on_ua p, clear p, intro p, induction p, esimp,
intros,
apply ap (Precategory.mk X),
apply precategory_eq_of_equiv @q @r
end
-- elimination rules for paths between precategories.
-- The first elimination rule is "ap carrier"
definition Precategory_eq_hom [unfold 3] {C D : Precategory} (p : C = D) (a b : C)
: hom a b = hom (cast (ap carrier p) a) (cast (ap carrier p) b) :=
by induction p; reflexivity
--(ap10 (ap10 (apdt (λx, @hom (carrier x) (Precategory.struct x)) p⁻¹ᵖ) a) b)⁻¹ᵖ ⬝ _
-- beta/eta rules
definition ap_Precategory_eq' {C D : Precategory}
(p : carrier C = carrier D)
(q : Π{a b : C}, a ⟶ b = cast p a ⟶ cast p b)
(r : Π{a b c : C} (g : b ⟶ c) (f : a ⟶ b), cast q (g ∘ f) = cast q g ∘ cast q f)
(s : Πa, cast q (ID a) = ID (cast p a)) : ap carrier (Precategory_eq p @q @r) = p :=
begin
induction C with X C, induction D with Y D, esimp at *, induction p,
rewrite [↑Precategory_eq, -ap_compose,↑function.compose,ap_constant]
end
/-
theorem Precategory_eq'_eta {C D : Precategory} (p : C = D) :
Precategory_eq
(ap carrier p)
(Precategory_eq_hom p)
(by induction p; intros; reflexivity) = p :=
begin
induction p, induction C with X C, unfold Precategory_eq,
induction C, unfold precategory_eq, exact sorry
end
-/
/-
theorem Precategory_eq2 {C D : Precategory} (p q : C = D)
(r : ap carrier p = ap carrier q)
(s : Precategory_eq_hom p =[r] Precategory_eq_hom q)
: p = q :=
begin
end
-/
end category
|
b39c4a00b91087463a0637bd1ce7bef15b94882f | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Meta/Check.lean | 4e4cc09e63bf696333dd4751405bb119efdfb64c | [
"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,795 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.InferType
import Lean.Meta.LevelDefEq
/-
This is not the Kernel type checker, but an auxiliary method for checking
whether terms produced by tactics and `isDefEq` are type correct.
-/
namespace Lean
namespace Meta
private def ensureType (e : Expr) : MetaM Unit := do
_ ← getLevel e; pure ()
def throwLetTypeMismatchMessage {α} (fvarId : FVarId) : MetaM α := do
lctx ← getLCtx;
match lctx.find? fvarId with
| some (LocalDecl.ldecl _ _ n t v _) => do
vType ← inferType v;
throwError $
"invalid let declaration, term" ++ indentExpr v
++ Format.line ++ "has type " ++ indentExpr vType
++ Format.line ++ "but is expected to have type" ++ indentExpr t
| _ => unreachable!
@[specialize] private def checkLambdaLet
(check : Expr → MetaM Unit)
(e : Expr) : MetaM Unit :=
lambdaLetTelescope e $ fun xs b => do
xs.forM $ fun x => do {
xDecl ← getFVarLocalDecl x;
match xDecl with
| LocalDecl.cdecl _ _ _ t _ => do
ensureType t;
check t
| LocalDecl.ldecl _ _ _ t v _ => do
ensureType t;
check t;
vType ← inferType v;
unlessM (isDefEq t vType) $ throwLetTypeMismatchMessage x.fvarId!;
check v
};
check b
@[specialize] private def checkForall
(check : Expr → MetaM Unit)
(e : Expr) : MetaM Unit :=
forallTelescope e $ fun xs b => do
xs.forM $ fun x => do {
xDecl ← getFVarLocalDecl x;
ensureType xDecl.type;
check xDecl.type
};
ensureType b;
check b
private def checkConstant (constName : Name) (us : List Level) : MetaM Unit := do
cinfo ← getConstInfo constName;
unless (us.length == cinfo.lparams.length) $ throwIncorrectNumberOfLevels constName us
private def getFunctionDomain (f : Expr) : MetaM Expr := do
fType ← inferType f;
fType ← whnfD fType;
match fType with
| Expr.forallE _ d _ _ => pure d
| _ => throwFunctionExpected f
def throwAppTypeMismatch {α} {m} [Monad m] [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] [MonadLiftT MetaM m]
(f a : Expr) (extraMsg : MessageData := Format.nil) : m α := do
let e := mkApp f a;
aType ← inferType a;
expectedType ← liftM $ getFunctionDomain f;
throwError $
"application type mismatch" ++ indentExpr e
++ Format.line ++ "argument" ++ indentExpr a
++ Format.line ++ "has type" ++ indentExpr aType
++ Format.line ++ "but is expected to have type" ++ indentExpr expectedType
++ extraMsg
@[specialize] private def checkApp
(check : Expr → MetaM Unit)
(f a : Expr) : MetaM Unit := do
check f;
check a;
fType ← inferType f;
fType ← whnf fType;
match fType with
| Expr.forallE _ d _ _ => do
aType ← inferType a;
unlessM (isDefEq d aType) $ throwAppTypeMismatch f a
| _ => throwFunctionExpected (mkApp f a)
private partial def checkAux : Expr → MetaM Unit
| e@(Expr.forallE _ _ _ _) => checkForall checkAux e
| e@(Expr.lam _ _ _ _) => checkLambdaLet checkAux e
| e@(Expr.letE _ _ _ _ _) => checkLambdaLet checkAux e
| Expr.const c lvls _ => checkConstant c lvls
| Expr.app f a _ => checkApp checkAux f a
| Expr.mdata _ e _ => checkAux e
| Expr.proj _ _ e _ => checkAux e
| _ => pure ()
def check (e : Expr) : MetaM Unit :=
traceCtx `Meta.check $
withTransparency TransparencyMode.all $ checkAux e
def isTypeCorrect (e : Expr) : MetaM Bool :=
catch
(do check e; pure true)
(fun ex => do
trace! `Meta.typeError ex.toMessageData;
pure false)
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Meta.check;
registerTraceClass `Meta.typeError
end Meta
end Lean
|
b146eb96424218d5e356885776cab9d2bf2b54f3 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /05_Interacting_with_Lean.org.10.lean | e38134218ca99205d31458bc5edef3f62ca9a19b | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 215 | lean | /- page 67 -/
import standard
import standard algebra.ordered_ring
open nat algebra
-- BEGIN
check @mul_pos
check @mul_nonpos_of_nonneg_of_nonpos
check @add_lt_of_lt_of_nonpos
check @add_lt_of_nonpos_of_lt
-- END
|
6e6bd4827fa0854096f37c498fadabc0e4f7aba8 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/concrete_category/basic.lean | 0029fae725175000748e585cfc938266a328ed93 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 10,450 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather, Yury Kudryashov
-/
import category_theory.types
import category_theory.functor.epi_mono
import category_theory.limits.constructions.epi_mono
/-!
# Concrete categories
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A concrete category is a category `C` with a fixed faithful functor
`forget : C ⥤ Type*`. We define concrete categories using `class
concrete_category`. In particular, we impose no restrictions on the
carrier type `C`, so `Type` is a concrete category with the identity
forgetful functor.
Each concrete category `C` comes with a canonical faithful functor
`forget C : C ⥤ Type*`. We say that a concrete category `C` admits a
*forgetful functor* to a concrete category `D`, if it has a functor
`forget₂ C D : C ⥤ D` such that `(forget₂ C D) ⋙ (forget D) = forget C`,
see `class has_forget₂`. Due to `faithful.div_comp`, it suffices
to verify that `forget₂.obj` and `forget₂.map` agree with the equality
above; then `forget₂` will satisfy the functor laws automatically, see
`has_forget₂.mk'`.
Two classes helping construct concrete categories in the two most
common cases are provided in the files `bundled_hom` and
`unbundled_hom`, see their documentation for details.
## References
See [Ahrens and Lumsdaine, *Displayed Categories*][ahrens2017] for
related work.
-/
universes w v v' u u'
namespace category_theory
open category_theory.limits
/--
A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type`.
Note that `concrete_category` potentially depends on three independent universe levels,
* the universe level `w` appearing in `forget : C ⥤ Type w`
* the universe level `v` of the morphisms (i.e. we have a `category.{v} C`)
* the universe level `u` of the objects (i.e `C : Type u`)
They are specified that order, to avoid unnecessary universe annotations.
-/
class concrete_category (C : Type u) [category.{v} C] :=
(forget [] : C ⥤ Type w)
[forget_faithful : faithful forget]
attribute [instance] concrete_category.forget_faithful
/-- The forgetful functor from a concrete category to `Type u`. -/
@[reducible] def forget (C : Type u) [category.{v} C] [concrete_category.{w} C] : C ⥤ Type w :=
concrete_category.forget C
instance concrete_category.types : concrete_category (Type u) :=
{ forget := 𝟭 _ }
/--
Provide a coercion to `Type u` for a concrete category. This is not marked as an instance
as it could potentially apply to every type, and so is too expensive in typeclass search.
You can use it on particular examples as:
```
instance : has_coe_to_sort X := concrete_category.has_coe_to_sort X
```
-/
def concrete_category.has_coe_to_sort (C : Type u) [category.{v} C] [concrete_category.{w} C] :
has_coe_to_sort C (Type w) :=
⟨(concrete_category.forget C).obj⟩
section
local attribute [instance] concrete_category.has_coe_to_sort
variables {C : Type u} [category.{v} C] [concrete_category.{w} C]
@[simp] lemma forget_obj_eq_coe {X : C} : (forget C).obj X = X := rfl
/-- Usually a bundled hom structure already has a coercion to function
that works with different universes. So we don't use this as a global instance. -/
def concrete_category.has_coe_to_fun {X Y : C} : has_coe_to_fun (X ⟶ Y) (λ f, X → Y) :=
⟨λ f, (forget _).map f⟩
local attribute [instance] concrete_category.has_coe_to_fun
/-- In any concrete category, we can test equality of morphisms by pointwise evaluations.-/
lemma concrete_category.hom_ext {X Y : C} (f g : X ⟶ Y) (w : ∀ x : X, f x = g x) : f = g :=
begin
apply faithful.map_injective (forget C),
ext,
exact w x,
end
@[simp] lemma forget_map_eq_coe {X Y : C} (f : X ⟶ Y) : (forget C).map f = f := rfl
/--
Analogue of `congr_fun h x`,
when `h : f = g` is an equality between morphisms in a concrete category.
-/
lemma congr_hom {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x :=
congr_fun (congr_arg (λ k : X ⟶ Y, (k : X → Y)) h) x
lemma coe_id {X : C} : ((𝟙 X) : X → X) = id :=
(forget _).map_id X
lemma coe_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g : X → Z) = g ∘ f :=
(forget _).map_comp f g
@[simp] lemma id_apply {X : C} (x : X) : ((𝟙 X) : X → X) x = x :=
congr_fun ((forget _).map_id X) x
@[simp] lemma comp_apply {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) :
(f ≫ g) x = g (f x) :=
congr_fun ((forget _).map_comp _ _) x
lemma concrete_category.congr_hom {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x :=
congr_fun (congr_arg (λ f : X ⟶ Y, (f : X → Y)) h) x
lemma concrete_category.congr_arg {X Y : C} (f : X ⟶ Y) {x x' : X} (h : x = x') : f x = f x' :=
congr_arg (f : X → Y) h
/-- In any concrete category, injective morphisms are monomorphisms. -/
lemma concrete_category.mono_of_injective {X Y : C} (f : X ⟶ Y) (i : function.injective f) :
mono f :=
(forget C).mono_of_mono_map ((mono_iff_injective f).2 i)
lemma concrete_category.injective_of_mono_of_preserves_pullback {X Y : C} (f : X ⟶ Y) [mono f]
[preserves_limits_of_shape walking_cospan (forget C)] : function.injective f :=
(mono_iff_injective ((forget C).map f)).mp infer_instance
lemma concrete_category.mono_iff_injective_of_preserves_pullback {X Y : C} (f : X ⟶ Y)
[preserves_limits_of_shape walking_cospan (forget C)] : mono f ↔ function.injective f :=
((forget C).mono_map_iff_mono _).symm.trans (mono_iff_injective _)
/-- In any concrete category, surjective morphisms are epimorphisms. -/
lemma concrete_category.epi_of_surjective {X Y : C} (f : X ⟶ Y) (s : function.surjective f) :
epi f :=
(forget C).epi_of_epi_map ((epi_iff_surjective f).2 s)
lemma concrete_category.surjective_of_epi_of_preserves_pushout {X Y : C} (f : X ⟶ Y) [epi f]
[preserves_colimits_of_shape walking_span (forget C)] : function.surjective f :=
(epi_iff_surjective ((forget C).map f)).mp infer_instance
lemma concrete_category.epi_iff_surjective_of_preserves_pushout {X Y : C} (f : X ⟶ Y)
[preserves_colimits_of_shape walking_span (forget C)] : epi f ↔ function.surjective f :=
((forget C).epi_map_iff_epi _).symm.trans (epi_iff_surjective _)
lemma concrete_category.bijective_of_is_iso {X Y : C} (f : X ⟶ Y) [is_iso f] :
function.bijective ((forget C).map f) :=
by { rw ← is_iso_iff_bijective, apply_instance, }
@[simp] lemma concrete_category.has_coe_to_fun_Type {X Y : Type u} (f : X ⟶ Y) :
coe_fn f = f :=
rfl
end
/--
`has_forget₂ C D`, where `C` and `D` are both concrete categories, provides a functor
`forget₂ C D : C ⥤ D` and a proof that `forget₂ ⋙ (forget D) = forget C`.
-/
class has_forget₂ (C : Type u) (D : Type u') [category.{v} C] [concrete_category.{w} C]
[category.{v'} D] [concrete_category.{w} D] :=
(forget₂ : C ⥤ D)
(forget_comp : forget₂ ⋙ (forget D) = forget C . obviously)
/-- The forgetful functor `C ⥤ D` between concrete categories for which we have an instance
`has_forget₂ C `. -/
@[reducible] def forget₂ (C : Type u) (D : Type u') [category.{v} C] [concrete_category.{w} C]
[category.{v'} D] [concrete_category.{w} D] [has_forget₂ C D] : C ⥤ D :=
has_forget₂.forget₂
instance forget₂_faithful (C : Type u) (D : Type u') [category.{v} C] [concrete_category.{w} C]
[category.{v'} D] [concrete_category.{w} D] [has_forget₂ C D] : faithful (forget₂ C D) :=
has_forget₂.forget_comp.faithful_of_comp
instance forget₂_preserves_monomorphisms (C : Type u) (D : Type u')
[category.{v} C] [concrete_category.{w} C]
[category.{v'} D] [concrete_category.{w} D] [has_forget₂ C D]
[(forget C).preserves_monomorphisms] : (forget₂ C D).preserves_monomorphisms :=
have (forget₂ C D ⋙ forget D).preserves_monomorphisms,
by { simp only [has_forget₂.forget_comp], apply_instance },
by exactI functor.preserves_monomorphisms_of_preserves_of_reflects _ (forget D)
instance forget₂_preserves_epimorphisms (C : Type u) (D : Type u')
[category.{v} C] [concrete_category.{w} C]
[category.{v'} D] [concrete_category.{w} D] [has_forget₂ C D]
[(forget C).preserves_epimorphisms] : (forget₂ C D).preserves_epimorphisms :=
have (forget₂ C D ⋙ forget D).preserves_epimorphisms,
by { simp only [has_forget₂.forget_comp], apply_instance },
by exactI functor.preserves_epimorphisms_of_preserves_of_reflects _ (forget D)
instance induced_category.concrete_category {C : Type u} {D : Type u'} [category.{v'} D]
[concrete_category.{w} D] (f : C → D) :
concrete_category.{w} (induced_category D f) :=
{ forget := induced_functor f ⋙ forget D }
instance induced_category.has_forget₂
{C : Type u} {D : Type u'} [category.{v'} D] [concrete_category.{w} D]
(f : C → D) :
has_forget₂ (induced_category D f) D :=
{ forget₂ := induced_functor f,
forget_comp := rfl }
instance full_subcategory.concrete_category {C : Type u} [category.{v} C] [concrete_category.{w} C]
(Z : C → Prop) : concrete_category (full_subcategory Z) :=
{ forget := full_subcategory_inclusion Z ⋙ forget C }
instance full_subcategory.has_forget₂ {C : Type u} [category.{v} C] [concrete_category.{w} C]
(Z : C → Prop) : has_forget₂ (full_subcategory Z) C :=
{ forget₂ := full_subcategory_inclusion Z,
forget_comp := rfl }
/--
In order to construct a “partially forgetting” functor, we do not need to verify functor laws;
it suffices to ensure that compositions agree with `forget₂ C D ⋙ forget D = forget C`.
-/
def has_forget₂.mk' {C : Type u} {D : Type u'} [category.{v} C] [concrete_category.{w} C]
[category.{v'} D] [concrete_category.{w} D] (obj : C → D)
(h_obj : ∀ X, (forget D).obj (obj X) = (forget C).obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, (forget D).map (map f) == (forget C).map f) :
has_forget₂ C D :=
{ forget₂ := faithful.div _ _ _ @h_obj _ @h_map,
forget_comp := by apply faithful.div_comp }
/-- Every forgetful functor factors through the identity functor. This is not a global instance as
it is prone to creating type class resolution loops. -/
def has_forget_to_Type (C : Type u) [category.{v} C] [concrete_category.{w} C] :
has_forget₂ C (Type w) :=
{ forget₂ := forget C,
forget_comp := functor.comp_id _ }
end category_theory
|
e553f1f1e37eac8ac0bcd28dbcda2ce770c2620d | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/group_theory/group_action/prod.lean | 9b0f8b7f19f2c2dfac518037b849f8f1cafec32e | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,682 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot, Eric Wieser
-/
import algebra.group.prod
/-!
# Prod instances for additive and multiplicative actions
This file defines instances for binary product of additive and multiplicative actions
-/
variables {M N α β : Type*}
namespace prod
section
variables [has_scalar M α] [has_scalar M β] [has_scalar N α] [has_scalar N β] (a : M) (x : α × β)
@[to_additive prod.has_vadd] instance : has_scalar M (α × β) := ⟨λa p, (a • p.1, a • p.2)⟩
@[simp, to_additive] theorem smul_fst : (a • x).1 = a • x.1 := rfl
@[simp, to_additive] theorem smul_snd : (a • x).2 = a • x.2 := rfl
@[simp, to_additive] theorem smul_mk (a : M) (b : α) (c : β) : a • (b, c) = (a • b, a • c) := rfl
instance [has_scalar M N] [is_scalar_tower M N α] [is_scalar_tower M N β] :
is_scalar_tower M N (α × β) :=
⟨λ x y z, mk.inj_iff.mpr ⟨smul_assoc _ _ _, smul_assoc _ _ _⟩⟩
@[to_additive] instance [smul_comm_class M N α] [smul_comm_class M N β] :
smul_comm_class M N (α × β) :=
{ smul_comm := λ r s x, mk.inj_iff.mpr ⟨smul_comm _ _ _, smul_comm _ _ _⟩ }
@[to_additive has_faithful_vadd_left]
instance has_faithful_scalar_left [has_faithful_scalar M α] [nonempty β] :
has_faithful_scalar M (α × β) :=
⟨λ x y h, let ⟨b⟩ := ‹nonempty β› in eq_of_smul_eq_smul $ λ a : α, by injection h (a, b)⟩
@[to_additive has_faithful_vadd_right]
instance has_faithful_scalar_right [nonempty α] [has_faithful_scalar M β] :
has_faithful_scalar M (α × β) :=
⟨λ x y h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ b : β, by injection h (a, b)⟩
end
@[to_additive] instance {m : monoid M} [mul_action M α] [mul_action M β] : mul_action M (α × β) :=
{ mul_smul := λ a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩,
one_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩ }
instance {R M N : Type*} {r : monoid R} [add_monoid M] [add_monoid N]
[distrib_mul_action R M] [distrib_mul_action R N] : distrib_mul_action R (M × N) :=
{ smul_add := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩,
smul_zero := λ a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩ }
instance {R M N : Type*} {r : monoid R} [monoid M] [monoid N]
[mul_distrib_mul_action R M] [mul_distrib_mul_action R N] : mul_distrib_mul_action R (M × N) :=
{ smul_mul := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_mul' _ _ _, smul_mul' _ _ _⟩,
smul_one := λ a, mk.inj_iff.mpr ⟨smul_one _, smul_one _⟩ }
end prod
|
79018a41b10749adbd8456bae61d3d11c957213f | 48eee836fdb5c613d9a20741c17db44c8e12e61c | /src/algebra/notations/reserved.lean | cf8f2a580ff4265afd4dfe334506d7d5828ddb77 | [
"Apache-2.0"
] | permissive | fgdorais/lean-universal | 06430443a4abe51e303e602684c2977d1f5c0834 | 9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1 | refs/heads/master | 1,592,479,744,136 | 1,589,473,399,000 | 1,589,473,399,000 | 196,287,552 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 2,259 | lean | -- Copyright © 2019 François G. Dorais. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
reserve prefix `¬`:40 -- core := not
reserve prefix `~`:40 -- core
reserve prefix `-`:100 -- core := has_neg.neg
reserve infixl `; `:1 -- core := has_andthen.andthen
reserve infixl ` ⬝ `:75 -- core
reserve infixl ` + `:65 -- core := has_add.add
reserve infixl ` - `:65 -- core := has_sub.sub
reserve infixl ` * `:70 -- core := has_mul.mul
reserve infixl ` / `:70 -- core := has_div.div
reserve infixl ` % `:70 -- core := has_mod.mod
reserve infixl ` && `:70 -- core := band
reserve infixl ` || `:65 -- core := bor
reserve infixl ` ∩ `:70 -- core := has_inter.inter
reserve infixl ` ∪ `:65 -- core := has_union.union
reserve infixl ` ++ `:65 -- core := has_append.append
reserve infixl ` ∙ `:70
reserve infixr ` ^ `:80 -- core := has_pow.pow
reserve infixr ` ∧ `:35 -- core := and
reserve infixr ` /\ `:35 -- core := and
reserve infixr ` \/ `:30 -- core := or
reserve infixr ` ∨ `:30 -- core := or
reserve infixr ` :: `:67 -- core := list.cons
reserve infixr ` ▸ `:75 -- core := eq.subst
reserve infixr ` ▹ `:75 -- core
reserve infixr ` ⊕ `:30 -- core := sum
reserve infixr ` × `:35 -- core := prod
reserve infixr ` ∘ `:90 -- core := function.comp
reserve infix ` \ `:70 -- core := has_sdiff.sdiff
reserve infix ` <-> `:20 -- core := iff
reserve infix ` ↔ `:20 -- core := iff
reserve infix ` = `:50 -- core := eq
reserve infix ` == `:50 -- core := heq
reserve infix ` ≠ `:50 -- core := ne
reserve infix ` ≈ `:50 -- core := has_equiv.equiv
reserve infix ` ~ `:50 -- core
reserve infix ` ≡ `:50 -- core
reserve infix ` <= `:50 -- core := has_le.le
reserve infix ` ≤ `:50 -- core := has_le.le
reserve infix ` < `:50 -- core := has_lt.lt
reserve infix ` >= `:50 -- core := ge
reserve infix ` ≥ `:50 -- core := ge
reserve infix ` > `:50 -- core := gt
reserve infix ` ∈ `:50 -- core := has_mem.mem
reserve infix ` ∉ `:50 -- core := not (has_mem.mem #1 #0)
reserve infix ` ⊆ `:50 -- core := has_subset.subset
reserve infix ` ⊇ `:50 -- core := superset
reserve infix ` ⊂ `:50 -- core := has_ssubset.ssubset
reserve infix ` ⊃ `:50 -- core := ssuperset
reserve infix ` ∣ `:50 -- core
|
5db28a6e4740609d6db3dcbf8471f19573ca52a1 | b32d3853770e6eaf06817a1b8c52064baaed0ef1 | /src/super/inferences/resolution.lean | 301bd8f741096bba80ebce9734c00acc75c7447a | [] | no_license | gebner/super2 | 4d58b7477b6f7d945d5d866502982466db33ab0b | 9bc5256c31750021ab97d6b59b7387773e54b384 | refs/heads/master | 1,635,021,682,021 | 1,634,886,326,000 | 1,634,886,326,000 | 225,600,688 | 4 | 2 | null | 1,598,209,306,000 | 1,575,371,550,000 | Lean | UTF-8 | Lean | false | false | 1,138 | lean | import super.prover_state super.resolve
namespace super
open tactic
private meta def get_selected_lits (cs : list derived_clause) : list (derived_clause × ℕ × literal) :=
do c ← cs, i ← c.selected, some l ← pure (c.cls.literals.nth i) | [], pure (c, i, l)
meta def inference.forward_resolution : inference_rule | given := do
active ← get_active,
retrieve_packed $ do
(c1, i1, literal.pos a1) ← get_selected_lits active.values | [],
(c2, i2, literal.neg a2) ← get_selected_lits [given] | [],
pure $ do
some _ ← try_core (unify a1 a2) | pure [],
pure <$> clause.resolve c1.cls i1 c2.cls i2
meta def inference.backward_resolution : inference_rule | given := do
active ← get_active,
retrieve_packed $ do
(c1, i1, literal.pos a1) ← get_selected_lits [given] | [],
(c2, i2, literal.neg a2) ← get_selected_lits active.values | [],
pure $ do
some _ ← try_core (unify a1 a2) | pure [],
pure <$> clause.resolve c1.cls i1 c2.cls i2
meta def inference.resolution : inference_rule | given :=
(++) <$> inference.forward_resolution given
<*> inference.backward_resolution given
end super
|
eeb77afdb235cdfee11d59c6563091c7ccdaf9f2 | 76df16d6c3760cb415f1294caee997cc4736e09b | /lean/src/sym_factory/defs.lean | 042b62b6c57ad4eb39bc779dd5efbec1e01e1c78 | [
"MIT"
] | permissive | uw-unsat/leanette-popl22-artifact | 70409d9cbd8921d794d27b7992bf1d9a4087e9fe | 80fea2519e61b45a283fbf7903acdf6d5528dbe7 | refs/heads/master | 1,681,592,449,670 | 1,637,037,431,000 | 1,637,037,431,000 | 414,331,908 | 6 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 7,927 | lean | import ..cs.lang
import ..cs.sym
import ..op.sym
import ..op.lang
import ..tactic.all
namespace sym_factory
open sym
open op.sym
def mk_tt : term type.bool := term.lit $ lit.bool tt
def mk_ff : term type.bool := term.lit $ lit.bool ff
def is_tt : term type.bool → bool
| (term.lit (lit.bool tt)) := tt
| _ := ff
def is_ff : term type.bool → bool
| (term.lit (lit.bool ff)) := tt
| _ := ff
def pe_not : term type.bool → term type.bool
| (term.lit (lit.bool b)) := (term.lit (lit.bool (bnot b)))
| t := term.ite t mk_ff mk_tt
def pe_and : term type.bool → term type.bool → term type.bool
| (term.lit (lit.bool tt)) t_b := t_b
| (term.lit (lit.bool ff)) t_b := mk_ff
| t_a (term.lit (lit.bool tt)) := t_a
| t_a (term.lit (lit.bool ff)) := mk_ff
| t_a t_b :=
if t_a = t_b then
t_a
else
term.ite t_a t_b mk_ff
def pe_or : term type.bool → term type.bool → term type.bool
| (term.lit (lit.bool tt)) t_b := mk_tt
| (term.lit (lit.bool ff)) t_b := t_b
| t_a (term.lit (lit.bool tt)) := mk_tt
| t_a (term.lit (lit.bool ff)) := t_a
| t_a t_b :=
if t_a = t_b then
t_a
else
term.ite t_a mk_tt t_b
def pe_imp (t_a : term type.bool) (t_b : term type.bool) : term type.bool :=
pe_or (pe_not t_a) t_b
mutual def truth, truth.atom
with truth : val → term type.bool
| (val.atom va) := truth.atom va
| (val.union []) := term.lit $ lit.bool tt
| (val.union (⟨term.lit (lit.bool tt), va⟩ :: vs)) := truth.atom va
| (val.union (⟨term.lit (lit.bool ff), _⟩ :: vs)) := truth (val.union vs)
| (val.union (⟨g, va⟩ :: vs)) := term.ite g (truth.atom va) (truth (val.union vs))
with truth.atom : val_atom → term type.bool
| (@val_atom.term type.bool t) := t
| _ := term.lit $ lit.bool tt
def bval (b : bool) : val := (val.atom (val_atom.term (term.lit (lit.bool b))))
def dval : op.lang.datum → val
| (op.lang.datum.int i) := val.atom (val_atom.term (term.lit (lit.int i)))
| op.lang.datum.undef := val.union []
def cval : op.sym.clos → val
| ⟨x, e, ε⟩ := val.atom (val_atom.clos x e ε)
def adjust_core {τ : Type} : term type.bool → choices' τ → choices' τ
| t_acc [] := []
| t_acc (⟨g, va⟩ :: gvs) := ⟨pe_and g t_acc, va⟩ :: adjust_core (pe_and (pe_not g) t_acc) gvs
def adjust {τ : Type} : choices' τ → choices' τ := adjust_core mk_tt
def cast_choices : choices' val_atom → choices' clos
| [] := []
| (⟨g, val_atom.clos x e ε⟩ :: gvs) := ⟨g, ⟨x, e, ε⟩⟩ :: cast_choices gvs
| (⟨g, _⟩ :: gvs) := cast_choices gvs
def cast : val → choices' clos
| (val.atom (val_atom.clos x e ε)) := [⟨mk_tt, ⟨x, e, ε⟩⟩]
| (val.atom _) := []
| (val.union gvs) := cast_choices (adjust gvs)
def make_and (g : term type.bool) : choice (term type.bool) val_atom → choice (term type.bool) val_atom
| ⟨g', v'⟩ := ⟨pe_and g g', v'⟩
def merge.core : choices' val → choices' val_atom
| [] := []
| (⟨g, val.union gvs_sub⟩ :: gvs) := (adjust gvs_sub).map (make_and g) ++ merge.core gvs
| (⟨g, val.atom va⟩ :: gvs) := ⟨g, va⟩ :: merge.core gvs
def merge (gvs : choices' val) :=
match merge.core gvs with
| [⟨g, v⟩] :=
if is_tt g then
val.atom v
else
val.union [⟨g, v⟩]
| grs := val.union grs
end
def infeasible_choice : choice (term type.bool) val_atom := ⟨mk_ff, val_atom.term mk_ff⟩
def opS.int {τ : type}
(fC : ℤ → ℤ → op.sym.lit τ)
(fS : term type.int → term type.int → term τ) :
term type.int → term type.int → val_atom
| (term.lit (lit.int i_a)) (term.lit (lit.int i_b)) :=
val_atom.term (term.lit (fC i_a i_b))
| t_a t_b := val_atom.term (fS t_a t_b)
def opS.int_wrap : op.lang.op_int_2 → term type.int → term type.int → val_atom
| op.lang.op_int_2.add t_a t_b := opS.int (λ a b, lit.int $ a + b) (term.expr typedop.add) t_a t_b
| op.lang.op_int_2.mul t_a t_b := opS.int (λ a b, lit.int $ a * b) (term.expr typedop.mul) t_a t_b
| op.lang.op_int_2.lt t_a t_b := opS.int (λ a b, lit.bool $ a < b) (term.expr typedop.lt) t_a t_b
| op.lang.op_int_2.eq t_a t_b := opS.int (λ a b, lit.bool $ a = b) (term.expr typedop.eq) t_a t_b
def opS.core : op.lang.op → list val_atom → option val
| (op.lang.op.int_2 o) vas :=
match vas with
| [va_a, va_b] :=
match va_a, va_b with
| @val_atom.term type.int t_a, @val_atom.term type.int t_b :=
some $ val.atom (opS.int_wrap o t_a t_b)
| _, _ := none
end
| _ := none
end
| (op.lang.op.list_proj o) vas :=
match vas with
| [va] :=
match va with
| val_atom.list (v :: vs) :=
match o with
| op.lang.op_list_proj.first := some v
| op.lang.op_list_proj.rest := some $ val.atom $ val_atom.list vs
end
| _ := none
end
| _ := none
end
| op.lang.op.list_cons vas :=
match vas with
| [va_x, va_y] :=
match va_y with
| val_atom.list vs := some $ val.atom $ val_atom.list (val.atom va_x :: vs)
| _ := none
end
| _ := none
end
| op.lang.op.list_null vas :=
match vas with
| [] := some $ val.atom $ val_atom.list []
| _ := none
end
| op.lang.op.list_is_null vas :=
match vas with
| [va] :=
some $ val.atom $ val_atom.term $ term.lit $ lit.bool $
match va with
| val_atom.list [] := tt
| _ := ff
end
| _ := none
end
def make_disjunction {τ : Type} : choices (term type.bool) τ → term type.bool
| [] := mk_ff
| (⟨g, _⟩ :: gvs) := pe_or g (make_disjunction gvs)
def measure : psum (list val) (list val) → ℕ
| (psum.inl vs) := 2 * vs.length
| (psum.inr vs) := (2 * vs.length) + 1
lemma measure_decreases {n : ℕ} : 2 * n + 1 < 2 * (n + 1) := by linarith
mutual def opS.split, opS.split_map (o : op.lang.op)
with opS.split : list val → term type.bool → list val_atom → choice (term type.bool) val
| [] := λ g_acc vas,
match opS.core o (list.reverse vas) with
| none := ⟨mk_ff, val.union []⟩
| some v := ⟨g_acc, v⟩
end
| ((val.union gvs) :: vs) :=
λ g_acc vas,
have measure (psum.inr vs) < measure (psum.inl ((val.union gvs) :: vs)) := by {
simp only [measure],
apply measure_decreases,
},
let gvs' := opS.split_map vs gvs g_acc vas in
⟨make_disjunction gvs', merge gvs'⟩
| ((val.atom va) :: vs) :=
λ g_acc vas ,
have measure (psum.inl vs) < measure (psum.inl ((val.atom va) :: vs)) := by simp [measure],
opS.split vs g_acc (va :: vas)
with opS.split_map : list val → choices' val_atom → term type.bool → list val_atom → choices' val
| vs :=
λ gvs g_acc vas,
have measure (psum.inl vs) < measure (psum.inr vs) := by simp [measure],
(adjust gvs).map (λ ⟨g, va⟩, opS.split vs (pe_and g_acc g) (va :: vas))
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf measure⟩]}
def opS (o : op.lang.op) (xs : list val) : op.sym.result :=
match opS.split o xs mk_tt [] with ⟨g, v⟩ :=
if is_ff g then
result.halt ⟨mk_tt, mk_ff⟩
else
result.ans ⟨mk_tt, g⟩ v
end
mutual def lift, lifts
with lift : op.lang.val → val
| (lang.val.datum (op.lang.datum.int x)) :=
val.atom (val_atom.term (term.lit (lit.int x)))
| (lang.val.datum op.lang.datum.undef) :=
val.union []
| (lang.val.list xs) :=
val.atom (val_atom.list (lifts xs))
| (lang.val.bool v) :=
val.atom (val_atom.term (term.lit (lit.bool v)))
| (lang.val.clos x e ε) :=
val.atom (val_atom.clos x e (lifts ε))
with lifts : list op.lang.val → list val
| [] := []
| (x :: xs) := lift x :: lifts xs
def lift.atom : op.lang.val → val_atom
| (lang.val.datum (op.lang.datum.int x)) :=
val_atom.term (term.lit (lit.int x))
| (lang.val.datum op.lang.datum.undef) :=
val_atom.list [] -- deadcode
| (lang.val.list xs) :=
val_atom.list (lifts xs)
| (lang.val.bool v) :=
val_atom.term (term.lit (lit.bool v))
| (lang.val.clos x e ε) :=
val_atom.clos x e (lifts ε)
end sym_factory
|
ad2821061f8eb0ad95d0b005ffffdeb09ab27c42 | 1e7164e9c5aacccd114777e0ea8f8201177f1289 | /src/traversals/geom_real.lean | a4260b19042d3b81664d2a9943925762409ccc85 | [] | no_license | floriscnossen/simplicial_sets_in_lean | e7cb1780474407668208ec5b8f19de7eb5936701 | c260d8196964bb288331bff7a3bfe24266792f0c | refs/heads/master | 1,685,636,159,913 | 1,624,118,064,000 | 1,624,118,064,000 | 352,801,219 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,653 | lean | import traversals.basic
open category_theory
open category_theory.limits
open simplex_category
open sSet
open_locale simplicial
/-! # Geometric realisation of a traversal -/
namespace traversal
namespace geom_real
variables {n : ℕ} (θ : traversal n)
@[reducible]
def shape := fin(θ.length + 1) ⊕ fin(θ.length)
namespace shape
inductive hom : shape θ → shape θ → Type*
| id (X) : hom X X
| s (i : fin(θ.length)) : hom (sum.inl i.cast_succ) (sum.inr i)
| t (i : fin(θ.length)) : hom (sum.inl i.succ) (sum.inr i)
instance category : small_category (shape θ) :=
{ hom := hom θ,
id := λ j, hom.id j,
comp := λ j₁ j₂ j₃ f g,
begin
cases f, exact g,
cases g, exact hom.s f_1,
cases g, exact hom.t f_1,
end,
id_comp' := λ j₁ j₂ f, rfl,
comp_id' := λ j₁ j₂ f, by cases f; refl,
assoc' := λ j₁ j₂ j₃ j₄ f g h, by cases f; cases g; refl,
}
end shape
def diagram : shape θ ⥤ sSet :=
{ obj := λ j, sum.cases_on j (λ j, Δ[n]) (λ j, Δ[n+1]),
map := λ _ _ f,
begin
cases f with _ j j,
exact 𝟙 _,
exact to_sSet_hom (δ (list.nth_le θ j.1 j.2).s),
exact to_sSet_hom (δ (list.nth_le θ j.1 j.2).t),
end,
map_id' := λ j, rfl,
map_comp' := λ _ _ _ f g, by cases f; cases g; refl, }
def colimit : colimit_cocone (diagram θ) :=
{ cocone := combine_cocones (diagram θ) (λ n,
{ cocone := types.colimit_cocone _,
is_colimit := types.colimit_cocone_is_colimit _ }),
is_colimit := combined_is_colimit _ _,
}
end geom_real
def geom_real {n} (θ : traversal n) : sSet := (geom_real.colimit θ).cocone.X
end traversal
|
218624dfe84381182042a487e40bfc47c7c305c7 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/data/nat/dist.lean | 6ec114949a624d1149f072218b02795f6c0f80a1 | [
"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 | 3,964 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jeremy Avigad
Distance function on the natural numbers.
-/
import data.nat.basic
namespace nat
/- distance -/
/-- Distance (absolute value of difference) between natural numbers. -/
def dist (n m : ℕ) := (n - m) + (m - n)
theorem dist.def (n m : ℕ) : dist n m = (n - m) + (m - n) := rfl
@[simp] theorem dist_comm (n m : ℕ) : dist n m = dist m n :=
by simp [dist.def]
@[simp] theorem dist_self (n : ℕ) : dist n n = 0 :=
by simp [dist.def, nat.sub_self]
theorem eq_of_dist_eq_zero {n m : ℕ} (h : dist n m = 0) : n = m :=
have n - m = 0, from eq_zero_of_add_eq_zero_right h,
have n ≤ m, from nat.le_of_sub_eq_zero this,
have m - n = 0, from eq_zero_of_add_eq_zero_left h,
have m ≤ n, from nat.le_of_sub_eq_zero this,
le_antisymm ‹n ≤ m› ‹m ≤ n›
theorem dist_eq_zero {n m : ℕ} (h : n = m) : dist n m = 0 :=
begin rw [h, dist_self] end
theorem dist_eq_sub_of_le {n m : ℕ} (h : n ≤ m) : dist n m = m - n :=
begin rw [dist.def, sub_eq_zero_of_le h, zero_add] end
theorem dist_eq_sub_of_ge {n m : ℕ} (h : n ≥ m) : dist n m = n - m :=
begin rw [dist_comm], apply dist_eq_sub_of_le h end
theorem dist_zero_right (n : ℕ) : dist n 0 = n :=
eq.trans (dist_eq_sub_of_ge (zero_le n)) (nat.sub_zero n)
theorem dist_zero_left (n : ℕ) : dist 0 n = n :=
eq.trans (dist_eq_sub_of_le (zero_le n)) (nat.sub_zero n)
theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m :=
calc
dist (n + k) (m + k) = ((n + k) - (m + k)) + ((m + k)-(n + k)) : rfl
... = (n - m) + ((m + k) - (n + k)) : by rw nat.add_sub_add_right
... = (n - m) + (m - n) : by rw nat.add_sub_add_right
theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m :=
begin rw [add_comm k n, add_comm k m], apply dist_add_add_right end
theorem dist_eq_intro {n m k l : ℕ} (h : n + m = k + l) : dist n k = dist l m :=
calc
dist n k = dist (n + m) (k + m) : by rw dist_add_add_right
... = dist (k + l) (k + m) : by rw h
... = dist l m : by rw dist_add_add_left
protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) :=
or.elim (le_total k m)
(assume : k ≤ m,
begin rw ←nat.add_sub_assoc this, apply nat.sub_le_sub_right, apply nat.le_sub_add end)
(assume : k ≥ m,
begin rw [sub_eq_zero_of_le this, add_zero], apply nat.sub_le_sub_left, exact this end)
theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k :=
have dist n m + dist m k = (n - m) + (m - k) + ((k - m) + (m - n)), by simp [dist.def],
begin
rw [this, dist.def], apply add_le_add, repeat { apply nat.sub_lt_sub_add_sub }
end
theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k :=
by rw [dist.def, dist.def, right_distrib, nat.mul_sub_right_distrib, nat.mul_sub_right_distrib]
theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m :=
by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm]
-- TODO(Jeremy): do when we have max and minx
--theorem dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j :=
--sorry
/-
or.elim (lt_or_ge i j)
(assume : i < j,
by rw [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this])
(assume : i ≥ j,
by rw [max_eq_left this , min_eq_right this, dist_eq_sub_of_ge this])
-/
theorem dist_succ_succ {i j : nat} : dist (succ i) (succ j) = dist i j :=
by simp [dist.def, succ_sub_succ]
theorem dist_pos_of_ne {i j : nat} : i ≠ j → 0 < dist i j :=
assume hne, nat.lt_by_cases
(assume : i < j,
begin rw [dist_eq_sub_of_le (le_of_lt this)], apply nat.sub_pos_of_lt this end)
(assume : i = j, by contradiction)
(assume : i > j,
begin rw [dist_eq_sub_of_ge (le_of_lt this)], apply nat.sub_pos_of_lt this end)
end nat
|
e4396454413737f9dae9b3d9d608acb7dcf24ac0 | 40c8b73f5a82a3c09e3d1956df44aad9ffd510b7 | /src/section_13a.lean | 8f86e9fdd14755171fed8050a0d36627dea85209 | [] | no_license | lean-forward/cap_set_problem | 343c02d42775eb25b32b6c567d13769fd42dd4ca | 095a2f18f81c551a0053f2e65806de751e438fc4 | refs/heads/master | 1,626,463,115,144 | 1,561,829,195,000 | 1,561,829,195,000 | 178,678,372 | 7 | 1 | null | 1,625,412,745,000 | 1,554,031,306,000 | Lean | UTF-8 | Lean | false | false | 12,485 | lean | /-
Copyright (c) 2018 Sander Dahmen, Johannes Hölzl, Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sander Dahmen, Johannes Hölzl, Robert Y. Lewis
"On large subsets of 𝔽ⁿ_q with no three-term arithmetic progression"
by J. S. Ellenberg and D. Gijswijt
This file proves a result about the coefficients of a complex polynomial.
It is independent of the rest of our development so far, and used in section_13b.lean.
It corresponds to the first part of section 13 of our blueprint.
NOTE: after simplifications to the proof suggested by Dion Gijswijt, this part of the argument
is unnecessary. This file is not imported in the final result.
-/
import tactic.linarith
import data.polynomial
import analysis.complex.exponential
variables {α : Type*} {β : Type*} {γ : Type*}
namespace units
variables [division_ring α] {a b : α}
end units
variable [discrete_field β]
open finset
def geom_sum0 [semiring α] (x : α) (n : ℕ) : α :=
(range n).sum (λ i, x^i)
lemma geom_sum_one [semiring α] {k : ℕ} : geom_sum0 (1 : α) k = k :=
by simp [geom_sum0,one_pow]
-- Lemma 13.3 from the notes
lemma geom_sum_bound (x: ℝ) (M : ℕ) (h1 : 0 < x) (h2 : x < 1) : geom_sum0 (1/x) (M+1) < (1 - x)⁻¹ * (x^M)⁻¹ :=
have hxn0 : x ≠ 0 := ne_of_gt h1,
have hxn1 : x ≠ 1 := ne_of_lt h2,
let M' := (M : ℤ) in
have h : geom_sum0 (1/x) (M+1) = (1 - x)⁻¹ * (x^M)⁻¹ * (1 - x^(M + 1)), from
calc geom_sum0 (1/x) (M+1) = (range (M+1)).sum (λ i, (1/x)^i) : by rw [geom_sum0]
... = (range (M+1)).sum (λ i, x⁻¹ ^i) : by simp
... = (x - 1)⁻¹ * (x - x⁻¹ ^ (M+1) * x) : by rw [geom_sum_inv hxn1 hxn0 (M+1)]
... = (x - 1)⁻¹ * (x - x⁻¹ ^ (M'+1) * x) : by refl
... = (x - 1)⁻¹ * ((x^M')⁻¹ * (x^(M'+1) - 1)) :
begin
congr, rw [mul_sub, fpow_add hxn0, fpow_add, fpow_one, fpow_one, mul_one,
mul_assoc, inv_mul_cancel hxn0, ← mul_assoc, inv_mul_cancel, one_mul, mul_one,
← fpow_inv, ← fpow_inv, ← fpow_mul, ← fpow_mul],
simp,
exact fpow_ne_zero_of_ne_zero hxn0 _,
exact inv_ne_zero hxn0
end
... = (x - 1)⁻¹ * (x^M)⁻¹ * (x^(M+1) - 1) : by rw[mul_assoc]; refl
... = (1 - x)⁻¹ * (x^M)⁻¹ * (1 - x^(M + 1)) :
begin
rw [← neg_sub, ← neg_sub (1:ℝ)],
simp only [neg_inv', neg_mul_eq_neg_mul, (neg_mul_comm _ _).symm, neg_neg]
end,
have hRight : 1 - x^(M+1) < 1, from
calc 1 - x^(M+1) < 1-0 : sub_lt_sub_left (pow_pos h1 (M+1)) 1
... = 1 : by simp,
have hLeft : (1 - x)⁻¹ * (x ^ M)⁻¹ > 0, from
have hh : 1-x > 0 := by linarith,
have foo : (1-x)⁻¹ > 0 :=
calc (1-x)⁻¹ = 1/(1-x) : by rw inv_eq_one_div
... > 0 : one_div_pos_of_pos hh,
have bar : (x^M)⁻¹ > 0 :=
calc (x^M)⁻¹ = 1/(x^M) : by rw inv_eq_one_div
... > 0 : one_div_pos_of_pos (pow_pos h1 M),
mul_pos foo bar,
calc geom_sum0 (1/x) (M+1) = (1 - x)⁻¹ * (x^M)⁻¹ * (1 - x^(M + 1)) : h
... < (1 - x)⁻¹ * (x^M)⁻¹ * 1 : mul_lt_mul_of_pos_left hRight hLeft
... = (1 - x)⁻¹ * (x^M)⁻¹ : by rw mul_one
/-- `is_k_uroot x k`: `x` is a `k`-th root of unity -/
def is_k_uroot [semiring α] (x : α) (k : ℕ) : Prop := k > 0 ∧ x^k=1
namespace is_k_uroot
variable [semiring α]
def to_unit {x : α} {k : ℕ} (h : is_k_uroot x k) : units α :=
{ val := x,
inv := x^(k-1),
val_inv :=
calc x * x ^ (k - 1) = x^(1+(k-1)) : by rw[pow_add, pow_one]
... = x^k : by rw[nat.add_sub_cancel'] ; exact h.1
... = 1 : h.2,
inv_val :=
calc x ^ (k - 1) * x = x^(1+(k-1)) : by rw[add_comm,pow_add, pow_one]
... = x^k : by rw[nat.add_sub_cancel'] ; exact h.1
... = 1 : h.2 }
@[simp] lemma coe_to_unit {x : α} {k : ℕ} (h : is_k_uroot x k) : (h.to_unit : α) = x := rfl
@[simp] lemma to_unit_pow_k {x : α} {k : ℕ} (h : is_k_uroot x k) : h.to_unit ^ k = 1 :=
by ext; rw [units.coe_pow, units.coe_one, coe_to_unit, h.2]
end is_k_uroot
def is_primitive_k_uroot [semiring α] (x : α) (k : ℕ) : Prop :=
is_k_uroot x k ∧ (∀n, is_k_uroot x n → k ≤ n)
section geom_sum_uroot
variables [domain α] [discrete_field β]
lemma geom_sum_uroot {x : α} {k : ℕ} (hx : is_k_uroot x k) (i : ℤ) (h : hx.to_unit ^ i ≠ 1):
(geom_sum0 (hx.to_unit ^ i : units _) k : α) = 0 :=
let x' : ℤ → units α := λi, hx.to_unit ^ i in
have eq_zero : (geom_sum0 (x' i) k : α) * ((x' i) - 1) = 0, from
calc (geom_sum0 (x' i) k : α) * ((x' i) - 1) = (x' i)^k - 1 : geom_sum_mul _ _
... = (x' (k * i)) - 1 : begin simp only [x'], rw[←units.coe_pow, mul_comm, gpow_mul], refl end
... = 0 : by simp only [x', gpow_mul, gpow_coe_nat, hx.to_unit_pow_k, one_gpow, units.coe_one, sub_self],
have ne_zero : ((x' i) - 1 : α) ≠ 0,
by rwa [(≠), sub_eq_zero, ← units.coe_one, ← units.ext_iff],
begin
rw mul_eq_zero at eq_zero,
exact eq_zero.resolve_right ne_zero
end
lemma geom_sum_uroot' {x : α} {k : ℕ} (hx : is_k_uroot x k) (i : ℕ) (h : x^i ≠ 1):
geom_sum0 (x^i) k = 0 :=
have eq_zero : geom_sum0 (x^i) k * (x^i - 1) = 0, from
calc geom_sum0 (x^i) k * (x^i - 1) = (x^i)^k - 1 : geom_sum_mul _ _
... = (x^(k * i)) - 1 : by rw[mul_comm, pow_mul]
... = 0 : by simp only [pow_mul, one_pow, hx.2, sub_self],
have ne_zero : x^i - 1 ≠ 0,
by rwa [(≠), sub_eq_zero],
begin
rw mul_eq_zero at eq_zero,
exact eq_zero.resolve_right ne_zero
end
lemma geom_sum_uroot'' {x : β} {k : ℕ} (hx : is_k_uroot x k) (i : ℤ) (h : x^i ≠ 1):
geom_sum0 (x^i) k = 0 :=
have eq_zero : geom_sum0 (x^i) k * (x^i - 1) = 0, from
calc geom_sum0 (x^i) k * (x^i - 1) = (x^i)^k - 1 : geom_sum_mul _ _
... = (x^(k * i : ℤ)) - 1 : by rw [mul_comm, fpow_mul, fpow_of_nat]
... = _ : by rw [fpow_mul, fpow_of_nat, hx.2, one_fpow, sub_self],
have ne_zero : x^i - 1 ≠ 0,
by rwa [(≠), sub_eq_zero],
begin
rw mul_eq_zero at eq_zero,
exact eq_zero.resolve_right ne_zero
end
-- Only necessary for more general framework:
lemma uroot_pow_one {x : β} {k : ℕ} (hx : is_primitive_k_uroot x k)
(i : ℕ) (h : k ∣ i) :
x^i=1 :=
match h with ⟨d,hd⟩ := by rw [hd, pow_mul,hx.1.2,one_pow]
end
-- lemma uroot_pow_not_one {x : β} {k : ℕ} (hx : is_primitive_k_uroot x k)
-- (i : nat) (h : ¬ (k ∣ i)) :
-- x^i ≠ 1 := sorry
end geom_sum_uroot
--- Spcial case of Thoerem 13.7, as used in proof of Lemma 13.10
open complex
local notation `π` := real.pi
noncomputable def ζk (k : ℤ) : ℂ := exp (2*π*I/k)
lemma abs_of_uroot (k : ℤ): abs (ζk k) = 1 :=
calc abs (exp (2*π*I/k))
= abs (exp 0) : by rw abs_exp_eq_iff_re_eq; simp [div_eq_mul_inv]
... = 1 : by simp
-- Lemma 13.5 special case(s)
lemma pi_ne_zero : real.pi ≠ 0 :=
ne_of_gt real.pi_pos
lemma my_exp_nat_mul (z: ℂ) (n : ℕ) : complex.exp z ^ n = complex.exp (z*n) :=
by rw[←exp_nat_mul,mul_comm]
lemma my_exp_int_mul (z: ℂ) : ∀ n : ℤ, complex.exp z ^ n= complex.exp (z*n)
| (int.of_nat n) := my_exp_nat_mul z n
| -[1+n] :=
calc exp z ^ -[1+ n] = exp z ^ -((n:ℤ) + 1) : rfl
... = exp z ^ -(1 * ((n:ℤ)+1)) : by rw [one_mul]
... = ((exp z)^(-1:ℤ)) ^ ((n:ℤ)+1) : by rw [neg_mul_eq_neg_mul, fpow_mul]
... = ((exp z)^(-1:ℤ)) ^ (n+1) : rfl
... = (exp (-z)) ^ (n+1) : by rw [fpow_inv, exp_neg]
... = exp (-z*(n+1)) : my_exp_nat_mul _ _
... = exp (z*(-(n+1))) : by rw [←neg_mul_eq_neg_mul, neg_mul_eq_mul_neg]
-- ... = exp (z * ↑-[1+ n]) : rfl
lemma exp_2piI_eq : exp (2*π*I)=1 :=
have h : ∃ (n : ℤ), 1 * (2 * ↑π * I) = ↑n * (2 * ↑π * I) :=
by existsi (1:ℤ); simp, by rwa [←one_mul (2 * ↑π * I), complex.exp_eq_one_iff]
lemma foo (k : ℕ) : (ζk k)^k=1 :=
if h : k =0 then by rw [h, pow_zero]
else
calc (ζk k)^k = exp ((2*π*I/k)*k) : my_exp_int_mul _ k
... = 1 : by rw [div_mul_cancel, exp_2piI_eq]; simp [h]
lemma bar (k n : ℤ) (hknz : k ≠ 0): (ζk k)^n =1 ↔ k∣ n :=
have h : (ζk k)^n=exp ((n/k) * (2 * π * I)) :=
calc (ζk k)^n= _ : my_exp_int_mul _ n
... = exp ((n/k) * (2 * π * I)) :
by simp[div_eq_mul_inv, mul_assoc, mul_comm, mul_left_comm],
calc (ζk k)^n =1 ↔ exp ((n/k) * (2 * π * I)) =1 : by rw h
... ↔ (∃ (i : ℤ), (i : ℂ) * k = n) :
by simp [exp_eq_one_iff, domain.mul_right_inj, I_ne_zero, pi_ne_zero, two_ne_zero',
div_eq_iff_mul_eq, hknz]
... ↔ k ∣ n :
begin
refine exists_congr (assume i, _),
rw [← int.cast_mul, int.cast_inj, mul_comm, eq_comm],
end
lemma geom_sum_uroot_pow_nmid (k : ℕ) (i : ℤ) (hnmid : ¬ (k : ℤ) ∣ i) :
geom_sum0 ((ζk k)^i) k = 0 :=
if h : k =0 then by simp [geom_sum0, h]
else
have hh : (k:ℤ) ≠ 0 := by simp[h],
have X : ζk ↑k ^ i ≠ 1 := by simp [bar (k:ℤ) i hh, hnmid],
have hpow1 : (ζk ↑k ^ i) ^ k = 1 :=
calc (ζk ↑k ^ i) ^ k = (ζk ↑k ^ i) ^ (k:ℤ) : rfl
... = (ζk ↑k ^ ↑k)^ i : by rw[←fpow_mul,mul_comm,fpow_mul]
... = (ζk k ^ k)^ i : by refl
... = 1 : by rw [foo, one_fpow],
begin
rw [geom_sum0, geom_sum,hpow1],
simpa,
end
lemma geom_sum_uroot_pow_mid (k : ℕ) (i : ℤ) (hmid: (k : ℤ) ∣ i) :
geom_sum0 ((ζk k)^i) k = k :=
if h : k =0 then by simp [geom_sum0, h]
else
have hh : (k:ℤ) ≠ 0 := by simp[h],
calc geom_sum0 ((ζk k)^i) k = geom_sum0 1 k : by rw [(bar k i hh).2 hmid]
... = k : geom_sum_one
lemma pick_out_div (m i e : ℕ) (h1 : i < m) (h2 : e < m) : e=i ↔ (m:ℤ) ∣ e-i :=
have hm : -(m:ℤ) <e-i := by linarith,
have he : (e:ℤ)-i<m := by linarith,
have hmpos : (m:ℤ) ≥ 0 := by linarith,
begin
split,
intro,
simp*,
rintro ⟨k, hk⟩,
have X : (m:ℤ)=↑m*1 := by rw [mul_one],
rw [X,hk] at he,
rw [X,hk,neg_mul_eq_mul_neg] at hm,
have hk1 : k < 1 :=lt_of_mul_lt_mul_left he hmpos,
have hkneg1 : -1 < k :=lt_of_mul_lt_mul_left hm hmpos,
have hk0 : k=0 := by linarith,
rw [hk0,mul_zero, ←neg_add_eq_sub] at hk,
linarith,
end
open polynomial
lemma zetak_ne_zero (k : ℤ) : ζk k ≠ 0 := exp_ne_zero _
lemma pick_out_coef' (f : polynomial ℂ) (m i : ℕ)
(h1 : i < m) (h2 : m > nat_degree f) (r : ℂ) (h3 : r ≠ 0):
(range m).sum (λ j, (eval (r*(ζk m)^j) f)/(r^i * (ζk m)^(i*j)) ) = (coeff f i) * m :=
let ζ := (ζk m) in
calc (range m).sum (λ j, (eval (r*ζ^j) f)/(r^i * ζ^(i*j)) )
= (range m).sum (λ j,(f.support.sum (λ e,(f.to_fun e)*(r*ζ^j)^e))*(r^i * ζ^(i*j))⁻¹) : rfl
... = (range m).sum (λ j,f.support.sum (λ e,(f.to_fun e)*(r*ζ^j)^e*(r^i * ζ^(i*j))⁻¹))
: by congr; funext; rw [sum_mul] --by simp[sum_mul]
... = f.support.sum (λ e,(range m).sum (λ j,(f.to_fun e)*(r*ζ^j)^e*(r^i * ζ^(i*j))⁻¹))
: sum_comm -- rw [sum_comm] also works here, but not simp ...
... = f.support.sum (λ e,(range m).sum (λ j,(f.to_fun e)*r^((e:ℤ)-i)*ζ^((j:ℤ)*(e-i)))) :
begin
simp [-sub_eq_add_neg, fpow_sub, h3, mul_sub, zetak_ne_zero, mul_fpow, mul_inv', mul_assoc, mul_comm, mul_left_comm, div_eq_mul_inv, -fpow_of_nat,
(fpow_of_nat _ _).symm, -fpow_mul, (fpow_mul _ _ _).symm],
end
... = f.support.sum (λ e,(f.to_fun e)*r^((e:ℤ)-i)*(range m).sum (λ j,ζ^((j:ℤ)*(e-i))))
: by simp only [mul_sum, eq_self_iff_true, sub_eq_add_neg]
... = f.support.sum (λ e,(f.to_fun e)*r^((e:ℤ)-i)*(range m).sum (λ j,(ζ^((e:ℤ)-i))^(j:ℤ)))
: by congr; funext; congr; funext; rw [mul_comm, fpow_mul]
... = f.support.sum (λ e,(f.to_fun e)*r^((e:ℤ)-i)*geom_sum0 (ζ^((e:ℤ)-i)) m)
: rfl
... = (f.to_fun i)*r^((i:ℤ)-i)*geom_sum0 (ζ^((i:ℤ)-i)) m :
begin
refine sum_eq_single i _ _,
intros e hes henei,
have heltdf : e ≤ nat_degree f :=
have hc : coeff f e ≠ 0 := finsupp.mem_support_iff.1 hes,
le_nat_degree_of_ne_zero hc,
have heltm : e < m := begin linarith, end,
change ¬ e = i at henei,
have hnmid : ¬ (m:ℤ) ∣ e-i := mt (pick_out_div m i e h1 heltm).2 henei,
have hsum0 : geom_sum0 (ζ ^ (↑e - ↑i)) m =0 := by rw[geom_sum_uroot_pow_nmid]; exact hnmid,
rw[hsum0,mul_zero],
intro h,
have hfi0 : f.to_fun i = 0 := (finsupp.not_mem_support_iff).1 h,
rw[hfi0,mul_assoc,zero_mul],
end
... = (coeff f i) * m
: by rw[sub_eq_zero.2, fpow_zero, fpow_zero, geom_sum_one, coeff]; simp
lemma pick_out_coef (f : polynomial ℂ) (i m : ℕ)
(h1 : m > i) (h2 : m > nat_degree f) (r : ℝ) (h3 : r > 0) :
(coeff f i) * m = (range m).sum (λ j,
(eval (r*(ζk m)^j) f)/(r^i * (ζk m)^(i*j))) :=
eq.symm $ pick_out_coef' f m i h1 h2 (r:ℂ) $
by simp only [*, ne_of_gt h3, ne.def, not_false_iff, complex.of_real_eq_zero]
|
6efc1fba1a1e144ac1ca0a8abfcfb8b1901ebb78 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/combinatorics/composition_auto.lean | eb39cc47ca2bc4771fe090e7cb2f585acadca45a | [] | 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 | 28,728 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.fintype.card
import Mathlib.data.finset.sort
import Mathlib.tactic.omega.default
import Mathlib.algebra.big_operators.order
import Mathlib.PostPort
universes l u_1
namespace Mathlib
/-!
# Compositions
A composition of a natural number `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum
of positive integers. Combinatorially, it corresponds to a decomposition of `{0, ..., n-1}` into
non-empty blocks of consecutive integers, where the `iⱼ` are the lengths of the blocks.
This notion is closely related to that of a partition of `n`, but in a composition of `n` the
order of the `iⱼ`s matters.
We implement two different structures covering these two viewpoints on compositions. The first
one, made of a list of positive integers summing to `n`, is the main one and is called
`composition n`. The second one is useful for combinatorial arguments (for instance to show that
the number of compositions of `n` is `2^(n-1)`). It is given by a subset of `{0, ..., n}`
containing `0` and `n`, where the elements of the subset (other than `n`) correspond to the leftmost
points of each block. The main API is built on `composition n`, and we provide an equivalence
between the two types.
## Main functions
* `c : composition n` is a structure, made of a list of integers which are all positive and
add up to `n`.
* `composition_card` states that the cardinality of `composition n` is exactly
`2^(n-1)`, which is proved by constructing an equiv with `composition_as_set n` (see below), which
is itself in bijection with the subsets of `fin (n-1)` (this holds even for `n = 0`, where `-` is
nat subtraction).
Let `c : composition n` be a composition of `n`. Then
* `c.blocks` is the list of blocks in `c`.
* `c.length` is the number of blocks in the composition.
* `c.blocks_fun : fin c.length → ℕ` is the realization of `c.blocks` as a function on
`fin c.length`. This is the main object when using compositions to understand the composition of
analytic functions.
* `c.size_up_to : ℕ → ℕ` is the sum of the size of the blocks up to `i`.;
* `c.embedding i : fin (c.blocks_fun i) → fin n` is the increasing embedding of the `i`-th block in
`fin n`;
* `c.index j`, for `j : fin n`, is the index of the block containing `j`.
* `composition.ones n` is the composition of `n` made of ones, i.e., `[1, ..., 1]`.
* `composition.single n (hn : 0 < n)` is the composition of `n` made of a single block of size `n`.
Compositions can also be used to split lists. Let `l` be a list of length `n` and `c` a composition
of `n`.
* `l.split_wrt_composition c` is a list of lists, made of the slices of `l` corresponding to the
blocks of `c`.
* `join_split_wrt_composition` states that splitting a list and then joining it gives back the
original list.
* `split_wrt_composition_join` states that joining a list of lists, and then splitting it back
according to the right composition, gives back the original list of lists.
We turn to the second viewpoint on compositions, that we realize as a finset of `fin (n+1)`.
`c : composition_as_set n` is a structure made of a finset of `fin (n+1)` called `c.boundaries`
and proofs that it contains `0` and `n`. (Taking a finset of `fin n` containing `0` would not
make sense in the edge case `n = 0`, while the previous description works in all cases).
The elements of this set (other than `n`) correspond to leftmost points of blocks.
Thus, there is an equiv between `composition n` and `composition_as_set n`. We
only construct basic API on `composition_as_set` (notably `c.length` and `c.blocks`) to be able
to construct this equiv, called `composition_equiv n`. Since there is a straightforward equiv
between `composition_as_set n` and finsets of `{1, ..., n-1}` (obtained by removing `0` and `n`
from a `composition_as_set` and called `composition_as_set_equiv n`), we deduce that
`composition_as_set n` and `composition n` are both fintypes of cardinality `2^(n - 1)`
(see `composition_as_set_card` and `composition_card`).
## Implementation details
The main motivation for this structure and its API is in the construction of the composition of
formal multilinear series, and the proof that the composition of analytic functions is analytic.
The representation of a composition as a list is very handy as lists are very flexible and already
have a well-developed API.
## Tags
Composition, partition
## References
<https://en.wikipedia.org/wiki/Composition_(combinatorics)>
-/
/-- A composition of `n` is a list of positive integers summing to `n`. -/
structure composition (n : ℕ) where
blocks : List ℕ
blocks_pos : ∀ {i : ℕ}, i ∈ blocks → 0 < i
blocks_sum : list.sum blocks = n
/-- Combinatorial viewpoint on a composition of `n`, by seeing it as non-empty blocks of
consecutive integers in `{0, ..., n-1}`. We register every block by its left end-point, yielding
a finset containing `0`. As this does not make sense for `n = 0`, we add `n` to this finset, and
get a finset of `{0, ..., n}` containing `0` and `n`. This is the data in the structure
`composition_as_set n`. -/
structure composition_as_set (n : ℕ) where
boundaries : finset (fin (Nat.succ n))
zero_mem : 0 ∈ boundaries
last_mem : fin.last n ∈ boundaries
protected instance composition_as_set.inhabited {n : ℕ} : Inhabited (composition_as_set n) :=
{ default := composition_as_set.mk finset.univ sorry sorry }
/-!
### Compositions
A composition of an integer `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of
positive integers.
-/
namespace composition
protected instance has_to_string (n : ℕ) : has_to_string (composition n) :=
has_to_string.mk fun (c : composition n) => to_string (blocks c)
/-- The length of a composition, i.e., the number of blocks in the composition. -/
def length {n : ℕ} (c : composition n) : ℕ := list.length (blocks c)
theorem blocks_length {n : ℕ} (c : composition n) : list.length (blocks c) = length c := rfl
/-- The blocks of a composition, seen as a function on `fin c.length`. When composing analytic
functions using compositions, this is the main player. -/
def blocks_fun {n : ℕ} (c : composition n) : fin (length c) → ℕ :=
fun (i : fin (length c)) => list.nth_le (blocks c) ↑i sorry
theorem of_fn_blocks_fun {n : ℕ} (c : composition n) : list.of_fn (blocks_fun c) = blocks c :=
list.of_fn_nth_le (blocks c)
theorem sum_blocks_fun {n : ℕ} (c : composition n) :
(finset.sum finset.univ fun (i : fin (length c)) => blocks_fun c i) = n :=
sorry
theorem blocks_fun_mem_blocks {n : ℕ} (c : composition n) (i : fin (length c)) :
blocks_fun c i ∈ blocks c :=
list.nth_le_mem (blocks c) (↑i) (blocks_fun._proof_1 c i)
@[simp] theorem one_le_blocks {n : ℕ} (c : composition n) {i : ℕ} (h : i ∈ blocks c) : 1 ≤ i :=
blocks_pos c h
@[simp] theorem one_le_blocks' {n : ℕ} (c : composition n) {i : ℕ} (h : i < length c) :
1 ≤ list.nth_le (blocks c) i h :=
one_le_blocks c (list.nth_le_mem (blocks c) i h)
@[simp] theorem blocks_pos' {n : ℕ} (c : composition n) (i : ℕ) (h : i < length c) :
0 < list.nth_le (blocks c) i h :=
one_le_blocks' c h
theorem one_le_blocks_fun {n : ℕ} (c : composition n) (i : fin (length c)) : 1 ≤ blocks_fun c i :=
one_le_blocks c (blocks_fun_mem_blocks c i)
theorem length_le {n : ℕ} (c : composition n) : length c ≤ n := sorry
theorem length_pos_of_pos {n : ℕ} (c : composition n) (h : 0 < n) : 0 < length c := sorry
/-- The sum of the sizes of the blocks in a composition up to `i`. -/
def size_up_to {n : ℕ} (c : composition n) (i : ℕ) : ℕ := list.sum (list.take i (blocks c))
@[simp] theorem size_up_to_zero {n : ℕ} (c : composition n) : size_up_to c 0 = 0 := sorry
theorem size_up_to_of_length_le {n : ℕ} (c : composition n) (i : ℕ) (h : length c ≤ i) :
size_up_to c i = n :=
sorry
@[simp] theorem size_up_to_length {n : ℕ} (c : composition n) : size_up_to c (length c) = n :=
size_up_to_of_length_le c (length c) (le_refl (length c))
theorem size_up_to_le {n : ℕ} (c : composition n) (i : ℕ) : size_up_to c i ≤ n := sorry
theorem size_up_to_succ {n : ℕ} (c : composition n) {i : ℕ} (h : i < length c) :
size_up_to c (i + 1) = size_up_to c i + list.nth_le (blocks c) i h :=
sorry
theorem size_up_to_succ' {n : ℕ} (c : composition n) (i : fin (length c)) :
size_up_to c (↑i + 1) = size_up_to c ↑i + blocks_fun c i :=
size_up_to_succ c (subtype.property i)
theorem size_up_to_strict_mono {n : ℕ} (c : composition n) {i : ℕ} (h : i < length c) :
size_up_to c i < size_up_to c (i + 1) :=
sorry
theorem monotone_size_up_to {n : ℕ} (c : composition n) : monotone (size_up_to c) :=
list.monotone_sum_take (blocks c)
/-- The `i`-th boundary of a composition, i.e., the leftmost point of the `i`-th block. We include
a virtual point at the right of the last block, to make for a nice equiv with
`composition_as_set n`. -/
def boundary {n : ℕ} (c : composition n) : fin (length c + 1) ↪o fin (n + 1) :=
order_embedding.of_strict_mono
(fun (i : fin (length c + 1)) => { val := size_up_to c ↑i, property := sorry }) sorry
@[simp] theorem boundary_zero {n : ℕ} (c : composition n) : coe_fn (boundary c) 0 = 0 := sorry
@[simp] theorem boundary_last {n : ℕ} (c : composition n) :
coe_fn (boundary c) (fin.last (length c)) = fin.last n :=
sorry
/-- The boundaries of a composition, i.e., the leftmost point of all the blocks. We include
a virtual point at the right of the last block, to make for a nice equiv with
`composition_as_set n`. -/
def boundaries {n : ℕ} (c : composition n) : finset (fin (n + 1)) :=
finset.map (rel_embedding.to_embedding (boundary c)) finset.univ
theorem card_boundaries_eq_succ_length {n : ℕ} (c : composition n) :
finset.card (boundaries c) = length c + 1 :=
sorry
/-- To `c : composition n`, one can associate a `composition_as_set n` by registering the leftmost
point of each block, and adding a virtual point at the right of the last block. -/
def to_composition_as_set {n : ℕ} (c : composition n) : composition_as_set n :=
composition_as_set.mk (boundaries c) sorry sorry
/-- The canonical increasing bijection between `fin (c.length + 1)` and `c.boundaries` is
exactly `c.boundary`. -/
theorem order_emb_of_fin_boundaries {n : ℕ} (c : composition n) :
finset.order_emb_of_fin (boundaries c) (card_boundaries_eq_succ_length c) = boundary c :=
sorry
/-- Embedding the `i`-th block of a composition (identified with `fin (c.blocks_fun i)`) into
`fin n` at the relevant position. -/
def embedding {n : ℕ} (c : composition n) (i : fin (length c)) : fin (blocks_fun c i) ↪o fin n :=
rel_embedding.trans (fin.nat_add (size_up_to c ↑i)) (fin.cast_le sorry)
@[simp] theorem coe_embedding {n : ℕ} (c : composition n) (i : fin (length c))
(j : fin (blocks_fun c i)) : ↑(coe_fn (embedding c i) j) = size_up_to c ↑i + ↑j :=
rfl
/--
`index_exists` asserts there is some `i` with `j < c.size_up_to (i+1)`.
In the next definition `index` we use `nat.find` to produce the minimal such index.
-/
theorem index_exists {n : ℕ} (c : composition n) {j : ℕ} (h : j < n) :
∃ (i : ℕ), j < size_up_to c (Nat.succ i) ∧ i < length c :=
sorry
/-- `c.index j` is the index of the block in the composition `c` containing `j`. -/
def index {n : ℕ} (c : composition n) (j : fin n) : fin (length c) :=
{ val := nat.find sorry, property := sorry }
theorem lt_size_up_to_index_succ {n : ℕ} (c : composition n) (j : fin n) :
↑j < size_up_to c ↑(fin.succ (index c j)) :=
and.left (nat.find_spec (index_exists c (subtype.property j)))
theorem size_up_to_index_le {n : ℕ} (c : composition n) (j : fin n) :
size_up_to c ↑(index c j) ≤ ↑j :=
sorry
/-- Mapping an element `j` of `fin n` to the element in the block containing it, identified with
`fin (c.blocks_fun (c.index j))` through the canonical increasing bijection. -/
def inv_embedding {n : ℕ} (c : composition n) (j : fin n) : fin (blocks_fun c (index c j)) :=
{ val := ↑j - size_up_to c ↑(index c j), property := sorry }
@[simp] theorem coe_inv_embedding {n : ℕ} (c : composition n) (j : fin n) :
↑(inv_embedding c j) = ↑j - size_up_to c ↑(index c j) :=
rfl
theorem embedding_comp_inv {n : ℕ} (c : composition n) (j : fin n) :
coe_fn (embedding c (index c j)) (inv_embedding c j) = j :=
sorry
theorem mem_range_embedding_iff {n : ℕ} (c : composition n) {j : fin n} {i : fin (length c)} :
j ∈ set.range ⇑(embedding c i) ↔ size_up_to c ↑i ≤ ↑j ∧ ↑j < size_up_to c (Nat.succ ↑i) :=
sorry
/-- The embeddings of different blocks of a composition are disjoint. -/
theorem disjoint_range {n : ℕ} (c : composition n) {i₁ : fin (length c)} {i₂ : fin (length c)}
(h : i₁ ≠ i₂) : disjoint (set.range ⇑(embedding c i₁)) (set.range ⇑(embedding c i₂)) :=
sorry
theorem mem_range_embedding {n : ℕ} (c : composition n) (j : fin n) :
j ∈ set.range ⇑(embedding c (index c j)) :=
sorry
theorem mem_range_embedding_iff' {n : ℕ} (c : composition n) {j : fin n} {i : fin (length c)} :
j ∈ set.range ⇑(embedding c i) ↔ i = index c j :=
sorry
theorem index_embedding {n : ℕ} (c : composition n) (i : fin (length c))
(j : fin (blocks_fun c i)) : index c (coe_fn (embedding c i) j) = i :=
sorry
theorem inv_embedding_comp {n : ℕ} (c : composition n) (i : fin (length c))
(j : fin (blocks_fun c i)) : ↑(inv_embedding c (coe_fn (embedding c i) j)) = ↑j :=
sorry
/-- Equivalence between the disjoint union of the blocks (each of them seen as
`fin (c.blocks_fun i)`) with `fin n`. -/
def blocks_fin_equiv {n : ℕ} (c : composition n) :
(sigma fun (i : fin (length c)) => fin (blocks_fun c i)) ≃ fin n :=
equiv.mk
(fun (x : sigma fun (i : fin (length c)) => fin (blocks_fun c i)) =>
coe_fn (embedding c (sigma.fst x)) (sigma.snd x))
(fun (j : fin n) => sigma.mk (index c j) (inv_embedding c j)) sorry sorry
theorem blocks_fun_congr {n₁ : ℕ} {n₂ : ℕ} (c₁ : composition n₁) (c₂ : composition n₂)
(i₁ : fin (length c₁)) (i₂ : fin (length c₂)) (hn : n₁ = n₂) (hc : blocks c₁ = blocks c₂)
(hi : ↑i₁ = ↑i₂) : blocks_fun c₁ i₁ = blocks_fun c₂ i₂ :=
sorry
/-- Two compositions (possibly of different integers) coincide if and only if they have the
same sequence of blocks. -/
theorem sigma_eq_iff_blocks_eq {c : sigma fun (n : ℕ) => composition n}
{c' : sigma fun (n : ℕ) => composition n} :
c = c' ↔ blocks (sigma.snd c) = blocks (sigma.snd c') :=
sorry
/-! ### The composition `composition.ones` -/
/-- The composition made of blocks all of size `1`. -/
def ones (n : ℕ) : composition n := mk (list.repeat 1 n) sorry sorry
protected instance inhabited {n : ℕ} : Inhabited (composition n) := { default := ones n }
@[simp] theorem ones_length (n : ℕ) : length (ones n) = n := list.length_repeat 1 n
@[simp] theorem ones_blocks (n : ℕ) : blocks (ones n) = list.repeat 1 n := rfl
@[simp] theorem ones_blocks_fun (n : ℕ) (i : fin (length (ones n))) : blocks_fun (ones n) i = 1 :=
sorry
@[simp] theorem ones_size_up_to (n : ℕ) (i : ℕ) : size_up_to (ones n) i = min i n := sorry
@[simp] theorem ones_embedding {n : ℕ} (i : fin (length (ones n))) (h : 0 < blocks_fun (ones n) i) :
coe_fn (embedding (ones n) i) { val := 0, property := h } =
{ val := ↑i, property := lt_of_lt_of_le (subtype.property i) (length_le (ones n)) } :=
sorry
theorem eq_ones_iff {n : ℕ} {c : composition n} : c = ones n ↔ ∀ (i : ℕ), i ∈ blocks c → i = 1 :=
sorry
theorem ne_ones_iff {n : ℕ} {c : composition n} :
c ≠ ones n ↔ ∃ (i : ℕ), ∃ (H : i ∈ blocks c), 1 < i :=
sorry
theorem eq_ones_iff_length {n : ℕ} {c : composition n} : c = ones n ↔ length c = n := sorry
theorem eq_ones_iff_le_length {n : ℕ} {c : composition n} : c = ones n ↔ n ≤ length c := sorry
/-! ### The composition `composition.single` -/
/-- The composition made of a single block of size `n`. -/
def single (n : ℕ) (h : 0 < n) : composition n := mk [n] sorry sorry
@[simp] theorem single_length {n : ℕ} (h : 0 < n) : length (single n h) = 1 := rfl
@[simp] theorem single_blocks {n : ℕ} (h : 0 < n) : blocks (single n h) = [n] := rfl
@[simp] theorem single_blocks_fun {n : ℕ} (h : 0 < n) (i : fin (length (single n h))) :
blocks_fun (single n h) i = n :=
sorry
@[simp] theorem single_embedding {n : ℕ} (h : 0 < n) (i : fin n) :
coe_fn (embedding (single n h) { val := 0, property := single_length h ▸ zero_lt_one }) i = i :=
sorry
theorem eq_single_iff_length {n : ℕ} (h : 0 < n) {c : composition n} :
c = single n h ↔ length c = 1 :=
sorry
theorem ne_single_iff {n : ℕ} (hn : 0 < n) {c : composition n} :
c ≠ single n hn ↔ ∀ (i : fin (length c)), blocks_fun c i < n :=
sorry
end composition
/-!
### Splitting a list
Given a list of length `n` and a composition `c` of `n`, one can split `l` into `c.length` sublists
of respective lengths `c.blocks_fun 0`, ..., `c.blocks_fun (c.length-1)`. This is inverse to the
join operation.
-/
namespace list
/-- Auxiliary for `list.split_wrt_composition`. -/
def split_wrt_composition_aux {α : Type u_1} : List α → List ℕ → List (List α) := sorry
/-- Given a list of length `n` and a composition `[i₁, ..., iₖ]` of `n`, split `l` into a list of
`k` lists corresponding to the blocks of the composition, of respective lengths `i₁`, ..., `iₖ`.
This makes sense mostly when `n = l.length`, but this is not necessary for the definition. -/
def split_wrt_composition {n : ℕ} {α : Type u_1} (l : List α) (c : composition n) : List (List α) :=
split_wrt_composition_aux l (composition.blocks c)
theorem split_wrt_composition_aux_cons {α : Type u_1} (l : List α) (n : ℕ) (ns : List ℕ) :
split_wrt_composition_aux l (n :: ns) = take n l :: split_wrt_composition_aux (drop n l) ns :=
sorry
theorem length_split_wrt_composition_aux {α : Type u_1} (l : List α) (ns : List ℕ) :
length (split_wrt_composition_aux l ns) = length ns :=
sorry
/-- When one splits a list along a composition `c`, the number of sublists thus created is
`c.length`. -/
@[simp] theorem length_split_wrt_composition {n : ℕ} {α : Type u_1} (l : List α)
(c : composition n) : length (split_wrt_composition l c) = composition.length c :=
length_split_wrt_composition_aux l (composition.blocks c)
theorem map_length_split_wrt_composition_aux {α : Type u_1} {ns : List ℕ} {l : List α} :
sum ns ≤ length l → map length (split_wrt_composition_aux l ns) = ns :=
sorry
/-- When one splits a list along a composition `c`, the lengths of the sublists thus created are
given by the block sizes in `c`. -/
theorem map_length_split_wrt_composition {α : Type u_1} (l : List α) (c : composition (length l)) :
map length (split_wrt_composition l c) = composition.blocks c :=
map_length_split_wrt_composition_aux (le_of_eq (composition.blocks_sum c))
theorem length_pos_of_mem_split_wrt_composition {α : Type u_1} {l : List α} {l' : List α}
{c : composition (length l)} (h : l' ∈ split_wrt_composition l c) : 0 < length l' :=
sorry
theorem sum_take_map_length_split_wrt_composition {α : Type u_1} (l : List α)
(c : composition (length l)) (i : ℕ) :
sum (take i (map length (split_wrt_composition l c))) = composition.size_up_to c i :=
sorry
theorem nth_le_split_wrt_composition_aux {α : Type u_1} (l : List α) (ns : List ℕ) {i : ℕ}
(hi : i < length (split_wrt_composition_aux l ns)) :
nth_le (split_wrt_composition_aux l ns) i hi =
drop (sum (take i ns)) (take (sum (take (i + 1) ns)) l) :=
sorry
/-- The `i`-th sublist in the splitting of a list `l` along a composition `c`, is the slice of `l`
between the indices `c.size_up_to i` and `c.size_up_to (i+1)`, i.e., the indices in the `i`-th
block of the composition. -/
theorem nth_le_split_wrt_composition {n : ℕ} {α : Type u_1} (l : List α) (c : composition n) {i : ℕ}
(hi : i < length (split_wrt_composition l c)) :
nth_le (split_wrt_composition l c) i hi =
drop (composition.size_up_to c i) (take (composition.size_up_to c (i + 1)) l) :=
nth_le_split_wrt_composition_aux l (composition.blocks c) hi
theorem join_split_wrt_composition_aux {α : Type u_1} {ns : List ℕ} {l : List α} :
sum ns = length l → join (split_wrt_composition_aux l ns) = l :=
sorry
/-- If one splits a list along a composition, and then joins the sublists, one gets back the
original list. -/
@[simp] theorem join_split_wrt_composition {α : Type u_1} (l : List α)
(c : composition (length l)) : join (split_wrt_composition l c) = l :=
join_split_wrt_composition_aux (composition.blocks_sum c)
/-- If one joins a list of lists and then splits the join along the right composition, one gets
back the original list of lists. -/
@[simp] theorem split_wrt_composition_join {α : Type u_1} (L : List (List α))
(c : composition (length (join L))) (h : map length L = composition.blocks c) :
split_wrt_composition (join L) c = L :=
sorry
end list
/-!
### Compositions as sets
Combinatorial viewpoints on compositions, seen as finite subsets of `fin (n+1)` containing `0` and
`n`, where the points of the set (other than `n`) correspond to the leftmost points of each block.
-/
/-- Bijection between compositions of `n` and subsets of `{0, ..., n-2}`, defined by
considering the restriction of the subset to `{1, ..., n-1}` and shifting to the left by one. -/
def composition_as_set_equiv (n : ℕ) : composition_as_set n ≃ finset (fin (n - 1)) :=
equiv.mk
(fun (c : composition_as_set n) =>
set.to_finset
(set_of
fun (i : fin (n - 1)) =>
{ val := 1 + ↑i, property := sorry } ∈ composition_as_set.boundaries c))
(fun (s : finset (fin (n - 1))) =>
composition_as_set.mk
(set.to_finset
(set_of
fun (i : fin (Nat.succ n)) =>
i = 0 ∨ i = fin.last n ∨ ∃ (j : fin (n - 1)), ∃ (hj : j ∈ s), ↑i = ↑j + 1))
sorry sorry)
sorry sorry
protected instance composition_as_set_fintype (n : ℕ) : fintype (composition_as_set n) :=
fintype.of_equiv (finset (fin (n - 1))) (equiv.symm (composition_as_set_equiv n))
theorem composition_as_set_card (n : ℕ) : fintype.card (composition_as_set n) = bit0 1 ^ (n - 1) :=
sorry
namespace composition_as_set
theorem boundaries_nonempty {n : ℕ} (c : composition_as_set n) : finset.nonempty (boundaries c) :=
Exists.intro 0 (zero_mem c)
theorem card_boundaries_pos {n : ℕ} (c : composition_as_set n) : 0 < finset.card (boundaries c) :=
iff.mpr finset.card_pos (boundaries_nonempty c)
/-- Number of blocks in a `composition_as_set`. -/
def length {n : ℕ} (c : composition_as_set n) : ℕ := finset.card (boundaries c) - 1
theorem card_boundaries_eq_succ_length {n : ℕ} (c : composition_as_set n) :
finset.card (boundaries c) = length c + 1 :=
iff.mp (nat.sub_eq_iff_eq_add (card_boundaries_pos c)) rfl
theorem length_lt_card_boundaries {n : ℕ} (c : composition_as_set n) :
length c < finset.card (boundaries c) :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (length c < finset.card (boundaries c)))
(card_boundaries_eq_succ_length c)))
(lt_add_one (length c))
theorem lt_length {n : ℕ} (c : composition_as_set n) (i : fin (length c)) :
↑i + 1 < finset.card (boundaries c) :=
nat.add_lt_of_lt_sub_right (subtype.property i)
theorem lt_length' {n : ℕ} (c : composition_as_set n) (i : fin (length c)) :
↑i < finset.card (boundaries c) :=
lt_of_le_of_lt (nat.le_succ ↑i) (lt_length c i)
/-- Canonical increasing bijection from `fin c.boundaries.card` to `c.boundaries`. -/
def boundary {n : ℕ} (c : composition_as_set n) : fin (finset.card (boundaries c)) ↪o fin (n + 1) :=
finset.order_emb_of_fin (boundaries c) sorry
@[simp] theorem boundary_zero {n : ℕ} (c : composition_as_set n) :
coe_fn (boundary c) { val := 0, property := card_boundaries_pos c } = 0 :=
sorry
@[simp] theorem boundary_length {n : ℕ} (c : composition_as_set n) :
coe_fn (boundary c) { val := length c, property := length_lt_card_boundaries c } = fin.last n :=
sorry
/-- Size of the `i`-th block in a `composition_as_set`, seen as a function on `fin c.length`. -/
def blocks_fun {n : ℕ} (c : composition_as_set n) (i : fin (length c)) : ℕ :=
↑(coe_fn (boundary c) { val := ↑i + 1, property := lt_length c i }) -
↑(coe_fn (boundary c) { val := ↑i, property := lt_length' c i })
theorem blocks_fun_pos {n : ℕ} (c : composition_as_set n) (i : fin (length c)) :
0 < blocks_fun c i :=
nat.lt_sub_left_of_add_lt
(order_embedding.strict_mono (finset.order_emb_of_fin (boundaries c) rfl)
(nat.lt_succ_self (subtype.val { val := ↑i, property := lt_length' c i })))
/-- List of the sizes of the blocks in a `composition_as_set`. -/
def blocks {n : ℕ} (c : composition_as_set n) : List ℕ := list.of_fn (blocks_fun c)
@[simp] theorem blocks_length {n : ℕ} (c : composition_as_set n) :
list.length (blocks c) = length c :=
list.length_of_fn (blocks_fun c)
theorem blocks_partial_sum {n : ℕ} (c : composition_as_set n) {i : ℕ}
(h : i < finset.card (boundaries c)) :
list.sum (list.take i (blocks c)) = ↑(coe_fn (boundary c) { val := i, property := h }) :=
sorry
theorem mem_boundaries_iff_exists_blocks_sum_take_eq {n : ℕ} (c : composition_as_set n)
{j : fin (n + 1)} :
j ∈ boundaries c ↔
∃ (i : ℕ), ∃ (H : i < finset.card (boundaries c)), list.sum (list.take i (blocks c)) = ↑j :=
sorry
theorem blocks_sum {n : ℕ} (c : composition_as_set n) : list.sum (blocks c) = n := sorry
/-- Associating a `composition n` to a `composition_as_set n`, by registering the sizes of the
blocks as a list of positive integers. -/
def to_composition {n : ℕ} (c : composition_as_set n) : composition n :=
composition.mk (blocks c) sorry (blocks_sum c)
end composition_as_set
/-!
### Equivalence between compositions and compositions as sets
In this section, we explain how to go back and forth between a `composition` and a
`composition_as_set`, by showing that their `blocks` and `length` and `boundaries` correspond to
each other, and construct an equivalence between them called `composition_equiv`.
-/
@[simp] theorem composition.to_composition_as_set_length {n : ℕ} (c : composition n) :
composition_as_set.length (composition.to_composition_as_set c) = composition.length c :=
sorry
@[simp] theorem composition_as_set.to_composition_length {n : ℕ} (c : composition_as_set n) :
composition.length (composition_as_set.to_composition c) = composition_as_set.length c :=
sorry
@[simp] theorem composition.to_composition_as_set_blocks {n : ℕ} (c : composition n) :
composition_as_set.blocks (composition.to_composition_as_set c) = composition.blocks c :=
sorry
@[simp] theorem composition_as_set.to_composition_blocks {n : ℕ} (c : composition_as_set n) :
composition.blocks (composition_as_set.to_composition c) = composition_as_set.blocks c :=
rfl
@[simp] theorem composition_as_set.to_composition_boundaries {n : ℕ} (c : composition_as_set n) :
composition.boundaries (composition_as_set.to_composition c) =
composition_as_set.boundaries c :=
sorry
@[simp] theorem composition.to_composition_as_set_boundaries {n : ℕ} (c : composition n) :
composition_as_set.boundaries (composition.to_composition_as_set c) =
composition.boundaries c :=
rfl
/-- Equivalence between `composition n` and `composition_as_set n`. -/
def composition_equiv (n : ℕ) : composition n ≃ composition_as_set n :=
equiv.mk (fun (c : composition n) => composition.to_composition_as_set c)
(fun (c : composition_as_set n) => composition_as_set.to_composition c) sorry sorry
protected instance composition_fintype (n : ℕ) : fintype (composition n) :=
fintype.of_equiv (composition_as_set n) (equiv.symm (composition_equiv n))
theorem composition_card (n : ℕ) : fintype.card (composition n) = bit0 1 ^ (n - 1) :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (fintype.card (composition n) = bit0 1 ^ (n - 1)))
(Eq.symm (composition_as_set_card n))))
(fintype.card_congr (composition_equiv n))
end Mathlib |
8bc552611cadb9fccbd69343a3b6c7591dcb95a1 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /src/Lean/Compiler/IR/Format.lean | 775fe754a9819b5c3ed4ed3301bd28d716cccf2b | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,921 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.IR.Basic
namespace Lean
namespace IR
private def formatArg : Arg → Format
| Arg.var id => format id
| Arg.irrelevant => "◾"
instance : ToFormat Arg := ⟨formatArg⟩
def formatArray {α : Type} [ToFormat α] (args : Array α) : Format :=
args.foldl (fun r a => r ++ " " ++ format a) Format.nil
private def formatLitVal : LitVal → Format
| LitVal.num v => format v
| LitVal.str v => format (repr v)
instance : ToFormat LitVal := ⟨formatLitVal⟩
private def formatCtorInfo : CtorInfo → Format
| { name := name, cidx := cidx, usize := usize, ssize := ssize, .. } => do
let mut r := f!"ctor_{cidx}"
if usize > 0 || ssize > 0 then
r := f!"{r}.{usize}.{ssize}"
if name != Name.anonymous then
r := f!"{r}[{name}]"
r
instance : ToFormat CtorInfo := ⟨formatCtorInfo⟩
private def formatExpr : Expr → Format
| Expr.ctor i ys => format i ++ formatArray ys
| Expr.reset n x => "reset[" ++ format n ++ "] " ++ format x
| Expr.reuse x i u ys => "reuse" ++ (if u then "!" else "") ++ " " ++ format x ++ " in " ++ format i ++ formatArray ys
| Expr.proj i x => "proj[" ++ format i ++ "] " ++ format x
| Expr.uproj i x => "uproj[" ++ format i ++ "] " ++ format x
| Expr.sproj n o x => "sproj[" ++ format n ++ ", " ++ format o ++ "] " ++ format x
| Expr.fap c ys => format c ++ formatArray ys
| Expr.pap c ys => "pap " ++ format c ++ formatArray ys
| Expr.ap x ys => "app " ++ format x ++ formatArray ys
| Expr.box _ x => "box " ++ format x
| Expr.unbox x => "unbox " ++ format x
| Expr.lit v => format v
| Expr.isShared x => "isShared " ++ format x
| Expr.isTaggedPtr x => "isTaggedPtr " ++ format x
instance : ToFormat Expr := ⟨formatExpr⟩
instance : ToString Expr := ⟨fun e => Format.pretty (format e)⟩
private partial def formatIRType : IRType → Format
| IRType.float => "float"
| IRType.uint8 => "u8"
| IRType.uint16 => "u16"
| IRType.uint32 => "u32"
| IRType.uint64 => "u64"
| IRType.usize => "usize"
| IRType.irrelevant => "◾"
| IRType.object => "obj"
| IRType.tobject => "tobj"
| IRType.struct _ tys => "struct " ++ Format.bracket "{" (@Format.joinSep _ ⟨formatIRType⟩ tys.toList ", ") "}"
| IRType.union _ tys => "union " ++ Format.bracket "{" (@Format.joinSep _ ⟨formatIRType⟩ tys.toList ", ") "}"
instance : ToFormat IRType := ⟨formatIRType⟩
instance : ToString IRType := ⟨toString ∘ format⟩
private def formatParam : Param → Format
| { x := name, borrow := b, ty := ty } => "(" ++ format name ++ " : " ++ (if b then "@& " else "") ++ format ty ++ ")"
instance : ToFormat Param := ⟨formatParam⟩
def formatAlt (fmt : FnBody → Format) (indent : Nat) : Alt → Format
| Alt.ctor i b => format i.name ++ " →" ++ Format.nest indent (Format.line ++ fmt b)
| Alt.default b => "default →" ++ Format.nest indent (Format.line ++ fmt b)
def formatParams (ps : Array Param) : Format :=
formatArray ps
@[export lean_ir_format_fn_body_head]
def formatFnBodyHead : FnBody → Format
| FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e
| FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " := ..."
| FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y
| FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y
| FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y
| FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx
| FnBody.inc x n c _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x
| FnBody.dec x n c _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x
| FnBody.del x b => "del " ++ format x
| FnBody.mdata d b => "mdata " ++ format d
| FnBody.case tid x xType cs => "case " ++ format x ++ " of ..."
| FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys
| FnBody.ret x => "ret " ++ format x
| FnBody.unreachable => "⊥"
partial def formatFnBody (fnBody : FnBody) (indent : Nat := 2) : Format :=
let rec loop : FnBody → Format
| FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e ++ ";" ++ Format.line ++ loop b
| FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " :=" ++ Format.nest indent (Format.line ++ loop v) ++ ";" ++ Format.line ++ loop b
| FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b
| FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b
| FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y ++ ";" ++ Format.line ++ loop b
| FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx ++ ";" ++ Format.line ++ loop b
| FnBody.inc x n c _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b
| FnBody.dec x n c _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b
| FnBody.del x b => "del " ++ format x ++ ";" ++ Format.line ++ loop b
| FnBody.mdata d b => "mdata " ++ format d ++ ";" ++ Format.line ++ loop b
| FnBody.case tid x xType cs => "case " ++ format x ++ " : " ++ format xType ++ " of" ++ cs.foldl (fun r c => r ++ Format.line ++ formatAlt loop indent c) Format.nil
| FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys
| FnBody.ret x => "ret " ++ format x
| FnBody.unreachable => "⊥"
loop fnBody
instance : ToFormat FnBody := ⟨formatFnBody⟩
instance : ToString FnBody := ⟨fun b => (format b).pretty⟩
def formatDecl (decl : Decl) (indent : Nat := 2) : Format :=
match decl with
| Decl.fdecl f xs ty b => "def " ++ format f ++ formatParams xs ++ format " : " ++ format ty ++ " :=" ++ Format.nest indent (Format.line ++ formatFnBody b indent)
| Decl.extern f xs ty _ => "extern " ++ format f ++ formatParams xs ++ format " : " ++ format ty
instance : ToFormat Decl := ⟨formatDecl⟩
@[export lean_ir_decl_to_string]
def declToString (d : Decl) : String :=
(format d).pretty
instance : ToString Decl := ⟨declToString⟩
end Lean.IR
|
d10a0cacb8676cfaba3c244354dbb2598434dc2e | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/order/filter/bases.lean | 6f87ab1839f7703b70f338e0c468f52d51e0c57f | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 47,478 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import data.prod.pprod
import data.set.countable
import order.filter.prod
/-!
# Filter bases
A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α`
such that the intersection of two elements of this collection contains some element of
the collection. Compared to filters, filter bases do not require that any set containing
an element of `B` belongs to `B`.
A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs
to `B.filter` if and only if it contains an element of `B`.
Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`,
the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p`
(ie. `s '' set_of p`) defines a filter basis `h.filter_basis`.
If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop`
and `s : ι → set α` as above) means that a set belongs to `l` if and
only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and
`l = h.filter_basis.filter`. The point of this definition is that checking statements
involving elements of `l` often reduces to checking them on the basis elements.
We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns
some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual
destruction of `h.mem_iff.mpr ht` using `cases` or `let`.
This file also introduces more restricted classes of bases, involving monotonicity or
countability. In particular, for `l : filter α`, `l.is_countably_generated` means
there is a countable set of sets which generates `s`. This is reformulated in term of bases,
and consequences are derived.
## Main statements
* `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f`
in terms of a basis;
* `basis_sets` : all sets of a filter form a basis;
* `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`,
`has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`,
`l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively;
* `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms
of bases.
* `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate
`tendsto f l l'` in terms of bases.
* `is_countably_generated_iff_exists_antitone_basis` : proves a filter is
countably generated if and only if it admits a basis parametrized by a
decreasing sequence of sets indexed by `ℕ`.
* `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous".
## Implementation notes
As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases:
* `has_basis l s`, `s : set (set α)`;
* `has_basis l s`, `s : ι → set α`;
* `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`.
We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis
of this form. The other two can be emulated using `s = id` or `p = λ _, true`.
With this approach sometimes one needs to `simp` the statement provided by the `has_basis`
machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help
with the case `p = λ _, true`.
-/
open set filter
open_locale filter classical
section sort
variables {α β γ : Type*} {ι ι' : Sort*}
/-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α`
such that the intersection of two elements of this collection contains some element
of the collection. -/
structure filter_basis (α : Type*) :=
(sets : set (set α))
(nonempty : sets.nonempty)
(inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y)
instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype
/-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as
on paper. -/
@[reducible]
instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩
-- For illustration purposes, the filter basis defining (at_top : filter ℕ)
instance : inhabited (filter_basis ℕ) :=
⟨{ sets := range Ici,
nonempty := ⟨Ici 0, mem_range_self 0⟩,
inter_sets := begin
rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
refine ⟨Ici (max n m), mem_range_self _, _⟩,
rintros p p_in,
split ; rw mem_Ici at *,
exact le_of_max_le_left p_in,
exact le_of_max_le_right p_in,
end }⟩
/-- View a filter as a filter basis. -/
def filter.as_basis (f : filter α) : filter_basis α :=
⟨f.sets, ⟨univ, univ_mem⟩, λ x y hx hy, ⟨x ∩ y, inter_mem hx hy, subset_rfl⟩⟩
/-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/
protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop :=
(nonempty : ∃ i, p i)
(inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j)
namespace filter
namespace is_basis
/-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/
protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α :=
{ sets := {t | ∃ i, p i ∧ s i = t},
nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, ⟨i, hi, rfl⟩⟩,
inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩,
rcases h.inter hi hj with ⟨k, hk, hk'⟩,
exact ⟨_, ⟨k, hk, rfl⟩, hk'⟩ } }
variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s)
lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U :=
iff.rfl
end is_basis
end filter
namespace filter_basis
/-- The filter associated to a filter basis. -/
protected def filter (B : filter_basis α) : filter α :=
{ sets := {s | ∃ t ∈ B, t ⊆ s},
univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩,
sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩,
inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩,
let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in
⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ }
lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U :=
iff.rfl
lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:=
λ U_in, ⟨U, U_in, subset.refl _⟩
lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s :=
begin
have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)),
{ rintros ⟨U, U_in⟩ ⟨V, V_in⟩,
rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩,
use [W, W_in],
simp only [ge_iff_le, le_principal_iff, mem_principal, subtype.coe_mk],
exact subset_inter_iff.mp W_sub },
ext U,
simp [mem_filter_iff, mem_infi_of_directed this]
end
protected lemma generate (B : filter_basis α) : generate B.sets = B.filter :=
begin
apply le_antisymm,
{ intros U U_in,
rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩,
exact generate_sets.superset (generate_sets.basic V_in) h },
{ rw sets_iff_generate,
apply mem_filter_of_mem }
end
end filter_basis
namespace filter
namespace is_basis
variables {p : ι → Prop} {s : ι → set α}
/-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/
protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter
protected lemma mem_filter_iff (h : is_basis p s) {U : set α} :
U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U :=
begin
erw [h.filter_basis.mem_filter_iff],
simp only [mem_filter_basis_iff h, exists_prop],
split,
{ rintros ⟨_, ⟨i, pi, rfl⟩, h⟩,
tauto },
{ tauto }
end
lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} :=
by erw h.filter_basis.generate ; refl
end is_basis
/-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/
protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop :=
(mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t)
section same_type
variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι}
{p' : ι' → Prop} {s' : ι' → set α} {i' : ι'}
lemma has_basis_generate (s : set (set α)) :
(generate s).has_basis (λ t, set.finite t ∧ t ⊆ s) (λ t, ⋂₀ t) :=
⟨begin
intro U,
rw mem_generate_iff,
apply exists_congr,
tauto
end⟩
/-- The smallest filter basis containing a given collection of sets. -/
def filter_basis.of_sets (s : set (set α)) : filter_basis α :=
{ sets := sInter '' { t | set.finite t ∧ t ⊆ s},
nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩,
inter_sets := begin
rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩,
exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩,
by rw sInter_union⟩,
end }
/-- Definition of `has_basis` unfolded with implicit set argument. -/
lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t :=
hl.mem_iff' t
lemma has_basis.eq_of_same_basis (hl : l.has_basis p s) (hl' : l'.has_basis p s) : l = l' :=
begin
ext t,
rw [hl.mem_iff, hl'.mem_iff]
end
lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t :=
⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩
lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i :=
let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem in ⟨i, pi⟩
protected lemma has_basis.nonempty (h : l.has_basis p s) : nonempty ι :=
nonempty_of_exists h.ex_mem
protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s :=
⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩
lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l :=
(hl.mem_iff).2 ⟨i, hi, ht⟩
lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l :=
hl.mem_of_superset hi $ subset.refl _
/-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/
noncomputable def has_basis.index (h : l.has_basis p s) (t : set α) (ht : t ∈ l) :
{i : ι // p i} :=
⟨(h.mem_iff.1 ht).some, (h.mem_iff.1 ht).some_spec.fst⟩
lemma has_basis.property_index (h : l.has_basis p s) (ht : t ∈ l) : p (h.index t ht) :=
(h.index t ht).2
lemma has_basis.set_index_mem (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l :=
h.mem_of_mem $ h.property_index _
lemma has_basis.set_index_subset (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t :=
(h.mem_iff.1 ht).some_spec.snd
lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s :=
{ nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem in ⟨i, hi⟩,
inter := λ i j hi hj, by simpa [h.mem_iff]
using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) }
lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l :=
by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] }
lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } :=
by rw [← h.is_basis.filter_eq_generate, h.filter_eq]
lemma generate_eq_generate_inter (s : set (set α)) :
generate s = generate (sInter '' { t | set.finite t ∧ t ⊆ s}) :=
by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl
lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s :=
by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl
protected lemma _root_.filter_basis.has_basis {α : Type*} (B : filter_basis α) :
has_basis (B.filter) (λ s : set α, s ∈ B) id :=
⟨λ t, B.mem_filter_iff⟩
lemma has_basis.to_has_basis' (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i)
(h' : ∀ i', p' i' → s' i' ∈ l) : l.has_basis p' s' :=
begin
refine ⟨λ t, ⟨λ ht, _, λ ⟨i', hi', ht⟩, mem_of_superset (h' i' hi') ht⟩⟩,
rcases hl.mem_iff.1 ht with ⟨i, hi, ht⟩,
rcases h i hi with ⟨i', hi', hs's⟩,
exact ⟨i', hi', subset.trans hs's ht⟩
end
lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i)
(h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' :=
hl.to_has_basis' h $ λ i' hi', let ⟨i, hi, hss'⟩ := h' i' hi' in hl.mem_iff.2 ⟨i, hi, hss'⟩
lemma has_basis.to_subset (hl : l.has_basis p s) {t : ι → set α} (h : ∀ i, p i → t i ⊆ s i)
(ht : ∀ i, p i → t i ∈ l) : l.has_basis p t :=
hl.to_has_basis' (λ i hi, ⟨i, hi, h i hi⟩) ht
lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} :
(∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x :=
by simpa using hl.mem_iff
lemma has_basis.frequently_iff (hl : l.has_basis p s) {q : α → Prop} :
(∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x :=
by simp [filter.frequently, hl.eventually_iff]
lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop}
(mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) :
(∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) :=
⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩,
λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩
lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop}
(mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) :
(∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) :=
⟨λ H i hi, H (s i) $ hl.mem_of_mem hi,
λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩
lemma has_basis.ne_bot_iff (hl : l.has_basis p s) :
ne_bot l ↔ (∀ {i}, p i → (s i).nonempty) :=
forall_mem_nonempty_iff_ne_bot.symm.trans $ hl.forall_iff $ λ _ _, nonempty.mono
lemma has_basis.eq_bot_iff (hl : l.has_basis p s) :
l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ :=
not_iff_not.1 $ ne_bot_iff.symm.trans $ hl.ne_bot_iff.trans $
by simp only [not_exists, not_and, ← ne_empty_iff_nonempty]
lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id :=
⟨λ t, exists_mem_subset_iff.symm⟩
lemma as_basis_filter (f : filter α) : f.as_basis.filter = f :=
by ext t; exact exists_mem_subset_iff
lemma has_basis_self {l : filter α} {P : set α → Prop} :
has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t ∈ l, ∃ r ∈ l, P r ∧ r ⊆ t :=
begin
simp only [has_basis_iff, exists_prop, id, and_assoc],
exact forall_congr (λ s, ⟨λ h, h.1, λ h, ⟨h, λ ⟨t, hl, hP, hts⟩, mem_of_superset hl hts⟩⟩)
end
lemma has_basis.comp_of_surjective (h : l.has_basis p s) {g : ι' → ι} (hg : function.surjective g) :
l.has_basis (p ∘ g) (s ∘ g) :=
⟨λ t, h.mem_iff.trans hg.exists⟩
lemma has_basis.comp_equiv (h : l.has_basis p s) (e : ι' ≃ ι) : l.has_basis (p ∘ e) (s ∘ e) :=
h.comp_of_surjective e.surjective
/-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that
`p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/
lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop}
(hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) :
l.has_basis (λ i, p i ∧ q i) s :=
begin
refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩,
rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩,
rcases hq i hpi with ⟨j, hpj, hqj, hji⟩,
exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩
end
/-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}`
is a basis of `l`. -/
lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) :
l.has_basis (λ i, p i ∧ s i ⊆ V) s :=
h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem hV (h.mem_of_mem hi))).imp $
λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩
lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id)
{V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id :=
by simpa only [and_assoc] using h.restrict_subset hV
theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l :=
⟨λ h i' hi', h $ hl'.mem_of_mem hi',
λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_of_superset (h _ hi') hs⟩
theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t :=
by simp only [le_def, hl.mem_iff]
theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' :=
by simp only [hl'.ge_iff, hl.mem_iff]
lemma has_basis.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s')
(h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i)
(h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' :=
begin
apply le_antisymm,
{ rw hl.le_basis_iff hl',
simpa using h' },
{ rw hl'.le_basis_iff hl,
simpa using h },
end
lemma has_basis.inf' (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
(l ⊓ l').has_basis (λ i : pprod ι ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) :=
⟨begin
intro t,
split,
{ simp only [mem_inf_iff, exists_prop, hl.mem_iff, hl'.mem_iff],
rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, rfl⟩,
use [⟨i, i'⟩, ⟨hi, hi'⟩, inter_subset_inter ht ht'] },
{ rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩,
exact mem_inf_of_inter (hl.mem_of_mem hi) (hl'.mem_of_mem hi') H }
end⟩
lemma has_basis.inf {ι ι' : Type*} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop}
{s' : ι' → set α} (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
(l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) :=
(hl.inf' hl').to_has_basis (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩)
(λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩)
lemma has_basis_infi' {ι : Type*} {ι' : ι → Type*} {l : ι → filter α}
{p : Π i, ι' i → Prop} {s : Π i, ι' i → set α} (hl : ∀ i, (l i).has_basis (p i) (s i)) :
(⨅ i, l i).has_basis (λ If : set ι × Π i, ι' i, If.1.finite ∧ ∀ i ∈ If.1, p i (If.2 i))
(λ If : set ι × Π i, ι' i, ⋂ i ∈ If.1, s i (If.2 i)) :=
⟨begin
intro t,
split,
{ simp only [mem_infi', (hl _).mem_iff],
rintros ⟨I, hI, V, hV, -, rfl, -⟩,
choose u hu using hV,
exact ⟨⟨I, u⟩, ⟨hI, λ i _, (hu i).1⟩, Inter_mono (λ i, Inter_mono $ λ hi, (hu i).2)⟩ },
{ rintros ⟨⟨I, f⟩, ⟨hI₁, hI₂⟩, hsub⟩,
refine mem_of_superset _ hsub,
exact (bInter_mem hI₁).mpr (λ i hi, mem_infi_of_mem i $ (hl i).mem_of_mem $ hI₂ _ hi) }
end⟩
lemma has_basis_infi {ι : Type*} {ι' : ι → Type*} {l : ι → filter α}
{p : Π i, ι' i → Prop} {s : Π i, ι' i → set α} (hl : ∀ i, (l i).has_basis (p i) (s i)) :
(⨅ i, l i).has_basis (λ If : Σ I : set ι, Π i : I, ι' i, If.1.finite ∧ ∀ i : If.1, p i (If.2 i))
(λ If, ⋂ i : If.1, s i (If.2 i)) :=
begin
refine ⟨λ t, ⟨λ ht, _, _⟩⟩,
{ rcases (has_basis_infi' hl).mem_iff.mp ht with ⟨⟨I, f⟩, ⟨hI, hf⟩, hsub⟩,
exact ⟨⟨I, λ i, f i⟩, ⟨hI, subtype.forall.mpr hf⟩,
trans_rel_right _ (Inter_subtype _ _) hsub⟩ },
{ rintro ⟨⟨I, f⟩, ⟨hI, hf⟩, hsub⟩,
refine mem_of_superset _ hsub,
casesI hI.nonempty_fintype,
exact Inter_mem.2 (λ i, mem_infi_of_mem i $ (hl i).mem_of_mem $ hf _) }
end
lemma has_basis_infi_of_directed' {ι : Type*} {ι' : ι → Sort*}
[nonempty ι]
{l : ι → filter α} (s : Π i, (ι' i) → set α) (p : Π i, (ι' i) → Prop)
(hl : ∀ i, (l i).has_basis (p i) (s i)) (h : directed (≥) l) :
(⨅ i, l i).has_basis (λ (ii' : Σ i, ι' i), p ii'.1 ii'.2) (λ ii', s ii'.1 ii'.2) :=
begin
refine ⟨λ t, _⟩,
rw [mem_infi_of_directed h, sigma.exists],
exact exists_congr (λ i, (hl i).mem_iff)
end
lemma has_basis_infi_of_directed {ι : Type*} {ι' : Sort*}
[nonempty ι]
{l : ι → filter α} (s : ι → ι' → set α) (p : ι → ι' → Prop)
(hl : ∀ i, (l i).has_basis (p i) (s i)) (h : directed (≥) l) :
(⨅ i, l i).has_basis (λ (ii' : ι × ι'), p ii'.1 ii'.2) (λ ii', s ii'.1 ii'.2) :=
begin
refine ⟨λ t, _⟩,
rw [mem_infi_of_directed h, prod.exists],
exact exists_congr (λ i, (hl i).mem_iff)
end
lemma has_basis_binfi_of_directed' {ι : Type*} {ι' : ι → Sort*}
{dom : set ι} (hdom : dom.nonempty)
{l : ι → filter α} (s : Π i, (ι' i) → set α) (p : Π i, (ι' i) → Prop)
(hl : ∀ i ∈ dom, (l i).has_basis (p i) (s i)) (h : directed_on (l ⁻¹'o ge) dom) :
(⨅ i ∈ dom, l i).has_basis (λ (ii' : Σ i, ι' i), ii'.1 ∈ dom ∧ p ii'.1 ii'.2)
(λ ii', s ii'.1 ii'.2) :=
begin
refine ⟨λ t, _⟩,
rw [mem_binfi_of_directed h hdom, sigma.exists],
refine exists_congr (λ i, ⟨_, _⟩),
{ rintros ⟨hi, hti⟩,
rcases (hl i hi).mem_iff.mp hti with ⟨b, hb, hbt⟩,
exact ⟨b, ⟨hi, hb⟩, hbt⟩ },
{ rintros ⟨b, ⟨hi, hb⟩, hibt⟩,
exact ⟨hi, (hl i hi).mem_iff.mpr ⟨b, hb, hibt⟩⟩ }
end
lemma has_basis_binfi_of_directed {ι : Type*} {ι' : Sort*}
{dom : set ι} (hdom : dom.nonempty)
{l : ι → filter α} (s : ι → ι' → set α) (p : ι → ι' → Prop)
(hl : ∀ i ∈ dom, (l i).has_basis (p i) (s i)) (h : directed_on (l ⁻¹'o ge) dom) :
(⨅ i ∈ dom, l i).has_basis (λ (ii' : ι × ι'), ii'.1 ∈ dom ∧ p ii'.1 ii'.2)
(λ ii', s ii'.1 ii'.2) :=
begin
refine ⟨λ t, _⟩,
rw [mem_binfi_of_directed h hdom, prod.exists],
refine exists_congr (λ i, ⟨_, _⟩),
{ rintros ⟨hi, hti⟩,
rcases (hl i hi).mem_iff.mp hti with ⟨b, hb, hbt⟩,
exact ⟨b, ⟨hi, hb⟩, hbt⟩ },
{ rintros ⟨b, ⟨hi, hb⟩, hibt⟩,
exact ⟨hi, (hl i hi).mem_iff.mpr ⟨b, hb, hibt⟩⟩ }
end
lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) :=
⟨λ U, by simp⟩
lemma has_basis_pure (x : α) : (pure x : filter α).has_basis (λ i : unit, true) (λ i, {x}) :=
by simp only [← principal_singleton, has_basis_principal]
lemma has_basis.sup' (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
(l ⊔ l').has_basis (λ i : pprod ι ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) :=
⟨begin
intros t,
simp only [mem_sup, hl.mem_iff, hl'.mem_iff, pprod.exists, union_subset_iff, exists_prop,
and_assoc, exists_and_distrib_left],
simp only [← and_assoc, exists_and_distrib_right, and_comm]
end⟩
lemma has_basis.sup {ι ι' : Type*} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop}
{s' : ι' → set α} (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
(l ⊔ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) :=
(hl.sup' hl').to_has_basis (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩)
(λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩)
lemma has_basis_supr {ι : Sort*} {ι' : ι → Type*} {l : ι → filter α}
{p : Π i, ι' i → Prop} {s : Π i, ι' i → set α} (hl : ∀ i, (l i).has_basis (p i) (s i)) :
(⨆ i, l i).has_basis (λ f : Π i, ι' i, ∀ i, p i (f i)) (λ f : Π i, ι' i, ⋃ i, s i (f i)) :=
has_basis_iff.mpr $ λ t, by simp only [has_basis_iff, (hl _).mem_iff, classical.skolem,
forall_and_distrib, Union_subset_iff, mem_supr]
lemma has_basis.sup_principal (hl : l.has_basis p s) (t : set α) :
(l ⊔ 𝓟 t).has_basis p (λ i, s i ∪ t) :=
⟨λ u, by simp only [(hl.sup' (has_basis_principal t)).mem_iff, pprod.exists, exists_prop, and_true,
unique.exists_iff]⟩
lemma has_basis.sup_pure (hl : l.has_basis p s) (x : α) :
(l ⊔ pure x).has_basis p (λ i, s i ∪ {x}) :=
by simp only [← principal_singleton, hl.sup_principal]
lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) :
(l ⊓ 𝓟 s').has_basis p (λ i, s i ∩ s') :=
⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq,
mem_inter_iff, and_imp]⟩
lemma has_basis.principal_inf (hl : l.has_basis p s) (s' : set α) :
(𝓟 s' ⊓ l).has_basis p (λ i, s' ∩ s i) :=
by simpa only [inf_comm, inter_comm] using hl.inf_principal s'
lemma has_basis.inf_basis_ne_bot_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃i'⦄ (hi' : p' i'), (s i ∩ s' i').nonempty :=
(hl.inf' hl').ne_bot_iff.trans $ by simp [@forall_swap _ ι']
lemma has_basis.inf_ne_bot_iff (hl : l.has_basis p s) :
ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃s'⦄ (hs' : s' ∈ l'), (s i ∩ s').nonempty :=
hl.inf_basis_ne_bot_iff l'.basis_sets
lemma has_basis.inf_principal_ne_bot_iff (hl : l.has_basis p s) {t : set α} :
ne_bot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄ (hi : p i), (s i ∩ t).nonempty :=
(hl.inf_principal t).ne_bot_iff
lemma has_basis.disjoint_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
disjoint l l' ↔ ∃ i (hi : p i) i' (hi' : p' i'), disjoint (s i) (s' i') :=
not_iff_not.mp $ by simp only [disjoint_iff, ← ne.def, ← ne_bot_iff, hl.inf_basis_ne_bot_iff hl',
not_exists, bot_eq_empty, ne_empty_iff_nonempty, inf_eq_inter]
lemma inf_ne_bot_iff :
ne_bot (l ⊓ l') ↔ ∀ ⦃s : set α⦄ (hs : s ∈ l) ⦃s'⦄ (hs' : s' ∈ l'), (s ∩ s').nonempty :=
l.basis_sets.inf_ne_bot_iff
lemma inf_principal_ne_bot_iff {s : set α} :
ne_bot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).nonempty :=
l.basis_sets.inf_principal_ne_bot_iff
lemma mem_iff_inf_principal_compl {f : filter α} {s : set α} :
s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ :=
begin
refine not_iff_not.1 ((inf_principal_ne_bot_iff.trans _).symm.trans ne_bot_iff),
exact ⟨λ h hs, by simpa [empty_not_nonempty] using h s hs,
λ hs t ht, inter_compl_nonempty_iff.2 $ λ hts, hs $ mem_of_superset ht hts⟩,
end
lemma not_mem_iff_inf_principal_compl {f : filter α} {s : set α} :
s ∉ f ↔ ne_bot (f ⊓ 𝓟 sᶜ) :=
(not_congr mem_iff_inf_principal_compl).trans ne_bot_iff.symm
@[simp] lemma disjoint_principal_right {f : filter α} {s : set α} :
disjoint f (𝓟 s) ↔ sᶜ ∈ f :=
by rw [mem_iff_inf_principal_compl, compl_compl, disjoint_iff]
@[simp] lemma disjoint_principal_left {f : filter α} {s : set α} :
disjoint (𝓟 s) f ↔ sᶜ ∈ f :=
by rw [disjoint.comm, disjoint_principal_right]
@[simp] lemma disjoint_principal_principal {s t : set α} :
disjoint (𝓟 s) (𝓟 t) ↔ disjoint s t :=
by simp [←subset_compl_iff_disjoint_left]
alias disjoint_principal_principal ↔ _ _root_.disjoint.filter_principal
@[simp] lemma disjoint_pure_pure {x y : α} :
disjoint (pure x : filter α) (pure y) ↔ x ≠ y :=
by simp only [← principal_singleton, disjoint_principal_principal, disjoint_singleton]
@[simp] lemma compl_diagonal_mem_prod {l₁ l₂ : filter α} :
(diagonal α)ᶜ ∈ l₁ ×ᶠ l₂ ↔ disjoint l₁ l₂ :=
by simp only [mem_prod_iff, filter.disjoint_iff, prod_subset_compl_diagonal_iff_disjoint]
lemma le_iff_forall_inf_principal_compl {f g : filter α} :
f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ :=
forall₂_congr $ λ _ _, mem_iff_inf_principal_compl
lemma inf_ne_bot_iff_frequently_left {f g : filter α} :
ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x :=
by simpa only [inf_ne_bot_iff, frequently_iff, exists_prop, and_comm]
lemma inf_ne_bot_iff_frequently_right {f g : filter α} :
ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x :=
by { rw inf_comm, exact inf_ne_bot_iff_frequently_left }
lemma has_basis.eq_binfi (h : l.has_basis p s) :
l = ⨅ i (_ : p i), 𝓟 (s i) :=
eq_binfi_of_mem_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal]
lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) :
l = ⨅ i, 𝓟 (s i) :=
by simpa only [infi_true] using h.eq_binfi
lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] :
(⨅ i, 𝓟 (s i)).has_basis (λ _, true) s :=
⟨begin
refine λ t, (mem_infi_of_directed (h.mono_comp _ _) t).trans $
by simp only [exists_prop, true_and, mem_principal],
exact λ _ _, principal_mono.2
end⟩
/-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis
of `⨅ i, 𝓟 (s i)`. -/
lemma has_basis_infi_principal_finite {ι : Type*} (s : ι → set α) :
(⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, t.finite) (λ t, ⋂ i ∈ t, s i) :=
begin
refine ⟨λ U, (mem_infi_finite _).trans _⟩,
simp only [infi_principal_finset, mem_Union, mem_principal, exists_prop,
exists_finite_iff_finset, finset.set_bInter_coe]
end
lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S)
(ne : S.nonempty) :
(⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s :=
⟨begin
refine λ t, (mem_binfi_of_directed _ ne).trans $ by simp only [mem_principal],
rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢,
apply h.mono_comp _ _,
exact λ _ _, principal_mono.2
end⟩
lemma has_basis_binfi_principal' {ι : Type*} {p : ι → Prop} {s : ι → set α}
(h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) :
(⨅ i (h : p i), 𝓟 (s i)).has_basis p s :=
filter.has_basis_binfi_principal h ne
lemma has_basis.map (f : α → β) (hl : l.has_basis p s) :
(l.map f).has_basis p (λ i, f '' (s i)) :=
⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩
lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) :
(l.comap f).has_basis p (λ i, f ⁻¹' (s i)) :=
⟨begin
intro t,
simp only [mem_comap, exists_prop, hl.mem_iff],
split,
{ rintros ⟨t', ⟨i, hi, ht'⟩, H⟩,
exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ },
{ rintros ⟨i, hi, H⟩,
exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ }
end⟩
lemma comap_has_basis (f : α → β) (l : filter β) :
has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) :=
⟨λ t, mem_comap⟩
lemma has_basis.forall_mem_mem (h : has_basis l p s) {x : α} :
(∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i :=
begin
simp only [h.mem_iff, exists_imp_distrib],
exact ⟨λ h i hi, h (s i) i hi subset.rfl, λ h t i hi ht, ht (h i hi)⟩
end
protected lemma has_basis.binfi_mem [complete_lattice β] {f : set α → β} (h : has_basis l p s)
(hf : monotone f) :
(⨅ t ∈ l, f t) = ⨅ i (hi : p i), f (s i) :=
le_antisymm (le_infi₂ $ λ i hi, infi₂_le (s i) (h.mem_of_mem hi)) $
le_infi₂ $ λ t ht, let ⟨i, hpi, hi⟩ := h.mem_iff.1 ht in infi₂_le_of_le i hpi (hf hi)
protected lemma has_basis.bInter_mem {f : set α → set β} (h : has_basis l p s) (hf : monotone f) :
(⋂ t ∈ l, f t) = ⋂ i (hi : p i), f (s i) :=
h.binfi_mem hf
lemma has_basis.sInter_sets (h : has_basis l p s) : ⋂₀ l.sets = ⋂ i (hi : p i), s i :=
by { rw [sInter_eq_bInter], exact h.bInter_mem monotone_id }
variables {ι'' : Type*} [preorder ι''] (l) (s'' : ι'' → set α)
/-- `is_antitone_basis s` means the image of `s` is a filter basis such that `s` is decreasing. -/
@[protect_proj] structure is_antitone_basis extends is_basis (λ _, true) s'' : Prop :=
(antitone : antitone s'')
/-- We say that a filter `l` has an antitone basis `s : ι → set α`, if `t ∈ l` if and only if `t`
includes `s i` for some `i`, and `s` is decreasing. -/
@[protect_proj] structure has_antitone_basis (l : filter α) (s : ι'' → set α)
extends has_basis l (λ _, true) s : Prop :=
(antitone : antitone s)
lemma has_antitone_basis.map {l : filter α} {s : ι'' → set α} {m : α → β}
(hf : has_antitone_basis l s) :
has_antitone_basis (map m l) (λ n, m '' s n) :=
⟨has_basis.map _ hf.to_has_basis, λ i j hij, image_subset _ $ hf.2 hij⟩
end same_type
section two_types
variables {la : filter α} {pa : ι → Prop} {sa : ι → set α}
{lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β}
lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) :
tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), maps_to f (sa i) t :=
by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl }
lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) :
tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i :=
by simpa only [tendsto, hlb.ge_iff, mem_map, filter.eventually]
lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) :
tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib :=
by simp [hlb.tendsto_right_iff, hla.eventually_iff]
lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) :
∀ t ∈ lb, ∃ i (hi : pa i), maps_to f (sa i) t :=
hla.tendsto_left_iff.1 H
lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) :
∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i :=
hlb.tendsto_right_iff.1 H
lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa)
(hlb : lb.has_basis pb sb) :
∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib :=
(hla.tendsto_iff hlb).1 H
lemma has_basis.prod_pprod (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) :
(la ×ᶠ lb).has_basis (λ i : pprod ι ι', pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) :=
(hla.comap prod.fst).inf' (hlb.comap prod.snd)
lemma has_basis.prod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → set α} {pb : ι' → Prop}
{sb : ι' → set β} (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) :
(la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) :=
(hla.comap prod.fst).inf (hlb.comap prod.snd)
lemma has_basis.prod_same_index {p : ι → Prop} {sb : ι → set β}
(hla : la.has_basis p sa) (hlb : lb.has_basis p sb)
(h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) :
(la ×ᶠ lb).has_basis p (λ i, sa i ×ˢ sb i) :=
begin
simp only [has_basis_iff, (hla.prod_pprod hlb).mem_iff],
refine λ t, ⟨_, _⟩,
{ rintros ⟨⟨i, j⟩, ⟨hi, hj⟩, hsub : sa i ×ˢ sb j ⊆ t⟩,
rcases h_dir hi hj with ⟨k, hk, ki, kj⟩,
exact ⟨k, hk, (set.prod_mono ki kj).trans hsub⟩ },
{ rintro ⟨i, hi, h⟩,
exact ⟨⟨i, i⟩, ⟨hi, hi⟩, h⟩ },
end
lemma has_basis.prod_same_index_mono {ι : Type*} [linear_order ι]
{p : ι → Prop} {sa : ι → set α} {sb : ι → set β}
(hla : la.has_basis p sa) (hlb : lb.has_basis p sb)
(hsa : monotone_on sa {i | p i}) (hsb : monotone_on sb {i | p i}) :
(la ×ᶠ lb).has_basis p (λ i, sa i ×ˢ sb i) :=
hla.prod_same_index hlb $ λ i j hi hj,
have p (min i j), from min_rec' _ hi hj,
⟨min i j, this, hsa this hi $ min_le_left _ _, hsb this hj $ min_le_right _ _⟩
lemma has_basis.prod_same_index_anti {ι : Type*} [linear_order ι]
{p : ι → Prop} {sa : ι → set α} {sb : ι → set β}
(hla : la.has_basis p sa) (hlb : lb.has_basis p sb)
(hsa : antitone_on sa {i | p i}) (hsb : antitone_on sb {i | p i}) :
(la ×ᶠ lb).has_basis p (λ i, sa i ×ˢ sb i) :=
@has_basis.prod_same_index_mono _ _ _ _ ιᵒᵈ _ _ _ _ hla hlb hsa.dual_left hsb.dual_left
lemma has_basis.prod_self (hl : la.has_basis pa sa) :
(la ×ᶠ la).has_basis pa (λ i, sa i ×ˢ sa i) :=
hl.prod_same_index hl $ λ i j hi hj, by simpa only [exists_prop, subset_inter_iff]
using hl.mem_iff.1 (inter_mem (hl.mem_of_mem hi) (hl.mem_of_mem hj))
lemma mem_prod_self_iff {s} : s ∈ la ×ᶠ la ↔ ∃ t ∈ la, t ×ˢ t ⊆ s :=
la.basis_sets.prod_self.mem_iff
lemma has_antitone_basis.prod {ι : Type*} [linear_order ι] {f : filter α} {g : filter β}
{s : ι → set α} {t : ι → set β} (hf : has_antitone_basis f s) (hg : has_antitone_basis g t) :
has_antitone_basis (f ×ᶠ g) (λ n, s n ×ˢ t n) :=
⟨hf.1.prod_same_index_anti hg.1 (hf.2.antitone_on _) (hg.2.antitone_on _), hf.2.set_prod hg.2⟩
lemma has_basis.coprod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → set α} {pb : ι' → Prop}
{sb : ι' → set β} (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) :
(la.coprod lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2)
(λ i, prod.fst ⁻¹' sa i.1 ∪ prod.snd ⁻¹' sb i.2) :=
(hla.comap prod.fst).sup (hlb.comap prod.snd)
end two_types
lemma map_sigma_mk_comap {π : α → Type*} {π' : β → Type*} {f : α → β}
(hf : function.injective f) (g : Π a, π a → π' (f a)) (a : α) (l : filter (π' (f a))) :
map (sigma.mk a) (comap (g a) l) = comap (sigma.map f g) (map (sigma.mk (f a)) l) :=
begin
refine (((basis_sets _).comap _).map _).eq_of_same_basis _,
convert ((basis_sets _).map _).comap _,
ext1 s,
apply image_sigma_mk_preimage_sigma_map hf
end
end filter
end sort
namespace filter
variables {α β γ ι : Type*} {ι' : Sort*}
/-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/
class is_countably_generated (f : filter α) : Prop :=
(out [] : ∃ s : set (set α), s.countable ∧ f = generate s)
/-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/
structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop :=
(countable : (set_of p).countable)
/-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set
defined by `p` is countable. -/
structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α)
extends has_basis l p s : Prop :=
(countable : (set_of p).countable)
/-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α`
such that the intersection of two elements of this collection contains some element
of the collection. -/
structure countable_filter_basis (α : Type*) extends filter_basis α :=
(countable : sets.countable)
-- For illustration purposes, the countable filter basis defining (at_top : filter ℕ)
instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) :=
⟨{ countable := countable_range (λ n, Ici n),
..(default : filter_basis ℕ) }⟩
lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α}
(h : f.has_countable_basis p s) :
f.is_countably_generated :=
⟨⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩⟩
lemma antitone_seq_of_seq (s : ℕ → set α) :
∃ t : ℕ → set α, antitone t ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) :=
begin
use λ n, ⋂ m ≤ n, s m, split,
{ exact λ i j hij, bInter_mono (Iic_subset_Iic.2 hij) (λ n hn, subset.refl _) },
apply le_antisymm; rw le_infi_iff; intro i,
{ rw le_principal_iff, refine (bInter_mem (finite_le_nat _)).2 (λ j hji, _),
rw ← le_principal_iff, apply infi_le_of_le j _, exact le_rfl },
{ apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl },
end
lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : B.countable)
(Bne : B.nonempty) (f : ι → α) :
∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) :=
let ⟨g, hg⟩ := Bcbl.exists_eq_range Bne in ⟨g, hg.symm ▸ infi_range⟩
lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : B.countable) (f : ι → α)
{i₀ : ι} (h : f i₀ = ⊤) :
∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) :=
begin
cases B.eq_empty_or_nonempty with hB Bnonempty,
{ rw [hB, infi_emptyset],
use λ n, i₀,
simp [h] },
{ exact countable_binfi_eq_infi_seq Bcbl Bnonempty f }
end
lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : B.countable) :
∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) :=
countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ
section is_countably_generated
protected lemma has_antitone_basis.mem_iff [preorder ι] {l : filter α} {s : ι → set α}
(hs : l.has_antitone_basis s) {t : set α} : t ∈ l ↔ ∃ i, s i ⊆ t :=
hs.to_has_basis.mem_iff.trans $ by simp only [exists_prop, true_and]
protected lemma has_antitone_basis.mem [preorder ι] {l : filter α} {s : ι → set α}
(hs : l.has_antitone_basis s) (i : ι) : s i ∈ l :=
hs.to_has_basis.mem_of_mem trivial
lemma has_antitone_basis.has_basis_ge [preorder ι] [is_directed ι (≤)] {l : filter α}
{s : ι → set α} (hs : l.has_antitone_basis s) (i : ι) :
l.has_basis (λ j, i ≤ j) s :=
hs.1.to_has_basis (λ j _, (exists_ge_ge i j).imp $ λ k hk, ⟨hk.1, hs.2 hk.2⟩)
(λ j hj, ⟨j, trivial, subset.rfl⟩)
/-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis
enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a
sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which
forms a basis of `f`-/
lemma has_basis.exists_antitone_subbasis {f : filter α} [h : f.is_countably_generated]
{p : ι' → Prop} {s : ι' → set α} (hs : f.has_basis p s) :
∃ x : ℕ → ι', (∀ i, p (x i)) ∧ f.has_antitone_basis (λ i, s (x i)) :=
begin
obtain ⟨x', hx'⟩ : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i),
{ unfreezingI { rcases h with ⟨s, hsc, rfl⟩ },
rw generate_eq_binfi,
exact countable_binfi_principal_eq_seq_infi hsc },
have : ∀ i, x' i ∈ f := λ i, hx'.symm ▸ (infi_le (λ i, 𝓟 (x' i)) i) (mem_principal_self _),
let x : ℕ → {i : ι' // p i} := λ n, nat.rec_on n (hs.index _ $ this 0)
(λ n xn, (hs.index _ $ inter_mem (this $ n + 1) (hs.mem_of_mem xn.2))),
have x_mono : antitone (λ i, s (x i)),
{ refine antitone_nat_of_succ_le (λ i, _),
exact (hs.set_index_subset _).trans (inter_subset_right _ _) },
have x_subset : ∀ i, s (x i) ⊆ x' i,
{ rintro (_|i),
exacts [hs.set_index_subset _, subset.trans (hs.set_index_subset _) (inter_subset_left _ _)] },
refine ⟨λ i, x i, λ i, (x i).2, _⟩,
have : (⨅ i, 𝓟 (s (x i))).has_antitone_basis (λ i, s (x i)) :=
⟨has_basis_infi_principal (directed_of_sup x_mono), x_mono⟩,
convert this,
exact le_antisymm (le_infi $ λ i, le_principal_iff.2 $ by cases i; apply hs.set_index_mem)
(hx'.symm ▸ le_infi (λ i, le_principal_iff.2 $
this.to_has_basis.mem_iff.2 ⟨i, trivial, x_subset i⟩))
end
/-- A countably generated filter admits a basis formed by an antitone sequence of sets. -/
lemma exists_antitone_basis (f : filter α) [f.is_countably_generated] :
∃ x : ℕ → set α, f.has_antitone_basis x :=
let ⟨x, hxf, hx⟩ := f.basis_sets.exists_antitone_subbasis in ⟨x, hx⟩
lemma exists_antitone_seq (f : filter α) [f.is_countably_generated] :
∃ x : ℕ → set α, antitone x ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) :=
let ⟨x, hx⟩ := f.exists_antitone_basis in
⟨x, hx.antitone, λ s, by simp [hx.to_has_basis.mem_iff]⟩
instance inf.is_countably_generated (f g : filter α) [is_countably_generated f]
[is_countably_generated g] :
is_countably_generated (f ⊓ g) :=
begin
rcases f.exists_antitone_basis with ⟨s, hs⟩,
rcases g.exists_antitone_basis with ⟨t, ht⟩,
exact has_countable_basis.is_countably_generated
⟨hs.to_has_basis.inf ht.to_has_basis, set.to_countable _⟩
end
instance map.is_countably_generated (l : filter α) [l.is_countably_generated] (f : α → β) :
(map f l).is_countably_generated :=
let ⟨x, hxl⟩ := l.exists_antitone_basis in
has_countable_basis.is_countably_generated ⟨hxl.map.to_has_basis, to_countable _⟩
instance comap.is_countably_generated (l : filter β) [l.is_countably_generated] (f : α → β) :
(comap f l).is_countably_generated :=
let ⟨x, hxl⟩ := l.exists_antitone_basis in
has_countable_basis.is_countably_generated ⟨hxl.to_has_basis.comap _, to_countable _⟩
instance sup.is_countably_generated (f g : filter α) [is_countably_generated f]
[is_countably_generated g] :
is_countably_generated (f ⊔ g) :=
begin
rcases f.exists_antitone_basis with ⟨s, hs⟩,
rcases g.exists_antitone_basis with ⟨t, ht⟩,
exact has_countable_basis.is_countably_generated
⟨hs.to_has_basis.sup ht.to_has_basis, set.to_countable _⟩
end
instance prod.is_countably_generated (la : filter α) (lb : filter β) [is_countably_generated la]
[is_countably_generated lb] : is_countably_generated (la ×ᶠ lb) :=
filter.inf.is_countably_generated _ _
instance coprod.is_countably_generated (la : filter α) (lb : filter β) [is_countably_generated la]
[is_countably_generated lb] : is_countably_generated (la.coprod lb) :=
filter.sup.is_countably_generated _ _
end is_countably_generated
lemma is_countably_generated_seq [countable β] (x : β → set α) :
is_countably_generated (⨅ i, 𝓟 $ x i) :=
begin
use [range x, countable_range x],
rw [generate_eq_binfi, infi_range]
end
lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) :
f.is_countably_generated :=
let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq
lemma is_countably_generated_binfi_principal {B : set $ set α} (h : B.countable) :
is_countably_generated (⨅ (s ∈ B), 𝓟 s) :=
is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h)
lemma is_countably_generated_iff_exists_antitone_basis {f : filter α} :
is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antitone_basis x :=
begin
split,
{ introI h, exact f.exists_antitone_basis },
{ rintros ⟨x, h⟩,
rw h.to_has_basis.eq_infi,
exact is_countably_generated_seq x },
end
@[instance] lemma is_countably_generated_principal (s : set α) : is_countably_generated (𝓟 s) :=
is_countably_generated_of_seq ⟨λ _, s, infi_const.symm⟩
@[instance] lemma is_countably_generated_pure (a : α) : is_countably_generated (pure a) :=
by { rw ← principal_singleton, exact is_countably_generated_principal _, }
@[instance] lemma is_countably_generated_bot : is_countably_generated (⊥ : filter α) :=
@principal_empty α ▸ is_countably_generated_principal _
@[instance] lemma is_countably_generated_top : is_countably_generated (⊤ : filter α) :=
@principal_univ α ▸ is_countably_generated_principal _
instance infi.is_countably_generated {ι : Sort*} [countable ι] (f : ι → filter α)
[∀ i, is_countably_generated (f i)] : is_countably_generated (⨅ i, f i) :=
begin
choose s hs using λ i, exists_antitone_basis (f i),
rw [← plift.down_surjective.infi_comp],
refine has_countable_basis.is_countably_generated
⟨has_basis_infi (λ n, (hs _).to_has_basis), _⟩,
refine (countable_range $ sigma.map (coe : finset (plift ι) → set (plift ι)) (λ _, id)).mono _,
rintro ⟨I, f⟩ ⟨hI, -⟩,
lift I to finset (plift ι) using hI,
exact ⟨⟨I, f⟩, rfl⟩
end
end filter
|
43864a5bba9d9eef55c6253fa8afcb87f31bf79b | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/PrettyPrinter/Parenthesizer.lean | 988905f765295774cafc0207141b23b399441505 | [
"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",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 28,061 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.Parser.Extension
import Lean.Parser.StrInterpolation
import Lean.ParserCompiler.Attribute
import Lean.PrettyPrinter.Basic
/-!
The parenthesizer inserts parentheses into a `Syntax` object where syntactically necessary, usually as an intermediary
step between the delaborator and the formatter. While the delaborator outputs structurally well-formed syntax trees that
can be re-elaborated without post-processing, this tree structure is lost in the formatter and thus needs to be
preserved by proper insertion of parentheses.
# The abstract problem & solution
The Lean 4 grammar is unstructured and extensible with arbitrary new parsers, so in general it is undecidable whether
parentheses are necessary or even allowed at any point in the syntax tree. Parentheses for different categories, e.g.
terms and levels, might not even have the same structure. In this module, we focus on the correct parenthesization of
parsers defined via `Lean.Parser.prattParser`, which includes both aforementioned built-in categories. Custom
parenthesizers can be added for new node kinds, but the data collected in the implementation below might not be
appropriate for other parenthesization strategies.
Usages of a parser defined via `prattParser` in general have the form `p prec`, where `prec` is the minimum precedence
or binding power. Recall that a Pratt parser greedily runs a leading parser with precedence at least `prec` (otherwise
it fails) followed by zero or more trailing parsers with precedence at least `prec`; the precedence of a parser is
encoded in the call to `leadingNode/trailingNode`, respectively. Thus we should parenthesize a syntax node `stx`
supposedly produced by `p prec` if
1. the leading/any trailing parser involved in `stx` has precedence < `prec` (because without parentheses, `p prec`
would not produce all of `stx`), or
2. the trailing parser parsing the input to *the right of* `stx`, if any, has precedence >= `prec` (because without
parentheses, `p prec` would have parsed it as well and made it a part of `stx`). We also check that the two parsers
are from the same syntax category.
Note that in case 2, it is also sufficient to parenthesize a *parent* node as long as the offending parser is still to
the right of that node. For example, imagine the tree structure of `(f fun x => x) y` without parentheses. We need to
insert *some* parentheses between `x` and `y` since the lambda body is parsed with precedence 0, while the identifier
parser for `y` has precedence `maxPrec`. But we need to parenthesize the `$` node anyway since the precedence of its
RHS (0) again is smaller than that of `y`. So it's better to only parenthesize the outer node than ending up with
`(f $ (fun x => x)) y`.
# Implementation
We transform the syntax tree and collect the necessary precedence information for that in a single traversal. The
traversal is right-to-left to cover case 2. More specifically, for every Pratt parser call, we store as monadic state
the precedence of the left-most trailing parser and the minimum precedence of any parser (`contPrec`/`minPrec`) in this
call, if any, and the precedence of the nested trailing Pratt parser call (`trailPrec`), if any. If `stP` is the state
resulting from the traversal of a Pratt parser call `p prec`, and `st` is the state of the surrounding call, we
parenthesize if `prec > stP.minPrec` (case 1) or if `stP.trailPrec <= st.contPrec` (case 2).
The traversal can be customized for each `[*Parser]` parser declaration `c` (more specifically, each `SyntaxNodeKind`
`c`) using the `[parenthesizer c]` attribute. Otherwise, a default parenthesizer will be synthesized from the used
parser combinators by recursively replacing them with declarations tagged as `[combinator_parenthesizer]` for the
respective combinator. If a called function does not have a registered combinator parenthesizer and is not reducible,
the synthesizer fails. This happens mostly at the `Parser.mk` decl, which is irreducible, when some parser primitive has
not been handled yet.
The traversal over the `Syntax` object is complicated by the fact that a parser does not produce exactly one syntax
node, but an arbitrary (but constant, for each parser) amount that it pushes on top of the parser stack. This amount can
even be zero for parsers such as `checkWsBefore`. Thus we cannot simply pass and return a `Syntax` object to and from
`visit`. Instead, we use a `Syntax.Traverser` that allows arbitrary movement and modification inside the syntax tree.
Our traversal invariant is that a parser interpreter should stop at the syntax object to the *left* of all syntax
objects its parser produced, except when it is already at the left-most child. This special case is not an issue in
practice since if there is another parser to the left that produced zero nodes in this case, it should always do so, so
there is no danger of the left-most child being processed multiple times.
Ultimately, most parenthesizers are implemented via three primitives that do all the actual syntax traversal:
`maybeParenthesize mkParen prec x` runs `x` and afterwards transforms it with `mkParen` if the above
condition for `p prec` is fulfilled. `visitToken` advances to the preceding sibling and is used on atoms. `visitArgs x`
executes `x` on the last child of the current node and then advances to the preceding sibling (of the original current
node).
-/
namespace Lean
namespace PrettyPrinter
namespace Parenthesizer
structure Context where
-- We need to store this `categoryParser` argument to deal with the implicit Pratt parser call in `trailingNode.parenthesizer`.
cat : Name := Name.anonymous
structure State where
stxTrav : Syntax.Traverser
--- precedence and category of the current left-most trailing parser, if any; see module doc for details
contPrec : Option Nat := none
contCat : Name := Name.anonymous
-- current minimum precedence in this Pratt parser call, if any; see module doc for details
minPrec : Option Nat := none
-- precedence and category of the trailing Pratt parser call if any; see module doc for details
trailPrec : Option Nat := none
trailCat : Name := Name.anonymous
-- true iff we have already visited a token on this parser level; used for detecting trailing parsers
visitedToken : Bool := false
end Parenthesizer
abbrev ParenthesizerM := ReaderT Parenthesizer.Context $ StateRefT Parenthesizer.State CoreM
abbrev Parenthesizer := ParenthesizerM Unit
@[inline] def ParenthesizerM.orElse (p₁ : ParenthesizerM α) (p₂ : Unit → ParenthesizerM α) : ParenthesizerM α := do
let s ← get
catchInternalId backtrackExceptionId
p₁
(fun _ => do set s; p₂ ())
instance : OrElse (ParenthesizerM α) := ⟨ParenthesizerM.orElse⟩
unsafe def mkParenthesizerAttribute : IO (KeyedDeclsAttribute Parenthesizer) :=
KeyedDeclsAttribute.init {
builtinName := `builtin_parenthesizer,
name := `parenthesizer,
descr := "Register a parenthesizer for a parser.
[parenthesizer k] registers a declaration of type `Lean.PrettyPrinter.Parenthesizer` for the `SyntaxNodeKind` `k`.",
valueTypeName := `Lean.PrettyPrinter.Parenthesizer,
evalKey := fun builtin stx => do
let env ← getEnv
let stx ← Attribute.Builtin.getIdent stx
let id := stx.getId
-- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to
-- synthesize a parenthesizer for it immediately, so we just check for a declaration in this case
unless (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id do
throwError "invalid [parenthesizer] argument, unknown syntax kind '{id}'"
if (← getEnv).contains id && (← Elab.getInfoState).enabled then
Elab.addConstInfo stx id none
pure id
} `Lean.PrettyPrinter.parenthesizerAttribute
@[builtin_init mkParenthesizerAttribute] opaque parenthesizerAttribute : KeyedDeclsAttribute Parenthesizer
abbrev CategoryParenthesizer := (prec : Nat) → Parenthesizer
unsafe def mkCategoryParenthesizerAttribute : IO (KeyedDeclsAttribute CategoryParenthesizer) :=
KeyedDeclsAttribute.init {
builtinName := `builtin_category_parenthesizer,
name := `category_parenthesizer,
descr := "Register a parenthesizer for a syntax category.
[category_parenthesizer cat] registers a declaration of type `Lean.PrettyPrinter.CategoryParenthesizer` for the category `cat`,
which is used when parenthesizing calls of `categoryParser cat prec`. Implementations should call `maybeParenthesize`
with the precedence and `cat`. If no category parenthesizer is registered, the category will never be parenthesized,
but still be traversed for parenthesizing nested categories.",
valueTypeName := `Lean.PrettyPrinter.CategoryParenthesizer,
evalKey := fun _ stx => do
let env ← getEnv
let stx ← Attribute.Builtin.getIdent stx
let id := stx.getId
let some cat := (Parser.parserExtension.getState env).categories.find? id
| throwError "invalid [category_parenthesizer] argument, unknown parser category '{toString id}'"
if (← Elab.getInfoState).enabled && (← getEnv).contains cat.declName then
Elab.addConstInfo stx cat.declName none
pure id
} `Lean.PrettyPrinter.categoryParenthesizerAttribute
@[builtin_init mkCategoryParenthesizerAttribute] opaque categoryParenthesizerAttribute : KeyedDeclsAttribute CategoryParenthesizer
unsafe def mkCombinatorParenthesizerAttribute : IO ParserCompiler.CombinatorAttribute :=
ParserCompiler.registerCombinatorAttribute
`combinator_parenthesizer
"Register a parenthesizer for a parser combinator.
[combinator_parenthesizer c] registers a declaration of type `Lean.PrettyPrinter.Parenthesizer` for the `Parser` declaration `c`.
Note that, unlike with [parenthesizer], this is not a node kind since combinators usually do not introduce their own node kinds.
The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced
with `Parenthesizer` in the parameter types."
@[builtin_init mkCombinatorParenthesizerAttribute] opaque combinatorParenthesizerAttribute : ParserCompiler.CombinatorAttribute
namespace Parenthesizer
open Lean.Core Parser
open Std.Format
def throwBacktrack {α} : ParenthesizerM α :=
throw $ Exception.internal backtrackExceptionId
instance : Syntax.MonadTraverser ParenthesizerM := ⟨{
get := State.stxTrav <$> get,
set := fun t => modify (fun st => { st with stxTrav := t }),
modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t }))
}⟩
open Syntax.MonadTraverser
def addPrecCheck (prec : Nat) : ParenthesizerM Unit :=
modify fun st => { st with contPrec := Nat.min (st.contPrec.getD prec) prec, minPrec := Nat.min (st.minPrec.getD prec) prec }
/-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/
def visitArgs (x : ParenthesizerM Unit) : ParenthesizerM Unit := do
let stx ← getCur
if stx.getArgs.size > 0 then
goDown (stx.getArgs.size - 1) *> x <* goUp
goLeft
-- Macro scopes in the parenthesizer output are ultimately ignored by the pretty printer,
-- so give a trivial implementation.
instance : MonadQuotation ParenthesizerM := {
getCurrMacroScope := pure default
getMainModule := pure default
withFreshMacroScope := fun x => x
}
/--
Run `x` and parenthesize the result using `mkParen` if necessary.
If `canJuxtapose` is false, we assume the category does not have a token-less juxtaposition syntax a la function application and deactivate rule 2. -/
def maybeParenthesize (cat : Name) (canJuxtapose : Bool) (mkParen : Syntax → Syntax) (prec : Nat) (x : ParenthesizerM Unit) : ParenthesizerM Unit := do
let stx ← getCur
let idx ← getIdx
let st ← get
-- reset precs for the recursive call
set { stxTrav := st.stxTrav : State }
trace[PrettyPrinter.parenthesize] "parenthesizing (cont := {(st.contPrec, st.contCat)}){indentD (format stx)}"
x
let { minPrec := some minPrec, trailPrec := trailPrec, trailCat := trailCat, .. } ← get
| trace[PrettyPrinter.parenthesize] "visited a syntax tree without precedences?!{line ++ format stx}"
trace[PrettyPrinter.parenthesize] (m!"...precedences are {prec} >? {minPrec}" ++ if canJuxtapose then m!", {(trailPrec, trailCat)} <=? {(st.contPrec, st.contCat)}" else "")
-- Should we parenthesize?
if (prec > minPrec || canJuxtapose && match trailPrec, st.contPrec with | some trailPrec, some contPrec => trailCat == st.contCat && trailPrec <= contPrec | _, _ => false) then
-- The recursive `visit` call, by the invariant, has moved to the preceding node. In order to parenthesize
-- the original node, we must first move to the right, except if we already were at the left-most child in the first
-- place.
if idx > 0 then goRight
let mut stx ← getCur
-- Move leading/trailing whitespace of `stx` outside of parentheses
if let SourceInfo.original _ pos trail endPos := stx.getHeadInfo then
stx := stx.setHeadInfo (SourceInfo.original "".toSubstring pos trail endPos)
if let SourceInfo.original lead pos _ endPos := stx.getTailInfo then
stx := stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos)
let mut stx' := mkParen stx
if let SourceInfo.original lead pos _ endPos := stx.getHeadInfo then
stx' := stx'.setHeadInfo (SourceInfo.original lead pos "".toSubstring endPos)
if let SourceInfo.original _ pos trail endPos := stx.getTailInfo then
stx' := stx'.setTailInfo (SourceInfo.original "".toSubstring pos trail endPos)
trace[PrettyPrinter.parenthesize] "parenthesized: {stx'.formatStx none}"
setCur stx'
goLeft
-- after parenthesization, there is no more trailing parser
modify (fun st => { st with contPrec := Parser.maxPrec, contCat := cat, trailPrec := none })
let { trailPrec := trailPrec, .. } ← get
-- If we already had a token at this level, keep the trailing parser. Otherwise, use the minimum of
-- `prec` and `trailPrec`.
if st.visitedToken then
modify fun stP => { stP with trailPrec := st.trailPrec, trailCat := st.trailCat }
else
let trailPrec := match trailPrec with
| some trailPrec => Nat.min trailPrec prec
| _ => prec
modify fun stP => { stP with trailPrec := trailPrec, trailCat := cat }
modify fun stP => { stP with minPrec := st.minPrec }
/-- Adjust state and advance. -/
def visitToken : Parenthesizer := do
modify fun st => { st with contPrec := none, contCat := Name.anonymous, visitedToken := true }
goLeft
@[combinator_parenthesizer orelse] partial def orelse.parenthesizer (p1 p2 : Parenthesizer) : Parenthesizer := do
let stx ← getCur
-- `orelse` may produce `choice` nodes for antiquotations
if stx.getKind == `choice then
visitArgs $ stx.getArgs.size.forM fun _ => do
orelse.parenthesizer p1 p2
else
-- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try
-- them in turn. Uses the syntax traverser non-linearly!
p1 <|> p2
-- `mkAntiquot` is quite complex, so we'd rather have its parenthesizer synthesized below the actual parser definition.
-- Note that there is a mutual recursion
-- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere
-- anyway.
@[extern "lean_mk_antiquot_parenthesizer"]
opaque mkAntiquot.parenthesizer' (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := false) : Parenthesizer
@[inline] def liftCoreM {α} (x : CoreM α) : ParenthesizerM α :=
liftM x
-- break up big mutual recursion
@[extern "lean_pretty_printer_parenthesizer_interpret_parser_descr"]
opaque interpretParserDescr' : ParserDescr → CoreM Parenthesizer
unsafe def parenthesizerForKindUnsafe (k : SyntaxNodeKind) : Parenthesizer := do
if k == `missing then
pure ()
else
let p ← runForNodeKind parenthesizerAttribute k interpretParserDescr'
p
@[implemented_by parenthesizerForKindUnsafe]
opaque parenthesizerForKind (k : SyntaxNodeKind) : Parenthesizer
@[combinator_parenthesizer withAntiquot]
def withAntiquot.parenthesizer (antiP p : Parenthesizer) : Parenthesizer := do
let stx ← getCur
-- early check as minor optimization that also cleans up the backtrack traces
if stx.isAntiquot || stx.isAntiquotSplice then
orelse.parenthesizer antiP p
else
p
@[combinator_parenthesizer withAntiquotSuffixSplice]
def withAntiquotSuffixSplice.parenthesizer (_ : SyntaxNodeKind) (p suffix : Parenthesizer) : Parenthesizer := do
if (← getCur).isAntiquotSuffixSplice then
visitArgs <| suffix *> p
else
p
@[combinator_parenthesizer tokenWithAntiquot]
def tokenWithAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do
if (← getCur).isTokenAntiquot then
visitArgs p
else
p
partial def parenthesizeCategoryCore (cat : Name) (_prec : Nat) : Parenthesizer :=
withReader (fun ctx => { ctx with cat := cat }) do
let stx ← getCur
if stx.getKind == `choice then
visitArgs $ stx.getArgs.size.forM fun _ => do
parenthesizeCategoryCore cat _prec
else
withAntiquot.parenthesizer (mkAntiquot.parenthesizer' cat.toString cat (isPseudoKind := true)) (parenthesizerForKind stx.getKind)
modify fun st => { st with contCat := cat }
@[combinator_parenthesizer categoryParser]
def categoryParser.parenthesizer (cat : Name) (prec : Nat) : Parenthesizer := do
let env ← getEnv
match categoryParenthesizerAttribute.getValues env cat with
| p::_ => p prec
-- Fall back to the generic parenthesizer.
-- In this case this node will never be parenthesized since we don't know which parentheses to use.
| _ => parenthesizeCategoryCore cat prec
@[combinator_parenthesizer parserOfStack]
def parserOfStack.parenthesizer (offset : Nat) (_prec : Nat := 0) : Parenthesizer := do
let st ← get
let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset)
parenthesizerForKind stx.getKind
@[builtin_category_parenthesizer term]
def term.parenthesizer : CategoryParenthesizer | prec => do
maybeParenthesize `term true (fun stx => Unhygienic.run `(($(⟨stx⟩)))) prec $
parenthesizeCategoryCore `term prec
@[builtin_category_parenthesizer tactic]
def tactic.parenthesizer : CategoryParenthesizer | prec => do
maybeParenthesize `tactic false (fun stx => Unhygienic.run `(tactic|($(⟨stx⟩)))) prec $
parenthesizeCategoryCore `tactic prec
@[builtin_category_parenthesizer level]
def level.parenthesizer : CategoryParenthesizer | prec => do
maybeParenthesize `level false (fun stx => Unhygienic.run `(level|($(⟨stx⟩)))) prec $
parenthesizeCategoryCore `level prec
@[builtin_category_parenthesizer rawStx]
def rawStx.parenthesizer : CategoryParenthesizer | _ => do
goLeft
@[combinator_parenthesizer error]
def error.parenthesizer (_msg : String) : Parenthesizer :=
pure ()
@[combinator_parenthesizer errorAtSavedPos]
def errorAtSavedPos.parenthesizer (_msg : String) (_delta : Bool) : Parenthesizer :=
pure ()
@[combinator_parenthesizer atomic]
def atomic.parenthesizer (p : Parenthesizer) : Parenthesizer :=
p
@[combinator_parenthesizer lookahead]
def lookahead.parenthesizer (_ : Parenthesizer) : Parenthesizer :=
pure ()
@[combinator_parenthesizer notFollowedBy]
def notFollowedBy.parenthesizer (_ : Parenthesizer) : Parenthesizer :=
pure ()
@[combinator_parenthesizer andthen]
def andthen.parenthesizer (p1 p2 : Parenthesizer) : Parenthesizer :=
p2 *> p1
def checkKind (k : SyntaxNodeKind) : Parenthesizer := do
let stx ← getCur
if k != stx.getKind then
trace[PrettyPrinter.parenthesize.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'"
-- HACK; see `orelse.parenthesizer`
throwBacktrack
@[combinator_parenthesizer node]
def node.parenthesizer (k : SyntaxNodeKind) (p : Parenthesizer) : Parenthesizer := do
checkKind k
visitArgs p
@[combinator_parenthesizer checkPrec]
def checkPrec.parenthesizer (prec : Nat) : Parenthesizer :=
addPrecCheck prec
@[combinator_parenthesizer withFn]
def withFn.parenthesizer (_ : ParserFn → ParserFn) (p : Parenthesizer) : Parenthesizer := p
@[combinator_parenthesizer leadingNode]
def leadingNode.parenthesizer (k : SyntaxNodeKind) (prec : Nat) (p : Parenthesizer) : Parenthesizer := do
node.parenthesizer k p
addPrecCheck prec
-- Limit `cont` precedence to `maxPrec-1`.
-- This is because `maxPrec-1` is the precedence of function application, which is the only way to turn a leading parser
-- into a trailing one.
modify fun st => { st with contPrec := Nat.min (Parser.maxPrec-1) prec }
@[combinator_parenthesizer trailingNode]
def trailingNode.parenthesizer (k : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parenthesizer) : Parenthesizer := do
checkKind k
visitArgs do
p
addPrecCheck prec
let ctx ← read
modify fun st => { st with contCat := ctx.cat }
-- After visiting the nodes actually produced by the parser passed to `trailingNode`, we are positioned on the
-- left-most child, which is the term injected by `trailingNode` in place of the recursion. Left recursion is not an
-- issue for the parenthesizer, so we can think of this child being produced by `termParser lhsPrec`, or whichever Pratt
-- parser is calling us.
categoryParser.parenthesizer ctx.cat lhsPrec
@[combinator_parenthesizer rawCh] def rawCh.parenthesizer (_ch : Char) := visitToken
@[combinator_parenthesizer symbolNoAntiquot] def symbolNoAntiquot.parenthesizer (_sym : String) := visitToken
@[combinator_parenthesizer unicodeSymbolNoAntiquot] def unicodeSymbolNoAntiquot.parenthesizer (_sym _asciiSym : String) := visitToken
@[combinator_parenthesizer identNoAntiquot] def identNoAntiquot.parenthesizer := do checkKind identKind; visitToken
@[combinator_parenthesizer rawIdentNoAntiquot] def rawIdentNoAntiquot.parenthesizer := visitToken
@[combinator_parenthesizer identEq] def identEq.parenthesizer (_id : Name) := visitToken
@[combinator_parenthesizer nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.parenthesizer (_sym : String) (_includeIdent : Bool) := visitToken
@[combinator_parenthesizer charLitNoAntiquot] def charLitNoAntiquot.parenthesizer := visitToken
@[combinator_parenthesizer strLitNoAntiquot] def strLitNoAntiquot.parenthesizer := visitToken
@[combinator_parenthesizer nameLitNoAntiquot] def nameLitNoAntiquot.parenthesizer := visitToken
@[combinator_parenthesizer numLitNoAntiquot] def numLitNoAntiquot.parenthesizer := visitToken
@[combinator_parenthesizer scientificLitNoAntiquot] def scientificLitNoAntiquot.parenthesizer := visitToken
@[combinator_parenthesizer fieldIdx] def fieldIdx.parenthesizer := visitToken
@[combinator_parenthesizer manyNoAntiquot]
def manyNoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do
let stx ← getCur
visitArgs $ stx.getArgs.size.forM fun _ => p
@[combinator_parenthesizer many1NoAntiquot]
def many1NoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do
manyNoAntiquot.parenthesizer p
@[combinator_parenthesizer many1Unbox]
def many1Unbox.parenthesizer (p : Parenthesizer) : Parenthesizer := do
let stx ← getCur
if stx.getKind == nullKind then
manyNoAntiquot.parenthesizer p
else
p
@[combinator_parenthesizer optionalNoAntiquot]
def optionalNoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do
visitArgs p
@[combinator_parenthesizer sepByNoAntiquot]
def sepByNoAntiquot.parenthesizer (p pSep : Parenthesizer) : Parenthesizer := do
let stx ← getCur
visitArgs <| (List.range stx.getArgs.size).reverse.forM fun i => if i % 2 == 0 then p else pSep
@[combinator_parenthesizer sepBy1NoAntiquot] def sepBy1NoAntiquot.parenthesizer := sepByNoAntiquot.parenthesizer
@[combinator_parenthesizer withPosition] def withPosition.parenthesizer (p : Parenthesizer) : Parenthesizer := do
-- We assume the formatter will indent syntax sufficiently such that parenthesizing a `withPosition` node is never necessary
modify fun st => { st with contPrec := none }
p
@[combinator_parenthesizer withPositionAfterLinebreak] def withPositionAfterLinebreak.parenthesizer (p : Parenthesizer) : Parenthesizer :=
-- TODO: improve?
withPosition.parenthesizer p
@[combinator_parenthesizer withoutInfo] def withoutInfo.parenthesizer (p : Parenthesizer) : Parenthesizer := p
@[combinator_parenthesizer checkStackTop] def checkStackTop.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkWsBefore] def checkWsBefore.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkNoWsBefore] def checkNoWsBefore.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkLinebreakBefore] def checkLinebreakBefore.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkTailWs] def checkTailWs.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkColEq] def checkColEq.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkColGe] def checkColGe.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkColGt] def checkColGt.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkLineEq] def checkLineEq.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer eoi] def eoi.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer checkNoImmediateColon] def checkNoImmediateColon.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer skip] def skip.parenthesizer : Parenthesizer := pure ()
@[combinator_parenthesizer pushNone] def pushNone.parenthesizer : Parenthesizer := goLeft
@[combinator_parenthesizer interpolatedStr]
def interpolatedStr.parenthesizer (p : Parenthesizer) : Parenthesizer := do
visitArgs $ (← getCur).getArgs.reverse.forM fun chunk =>
if chunk.isOfKind interpolatedStrLitKind then
goLeft
else
p
@[combinator_parenthesizer _root_.ite, macro_inline] def ite {_ : Type} (c : Prop) [Decidable c] (t e : Parenthesizer) : Parenthesizer :=
if c then t else e
open Parser
abbrev ParenthesizerAliasValue := AliasValue Parenthesizer
builtin_initialize parenthesizerAliasesRef : IO.Ref (NameMap ParenthesizerAliasValue) ← IO.mkRef {}
def registerAlias (aliasName : Name) (v : ParenthesizerAliasValue) : IO Unit := do
Parser.registerAliasCore parenthesizerAliasesRef aliasName v
instance : Coe Parenthesizer ParenthesizerAliasValue := { coe := AliasValue.const }
instance : Coe (Parenthesizer → Parenthesizer) ParenthesizerAliasValue := { coe := AliasValue.unary }
instance : Coe (Parenthesizer → Parenthesizer → Parenthesizer) ParenthesizerAliasValue := { coe := AliasValue.binary }
end Parenthesizer
open Parenthesizer
/-- Add necessary parentheses in `stx` parsed by `parser`. -/
def parenthesize (parenthesizer : Parenthesizer) (stx : Syntax) : CoreM Syntax := do
trace[PrettyPrinter.parenthesize.input] "{format stx}"
catchInternalId backtrackExceptionId
(do
let (_, st) ← (parenthesizer {}).run { stxTrav := Syntax.Traverser.fromSyntax stx }
pure st.stxTrav.cur)
(fun _ => throwError "parenthesize: uncaught backtrack exception")
def parenthesizeCategory (cat : Name) := parenthesize <| categoryParser.parenthesizer cat 0
def parenthesizeTerm := parenthesizeCategory `term
def parenthesizeTactic := parenthesizeCategory `tactic
def parenthesizeCommand := parenthesizeCategory `command
builtin_initialize
registerTraceClass `PrettyPrinter.parenthesize
registerTraceClass `PrettyPrinter.parenthesize.backtrack (inherited := true)
registerTraceClass `PrettyPrinter.parenthesize.input (inherited := true)
end PrettyPrinter
end Lean
|
7625d120580b4bb7da3dfb090908df2ff1a583be | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/algebra/ring.lean | 67f32f2992cbdd809fdb8e095dfbbdae37834faf | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,204 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: algebra.ring
Authors: Jeremy Avigad, Leonardo de Moura
Structures with multiplicative and additive components, including semirings, rings, and fields.
The development is modeled after Isabelle's library.
-/
import logic.eq logic.connectives data.unit data.sigma data.prod
import algebra.function algebra.binary algebra.group
open eq eq.ops
namespace algebra
variable {A : Type}
/- auxiliary classes -/
structure distrib [class] (A : Type) extends has_mul A, has_add A :=
(left_distrib : ∀a b c, mul a (add b c) = add (mul a b) (mul a c))
(right_distrib : ∀a b c, mul (add a b) c = add (mul a c) (mul b c))
theorem left_distrib [s : distrib A] (a b c : A) : a * (b + c) = a * b + a * c :=
!distrib.left_distrib
theorem right_distrib [s: distrib A] (a b c : A) : (a + b) * c = a * c + b * c :=
!distrib.right_distrib
structure mul_zero_class [class] (A : Type) extends has_mul A, has_zero A :=
(zero_mul : ∀a, mul zero a = zero)
(mul_zero : ∀a, mul a zero = zero)
theorem zero_mul [s : mul_zero_class A] (a : A) : 0 * a = 0 := !mul_zero_class.zero_mul
theorem mul_zero [s : mul_zero_class A] (a : A) : a * 0 = 0 := !mul_zero_class.mul_zero
structure zero_ne_one_class [class] (A : Type) extends has_zero A, has_one A :=
(zero_ne_one : zero ≠ one)
theorem zero_ne_one [s: zero_ne_one_class A] : 0 ≠ 1 := @zero_ne_one_class.zero_ne_one A s
/- semiring -/
structure semiring [class] (A : Type) extends add_comm_monoid A, monoid A, distrib A,
mul_zero_class A
section semiring
variables [s : semiring A] (a b c : A)
include s
theorem ne_zero_of_mul_ne_zero_right {a b : A} (H : a * b ≠ 0) : a ≠ 0 :=
assume H1 : a = 0,
have H2 : a * b = 0, from H1⁻¹ ▸ zero_mul b,
H H2
theorem ne_zero_of_mul_ne_zero_left {a b : A} (H : a * b ≠ 0) : b ≠ 0 :=
assume H1 : b = 0,
have H2 : a * b = 0, from H1⁻¹ ▸ mul_zero a,
H H2
end semiring
/- comm semiring -/
structure comm_semiring [class] (A : Type) extends semiring A, comm_semigroup A
-- TODO: we could also define a cancelative comm_semiring, i.e. satisfying
-- c ≠ 0 → c * a = c * b → a = b.
section comm_semiring
variables [s : comm_semiring A] (a b c : A)
include s
definition dvd (a b : A) : Prop := ∃c, b = a * c
notation a ∣ b := dvd a b
theorem dvd.intro {a b c : A} (H : a * c = b) : a ∣ b :=
exists.intro _ H⁻¹
theorem dvd.intro_left {a b c : A} (H : c * a = b) : a ∣ b :=
dvd.intro (!mul.comm ▸ H)
theorem exists_eq_mul_right_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = a * c := H
theorem dvd.elim {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = a * c → P) : P :=
exists.elim H₁ H₂
theorem exists_eq_mul_left_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = c * a :=
dvd.elim H (take c, assume H1 : b = a * c, exists.intro c (H1 ⬝ !mul.comm))
theorem dvd.elim_left {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = c * a → P) : P :=
exists.elim (exists_eq_mul_left_of_dvd H₁) (take c, assume H₃ : b = c * a, H₂ c H₃)
theorem dvd.refl : a ∣ a := dvd.intro !mul_one
theorem dvd.trans {a b c : A} (H₁ : a ∣ b) (H₂ : b ∣ c) : a ∣ c :=
dvd.elim H₁
(take d, assume H₃ : b = a * d,
dvd.elim H₂
(take e, assume H₄ : c = b * e,
dvd.intro
(show a * (d * e) = c, by rewrite [-mul.assoc, -H₃, H₄])))
theorem eq_zero_of_zero_dvd {a : A} (H : 0 ∣ a) : a = 0 :=
dvd.elim H (take c, assume H' : a = 0 * c, H' ⬝ !zero_mul)
theorem dvd_zero : a ∣ 0 := dvd.intro !mul_zero
theorem one_dvd : 1 ∣ a := dvd.intro !one_mul
theorem dvd_mul_right : a ∣ a * b := dvd.intro rfl
theorem dvd_mul_left : a ∣ b * a := mul.comm a b ▸ dvd_mul_right a b
theorem dvd_mul_of_dvd_left {a b : A} (H : a ∣ b) (c : A) : a ∣ b * c :=
dvd.elim H
(take d,
assume H₁ : b = a * d,
dvd.intro
(show a * (d * c) = b * c, from by rewrite [-mul.assoc, H₁]))
theorem dvd_mul_of_dvd_right {a b : A} (H : a ∣ b) (c : A) : a ∣ c * b :=
!mul.comm ▸ (dvd_mul_of_dvd_left H _)
theorem mul_dvd_mul {a b c d : A} (dvd_ab : (a ∣ b)) (dvd_cd : c ∣ d) : a * c ∣ b * d :=
dvd.elim dvd_ab
(take e, assume Haeb : b = a * e,
dvd.elim dvd_cd
(take f, assume Hcfd : d = c * f,
dvd.intro
(show a * c * (e * f) = b * d,
by rewrite [mul.assoc, {c*_}mul.left_comm, -mul.assoc, Haeb, Hcfd])))
theorem dvd_of_mul_right_dvd {a b c : A} (H : a * b ∣ c) : a ∣ c :=
dvd.elim H (take d, assume Habdc : c = a * b * d, dvd.intro (!mul.assoc⁻¹ ⬝ Habdc⁻¹))
theorem dvd_of_mul_left_dvd {a b c : A} (H : a * b ∣ c) : b ∣ c :=
dvd_of_mul_right_dvd (mul.comm a b ▸ H)
theorem dvd_add {a b c : A} (Hab : a ∣ b) (Hac : a ∣ c) : a ∣ b + c :=
dvd.elim Hab
(take d, assume Hadb : b = a * d,
dvd.elim Hac
(take e, assume Haec : c = a * e,
dvd.intro (show a * (d + e) = b + c,
by rewrite [left_distrib, -Hadb, -Haec])))
end comm_semiring
/- ring -/
structure ring [class] (A : Type) extends add_comm_group A, monoid A, distrib A
theorem ring.mul_zero [s : ring A] (a : A) : a * 0 = 0 :=
have H : a * 0 + 0 = a * 0 + a * 0, from calc
a * 0 + 0 = a * 0 : by rewrite add_zero
... = a * (0 + 0) : by rewrite add_zero
... = a * 0 + a * 0 : by rewrite {a*_}ring.left_distrib,
show a * 0 = 0, from (add.left_cancel H)⁻¹
theorem ring.zero_mul [s : ring A] (a : A) : 0 * a = 0 :=
have H : 0 * a + 0 = 0 * a + 0 * a, from calc
0 * a + 0 = 0 * a : by rewrite add_zero
... = (0 + 0) * a : by rewrite add_zero
... = 0 * a + 0 * a : by rewrite {_*a}ring.right_distrib,
show 0 * a = 0, from (add.left_cancel H)⁻¹
definition ring.to_semiring [instance] [coercion] [reducible] [s : ring A] : semiring A :=
⦃ semiring, s,
mul_zero := ring.mul_zero,
zero_mul := ring.zero_mul ⦄
section
variables [s : ring A] (a b c d e : A)
include s
theorem neg_mul_eq_neg_mul : -(a * b) = -a * b :=
neg_eq_of_add_eq_zero
begin
rewrite [-right_distrib, add.right_inv, zero_mul]
end
theorem neg_mul_eq_mul_neg : -(a * b) = a * -b :=
neg_eq_of_add_eq_zero
begin
rewrite [-left_distrib, add.right_inv, mul_zero]
end
theorem neg_mul_neg : -a * -b = a * b :=
calc
-a * -b = -(a * -b) : by rewrite -neg_mul_eq_neg_mul
... = - -(a * b) : by rewrite -neg_mul_eq_mul_neg
... = a * b : by rewrite neg_neg
theorem neg_mul_comm : -a * b = a * -b := !neg_mul_eq_neg_mul⁻¹ ⬝ !neg_mul_eq_mul_neg
theorem neg_eq_neg_one_mul : -a = -1 * a :=
calc
-a = -(1 * a) : by rewrite one_mul
... = -1 * a : by rewrite neg_mul_eq_neg_mul
theorem mul_sub_left_distrib : a * (b - c) = a * b - a * c :=
calc
a * (b - c) = a * b + a * -c : left_distrib
... = a * b + - (a * c) : by rewrite -neg_mul_eq_mul_neg
... = a * b - a * c : rfl
theorem mul_sub_right_distrib : (a - b) * c = a * c - b * c :=
calc
(a - b) * c = a * c + -b * c : right_distrib
... = a * c + - (b * c) : by rewrite neg_mul_eq_neg_mul
... = a * c - b * c : rfl
-- TODO: can calc mode be improved to make this easier?
-- TODO: there is also the other direction. It will be easier when we
-- have the simplifier.
theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d :=
calc
a * e + c = b * e + d ↔ a * e + c = d + b * e : by rewrite {b*e+_}add.comm
... ↔ a * e + c - b * e = d : iff.symm !sub_eq_iff_eq_add
... ↔ a * e - b * e + c = d : by rewrite sub_add_eq_add_sub
... ↔ (a - b) * e + c = d : by rewrite mul_sub_right_distrib
theorem mul_neg_one_eq_neg : a * (-1) = -a :=
have H : a + a * -1 = 0, from calc
a + a * -1 = a * 1 + a * -1 : mul_one
... = a * (1 + -1) : left_distrib
... = a * 0 : add.right_inv
... = 0 : mul_zero,
symm (neg_eq_of_add_eq_zero H)
theorem mul_ne_zero_imp_ne_zero {a b} (H : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
have Ha : a ≠ 0, from
(assume Ha1 : a = 0,
have H1 : a * b = 0, by rewrite [Ha1, zero_mul],
absurd H1 H),
have Hb : b ≠ 0, from
(assume Hb1 : b = 0,
have H1 : a * b = 0, by rewrite [Hb1, mul_zero],
absurd H1 H),
and.intro Ha Hb
end
structure comm_ring [class] (A : Type) extends ring A, comm_semigroup A
definition comm_ring.to_comm_semiring [instance] [coercion] [reducible] [s : comm_ring A] : comm_semiring A :=
⦃ comm_semiring, s,
mul_zero := mul_zero,
zero_mul := zero_mul ⦄
section
variables [s : comm_ring A] (a b c d e : A)
include s
theorem mul_self_sub_mul_self_eq : a * a - b * b = (a + b) * (a - b) :=
by rewrite [left_distrib, *right_distrib, add.assoc, -{b*a + _}add.assoc,
-*neg_mul_eq_mul_neg, {a*b}mul.comm, add.right_inv, zero_add]
theorem mul_self_sub_one_eq : a * a - 1 = (a + 1) * (a - 1) :=
mul_one 1 ▸ mul_self_sub_mul_self_eq a 1
theorem dvd_neg_iff_dvd : (a ∣ -b) ↔ (a ∣ b) :=
iff.intro
(assume H : (a ∣ -b),
dvd.elim H
(take c, assume H' : -b = a * c,
dvd.intro
(show a * -c = b,
by rewrite [-neg_mul_eq_mul_neg, -H', neg_neg])))
(assume H : (a ∣ b),
dvd.elim H
(take c, assume H' : b = a * c,
dvd.intro
(show a * -c = -b,
by rewrite [-neg_mul_eq_mul_neg, -H'])))
theorem neg_dvd_iff_dvd : (-a ∣ b) ↔ (a ∣ b) :=
iff.intro
(assume H : (-a ∣ b),
dvd.elim H
(take c, assume H' : b = -a * c,
dvd.intro
(show a * -c = b, by rewrite [-neg_mul_comm, H'])))
(assume H : (a ∣ b),
dvd.elim H
(take c, assume H' : b = a * c,
dvd.intro
(show -a * -c = b, by rewrite [neg_mul_neg, H'])))
theorem dvd_sub (H₁ : (a ∣ b)) (H₂ : (a ∣ c)) : (a ∣ b - c) :=
dvd_add H₁ (iff.elim_right !dvd_neg_iff_dvd H₂)
end
/- integral domains -/
structure no_zero_divisors [class] (A : Type) extends has_mul A, has_zero A :=
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀a b, mul a b = zero → a = zero ∨ b = zero)
theorem eq_zero_or_eq_zero_of_mul_eq_zero {A : Type} [s : no_zero_divisors A] {a b : A}
(H : a * b = 0) :
a = 0 ∨ b = 0 := !no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero H
structure integral_domain [class] (A : Type) extends comm_ring A, no_zero_divisors A
section
variables [s : integral_domain A] (a b c d e : A)
include s
theorem mul_ne_zero {a b : A} (H1 : a ≠ 0) (H2 : b ≠ 0) : a * b ≠ 0 :=
assume H : a * b = 0,
or.elim (eq_zero_or_eq_zero_of_mul_eq_zero H) (assume H3, H1 H3) (assume H4, H2 H4)
theorem mul.cancel_right {a b c : A} (Ha : a ≠ 0) (H : b * a = c * a) : b = c :=
have H1 : b * a - c * a = 0, from iff.mp !eq_iff_sub_eq_zero H,
have H2 : (b - c) * a = 0, using H1, by rewrite [mul_sub_right_distrib, H1],
have H3 : b - c = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H2) Ha,
iff.elim_right !eq_iff_sub_eq_zero H3
theorem mul.cancel_left {a b c : A} (Ha : a ≠ 0) (H : a * b = a * c) : b = c :=
have H1 : a * b - a * c = 0, from iff.mp !eq_iff_sub_eq_zero H,
have H2 : a * (b - c) = 0, using H1, by rewrite [mul_sub_left_distrib, H1],
have H3 : b - c = 0, from or_resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero H2) Ha,
iff.elim_right !eq_iff_sub_eq_zero H3
-- TODO: do we want the iff versions?
theorem mul_self_eq_mul_self_iff (a b : A) : a * a = b * b ↔ a = b ∨ a = -b :=
iff.intro
(λ H : a * a = b * b,
have aux₁ : (a - b) * (a + b) = 0,
by rewrite [mul.comm, -mul_self_sub_mul_self_eq, H, sub_self],
assert aux₂ : a - b = 0 ∨ a + b = 0, from !eq_zero_or_eq_zero_of_mul_eq_zero aux₁,
or.elim aux₂
(λ H : a - b = 0, or.inl (eq_of_sub_eq_zero H))
(λ H : a + b = 0, or.inr (eq_neg_of_add_eq_zero H)))
(λ H : a = b ∨ a = -b, or.elim H
(λ a_eq_b, by rewrite a_eq_b)
(λ a_eq_mb, by rewrite [a_eq_mb, neg_mul_neg]))
theorem mul_self_eq_one_iff (a : A) : a * a = 1 ↔ a = 1 ∨ a = -1 :=
assert aux : a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1,
by rewrite mul_one at aux; exact aux
-- TODO: c - b * c → c = 0 ∨ b = 1 and variants
theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) :=
dvd.elim Hdvd
(take d,
assume H : a * c = a * b * d,
have H1 : b * d = c, from mul.cancel_left Ha (mul.assoc a b d ▸ H⁻¹),
dvd.intro H1)
theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) :=
dvd.elim Hdvd
(take d,
assume H : c * a = b * a * d,
have H1 : b * d * a = c * a, from by rewrite [mul.right_comm, -H],
have H2 : b * d = c, from mul.cancel_right Ha H1,
dvd.intro H2)
end
end algebra
|
f3efbbe75ef49dfb37f49a06de146917d8069b22 | b4de178dd16cc5cd7310d3c301f2fe4643abc186 | /TestPkg2.lean | 660d034ebbfa0d66a7aa08fd56b70e7c262fd83d | [] | no_license | Kha/testpkg2 | ca22a90895195c8d1f5924ba239c69ef798092b4 | df59011558d349127c11c6be92b290981c805463 | refs/heads/master | 1,674,159,038,420 | 1,606,925,479,000 | 1,606,926,940,000 | 317,924,522 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 45 | lean | import TestPkg1
#eval s!"Hello, {subject}!"
|
25cb66f79db28078e5d78caf98d08ba40b292ab8 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/order/complete_boolean_algebra.lean | e7e055258a027ecbd15e320c3734d77d219e423b | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 2,525 | 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 complete Boolean algebras.
-/
import order.complete_lattice order.boolean_algebra data.set.basic
set_option old_structure_cmd true
universes u v w
variables {α : Type u} {β : Type v} {ι : Sort w}
namespace lattice
/-- A complete distributive lattice is a bit stronger than the name might
suggest; perhaps completely distributive lattice is more descriptive,
as this class includes a requirement that the lattice join
distribute over *arbitrary* infima, and similarly for the dual. -/
class complete_distrib_lattice α extends complete_lattice α :=
(infi_sup_le_sup_Inf : ∀a s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s)
(inf_Sup_le_supr_inf : ∀a s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b))
section complete_distrib_lattice
variables [complete_distrib_lattice α] {a : α} {s : set α}
theorem sup_Inf_eq : a ⊔ Inf s = (⨅ b ∈ s, a ⊔ b) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume h, sup_le_sup (le_refl _) (Inf_le h))
(complete_distrib_lattice.infi_sup_le_sup_Inf _ _)
theorem inf_Sup_eq : a ⊓ Sup s = (⨆ b ∈ s, a ⊓ b) :=
le_antisymm
(complete_distrib_lattice.inf_Sup_le_supr_inf _ _)
(supr_le $ assume i, supr_le $ assume h, inf_le_inf (le_refl _) (le_Sup h))
end complete_distrib_lattice
instance [d : complete_distrib_lattice α] : bounded_distrib_lattice α :=
{ le_sup_inf := assume x y z,
calc (x ⊔ y) ⊓ (x ⊔ z) ≤ (⨅ b ∈ ({z, y} : set α), x ⊔ b) :
by simp [or_imp_distrib] {contextual := tt}
... = x ⊔ Inf {z, y} : sup_Inf_eq.symm
... = x ⊔ y ⊓ z : by rw insert_of_has_insert; simp,
..d }
/-- A complete boolean algebra is a completely distributive boolean algebra. -/
class complete_boolean_algebra α extends boolean_algebra α, complete_distrib_lattice α
section complete_boolean_algebra
variables [complete_boolean_algebra α] {a b : α} {s : set α} {f : ι → α}
theorem neg_infi : - infi f = (⨆i, - f i) :=
le_antisymm
(neg_le_of_neg_le $ le_infi $ assume i, neg_le_of_neg_le $ le_supr (λi, - f i) i)
(supr_le $ assume i, neg_le_neg $ infi_le _ _)
theorem neg_supr : - supr f = (⨅i, - f i) :=
neg_eq_neg_of_eq (by simp [neg_infi])
theorem neg_Inf : - Inf s = (⨆i∈s, - i) :=
by simp [Inf_eq_infi, neg_infi]
theorem neg_Sup : - Sup s = (⨅i∈s, - i) :=
by simp [Sup_eq_supr, neg_supr]
end complete_boolean_algebra
end lattice
|
404a07eb0605d34c3125860a2323cafeb12c852c | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/control/lawful_fix.lean | 4548dede4a885a8021e5715bd648659f77a894bc | [
"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 | 7,720 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic.apply
import control.fix
import order.omega_complete_partial_order
/-!
# Lawful fixed point operators
This module defines the laws required of a `has_fix` instance, using the theory of
omega complete partial orders (ωCPO). Proofs of the lawfulness of all `has_fix` instances in
`control.fix` are provided.
## Main definition
* class `lawful_fix`
-/
universes u v
open_locale classical
variables {α : Type*} {β : α → Type*}
open omega_complete_partial_order
/-- Intuitively, a fixed point operator `fix` is lawful if it satisfies `fix f = f (fix f)` for all
`f`, but this is inconsistent / uninteresting in most cases due to the existence of "exotic"
functions `f`, such as the function that is defined iff its argument is not, familiar from the
halting problem. Instead, this requirement is limited to only functions that are `continuous` in the
sense of `ω`-complete partial orders, which excludes the example because it is not monotone
(making the input argument less defined can make `f` more defined). -/
class lawful_fix (α : Type*) [omega_complete_partial_order α] extends has_fix α :=
(fix_eq : ∀ {f : α →ₘ α}, continuous f → has_fix.fix f = f (has_fix.fix f))
lemma lawful_fix.fix_eq' {α} [omega_complete_partial_order α] [lawful_fix α]
{f : α → α} (hf : continuous' f) :
has_fix.fix f = f (has_fix.fix f) :=
lawful_fix.fix_eq (continuous.to_bundled _ hf)
namespace part
open part nat nat.upto
namespace fix
variables (f : (Π a, part $ β a) →ₘ (Π a, part $ β a))
lemma approx_mono' {i : ℕ} : fix.approx f i ≤ fix.approx f (succ i) :=
begin
induction i, dsimp [approx], apply @bot_le _ _ (f ⊥),
intro, apply f.monotone, apply i_ih
end
lemma approx_mono ⦃i j : ℕ⦄ (hij : i ≤ j) : approx f i ≤ approx f j :=
begin
induction j, cases hij, refine @le_refl _ _ _,
cases hij, apply @le_refl _ _ _,
apply @le_trans _ _ _ (approx f j_n) _ (j_ih ‹_›),
apply approx_mono' f
end
lemma mem_iff (a : α) (b : β a) : b ∈ part.fix f a ↔ ∃ i, b ∈ approx f i a :=
begin
by_cases h₀ : ∃ (i : ℕ), (approx f i a).dom,
{ simp only [part.fix_def f h₀],
split; intro hh, exact ⟨_,hh⟩,
have h₁ := nat.find_spec h₀,
rw [dom_iff_mem] at h₁,
cases h₁ with y h₁,
replace h₁ := approx_mono' f _ _ h₁,
suffices : y = b, subst this, exact h₁,
cases hh with i hh,
revert h₁, generalize : (succ (nat.find h₀)) = j, intro,
wlog : i ≤ j := le_total i j using [i j b y,j i y b],
replace hh := approx_mono f case _ _ hh,
apply part.mem_unique h₁ hh },
{ simp only [fix_def' ⇑f h₀, not_exists, false_iff, not_mem_none],
simp only [dom_iff_mem, not_exists] at h₀,
intro, apply h₀ }
end
lemma approx_le_fix (i : ℕ) : approx f i ≤ part.fix f :=
assume a b hh,
by { rw [mem_iff f], exact ⟨_,hh⟩ }
lemma exists_fix_le_approx (x : α) : ∃ i, part.fix f x ≤ approx f i x :=
begin
by_cases hh : ∃ i b, b ∈ approx f i x,
{ rcases hh with ⟨i,b,hb⟩, existsi i,
intros b' h',
have hb' := approx_le_fix f i _ _ hb,
have hh := part.mem_unique h' hb',
subst hh, exact hb },
{ simp only [not_exists] at hh, existsi 0,
intros b' h',
simp only [mem_iff f] at h',
cases h' with i h',
cases hh _ _ h' }
end
include f
/-- The series of approximations of `fix f` (see `approx`) as a `chain` -/
def approx_chain : chain (Π a, part $ β a) := ⟨approx f, approx_mono f⟩
lemma le_f_of_mem_approx {x} (hx : x ∈ approx_chain f) : x ≤ f x :=
begin
revert hx, simp [(∈)],
intros i hx, subst x,
apply approx_mono'
end
lemma approx_mem_approx_chain {i} : approx f i ∈ approx_chain f :=
stream.mem_of_nth_eq rfl
end fix
open fix
variables {α}
variables (f : (Π a, part $ β a) →ₘ (Π a, part $ β a))
open omega_complete_partial_order
open part (hiding ωSup) nat
open nat.upto omega_complete_partial_order
lemma fix_eq_ωSup : part.fix f = ωSup (approx_chain f) :=
begin
apply le_antisymm,
{ intro x, cases exists_fix_le_approx f x with i hx,
transitivity' approx f i.succ x,
{ transitivity', apply hx, apply approx_mono' f },
apply' le_ωSup_of_le i.succ,
dsimp [approx], refl', },
{ apply ωSup_le _ _ _,
simp only [fix.approx_chain, preorder_hom.coe_fun_mk],
intros y x, apply approx_le_fix f },
end
lemma fix_le {X : Π a, part $ β a} (hX : f X ≤ X) : part.fix f ≤ X :=
begin
rw fix_eq_ωSup f,
apply ωSup_le _ _ _,
simp only [fix.approx_chain, preorder_hom.coe_fun_mk],
intros i,
induction i, dsimp [fix.approx], apply' bot_le,
transitivity' f X, apply f.monotone i_ih,
apply hX
end
variables {f} (hc : continuous f)
include hc
lemma fix_eq : part.fix f = f (part.fix f) :=
begin
rw [fix_eq_ωSup f,hc],
apply le_antisymm,
{ apply ωSup_le_ωSup_of_le _,
intros i, existsi [i], intro x, -- intros x y hx,
apply le_f_of_mem_approx _ ⟨i, rfl⟩, },
{ apply ωSup_le_ωSup_of_le _,
intros i, existsi i.succ, refl', }
end
end part
namespace part
/-- `to_unit` as a monotone function -/
@[simps]
def to_unit_mono (f : part α →ₘ part α) : (unit → part α) →ₘ (unit → part α) :=
{ to_fun := λ x u, f (x u),
monotone' := λ x y (h : x ≤ y) u, f.monotone $ h u }
lemma to_unit_cont (f : part α →ₘ part α) (hc : continuous f) : continuous (to_unit_mono f)
| c := begin
ext ⟨⟩ : 1,
dsimp [omega_complete_partial_order.ωSup],
erw [hc, chain.map_comp], refl
end
noncomputable instance : lawful_fix (part α) :=
⟨λ f hc, show part.fix (to_unit_mono f) () = _, by rw part.fix_eq (to_unit_cont f hc); refl⟩
end part
open sigma
namespace pi
noncomputable instance {β} : lawful_fix (α → part β) := ⟨λ f, part.fix_eq⟩
variables {γ : Π a : α, β a → Type*}
section monotone
variables (α β γ)
/-- `sigma.curry` as a monotone function. -/
@[simps]
def monotone_curry [∀ x y, preorder $ γ x y] :
(Π x : Σ a, β a, γ x.1 x.2) →ₘ (Π a (b : β a), γ a b) :=
{ to_fun := curry,
monotone' := λ x y h a b, h ⟨a,b⟩ }
/-- `sigma.uncurry` as a monotone function. -/
@[simps]
def monotone_uncurry [∀ x y, preorder $ γ x y] :
(Π a (b : β a), γ a b) →ₘ (Π x : Σ a, β a, γ x.1 x.2) :=
{ to_fun := uncurry,
monotone' := λ x y h a, h a.1 a.2 }
variables [∀ x y, omega_complete_partial_order $ γ x y]
open omega_complete_partial_order.chain
lemma continuous_curry : continuous $ monotone_curry α β γ :=
λ c, by { ext x y, dsimp [curry,ωSup], rw [map_comp,map_comp], refl }
lemma continuous_uncurry : continuous $ monotone_uncurry α β γ :=
λ c, by { ext x y, dsimp [uncurry,ωSup], rw [map_comp,map_comp], refl }
end monotone
open has_fix
instance [has_fix $ Π x : sigma β, γ x.1 x.2] : has_fix (Π x (y : β x), γ x y) :=
⟨ λ f, curry (fix $ uncurry ∘ f ∘ curry) ⟩
variables [∀ x y, omega_complete_partial_order $ γ x y]
section curry
variables {f : (Π x (y : β x), γ x y) →ₘ (Π x (y : β x), γ x y)}
variables (hc : continuous f)
lemma uncurry_curry_continuous :
continuous $ (monotone_uncurry α β γ).comp $ f.comp $ monotone_curry α β γ :=
continuous_comp _ _
(continuous_comp _ _ (continuous_curry _ _ _) hc)
(continuous_uncurry _ _ _)
end curry
instance pi.lawful_fix' [lawful_fix $ Π x : sigma β, γ x.1 x.2] : lawful_fix (Π x y, γ x y) :=
{ fix_eq := λ f hc,
begin
dsimp [fix],
conv { to_lhs, erw [lawful_fix.fix_eq (uncurry_curry_continuous hc)] },
refl,
end, }
end pi
|
754a5d3cb03ede84fdf78d99e49f2996799ca561 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/measure_theory/integral/interval_integral.lean | 15062741e82dc6f4ad196b2468898d0e08cd6596 | [
"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 | 62,137 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Patrick Massot, Sébastien Gouëzel
-/
import data.set.intervals.disjoint
import measure_theory.integral.set_integral
import measure_theory.measure.lebesgue
/-!
# Integral over an interval
In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and
`-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`.
## Implementation notes
### Avoiding `if`, `min`, and `max`
In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as
`integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these
intervals is empty and the other coincides with `set.uIoc a b = set.Ioc (min a b) (max a b)`.
Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`.
Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result.
This way some properties can be translated from integrals over sets without dealing with
the cases `a ≤ b` and `b ≤ a` separately.
### Choice of the interval
We use integral over `set.uIoc a b = set.Ioc (min a b) (max a b)` instead of one of the other
three possible intervals with the same endpoints for two reasons:
* this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever
`f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom
at `b`; this rules out `set.Ioo` and `set.Icc` intervals;
* with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals
the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the
[cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function)
of `μ`.
## Tags
integral
-/
noncomputable theory
open topological_space (second_countable_topology)
open measure_theory set classical filter function
open_locale classical topology filter ennreal big_operators interval nnreal
variables {ι 𝕜 E F A : Type*} [normed_add_comm_group E]
/-!
### Integrability on an interval
-/
/-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered
interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these
intervals is always empty, so this property is equivalent to `f` being integrable on
`(min a b, max a b]`. -/
def interval_integrable (f : ℝ → E) (μ : measure ℝ) (a b : ℝ) : Prop :=
integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ
section
variables {f : ℝ → E} {a b : ℝ} {μ : measure ℝ}
/-- A function is interval integrable with respect to a given measure `μ` on `a..b` if and
only if it is integrable on `uIoc a b` with respect to `μ`. This is an equivalent
definition of `interval_integrable`. -/
lemma interval_integrable_iff : interval_integrable f μ a b ↔ integrable_on f (Ι a b) μ :=
by rw [uIoc_eq_union, integrable_on_union, interval_integrable]
/-- If a function is interval integrable with respect to a given measure `μ` on `a..b` then
it is integrable on `uIoc a b` with respect to `μ`. -/
lemma interval_integrable.def (h : interval_integrable f μ a b) : integrable_on f (Ι a b) μ :=
interval_integrable_iff.mp h
lemma interval_integrable_iff_integrable_Ioc_of_le (hab : a ≤ b) :
interval_integrable f μ a b ↔ integrable_on f (Ioc a b) μ :=
by rw [interval_integrable_iff, uIoc_of_le hab]
lemma interval_integrable_iff' [has_no_atoms μ] :
interval_integrable f μ a b ↔ integrable_on f (uIcc a b) μ :=
by rw [interval_integrable_iff, ←Icc_min_max, uIoc, integrable_on_Icc_iff_integrable_on_Ioc]
lemma interval_integrable_iff_integrable_Icc_of_le
{f : ℝ → E} {a b : ℝ} (hab : a ≤ b) {μ : measure ℝ} [has_no_atoms μ] :
interval_integrable f μ a b ↔ integrable_on f (Icc a b) μ :=
by rw [interval_integrable_iff_integrable_Ioc_of_le hab, integrable_on_Icc_iff_integrable_on_Ioc]
/-- If a function is integrable with respect to a given measure `μ` then it is interval integrable
with respect to `μ` on `uIcc a b`. -/
lemma measure_theory.integrable.interval_integrable (hf : integrable f μ) :
interval_integrable f μ a b :=
⟨hf.integrable_on, hf.integrable_on⟩
lemma measure_theory.integrable_on.interval_integrable (hf : integrable_on f [a, b] μ) :
interval_integrable f μ a b :=
⟨measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_uIcc),
measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_uIcc')⟩
lemma interval_integrable_const_iff {c : E} :
interval_integrable (λ _, c) μ a b ↔ c = 0 ∨ μ (Ι a b) < ∞ :=
by simp only [interval_integrable_iff, integrable_on_const]
@[simp] lemma interval_integrable_const [is_locally_finite_measure μ] {c : E} :
interval_integrable (λ _, c) μ a b :=
interval_integrable_const_iff.2 $ or.inr measure_Ioc_lt_top
end
namespace interval_integrable
section
variables {f : ℝ → E} {a b c d : ℝ} {μ ν : measure ℝ}
@[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a :=
h.symm
@[refl] lemma refl : interval_integrable f μ a a :=
by split; simp
@[trans] lemma trans {a b c : ℝ} (hab : interval_integrable f μ a b)
(hbc : interval_integrable f μ b c) : interval_integrable f μ a c :=
⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc,
(hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩
lemma trans_iterate_Ico {a : ℕ → ℝ} {m n : ℕ} (hmn : m ≤ n)
(hint : ∀ k ∈ Ico m n, interval_integrable f μ (a k) (a $ k+1)) :
interval_integrable f μ (a m) (a n) :=
begin
revert hint,
refine nat.le_induction _ _ n hmn,
{ simp },
{ assume p hp IH h,
exact (IH (λ k hk, h k (Ico_subset_Ico_right p.le_succ hk))).trans (h p (by simp [hp])) }
end
lemma trans_iterate {a : ℕ → ℝ} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) :
interval_integrable f μ (a 0) (a n) :=
trans_iterate_Ico bot_le (λ k hk, hint k hk.2)
lemma neg (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b :=
⟨h.1.neg, h.2.neg⟩
lemma norm (h : interval_integrable f μ a b) :
interval_integrable (λ x, ‖f x‖) μ a b :=
⟨h.1.norm, h.2.norm⟩
lemma interval_integrable_norm_iff {f : ℝ → E} {μ : measure ℝ} {a b : ℝ}
(hf : ae_strongly_measurable f (μ.restrict (Ι a b))) :
interval_integrable (λ t, ‖f t‖) μ a b ↔ interval_integrable f μ a b :=
by { simp_rw [interval_integrable_iff, integrable_on], exact integrable_norm_iff hf }
lemma abs {f : ℝ → ℝ} (h : interval_integrable f μ a b) :
interval_integrable (λ x, |f x|) μ a b :=
h.norm
lemma mono (hf : interval_integrable f ν a b) (h1 : [c, d] ⊆ [a, b]) (h2 : μ ≤ ν) :
interval_integrable f μ c d :=
interval_integrable_iff.mpr $ hf.def.mono
(uIoc_subset_uIoc_of_uIcc_subset_uIcc h1) h2
lemma mono_measure (hf : interval_integrable f ν a b) (h : μ ≤ ν) :
interval_integrable f μ a b :=
hf.mono rfl.subset h
lemma mono_set (hf : interval_integrable f μ a b) (h : [c, d] ⊆ [a, b]) :
interval_integrable f μ c d :=
hf.mono h rfl.le
lemma mono_set_ae (hf : interval_integrable f μ a b) (h : Ι c d ≤ᵐ[μ] Ι a b) :
interval_integrable f μ c d :=
interval_integrable_iff.mpr $ hf.def.mono_set_ae h
lemma mono_set' (hf : interval_integrable f μ a b) (hsub : Ι c d ⊆ Ι a b) :
interval_integrable f μ c d :=
hf.mono_set_ae $ eventually_of_forall hsub
lemma mono_fun [normed_add_comm_group F] {g : ℝ → F}
(hf : interval_integrable f μ a b) (hgm : ae_strongly_measurable g (μ.restrict (Ι a b)))
(hle : (λ x, ‖g x‖) ≤ᵐ[μ.restrict (Ι a b)] (λ x, ‖f x‖)) : interval_integrable g μ a b :=
interval_integrable_iff.2 $ hf.def.integrable.mono hgm hle
lemma mono_fun' {g : ℝ → ℝ} (hg : interval_integrable g μ a b)
(hfm : ae_strongly_measurable f (μ.restrict (Ι a b)))
(hle : (λ x, ‖f x‖) ≤ᵐ[μ.restrict (Ι a b)] g) : interval_integrable f μ a b :=
interval_integrable_iff.2 $ hg.def.integrable.mono' hfm hle
protected lemma ae_strongly_measurable (h : interval_integrable f μ a b) :
ae_strongly_measurable f (μ.restrict (Ioc a b)):=
h.1.ae_strongly_measurable
protected lemma ae_strongly_measurable' (h : interval_integrable f μ a b) :
ae_strongly_measurable f (μ.restrict (Ioc b a)):=
h.2.ae_strongly_measurable
end
variables [normed_ring A] {f g : ℝ → E} {a b : ℝ} {μ : measure ℝ}
lemma smul [normed_field 𝕜] [normed_space 𝕜 E]
{f : ℝ → E} {a b : ℝ} {μ : measure ℝ} (h : interval_integrable f μ a b) (r : 𝕜) :
interval_integrable (r • f) μ a b :=
⟨h.1.smul r, h.2.smul r⟩
@[simp] lemma add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) :
interval_integrable (λ x, f x + g x) μ a b :=
⟨hf.1.add hg.1, hf.2.add hg.2⟩
@[simp] lemma sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) :
interval_integrable (λ x, f x - g x) μ a b :=
⟨hf.1.sub hg.1, hf.2.sub hg.2⟩
lemma sum (s : finset ι) {f : ι → ℝ → E} (h : ∀ i ∈ s, interval_integrable (f i) μ a b) :
interval_integrable (∑ i in s, f i) μ a b :=
⟨integrable_finset_sum' s (λ i hi, (h i hi).1), integrable_finset_sum' s (λ i hi, (h i hi).2)⟩
lemma mul_continuous_on {f g : ℝ → A}
(hf : interval_integrable f μ a b) (hg : continuous_on g [a, b]) :
interval_integrable (λ x, f x * g x) μ a b :=
begin
rw interval_integrable_iff at hf ⊢,
exact hf.mul_continuous_on_of_subset hg measurable_set_Ioc is_compact_uIcc Ioc_subset_Icc_self
end
lemma continuous_on_mul {f g : ℝ → A}
(hf : interval_integrable f μ a b) (hg : continuous_on g [a, b]) :
interval_integrable (λ x, g x * f x) μ a b :=
begin
rw interval_integrable_iff at hf ⊢,
exact hf.continuous_on_mul_of_subset hg is_compact_uIcc measurable_set_Ioc Ioc_subset_Icc_self
end
@[simp]
lemma const_mul {f : ℝ → A}
(hf : interval_integrable f μ a b) (c : A) : interval_integrable (λ x, c * f x) μ a b :=
hf.continuous_on_mul continuous_on_const
@[simp]
lemma mul_const {f : ℝ → A}
(hf : interval_integrable f μ a b) (c : A) : interval_integrable (λ x, f x * c) μ a b :=
hf.mul_continuous_on continuous_on_const
@[simp]
lemma div_const {𝕜 : Type*} {f : ℝ → 𝕜} [normed_field 𝕜]
(h : interval_integrable f μ a b) (c : 𝕜) :
interval_integrable (λ x, f x / c) μ a b :=
by simpa only [div_eq_mul_inv] using mul_const h c⁻¹
lemma comp_mul_left (hf : interval_integrable f volume a b) (c : ℝ) :
interval_integrable (λ x, f (c * x)) volume (a / c) (b / c) :=
begin
rcases eq_or_ne c 0 with hc|hc, { rw hc, simp },
rw interval_integrable_iff' at hf ⊢,
have A : measurable_embedding (λ x, x * c⁻¹) :=
(homeomorph.mul_right₀ _ (inv_ne_zero hc)).closed_embedding.measurable_embedding,
rw [←real.smul_map_volume_mul_right (inv_ne_zero hc), integrable_on, measure.restrict_smul,
integrable_smul_measure (by simpa : ennreal.of_real (|c⁻¹|) ≠ 0) ennreal.of_real_ne_top,
←integrable_on, measurable_embedding.integrable_on_map_iff A],
convert hf using 1,
{ ext, simp only [comp_app], congr' 1, field_simp, ring },
{ rw preimage_mul_const_uIcc (inv_ne_zero hc), field_simp [hc] },
end
lemma comp_mul_right (hf : interval_integrable f volume a b) (c : ℝ) :
interval_integrable (λ x, f (x * c)) volume (a / c) (b / c) :=
by simpa only [mul_comm] using comp_mul_left hf c
lemma comp_add_right (hf : interval_integrable f volume a b) (c : ℝ) :
interval_integrable (λ x, f (x + c)) volume (a - c) (b - c) :=
begin
wlog h : a ≤ b,
{ exact interval_integrable.symm (this hf.symm _ (le_of_not_le h)) },
rw interval_integrable_iff' at hf ⊢,
have A : measurable_embedding (λ x, x + c) :=
(homeomorph.add_right c).closed_embedding.measurable_embedding,
have Am : measure.map (λ x, x + c) volume = volume,
{ exact is_add_left_invariant.is_add_right_invariant.map_add_right_eq_self _ },
rw ←Am at hf,
convert (measurable_embedding.integrable_on_map_iff A).mp hf,
rw preimage_add_const_uIcc,
end
lemma comp_add_left (hf : interval_integrable f volume a b) (c : ℝ) :
interval_integrable (λ x, f (c + x)) volume (a - c) (b - c) :=
by simpa only [add_comm] using interval_integrable.comp_add_right hf c
lemma comp_sub_right (hf : interval_integrable f volume a b) (c : ℝ) :
interval_integrable (λ x, f (x - c)) volume (a + c) (b + c) :=
by simpa only [sub_neg_eq_add] using interval_integrable.comp_add_right hf (-c)
lemma iff_comp_neg :
interval_integrable f volume a b ↔ interval_integrable (λ x, f (-x)) volume (-a) (-b) :=
begin
split, all_goals { intro hf, convert comp_mul_left hf (-1), simp, field_simp, field_simp },
end
lemma comp_sub_left (hf : interval_integrable f volume a b) (c : ℝ) :
interval_integrable (λ x, f (c - x)) volume (c - a) (c - b) :=
by simpa only [neg_sub, ←sub_eq_add_neg] using iff_comp_neg.mp (hf.comp_add_left c)
end interval_integrable
section
variables {μ : measure ℝ} [is_locally_finite_measure μ]
lemma continuous_on.interval_integrable {u : ℝ → E} {a b : ℝ}
(hu : continuous_on u (uIcc a b)) : interval_integrable u μ a b :=
(continuous_on.integrable_on_Icc hu).interval_integrable
lemma continuous_on.interval_integrable_of_Icc {u : ℝ → E} {a b : ℝ} (h : a ≤ b)
(hu : continuous_on u (Icc a b)) : interval_integrable u μ a b :=
continuous_on.interval_integrable ((uIcc_of_le h).symm ▸ hu)
/-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure
`ν` on ℝ. -/
lemma continuous.interval_integrable {u : ℝ → E} (hu : continuous u) (a b : ℝ) :
interval_integrable u μ a b :=
hu.continuous_on.interval_integrable
end
section
variables {μ : measure ℝ} [is_locally_finite_measure μ] [conditionally_complete_linear_order E]
[order_topology E] [second_countable_topology E]
lemma monotone_on.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : monotone_on u (uIcc a b)) :
interval_integrable u μ a b :=
begin
rw interval_integrable_iff,
exact (hu.integrable_on_is_compact is_compact_uIcc).mono_set Ioc_subset_Icc_self,
end
lemma antitone_on.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : antitone_on u (uIcc a b)) :
interval_integrable u μ a b :=
hu.dual_right.interval_integrable
lemma monotone.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : monotone u) :
interval_integrable u μ a b :=
(hu.monotone_on _).interval_integrable
lemma antitone.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : antitone u) :
interval_integrable u μ a b :=
(hu.antitone_on _).interval_integrable
end
/-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'`
eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`.
Suppose that `f : ℝ → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on
`u..v` provided that both `u` and `v` tend to `l`.
Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so
`apply tendsto.eventually_interval_integrable_ae` will generate goals `filter ℝ` and
`tendsto_Ixx_class Ioc ?m_1 l'`. -/
lemma filter.tendsto.eventually_interval_integrable_ae {f : ℝ → E} {μ : measure ℝ}
{l l' : filter ℝ} (hfm : strongly_measurable_at_filter f l' μ)
[tendsto_Ixx_class Ioc l l'] [is_measurably_generated l']
(hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c))
{u v : ι → ℝ} {lt : filter ι} (hu : tendsto u lt l) (hv : tendsto v lt l) :
∀ᶠ t in lt, interval_integrable f μ (u t) (v t) :=
have _ := (hf.integrable_at_filter_ae hfm hμ).eventually,
((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this
/-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'`
eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`.
Suppose that `f : ℝ → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v`
provided that both `u` and `v` tend to `l`.
Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so
`apply tendsto.eventually_interval_integrable_ae` will generate goals `filter ℝ` and
`tendsto_Ixx_class Ioc ?m_1 l'`. -/
lemma filter.tendsto.eventually_interval_integrable {f : ℝ → E} {μ : measure ℝ}
{l l' : filter ℝ} (hfm : strongly_measurable_at_filter f l' μ)
[tendsto_Ixx_class Ioc l l'] [is_measurably_generated l']
(hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c))
{u v : ι → ℝ} {lt : filter ι} (hu : tendsto u lt l) (hv : tendsto v lt l) :
∀ᶠ t in lt, interval_integrable f μ (u t) (v t) :=
(hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv
/-!
### Interval integral: definition and basic properties
In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`
and prove some basic properties.
-/
variables [complete_space E] [normed_space ℝ E]
/-- The interval integral `∫ x in a..b, f x ∂μ` is defined
as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals
`∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/
def interval_integral (f : ℝ → E) (a b : ℝ) (μ : measure ℝ) : E :=
∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ
notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ
notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r
namespace interval_integral
section basic
variables {a b : ℝ} {f g : ℝ → E} {μ : measure ℝ}
@[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 :=
by simp [interval_integral]
lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ :=
by simp [interval_integral, h]
@[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 :=
sub_self _
lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ :=
by simp only [interval_integral, neg_sub]
lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ :=
by simp only [integral_symm b, integral_of_le h]
lemma interval_integral_eq_integral_uIoc (f : ℝ → E) (a b : ℝ) (μ : measure ℝ) :
∫ x in a..b, f x ∂μ = (if a ≤ b then 1 else -1 : ℝ) • ∫ x in Ι a b, f x ∂μ :=
begin
split_ifs with h,
{ simp only [integral_of_le h, uIoc_of_le h, one_smul] },
{ simp only [integral_of_ge (not_le.1 h).le, uIoc_of_lt (not_le.1 h), neg_one_smul] }
end
lemma norm_interval_integral_eq (f : ℝ → E) (a b : ℝ) (μ : measure ℝ) :
‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ :=
begin
simp_rw [interval_integral_eq_integral_uIoc, norm_smul],
split_ifs; simp only [norm_neg, norm_one, one_mul],
end
lemma abs_interval_integral_eq (f : ℝ → ℝ) (a b : ℝ) (μ : measure ℝ) :
|∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| :=
norm_interval_integral_eq f a b μ
lemma integral_cases (f : ℝ → E) (a b) :
∫ x in a..b, f x ∂μ ∈ ({∫ x in Ι a b, f x ∂μ, -∫ x in Ι a b, f x ∂μ} : set E) :=
by { rw interval_integral_eq_integral_uIoc, split_ifs; simp }
lemma integral_undef (h : ¬ interval_integrable f μ a b) :
∫ x in a..b, f x ∂μ = 0 :=
by cases le_total a b with hab hab;
simp only [integral_of_le, integral_of_ge, hab, neg_eq_zero];
refine integral_undef (not_imp_not.mpr _ h);
simpa only [hab, Ioc_eq_empty_of_le, integrable_on_empty, not_true, false_or, or_false]
using not_and_distrib.mp h
lemma interval_integrable_of_integral_ne_zero {a b : ℝ}
{f : ℝ → E} {μ : measure ℝ} (h : ∫ x in a..b, f x ∂μ ≠ 0) :
interval_integrable f μ a b :=
by { contrapose! h, exact interval_integral.integral_undef h }
lemma integral_non_ae_strongly_measurable
(hf : ¬ ae_strongly_measurable f (μ.restrict (Ι a b))) :
∫ x in a..b, f x ∂μ = 0 :=
by rw [interval_integral_eq_integral_uIoc, integral_non_ae_strongly_measurable hf, smul_zero]
lemma integral_non_ae_strongly_measurable_of_le (h : a ≤ b)
(hf : ¬ ae_strongly_measurable f (μ.restrict (Ioc a b))) :
∫ x in a..b, f x ∂μ = 0 :=
integral_non_ae_strongly_measurable $ by rwa [uIoc_of_le h]
lemma norm_integral_min_max (f : ℝ → E) :
‖∫ x in min a b..max a b, f x ∂μ‖ = ‖∫ x in a..b, f x ∂μ‖ :=
by cases le_total a b; simp [*, integral_symm a b]
lemma norm_integral_eq_norm_integral_Ioc (f : ℝ → E) :
‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ :=
by rw [← norm_integral_min_max, integral_of_le min_le_max, uIoc]
lemma abs_integral_eq_abs_integral_uIoc (f : ℝ → ℝ) :
|∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| :=
norm_integral_eq_norm_integral_Ioc f
lemma norm_integral_le_integral_norm_Ioc :
‖∫ x in a..b, f x ∂μ‖ ≤ ∫ x in Ι a b, ‖f x‖ ∂μ :=
calc ‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ :
norm_integral_eq_norm_integral_Ioc f
... ≤ ∫ x in Ι a b, ‖f x‖ ∂μ :
norm_integral_le_integral_norm f
lemma norm_integral_le_abs_integral_norm : ‖∫ x in a..b, f x ∂μ‖ ≤ |∫ x in a..b, ‖f x‖ ∂μ| :=
begin
simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc],
exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _)
end
lemma norm_integral_le_integral_norm (h : a ≤ b) :
‖∫ x in a..b, f x ∂μ‖ ≤ ∫ x in a..b, ‖f x‖ ∂μ :=
norm_integral_le_integral_norm_Ioc.trans_eq $ by rw [uIoc_of_le h, integral_of_le h]
lemma norm_integral_le_of_norm_le {g : ℝ → ℝ}
(h : ∀ᵐ t ∂(μ.restrict $ Ι a b), ‖f t‖ ≤ g t)
(hbound : interval_integrable g μ a b) :
‖∫ t in a..b, f t ∂μ‖ ≤ |∫ t in a..b, g t ∂μ| :=
by simp_rw [norm_interval_integral_eq, abs_interval_integral_eq,
abs_eq_self.mpr (integral_nonneg_of_ae $ h.mono $ λ t ht, (norm_nonneg _).trans ht),
norm_integral_le_of_norm_le hbound.def h]
lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E}
(h : ∀ᵐ x, x ∈ Ι a b → ‖f x‖ ≤ C) :
‖∫ x in a..b, f x‖ ≤ C * |b - a| :=
begin
rw [norm_integral_eq_norm_integral_Ioc],
convert norm_set_integral_le_of_norm_le_const_ae'' _ measurable_set_Ioc h,
{ rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] },
{ simp only [real.volume_Ioc, ennreal.of_real_lt_top] },
end
lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E}
(h : ∀ x ∈ Ι a b, ‖f x‖ ≤ C) :
‖∫ x in a..b, f x‖ ≤ C * |b - a| :=
norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h
@[simp] lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) :
∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ :=
by simp only [interval_integral_eq_integral_uIoc, integral_add hf.def hg.def, smul_add]
lemma integral_finset_sum {ι} {s : finset ι} {f : ι → ℝ → E}
(h : ∀ i ∈ s, interval_integrable (f i) μ a b) :
∫ x in a..b, ∑ i in s, f i x ∂μ = ∑ i in s, ∫ x in a..b, f i x ∂μ :=
by simp only [interval_integral_eq_integral_uIoc,
integral_finset_sum s (λ i hi, (h i hi).def), finset.smul_sum]
@[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ :=
by { simp only [interval_integral, integral_neg], abel }
@[simp] lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) :
∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ :=
by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg)
@[simp] lemma integral_smul {𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_space 𝕜 E]
[smul_comm_class ℝ 𝕜 E]
(r : 𝕜) (f : ℝ → E) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ :=
by simp only [interval_integral, integral_smul, smul_sub]
@[simp] lemma integral_smul_const {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] (f : ℝ → 𝕜) (c : E) :
∫ x in a..b, f x • c ∂μ = (∫ x in a..b, f x ∂μ) • c :=
by simp only [interval_integral_eq_integral_uIoc, integral_smul_const, smul_assoc]
@[simp] lemma integral_const_mul {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) :
∫ x in a..b, r * f x ∂μ = r * ∫ x in a..b, f x ∂μ :=
integral_smul r f
@[simp] lemma integral_mul_const {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) :
∫ x in a..b, f x * r ∂μ = ∫ x in a..b, f x ∂μ * r :=
by simpa only [mul_comm r] using integral_const_mul r f
@[simp] lemma integral_div {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) :
∫ x in a..b, f x / r ∂μ = ∫ x in a..b, f x ∂μ / r :=
by simpa only [div_eq_mul_inv] using integral_mul_const r⁻¹ f
lemma integral_const' (c : E) :
∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c :=
by simp only [interval_integral, set_integral_const, sub_smul]
@[simp] lemma integral_const (c : E) : ∫ x in a..b, c = (b - a) • c :=
by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b,
max_zero_sub_eq_self]
lemma integral_smul_measure (c : ℝ≥0∞) :
∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ :=
by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub]
end basic
lemma integral_of_real {a b : ℝ} {μ : measure ℝ} {f : ℝ → ℝ} :
∫ x in a..b, (f x : ℂ) ∂μ = ↑(∫ x in a..b, f x ∂μ) :=
by simp only [interval_integral, integral_of_real, complex.of_real_sub]
section continuous_linear_map
variables {a b : ℝ} {μ : measure ℝ} {f : ℝ → E}
variables [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F]
open continuous_linear_map
lemma _root_.continuous_linear_map.interval_integral_apply {a b : ℝ} {φ : ℝ → F →L[𝕜] E}
(hφ : interval_integrable φ μ a b) (v : F) :
(∫ x in a..b, φ x ∂μ) v = ∫ x in a..b, φ x v ∂μ :=
by simp_rw [interval_integral_eq_integral_uIoc, ← integral_apply hφ.def v, coe_smul',
pi.smul_apply]
variables [normed_space ℝ F] [complete_space F]
lemma _root_.continuous_linear_map.interval_integral_comp_comm
(L : E →L[𝕜] F) (hf : interval_integrable f μ a b) :
∫ x in a..b, L (f x) ∂μ = L (∫ x in a..b, f x ∂μ) :=
by simp_rw [interval_integral, L.integral_comp_comm hf.1, L.integral_comp_comm hf.2, L.map_sub]
end continuous_linear_map
section comp
variables {a b c d : ℝ} (f : ℝ → E)
@[simp] lemma integral_comp_mul_right (hc : c ≠ 0) :
∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x :=
begin
have A : measurable_embedding (λ x, x * c) :=
(homeomorph.mul_right₀ c hc).closed_embedding.measurable_embedding,
conv_rhs { rw [← real.smul_map_volume_mul_right hc] },
simp_rw [integral_smul_measure, interval_integral, A.set_integral_map,
ennreal.to_real_of_real (abs_nonneg c)],
cases hc.lt_or_lt,
{ simp [h, mul_div_cancel, hc, abs_of_neg, measure.restrict_congr_set Ico_ae_eq_Ioc] },
{ simp [h, mul_div_cancel, hc, abs_of_pos] }
end
@[simp] lemma smul_integral_comp_mul_right (c) :
c • ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_mul_left (hc : c ≠ 0) :
∫ x in a..b, f (c * x) = c⁻¹ • ∫ x in c*a..c*b, f x :=
by simpa only [mul_comm c] using integral_comp_mul_right f hc
@[simp] lemma smul_integral_comp_mul_left (c) :
c • ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_div (hc : c ≠ 0) :
∫ x in a..b, f (x / c) = c • ∫ x in a/c..b/c, f x :=
by simpa only [inv_inv] using integral_comp_mul_right f (inv_ne_zero hc)
@[simp] lemma inv_smul_integral_comp_div (c) :
c⁻¹ • ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_add_right (d) :
∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x :=
have A : measurable_embedding (λ x, x + d) :=
(homeomorph.add_right d).closed_embedding.measurable_embedding,
calc ∫ x in a..b, f (x + d)
= ∫ x in a+d..b+d, f x ∂(measure.map (λ x, x + d) volume)
: by simp [interval_integral, A.set_integral_map]
... = ∫ x in a+d..b+d, f x : by rw [map_add_right_eq_self]
@[simp] lemma integral_comp_add_left (d) :
∫ x in a..b, f (d + x) = ∫ x in d+a..d+b, f x :=
by simpa only [add_comm] using integral_comp_add_right f d
@[simp] lemma integral_comp_mul_add (hc : c ≠ 0) (d) :
∫ x in a..b, f (c * x + d) = c⁻¹ • ∫ x in c*a+d..c*b+d, f x :=
by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc]
@[simp] lemma smul_integral_comp_mul_add (c d) :
c • ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_add_mul (hc : c ≠ 0) (d) :
∫ x in a..b, f (d + c * x) = c⁻¹ • ∫ x in d+c*a..d+c*b, f x :=
by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc]
@[simp] lemma smul_integral_comp_add_mul (c d) :
c • ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_div_add (hc : c ≠ 0) (d) :
∫ x in a..b, f (x / c + d) = c • ∫ x in a/c+d..b/c+d, f x :=
by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_mul_add f (inv_ne_zero hc) d
@[simp] lemma inv_smul_integral_comp_div_add (c d) :
c⁻¹ • ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_add_div (hc : c ≠ 0) (d) :
∫ x in a..b, f (d + x / c) = c • ∫ x in d+a/c..d+b/c, f x :=
by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_add_mul f (inv_ne_zero hc) d
@[simp] lemma inv_smul_integral_comp_add_div (c d) :
c⁻¹ • ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_mul_sub (hc : c ≠ 0) (d) :
∫ x in a..b, f (c * x - d) = c⁻¹ • ∫ x in c*a-d..c*b-d, f x :=
by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d)
@[simp] lemma smul_integral_comp_mul_sub (c d) :
c • ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_sub_mul (hc : c ≠ 0) (d) :
∫ x in a..b, f (d - c * x) = c⁻¹ • ∫ x in d-c*b..d-c*a, f x :=
begin
simp only [sub_eq_add_neg, neg_mul_eq_neg_mul],
rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm],
simp only [inv_neg, smul_neg, neg_neg, neg_smul],
end
@[simp] lemma smul_integral_comp_sub_mul (c d) :
c • ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_div_sub (hc : c ≠ 0) (d) :
∫ x in a..b, f (x / c - d) = c • ∫ x in a/c-d..b/c-d, f x :=
by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_mul_sub f (inv_ne_zero hc) d
@[simp] lemma inv_smul_integral_comp_div_sub (c d) :
c⁻¹ • ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_sub_div (hc : c ≠ 0) (d) :
∫ x in a..b, f (d - x / c) = c • ∫ x in d-b/c..d-a/c, f x :=
by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_sub_mul f (inv_ne_zero hc) d
@[simp] lemma inv_smul_integral_comp_sub_div (c d) :
c⁻¹ • ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_sub_right (d) :
∫ x in a..b, f (x - d) = ∫ x in a-d..b-d, f x :=
by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d)
@[simp] lemma integral_comp_sub_left (d) :
∫ x in a..b, f (d - x) = ∫ x in d-b..d-a, f x :=
by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d
@[simp] lemma integral_comp_neg : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x :=
by simpa only [zero_sub] using integral_comp_sub_left f 0
end comp
/-!
### Integral is an additive function of the interval
In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ`
as well as a few other identities trivially equivalent to this one. We also prove that
`∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`.
-/
section order_closed_topology
variables {a b c d : ℝ} {f g : ℝ → E} {μ : measure ℝ}
/-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/
lemma integral_congr {a b : ℝ} (h : eq_on f g [a, b]) :
∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ :=
by cases le_total a b with hab hab; simpa [hab, integral_of_le, integral_of_ge]
using set_integral_congr measurable_set_Ioc (h.mono Ioc_subset_Icc_self)
lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b)
(hbc : interval_integrable f μ b c) :
∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 :=
begin
have hac := hab.trans hbc,
simp only [interval_integral, sub_add_sub_comm, sub_eq_zero],
iterate 4 { rw ← integral_union },
{ suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this,
rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle,
min_left_comm, max_left_comm] },
all_goals { simp [*, measurable_set.union, measurable_set_Ioc, Ioc_disjoint_Ioc_same,
Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] }
end
lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b)
(hbc : interval_integrable f μ b c) :
∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ :=
by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc]
lemma sum_integral_adjacent_intervals_Ico {a : ℕ → ℝ} {m n : ℕ} (hmn : m ≤ n)
(hint : ∀ k ∈ Ico m n, interval_integrable f μ (a k) (a $ k+1)) :
∑ (k : ℕ) in finset.Ico m n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a m)..(a n), f x ∂μ :=
begin
revert hint,
refine nat.le_induction _ _ n hmn,
{ simp },
{ assume p hmp IH h,
rw [finset.sum_Ico_succ_top hmp, IH, integral_add_adjacent_intervals],
{ apply interval_integrable.trans_iterate_Ico hmp (λ k hk, h k _),
exact (Ico_subset_Ico le_rfl (nat.le_succ _)) hk },
{ apply h,
simp [hmp] },
{ assume k hk,
exact h _ (Ico_subset_Ico_right p.le_succ hk) } }
end
lemma sum_integral_adjacent_intervals {a : ℕ → ℝ} {n : ℕ}
(hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) :
∑ (k : ℕ) in finset.range n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ :=
begin
rw ← nat.Ico_zero_eq_range,
exact sum_integral_adjacent_intervals_Ico (zero_le n) (λ k hk, hint k hk.2),
end
lemma integral_interval_sub_left (hab : interval_integrable f μ a b)
(hac : interval_integrable f μ a c) :
∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ :=
sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab)
lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b)
(hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) :
∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ :=
by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm,
integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm]
lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b)
(hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) :
∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ :=
by simp only [sub_eq_add_neg, ← integral_symm,
integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)]
lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b)
(hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) :
∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ :=
by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c,
sub_neg_eq_add, sub_eq_neg_add], }
lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) :
∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ :=
begin
wlog hab : a ≤ b generalizing a b,
{ rw [integral_symm, ← this hb ha (le_of_not_le hab), neg_sub] },
rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc le_rfl),
Iic_union_Ioc_eq_Iic hab],
exacts [measurable_set_Ioc, ha, hb.mono_set (λ _, and.right)]
end
/-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/
lemma integral_const_of_cdf [is_finite_measure μ] (c : E) :
∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c :=
begin
simp only [sub_smul, ← set_integral_const],
refine (integral_Iic_sub_Iic _ _).symm;
simp only [integrable_on_const, measure_lt_top, or_true]
end
lemma integral_eq_integral_of_support_subset {a b} (h : support f ⊆ Ioc a b) :
∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ :=
begin
cases le_total a b with hab hab,
{ rw [integral_of_le hab, ← integral_indicator measurable_set_Ioc, indicator_eq_self.2 h];
apply_instance },
{ rw [Ioc_eq_empty hab.not_lt, subset_empty_iff, support_eq_empty_iff] at h,
simp [h] }
end
lemma integral_congr_ae' (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x)
(h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) :
∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ :=
by simp only [interval_integral, set_integral_congr_ae (measurable_set_Ioc) h,
set_integral_congr_ae (measurable_set_Ioc) h']
lemma integral_congr_ae (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) :
∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ :=
integral_congr_ae' (ae_uIoc_iff.mp h).1 (ae_uIoc_iff.mp h).2
lemma integral_zero_ae (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) :
∫ x in a..b, f x ∂μ = 0 :=
calc ∫ x in a..b, f x ∂μ = ∫ x in a..b, 0 ∂μ : integral_congr_ae h
... = 0 : integral_zero
lemma integral_indicator {a₁ a₂ a₃ : ℝ} (h : a₂ ∈ Icc a₁ a₃) :
∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂ μ = ∫ x in a₁..a₂, f x ∂ μ :=
begin
have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂, from Iic_inter_Ioc_of_le h.2,
rw [integral_of_le h.1, integral_of_le (h.1.trans h.2),
integral_indicator, measure.restrict_restrict, this],
exact measurable_set_Iic,
all_goals { apply measurable_set_Iic },
end
/-- Lebesgue dominated convergence theorem for filters with a countable basis -/
lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι}
[l.is_countably_generated] {F : ι → ℝ → E} (bound : ℝ → ℝ)
(hF_meas : ∀ᶠ n in l, ae_strongly_measurable (F n) (μ.restrict (Ι a b)))
(h_bound : ∀ᶠ n in l, ∀ᵐ x ∂μ, x ∈ Ι a b → ‖F n x‖ ≤ bound x)
(bound_integrable : interval_integrable bound μ a b)
(h_lim : ∀ᵐ x ∂μ, x ∈ Ι a b → tendsto (λ n, F n x) l (𝓝 (f x))) :
tendsto (λn, ∫ x in a..b, F n x ∂μ) l (𝓝 $ ∫ x in a..b, f x ∂μ) :=
begin
simp only [interval_integrable_iff, interval_integral_eq_integral_uIoc,
← ae_restrict_iff' measurable_set_uIoc] at *,
exact tendsto_const_nhds.smul
(tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_lim)
end
/-- Lebesgue dominated convergence theorem for series. -/
lemma has_sum_integral_of_dominated_convergence {ι} [countable ι]
{F : ι → ℝ → E} (bound : ι → ℝ → ℝ)
(hF_meas : ∀ n, ae_strongly_measurable (F n) (μ.restrict (Ι a b)))
(h_bound : ∀ n, ∀ᵐ t ∂μ, t ∈ Ι a b → ‖F n t‖ ≤ bound n t)
(bound_summable : ∀ᵐ t ∂μ, t ∈ Ι a b → summable (λ n, bound n t))
(bound_integrable : interval_integrable (λ t, ∑' n, bound n t) μ a b)
(h_lim : ∀ᵐ t ∂μ, t ∈ Ι a b → has_sum (λ n, F n t) (f t)) :
has_sum (λn, ∫ t in a..b, F n t ∂μ) (∫ t in a..b, f t ∂μ) :=
begin
simp only [interval_integrable_iff, interval_integral_eq_integral_uIoc,
← ae_restrict_iff' measurable_set_uIoc] at *,
exact (has_sum_integral_of_dominated_convergence bound hF_meas h_bound bound_summable
bound_integrable h_lim).const_smul _,
end
open topological_space
/-- Interval integrals commute with countable sums, when the supremum norms are summable (a
special case of the dominated convergence theorem). -/
lemma has_sum_interval_integral_of_summable_norm [countable ι] {f : ι → C(ℝ, E)}
(hf_sum : summable (λ i : ι, ‖(f i).restrict (⟨uIcc a b, is_compact_uIcc⟩ : compacts ℝ)‖)) :
has_sum (λ i : ι, ∫ x in a..b, f i x) (∫ x in a..b, (∑' i : ι, f i x)) :=
begin
refine has_sum_integral_of_dominated_convergence
(λ i (x : ℝ), ‖(f i).restrict ↑(⟨uIcc a b, is_compact_uIcc⟩ : compacts ℝ)‖)
(λ i, (map_continuous $ f i).ae_strongly_measurable)
(λ i, ae_of_all _ (λ x hx, ((f i).restrict ↑(⟨uIcc a b, is_compact_uIcc⟩ :
compacts ℝ)).norm_coe_le_norm ⟨x, ⟨hx.1.le, hx.2⟩⟩))
(ae_of_all _ (λ x hx, hf_sum))
interval_integrable_const
(ae_of_all _ (λ x hx, summable.has_sum _)),
-- next line is slow, & doesn't work with "exact" in place of "apply" -- ?
apply continuous_map.summable_apply (summable_of_summable_norm hf_sum) ⟨x, ⟨hx.1.le, hx.2⟩⟩,
end
lemma tsum_interval_integral_eq_of_summable_norm [countable ι] {f : ι → C(ℝ, E)}
(hf_sum : summable (λ i : ι, ‖(f i).restrict (⟨uIcc a b, is_compact_uIcc⟩ : compacts ℝ)‖)) :
∑' (i : ι), ∫ x in a..b, f i x = ∫ x in a..b, (∑' i : ι, f i x) :=
(has_sum_interval_integral_of_summable_norm hf_sum).tsum_eq
variables {X : Type*} [topological_space X] [first_countable_topology X]
/-- Continuity of interval integral with respect to a parameter, at a point within a set.
Given `F : X → ℝ → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a
neighborhood of `x₀` within `s` and at `x₀`, and assume it is bounded by a function integrable
on `[a, b]` independent of `x` in a neighborhood of `x₀` within `s`. If `(λ x, F x t)`
is continuous at `x₀` within `s` for almost every `t` in `[a, b]`
then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/
lemma continuous_within_at_of_dominated_interval
{F : X → ℝ → E} {x₀ : X} {bound : ℝ → ℝ} {a b : ℝ} {s : set X}
(hF_meas : ∀ᶠ x in 𝓝[s] x₀, ae_strongly_measurable (F x) (μ.restrict $ Ι a b))
(h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ t ∂μ, t ∈ Ι a b → ‖F x t‖ ≤ bound t)
(bound_integrable : interval_integrable bound μ a b)
(h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous_within_at (λ x, F x t) s x₀) :
continuous_within_at (λ x, ∫ t in a..b, F x t ∂μ) s x₀ :=
tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_cont
/-- Continuity of interval integral with respect to a parameter at a point.
Given `F : X → ℝ → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a
neighborhood of `x₀`, and assume it is bounded by a function integrable on
`[a, b]` independent of `x` in a neighborhood of `x₀`. If `(λ x, F x t)`
is continuous at `x₀` for almost every `t` in `[a, b]`
then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/
lemma continuous_at_of_dominated_interval
{F : X → ℝ → E} {x₀ : X} {bound : ℝ → ℝ} {a b : ℝ}
(hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict $ Ι a b))
(h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂μ, t ∈ Ι a b → ‖F x t‖ ≤ bound t)
(bound_integrable : interval_integrable bound μ a b)
(h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous_at (λ x, F x t) x₀) :
continuous_at (λ x, ∫ t in a..b, F x t ∂μ) x₀ :=
tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_cont
/-- Continuity of interval integral with respect to a parameter.
Given `F : X → ℝ → E`, assume each `F x` is ae-measurable on `[a, b]`,
and assume it is bounded by a function integrable on `[a, b]` independent of `x`.
If `(λ x, F x t)` is continuous for almost every `t` in `[a, b]`
then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/
lemma continuous_of_dominated_interval {F : X → ℝ → E} {bound : ℝ → ℝ} {a b : ℝ}
(hF_meas : ∀ x, ae_strongly_measurable (F x) $ μ.restrict $ Ι a b)
(h_bound : ∀ x, ∀ᵐ t ∂μ, t ∈ Ι a b → ‖F x t‖ ≤ bound t)
(bound_integrable : interval_integrable bound μ a b)
(h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous (λ x, F x t)) :
continuous (λ x, ∫ t in a..b, F x t ∂μ) :=
continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated_interval
(eventually_of_forall hF_meas) (eventually_of_forall h_bound) bound_integrable $ h_cont.mono $
λ x himp hx, (himp hx).continuous_at)
end order_closed_topology
section continuous_primitive
open topological_space
variables {a b b₀ b₁ b₂ : ℝ} {μ : measure ℝ} {f g : ℝ → E}
lemma continuous_within_at_primitive (hb₀ : μ {b₀} = 0)
(h_int : interval_integrable f μ (min a b₁) (max a b₂)) :
continuous_within_at (λ b, ∫ x in a .. b, f x ∂ μ) (Icc b₁ b₂) b₀ :=
begin
by_cases h₀ : b₀ ∈ Icc b₁ b₂,
{ have h₁₂ : b₁ ≤ b₂ := h₀.1.trans h₀.2,
have min₁₂ : min b₁ b₂ = b₁ := min_eq_left h₁₂,
have h_int' : ∀ {x}, x ∈ Icc b₁ b₂ → interval_integrable f μ b₁ x,
{ rintros x ⟨h₁, h₂⟩,
apply h_int.mono_set,
apply uIcc_subset_uIcc,
{ exact ⟨min_le_of_left_le (min_le_right a b₁),
h₁.trans (h₂.trans $ le_max_of_le_right $ le_max_right _ _)⟩ },
{ exact ⟨min_le_of_left_le $ (min_le_right _ _).trans h₁,
le_max_of_le_right $ h₂.trans $ le_max_right _ _⟩ } },
have : ∀ b ∈ Icc b₁ b₂, ∫ x in a..b, f x ∂μ = ∫ x in a..b₁, f x ∂μ + ∫ x in b₁..b, f x ∂μ,
{ rintros b ⟨h₁, h₂⟩,
rw ← integral_add_adjacent_intervals _ (h_int' ⟨h₁, h₂⟩),
apply h_int.mono_set,
apply uIcc_subset_uIcc,
{ exact ⟨min_le_of_left_le (min_le_left a b₁), le_max_of_le_right (le_max_left _ _)⟩ },
{ exact ⟨min_le_of_left_le (min_le_right _ _),
le_max_of_le_right (h₁.trans $ h₂.trans (le_max_right a b₂))⟩ } },
apply continuous_within_at.congr _ this (this _ h₀), clear this,
refine continuous_within_at_const.add _,
have : (λ b, ∫ x in b₁..b, f x ∂μ) =ᶠ[𝓝[Icc b₁ b₂] b₀]
λ b, ∫ x in b₁..b₂, indicator {x | x ≤ b} f x ∂ μ,
{ apply eventually_eq_of_mem self_mem_nhds_within,
exact λ b b_in, (integral_indicator b_in).symm },
apply continuous_within_at.congr_of_eventually_eq _ this (integral_indicator h₀).symm,
have : interval_integrable (λ x, ‖f x‖) μ b₁ b₂,
from interval_integrable.norm (h_int' $ right_mem_Icc.mpr h₁₂),
refine continuous_within_at_of_dominated_interval _ _ this _ ; clear this,
{ apply eventually.mono (self_mem_nhds_within),
intros x hx,
erw [ae_strongly_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le],
{ rw min₁₂,
exact (h_int' hx).1.ae_strongly_measurable },
{ exact le_max_of_le_right hx.2 },
exacts [measurable_set_Iic, measurable_set_Iic] },
{ refine eventually_of_forall (λ x, eventually_of_forall (λ t, _)),
dsimp [indicator],
split_ifs ; simp },
{ have : ∀ᵐ t ∂μ, t < b₀ ∨ b₀ < t,
{ apply eventually.mono (compl_mem_ae_iff.mpr hb₀),
intros x hx,
exact ne.lt_or_lt hx },
apply this.mono,
rintros x₀ (hx₀ | hx₀) -,
{ have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : ℝ | t ≤ x}.indicator f x₀ = f x₀,
{ apply mem_nhds_within_of_mem_nhds,
apply eventually.mono (Ioi_mem_nhds hx₀),
intros x hx,
simp [hx.le] },
apply continuous_within_at_const.congr_of_eventually_eq this,
simp [hx₀.le] },
{ have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : ℝ | t ≤ x}.indicator f x₀ = 0,
{ apply mem_nhds_within_of_mem_nhds,
apply eventually.mono (Iio_mem_nhds hx₀),
intros x hx,
simp [hx] },
apply continuous_within_at_const.congr_of_eventually_eq this,
simp [hx₀] } } },
{ apply continuous_within_at_of_not_mem_closure,
rwa [closure_Icc] }
end
lemma continuous_on_primitive [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) :
continuous_on (λ x, ∫ t in Ioc a x, f t ∂ μ) (Icc a b) :=
begin
by_cases h : a ≤ b,
{ have : ∀ x ∈ Icc a b, ∫ t in Ioc a x, f t ∂μ = ∫ t in a..x, f t ∂μ,
{ intros x x_in,
simp_rw [← uIoc_of_le h, integral_of_le x_in.1] },
rw continuous_on_congr this,
intros x₀ hx₀,
refine continuous_within_at_primitive (measure_singleton x₀) _,
simp only [interval_integrable_iff_integrable_Ioc_of_le, min_eq_left, max_eq_right, h],
exact h_int.mono Ioc_subset_Icc_self le_rfl },
{ rw Icc_eq_empty h,
exact continuous_on_empty _ },
end
lemma continuous_on_primitive_Icc [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) :
continuous_on (λ x, ∫ t in Icc a x, f t ∂ μ) (Icc a b) :=
begin
rw show (λ x, ∫ t in Icc a x, f t ∂μ) = λ x, ∫ t in Ioc a x, f t ∂μ,
by { ext x, exact integral_Icc_eq_integral_Ioc },
exact continuous_on_primitive h_int
end
/-- Note: this assumes that `f` is `interval_integrable`, in contrast to some other lemmas here. -/
lemma continuous_on_primitive_interval' [has_no_atoms μ]
(h_int : interval_integrable f μ b₁ b₂) (ha : a ∈ [b₁, b₂]) :
continuous_on (λ b, ∫ x in a..b, f x ∂ μ) [b₁, b₂] :=
begin
intros b₀ hb₀,
refine continuous_within_at_primitive (measure_singleton _) _,
rw [min_eq_right ha.1, max_eq_right ha.2],
simpa [interval_integrable_iff, uIoc] using h_int,
end
lemma continuous_on_primitive_interval [has_no_atoms μ]
(h_int : integrable_on f (uIcc a b) μ) :
continuous_on (λ x, ∫ t in a..x, f t ∂ μ) (uIcc a b) :=
continuous_on_primitive_interval' h_int.interval_integrable left_mem_uIcc
lemma continuous_on_primitive_interval_left [has_no_atoms μ]
(h_int : integrable_on f (uIcc a b) μ) :
continuous_on (λ x, ∫ t in x..b, f t ∂ μ) (uIcc a b) :=
begin
rw uIcc_comm a b at h_int ⊢,
simp only [integral_symm b],
exact (continuous_on_primitive_interval h_int).neg,
end
variables [has_no_atoms μ]
lemma continuous_primitive (h_int : ∀ a b, interval_integrable f μ a b) (a : ℝ) :
continuous (λ b, ∫ x in a..b, f x ∂ μ) :=
begin
rw continuous_iff_continuous_at,
intro b₀,
cases exists_lt b₀ with b₁ hb₁,
cases exists_gt b₀ with b₂ hb₂,
apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₁ hb₂),
exact continuous_within_at_primitive (measure_singleton b₀) (h_int _ _)
end
lemma _root_.measure_theory.integrable.continuous_primitive (h_int : integrable f μ) (a : ℝ) :
continuous (λ b, ∫ x in a..b, f x ∂ μ) :=
continuous_primitive (λ _ _, h_int.interval_integrable) a
end continuous_primitive
section
variables {f g : ℝ → ℝ} {a b : ℝ} {μ : measure ℝ}
lemma integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b)
(hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : interval_integrable f μ a b) :
∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b)] 0 :=
by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1]
lemma integral_eq_zero_iff_of_nonneg_ae
(hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) :
∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 :=
begin
cases le_total a b with hab hab;
simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢,
{ exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi },
{ rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] }
end
/-- If `f` is nonnegative and integrable on the unordered interval `set.uIoc a b`, then its
integral over `a..b` is positive if and only if `a < b` and the measure of
`function.support f ∩ set.Ioc a b` is positive. -/
lemma integral_pos_iff_support_of_nonneg_ae'
(hf : 0 ≤ᵐ[μ.restrict (Ι a b)] f) (hfi : interval_integrable f μ a b) :
0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) :=
begin
cases lt_or_le a b with hab hba,
{ rw uIoc_of_le hab.le at hf,
simp only [hab, true_and, integral_of_le hab.le,
set_integral_pos_iff_support_of_nonneg_ae hf hfi.1] },
{ suffices : ∫ x in a..b, f x ∂μ ≤ 0, by simp only [this.not_lt, hba.not_lt, false_and],
rw [integral_of_ge hba, neg_nonpos],
rw [uIoc_swap, uIoc_of_le hba] at hf,
exact integral_nonneg_of_ae hf }
end
/-- If `f` is nonnegative a.e.-everywhere and it is integrable on the unordered interval
`set.uIoc a b`, then its integral over `a..b` is positive if and only if `a < b` and the
measure of `function.support f ∩ set.Ioc a b` is positive. -/
lemma integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : interval_integrable f μ a b) :
0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) :=
integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi
/-- If `f : ℝ → ℝ` is integrable on `(a, b]` for real numbers `a < b`, and positive on the interior
of the interval, then its integral over `a..b` is strictly positive. -/
lemma interval_integral_pos_of_pos_on {f : ℝ → ℝ} {a b : ℝ}
(hfi : interval_integrable f volume a b) (hpos : ∀ (x : ℝ), x ∈ Ioo a b → 0 < f x) (hab : a < b) :
0 < ∫ (x : ℝ) in a..b, f x :=
begin
have hsupp : Ioo a b ⊆ support f ∩ Ioc a b :=
λ x hx, ⟨mem_support.mpr (hpos x hx).ne', Ioo_subset_Ioc_self hx⟩,
have h₀ : 0 ≤ᵐ[volume.restrict (uIoc a b)] f,
{ rw [eventually_le, uIoc_of_le hab.le],
refine ae_restrict_of_ae_eq_of_ae_restrict Ioo_ae_eq_Ioc _,
exact (ae_restrict_iff' measurable_set_Ioo).mpr (ae_of_all _ (λ x hx, (hpos x hx).le)) },
rw integral_pos_iff_support_of_nonneg_ae' h₀ hfi,
exact ⟨hab, ((measure.measure_Ioo_pos _).mpr hab).trans_le (measure_mono hsupp)⟩,
end
/-- If `f : ℝ → ℝ` is strictly positive everywhere, and integrable on `(a, b]` for real numbers
`a < b`, then its integral over `a..b` is strictly positive. (See `interval_integral_pos_of_pos_on`
for a version only assuming positivity of `f` on `(a, b)` rather than everywhere.) -/
lemma interval_integral_pos_of_pos {f : ℝ → ℝ} {a b : ℝ}
(hfi : interval_integrable f measure_space.volume a b) (hpos : ∀ x, 0 < f x) (hab : a < b) :
0 < ∫ x in a..b, f x :=
interval_integral_pos_of_pos_on hfi (λ x hx, hpos x) hab
/-- If `f` and `g` are two functions that are interval integrable on `a..b`, `a ≤ b`,
`f x ≤ g x` for a.e. `x ∈ set.Ioc a b`, and `f x < g x` on a subset of `set.Ioc a b`
of nonzero measure, then `∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ`. -/
lemma integral_lt_integral_of_ae_le_of_measure_set_of_lt_ne_zero (hab : a ≤ b)
(hfi : interval_integrable f μ a b) (hgi : interval_integrable g μ a b)
(hle : f ≤ᵐ[μ.restrict (Ioc a b)] g) (hlt : μ.restrict (Ioc a b) {x | f x < g x} ≠ 0) :
∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ :=
begin
rw [← sub_pos, ← integral_sub hgi hfi, integral_of_le hab,
measure_theory.integral_pos_iff_support_of_nonneg_ae],
{ refine pos_iff_ne_zero.2 (mt (measure_mono_null _) hlt),
exact λ x hx, (sub_pos.2 hx).ne' },
exacts [hle.mono (λ x, sub_nonneg.2), hgi.1.sub hfi.1]
end
/-- If `f` and `g` are continuous on `[a, b]`, `a < b`, `f x ≤ g x` on this interval, and
`f c < g c` at some point `c ∈ [a, b]`, then `∫ x in a..b, f x < ∫ x in a..b, g x`. -/
lemma integral_lt_integral_of_continuous_on_of_le_of_exists_lt {f g : ℝ → ℝ} {a b : ℝ}
(hab : a < b) (hfc : continuous_on f (Icc a b)) (hgc : continuous_on g (Icc a b))
(hle : ∀ x ∈ Ioc a b, f x ≤ g x) (hlt : ∃ c ∈ Icc a b, f c < g c) :
∫ x in a..b, f x < ∫ x in a..b, g x :=
begin
refine integral_lt_integral_of_ae_le_of_measure_set_of_lt_ne_zero hab.le
(hfc.interval_integrable_of_Icc hab.le) (hgc.interval_integrable_of_Icc hab.le)
((ae_restrict_mem measurable_set_Ioc).mono hle) _,
contrapose! hlt,
have h_eq : f =ᵐ[volume.restrict (Ioc a b)] g,
{ simp only [← not_le, ← ae_iff] at hlt,
exact eventually_le.antisymm ((ae_restrict_iff' measurable_set_Ioc).2 $
eventually_of_forall hle) hlt },
simp only [measure.restrict_congr_set Ioc_ae_eq_Icc] at h_eq,
exact λ c hc, (measure.eq_on_Icc_of_ae_eq volume hab.ne h_eq hfc hgc hc).ge
end
lemma integral_nonneg_of_ae_restrict (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) :
0 ≤ (∫ u in a..b, f u ∂μ) :=
let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf in
by simpa only [integral_of_le hab] using set_integral_nonneg_of_ae_restrict H
lemma integral_nonneg_of_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ] f) :
0 ≤ (∫ u in a..b, f u ∂μ) :=
integral_nonneg_of_ae_restrict hab $ ae_restrict_of_ae hf
lemma integral_nonneg_of_forall (hab : a ≤ b) (hf : ∀ u, 0 ≤ f u) :
0 ≤ (∫ u in a..b, f u ∂μ) :=
integral_nonneg_of_ae hab $ eventually_of_forall hf
lemma integral_nonneg (hab : a ≤ b) (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) :
0 ≤ (∫ u in a..b, f u ∂μ) :=
integral_nonneg_of_ae_restrict hab $ (ae_restrict_iff' measurable_set_Icc).mpr $ ae_of_all μ hf
lemma abs_integral_le_integral_abs (hab : a ≤ b) :
|∫ x in a..b, f x ∂μ| ≤ ∫ x in a..b, |f x| ∂μ :=
by simpa only [← real.norm_eq_abs] using norm_integral_le_integral_norm hab
section mono
variables (hab : a ≤ b) (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b)
include hab hf hg
lemma integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) :
∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ :=
let H := h.filter_mono $ ae_mono $ measure.restrict_mono Ioc_subset_Icc_self $ le_refl μ in
by simpa only [integral_of_le hab] using set_integral_mono_ae_restrict hf.1 hg.1 H
lemma integral_mono_ae (h : f ≤ᵐ[μ] g) :
∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ :=
by simpa only [integral_of_le hab] using set_integral_mono_ae hf.1 hg.1 h
lemma integral_mono_on (h : ∀ x ∈ Icc a b, f x ≤ g x) :
∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ :=
let H := λ x hx, h x $ Ioc_subset_Icc_self hx in
by simpa only [integral_of_le hab] using set_integral_mono_on hf.1 hg.1 measurable_set_Ioc H
lemma integral_mono (h : f ≤ g) :
∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ :=
integral_mono_ae hab hf hg $ ae_of_all _ h
omit hg hab
lemma integral_mono_interval {c d} (hca : c ≤ a) (hab : a ≤ b) (hbd : b ≤ d)
(hf : 0 ≤ᵐ[μ.restrict (Ioc c d)] f) (hfi : interval_integrable f μ c d):
∫ x in a..b, f x ∂μ ≤ ∫ x in c..d, f x ∂μ :=
begin
rw [integral_of_le hab, integral_of_le (hca.trans (hab.trans hbd))],
exact set_integral_mono_set hfi.1 hf (Ioc_subset_Ioc hca hbd).eventually_le
end
lemma abs_integral_mono_interval {c d } (h : Ι a b ⊆ Ι c d)
(hf : 0 ≤ᵐ[μ.restrict (Ι c d)] f) (hfi : interval_integrable f μ c d) :
|∫ x in a..b, f x ∂μ| ≤ |∫ x in c..d, f x ∂μ| :=
have hf' : 0 ≤ᵐ[μ.restrict (Ι a b)] f, from ae_mono (measure.restrict_mono h le_rfl) hf,
calc |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| : abs_integral_eq_abs_integral_uIoc f
... = ∫ x in Ι a b, f x ∂μ : abs_of_nonneg (measure_theory.integral_nonneg_of_ae hf')
... ≤ ∫ x in Ι c d, f x ∂μ : set_integral_mono_set hfi.def hf h.eventually_le
... ≤ |∫ x in Ι c d, f x ∂μ| : le_abs_self _
... = |∫ x in c..d, f x ∂μ| : (abs_integral_eq_abs_integral_uIoc f).symm
end mono
end
section has_sum
variables {μ : measure ℝ} {f : ℝ → E}
lemma _root_.measure_theory.integrable.has_sum_interval_integral (hfi : integrable f μ) (y : ℝ) :
has_sum (λ (n : ℤ), ∫ x in (y + n)..(y + n + 1), f x ∂μ) (∫ x, f x ∂μ) :=
begin
simp_rw integral_of_le (le_add_of_nonneg_right zero_le_one),
rw [←integral_univ, ←Union_Ioc_add_int_cast y],
exact has_sum_integral_Union (λ i, measurable_set_Ioc) (pairwise_disjoint_Ioc_add_int_cast y)
hfi.integrable_on,
end
lemma _root_.measure_theory.integrable.has_sum_interval_integral_comp_add_int
(hfi : integrable f) :
has_sum (λ (n : ℤ), ∫ x in 0..1, f (x + n)) (∫ x, f x) :=
begin
convert hfi.has_sum_interval_integral 0 using 2,
ext1 n,
rw [integral_comp_add_right, zero_add, add_comm],
end
end has_sum
end interval_integral
|
fe8eaf7d3a7376a5c37d5dc36f1b65efefc1f81d | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/control/monad/basic.lean | 06fdadec99435f681517b5f326a685b8b460b3a9 | [
"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 | 2,892 | 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 logic.equiv.defs
import tactic.basic
/-!
# Monad
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/752
> Any changes to this file require a corresponding PR to mathlib4.
## Attributes
* ext
* functor_norm
* monad_norm
## Implementation Details
Set of rewrite rules and automation for monads in general and
`reader_t`, `state_t`, `except_t` and `option_t` in particular.
The rewrite rules for monads are carefully chosen so that `simp with
functor_norm` will not introduce monadic vocabulary in a context where
applicatives would do just fine but will handle monadic notation
already present in an expression.
In a context where monadic reasoning is desired `simp with monad_norm`
will translate functor and applicative notation into monad notation
and use regular `functor_norm` rules as well.
## Tags
functor, applicative, monad, simp
-/
mk_simp_attribute monad_norm none with functor_norm
attribute [ext] reader_t.ext state_t.ext except_t.ext option_t.ext
attribute [functor_norm] bind_assoc pure_bind bind_pure
attribute [monad_norm] seq_eq_bind_map
universes u v
@[monad_norm]
lemma map_eq_bind_pure_comp
(m : Type u → Type v) [monad m] [is_lawful_monad m] {α β : Type u} (f : α → β) (x : m α) :
f <$> x = x >>= pure ∘ f := by rw bind_pure_comp_eq_map
/-- run a `state_t` program and discard the final state -/
def state_t.eval {m : Type u → Type v} [functor m] {σ α} (cmd : state_t σ m α) (s : σ) : m α :=
prod.fst <$> cmd.run s
universes u₀ u₁ v₀ v₁
/-- reduce the equivalence between two state monads to the equivalence between
their respective function spaces -/
def state_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁}
{α₁ σ₁ : Type u₀} {α₂ σ₂ : Type u₁} (F : (σ₁ → m₁ (α₁ × σ₁)) ≃ (σ₂ → m₂ (α₂ × σ₂))) :
state_t σ₁ m₁ α₁ ≃ state_t σ₂ m₂ α₂ :=
{ to_fun := λ ⟨f⟩, ⟨F f⟩,
inv_fun := λ ⟨f⟩, ⟨F.symm f⟩,
left_inv := λ ⟨f⟩, congr_arg state_t.mk $ F.left_inv _,
right_inv := λ ⟨f⟩, congr_arg state_t.mk $ F.right_inv _ }
/-- reduce the equivalence between two reader monads to the equivalence between
their respective function spaces -/
def reader_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁}
{α₁ ρ₁ : Type u₀} {α₂ ρ₂ : Type u₁} (F : (ρ₁ → m₁ α₁) ≃ (ρ₂ → m₂ α₂)) :
reader_t ρ₁ m₁ α₁ ≃ reader_t ρ₂ m₂ α₂ :=
{ to_fun := λ ⟨f⟩, ⟨F f⟩,
inv_fun := λ ⟨f⟩, ⟨F.symm f⟩,
left_inv := λ ⟨f⟩, congr_arg reader_t.mk $ F.left_inv _,
right_inv := λ ⟨f⟩, congr_arg reader_t.mk $ F.right_inv _ }
|
2a41d57bc8b464b2bad68f328a874e9ff0dcc31b | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/combinatorics/colex.lean | 5d9debbe88e0fc85246bb5c0a0b63864475c0686 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 14,994 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Alena Gusakov
-/
import data.fintype.basic
import algebra.geom_sum
/-!
# Colex
We define the colex ordering for finite sets, and give a couple of important
lemmas and properties relating to it.
The colex ordering likes to avoid large values - it can be thought of on
`finset ℕ` as the "binary" ordering. That is, order A based on
`∑_{i ∈ A} 2^i`.
It's defined here in a slightly more general way, requiring only `has_lt α` in
the definition of colex on `finset α`. In the context of the Kruskal-Katona
theorem, we are interested in particular on how colex behaves for sets of a
fixed size. If the size is 3, colex on ℕ starts
123, 124, 134, 234, 125, 135, 235, 145, 245, 345, ...
## Main statements
* `colex.hom_lt_iff`: strictly monotone functions preserve colex
* Colex order properties - linearity, decidability and so on.
* `forall_lt_of_colex_lt_of_forall_lt`: if A < B in colex, and everything
in B is < t, then everything in A is < t. This confirms the idea that
an enumeration under colex will exhaust all sets using elements < t before
allowing t to be included.
* `sum_two_pow_le_iff_lt`: colex for α = ℕ is the same as binary
(this also proves binary expansions are unique)
## See also
Related files are:
* `data.list.lex`: Lexicographic order on lists.
* `data.psigma.order`: Lexicographic order on `Σ' i, α i`.
* `data.sigma.order`: Lexicographic order on `Σ i, α i`.
* `order.lexicographic`: Lexicographic order on `α × β`.
## Tags
colex, colexicographic, binary
## References
* https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf
-/
variable {α : Type*}
open finset
open_locale big_operators
/--
We define this type synonym to refer to the colexicographic ordering on finsets
rather than the natural subset ordering.
-/
@[derive inhabited]
def finset.colex (α) := finset α
/--
A convenience constructor to turn a `finset α` into a `finset.colex α`, useful in order to
use the colex ordering rather than the subset ordering.
-/
def finset.to_colex {α} (s : finset α) : finset.colex α := s
@[simp]
lemma colex.eq_iff (A B : finset α) :
A.to_colex = B.to_colex ↔ A = B := iff.rfl
/--
`A` is less than `B` in the colex ordering if the largest thing that's not in both sets is in B.
In other words, max (A Δ B) ∈ B (if the maximum exists).
-/
instance [has_lt α] : has_lt (finset.colex α) :=
⟨λ (A B : finset α), ∃ (k : α), (∀ {x}, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A ∧ k ∈ B⟩
/-- We can define (≤) in the obvious way. -/
instance [has_lt α] : has_le (finset.colex α) :=
⟨λ A B, A < B ∨ A = B⟩
lemma colex.lt_def [has_lt α] (A B : finset α) :
A.to_colex < B.to_colex ↔ ∃ k, (∀ {x}, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A ∧ k ∈ B :=
iff.rfl
lemma colex.le_def [has_lt α] (A B : finset α) :
A.to_colex ≤ B.to_colex ↔ A.to_colex < B.to_colex ∨ A = B :=
iff.rfl
/-- If everything in `A` is less than `k`, we can bound the sum of powers. -/
lemma nat.sum_two_pow_lt {k : ℕ} {A : finset ℕ} (h₁ : ∀ {x}, x ∈ A → x < k) :
A.sum (pow 2) < 2^k :=
begin
apply lt_of_le_of_lt (sum_le_sum_of_subset (λ t, mem_range.2 ∘ h₁)),
have z := geom_sum_mul_add 1 k,
rw [geom_sum, mul_one, one_add_one_eq_two] at z,
rw ← z,
apply nat.lt_succ_self,
end
namespace colex
/-- Strictly monotone functions preserve the colex ordering. -/
lemma hom_lt_iff {β : Type*} [linear_order α] [decidable_eq β] [preorder β]
{f : α → β} (h₁ : strict_mono f) (A B : finset α) :
(A.image f).to_colex < (B.image f).to_colex ↔ A.to_colex < B.to_colex :=
begin
simp only [colex.lt_def, not_exists, mem_image, exists_prop, not_and],
split,
{ rintro ⟨k, z, q, k', _, rfl⟩,
exact ⟨k', λ x hx, by simpa [h₁.injective.eq_iff] using z (h₁ hx), λ t, q _ t rfl, ‹k' ∈ B›⟩ },
rintro ⟨k, z, ka, _⟩,
refine ⟨f k, λ x hx, _, _, k, ‹k ∈ B›, rfl⟩,
{ split,
any_goals
{ rintro ⟨x', hx', rfl⟩,
refine ⟨x', _, rfl⟩,
rwa ← z _ <|> rwa z _,
rwa strict_mono.lt_iff_lt h₁ at hx } },
{ simp only [h₁.injective, function.injective.eq_iff],
exact λ x hx, ne_of_mem_of_not_mem hx ka }
end
/-- A special case of `colex.hom_lt_iff` which is sometimes useful. -/
@[simp] lemma hom_fin_lt_iff {n : ℕ} (A B : finset (fin n)) :
(A.image (λ i : fin n, (i : ℕ))).to_colex < (B.image (λ i : fin n, (i : ℕ))).to_colex
↔ A.to_colex < B.to_colex :=
colex.hom_lt_iff (λ x y k, k) _ _
instance [has_lt α] : is_irrefl (finset.colex α) (<) :=
⟨λ A h, exists.elim h (λ _ ⟨_,a,b⟩, a b)⟩
@[trans]
lemma lt_trans [linear_order α] {a b c : finset.colex α} :
a < b → b < c → a < c :=
begin
rintros ⟨k₁, k₁z, notinA, inB⟩ ⟨k₂, k₂z, notinB, inC⟩,
cases lt_or_gt_of_ne (ne_of_mem_of_not_mem inB notinB),
{ refine ⟨k₂, _, by rwa k₁z h, inC⟩,
intros x hx,
rw ← k₂z hx,
apply k₁z (trans h hx) },
{ refine ⟨k₁, _, notinA, by rwa ← k₂z h⟩,
intros x hx,
rw k₁z hx,
apply k₂z (trans h hx) }
end
@[trans]
lemma le_trans [linear_order α] (a b c : finset.colex α) :
a ≤ b → b ≤ c → a ≤ c :=
λ AB BC, AB.elim (λ k, BC.elim (λ t, or.inl (lt_trans k t)) (λ t, t ▸ AB)) (λ k, k.symm ▸ BC)
instance [linear_order α] : is_trans (finset.colex α) (<) := ⟨λ _ _ _, colex.lt_trans⟩
lemma lt_trichotomy [linear_order α] (A B : finset.colex α) :
A < B ∨ A = B ∨ B < A :=
begin
by_cases h₁ : (A = B),
{ tauto },
rcases (exists_max_image (A \ B ∪ B \ A) id _) with ⟨k, hk, z⟩,
{ simp only [mem_union, mem_sdiff] at hk,
cases hk,
{ right,
right,
refine ⟨k, λ t th, _, hk.2, hk.1⟩,
specialize z t,
by_contra h₂,
simp only [mem_union, mem_sdiff, id.def] at z,
rw [not_iff, iff_iff_and_or_not_and_not, not_not, and_comm] at h₂,
apply not_le_of_lt th (z h₂) },
{ left,
refine ⟨k, λ t th, _, hk.2, hk.1⟩,
specialize z t,
by_contra h₃,
simp only [mem_union, mem_sdiff, id.def] at z,
rw [not_iff, iff_iff_and_or_not_and_not, not_not, and_comm, or_comm] at h₃,
apply not_le_of_lt th (z h₃) }, },
rw nonempty_iff_ne_empty,
intro a,
simp only [union_eq_empty_iff, sdiff_eq_empty_iff_subset] at a,
apply h₁ (subset.antisymm a.1 a.2)
end
instance [linear_order α] : is_trichotomous (finset.colex α) (<) := ⟨lt_trichotomy⟩
instance decidable_lt [linear_order α] : ∀ {A B : finset.colex α}, decidable (A < B) :=
show ∀ A B : finset α, decidable (A.to_colex < B.to_colex),
from λ A B, decidable_of_iff'
(∃ (k ∈ B), (∀ x ∈ A ∪ B, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A)
begin
rw colex.lt_def,
apply exists_congr,
simp only [mem_union, exists_prop, or_imp_distrib, and_comm (_ ∈ B), and_assoc],
intro k,
refine and_congr_left' (forall_congr _),
tauto,
end
instance [linear_order α] : linear_order (finset.colex α) :=
{ le_refl := λ A, or.inr rfl,
le_trans := le_trans,
le_antisymm := λ A B AB BA, AB.elim (λ k, BA.elim (λ t, (asymm k t).elim) (λ t, t.symm)) id,
le_total := λ A B,
(lt_trichotomy A B).elim3 (or.inl ∘ or.inl) (or.inl ∘ or.inr) (or.inr ∘ or.inl),
decidable_le := λ A B, by apply_instance,
decidable_lt := λ A B, by apply_instance,
decidable_eq := λ A B, by apply_instance,
lt_iff_le_not_le := λ A B,
begin
split,
{ intro t,
refine ⟨or.inl t, _⟩,
rintro (i | rfl),
{ apply asymm_of _ t i },
{ apply irrefl _ t } },
rintro ⟨h₁ | rfl, h₂⟩,
{ apply h₁ },
apply h₂.elim (or.inr rfl),
end,
..finset.colex.has_lt,
..finset.colex.has_le }
/-- The instances set up let us infer that `colex.lt` is a strict total order. -/
example [linear_order α] : is_strict_total_order (finset.colex α) (<) := infer_instance
/-- Strictly monotone functions preserve the colex ordering. -/
lemma hom_le_iff {β : Type*} [linear_order α] [linear_order β]
{f : α → β} (h₁ : strict_mono f) (A B : finset α) :
(A.image f).to_colex ≤ (B.image f).to_colex ↔ A.to_colex ≤ B.to_colex :=
by rw [le_iff_le_iff_lt_iff_lt, hom_lt_iff h₁]
/-- A special case of `colex_hom` which is sometimes useful. -/
@[simp] lemma hom_fin_le_iff {n : ℕ} (A B : finset (fin n)) :
(A.image (λ i : fin n, (i : ℕ))).to_colex ≤ (B.image (λ i : fin n, (i : ℕ))).to_colex
↔ A.to_colex ≤ B.to_colex :=
colex.hom_le_iff (λ x y k, k) _ _
/--
If `A` is before `B` in colex, and everything in `B` is small, then everything in `A` is small.
-/
lemma forall_lt_of_colex_lt_of_forall_lt [linear_order α] {A B : finset α}
(t : α) (h₁ : A.to_colex < B.to_colex) (h₂ : ∀ x ∈ B, x < t) :
∀ x ∈ A, x < t :=
begin
rw colex.lt_def at h₁,
rcases h₁ with ⟨k, z, _, _⟩,
intros x hx,
apply lt_of_not_ge,
intro a,
refine not_lt_of_ge a (h₂ x _),
rwa ← z,
apply lt_of_lt_of_le (h₂ k ‹_›) a,
end
/-- `s.to_colex < {r}.to_colex` iff all elements of `s` are less than `r`. -/
lemma lt_singleton_iff_mem_lt [linear_order α] {r : α} {s : finset α} :
s.to_colex < ({r} : finset α).to_colex ↔ ∀ x ∈ s, x < r :=
begin
simp only [lt_def, mem_singleton, ←and_assoc, exists_eq_right],
split,
{ intros t x hx,
rw ←not_le,
intro h,
rcases lt_or_eq_of_le h with h₁ | rfl,
{ exact ne_of_irrefl h₁ ((t.1 h₁).1 hx).symm },
{ exact t.2 hx } },
{ exact λ h, ⟨λ z hz, ⟨λ i, (asymm hz (h _ i)).elim, λ i, (hz.ne' i).elim⟩, by simpa using h r⟩ }
end
/-- If {r} is less than or equal to s in the colexicographical sense,
then s contains an element greater than or equal to r. -/
lemma mem_le_of_singleton_le [linear_order α] {r : α} {s : finset α}:
({r} : finset α).to_colex ≤ s.to_colex ↔ ∃ x ∈ s, r ≤ x :=
by { rw ←not_lt, simp [lt_singleton_iff_mem_lt] }
/-- Colex is an extension of the base ordering on α. -/
lemma singleton_lt_iff_lt [linear_order α] {r s : α} :
({r} : finset α).to_colex < ({s} : finset α).to_colex ↔ r < s :=
by simp [lt_singleton_iff_mem_lt]
/-- Colex is an extension of the base ordering on α. -/
lemma singleton_le_iff_le [linear_order α] {r s : α} :
({r} : finset α).to_colex ≤ ({s} : finset α).to_colex ↔ r ≤ s :=
by rw [le_iff_le_iff_lt_iff_lt, singleton_lt_iff_lt]
/-- Colex doesn't care if you remove the other set -/
@[simp] lemma sdiff_lt_sdiff_iff_lt [has_lt α] [decidable_eq α] (A B : finset α) :
(A \ B).to_colex < (B \ A).to_colex ↔ A.to_colex < B.to_colex :=
begin
rw [colex.lt_def, colex.lt_def],
apply exists_congr,
intro k,
simp only [mem_sdiff, not_and, not_not],
split,
{ rintro ⟨z, kAB, kB, kA⟩,
refine ⟨_, kA, kB⟩,
{ intros x hx,
specialize z hx,
tauto } },
{ rintro ⟨z, kA, kB⟩,
refine ⟨_, λ _, kB, kB, kA⟩,
intros x hx,
rw z hx },
end
/-- Colex doesn't care if you remove the other set -/
@[simp] lemma sdiff_le_sdiff_iff_le [linear_order α] (A B : finset α) :
(A \ B).to_colex ≤ (B \ A).to_colex ↔ A.to_colex ≤ B.to_colex :=
by rw [le_iff_le_iff_lt_iff_lt, sdiff_lt_sdiff_iff_lt]
lemma empty_to_colex_lt [linear_order α] {A : finset α} (hA : A.nonempty) :
(∅ : finset α).to_colex < A.to_colex :=
begin
rw [colex.lt_def],
refine ⟨max' _ hA, _, by simp, max'_mem _ _⟩,
simp only [false_iff, not_mem_empty],
intros x hx t,
apply not_le_of_lt hx (le_max' _ _ t),
end
/-- If `A ⊂ B`, then `A` is less than `B` in the colex order. Note the converse does not hold, as
`⊆` is not a linear order. -/
lemma colex_lt_of_ssubset [linear_order α] {A B : finset α} (h : A ⊂ B) :
A.to_colex < B.to_colex :=
begin
rw [←sdiff_lt_sdiff_iff_lt, sdiff_eq_empty_iff_subset.2 h.1],
exact empty_to_colex_lt (by simpa [finset.nonempty] using exists_of_ssubset h),
end
@[simp] lemma empty_to_colex_le [linear_order α] {A : finset α} :
(∅ : finset α).to_colex ≤ A.to_colex :=
begin
rcases A.eq_empty_or_nonempty with rfl | hA,
{ simp },
{ apply (empty_to_colex_lt hA).le },
end
/-- If `A ⊆ B`, then `A ≤ B` in the colex order. Note the converse does not hold, as `⊆` is not a
linear order. -/
lemma colex_le_of_subset [linear_order α] {A B : finset α} (h : A ⊆ B) :
A.to_colex ≤ B.to_colex :=
begin
rw [←sdiff_le_sdiff_iff_le, sdiff_eq_empty_iff_subset.2 h],
apply empty_to_colex_le
end
/-- The function from finsets to finsets with the colex order is a relation homomorphism. -/
@[simps]
def to_colex_rel_hom [linear_order α] :
((⊆) : finset α → finset α → Prop) →r ((≤) : finset.colex α → finset.colex α → Prop) :=
{ to_fun := finset.to_colex,
map_rel' := λ A B, colex_le_of_subset }
instance [linear_order α] : order_bot (finset.colex α) :=
{ bot := (∅ : finset α).to_colex,
bot_le := λ x, empty_to_colex_le }
instance [linear_order α] [fintype α] : order_top (finset.colex α) :=
{ top := finset.univ.to_colex,
le_top := λ x, colex_le_of_subset (subset_univ _) }
instance [linear_order α] : lattice (finset.colex α) :=
{ ..(by apply_instance : semilattice_sup (finset.colex α)),
..(by apply_instance : semilattice_inf (finset.colex α)) }
instance [linear_order α] [fintype α] : bounded_order (finset.colex α) :=
{ ..(by apply_instance : order_top (finset.colex α)),
..(by apply_instance : order_bot (finset.colex α)) }
/-- For subsets of ℕ, we can show that colex is equivalent to binary. -/
lemma sum_two_pow_lt_iff_lt (A B : finset ℕ) :
∑ i in A, 2^i < ∑ i in B, 2^i ↔ A.to_colex < B.to_colex :=
begin
have z : ∀ (A B : finset ℕ), A.to_colex < B.to_colex → ∑ i in A, 2^i < ∑ i in B, 2^i,
{ intros A B,
rw [← sdiff_lt_sdiff_iff_lt, colex.lt_def],
rintro ⟨k, z, kA, kB⟩,
rw ← sdiff_union_inter A B,
conv_rhs { rw ← sdiff_union_inter B A },
rw [sum_union (disjoint_sdiff_inter _ _), sum_union (disjoint_sdiff_inter _ _),
inter_comm, add_lt_add_iff_right],
apply lt_of_lt_of_le (@nat.sum_two_pow_lt k (A \ B) _),
{ apply single_le_sum (λ _ _, nat.zero_le _) kB },
intros x hx,
apply lt_of_le_of_ne (le_of_not_lt (λ kx, _)),
{ apply (ne_of_mem_of_not_mem hx kA) },
have := (z kx).1 hx,
rw mem_sdiff at this hx,
exact hx.2 this.1 },
refine ⟨λ h, (lt_trichotomy A B).resolve_right (λ h₁, h₁.elim _ (not_lt_of_gt h ∘ z _ _)), z A B⟩,
rintro rfl,
apply irrefl _ h
end
/-- For subsets of ℕ, we can show that colex is equivalent to binary. -/
lemma sum_two_pow_le_iff_lt (A B : finset ℕ) :
∑ i in A, 2^i ≤ ∑ i in B, 2^i ↔ A.to_colex ≤ B.to_colex :=
by rw [le_iff_le_iff_lt_iff_lt, sum_two_pow_lt_iff_lt]
end colex
|
fe2489b7a0b751e478889326b9eb114df252b73b | ea5678cc400c34ff95b661fa26d15024e27ea8cd | /good_diag_flip.lean | efc50975892e7bd8961aad26f61c2d78603efdaf | [] | no_license | ChrisHughes24/leanstuff | dca0b5349c3ed893e8792ffbd98cbcadaff20411 | 9efa85f72efaccd1d540385952a6acc18fce8687 | refs/heads/master | 1,654,883,241,759 | 1,652,873,885,000 | 1,652,873,885,000 | 134,599,537 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,421 | lean |
import algebra.big_operators
open nat finset
lemma {α : Type*} [add_comm_monoid α] (f : ℕ → ℕ → α) (n : ℕ) :
(range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) =
(range n).sum (λ m, (range (n - m)).sum (f m)) :=
have h₁ : ((range n).sigma (range ∘ succ)).sum
(λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) =
(range n).sum (λ m, (range (m + 1)).sum
(λ k, f k (m - k))) := sum_sigma,
have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) =
(range n).sum (λ m, (range (n - m)).sum (f m)) := sum_sigma,
h₁ ▸ h₂ ▸ sum_bij
(λ a _, ⟨a.2, a.1 - a.2⟩)
(λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1,
have h₂ : a.2 < succ a.1 := mem_range.1 (mem_sigma.1 ha).2,
mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁),
mem_range.2 ((nat.sub_lt_sub_right_iff (le_of_lt_succ h₂)).2 h₁)⟩)
(λ _ _, rfl)
(λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h,
have ha : a₁ < n ∧ a₂ ≤ a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩,
have hb : b₁ < n ∧ b₂ ≤ b₁ :=
⟨mem_range.1 (mem_sigma.1 hb).1, le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩,
have h : a₂ = b₂ ∧ _ := sigma.mk.inj h,
have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2),
sigma.mk.inj_iff.2
⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl,
(heq_of_eq h.1)⟩)
(λ ⟨a₁, a₂⟩ ha,
have ha : a₁ < n ∧ a₂ < n - a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩,
⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (by omega),
mem_range.2 (lt_succ_of_le (le_add_left _ _))⟩,
sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩)
local notation f `∑`: 90 n :90 := (range n).sum f
lemma sum_range_diag_flip (f : ℕ → ℕ → α) :
(λ m, (λ k, f k (m - k)) ∑ (succ m)) ∑ n = (λ m, (λ k, f m k) ∑ (n - m)) ∑ n :=
begin
suffices : ∀ j < n, (λ m, (λ k, f k (m - k)) ∑ succ (min j m)) ∑ n = (λ m, (λ k, f m k) ∑ (n - m)) ∑ succ j,
{ cases n with n,
{ simp },
{ rw ← this n (lt_succ_self _),
apply finset.sum_congr rfl,
assume m hm,
rw finset.mem_range at hm,
rw min_eq_right (le_of_lt_succ hm) } },
assume j hj,
induction j with j hi,
{ clear hj,
induction n; simp * at * },
{ specialize hi (le_of_succ_le hj),
rw [sum_range_succ _ (succ j), ← hi],
clear hi,
induction n with n hi,
{ exact absurd hj dec_trivial },
{ cases lt_or_eq_of_le (le_of_lt_succ hj) with hj' hj',
{ specialize hi hj',
rw [sum_range_succ, sum_range_succ _ n, hi, min_eq_left (le_of_lt hj'), succ_sub (le_of_lt hj'),
min_eq_left (le_of_lt (lt_of_succ_lt_succ hj)), sum_range_succ _ (_ - _), sum_range_succ _ (succ j)],
simp },
{ rw [sum_range_succ, sum_range_succ _ n, ← hj', min_eq_left (le_refl _), min_eq_left (le_succ _), sum_range_succ _ (succ _),
succ_sub (le_refl _), nat.sub_self, sum_range_succ _ 0, finset.range_zero, finset.sum_empty, add_zero, ← add_assoc],
refine congr_arg _ (finset.sum_congr rfl _),
assume m hm,
rw finset.mem_range at hm,
rw [min_eq_right (le_of_lt hm), min_eq_right (le_of_lt_succ hm)] } } }
end
#print sum_range_diag_flip
end sum_range
theorem binomial [comm_semiring α] (x y : α) : ∀ n : ℕ,
(x + y)^n = (λ m, x^m * y^(n - m) * choose n m) ∑ succ n
| 0 := by simp
| (succ n) :=
begin
rw [_root_.pow_succ, binomial, add_mul, finset.mul_sum, finset.mul_sum, sum_range_succ, sum_range_succ',
sum_range_succ, sum_range_succ', add_assoc, ← add_assoc (_ ∑ n), ← finset.sum_add_distrib],
have h₁ : x * (x^n * y^(n - n) * choose n n) = x^succ n * y^(succ n - succ n)
* choose (succ n) (succ n) :=
by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm],
have h₂ : y * (x^0 * y^(n - 0) * choose n 0) = x^0 * y^(succ n - 0) * choose (succ n) 0 :=
by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm],
have h₃ : (λ m, x * (x^m * y^(n - m) * choose n m) + y * (x^succ m * y^(n - succ m)
* choose n (succ m))) ∑ n
= (λ m, x^succ m * y^(succ n - succ m) * ↑(choose (succ n) (succ m))) ∑ n :=
finset.sum_congr rfl
begin
assume m hm,
rw finset.mem_range at hm,
rw [← mul_assoc y, ← mul_assoc y, mul_right_comm y, ← _root_.pow_succ, add_one, ← succ_sub hm],
simp [succ_sub_succ, _root_.pow_succ, choose_succ_succ, mul_add, mul_comm,
mul_assoc, mul_left_comm]
end,
rw [h₁, h₂, h₃]
end
lemma zero_pow [semiring α] {n : ℕ} (hn : 0 < n) : (0 : α)^n = 0 :=
begin
induction n with n hi,
{ exact absurd hn dec_trivial },
{ cases n with n,
{ simp },
{ simp [hi dec_trivial, _root_.pow_succ _ (succ _), zero_mul] } }
end
lemma pow_abv (x : β) {n : ℕ} (hn : 1 ≤ n) (abv: β → α) [is_absolute_value abv] : abv (x^n) = (abv x)^n :=
begin
induction n with n hi,
{ exact absurd hn dec_trivial },
{ cases n with n,
{ simp },
{ simp [hi dec_trivial, _root_.pow_succ _ (succ _), abv_mul abv] } }
end
section geo_series
open cau_seq
variables [discrete_linear_ordered_field α] [ring β] {abv : β → α} [is_absolute_value abv]
private lemma lim_zero_pow_lt_one_aux [archimedean α] {x : β} (hx : abv x < 1) : ∀ ε > 0, ∃ i : ℕ, ∀ j ≥ i, abv (x^j) < ε :=
begin
assume ε ε0,
cases classical.em (x = 0),
{ existsi 1,
assume j hj,
simpa [h, _root_.zero_pow hj, abv_zero abv] },
{ have hx : (abv x)⁻¹ > 1 := one_lt_inv ((abv_pos abv).mpr h) hx,
cases pow_unbounded_of_gt_one ε⁻¹ hx with i hi,
have hax : 0 < abv x := by rwa abv_pos abv,
existsi max i 1,
assume j hj,
rw [pow_abv _ (le_trans (le_max_right _ _) hj), ← inv_lt_inv ε0 (pow_pos hax _),
pow_inv _ _ (ne_of_lt hax).symm],
exact lt_of_lt_of_le hi (pow_le_pow (le_of_lt hx) (le_trans (le_max_left _ _) hj)) }
end
lemma is_cau_pow_lt_one [archimedean α] {x : β} (hx : abv x < 1) : is_cau_seq abv (λ n, x^n) :=
of_near _ (const abv 0) $ by simp only [const_apply, sub_zero]; exact lim_zero_pow_lt_one_aux hx
lemma lim_zero_pow_lt_one [archimedean α] (x : β) (hx : abv x < 1) : lim_zero ⟨λ n, x^n, is_cau_pow_lt_one _ hx⟩ :=
lim_zero_pow_lt_one_aux abv hx
lemma sum_geo {x : β} (hx : x ≠ 1) : ∀ n, (λ m, x^m) ∑ n * (1 - x) = 1 - x^n
| 0 := by simp
| (n + 1) := by rw [sum_range_succ, add_mul, sum_geo]; simp [mul_add, _root_.pow_succ']
lemma is_cau_abv_geo_series [archimedean α] {x : β} (hx : abv x < 1) : is_cau_seq abs (λ n, (λ m, (abv x)^m) ∑ n) :=
begin
have haa : abs (abv x) < 1 := by rwa abs_of_nonneg (abv_nonneg abv _),
have hax1 : ¬ 1 - abv x = 0 := by rw [sub_eq_zero_iff_eq]; exact (ne_of_lt hx).symm,
have hax1' : ¬ abv x = 1 := by rwa [eq_comm, ← sub_eq_zero_iff_eq],
let s : cau_seq α abs := (cau_seq.const abs 1 - ⟨_, is_cau_pow_lt_one abs haa⟩) *
cau_seq.inv (cau_seq.const abs (1 - abv x)) (by rwa const_lim_zero),
refine (cau_seq.of_eq s _ _).2,
assume n,
simp [s],
rw [← div_eq_mul_inv, div_eq_iff_mul_eq],
exact sum_geo hax1' _, assumption,
end
end geo_series
-- -- proof that two different ways of representing a sum across a 2D plane are equal, used
-- -- in proof of exp (x + y) = exp x * exp y
-- lemma series_series_diag_flip [add_comm_monoid α] (f : ℕ → ℕ → α) (n : ℕ) : series (λ i,
-- series (λ k, f k (i - k)) i) n = series (λ i, series (λ k, f i k) (n - i)) n := begin
-- have : ∀ m : ℕ, m ≤ n → series (λ (i : ℕ), series (λ k, f k (i - k)) (min m i)) n =
-- series (λ i, series (λ k, f i k) (n - i)) m := by
-- { assume m mn, induction m with m' hi,
-- simp[series_succ,series_zero,mul_add,max_eq_left (zero_le n)],
-- simp only [series_succ _ m'],rw ←hi (le_of_succ_le mn),clear hi,
-- induction n with n' hi,
-- simp[series_succ],exact absurd mn dec_trivial,cases n' with n₂,
-- simp [series_succ],rw [min_eq_left mn,series_succ,min_eq_left (le_of_succ_le mn)],
-- rw eq_zero_of_le_zero (le_of_succ_le_succ mn),simp,
-- cases lt_or_eq_of_le mn,
-- simp [series_succ _ (succ n₂),min_eq_left mn,hi (le_of_lt_succ h)],rw [←add_assoc,←add_assoc],
-- suffices : series (f (succ m')) (n₂ - m') + series (λ (k : ℕ), f k (succ (succ n₂) - k)) (succ m')
-- = series (f (succ m')) (succ n₂ - m') +
-- series (λ (k : ℕ), f k (succ (succ n₂) - k)) (min m' (succ (succ n₂))),
-- rw this,rw[min_eq_left (le_of_succ_le mn),series_succ,succ_sub_succ,succ_sub (le_of_succ_le_succ (le_of_lt_succ h)),series_succ],
-- rw [add_comm (series (λ (k : ℕ), f k (succ (succ n₂) - k)) m'),add_assoc],
-- rw ←h,simp[nat.sub_self],clear hi mn h,simp[series_succ,nat.sub_self],
-- suffices : series (λ (i : ℕ), series (λ (k : ℕ), f k (i - k)) (min (succ m') i)) m' = series (λ (i : ℕ), series (λ (k : ℕ), f k (i - k)) (min m' i)) m',
-- rw [this,min_eq_left (le_succ _)],clear n₂,
-- have h₁ : ∀ i ≤ m', (λ (i : ℕ), series (λ (k : ℕ), f k (i - k)) (min (succ m') i)) i = (λ (i : ℕ), series (λ (k : ℕ), f k (i - k)) (min m' i)) i,
-- assume i im,simp, rw [min_eq_right im,min_eq_right (le_succ_of_le im)],
-- rw series_congr h₁},
-- specialize this n (le_refl _),
-- rw ←this,refine series_congr _,assume i ni,rw min_eq_right ni,
-- end
-- open monoid
-- theorem series_binomial {α : Type*} [comm_semiring α] (x y : α) (i : ℕ) : pow (x + y) i =
-- series (λ j, choose i j * pow x j * pow y (i - j)) i := begin
-- induction i with i' hi,
-- simp!,unfold monoid.pow,rw hi,
-- rw [←series_mul_left],
-- have : ∀ j : ℕ, j ≤ i' → (λ (i : ℕ), (x + y) * (↑(choose i' i) * pow x i * pow y (i' - i))) j
-- = choose i' j * pow x (succ j) * pow y (i' - j) + choose i' j * pow x j * pow y (succ i' - j) := by
-- { assume j ji,dsimp only,rw add_mul,
-- have : x * (↑(choose i' j) * pow x j * pow y (i' - j)) + y * (↑(choose i' j) * pow x j * pow y (i' - j))
-- = ↑(choose i' j) * (x * pow x j) * pow y (i' - j) + ↑(choose i' j) * pow x j * (y * pow y (i' - j)),
-- simp[mul_comm,_root_.mul_assoc,mul_left_comm],
-- rw [this,←_root_.pow_succ,←_root_.pow_succ,succ_sub ji]},
-- rw [series_congr this],clear this,
-- clear hi,rw series_add,
-- have : series (λ (i : ℕ), ↑(choose i' i) * pow x i * pow y (succ i' - i)) i' =
-- series (λ (i : ℕ), ↑(choose i' i) * pow x i * pow y (succ i' - i)) (succ i') := by
-- { simp[series_succ],},
-- rw [this,series_succ₁,series_succ₁],
-- simp[nat.sub_self],rw ←series_add,
-- refine congr_arg _ (series_congr _),
-- assume j ji,unfold choose,rw [nat.cast_add,add_mul,add_mul],
-- end
-- lemma geo_series_eq {α : Type*} [field α] (x : α) (n : ℕ) : x ≠ 1 → series (pow x) n = (1 - pow x (succ n)) / (1 - x) := begin
-- assume x1,have x1' : 1 + -x ≠ 0,assume h,rw [eq_comm, ←sub_eq_iff_eq_add] at h,simp at h,trivial,
-- induction n with n' hi,
-- {simp![div_self x1']},
-- {rw eq_div_iff_mul_eq,simpa,
-- rw [_root_.series_succ,_root_.pow_succ _ (succ n')],
-- rw hi,simp,rw [add_mul,div_mul_cancel _ x1',mul_add],ring,exact x1'},
-- end
-- lemma is_cau_geo_series {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (x : α) :
-- abs x < 1 → is_cau_seq abs (series (pow x)) := begin
-- assume x1, have : series (pow x) = λ n,(1 - pow x (succ n)) / (1 - x),
-- apply funext,assume n,refine geo_series_eq x n _ ,assume h, rw h at x1,exact absurd x1 (by norm_num),rw this,
-- have absx : 0 < abs (1 - x),refine abs_pos_of_ne_zero _,assume h,rw sub_eq_zero_iff_eq at h,rw ←h at x1,
-- have : ¬abs (1 : α) < 1,norm_num,trivial,simp at absx,
-- cases classical.em (x = 0),rw h,simp[monoid.pow],assume ε ε0,existsi 1,assume j j1,simpa!,
-- have x2: 1 < (abs x)⁻¹,rw lt_inv,simpa,{norm_num},exact abs_pos_of_ne_zero h,
-- have pos_x : 0 < abs x := abs_pos_of_ne_zero h,
-- assume ε ε0,
-- cases pow_unbounded_of_gt_one (2 / (ε * abs (1 - x))) x2 with i hi,
-- have ε2 : 0 < 2 / (ε * abs (1 - x)) := div_pos (by norm_num) (mul_pos ε0 absx),
-- rw [pow_inv,lt_inv ε2 (pow_pos pos_x _)] at hi,
-- existsi i,assume j ji,rw [inv_eq_one_div,div_div_eq_mul_div,_root_.one_mul,lt_div_iff (by norm_num : (0 : α) < 2)] at hi,
-- rw [div_sub_div_same,abs_div,div_lt_iff absx],
-- refine lt_of_le_of_lt _ hi,
-- simp,
-- refine le_trans (abs_add _ _) _,
-- have : pow (abs x) i * 2 = pow (abs x) i + pow (abs x) i,ring,
-- rw this,
-- refine add_le_add _ _,
-- {rw [←_root_.one_mul (pow (abs x) i),pow_abs,_root_.pow_succ,abs_mul],
-- exact mul_le_mul_of_nonneg_right (le_of_lt x1) (abs_nonneg _)},
-- {rw [abs_neg,←pow_abs],
-- rw [←inv_le_inv (pow_pos pos_x _) (pow_pos pos_x _),←pow_inv,←pow_inv],
-- refine pow_le_pow (le_of_lt x2) (le_succ_of_le ji),}
-- end
-- lemma is_cau_geo_series_const {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (a x : α) :
-- abs x < 1 → is_cau_seq abs (series (λ n, a * pow x n)) := begin
-- assume x1 ε ε0,
-- cases classical.em (a = 0),
-- existsi 0,intros,rw [series_mul_left],induction j,simp!,assumption,rw h,simpa!,
-- cases is_cau_geo_series x x1 (ε / abs a) (div_pos ε0 (abs_pos_of_ne_zero h)) with i hi,
-- existsi i,assume j ji,rw [series_mul_left,series_mul_left,←mul_sub,abs_mul,mul_comm,←lt_div_iff],
-- exact hi j ji,exact abs_pos_of_ne_zero h,
-- end
-- lemma is_cau_series_of_abv_le_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] {f : ℕ → β}
-- {g : ℕ → α} {abv : β → α} [is_absolute_value abv] (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) →
-- is_cau_seq abs (series g) → is_cau_seq abv (series f) := begin
-- assume hm hg ε ε0,cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi,
-- existsi max n i,
-- assume j ji,
-- have hi₁ := hi j (le_trans (le_max_right n i) ji),
-- have hi₂ := hi (max n i) (le_max_right n i),
-- have sub_le := abs_sub_le (series g j) (series g i) (series g (max n i)),
-- have := add_lt_add hi₁ hi₂,rw abs_sub (series g (max n i)) at this,
-- have ε2 : ε / 2 + ε / 2 = ε,ring,
-- rw ε2 at this,
-- refine lt_of_le_of_lt _ this,
-- refine le_trans _ sub_le,
-- refine le_trans _ (le_abs_self _),
-- generalize hk : j - max n i = k,clear this ε2 hi₂ hi₁ hi ε0 ε hg sub_le,
-- rw nat.sub_eq_iff_eq_add ji at hk,rw hk, clear hk ji j,
-- induction k with k' hi,simp,rw abv_zero abv,
-- rw succ_add,unfold series,
-- rw [add_comm,add_sub_assoc],
-- refine le_trans (abv_add _ _ _) _,
-- rw [add_comm (series g (k' + max n i)),add_sub_assoc],
-- refine add_le_add _ _,
-- refine hm _ _,rw [←zero_add n,←succ_add],refine add_le_add _ _,exact zero_le _,
-- simp, exact le_max_left _ _,assumption,
-- end
-- -- The form of ratio test with 0 ≤ r < 1, and abv (f (succ m)) ≤ r * abv (f m) handled zero terms of series the best
-- lemma series_ratio_test {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β]
-- [archimedean α] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} (n : ℕ) (r : α) :
-- 0 ≤ r → r < 1 → (∀ m, n ≤ m → abv (f (succ m)) ≤ r * abv (f m)) → is_cau_seq abv (series f)
-- := begin
-- assume r0 r1 h,
-- refine is_cau_series_of_abv_le_cau (succ n) _ (is_cau_geo_series_const (abv (f (succ n)) * pow r⁻¹ (succ n)) r _),
-- assume m mn,
-- generalize hk : m - (succ n) = k,rw nat.sub_eq_iff_eq_add mn at hk,
-- cases classical.em (r = 0) with r_zero r_pos,have m_pos := lt_of_lt_of_le (succ_pos n) mn,
-- have := pred_le_pred mn,simp at this,
-- have := h (pred m) this,simp[r_zero,succ_pred_eq_of_pos m_pos] at this,
-- refine le_trans this _,refine mul_nonneg _ _,refine mul_nonneg (abv_nonneg _ _) (pow_nonneg (inv_nonneg.mpr r0) _),exact pow_nonneg r0 _,
-- replace r_pos : 0 < r,cases lt_or_eq_of_le r0 with h h,exact h,exact absurd h.symm r_pos,
-- revert m n,
-- induction k with k' hi,assume m n h mn hk,
-- rw [hk,zero_add,mul_right_comm,←pow_inv _ _ (ne_of_lt r_pos).symm,←div_eq_mul_inv,mul_div_cancel],
-- exact (ne_of_lt (pow_pos r_pos _)).symm,
-- assume m n h mn hk,rw [hk,succ_add],
-- have kn : k' + (succ n) ≥ (succ n), rw ←zero_add (succ n),refine add_le_add _ _,exact zero_le _,simp,
-- replace hi := hi (k' + (succ n)) n h kn rfl,
-- rw [(by simp!;ring : pow r (succ (k' + succ n)) = pow r (k' + succ n) * r),←_root_.mul_assoc],
-- replace h := h (k' + succ n) (le_of_succ_le kn),rw mul_comm at h,
-- exact le_trans h (mul_le_mul_of_nonneg_right hi r0),
-- rwa abs_of_nonneg r0,
-- end
-- lemma series_cau_of_abv_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] {abv : β → α} {f : ℕ → β}
-- [is_absolute_value abv] : is_cau_seq abs (series (λ n, abv (f n))) → is_cau_seq abv (series f) :=
-- λ h, is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) h
-- -- I did not use the equivalent function on cauchy sequences as I do not have a proof
-- -- series (λ n, series (λ m, a m * b (n - m)) n) j) is a cauchy sequence. Using this lemma
-- -- and of_near, this can be proven to be a cauchy sequence
-- lemma series_cauchy_prod {α β : Type*} [discrete_linear_ordered_field α] [ring β] {a b : ℕ → β}
-- {abv : β → α} [is_absolute_value abv] : is_cau_seq abs (series (λ n, abv (a n))) → is_cau_seq abv (series b) →
-- ∀ ε : α, 0 < ε → ∃ i : ℕ, ∀ j ≥ i, abv (series a j * series b j - series (λ n,
-- series (λ m, a m * b (n - m)) n) j) < ε := begin
-- -- slightly adapted version of theorem 9.4.7 from "The Real Numbers and Real Analysis", Ethan D. Bloch
-- assume ha hb ε ε0,
-- cases cau_seq.bounded ⟨_, hb⟩ with Q hQ,simp at hQ,
-- cases cau_seq.bounded ⟨_, ha⟩ with P hP,simp at hP,
-- have P0 : 0 < P,exact lt_of_le_of_lt (abs_nonneg _) (hP 0),
-- have Pε0 := div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) P0),
-- cases cau_seq.cauchy₂ ⟨_, hb⟩ Pε0 with N hN,simp at hN,
-- have Qε0 := div_pos ε0 (mul_pos (show (4 : α) > 0, from by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))),
-- cases cau_seq.cauchy₂ ⟨_, ha⟩ Qε0 with M hM,simp at hM,
-- existsi 2 * (max N M + 1),
-- assume K hK,have := series_series_diag_flip (λ m n, a m * b n) K,simp at this,rw this,clear this,
-- have : (λ (i : ℕ), series (λ (k : ℕ), a i * b k) (K - i)) = (λ (i : ℕ), a i * series (λ (k : ℕ), b k) (K - i)) := by
-- {apply funext,assume i,rw series_mul_left},
-- rw this,clear this,simp,
-- have : series (λ (i : ℕ), a i * series b (K - i)) K = series (λ (i : ℕ), a i * (series b (K - i) - series b K))
-- K + series (λ i, a i * series b K) K,
-- {rw ←series_add,simp[(mul_add _ _ _).symm]},
-- rw this, clear this,
-- rw series_mul_series,simp,
-- rw abv_neg abv,
-- refine lt_of_le_of_lt (abv_series_le_series_abv _) _,
-- simp [abv_mul abv],
-- suffices : series (λ (i : ℕ), abv (a i) * abv (series b (K - i) + -series b K)) (max N M + 1) +
-- (series (λ (i : ℕ), abv (a i) * abv (series b (K - i) + -series b K)) K -series (λ (i : ℕ),
-- abv (a i) * abv (series b (K - i) + -series b K)) (max N M + 1)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q),
-- { simp [(div_div_eq_div_mul _ _ _).symm] at this,
-- rwa[div_mul_cancel _ (ne_of_lt P0).symm,(by norm_num : (4 : α) = 2 * 2),←div_div_eq_div_mul,mul_comm (2 : α),←_root_.mul_assoc,
-- div_mul_cancel _ (ne_of_lt (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).symm,div_mul_cancel,add_halves] at this,
-- norm_num},
-- refine add_lt_add _ _,
-- {have : series (λ (i : ℕ), abv (a i) * abv (series b (K - i) + -series b K)) (max N M + 1) ≤ series
-- (λ (i : ℕ), abv (a i) * (ε / (2 * P))) (max N M + 1) := by
-- {refine series_le_series _,assume m mJ,refine mul_le_mul_of_nonneg_left _ _,
-- {refine le_of_lt (hN (K - m) K _ _),{
-- refine nat.le_sub_left_of_add_le (le_trans _ hK),
-- rw[succ_mul,_root_.one_mul],
-- exact add_le_add mJ (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))},
-- {refine le_trans _ hK,rw ←_root_.one_mul N,
-- refine mul_le_mul (by norm_num) (by rw _root_.one_mul;exact le_trans (le_max_left _ _)
-- (le_of_lt (lt_add_one _))) (zero_le _) (zero_le _)}},
-- exact abv_nonneg abv _},
-- refine lt_of_le_of_lt this _,
-- rw [series_mul_right,mul_comm],
-- specialize hP (max N M + 1),rwa abs_of_nonneg at hP,
-- exact (mul_lt_mul_left Pε0).mpr hP,
-- exact series_nonneg (λ x h, abv_nonneg abv _)},
-- {have hNMK : max N M + 1 < K := by
-- {refine lt_of_lt_of_le _ hK,
-- rw [succ_mul,_root_.one_mul,←add_zero (max N M + 1)],
-- refine add_lt_add_of_le_of_lt (le_refl _) _,rw add_zero,
-- refine add_pos_of_nonneg_of_pos (zero_le _) (by norm_num)},
-- rw series_sub_series _ hNMK,
-- have : series (λ (k : ℕ), abv (a (k + (max N M + 1 + 1))) * abv
-- (series b (K - (k + (max N M + 1 + 1))) + -series b K)) (K - (max N M + 1 + 1)) ≤
-- series (λ (k : ℕ), abv (a (k + (max N M + 1 + 1))) * (2 * Q)) (K - (max N M + 1 + 1)) := by
-- {refine series_le_series _,
-- assume m hm,
-- refine mul_le_mul_of_nonneg_left _ _,
-- {refine le_trans (abv_add abv _ _) _,
-- rw (by ring : 2 * Q = Q + Q),
-- refine add_le_add (le_of_lt (hQ _)) _,
-- rw abv_neg abv, exact le_of_lt (hQ _)},
-- exact abv_nonneg abv _},
-- refine lt_of_le_of_lt this _,
-- rw [series_mul_right],
-- refine (mul_lt_mul_right (mul_pos (by norm_num) (lt_of_le_of_lt (abv_nonneg abv _) (hQ 0)))).mpr _,
-- refine lt_of_le_of_lt (le_abs_self _) _,
-- rw[←@series_sub_series _ _ (λ k, abv (a k)) (max N M + 1) K hNMK],
-- refine hM _ _ _ (le_trans (le_max_right _ _) (le_of_lt (lt_add_one _))),
-- refine le_trans _ hK,
-- rw [succ_mul,_root_.one_mul,←add_zero M],
-- exact add_le_add (le_trans (le_max_right _ _) (le_of_lt (lt_add_one _))) (zero_le _)},
-- end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.